target: Fix bug with task_sg chained transport_free_dev_tasks release
[linux-flexiantxendom0-natty.git] / drivers / target / target_core_transport.c
1 /*******************************************************************************
2  * Filename:  target_core_transport.c
3  *
4  * This file contains the Generic Target Engine Core.
5  *
6  * Copyright (c) 2002, 2003, 2004, 2005 PyX Technologies, Inc.
7  * Copyright (c) 2005, 2006, 2007 SBE, Inc.
8  * Copyright (c) 2007-2010 Rising Tide Systems
9  * Copyright (c) 2008-2010 Linux-iSCSI.org
10  *
11  * Nicholas A. Bellinger <nab@kernel.org>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26  *
27  ******************************************************************************/
28
29 #include <linux/version.h>
30 #include <linux/net.h>
31 #include <linux/delay.h>
32 #include <linux/string.h>
33 #include <linux/timer.h>
34 #include <linux/slab.h>
35 #include <linux/blkdev.h>
36 #include <linux/spinlock.h>
37 #include <linux/smp_lock.h>
38 #include <linux/kthread.h>
39 #include <linux/in.h>
40 #include <linux/cdrom.h>
41 #include <asm/unaligned.h>
42 #include <net/sock.h>
43 #include <net/tcp.h>
44 #include <scsi/scsi.h>
45 #include <scsi/scsi_cmnd.h>
46 #include <scsi/libsas.h> /* For TASK_ATTR_* */
47
48 #include <target/target_core_base.h>
49 #include <target/target_core_device.h>
50 #include <target/target_core_tmr.h>
51 #include <target/target_core_tpg.h>
52 #include <target/target_core_transport.h>
53 #include <target/target_core_fabric_ops.h>
54 #include <target/target_core_configfs.h>
55
56 #include "target_core_alua.h"
57 #include "target_core_hba.h"
58 #include "target_core_pr.h"
59 #include "target_core_scdb.h"
60 #include "target_core_ua.h"
61
62 /* #define DEBUG_CDB_HANDLER */
63 #ifdef DEBUG_CDB_HANDLER
64 #define DEBUG_CDB_H(x...) printk(KERN_INFO x)
65 #else
66 #define DEBUG_CDB_H(x...)
67 #endif
68
69 /* #define DEBUG_CMD_MAP */
70 #ifdef DEBUG_CMD_MAP
71 #define DEBUG_CMD_M(x...) printk(KERN_INFO x)
72 #else
73 #define DEBUG_CMD_M(x...)
74 #endif
75
76 /* #define DEBUG_MEM_ALLOC */
77 #ifdef DEBUG_MEM_ALLOC
78 #define DEBUG_MEM(x...) printk(KERN_INFO x)
79 #else
80 #define DEBUG_MEM(x...)
81 #endif
82
83 /* #define DEBUG_MEM2_ALLOC */
84 #ifdef DEBUG_MEM2_ALLOC
85 #define DEBUG_MEM2(x...) printk(KERN_INFO x)
86 #else
87 #define DEBUG_MEM2(x...)
88 #endif
89
90 /* #define DEBUG_SG_CALC */
91 #ifdef DEBUG_SG_CALC
92 #define DEBUG_SC(x...) printk(KERN_INFO x)
93 #else
94 #define DEBUG_SC(x...)
95 #endif
96
97 /* #define DEBUG_SE_OBJ */
98 #ifdef DEBUG_SE_OBJ
99 #define DEBUG_SO(x...) printk(KERN_INFO x)
100 #else
101 #define DEBUG_SO(x...)
102 #endif
103
104 /* #define DEBUG_CMD_VOL */
105 #ifdef DEBUG_CMD_VOL
106 #define DEBUG_VOL(x...) printk(KERN_INFO x)
107 #else
108 #define DEBUG_VOL(x...)
109 #endif
110
111 /* #define DEBUG_CMD_STOP */
112 #ifdef DEBUG_CMD_STOP
113 #define DEBUG_CS(x...) printk(KERN_INFO x)
114 #else
115 #define DEBUG_CS(x...)
116 #endif
117
118 /* #define DEBUG_PASSTHROUGH */
119 #ifdef DEBUG_PASSTHROUGH
120 #define DEBUG_PT(x...) printk(KERN_INFO x)
121 #else
122 #define DEBUG_PT(x...)
123 #endif
124
125 /* #define DEBUG_TASK_STOP */
126 #ifdef DEBUG_TASK_STOP
127 #define DEBUG_TS(x...) printk(KERN_INFO x)
128 #else
129 #define DEBUG_TS(x...)
130 #endif
131
132 /* #define DEBUG_TRANSPORT_STOP */
133 #ifdef DEBUG_TRANSPORT_STOP
134 #define DEBUG_TRANSPORT_S(x...) printk(KERN_INFO x)
135 #else
136 #define DEBUG_TRANSPORT_S(x...)
137 #endif
138
139 /* #define DEBUG_TASK_FAILURE */
140 #ifdef DEBUG_TASK_FAILURE
141 #define DEBUG_TF(x...) printk(KERN_INFO x)
142 #else
143 #define DEBUG_TF(x...)
144 #endif
145
146 /* #define DEBUG_DEV_OFFLINE */
147 #ifdef DEBUG_DEV_OFFLINE
148 #define DEBUG_DO(x...) printk(KERN_INFO x)
149 #else
150 #define DEBUG_DO(x...)
151 #endif
152
153 /* #define DEBUG_TASK_STATE */
154 #ifdef DEBUG_TASK_STATE
155 #define DEBUG_TSTATE(x...) printk(KERN_INFO x)
156 #else
157 #define DEBUG_TSTATE(x...)
158 #endif
159
160 /* #define DEBUG_STATUS_THR */
161 #ifdef DEBUG_STATUS_THR
162 #define DEBUG_ST(x...) printk(KERN_INFO x)
163 #else
164 #define DEBUG_ST(x...)
165 #endif
166
167 /* #define DEBUG_TASK_TIMEOUT */
168 #ifdef DEBUG_TASK_TIMEOUT
169 #define DEBUG_TT(x...) printk(KERN_INFO x)
170 #else
171 #define DEBUG_TT(x...)
172 #endif
173
174 /* #define DEBUG_GENERIC_REQUEST_FAILURE */
175 #ifdef DEBUG_GENERIC_REQUEST_FAILURE
176 #define DEBUG_GRF(x...) printk(KERN_INFO x)
177 #else
178 #define DEBUG_GRF(x...)
179 #endif
180
181 /* #define DEBUG_SAM_TASK_ATTRS */
182 #ifdef DEBUG_SAM_TASK_ATTRS
183 #define DEBUG_STA(x...) printk(KERN_INFO x)
184 #else
185 #define DEBUG_STA(x...)
186 #endif
187
188 struct se_global *se_global;
189
190 static struct kmem_cache *se_cmd_cache;
191 static struct kmem_cache *se_sess_cache;
192 struct kmem_cache *se_tmr_req_cache;
193 struct kmem_cache *se_ua_cache;
194 struct kmem_cache *se_mem_cache;
195 struct kmem_cache *t10_pr_reg_cache;
196 struct kmem_cache *t10_alua_lu_gp_cache;
197 struct kmem_cache *t10_alua_lu_gp_mem_cache;
198 struct kmem_cache *t10_alua_tg_pt_gp_cache;
199 struct kmem_cache *t10_alua_tg_pt_gp_mem_cache;
200
201 /* Used for transport_dev_get_map_*() */
202 typedef int (*map_func_t)(struct se_task *, u32);
203
204 static int transport_generic_write_pending(struct se_cmd *);
205 static int transport_processing_thread(void *);
206 static int __transport_execute_tasks(struct se_device *dev);
207 static void transport_complete_task_attr(struct se_cmd *cmd);
208 static void transport_direct_request_timeout(struct se_cmd *cmd);
209 static void transport_free_dev_tasks(struct se_cmd *cmd);
210 static u32 transport_generic_get_cdb_count(struct se_cmd *cmd,
211                 unsigned long long starting_lba, u32 sectors,
212                 enum dma_data_direction data_direction,
213                 struct list_head *mem_list, int set_counts);
214 static int transport_generic_get_mem(struct se_cmd *cmd, u32 length,
215                 u32 dma_size);
216 static int transport_generic_remove(struct se_cmd *cmd,
217                 int release_to_pool, int session_reinstatement);
218 static int transport_get_sectors(struct se_cmd *cmd);
219 static struct list_head *transport_init_se_mem_list(void);
220 static int transport_map_sg_to_mem(struct se_cmd *cmd,
221                 struct list_head *se_mem_list, void *in_mem,
222                 u32 *se_mem_cnt);
223 static void transport_memcpy_se_mem_read_contig(struct se_cmd *cmd,
224                 unsigned char *dst, struct list_head *se_mem_list);
225 static void transport_release_fe_cmd(struct se_cmd *cmd);
226 static void transport_remove_cmd_from_queue(struct se_cmd *cmd,
227                 struct se_queue_obj *qobj);
228 static int transport_set_sense_codes(struct se_cmd *cmd, u8 asc, u8 ascq);
229 static void transport_stop_all_task_timers(struct se_cmd *cmd);
230
231 int transport_emulate_control_cdb(struct se_task *task);
232
233 int init_se_global(void)
234 {
235         struct se_global *global;
236
237         global = kzalloc(sizeof(struct se_global), GFP_KERNEL);
238         if (!(global)) {
239                 printk(KERN_ERR "Unable to allocate memory for struct se_global\n");
240                 return -1;
241         }
242
243         INIT_LIST_HEAD(&global->g_lu_gps_list);
244         INIT_LIST_HEAD(&global->g_se_tpg_list);
245         INIT_LIST_HEAD(&global->g_hba_list);
246         INIT_LIST_HEAD(&global->g_se_dev_list);
247         spin_lock_init(&global->g_device_lock);
248         spin_lock_init(&global->hba_lock);
249         spin_lock_init(&global->se_tpg_lock);
250         spin_lock_init(&global->lu_gps_lock);
251         spin_lock_init(&global->plugin_class_lock);
252
253         se_cmd_cache = kmem_cache_create("se_cmd_cache",
254                         sizeof(struct se_cmd), __alignof__(struct se_cmd), 0, NULL);
255         if (!(se_cmd_cache)) {
256                 printk(KERN_ERR "kmem_cache_create for struct se_cmd failed\n");
257                 goto out;
258         }
259         se_tmr_req_cache = kmem_cache_create("se_tmr_cache",
260                         sizeof(struct se_tmr_req), __alignof__(struct se_tmr_req),
261                         0, NULL);
262         if (!(se_tmr_req_cache)) {
263                 printk(KERN_ERR "kmem_cache_create() for struct se_tmr_req"
264                                 " failed\n");
265                 goto out;
266         }
267         se_sess_cache = kmem_cache_create("se_sess_cache",
268                         sizeof(struct se_session), __alignof__(struct se_session),
269                         0, NULL);
270         if (!(se_sess_cache)) {
271                 printk(KERN_ERR "kmem_cache_create() for struct se_session"
272                                 " failed\n");
273                 goto out;
274         }
275         se_ua_cache = kmem_cache_create("se_ua_cache",
276                         sizeof(struct se_ua), __alignof__(struct se_ua),
277                         0, NULL);
278         if (!(se_ua_cache)) {
279                 printk(KERN_ERR "kmem_cache_create() for struct se_ua failed\n");
280                 goto out;
281         }
282         se_mem_cache = kmem_cache_create("se_mem_cache",
283                         sizeof(struct se_mem), __alignof__(struct se_mem), 0, NULL);
284         if (!(se_mem_cache)) {
285                 printk(KERN_ERR "kmem_cache_create() for struct se_mem failed\n");
286                 goto out;
287         }
288         t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
289                         sizeof(struct t10_pr_registration),
290                         __alignof__(struct t10_pr_registration), 0, NULL);
291         if (!(t10_pr_reg_cache)) {
292                 printk(KERN_ERR "kmem_cache_create() for struct t10_pr_registration"
293                                 " failed\n");
294                 goto out;
295         }
296         t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
297                         sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
298                         0, NULL);
299         if (!(t10_alua_lu_gp_cache)) {
300                 printk(KERN_ERR "kmem_cache_create() for t10_alua_lu_gp_cache"
301                                 " failed\n");
302                 goto out;
303         }
304         t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
305                         sizeof(struct t10_alua_lu_gp_member),
306                         __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
307         if (!(t10_alua_lu_gp_mem_cache)) {
308                 printk(KERN_ERR "kmem_cache_create() for t10_alua_lu_gp_mem_"
309                                 "cache failed\n");
310                 goto out;
311         }
312         t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
313                         sizeof(struct t10_alua_tg_pt_gp),
314                         __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
315         if (!(t10_alua_tg_pt_gp_cache)) {
316                 printk(KERN_ERR "kmem_cache_create() for t10_alua_tg_pt_gp_"
317                                 "cache failed\n");
318                 goto out;
319         }
320         t10_alua_tg_pt_gp_mem_cache = kmem_cache_create(
321                         "t10_alua_tg_pt_gp_mem_cache",
322                         sizeof(struct t10_alua_tg_pt_gp_member),
323                         __alignof__(struct t10_alua_tg_pt_gp_member),
324                         0, NULL);
325         if (!(t10_alua_tg_pt_gp_mem_cache)) {
326                 printk(KERN_ERR "kmem_cache_create() for t10_alua_tg_pt_gp_"
327                                 "mem_t failed\n");
328                 goto out;
329         }
330
331         se_global = global;
332
333         return 0;
334 out:
335         if (se_cmd_cache)
336                 kmem_cache_destroy(se_cmd_cache);
337         if (se_tmr_req_cache)
338                 kmem_cache_destroy(se_tmr_req_cache);
339         if (se_sess_cache)
340                 kmem_cache_destroy(se_sess_cache);
341         if (se_ua_cache)
342                 kmem_cache_destroy(se_ua_cache);
343         if (se_mem_cache)
344                 kmem_cache_destroy(se_mem_cache);
345         if (t10_pr_reg_cache)
346                 kmem_cache_destroy(t10_pr_reg_cache);
347         if (t10_alua_lu_gp_cache)
348                 kmem_cache_destroy(t10_alua_lu_gp_cache);
349         if (t10_alua_lu_gp_mem_cache)
350                 kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
351         if (t10_alua_tg_pt_gp_cache)
352                 kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
353         if (t10_alua_tg_pt_gp_mem_cache)
354                 kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
355         kfree(global);
356         return -1;
357 }
358
359 void release_se_global(void)
360 {
361         struct se_global *global;
362
363         global = se_global;
364         if (!(global))
365                 return;
366
367         kmem_cache_destroy(se_cmd_cache);
368         kmem_cache_destroy(se_tmr_req_cache);
369         kmem_cache_destroy(se_sess_cache);
370         kmem_cache_destroy(se_ua_cache);
371         kmem_cache_destroy(se_mem_cache);
372         kmem_cache_destroy(t10_pr_reg_cache);
373         kmem_cache_destroy(t10_alua_lu_gp_cache);
374         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
375         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
376         kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
377         kfree(global);
378
379         se_global = NULL;
380 }
381
382 /* SCSI statistics table index */
383 static struct scsi_index_table scsi_index_table;
384
385 /*
386  * Initialize the index table for allocating unique row indexes to various mib
387  * tables.
388  */
389 void init_scsi_index_table(void)
390 {
391         memset(&scsi_index_table, 0, sizeof(struct scsi_index_table));
392         spin_lock_init(&scsi_index_table.lock);
393 }
394
395 /*
396  * Allocate a new row index for the entry type specified
397  */
398 u32 scsi_get_new_index(scsi_index_t type)
399 {
400         u32 new_index;
401
402         if ((type < 0) || (type >= SCSI_INDEX_TYPE_MAX)) {
403                 printk(KERN_ERR "Invalid index type %d\n", type);
404                 return -EINVAL;
405         }
406
407         spin_lock(&scsi_index_table.lock);
408         new_index = ++scsi_index_table.scsi_mib_index[type];
409         if (new_index == 0)
410                 new_index = ++scsi_index_table.scsi_mib_index[type];
411         spin_unlock(&scsi_index_table.lock);
412
413         return new_index;
414 }
415
416 void transport_init_queue_obj(struct se_queue_obj *qobj)
417 {
418         atomic_set(&qobj->queue_cnt, 0);
419         INIT_LIST_HEAD(&qobj->qobj_list);
420         init_waitqueue_head(&qobj->thread_wq);
421         spin_lock_init(&qobj->cmd_queue_lock);
422 }
423 EXPORT_SYMBOL(transport_init_queue_obj);
424
425 static int transport_subsystem_reqmods(void)
426 {
427         int ret;
428
429         ret = request_module("target_core_iblock");
430         if (ret != 0)
431                 printk(KERN_ERR "Unable to load target_core_iblock\n");
432
433         ret = request_module("target_core_file");
434         if (ret != 0)
435                 printk(KERN_ERR "Unable to load target_core_file\n");
436
437         ret = request_module("target_core_pscsi");
438         if (ret != 0)
439                 printk(KERN_ERR "Unable to load target_core_pscsi\n");
440
441         ret = request_module("target_core_stgt");
442         if (ret != 0)
443                 printk(KERN_ERR "Unable to load target_core_stgt\n");
444
445         return 0;
446 }
447
448 int transport_subsystem_check_init(void)
449 {
450         if (se_global->g_sub_api_initialized)
451                 return 0;
452         /*
453          * Request the loading of known TCM subsystem plugins..
454          */
455         if (transport_subsystem_reqmods() < 0)
456                 return -1;
457
458         se_global->g_sub_api_initialized = 1;
459         return 0;
460 }
461
462 struct se_session *transport_init_session(void)
463 {
464         struct se_session *se_sess;
465
466         se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
467         if (!(se_sess)) {
468                 printk(KERN_ERR "Unable to allocate struct se_session from"
469                                 " se_sess_cache\n");
470                 return ERR_PTR(-ENOMEM);
471         }
472         INIT_LIST_HEAD(&se_sess->sess_list);
473         INIT_LIST_HEAD(&se_sess->sess_acl_list);
474
475         return se_sess;
476 }
477 EXPORT_SYMBOL(transport_init_session);
478
479 /*
480  * Called with spin_lock_bh(&struct se_portal_group->session_lock called.
481  */
482 void __transport_register_session(
483         struct se_portal_group *se_tpg,
484         struct se_node_acl *se_nacl,
485         struct se_session *se_sess,
486         void *fabric_sess_ptr)
487 {
488         unsigned char buf[PR_REG_ISID_LEN];
489
490         se_sess->se_tpg = se_tpg;
491         se_sess->fabric_sess_ptr = fabric_sess_ptr;
492         /*
493          * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
494          *
495          * Only set for struct se_session's that will actually be moving I/O.
496          * eg: *NOT* discovery sessions.
497          */
498         if (se_nacl) {
499                 /*
500                  * If the fabric module supports an ISID based TransportID,
501                  * save this value in binary from the fabric I_T Nexus now.
502                  */
503                 if (TPG_TFO(se_tpg)->sess_get_initiator_sid != NULL) {
504                         memset(&buf[0], 0, PR_REG_ISID_LEN);
505                         TPG_TFO(se_tpg)->sess_get_initiator_sid(se_sess,
506                                         &buf[0], PR_REG_ISID_LEN);
507                         se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
508                 }
509                 spin_lock_irq(&se_nacl->nacl_sess_lock);
510                 /*
511                  * The se_nacl->nacl_sess pointer will be set to the
512                  * last active I_T Nexus for each struct se_node_acl.
513                  */
514                 se_nacl->nacl_sess = se_sess;
515
516                 list_add_tail(&se_sess->sess_acl_list,
517                               &se_nacl->acl_sess_list);
518                 spin_unlock_irq(&se_nacl->nacl_sess_lock);
519         }
520         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
521
522         printk(KERN_INFO "TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
523                 TPG_TFO(se_tpg)->get_fabric_name(), se_sess->fabric_sess_ptr);
524 }
525 EXPORT_SYMBOL(__transport_register_session);
526
527 void transport_register_session(
528         struct se_portal_group *se_tpg,
529         struct se_node_acl *se_nacl,
530         struct se_session *se_sess,
531         void *fabric_sess_ptr)
532 {
533         spin_lock_bh(&se_tpg->session_lock);
534         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
535         spin_unlock_bh(&se_tpg->session_lock);
536 }
537 EXPORT_SYMBOL(transport_register_session);
538
539 void transport_deregister_session_configfs(struct se_session *se_sess)
540 {
541         struct se_node_acl *se_nacl;
542
543         /*
544          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
545          */
546         se_nacl = se_sess->se_node_acl;
547         if ((se_nacl)) {
548                 spin_lock_irq(&se_nacl->nacl_sess_lock);
549                 list_del(&se_sess->sess_acl_list);
550                 /*
551                  * If the session list is empty, then clear the pointer.
552                  * Otherwise, set the struct se_session pointer from the tail
553                  * element of the per struct se_node_acl active session list.
554                  */
555                 if (list_empty(&se_nacl->acl_sess_list))
556                         se_nacl->nacl_sess = NULL;
557                 else {
558                         se_nacl->nacl_sess = container_of(
559                                         se_nacl->acl_sess_list.prev,
560                                         struct se_session, sess_acl_list);
561                 }
562                 spin_unlock_irq(&se_nacl->nacl_sess_lock);
563         }
564 }
565 EXPORT_SYMBOL(transport_deregister_session_configfs);
566
567 void transport_free_session(struct se_session *se_sess)
568 {
569         kmem_cache_free(se_sess_cache, se_sess);
570 }
571 EXPORT_SYMBOL(transport_free_session);
572
573 void transport_deregister_session(struct se_session *se_sess)
574 {
575         struct se_portal_group *se_tpg = se_sess->se_tpg;
576         struct se_node_acl *se_nacl;
577
578         if (!(se_tpg)) {
579                 transport_free_session(se_sess);
580                 return;
581         }
582
583         spin_lock_bh(&se_tpg->session_lock);
584         list_del(&se_sess->sess_list);
585         se_sess->se_tpg = NULL;
586         se_sess->fabric_sess_ptr = NULL;
587         spin_unlock_bh(&se_tpg->session_lock);
588
589         /*
590          * Determine if we need to do extra work for this initiator node's
591          * struct se_node_acl if it had been previously dynamically generated.
592          */
593         se_nacl = se_sess->se_node_acl;
594         if ((se_nacl)) {
595                 spin_lock_bh(&se_tpg->acl_node_lock);
596                 if (se_nacl->dynamic_node_acl) {
597                         if (!(TPG_TFO(se_tpg)->tpg_check_demo_mode_cache(
598                                         se_tpg))) {
599                                 list_del(&se_nacl->acl_list);
600                                 se_tpg->num_node_acls--;
601                                 spin_unlock_bh(&se_tpg->acl_node_lock);
602
603                                 core_tpg_wait_for_nacl_pr_ref(se_nacl);
604                                 core_free_device_list_for_node(se_nacl, se_tpg);
605                                 TPG_TFO(se_tpg)->tpg_release_fabric_acl(se_tpg,
606                                                 se_nacl);
607                                 spin_lock_bh(&se_tpg->acl_node_lock);
608                         }
609                 }
610                 spin_unlock_bh(&se_tpg->acl_node_lock);
611         }
612
613         transport_free_session(se_sess);
614
615         printk(KERN_INFO "TARGET_CORE[%s]: Deregistered fabric_sess\n",
616                 TPG_TFO(se_tpg)->get_fabric_name());
617 }
618 EXPORT_SYMBOL(transport_deregister_session);
619
620 /*
621  * Called with T_TASK(cmd)->t_state_lock held.
622  */
623 static void transport_all_task_dev_remove_state(struct se_cmd *cmd)
624 {
625         struct se_device *dev;
626         struct se_task *task;
627         unsigned long flags;
628
629         if (!T_TASK(cmd))
630                 return;
631
632         list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
633                 dev = task->se_dev;
634                 if (!(dev))
635                         continue;
636
637                 if (atomic_read(&task->task_active))
638                         continue;
639
640                 if (!(atomic_read(&task->task_state_active)))
641                         continue;
642
643                 spin_lock_irqsave(&dev->execute_task_lock, flags);
644                 list_del(&task->t_state_list);
645                 DEBUG_TSTATE("Removed ITT: 0x%08x dev: %p task[%p]\n",
646                         CMD_TFO(cmd)->tfo_get_task_tag(cmd), dev, task);
647                 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
648
649                 atomic_set(&task->task_state_active, 0);
650                 atomic_dec(&T_TASK(cmd)->t_task_cdbs_ex_left);
651         }
652 }
653
654 /*      transport_cmd_check_stop():
655  *
656  *      'transport_off = 1' determines if t_transport_active should be cleared.
657  *      'transport_off = 2' determines if task_dev_state should be removed.
658  *
659  *      A non-zero u8 t_state sets cmd->t_state.
660  *      Returns 1 when command is stopped, else 0.
661  */
662 static int transport_cmd_check_stop(
663         struct se_cmd *cmd,
664         int transport_off,
665         u8 t_state)
666 {
667         unsigned long flags;
668
669         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
670         /*
671          * Determine if IOCTL context caller in requesting the stopping of this
672          * command for LUN shutdown purposes.
673          */
674         if (atomic_read(&T_TASK(cmd)->transport_lun_stop)) {
675                 DEBUG_CS("%s:%d atomic_read(&T_TASK(cmd)->transport_lun_stop)"
676                         " == TRUE for ITT: 0x%08x\n", __func__, __LINE__,
677                         CMD_TFO(cmd)->get_task_tag(cmd));
678
679                 cmd->deferred_t_state = cmd->t_state;
680                 cmd->t_state = TRANSPORT_DEFERRED_CMD;
681                 atomic_set(&T_TASK(cmd)->t_transport_active, 0);
682                 if (transport_off == 2)
683                         transport_all_task_dev_remove_state(cmd);
684                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
685
686                 complete(&T_TASK(cmd)->transport_lun_stop_comp);
687                 return 1;
688         }
689         /*
690          * Determine if frontend context caller is requesting the stopping of
691          * this command for frontend excpections.
692          */
693         if (atomic_read(&T_TASK(cmd)->t_transport_stop)) {
694                 DEBUG_CS("%s:%d atomic_read(&T_TASK(cmd)->t_transport_stop) =="
695                         " TRUE for ITT: 0x%08x\n", __func__, __LINE__,
696                         CMD_TFO(cmd)->get_task_tag(cmd));
697
698                 cmd->deferred_t_state = cmd->t_state;
699                 cmd->t_state = TRANSPORT_DEFERRED_CMD;
700                 if (transport_off == 2)
701                         transport_all_task_dev_remove_state(cmd);
702
703                 /*
704                  * Clear struct se_cmd->se_lun before the transport_off == 2 handoff
705                  * to FE.
706                  */
707                 if (transport_off == 2)
708                         cmd->se_lun = NULL;
709                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
710
711                 complete(&T_TASK(cmd)->t_transport_stop_comp);
712                 return 1;
713         }
714         if (transport_off) {
715                 atomic_set(&T_TASK(cmd)->t_transport_active, 0);
716                 if (transport_off == 2) {
717                         transport_all_task_dev_remove_state(cmd);
718                         /*
719                          * Clear struct se_cmd->se_lun before the transport_off == 2
720                          * handoff to fabric module.
721                          */
722                         cmd->se_lun = NULL;
723                         /*
724                          * Some fabric modules like tcm_loop can release
725                          * their internally allocated I/O refrence now and
726                          * struct se_cmd now.
727                          */
728                         if (CMD_TFO(cmd)->check_stop_free != NULL) {
729                                 spin_unlock_irqrestore(
730                                         &T_TASK(cmd)->t_state_lock, flags);
731
732                                 CMD_TFO(cmd)->check_stop_free(cmd);
733                                 return 1;
734                         }
735                 }
736                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
737
738                 return 0;
739         } else if (t_state)
740                 cmd->t_state = t_state;
741         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
742
743         return 0;
744 }
745
746 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
747 {
748         return transport_cmd_check_stop(cmd, 2, 0);
749 }
750
751 static void transport_lun_remove_cmd(struct se_cmd *cmd)
752 {
753         struct se_lun *lun = SE_LUN(cmd);
754         unsigned long flags;
755
756         if (!lun)
757                 return;
758
759         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
760         if (!(atomic_read(&T_TASK(cmd)->transport_dev_active))) {
761                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
762                 goto check_lun;
763         }
764         atomic_set(&T_TASK(cmd)->transport_dev_active, 0);
765         transport_all_task_dev_remove_state(cmd);
766         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
767
768
769 check_lun:
770         spin_lock_irqsave(&lun->lun_cmd_lock, flags);
771         if (atomic_read(&T_TASK(cmd)->transport_lun_active)) {
772                 list_del(&cmd->se_lun_list);
773                 atomic_set(&T_TASK(cmd)->transport_lun_active, 0);
774 #if 0
775                 printk(KERN_INFO "Removed ITT: 0x%08x from LUN LIST[%d]\n"
776                         CMD_TFO(cmd)->get_task_tag(cmd), lun->unpacked_lun);
777 #endif
778         }
779         spin_unlock_irqrestore(&lun->lun_cmd_lock, flags);
780 }
781
782 void transport_cmd_finish_abort(struct se_cmd *cmd, int remove)
783 {
784         transport_remove_cmd_from_queue(cmd, SE_DEV(cmd)->dev_queue_obj);
785         transport_lun_remove_cmd(cmd);
786
787         if (transport_cmd_check_stop_to_fabric(cmd))
788                 return;
789         if (remove)
790                 transport_generic_remove(cmd, 0, 0);
791 }
792
793 void transport_cmd_finish_abort_tmr(struct se_cmd *cmd)
794 {
795         transport_remove_cmd_from_queue(cmd, SE_DEV(cmd)->dev_queue_obj);
796
797         if (transport_cmd_check_stop_to_fabric(cmd))
798                 return;
799
800         transport_generic_remove(cmd, 0, 0);
801 }
802
803 static int transport_add_cmd_to_queue(
804         struct se_cmd *cmd,
805         int t_state)
806 {
807         struct se_device *dev = cmd->se_dev;
808         struct se_queue_obj *qobj = dev->dev_queue_obj;
809         struct se_queue_req *qr;
810         unsigned long flags;
811
812         qr = kzalloc(sizeof(struct se_queue_req), GFP_ATOMIC);
813         if (!(qr)) {
814                 printk(KERN_ERR "Unable to allocate memory for"
815                                 " struct se_queue_req\n");
816                 return -1;
817         }
818         INIT_LIST_HEAD(&qr->qr_list);
819
820         qr->cmd = (void *)cmd;
821         qr->state = t_state;
822
823         if (t_state) {
824                 spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
825                 cmd->t_state = t_state;
826                 atomic_set(&T_TASK(cmd)->t_transport_active, 1);
827                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
828         }
829
830         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
831         list_add_tail(&qr->qr_list, &qobj->qobj_list);
832         atomic_inc(&T_TASK(cmd)->t_transport_queue_active);
833         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
834
835         atomic_inc(&qobj->queue_cnt);
836         wake_up_interruptible(&qobj->thread_wq);
837         return 0;
838 }
839
840 /*
841  * Called with struct se_queue_obj->cmd_queue_lock held.
842  */
843 static struct se_queue_req *
844 __transport_get_qr_from_queue(struct se_queue_obj *qobj)
845 {
846         struct se_cmd *cmd;
847         struct se_queue_req *qr = NULL;
848
849         if (list_empty(&qobj->qobj_list))
850                 return NULL;
851
852         list_for_each_entry(qr, &qobj->qobj_list, qr_list)
853                 break;
854
855         if (qr->cmd) {
856                 cmd = (struct se_cmd *)qr->cmd;
857                 atomic_dec(&T_TASK(cmd)->t_transport_queue_active);
858         }
859         list_del(&qr->qr_list);
860         atomic_dec(&qobj->queue_cnt);
861
862         return qr;
863 }
864
865 static struct se_queue_req *
866 transport_get_qr_from_queue(struct se_queue_obj *qobj)
867 {
868         struct se_cmd *cmd;
869         struct se_queue_req *qr;
870         unsigned long flags;
871
872         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
873         if (list_empty(&qobj->qobj_list)) {
874                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
875                 return NULL;
876         }
877
878         list_for_each_entry(qr, &qobj->qobj_list, qr_list)
879                 break;
880
881         if (qr->cmd) {
882                 cmd = (struct se_cmd *)qr->cmd;
883                 atomic_dec(&T_TASK(cmd)->t_transport_queue_active);
884         }
885         list_del(&qr->qr_list);
886         atomic_dec(&qobj->queue_cnt);
887         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
888
889         return qr;
890 }
891
892 static void transport_remove_cmd_from_queue(struct se_cmd *cmd,
893                 struct se_queue_obj *qobj)
894 {
895         struct se_cmd *q_cmd;
896         struct se_queue_req *qr = NULL, *qr_p = NULL;
897         unsigned long flags;
898
899         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
900         if (!(atomic_read(&T_TASK(cmd)->t_transport_queue_active))) {
901                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
902                 return;
903         }
904
905         list_for_each_entry_safe(qr, qr_p, &qobj->qobj_list, qr_list) {
906                 q_cmd = (struct se_cmd *)qr->cmd;
907                 if (q_cmd != cmd)
908                         continue;
909
910                 atomic_dec(&T_TASK(q_cmd)->t_transport_queue_active);
911                 atomic_dec(&qobj->queue_cnt);
912                 list_del(&qr->qr_list);
913                 kfree(qr);
914         }
915         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
916
917         if (atomic_read(&T_TASK(cmd)->t_transport_queue_active)) {
918                 printk(KERN_ERR "ITT: 0x%08x t_transport_queue_active: %d\n",
919                         CMD_TFO(cmd)->get_task_tag(cmd),
920                         atomic_read(&T_TASK(cmd)->t_transport_queue_active));
921         }
922 }
923
924 /*
925  * Completion function used by TCM subsystem plugins (such as FILEIO)
926  * for queueing up response from struct se_subsystem_api->do_task()
927  */
928 void transport_complete_sync_cache(struct se_cmd *cmd, int good)
929 {
930         struct se_task *task = list_entry(T_TASK(cmd)->t_task_list.next,
931                                 struct se_task, t_list);
932
933         if (good) {
934                 cmd->scsi_status = SAM_STAT_GOOD;
935                 task->task_scsi_status = GOOD;
936         } else {
937                 task->task_scsi_status = SAM_STAT_CHECK_CONDITION;
938                 task->task_error_status = PYX_TRANSPORT_ILLEGAL_REQUEST;
939                 TASK_CMD(task)->transport_error_status =
940                                         PYX_TRANSPORT_ILLEGAL_REQUEST;
941         }
942
943         transport_complete_task(task, good);
944 }
945 EXPORT_SYMBOL(transport_complete_sync_cache);
946
947 /*      transport_complete_task():
948  *
949  *      Called from interrupt and non interrupt context depending
950  *      on the transport plugin.
951  */
952 void transport_complete_task(struct se_task *task, int success)
953 {
954         struct se_cmd *cmd = TASK_CMD(task);
955         struct se_device *dev = task->se_dev;
956         int t_state;
957         unsigned long flags;
958 #if 0
959         printk(KERN_INFO "task: %p CDB: 0x%02x obj_ptr: %p\n", task,
960                         T_TASK(cmd)->t_task_cdb[0], dev);
961 #endif
962         if (dev) {
963                 spin_lock_irqsave(&SE_HBA(dev)->hba_queue_lock, flags);
964                 atomic_inc(&dev->depth_left);
965                 atomic_inc(&SE_HBA(dev)->left_queue_depth);
966                 spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
967         }
968
969         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
970         atomic_set(&task->task_active, 0);
971
972         /*
973          * See if any sense data exists, if so set the TASK_SENSE flag.
974          * Also check for any other post completion work that needs to be
975          * done by the plugins.
976          */
977         if (dev && dev->transport->transport_complete) {
978                 if (dev->transport->transport_complete(task) != 0) {
979                         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
980                         task->task_sense = 1;
981                         success = 1;
982                 }
983         }
984
985         /*
986          * See if we are waiting for outstanding struct se_task
987          * to complete for an exception condition
988          */
989         if (atomic_read(&task->task_stop)) {
990                 /*
991                  * Decrement T_TASK(cmd)->t_se_count if this task had
992                  * previously thrown its timeout exception handler.
993                  */
994                 if (atomic_read(&task->task_timeout)) {
995                         atomic_dec(&T_TASK(cmd)->t_se_count);
996                         atomic_set(&task->task_timeout, 0);
997                 }
998                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
999
1000                 complete(&task->task_stop_comp);
1001                 return;
1002         }
1003         /*
1004          * If the task's timeout handler has fired, use the t_task_cdbs_timeout
1005          * left counter to determine when the struct se_cmd is ready to be queued to
1006          * the processing thread.
1007          */
1008         if (atomic_read(&task->task_timeout)) {
1009                 if (!(atomic_dec_and_test(
1010                                 &T_TASK(cmd)->t_task_cdbs_timeout_left))) {
1011                         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
1012                                 flags);
1013                         return;
1014                 }
1015                 t_state = TRANSPORT_COMPLETE_TIMEOUT;
1016                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
1017
1018                 transport_add_cmd_to_queue(cmd, t_state);
1019                 return;
1020         }
1021         atomic_dec(&T_TASK(cmd)->t_task_cdbs_timeout_left);
1022
1023         /*
1024          * Decrement the outstanding t_task_cdbs_left count.  The last
1025          * struct se_task from struct se_cmd will complete itself into the
1026          * device queue depending upon int success.
1027          */
1028         if (!(atomic_dec_and_test(&T_TASK(cmd)->t_task_cdbs_left))) {
1029                 if (!success)
1030                         T_TASK(cmd)->t_tasks_failed = 1;
1031
1032                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
1033                 return;
1034         }
1035
1036         if (!success || T_TASK(cmd)->t_tasks_failed) {
1037                 t_state = TRANSPORT_COMPLETE_FAILURE;
1038                 if (!task->task_error_status) {
1039                         task->task_error_status =
1040                                 PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
1041                         cmd->transport_error_status =
1042                                 PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
1043                 }
1044         } else {
1045                 atomic_set(&T_TASK(cmd)->t_transport_complete, 1);
1046                 t_state = TRANSPORT_COMPLETE_OK;
1047         }
1048         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
1049
1050         transport_add_cmd_to_queue(cmd, t_state);
1051 }
1052 EXPORT_SYMBOL(transport_complete_task);
1053
1054 /*
1055  * Called by transport_add_tasks_from_cmd() once a struct se_cmd's
1056  * struct se_task list are ready to be added to the active execution list
1057  * struct se_device
1058
1059  * Called with se_dev_t->execute_task_lock called.
1060  */
1061 static inline int transport_add_task_check_sam_attr(
1062         struct se_task *task,
1063         struct se_task *task_prev,
1064         struct se_device *dev)
1065 {
1066         /*
1067          * No SAM Task attribute emulation enabled, add to tail of
1068          * execution queue
1069          */
1070         if (dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED) {
1071                 list_add_tail(&task->t_execute_list, &dev->execute_task_list);
1072                 return 0;
1073         }
1074         /*
1075          * HEAD_OF_QUEUE attribute for received CDB, which means
1076          * the first task that is associated with a struct se_cmd goes to
1077          * head of the struct se_device->execute_task_list, and task_prev
1078          * after that for each subsequent task
1079          */
1080         if (task->task_se_cmd->sam_task_attr == TASK_ATTR_HOQ) {
1081                 list_add(&task->t_execute_list,
1082                                 (task_prev != NULL) ?
1083                                 &task_prev->t_execute_list :
1084                                 &dev->execute_task_list);
1085
1086                 DEBUG_STA("Set HEAD_OF_QUEUE for task CDB: 0x%02x"
1087                                 " in execution queue\n",
1088                                 T_TASK(task->task_se_cmd)->t_task_cdb[0]);
1089                 return 1;
1090         }
1091         /*
1092          * For ORDERED, SIMPLE or UNTAGGED attribute tasks once they have been
1093          * transitioned from Dermant -> Active state, and are added to the end
1094          * of the struct se_device->execute_task_list
1095          */
1096         list_add_tail(&task->t_execute_list, &dev->execute_task_list);
1097         return 0;
1098 }
1099
1100 /*      __transport_add_task_to_execute_queue():
1101  *
1102  *      Called with se_dev_t->execute_task_lock called.
1103  */
1104 static void __transport_add_task_to_execute_queue(
1105         struct se_task *task,
1106         struct se_task *task_prev,
1107         struct se_device *dev)
1108 {
1109         int head_of_queue;
1110
1111         head_of_queue = transport_add_task_check_sam_attr(task, task_prev, dev);
1112         atomic_inc(&dev->execute_tasks);
1113
1114         if (atomic_read(&task->task_state_active))
1115                 return;
1116         /*
1117          * Determine if this task needs to go to HEAD_OF_QUEUE for the
1118          * state list as well.  Running with SAM Task Attribute emulation
1119          * will always return head_of_queue == 0 here
1120          */
1121         if (head_of_queue)
1122                 list_add(&task->t_state_list, (task_prev) ?
1123                                 &task_prev->t_state_list :
1124                                 &dev->state_task_list);
1125         else
1126                 list_add_tail(&task->t_state_list, &dev->state_task_list);
1127
1128         atomic_set(&task->task_state_active, 1);
1129
1130         DEBUG_TSTATE("Added ITT: 0x%08x task[%p] to dev: %p\n",
1131                 CMD_TFO(task->task_se_cmd)->get_task_tag(task->task_se_cmd),
1132                 task, dev);
1133 }
1134
1135 static void transport_add_tasks_to_state_queue(struct se_cmd *cmd)
1136 {
1137         struct se_device *dev;
1138         struct se_task *task;
1139         unsigned long flags;
1140
1141         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
1142         list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
1143                 dev = task->se_dev;
1144
1145                 if (atomic_read(&task->task_state_active))
1146                         continue;
1147
1148                 spin_lock(&dev->execute_task_lock);
1149                 list_add_tail(&task->t_state_list, &dev->state_task_list);
1150                 atomic_set(&task->task_state_active, 1);
1151
1152                 DEBUG_TSTATE("Added ITT: 0x%08x task[%p] to dev: %p\n",
1153                         CMD_TFO(task->task_se_cmd)->get_task_tag(
1154                         task->task_se_cmd), task, dev);
1155
1156                 spin_unlock(&dev->execute_task_lock);
1157         }
1158         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
1159 }
1160
1161 static void transport_add_tasks_from_cmd(struct se_cmd *cmd)
1162 {
1163         struct se_device *dev = SE_DEV(cmd);
1164         struct se_task *task, *task_prev = NULL;
1165         unsigned long flags;
1166
1167         spin_lock_irqsave(&dev->execute_task_lock, flags);
1168         list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
1169                 if (atomic_read(&task->task_execute_queue))
1170                         continue;
1171                 /*
1172                  * __transport_add_task_to_execute_queue() handles the
1173                  * SAM Task Attribute emulation if enabled
1174                  */
1175                 __transport_add_task_to_execute_queue(task, task_prev, dev);
1176                 atomic_set(&task->task_execute_queue, 1);
1177                 task_prev = task;
1178         }
1179         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
1180
1181         return;
1182 }
1183
1184 /*      transport_get_task_from_execute_queue():
1185  *
1186  *      Called with dev->execute_task_lock held.
1187  */
1188 static struct se_task *
1189 transport_get_task_from_execute_queue(struct se_device *dev)
1190 {
1191         struct se_task *task;
1192
1193         if (list_empty(&dev->execute_task_list))
1194                 return NULL;
1195
1196         list_for_each_entry(task, &dev->execute_task_list, t_execute_list)
1197                 break;
1198
1199         list_del(&task->t_execute_list);
1200         atomic_dec(&dev->execute_tasks);
1201
1202         return task;
1203 }
1204
1205 /*      transport_remove_task_from_execute_queue():
1206  *
1207  *
1208  */
1209 void transport_remove_task_from_execute_queue(
1210         struct se_task *task,
1211         struct se_device *dev)
1212 {
1213         unsigned long flags;
1214
1215         spin_lock_irqsave(&dev->execute_task_lock, flags);
1216         list_del(&task->t_execute_list);
1217         atomic_dec(&dev->execute_tasks);
1218         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
1219 }
1220
1221 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
1222 {
1223         switch (cmd->data_direction) {
1224         case DMA_NONE:
1225                 return "NONE";
1226         case DMA_FROM_DEVICE:
1227                 return "READ";
1228         case DMA_TO_DEVICE:
1229                 return "WRITE";
1230         case DMA_BIDIRECTIONAL:
1231                 return "BIDI";
1232         default:
1233                 break;
1234         }
1235
1236         return "UNKNOWN";
1237 }
1238
1239 void transport_dump_dev_state(
1240         struct se_device *dev,
1241         char *b,
1242         int *bl)
1243 {
1244         *bl += sprintf(b + *bl, "Status: ");
1245         switch (dev->dev_status) {
1246         case TRANSPORT_DEVICE_ACTIVATED:
1247                 *bl += sprintf(b + *bl, "ACTIVATED");
1248                 break;
1249         case TRANSPORT_DEVICE_DEACTIVATED:
1250                 *bl += sprintf(b + *bl, "DEACTIVATED");
1251                 break;
1252         case TRANSPORT_DEVICE_SHUTDOWN:
1253                 *bl += sprintf(b + *bl, "SHUTDOWN");
1254                 break;
1255         case TRANSPORT_DEVICE_OFFLINE_ACTIVATED:
1256         case TRANSPORT_DEVICE_OFFLINE_DEACTIVATED:
1257                 *bl += sprintf(b + *bl, "OFFLINE");
1258                 break;
1259         default:
1260                 *bl += sprintf(b + *bl, "UNKNOWN=%d", dev->dev_status);
1261                 break;
1262         }
1263
1264         *bl += sprintf(b + *bl, "  Execute/Left/Max Queue Depth: %d/%d/%d",
1265                 atomic_read(&dev->execute_tasks), atomic_read(&dev->depth_left),
1266                 dev->queue_depth);
1267         *bl += sprintf(b + *bl, "  SectorSize: %u  MaxSectors: %u\n",
1268                 DEV_ATTRIB(dev)->block_size, DEV_ATTRIB(dev)->max_sectors);
1269         *bl += sprintf(b + *bl, "        ");
1270 }
1271
1272 /*      transport_release_all_cmds():
1273  *
1274  *
1275  */
1276 static void transport_release_all_cmds(struct se_device *dev)
1277 {
1278         struct se_cmd *cmd = NULL;
1279         struct se_queue_req *qr = NULL, *qr_p = NULL;
1280         int bug_out = 0, t_state;
1281         unsigned long flags;
1282
1283         spin_lock_irqsave(&dev->dev_queue_obj->cmd_queue_lock, flags);
1284         list_for_each_entry_safe(qr, qr_p, &dev->dev_queue_obj->qobj_list,
1285                                 qr_list) {
1286
1287                 cmd = (struct se_cmd *)qr->cmd;
1288                 t_state = qr->state;
1289                 list_del(&qr->qr_list);
1290                 kfree(qr);
1291                 spin_unlock_irqrestore(&dev->dev_queue_obj->cmd_queue_lock,
1292                                 flags);
1293
1294                 printk(KERN_ERR "Releasing ITT: 0x%08x, i_state: %u,"
1295                         " t_state: %u directly\n",
1296                         CMD_TFO(cmd)->get_task_tag(cmd),
1297                         CMD_TFO(cmd)->get_cmd_state(cmd), t_state);
1298
1299                 transport_release_fe_cmd(cmd);
1300                 bug_out = 1;
1301
1302                 spin_lock_irqsave(&dev->dev_queue_obj->cmd_queue_lock, flags);
1303         }
1304         spin_unlock_irqrestore(&dev->dev_queue_obj->cmd_queue_lock, flags);
1305 #if 0
1306         if (bug_out)
1307                 BUG();
1308 #endif
1309 }
1310
1311 void transport_dump_vpd_proto_id(
1312         struct t10_vpd *vpd,
1313         unsigned char *p_buf,
1314         int p_buf_len)
1315 {
1316         unsigned char buf[VPD_TMP_BUF_SIZE];
1317         int len;
1318
1319         memset(buf, 0, VPD_TMP_BUF_SIZE);
1320         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
1321
1322         switch (vpd->protocol_identifier) {
1323         case 0x00:
1324                 sprintf(buf+len, "Fibre Channel\n");
1325                 break;
1326         case 0x10:
1327                 sprintf(buf+len, "Parallel SCSI\n");
1328                 break;
1329         case 0x20:
1330                 sprintf(buf+len, "SSA\n");
1331                 break;
1332         case 0x30:
1333                 sprintf(buf+len, "IEEE 1394\n");
1334                 break;
1335         case 0x40:
1336                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
1337                                 " Protocol\n");
1338                 break;
1339         case 0x50:
1340                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
1341                 break;
1342         case 0x60:
1343                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
1344                 break;
1345         case 0x70:
1346                 sprintf(buf+len, "Automation/Drive Interface Transport"
1347                                 " Protocol\n");
1348                 break;
1349         case 0x80:
1350                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
1351                 break;
1352         default:
1353                 sprintf(buf+len, "Unknown 0x%02x\n",
1354                                 vpd->protocol_identifier);
1355                 break;
1356         }
1357
1358         if (p_buf)
1359                 strncpy(p_buf, buf, p_buf_len);
1360         else
1361                 printk(KERN_INFO "%s", buf);
1362 }
1363
1364 void
1365 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1366 {
1367         /*
1368          * Check if the Protocol Identifier Valid (PIV) bit is set..
1369          *
1370          * from spc3r23.pdf section 7.5.1
1371          */
1372          if (page_83[1] & 0x80) {
1373                 vpd->protocol_identifier = (page_83[0] & 0xf0);
1374                 vpd->protocol_identifier_set = 1;
1375                 transport_dump_vpd_proto_id(vpd, NULL, 0);
1376         }
1377 }
1378 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1379
1380 int transport_dump_vpd_assoc(
1381         struct t10_vpd *vpd,
1382         unsigned char *p_buf,
1383         int p_buf_len)
1384 {
1385         unsigned char buf[VPD_TMP_BUF_SIZE];
1386         int ret = 0, len;
1387
1388         memset(buf, 0, VPD_TMP_BUF_SIZE);
1389         len = sprintf(buf, "T10 VPD Identifier Association: ");
1390
1391         switch (vpd->association) {
1392         case 0x00:
1393                 sprintf(buf+len, "addressed logical unit\n");
1394                 break;
1395         case 0x10:
1396                 sprintf(buf+len, "target port\n");
1397                 break;
1398         case 0x20:
1399                 sprintf(buf+len, "SCSI target device\n");
1400                 break;
1401         default:
1402                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1403                 ret = -1;
1404                 break;
1405         }
1406
1407         if (p_buf)
1408                 strncpy(p_buf, buf, p_buf_len);
1409         else
1410                 printk("%s", buf);
1411
1412         return ret;
1413 }
1414
1415 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1416 {
1417         /*
1418          * The VPD identification association..
1419          *
1420          * from spc3r23.pdf Section 7.6.3.1 Table 297
1421          */
1422         vpd->association = (page_83[1] & 0x30);
1423         return transport_dump_vpd_assoc(vpd, NULL, 0);
1424 }
1425 EXPORT_SYMBOL(transport_set_vpd_assoc);
1426
1427 int transport_dump_vpd_ident_type(
1428         struct t10_vpd *vpd,
1429         unsigned char *p_buf,
1430         int p_buf_len)
1431 {
1432         unsigned char buf[VPD_TMP_BUF_SIZE];
1433         int ret = 0, len;
1434
1435         memset(buf, 0, VPD_TMP_BUF_SIZE);
1436         len = sprintf(buf, "T10 VPD Identifier Type: ");
1437
1438         switch (vpd->device_identifier_type) {
1439         case 0x00:
1440                 sprintf(buf+len, "Vendor specific\n");
1441                 break;
1442         case 0x01:
1443                 sprintf(buf+len, "T10 Vendor ID based\n");
1444                 break;
1445         case 0x02:
1446                 sprintf(buf+len, "EUI-64 based\n");
1447                 break;
1448         case 0x03:
1449                 sprintf(buf+len, "NAA\n");
1450                 break;
1451         case 0x04:
1452                 sprintf(buf+len, "Relative target port identifier\n");
1453                 break;
1454         case 0x08:
1455                 sprintf(buf+len, "SCSI name string\n");
1456                 break;
1457         default:
1458                 sprintf(buf+len, "Unsupported: 0x%02x\n",
1459                                 vpd->device_identifier_type);
1460                 ret = -1;
1461                 break;
1462         }
1463
1464         if (p_buf)
1465                 strncpy(p_buf, buf, p_buf_len);
1466         else
1467                 printk("%s", buf);
1468
1469         return ret;
1470 }
1471
1472 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1473 {
1474         /*
1475          * The VPD identifier type..
1476          *
1477          * from spc3r23.pdf Section 7.6.3.1 Table 298
1478          */
1479         vpd->device_identifier_type = (page_83[1] & 0x0f);
1480         return transport_dump_vpd_ident_type(vpd, NULL, 0);
1481 }
1482 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1483
1484 int transport_dump_vpd_ident(
1485         struct t10_vpd *vpd,
1486         unsigned char *p_buf,
1487         int p_buf_len)
1488 {
1489         unsigned char buf[VPD_TMP_BUF_SIZE];
1490         int ret = 0;
1491
1492         memset(buf, 0, VPD_TMP_BUF_SIZE);
1493
1494         switch (vpd->device_identifier_code_set) {
1495         case 0x01: /* Binary */
1496                 sprintf(buf, "T10 VPD Binary Device Identifier: %s\n",
1497                         &vpd->device_identifier[0]);
1498                 break;
1499         case 0x02: /* ASCII */
1500                 sprintf(buf, "T10 VPD ASCII Device Identifier: %s\n",
1501                         &vpd->device_identifier[0]);
1502                 break;
1503         case 0x03: /* UTF-8 */
1504                 sprintf(buf, "T10 VPD UTF-8 Device Identifier: %s\n",
1505                         &vpd->device_identifier[0]);
1506                 break;
1507         default:
1508                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1509                         " 0x%02x", vpd->device_identifier_code_set);
1510                 ret = -1;
1511                 break;
1512         }
1513
1514         if (p_buf)
1515                 strncpy(p_buf, buf, p_buf_len);
1516         else
1517                 printk("%s", buf);
1518
1519         return ret;
1520 }
1521
1522 int
1523 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1524 {
1525         static const char hex_str[] = "0123456789abcdef";
1526         int j = 0, i = 4; /* offset to start of the identifer */
1527
1528         /*
1529          * The VPD Code Set (encoding)
1530          *
1531          * from spc3r23.pdf Section 7.6.3.1 Table 296
1532          */
1533         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1534         switch (vpd->device_identifier_code_set) {
1535         case 0x01: /* Binary */
1536                 vpd->device_identifier[j++] =
1537                                 hex_str[vpd->device_identifier_type];
1538                 while (i < (4 + page_83[3])) {
1539                         vpd->device_identifier[j++] =
1540                                 hex_str[(page_83[i] & 0xf0) >> 4];
1541                         vpd->device_identifier[j++] =
1542                                 hex_str[page_83[i] & 0x0f];
1543                         i++;
1544                 }
1545                 break;
1546         case 0x02: /* ASCII */
1547         case 0x03: /* UTF-8 */
1548                 while (i < (4 + page_83[3]))
1549                         vpd->device_identifier[j++] = page_83[i++];
1550                 break;
1551         default:
1552                 break;
1553         }
1554
1555         return transport_dump_vpd_ident(vpd, NULL, 0);
1556 }
1557 EXPORT_SYMBOL(transport_set_vpd_ident);
1558
1559 static void core_setup_task_attr_emulation(struct se_device *dev)
1560 {
1561         /*
1562          * If this device is from Target_Core_Mod/pSCSI, disable the
1563          * SAM Task Attribute emulation.
1564          *
1565          * This is currently not available in upsream Linux/SCSI Target
1566          * mode code, and is assumed to be disabled while using TCM/pSCSI.
1567          */
1568         if (TRANSPORT(dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) {
1569                 dev->dev_task_attr_type = SAM_TASK_ATTR_PASSTHROUGH;
1570                 return;
1571         }
1572
1573         dev->dev_task_attr_type = SAM_TASK_ATTR_EMULATED;
1574         DEBUG_STA("%s: Using SAM_TASK_ATTR_EMULATED for SPC: 0x%02x"
1575                 " device\n", TRANSPORT(dev)->name,
1576                 TRANSPORT(dev)->get_device_rev(dev));
1577 }
1578
1579 static void scsi_dump_inquiry(struct se_device *dev)
1580 {
1581         struct t10_wwn *wwn = DEV_T10_WWN(dev);
1582         int i, device_type;
1583         /*
1584          * Print Linux/SCSI style INQUIRY formatting to the kernel ring buffer
1585          */
1586         printk("  Vendor: ");
1587         for (i = 0; i < 8; i++)
1588                 if (wwn->vendor[i] >= 0x20)
1589                         printk("%c", wwn->vendor[i]);
1590                 else
1591                         printk(" ");
1592
1593         printk("  Model: ");
1594         for (i = 0; i < 16; i++)
1595                 if (wwn->model[i] >= 0x20)
1596                         printk("%c", wwn->model[i]);
1597                 else
1598                         printk(" ");
1599
1600         printk("  Revision: ");
1601         for (i = 0; i < 4; i++)
1602                 if (wwn->revision[i] >= 0x20)
1603                         printk("%c", wwn->revision[i]);
1604                 else
1605                         printk(" ");
1606
1607         printk("\n");
1608
1609         device_type = TRANSPORT(dev)->get_device_type(dev);
1610         printk("  Type:   %s ", scsi_device_type(device_type));
1611         printk("                 ANSI SCSI revision: %02x\n",
1612                                 TRANSPORT(dev)->get_device_rev(dev));
1613 }
1614
1615 struct se_device *transport_add_device_to_core_hba(
1616         struct se_hba *hba,
1617         struct se_subsystem_api *transport,
1618         struct se_subsystem_dev *se_dev,
1619         u32 device_flags,
1620         void *transport_dev,
1621         struct se_dev_limits *dev_limits,
1622         const char *inquiry_prod,
1623         const char *inquiry_rev)
1624 {
1625         int ret = 0, force_pt;
1626         struct se_device  *dev;
1627
1628         dev = kzalloc(sizeof(struct se_device), GFP_KERNEL);
1629         if (!(dev)) {
1630                 printk(KERN_ERR "Unable to allocate memory for se_dev_t\n");
1631                 return NULL;
1632         }
1633         dev->dev_queue_obj = kzalloc(sizeof(struct se_queue_obj), GFP_KERNEL);
1634         if (!(dev->dev_queue_obj)) {
1635                 printk(KERN_ERR "Unable to allocate memory for"
1636                                 " dev->dev_queue_obj\n");
1637                 kfree(dev);
1638                 return NULL;
1639         }
1640         transport_init_queue_obj(dev->dev_queue_obj);
1641
1642         dev->dev_status_queue_obj = kzalloc(sizeof(struct se_queue_obj),
1643                                         GFP_KERNEL);
1644         if (!(dev->dev_status_queue_obj)) {
1645                 printk(KERN_ERR "Unable to allocate memory for"
1646                                 " dev->dev_status_queue_obj\n");
1647                 kfree(dev->dev_queue_obj);
1648                 kfree(dev);
1649                 return NULL;
1650         }
1651         transport_init_queue_obj(dev->dev_status_queue_obj);
1652
1653         dev->dev_flags          = device_flags;
1654         dev->dev_status         |= TRANSPORT_DEVICE_DEACTIVATED;
1655         dev->dev_ptr            = (void *) transport_dev;
1656         dev->se_hba             = hba;
1657         dev->se_sub_dev         = se_dev;
1658         dev->transport          = transport;
1659         atomic_set(&dev->active_cmds, 0);
1660         INIT_LIST_HEAD(&dev->dev_list);
1661         INIT_LIST_HEAD(&dev->dev_sep_list);
1662         INIT_LIST_HEAD(&dev->dev_tmr_list);
1663         INIT_LIST_HEAD(&dev->execute_task_list);
1664         INIT_LIST_HEAD(&dev->delayed_cmd_list);
1665         INIT_LIST_HEAD(&dev->ordered_cmd_list);
1666         INIT_LIST_HEAD(&dev->state_task_list);
1667         spin_lock_init(&dev->execute_task_lock);
1668         spin_lock_init(&dev->delayed_cmd_lock);
1669         spin_lock_init(&dev->ordered_cmd_lock);
1670         spin_lock_init(&dev->state_task_lock);
1671         spin_lock_init(&dev->dev_alua_lock);
1672         spin_lock_init(&dev->dev_reservation_lock);
1673         spin_lock_init(&dev->dev_status_lock);
1674         spin_lock_init(&dev->dev_status_thr_lock);
1675         spin_lock_init(&dev->se_port_lock);
1676         spin_lock_init(&dev->se_tmr_lock);
1677
1678         dev->queue_depth        = dev_limits->queue_depth;
1679         atomic_set(&dev->depth_left, dev->queue_depth);
1680         atomic_set(&dev->dev_ordered_id, 0);
1681
1682         se_dev_set_default_attribs(dev, dev_limits);
1683
1684         dev->dev_index = scsi_get_new_index(SCSI_DEVICE_INDEX);
1685         dev->creation_time = get_jiffies_64();
1686         spin_lock_init(&dev->stats_lock);
1687
1688         spin_lock(&hba->device_lock);
1689         list_add_tail(&dev->dev_list, &hba->hba_dev_list);
1690         hba->dev_count++;
1691         spin_unlock(&hba->device_lock);
1692         /*
1693          * Setup the SAM Task Attribute emulation for struct se_device
1694          */
1695         core_setup_task_attr_emulation(dev);
1696         /*
1697          * Force PR and ALUA passthrough emulation with internal object use.
1698          */
1699         force_pt = (hba->hba_flags & HBA_FLAGS_INTERNAL_USE);
1700         /*
1701          * Setup the Reservations infrastructure for struct se_device
1702          */
1703         core_setup_reservations(dev, force_pt);
1704         /*
1705          * Setup the Asymmetric Logical Unit Assignment for struct se_device
1706          */
1707         if (core_setup_alua(dev, force_pt) < 0)
1708                 goto out;
1709
1710         /*
1711          * Startup the struct se_device processing thread
1712          */
1713         dev->process_thread = kthread_run(transport_processing_thread, dev,
1714                                           "LIO_%s", TRANSPORT(dev)->name);
1715         if (IS_ERR(dev->process_thread)) {
1716                 printk(KERN_ERR "Unable to create kthread: LIO_%s\n",
1717                         TRANSPORT(dev)->name);
1718                 goto out;
1719         }
1720
1721         /*
1722          * Preload the initial INQUIRY const values if we are doing
1723          * anything virtual (IBLOCK, FILEIO, RAMDISK), but not for TCM/pSCSI
1724          * passthrough because this is being provided by the backend LLD.
1725          * This is required so that transport_get_inquiry() copies these
1726          * originals once back into DEV_T10_WWN(dev) for the virtual device
1727          * setup.
1728          */
1729         if (TRANSPORT(dev)->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
1730                 if (!(inquiry_prod) || !(inquiry_prod)) {
1731                         printk(KERN_ERR "All non TCM/pSCSI plugins require"
1732                                 " INQUIRY consts\n");
1733                         goto out;
1734                 }
1735
1736                 strncpy(&DEV_T10_WWN(dev)->vendor[0], "LIO-ORG", 8);
1737                 strncpy(&DEV_T10_WWN(dev)->model[0], inquiry_prod, 16);
1738                 strncpy(&DEV_T10_WWN(dev)->revision[0], inquiry_rev, 4);
1739         }
1740         scsi_dump_inquiry(dev);
1741
1742 out:
1743         if (!ret)
1744                 return dev;
1745         kthread_stop(dev->process_thread);
1746
1747         spin_lock(&hba->device_lock);
1748         list_del(&dev->dev_list);
1749         hba->dev_count--;
1750         spin_unlock(&hba->device_lock);
1751
1752         se_release_vpd_for_dev(dev);
1753
1754         kfree(dev->dev_status_queue_obj);
1755         kfree(dev->dev_queue_obj);
1756         kfree(dev);
1757
1758         return NULL;
1759 }
1760 EXPORT_SYMBOL(transport_add_device_to_core_hba);
1761
1762 /*      transport_generic_prepare_cdb():
1763  *
1764  *      Since the Initiator sees iSCSI devices as LUNs,  the SCSI CDB will
1765  *      contain the iSCSI LUN in bits 7-5 of byte 1 as per SAM-2.
1766  *      The point of this is since we are mapping iSCSI LUNs to
1767  *      SCSI Target IDs having a non-zero LUN in the CDB will throw the
1768  *      devices and HBAs for a loop.
1769  */
1770 static inline void transport_generic_prepare_cdb(
1771         unsigned char *cdb)
1772 {
1773         switch (cdb[0]) {
1774         case READ_10: /* SBC - RDProtect */
1775         case READ_12: /* SBC - RDProtect */
1776         case READ_16: /* SBC - RDProtect */
1777         case SEND_DIAGNOSTIC: /* SPC - SELF-TEST Code */
1778         case VERIFY: /* SBC - VRProtect */
1779         case VERIFY_16: /* SBC - VRProtect */
1780         case WRITE_VERIFY: /* SBC - VRProtect */
1781         case WRITE_VERIFY_12: /* SBC - VRProtect */
1782                 break;
1783         default:
1784                 cdb[1] &= 0x1f; /* clear logical unit number */
1785                 break;
1786         }
1787 }
1788
1789 static struct se_task *
1790 transport_generic_get_task(struct se_cmd *cmd,
1791                 enum dma_data_direction data_direction)
1792 {
1793         struct se_task *task;
1794         struct se_device *dev = SE_DEV(cmd);
1795         unsigned long flags;
1796
1797         task = dev->transport->alloc_task(cmd);
1798         if (!task) {
1799                 printk(KERN_ERR "Unable to allocate struct se_task\n");
1800                 return NULL;
1801         }
1802
1803         INIT_LIST_HEAD(&task->t_list);
1804         INIT_LIST_HEAD(&task->t_execute_list);
1805         INIT_LIST_HEAD(&task->t_state_list);
1806         init_completion(&task->task_stop_comp);
1807         task->task_no = T_TASK(cmd)->t_tasks_no++;
1808         task->task_se_cmd = cmd;
1809         task->se_dev = dev;
1810         task->task_data_direction = data_direction;
1811
1812         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
1813         list_add_tail(&task->t_list, &T_TASK(cmd)->t_task_list);
1814         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
1815
1816         return task;
1817 }
1818
1819 static int transport_generic_cmd_sequencer(struct se_cmd *, unsigned char *);
1820
1821 void transport_device_setup_cmd(struct se_cmd *cmd)
1822 {
1823         cmd->se_dev = SE_LUN(cmd)->lun_se_dev;
1824 }
1825 EXPORT_SYMBOL(transport_device_setup_cmd);
1826
1827 /*
1828  * Used by fabric modules containing a local struct se_cmd within their
1829  * fabric dependent per I/O descriptor.
1830  */
1831 void transport_init_se_cmd(
1832         struct se_cmd *cmd,
1833         struct target_core_fabric_ops *tfo,
1834         struct se_session *se_sess,
1835         u32 data_length,
1836         int data_direction,
1837         int task_attr,
1838         unsigned char *sense_buffer)
1839 {
1840         INIT_LIST_HEAD(&cmd->se_lun_list);
1841         INIT_LIST_HEAD(&cmd->se_delayed_list);
1842         INIT_LIST_HEAD(&cmd->se_ordered_list);
1843         /*
1844          * Setup t_task pointer to t_task_backstore
1845          */
1846         cmd->t_task = &cmd->t_task_backstore;
1847
1848         INIT_LIST_HEAD(&T_TASK(cmd)->t_task_list);
1849         init_completion(&T_TASK(cmd)->transport_lun_fe_stop_comp);
1850         init_completion(&T_TASK(cmd)->transport_lun_stop_comp);
1851         init_completion(&T_TASK(cmd)->t_transport_stop_comp);
1852         spin_lock_init(&T_TASK(cmd)->t_state_lock);
1853         atomic_set(&T_TASK(cmd)->transport_dev_active, 1);
1854
1855         cmd->se_tfo = tfo;
1856         cmd->se_sess = se_sess;
1857         cmd->data_length = data_length;
1858         cmd->data_direction = data_direction;
1859         cmd->sam_task_attr = task_attr;
1860         cmd->sense_buffer = sense_buffer;
1861 }
1862 EXPORT_SYMBOL(transport_init_se_cmd);
1863
1864 static int transport_check_alloc_task_attr(struct se_cmd *cmd)
1865 {
1866         /*
1867          * Check if SAM Task Attribute emulation is enabled for this
1868          * struct se_device storage object
1869          */
1870         if (SE_DEV(cmd)->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1871                 return 0;
1872
1873         if (cmd->sam_task_attr == TASK_ATTR_ACA) {
1874                 DEBUG_STA("SAM Task Attribute ACA"
1875                         " emulation is not supported\n");
1876                 return -1;
1877         }
1878         /*
1879          * Used to determine when ORDERED commands should go from
1880          * Dormant to Active status.
1881          */
1882         cmd->se_ordered_id = atomic_inc_return(&SE_DEV(cmd)->dev_ordered_id);
1883         smp_mb__after_atomic_inc();
1884         DEBUG_STA("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n",
1885                         cmd->se_ordered_id, cmd->sam_task_attr,
1886                         TRANSPORT(cmd->se_dev)->name);
1887         return 0;
1888 }
1889
1890 void transport_free_se_cmd(
1891         struct se_cmd *se_cmd)
1892 {
1893         if (se_cmd->se_tmr_req)
1894                 core_tmr_release_req(se_cmd->se_tmr_req);
1895         /*
1896          * Check and free any extended CDB buffer that was allocated
1897          */
1898         if (T_TASK(se_cmd)->t_task_cdb != T_TASK(se_cmd)->__t_task_cdb)
1899                 kfree(T_TASK(se_cmd)->t_task_cdb);
1900 }
1901 EXPORT_SYMBOL(transport_free_se_cmd);
1902
1903 static void transport_generic_wait_for_tasks(struct se_cmd *, int, int);
1904
1905 /*      transport_generic_allocate_tasks():
1906  *
1907  *      Called from fabric RX Thread.
1908  */
1909 int transport_generic_allocate_tasks(
1910         struct se_cmd *cmd,
1911         unsigned char *cdb)
1912 {
1913         int ret;
1914
1915         transport_generic_prepare_cdb(cdb);
1916
1917         /*
1918          * This is needed for early exceptions.
1919          */
1920         cmd->transport_wait_for_tasks = &transport_generic_wait_for_tasks;
1921
1922         transport_device_setup_cmd(cmd);
1923         /*
1924          * Ensure that the received CDB is less than the max (252 + 8) bytes
1925          * for VARIABLE_LENGTH_CMD
1926          */
1927         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1928                 printk(KERN_ERR "Received SCSI CDB with command_size: %d that"
1929                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1930                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1931                 return -1;
1932         }
1933         /*
1934          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1935          * allocate the additional extended CDB buffer now..  Otherwise
1936          * setup the pointer from __t_task_cdb to t_task_cdb.
1937          */
1938         if (scsi_command_size(cdb) > sizeof(T_TASK(cmd)->__t_task_cdb)) {
1939                 T_TASK(cmd)->t_task_cdb = kzalloc(scsi_command_size(cdb),
1940                                                 GFP_KERNEL);
1941                 if (!(T_TASK(cmd)->t_task_cdb)) {
1942                         printk(KERN_ERR "Unable to allocate T_TASK(cmd)->t_task_cdb"
1943                                 " %u > sizeof(T_TASK(cmd)->__t_task_cdb): %lu ops\n",
1944                                 scsi_command_size(cdb),
1945                                 (unsigned long)sizeof(T_TASK(cmd)->__t_task_cdb));
1946                         return -1;
1947                 }
1948         } else
1949                 T_TASK(cmd)->t_task_cdb = &T_TASK(cmd)->__t_task_cdb[0];
1950         /*
1951          * Copy the original CDB into T_TASK(cmd).
1952          */
1953         memcpy(T_TASK(cmd)->t_task_cdb, cdb, scsi_command_size(cdb));
1954         /*
1955          * Setup the received CDB based on SCSI defined opcodes and
1956          * perform unit attention, persistent reservations and ALUA
1957          * checks for virtual device backends.  The T_TASK(cmd)->t_task_cdb
1958          * pointer is expected to be setup before we reach this point.
1959          */
1960         ret = transport_generic_cmd_sequencer(cmd, cdb);
1961         if (ret < 0)
1962                 return ret;
1963         /*
1964          * Check for SAM Task Attribute Emulation
1965          */
1966         if (transport_check_alloc_task_attr(cmd) < 0) {
1967                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1968                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1969                 return -2;
1970         }
1971         spin_lock(&cmd->se_lun->lun_sep_lock);
1972         if (cmd->se_lun->lun_sep)
1973                 cmd->se_lun->lun_sep->sep_stats.cmd_pdus++;
1974         spin_unlock(&cmd->se_lun->lun_sep_lock);
1975         return 0;
1976 }
1977 EXPORT_SYMBOL(transport_generic_allocate_tasks);
1978
1979 /*
1980  * Used by fabric module frontends not defining a TFO->new_cmd_map()
1981  * to queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD statis
1982  */
1983 int transport_generic_handle_cdb(
1984         struct se_cmd *cmd)
1985 {
1986         if (!SE_LUN(cmd)) {
1987                 dump_stack();
1988                 printk(KERN_ERR "SE_LUN(cmd) is NULL\n");
1989                 return -1;
1990         }
1991
1992         transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD);
1993         return 0;
1994 }
1995 EXPORT_SYMBOL(transport_generic_handle_cdb);
1996
1997 /*
1998  * Used by fabric module frontends defining a TFO->new_cmd_map() caller
1999  * to  queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD_MAP in order to
2000  * complete setup in TCM process context w/ TFO->new_cmd_map().
2001  */
2002 int transport_generic_handle_cdb_map(
2003         struct se_cmd *cmd)
2004 {
2005         if (!SE_LUN(cmd)) {
2006                 dump_stack();
2007                 printk(KERN_ERR "SE_LUN(cmd) is NULL\n");
2008                 return -1;
2009         }
2010
2011         transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD_MAP);
2012         return 0;
2013 }
2014 EXPORT_SYMBOL(transport_generic_handle_cdb_map);
2015
2016 /*      transport_generic_handle_data():
2017  *
2018  *
2019  */
2020 int transport_generic_handle_data(
2021         struct se_cmd *cmd)
2022 {
2023         /*
2024          * For the software fabric case, then we assume the nexus is being
2025          * failed/shutdown when signals are pending from the kthread context
2026          * caller, so we return a failure.  For the HW target mode case running
2027          * in interrupt code, the signal_pending() check is skipped.
2028          */
2029         if (!in_interrupt() && signal_pending(current))
2030                 return -1;
2031         /*
2032          * If the received CDB has aleady been ABORTED by the generic
2033          * target engine, we now call transport_check_aborted_status()
2034          * to queue any delated TASK_ABORTED status for the received CDB to the
2035          * fabric module as we are expecting no futher incoming DATA OUT
2036          * sequences at this point.
2037          */
2038         if (transport_check_aborted_status(cmd, 1) != 0)
2039                 return 0;
2040
2041         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_WRITE);
2042         return 0;
2043 }
2044 EXPORT_SYMBOL(transport_generic_handle_data);
2045
2046 /*      transport_generic_handle_tmr():
2047  *
2048  *
2049  */
2050 int transport_generic_handle_tmr(
2051         struct se_cmd *cmd)
2052 {
2053         /*
2054          * This is needed for early exceptions.
2055          */
2056         cmd->transport_wait_for_tasks = &transport_generic_wait_for_tasks;
2057         transport_device_setup_cmd(cmd);
2058
2059         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_TMR);
2060         return 0;
2061 }
2062 EXPORT_SYMBOL(transport_generic_handle_tmr);
2063
2064 void transport_generic_free_cmd_intr(
2065         struct se_cmd *cmd)
2066 {
2067         transport_add_cmd_to_queue(cmd, TRANSPORT_FREE_CMD_INTR);
2068 }
2069 EXPORT_SYMBOL(transport_generic_free_cmd_intr);
2070
2071 static int transport_stop_tasks_for_cmd(struct se_cmd *cmd)
2072 {
2073         struct se_task *task, *task_tmp;
2074         unsigned long flags;
2075         int ret = 0;
2076
2077         DEBUG_TS("ITT[0x%08x] - Stopping tasks\n",
2078                 CMD_TFO(cmd)->get_task_tag(cmd));
2079
2080         /*
2081          * No tasks remain in the execution queue
2082          */
2083         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2084         list_for_each_entry_safe(task, task_tmp,
2085                                 &T_TASK(cmd)->t_task_list, t_list) {
2086                 DEBUG_TS("task_no[%d] - Processing task %p\n",
2087                                 task->task_no, task);
2088                 /*
2089                  * If the struct se_task has not been sent and is not active,
2090                  * remove the struct se_task from the execution queue.
2091                  */
2092                 if (!atomic_read(&task->task_sent) &&
2093                     !atomic_read(&task->task_active)) {
2094                         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
2095                                         flags);
2096                         transport_remove_task_from_execute_queue(task,
2097                                         task->se_dev);
2098
2099                         DEBUG_TS("task_no[%d] - Removed from execute queue\n",
2100                                 task->task_no);
2101                         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2102                         continue;
2103                 }
2104
2105                 /*
2106                  * If the struct se_task is active, sleep until it is returned
2107                  * from the plugin.
2108                  */
2109                 if (atomic_read(&task->task_active)) {
2110                         atomic_set(&task->task_stop, 1);
2111                         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
2112                                         flags);
2113
2114                         DEBUG_TS("task_no[%d] - Waiting to complete\n",
2115                                 task->task_no);
2116                         wait_for_completion(&task->task_stop_comp);
2117                         DEBUG_TS("task_no[%d] - Stopped successfully\n",
2118                                 task->task_no);
2119
2120                         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2121                         atomic_dec(&T_TASK(cmd)->t_task_cdbs_left);
2122
2123                         atomic_set(&task->task_active, 0);
2124                         atomic_set(&task->task_stop, 0);
2125                 } else {
2126                         DEBUG_TS("task_no[%d] - Did nothing\n", task->task_no);
2127                         ret++;
2128                 }
2129
2130                 __transport_stop_task_timer(task, &flags);
2131         }
2132         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2133
2134         return ret;
2135 }
2136
2137 static void transport_failure_reset_queue_depth(struct se_device *dev)
2138 {
2139         unsigned long flags;
2140
2141         spin_lock_irqsave(&SE_HBA(dev)->hba_queue_lock, flags);;
2142         atomic_inc(&dev->depth_left);
2143         atomic_inc(&SE_HBA(dev)->left_queue_depth);
2144         spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
2145 }
2146
2147 /*
2148  * Handle SAM-esque emulation for generic transport request failures.
2149  */
2150 static void transport_generic_request_failure(
2151         struct se_cmd *cmd,
2152         struct se_device *dev,
2153         int complete,
2154         int sc)
2155 {
2156         DEBUG_GRF("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
2157                 " CDB: 0x%02x\n", cmd, CMD_TFO(cmd)->get_task_tag(cmd),
2158                 T_TASK(cmd)->t_task_cdb[0]);
2159         DEBUG_GRF("-----[ i_state: %d t_state/def_t_state:"
2160                 " %d/%d transport_error_status: %d\n",
2161                 CMD_TFO(cmd)->get_cmd_state(cmd),
2162                 cmd->t_state, cmd->deferred_t_state,
2163                 cmd->transport_error_status);
2164         DEBUG_GRF("-----[ t_task_cdbs: %d t_task_cdbs_left: %d"
2165                 " t_task_cdbs_sent: %d t_task_cdbs_ex_left: %d --"
2166                 " t_transport_active: %d t_transport_stop: %d"
2167                 " t_transport_sent: %d\n", T_TASK(cmd)->t_task_cdbs,
2168                 atomic_read(&T_TASK(cmd)->t_task_cdbs_left),
2169                 atomic_read(&T_TASK(cmd)->t_task_cdbs_sent),
2170                 atomic_read(&T_TASK(cmd)->t_task_cdbs_ex_left),
2171                 atomic_read(&T_TASK(cmd)->t_transport_active),
2172                 atomic_read(&T_TASK(cmd)->t_transport_stop),
2173                 atomic_read(&T_TASK(cmd)->t_transport_sent));
2174
2175         transport_stop_all_task_timers(cmd);
2176
2177         if (dev)
2178                 transport_failure_reset_queue_depth(dev);
2179         /*
2180          * For SAM Task Attribute emulation for failed struct se_cmd
2181          */
2182         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
2183                 transport_complete_task_attr(cmd);
2184
2185         if (complete) {
2186                 transport_direct_request_timeout(cmd);
2187                 cmd->transport_error_status = PYX_TRANSPORT_LU_COMM_FAILURE;
2188         }
2189
2190         switch (cmd->transport_error_status) {
2191         case PYX_TRANSPORT_UNKNOWN_SAM_OPCODE:
2192                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
2193                 break;
2194         case PYX_TRANSPORT_REQ_TOO_MANY_SECTORS:
2195                 cmd->scsi_sense_reason = TCM_SECTOR_COUNT_TOO_MANY;
2196                 break;
2197         case PYX_TRANSPORT_INVALID_CDB_FIELD:
2198                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
2199                 break;
2200         case PYX_TRANSPORT_INVALID_PARAMETER_LIST:
2201                 cmd->scsi_sense_reason = TCM_INVALID_PARAMETER_LIST;
2202                 break;
2203         case PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES:
2204                 if (!sc)
2205                         transport_new_cmd_failure(cmd);
2206                 /*
2207                  * Currently for PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES,
2208                  * we force this session to fall back to session
2209                  * recovery.
2210                  */
2211                 CMD_TFO(cmd)->fall_back_to_erl0(cmd->se_sess);
2212                 CMD_TFO(cmd)->stop_session(cmd->se_sess, 0, 0);
2213
2214                 goto check_stop;
2215         case PYX_TRANSPORT_LU_COMM_FAILURE:
2216         case PYX_TRANSPORT_ILLEGAL_REQUEST:
2217                 cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2218                 break;
2219         case PYX_TRANSPORT_UNKNOWN_MODE_PAGE:
2220                 cmd->scsi_sense_reason = TCM_UNKNOWN_MODE_PAGE;
2221                 break;
2222         case PYX_TRANSPORT_WRITE_PROTECTED:
2223                 cmd->scsi_sense_reason = TCM_WRITE_PROTECTED;
2224                 break;
2225         case PYX_TRANSPORT_RESERVATION_CONFLICT:
2226                 /*
2227                  * No SENSE Data payload for this case, set SCSI Status
2228                  * and queue the response to $FABRIC_MOD.
2229                  *
2230                  * Uses linux/include/scsi/scsi.h SAM status codes defs
2231                  */
2232                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2233                 /*
2234                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
2235                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
2236                  * CONFLICT STATUS.
2237                  *
2238                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
2239                  */
2240                 if (SE_SESS(cmd) &&
2241                     DEV_ATTRIB(cmd->se_dev)->emulate_ua_intlck_ctrl == 2)
2242                         core_scsi3_ua_allocate(SE_SESS(cmd)->se_node_acl,
2243                                 cmd->orig_fe_lun, 0x2C,
2244                                 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
2245
2246                 CMD_TFO(cmd)->queue_status(cmd);
2247                 goto check_stop;
2248         case PYX_TRANSPORT_USE_SENSE_REASON:
2249                 /*
2250                  * struct se_cmd->scsi_sense_reason already set
2251                  */
2252                 break;
2253         default:
2254                 printk(KERN_ERR "Unknown transport error for CDB 0x%02x: %d\n",
2255                         T_TASK(cmd)->t_task_cdb[0],
2256                         cmd->transport_error_status);
2257                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
2258                 break;
2259         }
2260
2261         if (!sc)
2262                 transport_new_cmd_failure(cmd);
2263         else
2264                 transport_send_check_condition_and_sense(cmd,
2265                         cmd->scsi_sense_reason, 0);
2266 check_stop:
2267         transport_lun_remove_cmd(cmd);
2268         if (!(transport_cmd_check_stop_to_fabric(cmd)))
2269                 ;
2270 }
2271
2272 static void transport_direct_request_timeout(struct se_cmd *cmd)
2273 {
2274         unsigned long flags;
2275
2276         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2277         if (!(atomic_read(&T_TASK(cmd)->t_transport_timeout))) {
2278                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2279                 return;
2280         }
2281         if (atomic_read(&T_TASK(cmd)->t_task_cdbs_timeout_left)) {
2282                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2283                 return;
2284         }
2285
2286         atomic_sub(atomic_read(&T_TASK(cmd)->t_transport_timeout),
2287                    &T_TASK(cmd)->t_se_count);
2288         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2289 }
2290
2291 static void transport_generic_request_timeout(struct se_cmd *cmd)
2292 {
2293         unsigned long flags;
2294
2295         /*
2296          * Reset T_TASK(cmd)->t_se_count to allow transport_generic_remove()
2297          * to allow last call to free memory resources.
2298          */
2299         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2300         if (atomic_read(&T_TASK(cmd)->t_transport_timeout) > 1) {
2301                 int tmp = (atomic_read(&T_TASK(cmd)->t_transport_timeout) - 1);
2302
2303                 atomic_sub(tmp, &T_TASK(cmd)->t_se_count);
2304         }
2305         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2306
2307         transport_generic_remove(cmd, 0, 0);
2308 }
2309
2310 static int
2311 transport_generic_allocate_buf(struct se_cmd *cmd, u32 data_length)
2312 {
2313         unsigned char *buf;
2314
2315         buf = kzalloc(data_length, GFP_KERNEL);
2316         if (!(buf)) {
2317                 printk(KERN_ERR "Unable to allocate memory for buffer\n");
2318                 return -1;
2319         }
2320
2321         T_TASK(cmd)->t_tasks_se_num = 0;
2322         T_TASK(cmd)->t_task_buf = buf;
2323
2324         return 0;
2325 }
2326
2327 static inline u32 transport_lba_21(unsigned char *cdb)
2328 {
2329         return ((cdb[1] & 0x1f) << 16) | (cdb[2] << 8) | cdb[3];
2330 }
2331
2332 static inline u32 transport_lba_32(unsigned char *cdb)
2333 {
2334         return (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
2335 }
2336
2337 static inline unsigned long long transport_lba_64(unsigned char *cdb)
2338 {
2339         unsigned int __v1, __v2;
2340
2341         __v1 = (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
2342         __v2 = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
2343
2344         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
2345 }
2346
2347 /*
2348  * For VARIABLE_LENGTH_CDB w/ 32 byte extended CDBs
2349  */
2350 static inline unsigned long long transport_lba_64_ext(unsigned char *cdb)
2351 {
2352         unsigned int __v1, __v2;
2353
2354         __v1 = (cdb[12] << 24) | (cdb[13] << 16) | (cdb[14] << 8) | cdb[15];
2355         __v2 = (cdb[16] << 24) | (cdb[17] << 16) | (cdb[18] << 8) | cdb[19];
2356
2357         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
2358 }
2359
2360 static void transport_set_supported_SAM_opcode(struct se_cmd *se_cmd)
2361 {
2362         unsigned long flags;
2363
2364         spin_lock_irqsave(&T_TASK(se_cmd)->t_state_lock, flags);
2365         se_cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
2366         spin_unlock_irqrestore(&T_TASK(se_cmd)->t_state_lock, flags);
2367 }
2368
2369 /*
2370  * Called from interrupt context.
2371  */
2372 static void transport_task_timeout_handler(unsigned long data)
2373 {
2374         struct se_task *task = (struct se_task *)data;
2375         struct se_cmd *cmd = TASK_CMD(task);
2376         unsigned long flags;
2377
2378         DEBUG_TT("transport task timeout fired! task: %p cmd: %p\n", task, cmd);
2379
2380         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2381         if (task->task_flags & TF_STOP) {
2382                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2383                 return;
2384         }
2385         task->task_flags &= ~TF_RUNNING;
2386
2387         /*
2388          * Determine if transport_complete_task() has already been called.
2389          */
2390         if (!(atomic_read(&task->task_active))) {
2391                 DEBUG_TT("transport task: %p cmd: %p timeout task_active"
2392                                 " == 0\n", task, cmd);
2393                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2394                 return;
2395         }
2396
2397         atomic_inc(&T_TASK(cmd)->t_se_count);
2398         atomic_inc(&T_TASK(cmd)->t_transport_timeout);
2399         T_TASK(cmd)->t_tasks_failed = 1;
2400
2401         atomic_set(&task->task_timeout, 1);
2402         task->task_error_status = PYX_TRANSPORT_TASK_TIMEOUT;
2403         task->task_scsi_status = 1;
2404
2405         if (atomic_read(&task->task_stop)) {
2406                 DEBUG_TT("transport task: %p cmd: %p timeout task_stop"
2407                                 " == 1\n", task, cmd);
2408                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2409                 complete(&task->task_stop_comp);
2410                 return;
2411         }
2412
2413         if (!(atomic_dec_and_test(&T_TASK(cmd)->t_task_cdbs_left))) {
2414                 DEBUG_TT("transport task: %p cmd: %p timeout non zero"
2415                                 " t_task_cdbs_left\n", task, cmd);
2416                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2417                 return;
2418         }
2419         DEBUG_TT("transport task: %p cmd: %p timeout ZERO t_task_cdbs_left\n",
2420                         task, cmd);
2421
2422         cmd->t_state = TRANSPORT_COMPLETE_FAILURE;
2423         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2424
2425         transport_add_cmd_to_queue(cmd, TRANSPORT_COMPLETE_FAILURE);
2426 }
2427
2428 /*
2429  * Called with T_TASK(cmd)->t_state_lock held.
2430  */
2431 static void transport_start_task_timer(struct se_task *task)
2432 {
2433         struct se_device *dev = task->se_dev;
2434         int timeout;
2435
2436         if (task->task_flags & TF_RUNNING)
2437                 return;
2438         /*
2439          * If the task_timeout is disabled, exit now.
2440          */
2441         timeout = DEV_ATTRIB(dev)->task_timeout;
2442         if (!(timeout))
2443                 return;
2444
2445         init_timer(&task->task_timer);
2446         task->task_timer.expires = (get_jiffies_64() + timeout * HZ);
2447         task->task_timer.data = (unsigned long) task;
2448         task->task_timer.function = transport_task_timeout_handler;
2449
2450         task->task_flags |= TF_RUNNING;
2451         add_timer(&task->task_timer);
2452 #if 0
2453         printk(KERN_INFO "Starting task timer for cmd: %p task: %p seconds:"
2454                 " %d\n", task->task_se_cmd, task, timeout);
2455 #endif
2456 }
2457
2458 /*
2459  * Called with spin_lock_irq(&T_TASK(cmd)->t_state_lock) held.
2460  */
2461 void __transport_stop_task_timer(struct se_task *task, unsigned long *flags)
2462 {
2463         struct se_cmd *cmd = TASK_CMD(task);
2464
2465         if (!(task->task_flags & TF_RUNNING))
2466                 return;
2467
2468         task->task_flags |= TF_STOP;
2469         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, *flags);
2470
2471         del_timer_sync(&task->task_timer);
2472
2473         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, *flags);
2474         task->task_flags &= ~TF_RUNNING;
2475         task->task_flags &= ~TF_STOP;
2476 }
2477
2478 static void transport_stop_all_task_timers(struct se_cmd *cmd)
2479 {
2480         struct se_task *task = NULL, *task_tmp;
2481         unsigned long flags;
2482
2483         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2484         list_for_each_entry_safe(task, task_tmp,
2485                                 &T_TASK(cmd)->t_task_list, t_list)
2486                 __transport_stop_task_timer(task, &flags);
2487         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2488 }
2489
2490 static inline int transport_tcq_window_closed(struct se_device *dev)
2491 {
2492         if (dev->dev_tcq_window_closed++ <
2493                         PYX_TRANSPORT_WINDOW_CLOSED_THRESHOLD) {
2494                 msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_SHORT);
2495         } else
2496                 msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_LONG);
2497
2498         wake_up_interruptible(&dev->dev_queue_obj->thread_wq);
2499         return 0;
2500 }
2501
2502 /*
2503  * Called from Fabric Module context from transport_execute_tasks()
2504  *
2505  * The return of this function determins if the tasks from struct se_cmd
2506  * get added to the execution queue in transport_execute_tasks(),
2507  * or are added to the delayed or ordered lists here.
2508  */
2509 static inline int transport_execute_task_attr(struct se_cmd *cmd)
2510 {
2511         if (SE_DEV(cmd)->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
2512                 return 1;
2513         /*
2514          * Check for the existance of HEAD_OF_QUEUE, and if true return 1
2515          * to allow the passed struct se_cmd list of tasks to the front of the list.
2516          */
2517          if (cmd->sam_task_attr == TASK_ATTR_HOQ) {
2518                 atomic_inc(&SE_DEV(cmd)->dev_hoq_count);
2519                 smp_mb__after_atomic_inc();
2520                 DEBUG_STA("Added HEAD_OF_QUEUE for CDB:"
2521                         " 0x%02x, se_ordered_id: %u\n",
2522                         T_TASK(cmd)->t_task_cdb[0],
2523                         cmd->se_ordered_id);
2524                 return 1;
2525         } else if (cmd->sam_task_attr == TASK_ATTR_ORDERED) {
2526                 spin_lock(&SE_DEV(cmd)->ordered_cmd_lock);
2527                 list_add_tail(&cmd->se_ordered_list,
2528                                 &SE_DEV(cmd)->ordered_cmd_list);
2529                 spin_unlock(&SE_DEV(cmd)->ordered_cmd_lock);
2530
2531                 atomic_inc(&SE_DEV(cmd)->dev_ordered_sync);
2532                 smp_mb__after_atomic_inc();
2533
2534                 DEBUG_STA("Added ORDERED for CDB: 0x%02x to ordered"
2535                                 " list, se_ordered_id: %u\n",
2536                                 T_TASK(cmd)->t_task_cdb[0],
2537                                 cmd->se_ordered_id);
2538                 /*
2539                  * Add ORDERED command to tail of execution queue if
2540                  * no other older commands exist that need to be
2541                  * completed first.
2542                  */
2543                 if (!(atomic_read(&SE_DEV(cmd)->simple_cmds)))
2544                         return 1;
2545         } else {
2546                 /*
2547                  * For SIMPLE and UNTAGGED Task Attribute commands
2548                  */
2549                 atomic_inc(&SE_DEV(cmd)->simple_cmds);
2550                 smp_mb__after_atomic_inc();
2551         }
2552         /*
2553          * Otherwise if one or more outstanding ORDERED task attribute exist,
2554          * add the dormant task(s) built for the passed struct se_cmd to the
2555          * execution queue and become in Active state for this struct se_device.
2556          */
2557         if (atomic_read(&SE_DEV(cmd)->dev_ordered_sync) != 0) {
2558                 /*
2559                  * Otherwise, add cmd w/ tasks to delayed cmd queue that
2560                  * will be drained upon competion of HEAD_OF_QUEUE task.
2561                  */
2562                 spin_lock(&SE_DEV(cmd)->delayed_cmd_lock);
2563                 cmd->se_cmd_flags |= SCF_DELAYED_CMD_FROM_SAM_ATTR;
2564                 list_add_tail(&cmd->se_delayed_list,
2565                                 &SE_DEV(cmd)->delayed_cmd_list);
2566                 spin_unlock(&SE_DEV(cmd)->delayed_cmd_lock);
2567
2568                 DEBUG_STA("Added CDB: 0x%02x Task Attr: 0x%02x to"
2569                         " delayed CMD list, se_ordered_id: %u\n",
2570                         T_TASK(cmd)->t_task_cdb[0], cmd->sam_task_attr,
2571                         cmd->se_ordered_id);
2572                 /*
2573                  * Return zero to let transport_execute_tasks() know
2574                  * not to add the delayed tasks to the execution list.
2575                  */
2576                 return 0;
2577         }
2578         /*
2579          * Otherwise, no ORDERED task attributes exist..
2580          */
2581         return 1;
2582 }
2583
2584 /*
2585  * Called from fabric module context in transport_generic_new_cmd() and
2586  * transport_generic_process_write()
2587  */
2588 static int transport_execute_tasks(struct se_cmd *cmd)
2589 {
2590         int add_tasks;
2591
2592         if (!(cmd->se_cmd_flags & SCF_SE_DISABLE_ONLINE_CHECK)) {
2593                 if (se_dev_check_online(cmd->se_orig_obj_ptr) != 0) {
2594                         cmd->transport_error_status =
2595                                 PYX_TRANSPORT_LU_COMM_FAILURE;
2596                         transport_generic_request_failure(cmd, NULL, 0, 1);
2597                         return 0;
2598                 }
2599         }
2600         /*
2601          * Call transport_cmd_check_stop() to see if a fabric exception
2602          * has occured that prevents execution.
2603          */
2604         if (!(transport_cmd_check_stop(cmd, 0, TRANSPORT_PROCESSING))) {
2605                 /*
2606                  * Check for SAM Task Attribute emulation and HEAD_OF_QUEUE
2607                  * attribute for the tasks of the received struct se_cmd CDB
2608                  */
2609                 add_tasks = transport_execute_task_attr(cmd);
2610                 if (add_tasks == 0)
2611                         goto execute_tasks;
2612                 /*
2613                  * This calls transport_add_tasks_from_cmd() to handle
2614                  * HEAD_OF_QUEUE ordering for SAM Task Attribute emulation
2615                  * (if enabled) in __transport_add_task_to_execute_queue() and
2616                  * transport_add_task_check_sam_attr().
2617                  */
2618                 transport_add_tasks_from_cmd(cmd);
2619         }
2620         /*
2621          * Kick the execution queue for the cmd associated struct se_device
2622          * storage object.
2623          */
2624 execute_tasks:
2625         __transport_execute_tasks(SE_DEV(cmd));
2626         return 0;
2627 }
2628
2629 /*
2630  * Called to check struct se_device tcq depth window, and once open pull struct se_task
2631  * from struct se_device->execute_task_list and
2632  *
2633  * Called from transport_processing_thread()
2634  */
2635 static int __transport_execute_tasks(struct se_device *dev)
2636 {
2637         int error;
2638         struct se_cmd *cmd = NULL;
2639         struct se_task *task;
2640         unsigned long flags;
2641
2642         /*
2643          * Check if there is enough room in the device and HBA queue to send
2644          * struct se_transport_task's to the selected transport.
2645          */
2646 check_depth:
2647         spin_lock_irqsave(&SE_HBA(dev)->hba_queue_lock, flags);
2648         if (!(atomic_read(&dev->depth_left)) ||
2649             !(atomic_read(&SE_HBA(dev)->left_queue_depth))) {
2650                 spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
2651                 return transport_tcq_window_closed(dev);
2652         }
2653         dev->dev_tcq_window_closed = 0;
2654
2655         spin_lock(&dev->execute_task_lock);
2656         task = transport_get_task_from_execute_queue(dev);
2657         spin_unlock(&dev->execute_task_lock);
2658
2659         if (!task) {
2660                 spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
2661                 return 0;
2662         }
2663
2664         atomic_dec(&dev->depth_left);
2665         atomic_dec(&SE_HBA(dev)->left_queue_depth);
2666         spin_unlock_irqrestore(&SE_HBA(dev)->hba_queue_lock, flags);
2667
2668         cmd = TASK_CMD(task);
2669
2670         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2671         atomic_set(&task->task_active, 1);
2672         atomic_set(&task->task_sent, 1);
2673         atomic_inc(&T_TASK(cmd)->t_task_cdbs_sent);
2674
2675         if (atomic_read(&T_TASK(cmd)->t_task_cdbs_sent) ==
2676             T_TASK(cmd)->t_task_cdbs)
2677                 atomic_set(&cmd->transport_sent, 1);
2678
2679         transport_start_task_timer(task);
2680         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
2681         /*
2682          * The struct se_cmd->transport_emulate_cdb() function pointer is used
2683          * to grab REPORT_LUNS CDBs before they hit the
2684          * struct se_subsystem_api->do_task() caller below.
2685          */
2686         if (cmd->transport_emulate_cdb) {
2687                 error = cmd->transport_emulate_cdb(cmd);
2688                 if (error != 0) {
2689                         cmd->transport_error_status = error;
2690                         atomic_set(&task->task_active, 0);
2691                         atomic_set(&cmd->transport_sent, 0);
2692                         transport_stop_tasks_for_cmd(cmd);
2693                         transport_generic_request_failure(cmd, dev, 0, 1);
2694                         goto check_depth;
2695                 }
2696                 /*
2697                  * Handle the successful completion for transport_emulate_cdb()
2698                  * for synchronous operation, following SCF_EMULATE_CDB_ASYNC
2699                  * Otherwise the caller is expected to complete the task with
2700                  * proper status.
2701                  */
2702                 if (!(cmd->se_cmd_flags & SCF_EMULATE_CDB_ASYNC)) {
2703                         cmd->scsi_status = SAM_STAT_GOOD;
2704                         task->task_scsi_status = GOOD;
2705                         transport_complete_task(task, 1);
2706                 }
2707         } else {
2708                 /*
2709                  * Currently for all virtual TCM plugins including IBLOCK, FILEIO and
2710                  * RAMDISK we use the internal transport_emulate_control_cdb() logic
2711                  * with struct se_subsystem_api callers for the primary SPC-3 TYPE_DISK
2712                  * LUN emulation code.
2713                  *
2714                  * For TCM/pSCSI and all other SCF_SCSI_DATA_SG_IO_CDB I/O tasks we
2715                  * call ->do_task() directly and let the underlying TCM subsystem plugin
2716                  * code handle the CDB emulation.
2717                  */
2718                 if ((TRANSPORT(dev)->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) &&
2719                     (!(TASK_CMD(task)->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB)))
2720                         error = transport_emulate_control_cdb(task);
2721                 else
2722                         error = TRANSPORT(dev)->do_task(task);
2723
2724                 if (error != 0) {
2725                         cmd->transport_error_status = error;
2726                         atomic_set(&task->task_active, 0);
2727                         atomic_set(&cmd->transport_sent, 0);
2728                         transport_stop_tasks_for_cmd(cmd);
2729                         transport_generic_request_failure(cmd, dev, 0, 1);
2730                 }
2731         }
2732
2733         goto check_depth;
2734
2735         return 0;
2736 }
2737
2738 void transport_new_cmd_failure(struct se_cmd *se_cmd)
2739 {
2740         unsigned long flags;
2741         /*
2742          * Any unsolicited data will get dumped for failed command inside of
2743          * the fabric plugin
2744          */
2745         spin_lock_irqsave(&T_TASK(se_cmd)->t_state_lock, flags);
2746         se_cmd->se_cmd_flags |= SCF_SE_CMD_FAILED;
2747         se_cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2748         spin_unlock_irqrestore(&T_TASK(se_cmd)->t_state_lock, flags);
2749
2750         CMD_TFO(se_cmd)->new_cmd_failure(se_cmd);
2751 }
2752
2753 static void transport_nop_wait_for_tasks(struct se_cmd *, int, int);
2754
2755 static inline u32 transport_get_sectors_6(
2756         unsigned char *cdb,
2757         struct se_cmd *cmd,
2758         int *ret)
2759 {
2760         struct se_device *dev = SE_LUN(cmd)->lun_se_dev;
2761
2762         /*
2763          * Assume TYPE_DISK for non struct se_device objects.
2764          * Use 8-bit sector value.
2765          */
2766         if (!dev)
2767                 goto type_disk;
2768
2769         /*
2770          * Use 24-bit allocation length for TYPE_TAPE.
2771          */
2772         if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE)
2773                 return (u32)(cdb[2] << 16) + (cdb[3] << 8) + cdb[4];
2774
2775         /*
2776          * Everything else assume TYPE_DISK Sector CDB location.
2777          * Use 8-bit sector value.
2778          */
2779 type_disk:
2780         return (u32)cdb[4];
2781 }
2782
2783 static inline u32 transport_get_sectors_10(
2784         unsigned char *cdb,
2785         struct se_cmd *cmd,
2786         int *ret)
2787 {
2788         struct se_device *dev = SE_LUN(cmd)->lun_se_dev;
2789
2790         /*
2791          * Assume TYPE_DISK for non struct se_device objects.
2792          * Use 16-bit sector value.
2793          */
2794         if (!dev)
2795                 goto type_disk;
2796
2797         /*
2798          * XXX_10 is not defined in SSC, throw an exception
2799          */
2800         if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE) {
2801                 *ret = -1;
2802                 return 0;
2803         }
2804
2805         /*
2806          * Everything else assume TYPE_DISK Sector CDB location.
2807          * Use 16-bit sector value.
2808          */
2809 type_disk:
2810         return (u32)(cdb[7] << 8) + cdb[8];
2811 }
2812
2813 static inline u32 transport_get_sectors_12(
2814         unsigned char *cdb,
2815         struct se_cmd *cmd,
2816         int *ret)
2817 {
2818         struct se_device *dev = SE_LUN(cmd)->lun_se_dev;
2819
2820         /*
2821          * Assume TYPE_DISK for non struct se_device objects.
2822          * Use 32-bit sector value.
2823          */
2824         if (!dev)
2825                 goto type_disk;
2826
2827         /*
2828          * XXX_12 is not defined in SSC, throw an exception
2829          */
2830         if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE) {
2831                 *ret = -1;
2832                 return 0;
2833         }
2834
2835         /*
2836          * Everything else assume TYPE_DISK Sector CDB location.
2837          * Use 32-bit sector value.
2838          */
2839 type_disk:
2840         return (u32)(cdb[6] << 24) + (cdb[7] << 16) + (cdb[8] << 8) + cdb[9];
2841 }
2842
2843 static inline u32 transport_get_sectors_16(
2844         unsigned char *cdb,
2845         struct se_cmd *cmd,
2846         int *ret)
2847 {
2848         struct se_device *dev = SE_LUN(cmd)->lun_se_dev;
2849
2850         /*
2851          * Assume TYPE_DISK for non struct se_device objects.
2852          * Use 32-bit sector value.
2853          */
2854         if (!dev)
2855                 goto type_disk;
2856
2857         /*
2858          * Use 24-bit allocation length for TYPE_TAPE.
2859          */
2860         if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE)
2861                 return (u32)(cdb[12] << 16) + (cdb[13] << 8) + cdb[14];
2862
2863 type_disk:
2864         return (u32)(cdb[10] << 24) + (cdb[11] << 16) +
2865                     (cdb[12] << 8) + cdb[13];
2866 }
2867
2868 /*
2869  * Used for VARIABLE_LENGTH_CDB WRITE_32 and READ_32 variants
2870  */
2871 static inline u32 transport_get_sectors_32(
2872         unsigned char *cdb,
2873         struct se_cmd *cmd,
2874         int *ret)
2875 {
2876         /*
2877          * Assume TYPE_DISK for non struct se_device objects.
2878          * Use 32-bit sector value.
2879          */
2880         return (u32)(cdb[28] << 24) + (cdb[29] << 16) +
2881                     (cdb[30] << 8) + cdb[31];
2882
2883 }
2884
2885 static inline u32 transport_get_size(
2886         u32 sectors,
2887         unsigned char *cdb,
2888         struct se_cmd *cmd)
2889 {
2890         struct se_device *dev = SE_DEV(cmd);
2891
2892         if (TRANSPORT(dev)->get_device_type(dev) == TYPE_TAPE) {
2893                 if (cdb[1] & 1) { /* sectors */
2894                         return DEV_ATTRIB(dev)->block_size * sectors;
2895                 } else /* bytes */
2896                         return sectors;
2897         }
2898 #if 0
2899         printk(KERN_INFO "Returning block_size: %u, sectors: %u == %u for"
2900                         " %s object\n", DEV_ATTRIB(dev)->block_size, sectors,
2901                         DEV_ATTRIB(dev)->block_size * sectors,
2902                         TRANSPORT(dev)->name);
2903 #endif
2904         return DEV_ATTRIB(dev)->block_size * sectors;
2905 }
2906
2907 unsigned char transport_asciihex_to_binaryhex(unsigned char val[2])
2908 {
2909         unsigned char result = 0;
2910         /*
2911          * MSB
2912          */
2913         if ((val[0] >= 'a') && (val[0] <= 'f'))
2914                 result = ((val[0] - 'a' + 10) & 0xf) << 4;
2915         else
2916                 if ((val[0] >= 'A') && (val[0] <= 'F'))
2917                         result = ((val[0] - 'A' + 10) & 0xf) << 4;
2918                 else /* digit */
2919                         result = ((val[0] - '0') & 0xf) << 4;
2920         /*
2921          * LSB
2922          */
2923         if ((val[1] >= 'a') && (val[1] <= 'f'))
2924                 result |= ((val[1] - 'a' + 10) & 0xf);
2925         else
2926                 if ((val[1] >= 'A') && (val[1] <= 'F'))
2927                         result |= ((val[1] - 'A' + 10) & 0xf);
2928                 else /* digit */
2929                         result |= ((val[1] - '0') & 0xf);
2930
2931         return result;
2932 }
2933 EXPORT_SYMBOL(transport_asciihex_to_binaryhex);
2934
2935 static void transport_xor_callback(struct se_cmd *cmd)
2936 {
2937         unsigned char *buf, *addr;
2938         struct se_mem *se_mem;
2939         unsigned int offset;
2940         int i;
2941         /*
2942          * From sbc3r22.pdf section 5.48 XDWRITEREAD (10) command
2943          *
2944          * 1) read the specified logical block(s);
2945          * 2) transfer logical blocks from the data-out buffer;
2946          * 3) XOR the logical blocks transferred from the data-out buffer with
2947          *    the logical blocks read, storing the resulting XOR data in a buffer;
2948          * 4) if the DISABLE WRITE bit is set to zero, then write the logical
2949          *    blocks transferred from the data-out buffer; and
2950          * 5) transfer the resulting XOR data to the data-in buffer.
2951          */
2952         buf = kmalloc(cmd->data_length, GFP_KERNEL);
2953         if (!(buf)) {
2954                 printk(KERN_ERR "Unable to allocate xor_callback buf\n");
2955                 return;
2956         }
2957         /*
2958          * Copy the scatterlist WRITE buffer located at T_TASK(cmd)->t_mem_list
2959          * into the locally allocated *buf
2960          */
2961         transport_memcpy_se_mem_read_contig(cmd, buf, T_TASK(cmd)->t_mem_list);
2962         /*
2963          * Now perform the XOR against the BIDI read memory located at
2964          * T_TASK(cmd)->t_mem_bidi_list
2965          */
2966
2967         offset = 0;
2968         list_for_each_entry(se_mem, T_TASK(cmd)->t_mem_bidi_list, se_list) {
2969                 addr = (unsigned char *)kmap_atomic(se_mem->se_page, KM_USER0);
2970                 if (!(addr))
2971                         goto out;
2972
2973                 for (i = 0; i < se_mem->se_len; i++)
2974                         *(addr + se_mem->se_off + i) ^= *(buf + offset + i);
2975
2976                 offset += se_mem->se_len;
2977                 kunmap_atomic(addr, KM_USER0);
2978         }
2979 out:
2980         kfree(buf);
2981 }
2982
2983 /*
2984  * Used to obtain Sense Data from underlying Linux/SCSI struct scsi_cmnd
2985  */
2986 static int transport_get_sense_data(struct se_cmd *cmd)
2987 {
2988         unsigned char *buffer = cmd->sense_buffer, *sense_buffer = NULL;
2989         struct se_device *dev;
2990         struct se_task *task = NULL, *task_tmp;
2991         unsigned long flags;
2992         u32 offset = 0;
2993
2994         if (!SE_LUN(cmd)) {
2995                 printk(KERN_ERR "SE_LUN(cmd) is NULL\n");
2996                 return -1;
2997         }
2998         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
2999         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3000                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
3001                 return 0;
3002         }
3003
3004         list_for_each_entry_safe(task, task_tmp,
3005                                 &T_TASK(cmd)->t_task_list, t_list) {
3006
3007                 if (!task->task_sense)
3008                         continue;
3009
3010                 dev = task->se_dev;
3011                 if (!(dev))
3012                         continue;
3013
3014                 if (!TRANSPORT(dev)->get_sense_buffer) {
3015                         printk(KERN_ERR "TRANSPORT(dev)->get_sense_buffer"
3016                                         " is NULL\n");
3017                         continue;
3018                 }
3019
3020                 sense_buffer = TRANSPORT(dev)->get_sense_buffer(task);
3021                 if (!(sense_buffer)) {
3022                         printk(KERN_ERR "ITT[0x%08x]_TASK[%d]: Unable to locate"
3023                                 " sense buffer for task with sense\n",
3024                                 CMD_TFO(cmd)->get_task_tag(cmd), task->task_no);
3025                         continue;
3026                 }
3027                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
3028
3029                 offset = CMD_TFO(cmd)->set_fabric_sense_len(cmd,
3030                                 TRANSPORT_SENSE_BUFFER);
3031
3032                 memcpy((void *)&buffer[offset], (void *)sense_buffer,
3033                                 TRANSPORT_SENSE_BUFFER);
3034                 cmd->scsi_status = task->task_scsi_status;
3035                 /* Automatically padded */
3036                 cmd->scsi_sense_length =
3037                                 (TRANSPORT_SENSE_BUFFER + offset);
3038
3039                 printk(KERN_INFO "HBA_[%u]_PLUG[%s]: Set SAM STATUS: 0x%02x"
3040                                 " and sense\n",
3041                         dev->se_hba->hba_id, TRANSPORT(dev)->name,
3042                                 cmd->scsi_status);
3043                 return 0;
3044         }
3045         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
3046
3047         return -1;
3048 }
3049
3050 static int transport_allocate_resources(struct se_cmd *cmd)
3051 {
3052         u32 length = cmd->data_length;
3053
3054         if ((cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) ||
3055             (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB))
3056                 return transport_generic_get_mem(cmd, length, PAGE_SIZE);
3057         else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB)
3058                 return transport_generic_allocate_buf(cmd, length);
3059         else
3060                 return 0;
3061 }
3062
3063 static int
3064 transport_handle_reservation_conflict(struct se_cmd *cmd)
3065 {
3066         cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
3067         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3068         cmd->se_cmd_flags |= SCF_SCSI_RESERVATION_CONFLICT;
3069         cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
3070         /*
3071          * For UA Interlock Code 11b, a RESERVATION CONFLICT will
3072          * establish a UNIT ATTENTION with PREVIOUS RESERVATION
3073          * CONFLICT STATUS.
3074          *
3075          * See spc4r17, section 7.4.6 Control Mode Page, Table 349
3076          */
3077         if (SE_SESS(cmd) &&
3078             DEV_ATTRIB(cmd->se_dev)->emulate_ua_intlck_ctrl == 2)
3079                 core_scsi3_ua_allocate(SE_SESS(cmd)->se_node_acl,
3080                         cmd->orig_fe_lun, 0x2C,
3081                         ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
3082         return -2;
3083 }
3084
3085 /*      transport_generic_cmd_sequencer():
3086  *
3087  *      Generic Command Sequencer that should work for most DAS transport
3088  *      drivers.
3089  *
3090  *      Called from transport_generic_allocate_tasks() in the $FABRIC_MOD
3091  *      RX Thread.
3092  *
3093  *      FIXME: Need to support other SCSI OPCODES where as well.
3094  */
3095 static int transport_generic_cmd_sequencer(
3096         struct se_cmd *cmd,
3097         unsigned char *cdb)
3098 {
3099         struct se_device *dev = SE_DEV(cmd);
3100         struct se_subsystem_dev *su_dev = dev->se_sub_dev;
3101         int ret = 0, sector_ret = 0, passthrough;
3102         u32 sectors = 0, size = 0, pr_reg_type = 0;
3103         u16 service_action;
3104         u8 alua_ascq = 0;
3105         /*
3106          * Check for an existing UNIT ATTENTION condition
3107          */
3108         if (core_scsi3_ua_check(cmd, cdb) < 0) {
3109                 cmd->transport_wait_for_tasks =
3110                                 &transport_nop_wait_for_tasks;
3111                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3112                 cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
3113                 return -2;
3114         }
3115         /*
3116          * Check status of Asymmetric Logical Unit Assignment port
3117          */
3118         ret = T10_ALUA(su_dev)->alua_state_check(cmd, cdb, &alua_ascq);
3119         if (ret != 0) {
3120                 cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
3121                 /*
3122                  * Set SCSI additional sense code (ASC) to 'LUN Not Accessable';
3123                  * The ALUA additional sense code qualifier (ASCQ) is determined
3124                  * by the ALUA primary or secondary access state..
3125                  */
3126                 if (ret > 0) {
3127 #if 0
3128                         printk(KERN_INFO "[%s]: ALUA TG Port not available,"
3129                                 " SenseKey: NOT_READY, ASC/ASCQ: 0x04/0x%02x\n",
3130                                 CMD_TFO(cmd)->get_fabric_name(), alua_ascq);
3131 #endif
3132                         transport_set_sense_codes(cmd, 0x04, alua_ascq);
3133                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3134                         cmd->scsi_sense_reason = TCM_CHECK_CONDITION_NOT_READY;
3135                         return -2;
3136                 }
3137                 goto out_invalid_cdb_field;
3138         }
3139         /*
3140          * Check status for SPC-3 Persistent Reservations
3141          */
3142         if (T10_PR_OPS(su_dev)->t10_reservation_check(cmd, &pr_reg_type) != 0) {
3143                 if (T10_PR_OPS(su_dev)->t10_seq_non_holder(
3144                                         cmd, cdb, pr_reg_type) != 0)
3145                         return transport_handle_reservation_conflict(cmd);
3146                 /*
3147                  * This means the CDB is allowed for the SCSI Initiator port
3148                  * when said port is *NOT* holding the legacy SPC-2 or
3149                  * SPC-3 Persistent Reservation.
3150                  */
3151         }
3152
3153         switch (cdb[0]) {
3154         case READ_6:
3155                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
3156                 if (sector_ret)
3157                         goto out_unsupported_cdb;
3158                 size = transport_get_size(sectors, cdb, cmd);
3159                 cmd->transport_split_cdb = &split_cdb_XX_6;
3160                 T_TASK(cmd)->t_task_lba = transport_lba_21(cdb);
3161                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3162                 break;
3163         case READ_10:
3164                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3165                 if (sector_ret)
3166                         goto out_unsupported_cdb;
3167                 size = transport_get_size(sectors, cdb, cmd);
3168                 cmd->transport_split_cdb = &split_cdb_XX_10;
3169                 T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
3170                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3171                 break;
3172         case READ_12:
3173                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
3174                 if (sector_ret)
3175                         goto out_unsupported_cdb;
3176                 size = transport_get_size(sectors, cdb, cmd);
3177                 cmd->transport_split_cdb = &split_cdb_XX_12;
3178                 T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
3179                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3180                 break;
3181         case READ_16:
3182                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3183                 if (sector_ret)
3184                         goto out_unsupported_cdb;
3185                 size = transport_get_size(sectors, cdb, cmd);
3186                 cmd->transport_split_cdb = &split_cdb_XX_16;
3187                 T_TASK(cmd)->t_task_lba = transport_lba_64(cdb);
3188                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3189                 break;
3190         case WRITE_6:
3191                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
3192                 if (sector_ret)
3193                         goto out_unsupported_cdb;
3194                 size = transport_get_size(sectors, cdb, cmd);
3195                 cmd->transport_split_cdb = &split_cdb_XX_6;
3196                 T_TASK(cmd)->t_task_lba = transport_lba_21(cdb);
3197                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3198                 break;
3199         case WRITE_10:
3200                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3201                 if (sector_ret)
3202                         goto out_unsupported_cdb;
3203                 size = transport_get_size(sectors, cdb, cmd);
3204                 cmd->transport_split_cdb = &split_cdb_XX_10;
3205                 T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
3206                 T_TASK(cmd)->t_tasks_fua = (cdb[1] & 0x8);
3207                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3208                 break;
3209         case WRITE_12:
3210                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
3211                 if (sector_ret)
3212                         goto out_unsupported_cdb;
3213                 size = transport_get_size(sectors, cdb, cmd);
3214                 cmd->transport_split_cdb = &split_cdb_XX_12;
3215                 T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
3216                 T_TASK(cmd)->t_tasks_fua = (cdb[1] & 0x8);
3217                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3218                 break;
3219         case WRITE_16:
3220                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3221                 if (sector_ret)
3222                         goto out_unsupported_cdb;
3223                 size = transport_get_size(sectors, cdb, cmd);
3224                 cmd->transport_split_cdb = &split_cdb_XX_16;
3225                 T_TASK(cmd)->t_task_lba = transport_lba_64(cdb);
3226                 T_TASK(cmd)->t_tasks_fua = (cdb[1] & 0x8);
3227                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3228                 break;
3229         case XDWRITEREAD_10:
3230                 if ((cmd->data_direction != DMA_TO_DEVICE) ||
3231                     !(T_TASK(cmd)->t_tasks_bidi))
3232                         goto out_invalid_cdb_field;
3233                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3234                 if (sector_ret)
3235                         goto out_unsupported_cdb;
3236                 size = transport_get_size(sectors, cdb, cmd);
3237                 cmd->transport_split_cdb = &split_cdb_XX_10;
3238                 T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
3239                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3240                 passthrough = (TRANSPORT(dev)->transport_type ==
3241                                 TRANSPORT_PLUGIN_PHBA_PDEV);
3242                 /*
3243                  * Skip the remaining assignments for TCM/PSCSI passthrough
3244                  */
3245                 if (passthrough)
3246                         break;
3247                 /*
3248                  * Setup BIDI XOR callback to be run during transport_generic_complete_ok()
3249                  */
3250                 cmd->transport_complete_callback = &transport_xor_callback;
3251                 T_TASK(cmd)->t_tasks_fua = (cdb[1] & 0x8);
3252                 break;
3253         case VARIABLE_LENGTH_CMD:
3254                 service_action = get_unaligned_be16(&cdb[8]);
3255                 /*
3256                  * Determine if this is TCM/PSCSI device and we should disable
3257                  * internal emulation for this CDB.
3258                  */
3259                 passthrough = (TRANSPORT(dev)->transport_type ==
3260                                         TRANSPORT_PLUGIN_PHBA_PDEV);
3261
3262                 switch (service_action) {
3263                 case XDWRITEREAD_32:
3264                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
3265                         if (sector_ret)
3266                                 goto out_unsupported_cdb;
3267                         size = transport_get_size(sectors, cdb, cmd);
3268                         /*
3269                          * Use WRITE_32 and READ_32 opcodes for the emulated
3270                          * XDWRITE_READ_32 logic.
3271                          */
3272                         cmd->transport_split_cdb = &split_cdb_XX_32;
3273                         T_TASK(cmd)->t_task_lba = transport_lba_64_ext(cdb);
3274                         cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3275
3276                         /*
3277                          * Skip the remaining assignments for TCM/PSCSI passthrough
3278                          */
3279                         if (passthrough)
3280                                 break;
3281
3282                         /*
3283                          * Setup BIDI XOR callback to be run during
3284                          * transport_generic_complete_ok()
3285                          */
3286                         cmd->transport_complete_callback = &transport_xor_callback;
3287                         T_TASK(cmd)->t_tasks_fua = (cdb[10] & 0x8);
3288                         break;
3289                 case WRITE_SAME_32:
3290                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
3291                         if (sector_ret)
3292                                 goto out_unsupported_cdb;
3293                         size = transport_get_size(sectors, cdb, cmd);
3294                         T_TASK(cmd)->t_task_lba = get_unaligned_be64(&cdb[12]);
3295                         cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3296
3297                         /*
3298                          * Skip the remaining assignments for TCM/PSCSI passthrough
3299                          */
3300                         if (passthrough)
3301                                 break;
3302
3303                         if ((cdb[10] & 0x04) || (cdb[10] & 0x02)) {
3304                                 printk(KERN_ERR "WRITE_SAME PBDATA and LBDATA"
3305                                         " bits not supported for Block Discard"
3306                                         " Emulation\n");
3307                                 goto out_invalid_cdb_field;
3308                         }
3309                         /*
3310                          * Currently for the emulated case we only accept
3311                          * tpws with the UNMAP=1 bit set.
3312                          */
3313                         if (!(cdb[10] & 0x08)) {
3314                                 printk(KERN_ERR "WRITE_SAME w/o UNMAP bit not"
3315                                         " supported for Block Discard Emulation\n");
3316                                 goto out_invalid_cdb_field;
3317                         }
3318                         break;
3319                 default:
3320                         printk(KERN_ERR "VARIABLE_LENGTH_CMD service action"
3321                                 " 0x%04x not supported\n", service_action);
3322                         goto out_unsupported_cdb;
3323                 }
3324                 break;
3325         case 0xa3:
3326                 if (TRANSPORT(dev)->get_device_type(dev) != TYPE_ROM) {
3327                         /* MAINTENANCE_IN from SCC-2 */
3328                         /*
3329                          * Check for emulated MI_REPORT_TARGET_PGS.
3330                          */
3331                         if (cdb[1] == MI_REPORT_TARGET_PGS) {
3332                                 cmd->transport_emulate_cdb =
3333                                 (T10_ALUA(su_dev)->alua_type ==
3334                                  SPC3_ALUA_EMULATED) ?
3335                                 &core_emulate_report_target_port_groups :
3336                                 NULL;
3337                         }
3338                         size = (cdb[6] << 24) | (cdb[7] << 16) |
3339                                (cdb[8] << 8) | cdb[9];
3340                 } else {
3341                         /* GPCMD_SEND_KEY from multi media commands */
3342                         size = (cdb[8] << 8) + cdb[9];
3343                 }
3344                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3345                 break;
3346         case MODE_SELECT:
3347                 size = cdb[4];
3348                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3349                 break;
3350         case MODE_SELECT_10:
3351                 size = (cdb[7] << 8) + cdb[8];
3352                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3353                 break;
3354         case MODE_SENSE:
3355                 size = cdb[4];
3356                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3357                 break;
3358         case MODE_SENSE_10:
3359         case GPCMD_READ_BUFFER_CAPACITY:
3360         case GPCMD_SEND_OPC:
3361         case LOG_SELECT:
3362         case LOG_SENSE:
3363                 size = (cdb[7] << 8) + cdb[8];
3364                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3365                 break;
3366         case READ_BLOCK_LIMITS:
3367                 size = READ_BLOCK_LEN;
3368                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3369                 break;
3370         case GPCMD_GET_CONFIGURATION:
3371         case GPCMD_READ_FORMAT_CAPACITIES:
3372         case GPCMD_READ_DISC_INFO:
3373         case GPCMD_READ_TRACK_RZONE_INFO:
3374                 size = (cdb[7] << 8) + cdb[8];
3375                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3376                 break;
3377         case PERSISTENT_RESERVE_IN:
3378         case PERSISTENT_RESERVE_OUT:
3379                 cmd->transport_emulate_cdb =
3380                         (T10_RES(su_dev)->res_type ==
3381                          SPC3_PERSISTENT_RESERVATIONS) ?
3382                         &core_scsi3_emulate_pr : NULL;
3383                 size = (cdb[7] << 8) + cdb[8];
3384                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3385                 break;
3386         case GPCMD_MECHANISM_STATUS:
3387         case GPCMD_READ_DVD_STRUCTURE:
3388                 size = (cdb[8] << 8) + cdb[9];
3389                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3390                 break;
3391         case READ_POSITION:
3392                 size = READ_POSITION_LEN;
3393                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3394                 break;
3395         case 0xa4:
3396                 if (TRANSPORT(dev)->get_device_type(dev) != TYPE_ROM) {
3397                         /* MAINTENANCE_OUT from SCC-2
3398                          *
3399                          * Check for emulated MO_SET_TARGET_PGS.
3400                          */
3401                         if (cdb[1] == MO_SET_TARGET_PGS) {
3402                                 cmd->transport_emulate_cdb =
3403                                 (T10_ALUA(su_dev)->alua_type ==
3404                                         SPC3_ALUA_EMULATED) ?
3405                                 &core_emulate_set_target_port_groups :
3406                                 NULL;
3407                         }
3408
3409                         size = (cdb[6] << 24) | (cdb[7] << 16) |
3410                                (cdb[8] << 8) | cdb[9];
3411                 } else  {
3412                         /* GPCMD_REPORT_KEY from multi media commands */
3413                         size = (cdb[8] << 8) + cdb[9];
3414                 }
3415                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3416                 break;
3417         case INQUIRY:
3418                 size = (cdb[3] << 8) + cdb[4];
3419                 /*
3420                  * Do implict HEAD_OF_QUEUE processing for INQUIRY.
3421                  * See spc4r17 section 5.3
3422                  */
3423                 if (SE_DEV(cmd)->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3424                         cmd->sam_task_attr = TASK_ATTR_HOQ;
3425                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3426                 break;
3427         case READ_BUFFER:
3428                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3429                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3430                 break;
3431         case READ_CAPACITY:
3432                 size = READ_CAP_LEN;
3433                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3434                 break;
3435         case READ_MEDIA_SERIAL_NUMBER:
3436         case SECURITY_PROTOCOL_IN:
3437         case SECURITY_PROTOCOL_OUT:
3438                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
3439                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3440                 break;
3441         case SERVICE_ACTION_IN:
3442         case ACCESS_CONTROL_IN:
3443         case ACCESS_CONTROL_OUT:
3444         case EXTENDED_COPY:
3445         case READ_ATTRIBUTE:
3446         case RECEIVE_COPY_RESULTS:
3447         case WRITE_ATTRIBUTE:
3448                 size = (cdb[10] << 24) | (cdb[11] << 16) |
3449                        (cdb[12] << 8) | cdb[13];
3450                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3451                 break;
3452         case RECEIVE_DIAGNOSTIC:
3453         case SEND_DIAGNOSTIC:
3454                 size = (cdb[3] << 8) | cdb[4];
3455                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3456                 break;
3457 /* #warning FIXME: Figure out correct GPCMD_READ_CD blocksize. */
3458 #if 0
3459         case GPCMD_READ_CD:
3460                 sectors = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3461                 size = (2336 * sectors);
3462                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3463                 break;
3464 #endif
3465         case READ_TOC:
3466                 size = cdb[8];
3467                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3468                 break;
3469         case REQUEST_SENSE:
3470                 size = cdb[4];
3471                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3472                 break;
3473         case READ_ELEMENT_STATUS:
3474                 size = 65536 * cdb[7] + 256 * cdb[8] + cdb[9];
3475                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3476                 break;
3477         case WRITE_BUFFER:
3478                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3479                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3480                 break;
3481         case RESERVE:
3482         case RESERVE_10:
3483                 /*
3484                  * The SPC-2 RESERVE does not contain a size in the SCSI CDB.
3485                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
3486                  */
3487                 if (cdb[0] == RESERVE_10)
3488                         size = (cdb[7] << 8) | cdb[8];
3489                 else
3490                         size = cmd->data_length;
3491
3492                 /*
3493                  * Setup the legacy emulated handler for SPC-2 and
3494                  * >= SPC-3 compatible reservation handling (CRH=1)
3495                  * Otherwise, we assume the underlying SCSI logic is
3496                  * is running in SPC_PASSTHROUGH, and wants reservations
3497                  * emulation disabled.
3498                  */
3499                 cmd->transport_emulate_cdb =
3500                                 (T10_RES(su_dev)->res_type !=
3501                                  SPC_PASSTHROUGH) ?
3502                                 &core_scsi2_emulate_crh : NULL;
3503                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3504                 break;
3505         case RELEASE:
3506         case RELEASE_10:
3507                 /*
3508                  * The SPC-2 RELEASE does not contain a size in the SCSI CDB.
3509                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
3510                 */
3511                 if (cdb[0] == RELEASE_10)
3512                         size = (cdb[7] << 8) | cdb[8];
3513                 else
3514                         size = cmd->data_length;
3515
3516                 cmd->transport_emulate_cdb =
3517                                 (T10_RES(su_dev)->res_type !=
3518                                  SPC_PASSTHROUGH) ?
3519                                 &core_scsi2_emulate_crh : NULL;
3520                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3521                 break;
3522         case SYNCHRONIZE_CACHE:
3523         case 0x91: /* SYNCHRONIZE_CACHE_16: */
3524                 /*
3525                  * Extract LBA and range to be flushed for emulated SYNCHRONIZE_CACHE
3526                  */
3527                 if (cdb[0] == SYNCHRONIZE_CACHE) {
3528                         sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3529                         T_TASK(cmd)->t_task_lba = transport_lba_32(cdb);
3530                 } else {
3531                         sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3532                         T_TASK(cmd)->t_task_lba = transport_lba_64(cdb);
3533                 }
3534                 if (sector_ret)
3535                         goto out_unsupported_cdb;
3536
3537                 size = transport_get_size(sectors, cdb, cmd);
3538                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3539
3540                 /*
3541                  * For TCM/pSCSI passthrough, skip cmd->transport_emulate_cdb()
3542                  */
3543                 if (TRANSPORT(dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV)
3544                         break;
3545                 /*
3546                  * Set SCF_EMULATE_CDB_ASYNC to ensure asynchronous operation
3547                  * for SYNCHRONIZE_CACHE* Immed=1 case in __transport_execute_tasks()
3548                  */
3549                 cmd->se_cmd_flags |= SCF_EMULATE_CDB_ASYNC;
3550                 /*
3551                  * Check to ensure that LBA + Range does not exceed past end of
3552                  * device.
3553                  */
3554                 if (transport_get_sectors(cmd) < 0)
3555                         goto out_invalid_cdb_field;
3556                 break;
3557         case UNMAP:
3558                 size = get_unaligned_be16(&cdb[7]);
3559                 passthrough = (TRANSPORT(dev)->transport_type ==
3560                                 TRANSPORT_PLUGIN_PHBA_PDEV);
3561                 /*
3562                  * Determine if the received UNMAP used to for direct passthrough
3563                  * into Linux/SCSI with struct request via TCM/pSCSI or we are
3564                  * signaling the use of internal transport_generic_unmap() emulation
3565                  * for UNMAP -> Linux/BLOCK disbard with TCM/IBLOCK and TCM/FILEIO
3566                  * subsystem plugin backstores.
3567                  */
3568                 if (!(passthrough))
3569                         cmd->se_cmd_flags |= SCF_EMULATE_SYNC_UNMAP;
3570
3571                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3572                 break;
3573         case WRITE_SAME_16:
3574                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3575                 if (sector_ret)
3576                         goto out_unsupported_cdb;
3577                 size = transport_get_size(sectors, cdb, cmd);
3578                 T_TASK(cmd)->t_task_lba = get_unaligned_be16(&cdb[2]);
3579                 passthrough = (TRANSPORT(dev)->transport_type ==
3580                                 TRANSPORT_PLUGIN_PHBA_PDEV);
3581                 /*
3582                  * Determine if the received WRITE_SAME_16 is used to for direct
3583                  * passthrough into Linux/SCSI with struct request via TCM/pSCSI
3584                  * or we are signaling the use of internal WRITE_SAME + UNMAP=1
3585                  * emulation for -> Linux/BLOCK disbard with TCM/IBLOCK and
3586                  * TCM/FILEIO subsystem plugin backstores.
3587                  */
3588                 if (!(passthrough)) {
3589                         if ((cdb[1] & 0x04) || (cdb[1] & 0x02)) {
3590                                 printk(KERN_ERR "WRITE_SAME PBDATA and LBDATA"
3591                                         " bits not supported for Block Discard"
3592                                         " Emulation\n");
3593                                 goto out_invalid_cdb_field;
3594                         }
3595                         /*
3596                          * Currently for the emulated case we only accept
3597                          * tpws with the UNMAP=1 bit set.
3598                          */
3599                         if (!(cdb[1] & 0x08)) {
3600                                 printk(KERN_ERR "WRITE_SAME w/o UNMAP bit not "
3601                                         " supported for Block Discard Emulation\n");
3602                                 goto out_invalid_cdb_field;
3603                         }
3604                 }
3605                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3606                 break;
3607         case ALLOW_MEDIUM_REMOVAL:
3608         case GPCMD_CLOSE_TRACK:
3609         case ERASE:
3610         case INITIALIZE_ELEMENT_STATUS:
3611         case GPCMD_LOAD_UNLOAD:
3612         case REZERO_UNIT:
3613         case SEEK_10:
3614         case GPCMD_SET_SPEED:
3615         case SPACE:
3616         case START_STOP:
3617         case TEST_UNIT_READY:
3618         case VERIFY:
3619         case WRITE_FILEMARKS:
3620         case MOVE_MEDIUM:
3621                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3622                 break;
3623         case REPORT_LUNS:
3624                 cmd->transport_emulate_cdb =
3625                                 &transport_core_report_lun_response;
3626                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
3627                 /*
3628                  * Do implict HEAD_OF_QUEUE processing for REPORT_LUNS
3629                  * See spc4r17 section 5.3
3630                  */
3631                 if (SE_DEV(cmd)->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3632                         cmd->sam_task_attr = TASK_ATTR_HOQ;
3633                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3634                 break;
3635         default:
3636                 printk(KERN_WARNING "TARGET_CORE[%s]: Unsupported SCSI Opcode"
3637                         " 0x%02x, sending CHECK_CONDITION.\n",
3638                         CMD_TFO(cmd)->get_fabric_name(), cdb[0]);
3639                 cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
3640                 goto out_unsupported_cdb;
3641         }
3642
3643         if (size != cmd->data_length) {
3644                 printk(KERN_WARNING "TARGET_CORE[%s]: Expected Transfer Length:"
3645                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
3646                         " 0x%02x\n", CMD_TFO(cmd)->get_fabric_name(),
3647                                 cmd->data_length, size, cdb[0]);
3648
3649                 cmd->cmd_spdtl = size;
3650
3651                 if (cmd->data_direction == DMA_TO_DEVICE) {
3652                         printk(KERN_ERR "Rejecting underflow/overflow"
3653                                         " WRITE data\n");
3654                         goto out_invalid_cdb_field;
3655                 }
3656                 /*
3657                  * Reject READ_* or WRITE_* with overflow/underflow for
3658                  * type SCF_SCSI_DATA_SG_IO_CDB.
3659                  */
3660                 if (!(ret) && (DEV_ATTRIB(dev)->block_size != 512))  {
3661                         printk(KERN_ERR "Failing OVERFLOW/UNDERFLOW for LBA op"
3662                                 " CDB on non 512-byte sector setup subsystem"
3663                                 " plugin: %s\n", TRANSPORT(dev)->name);
3664                         /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
3665                         goto out_invalid_cdb_field;
3666                 }
3667
3668                 if (size > cmd->data_length) {
3669                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
3670                         cmd->residual_count = (size - cmd->data_length);
3671                 } else {
3672                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
3673                         cmd->residual_count = (cmd->data_length - size);
3674                 }
3675                 cmd->data_length = size;
3676         }
3677
3678         transport_set_supported_SAM_opcode(cmd);
3679         return ret;
3680
3681 out_unsupported_cdb:
3682         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3683         cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
3684         return -2;
3685 out_invalid_cdb_field:
3686         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3687         cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
3688         return -2;
3689 }
3690
3691 static inline void transport_release_tasks(struct se_cmd *);
3692
3693 /*
3694  * This function will copy a contiguous *src buffer into a destination
3695  * struct scatterlist array.
3696  */
3697 static void transport_memcpy_write_contig(
3698         struct se_cmd *cmd,
3699         struct scatterlist *sg_d,
3700         unsigned char *src)
3701 {
3702         u32 i = 0, length = 0, total_length = cmd->data_length;
3703         void *dst;
3704
3705         while (total_length) {
3706                 length = sg_d[i].length;
3707
3708                 if (length > total_length)
3709                         length = total_length;
3710
3711                 dst = sg_virt(&sg_d[i]);
3712
3713                 memcpy(dst, src, length);
3714
3715                 if (!(total_length -= length))
3716                         return;
3717
3718                 src += length;
3719                 i++;
3720         }
3721 }
3722
3723 /*
3724  * This function will copy a struct scatterlist array *sg_s into a destination
3725  * contiguous *dst buffer.
3726  */
3727 static void transport_memcpy_read_contig(
3728         struct se_cmd *cmd,
3729         unsigned char *dst,
3730         struct scatterlist *sg_s)
3731 {
3732         u32 i = 0, length = 0, total_length = cmd->data_length;
3733         void *src;
3734
3735         while (total_length) {
3736                 length = sg_s[i].length;
3737
3738                 if (length > total_length)
3739                         length = total_length;
3740
3741                 src = sg_virt(&sg_s[i]);
3742
3743                 memcpy(dst, src, length);
3744
3745                 if (!(total_length -= length))
3746                         return;
3747
3748                 dst += length;
3749                 i++;
3750         }
3751 }
3752
3753 static void transport_memcpy_se_mem_read_contig(
3754         struct se_cmd *cmd,
3755         unsigned char *dst,
3756         struct list_head *se_mem_list)
3757 {
3758         struct se_mem *se_mem;
3759         void *src;
3760         u32 length = 0, total_length = cmd->data_length;
3761
3762         list_for_each_entry(se_mem, se_mem_list, se_list) {
3763                 length = se_mem->se_len;
3764
3765                 if (length > total_length)
3766                         length = total_length;
3767
3768                 src = page_address(se_mem->se_page) + se_mem->se_off;
3769
3770                 memcpy(dst, src, length);
3771
3772                 if (!(total_length -= length))
3773                         return;
3774
3775                 dst += length;
3776         }
3777 }
3778
3779 /*
3780  * Called from transport_generic_complete_ok() and
3781  * transport_generic_request_failure() to determine which dormant/delayed
3782  * and ordered cmds need to have their tasks added to the execution queue.
3783  */
3784 static void transport_complete_task_attr(struct se_cmd *cmd)
3785 {
3786         struct se_device *dev = SE_DEV(cmd);
3787         struct se_cmd *cmd_p, *cmd_tmp;
3788         int new_active_tasks = 0;
3789
3790         if (cmd->sam_task_attr == TASK_ATTR_SIMPLE) {
3791                 atomic_dec(&dev->simple_cmds);
3792                 smp_mb__after_atomic_dec();
3793                 dev->dev_cur_ordered_id++;
3794                 DEBUG_STA("Incremented dev->dev_cur_ordered_id: %u for"
3795                         " SIMPLE: %u\n", dev->dev_cur_ordered_id,
3796                         cmd->se_ordered_id);
3797         } else if (cmd->sam_task_attr == TASK_ATTR_HOQ) {
3798                 atomic_dec(&dev->dev_hoq_count);
3799                 smp_mb__after_atomic_dec();
3800                 dev->dev_cur_ordered_id++;
3801                 DEBUG_STA("Incremented dev_cur_ordered_id: %u for"
3802                         " HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id,
3803                         cmd->se_ordered_id);
3804         } else if (cmd->sam_task_attr == TASK_ATTR_ORDERED) {
3805                 spin_lock(&dev->ordered_cmd_lock);
3806                 list_del(&cmd->se_ordered_list);
3807                 atomic_dec(&dev->dev_ordered_sync);
3808                 smp_mb__after_atomic_dec();
3809                 spin_unlock(&dev->ordered_cmd_lock);
3810
3811                 dev->dev_cur_ordered_id++;
3812                 DEBUG_STA("Incremented dev_cur_ordered_id: %u for ORDERED:"
3813                         " %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id);
3814         }
3815         /*
3816          * Process all commands up to the last received
3817          * ORDERED task attribute which requires another blocking
3818          * boundary
3819          */
3820         spin_lock(&dev->delayed_cmd_lock);
3821         list_for_each_entry_safe(cmd_p, cmd_tmp,
3822                         &dev->delayed_cmd_list, se_delayed_list) {
3823
3824                 list_del(&cmd_p->se_delayed_list);
3825                 spin_unlock(&dev->delayed_cmd_lock);
3826
3827                 DEBUG_STA("Calling add_tasks() for"
3828                         " cmd_p: 0x%02x Task Attr: 0x%02x"
3829                         " Dormant -> Active, se_ordered_id: %u\n",
3830                         T_TASK(cmd_p)->t_task_cdb[0],
3831                         cmd_p->sam_task_attr, cmd_p->se_ordered_id);
3832
3833                 transport_add_tasks_from_cmd(cmd_p);
3834                 new_active_tasks++;
3835
3836                 spin_lock(&dev->delayed_cmd_lock);
3837                 if (cmd_p->sam_task_attr == TASK_ATTR_ORDERED)
3838                         break;
3839         }
3840         spin_unlock(&dev->delayed_cmd_lock);
3841         /*
3842          * If new tasks have become active, wake up the transport thread
3843          * to do the processing of the Active tasks.
3844          */
3845         if (new_active_tasks != 0)
3846                 wake_up_interruptible(&dev->dev_queue_obj->thread_wq);
3847 }
3848
3849 static void transport_generic_complete_ok(struct se_cmd *cmd)
3850 {
3851         int reason = 0;
3852         /*
3853          * Check if we need to move delayed/dormant tasks from cmds on the
3854          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
3855          * Attribute.
3856          */
3857         if (SE_DEV(cmd)->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3858                 transport_complete_task_attr(cmd);
3859         /*
3860          * Check if we need to retrieve a sense buffer from
3861          * the struct se_cmd in question.
3862          */
3863         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
3864                 if (transport_get_sense_data(cmd) < 0)
3865                         reason = TCM_NON_EXISTENT_LUN;
3866
3867                 /*
3868                  * Only set when an struct se_task->task_scsi_status returned
3869                  * a non GOOD status.
3870                  */
3871                 if (cmd->scsi_status) {
3872                         transport_send_check_condition_and_sense(
3873                                         cmd, reason, 1);
3874                         transport_lun_remove_cmd(cmd);
3875                         transport_cmd_check_stop_to_fabric(cmd);
3876                         return;
3877                 }
3878         }
3879         /*
3880          * Check for a callback, used by amoungst other things
3881          * XDWRITE_READ_10 emulation.
3882          */
3883         if (cmd->transport_complete_callback)
3884                 cmd->transport_complete_callback(cmd);
3885
3886         switch (cmd->data_direction) {
3887         case DMA_FROM_DEVICE:
3888                 spin_lock(&cmd->se_lun->lun_sep_lock);
3889                 if (SE_LUN(cmd)->lun_sep) {
3890                         SE_LUN(cmd)->lun_sep->sep_stats.tx_data_octets +=
3891                                         cmd->data_length;
3892                 }
3893                 spin_unlock(&cmd->se_lun->lun_sep_lock);
3894                 /*
3895                  * If enabled by TCM fabirc module pre-registered SGL
3896                  * memory, perform the memcpy() from the TCM internal
3897                  * contigious buffer back to the original SGL.
3898                  */
3899                 if (cmd->se_cmd_flags & SCF_PASSTHROUGH_CONTIG_TO_SG)
3900                         transport_memcpy_write_contig(cmd,
3901                                  T_TASK(cmd)->t_task_pt_sgl,
3902                                  T_TASK(cmd)->t_task_buf);
3903
3904                 CMD_TFO(cmd)->queue_data_in(cmd);
3905                 break;
3906         case DMA_TO_DEVICE:
3907                 spin_lock(&cmd->se_lun->lun_sep_lock);
3908                 if (SE_LUN(cmd)->lun_sep) {
3909                         SE_LUN(cmd)->lun_sep->sep_stats.rx_data_octets +=
3910                                 cmd->data_length;
3911                 }
3912                 spin_unlock(&cmd->se_lun->lun_sep_lock);
3913                 /*
3914                  * Check if we need to send READ payload for BIDI-COMMAND
3915                  */
3916                 if (T_TASK(cmd)->t_mem_bidi_list != NULL) {
3917                         spin_lock(&cmd->se_lun->lun_sep_lock);
3918                         if (SE_LUN(cmd)->lun_sep) {
3919                                 SE_LUN(cmd)->lun_sep->sep_stats.tx_data_octets +=
3920                                         cmd->data_length;
3921                         }
3922                         spin_unlock(&cmd->se_lun->lun_sep_lock);
3923                         CMD_TFO(cmd)->queue_data_in(cmd);
3924                         break;
3925                 }
3926                 /* Fall through for DMA_TO_DEVICE */
3927         case DMA_NONE:
3928                 CMD_TFO(cmd)->queue_status(cmd);
3929                 break;
3930         default:
3931                 break;
3932         }
3933
3934         transport_lun_remove_cmd(cmd);
3935         transport_cmd_check_stop_to_fabric(cmd);
3936 }
3937
3938 static void transport_free_dev_tasks(struct se_cmd *cmd)
3939 {
3940         struct se_task *task, *task_tmp;
3941         unsigned long flags;
3942
3943         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
3944         list_for_each_entry_safe(task, task_tmp,
3945                                 &T_TASK(cmd)->t_task_list, t_list) {
3946                 if (atomic_read(&task->task_active))
3947                         continue;
3948
3949                 kfree(task->task_sg_bidi);
3950                 kfree(task->task_sg);
3951
3952                 list_del(&task->t_list);
3953
3954                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
3955                 if (task->se_dev)
3956                         TRANSPORT(task->se_dev)->free_task(task);
3957                 else
3958                         printk(KERN_ERR "task[%u] - task->se_dev is NULL\n",
3959                                 task->task_no);
3960                 spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
3961         }
3962         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
3963 }
3964
3965 static inline void transport_free_pages(struct se_cmd *cmd)
3966 {
3967         struct se_mem *se_mem, *se_mem_tmp;
3968         int free_page = 1;
3969
3970         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)
3971                 free_page = 0;
3972         if (cmd->se_dev->transport->do_se_mem_map)
3973                 free_page = 0;
3974
3975         if (T_TASK(cmd)->t_task_buf) {
3976                 kfree(T_TASK(cmd)->t_task_buf);
3977                 T_TASK(cmd)->t_task_buf = NULL;
3978                 return;
3979         }
3980
3981         /*
3982          * Caller will handle releasing of struct se_mem.
3983          */
3984         if (cmd->se_cmd_flags & SCF_CMD_PASSTHROUGH_NOALLOC)
3985                 return;
3986
3987         if (!(T_TASK(cmd)->t_tasks_se_num))
3988                 return;
3989
3990         list_for_each_entry_safe(se_mem, se_mem_tmp,
3991                         T_TASK(cmd)->t_mem_list, se_list) {
3992                 /*
3993                  * We only release call __free_page(struct se_mem->se_page) when
3994                  * SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC is NOT in use,
3995                  */
3996                 if (free_page)
3997                         __free_page(se_mem->se_page);
3998
3999                 list_del(&se_mem->se_list);
4000                 kmem_cache_free(se_mem_cache, se_mem);
4001         }
4002
4003         if (T_TASK(cmd)->t_mem_bidi_list && T_TASK(cmd)->t_tasks_se_bidi_num) {
4004                 list_for_each_entry_safe(se_mem, se_mem_tmp,
4005                                 T_TASK(cmd)->t_mem_bidi_list, se_list) {
4006                         /*
4007                          * We only release call __free_page(struct se_mem->se_page) when
4008                          * SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC is NOT in use,
4009                          */
4010                         if (free_page)
4011                                 __free_page(se_mem->se_page);
4012
4013                         list_del(&se_mem->se_list);
4014                         kmem_cache_free(se_mem_cache, se_mem);
4015                 }
4016         }
4017
4018         kfree(T_TASK(cmd)->t_mem_bidi_list);
4019         T_TASK(cmd)->t_mem_bidi_list = NULL;
4020         kfree(T_TASK(cmd)->t_mem_list);
4021         T_TASK(cmd)->t_mem_list = NULL;
4022         T_TASK(cmd)->t_tasks_se_num = 0;
4023 }
4024
4025 static inline void transport_release_tasks(struct se_cmd *cmd)
4026 {
4027         transport_free_dev_tasks(cmd);
4028 }
4029
4030 static inline int transport_dec_and_check(struct se_cmd *cmd)
4031 {
4032         unsigned long flags;
4033
4034         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
4035         if (atomic_read(&T_TASK(cmd)->t_fe_count)) {
4036                 if (!(atomic_dec_and_test(&T_TASK(cmd)->t_fe_count))) {
4037                         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
4038                                         flags);
4039                         return 1;
4040                 }
4041         }
4042
4043         if (atomic_read(&T_TASK(cmd)->t_se_count)) {
4044                 if (!(atomic_dec_and_test(&T_TASK(cmd)->t_se_count))) {
4045                         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
4046                                         flags);
4047                         return 1;
4048                 }
4049         }
4050         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
4051
4052         return 0;
4053 }
4054
4055 static void transport_release_fe_cmd(struct se_cmd *cmd)
4056 {
4057         unsigned long flags;
4058
4059         if (transport_dec_and_check(cmd))
4060                 return;
4061
4062         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
4063         if (!(atomic_read(&T_TASK(cmd)->transport_dev_active))) {
4064                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
4065                 goto free_pages;
4066         }
4067         atomic_set(&T_TASK(cmd)->transport_dev_active, 0);
4068         transport_all_task_dev_remove_state(cmd);
4069         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
4070
4071         transport_release_tasks(cmd);
4072 free_pages:
4073         transport_free_pages(cmd);
4074         transport_free_se_cmd(cmd);
4075         CMD_TFO(cmd)->release_cmd_direct(cmd);
4076 }
4077
4078 static int transport_generic_remove(
4079         struct se_cmd *cmd,
4080         int release_to_pool,
4081         int session_reinstatement)
4082 {
4083         unsigned long flags;
4084
4085         if (!(T_TASK(cmd)))
4086                 goto release_cmd;
4087
4088         if (transport_dec_and_check(cmd)) {
4089                 if (session_reinstatement) {
4090                         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
4091                         transport_all_task_dev_remove_state(cmd);
4092                         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
4093                                         flags);
4094                 }
4095                 return 1;
4096         }
4097
4098         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
4099         if (!(atomic_read(&T_TASK(cmd)->transport_dev_active))) {
4100                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
4101                 goto free_pages;
4102         }
4103         atomic_set(&T_TASK(cmd)->transport_dev_active, 0);
4104         transport_all_task_dev_remove_state(cmd);
4105         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
4106
4107         transport_release_tasks(cmd);
4108 free_pages:
4109         transport_free_pages(cmd);
4110
4111 release_cmd:
4112         if (release_to_pool) {
4113                 transport_release_cmd_to_pool(cmd);
4114         } else {
4115                 transport_free_se_cmd(cmd);
4116                 CMD_TFO(cmd)->release_cmd_direct(cmd);
4117         }
4118
4119         return 0;
4120 }
4121
4122 /*
4123  * transport_generic_map_mem_to_cmd - Perform SGL -> struct se_mem map
4124  * @cmd:  Associated se_cmd descriptor
4125  * @mem:  SGL style memory for TCM WRITE / READ
4126  * @sg_mem_num: Number of SGL elements
4127  * @mem_bidi_in: SGL style memory for TCM BIDI READ
4128  * @sg_mem_bidi_num: Number of BIDI READ SGL elements
4129  *
4130  * Return: nonzero return cmd was rejected for -ENOMEM or inproper usage
4131  * of parameters.
4132  */
4133 int transport_generic_map_mem_to_cmd(
4134         struct se_cmd *cmd,
4135         struct scatterlist *mem,
4136         u32 sg_mem_num,
4137         struct scatterlist *mem_bidi_in,
4138         u32 sg_mem_bidi_num)
4139 {
4140         u32 se_mem_cnt_out = 0;
4141         int ret;
4142
4143         if (!(mem) || !(sg_mem_num))
4144                 return 0;
4145         /*
4146          * Passed *mem will contain a list_head containing preformatted
4147          * struct se_mem elements...
4148          */
4149         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM)) {
4150                 if ((mem_bidi_in) || (sg_mem_bidi_num)) {
4151                         printk(KERN_ERR "SCF_CMD_PASSTHROUGH_NOALLOC not supported"
4152                                 " with BIDI-COMMAND\n");
4153                         return -ENOSYS;
4154                 }
4155
4156                 T_TASK(cmd)->t_mem_list = (struct list_head *)mem;
4157                 T_TASK(cmd)->t_tasks_se_num = sg_mem_num;
4158                 cmd->se_cmd_flags |= SCF_CMD_PASSTHROUGH_NOALLOC;
4159                 return 0;
4160         }
4161         /*
4162          * Otherwise, assume the caller is passing a struct scatterlist
4163          * array from include/linux/scatterlist.h
4164          */
4165         if ((cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) ||
4166             (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB)) {
4167                 /*
4168                  * For CDB using TCM struct se_mem linked list scatterlist memory
4169                  * processed into a TCM struct se_subsystem_dev, we do the mapping
4170                  * from the passed physical memory to struct se_mem->se_page here.
4171                  */
4172                 T_TASK(cmd)->t_mem_list = transport_init_se_mem_list();
4173                 if (!(T_TASK(cmd)->t_mem_list))
4174                         return -ENOMEM;
4175
4176                 ret = transport_map_sg_to_mem(cmd,
4177                         T_TASK(cmd)->t_mem_list, mem, &se_mem_cnt_out);
4178                 if (ret < 0)
4179                         return -ENOMEM;
4180
4181                 T_TASK(cmd)->t_tasks_se_num = se_mem_cnt_out;
4182                 /*
4183                  * Setup BIDI READ list of struct se_mem elements
4184                  */
4185                 if ((mem_bidi_in) && (sg_mem_bidi_num)) {
4186                         T_TASK(cmd)->t_mem_bidi_list = transport_init_se_mem_list();
4187                         if (!(T_TASK(cmd)->t_mem_bidi_list)) {
4188                                 kfree(T_TASK(cmd)->t_mem_list);
4189                                 return -ENOMEM;
4190                         }
4191                         se_mem_cnt_out = 0;
4192
4193                         ret = transport_map_sg_to_mem(cmd,
4194                                 T_TASK(cmd)->t_mem_bidi_list, mem_bidi_in,
4195                                 &se_mem_cnt_out);
4196                         if (ret < 0) {
4197                                 kfree(T_TASK(cmd)->t_mem_list);
4198                                 return -ENOMEM;
4199                         }
4200
4201                         T_TASK(cmd)->t_tasks_se_bidi_num = se_mem_cnt_out;
4202                 }
4203                 cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
4204
4205         } else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB) {
4206                 if (mem_bidi_in || sg_mem_bidi_num) {
4207                         printk(KERN_ERR "BIDI-Commands not supported using "
4208                                 "SCF_SCSI_CONTROL_NONSG_IO_CDB\n");
4209                         return -ENOSYS;
4210                 }
4211                 /*
4212                  * For incoming CDBs using a contiguous buffer internall with TCM,
4213                  * save the passed struct scatterlist memory.  After TCM storage object
4214                  * processing has completed for this struct se_cmd, TCM core will call
4215                  * transport_memcpy_[write,read]_contig() as necessary from
4216                  * transport_generic_complete_ok() and transport_write_pending() in order
4217                  * to copy the TCM buffer to/from the original passed *mem in SGL ->
4218                  * struct scatterlist format.
4219                  */
4220                 cmd->se_cmd_flags |= SCF_PASSTHROUGH_CONTIG_TO_SG;
4221                 T_TASK(cmd)->t_task_pt_sgl = mem;
4222         }
4223
4224         return 0;
4225 }
4226 EXPORT_SYMBOL(transport_generic_map_mem_to_cmd);
4227
4228
4229 static inline long long transport_dev_end_lba(struct se_device *dev)
4230 {
4231         return dev->transport->get_blocks(dev) + 1;
4232 }
4233
4234 static int transport_get_sectors(struct se_cmd *cmd)
4235 {
4236         struct se_device *dev = SE_DEV(cmd);
4237
4238         T_TASK(cmd)->t_tasks_sectors =
4239                 (cmd->data_length / DEV_ATTRIB(dev)->block_size);
4240         if (!(T_TASK(cmd)->t_tasks_sectors))
4241                 T_TASK(cmd)->t_tasks_sectors = 1;
4242
4243         if (TRANSPORT(dev)->get_device_type(dev) != TYPE_DISK)
4244                 return 0;
4245
4246         if ((T_TASK(cmd)->t_task_lba + T_TASK(cmd)->t_tasks_sectors) >
4247              transport_dev_end_lba(dev)) {
4248                 printk(KERN_ERR "LBA: %llu Sectors: %u exceeds"
4249                         " transport_dev_end_lba(): %llu\n",
4250                         T_TASK(cmd)->t_task_lba, T_TASK(cmd)->t_tasks_sectors,
4251                         transport_dev_end_lba(dev));
4252                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
4253                 cmd->scsi_sense_reason = TCM_SECTOR_COUNT_TOO_MANY;
4254                 return PYX_TRANSPORT_REQ_TOO_MANY_SECTORS;
4255         }
4256
4257         return 0;
4258 }
4259
4260 static int transport_new_cmd_obj(struct se_cmd *cmd)
4261 {
4262         struct se_device *dev = SE_DEV(cmd);
4263         u32 task_cdbs = 0, rc;
4264
4265         if (!(cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB)) {
4266                 task_cdbs++;
4267                 T_TASK(cmd)->t_task_cdbs++;
4268         } else {
4269                 int set_counts = 1;
4270
4271                 /*
4272                  * Setup any BIDI READ tasks and memory from
4273                  * T_TASK(cmd)->t_mem_bidi_list so the READ struct se_tasks
4274                  * are queued first for the non pSCSI passthrough case.
4275                  */
4276                 if ((T_TASK(cmd)->t_mem_bidi_list != NULL) &&
4277                     (TRANSPORT(dev)->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV)) {
4278                         rc = transport_generic_get_cdb_count(cmd,
4279                                 T_TASK(cmd)->t_task_lba,
4280                                 T_TASK(cmd)->t_tasks_sectors,
4281                                 DMA_FROM_DEVICE, T_TASK(cmd)->t_mem_bidi_list,
4282                                 set_counts);
4283                         if (!(rc)) {
4284                                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
4285                                 cmd->scsi_sense_reason =
4286                                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
4287                                 return PYX_TRANSPORT_LU_COMM_FAILURE;
4288                         }
4289                         set_counts = 0;
4290                 }
4291                 /*
4292                  * Setup the tasks and memory from T_TASK(cmd)->t_mem_list
4293                  * Note for BIDI transfers this will contain the WRITE payload
4294                  */
4295                 task_cdbs = transport_generic_get_cdb_count(cmd,
4296                                 T_TASK(cmd)->t_task_lba,
4297                                 T_TASK(cmd)->t_tasks_sectors,
4298                                 cmd->data_direction, T_TASK(cmd)->t_mem_list,
4299                                 set_counts);
4300                 if (!(task_cdbs)) {
4301                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
4302                         cmd->scsi_sense_reason =
4303                                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
4304                         return PYX_TRANSPORT_LU_COMM_FAILURE;
4305                 }
4306                 T_TASK(cmd)->t_task_cdbs += task_cdbs;
4307
4308 #if 0
4309                 printk(KERN_INFO "data_length: %u, LBA: %llu t_tasks_sectors:"
4310                         " %u, t_task_cdbs: %u\n", obj_ptr, cmd->data_length,
4311                         T_TASK(cmd)->t_task_lba, T_TASK(cmd)->t_tasks_sectors,
4312                         T_TASK(cmd)->t_task_cdbs);
4313 #endif
4314         }
4315
4316         atomic_set(&T_TASK(cmd)->t_task_cdbs_left, task_cdbs);
4317         atomic_set(&T_TASK(cmd)->t_task_cdbs_ex_left, task_cdbs);
4318         atomic_set(&T_TASK(cmd)->t_task_cdbs_timeout_left, task_cdbs);
4319         return 0;
4320 }
4321
4322 static struct list_head *transport_init_se_mem_list(void)
4323 {
4324         struct list_head *se_mem_list;
4325
4326         se_mem_list = kzalloc(sizeof(struct list_head), GFP_KERNEL);
4327         if (!(se_mem_list)) {
4328                 printk(KERN_ERR "Unable to allocate memory for se_mem_list\n");
4329                 return NULL;
4330         }
4331         INIT_LIST_HEAD(se_mem_list);
4332
4333         return se_mem_list;
4334 }
4335
4336 static int
4337 transport_generic_get_mem(struct se_cmd *cmd, u32 length, u32 dma_size)
4338 {
4339         unsigned char *buf;
4340         struct se_mem *se_mem;
4341
4342         T_TASK(cmd)->t_mem_list = transport_init_se_mem_list();
4343         if (!(T_TASK(cmd)->t_mem_list))
4344                 return -ENOMEM;
4345
4346         /*
4347          * If the device uses memory mapping this is enough.
4348          */
4349         if (cmd->se_dev->transport->do_se_mem_map)
4350                 return 0;
4351
4352         /*
4353          * Setup BIDI-COMMAND READ list of struct se_mem elements
4354          */
4355         if (T_TASK(cmd)->t_tasks_bidi) {
4356                 T_TASK(cmd)->t_mem_bidi_list = transport_init_se_mem_list();
4357                 if (!(T_TASK(cmd)->t_mem_bidi_list)) {
4358                         kfree(T_TASK(cmd)->t_mem_list);
4359                         return -ENOMEM;
4360                 }
4361         }
4362
4363         while (length) {
4364                 se_mem = kmem_cache_zalloc(se_mem_cache, GFP_KERNEL);
4365                 if (!(se_mem)) {
4366                         printk(KERN_ERR "Unable to allocate struct se_mem\n");
4367                         goto out;
4368                 }
4369                 INIT_LIST_HEAD(&se_mem->se_list);
4370                 se_mem->se_len = (length > dma_size) ? dma_size : length;
4371
4372 /* #warning FIXME Allocate contigous pages for struct se_mem elements */
4373                 se_mem->se_page = (struct page *) alloc_pages(GFP_KERNEL, 0);
4374                 if (!(se_mem->se_page)) {
4375                         printk(KERN_ERR "alloc_pages() failed\n");
4376                         goto out;
4377                 }
4378
4379                 buf = kmap_atomic(se_mem->se_page, KM_IRQ0);
4380                 if (!(buf)) {
4381                         printk(KERN_ERR "kmap_atomic() failed\n");
4382                         goto out;
4383                 }
4384                 memset(buf, 0, se_mem->se_len);
4385                 kunmap_atomic(buf, KM_IRQ0);
4386
4387                 list_add_tail(&se_mem->se_list, T_TASK(cmd)->t_mem_list);
4388                 T_TASK(cmd)->t_tasks_se_num++;
4389
4390                 DEBUG_MEM("Allocated struct se_mem page(%p) Length(%u)"
4391                         " Offset(%u)\n", se_mem->se_page, se_mem->se_len,
4392                         se_mem->se_off);
4393
4394                 length -= se_mem->se_len;
4395         }
4396
4397         DEBUG_MEM("Allocated total struct se_mem elements(%u)\n",
4398                         T_TASK(cmd)->t_tasks_se_num);
4399
4400         return 0;
4401 out:
4402         return -1;
4403 }
4404
4405 extern u32 transport_calc_sg_num(
4406         struct se_task *task,
4407         struct se_mem *in_se_mem,
4408         u32 task_offset)
4409 {
4410         struct se_cmd *se_cmd = task->task_se_cmd;
4411         struct se_device *se_dev = SE_DEV(se_cmd);
4412         struct se_mem *se_mem = in_se_mem;
4413         struct target_core_fabric_ops *tfo = CMD_TFO(se_cmd);
4414         u32 sg_length, task_size = task->task_size, task_sg_num_padded;
4415
4416         while (task_size != 0) {
4417                 DEBUG_SC("se_mem->se_page(%p) se_mem->se_len(%u)"
4418                         " se_mem->se_off(%u) task_offset(%u)\n",
4419                         se_mem->se_page, se_mem->se_len,
4420                         se_mem->se_off, task_offset);
4421
4422                 if (task_offset == 0) {
4423                         if (task_size >= se_mem->se_len) {
4424                                 sg_length = se_mem->se_len;
4425
4426                                 if (!(list_is_last(&se_mem->se_list,
4427                                                 T_TASK(se_cmd)->t_mem_list)))
4428                                         se_mem = list_entry(se_mem->se_list.next,
4429                                                         struct se_mem, se_list);
4430                         } else {
4431                                 sg_length = task_size;
4432                                 task_size -= sg_length;
4433                                 goto next;
4434                         }
4435
4436                         DEBUG_SC("sg_length(%u) task_size(%u)\n",
4437                                         sg_length, task_size);
4438                 } else {
4439                         if ((se_mem->se_len - task_offset) > task_size) {
4440                                 sg_length = task_size;
4441                                 task_size -= sg_length;
4442                                 goto next;
4443                          } else {
4444                                 sg_length = (se_mem->se_len - task_offset);
4445
4446                                 if (!(list_is_last(&se_mem->se_list,
4447                                                 T_TASK(se_cmd)->t_mem_list)))
4448                                         se_mem = list_entry(se_mem->se_list.next,
4449                                                         struct se_mem, se_list);
4450                         }
4451
4452                         DEBUG_SC("sg_length(%u) task_size(%u)\n",
4453                                         sg_length, task_size);
4454
4455                         task_offset = 0;
4456                 }
4457                 task_size -= sg_length;
4458 next:
4459                 DEBUG_SC("task[%u] - Reducing task_size to(%u)\n",
4460                         task->task_no, task_size);
4461
4462                 task->task_sg_num++;
4463         }
4464         /*
4465          * Check if the fabric module driver is requesting that all
4466          * struct se_task->task_sg[] be chained together..  If so,
4467          * then allocate an extra padding SG entry for linking and
4468          * marking the end of the chained SGL.
4469          */
4470         if (tfo->task_sg_chaining) {
4471                 task_sg_num_padded = (task->task_sg_num + 1);
4472                 task->task_padded_sg = 1;
4473         } else
4474                 task_sg_num_padded = task->task_sg_num;
4475
4476         task->task_sg = kzalloc(task_sg_num_padded *
4477                         sizeof(struct scatterlist), GFP_KERNEL);
4478         if (!(task->task_sg)) {
4479                 printk(KERN_ERR "Unable to allocate memory for"
4480                                 " task->task_sg\n");
4481                 return 0;
4482         }
4483         sg_init_table(&task->task_sg[0], task_sg_num_padded);
4484         /*
4485          * Setup task->task_sg_bidi for SCSI READ payload for
4486          * TCM/pSCSI passthrough if present for BIDI-COMMAND
4487          */
4488         if ((T_TASK(se_cmd)->t_mem_bidi_list != NULL) &&
4489             (TRANSPORT(se_dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV)) {
4490                 task->task_sg_bidi = kzalloc(task_sg_num_padded *
4491                                 sizeof(struct scatterlist), GFP_KERNEL);
4492                 if (!(task->task_sg_bidi)) {
4493                         printk(KERN_ERR "Unable to allocate memory for"
4494                                 " task->task_sg_bidi\n");
4495                         return 0;
4496                 }
4497                 sg_init_table(&task->task_sg_bidi[0], task_sg_num_padded);
4498         }
4499         /*
4500          * For the chaining case, setup the proper end of SGL for the
4501          * initial submission struct task into struct se_subsystem_api.
4502          * This will be cleared later by transport_do_task_sg_chain()
4503          */
4504         if (task->task_padded_sg) {
4505                 sg_mark_end(&task->task_sg[task->task_sg_num - 1]);
4506                 /*
4507                  * Added the 'if' check before marking end of bi-directional
4508                  * scatterlist (which gets created only in case of request
4509                  * (RD + WR).
4510                  */
4511                 if (task->task_sg_bidi)
4512                         sg_mark_end(&task->task_sg_bidi[task->task_sg_num - 1]);
4513         }
4514
4515         DEBUG_SC("Successfully allocated task->task_sg_num(%u),"
4516                 " task_sg_num_padded(%u)\n", task->task_sg_num,
4517                 task_sg_num_padded);
4518
4519         return task->task_sg_num;
4520 }
4521
4522 static inline int transport_set_tasks_sectors_disk(
4523         struct se_task *task,
4524         struct se_device *dev,
4525         unsigned long long lba,
4526         u32 sectors,
4527         int *max_sectors_set)
4528 {
4529         if ((lba + sectors) > transport_dev_end_lba(dev)) {
4530                 task->task_sectors = ((transport_dev_end_lba(dev) - lba) + 1);
4531
4532                 if (task->task_sectors > DEV_ATTRIB(dev)->max_sectors) {
4533                         task->task_sectors = DEV_ATTRIB(dev)->max_sectors;
4534                         *max_sectors_set = 1;
4535                 }
4536         } else {
4537                 if (sectors > DEV_ATTRIB(dev)->max_sectors) {
4538                         task->task_sectors = DEV_ATTRIB(dev)->max_sectors;
4539                         *max_sectors_set = 1;
4540                 } else
4541                         task->task_sectors = sectors;
4542         }
4543
4544         return 0;
4545 }
4546
4547 static inline int transport_set_tasks_sectors_non_disk(
4548         struct se_task *task,
4549         struct se_device *dev,
4550         unsigned long long lba,
4551         u32 sectors,
4552         int *max_sectors_set)
4553 {
4554         if (sectors > DEV_ATTRIB(dev)->max_sectors) {
4555                 task->task_sectors = DEV_ATTRIB(dev)->max_sectors;
4556                 *max_sectors_set = 1;
4557         } else
4558                 task->task_sectors = sectors;
4559
4560         return 0;
4561 }
4562
4563 static inline int transport_set_tasks_sectors(
4564         struct se_task *task,
4565         struct se_device *dev,
4566         unsigned long long lba,
4567         u32 sectors,
4568         int *max_sectors_set)
4569 {
4570         return (TRANSPORT(dev)->get_device_type(dev) == TYPE_DISK) ?
4571                 transport_set_tasks_sectors_disk(task, dev, lba, sectors,
4572                                 max_sectors_set) :
4573                 transport_set_tasks_sectors_non_disk(task, dev, lba, sectors,
4574                                 max_sectors_set);
4575 }
4576
4577 static int transport_map_sg_to_mem(
4578         struct se_cmd *cmd,
4579         struct list_head *se_mem_list,
4580         void *in_mem,
4581         u32 *se_mem_cnt)
4582 {
4583         struct se_mem *se_mem;
4584         struct scatterlist *sg;
4585         u32 sg_count = 1, cmd_size = cmd->data_length;
4586
4587         if (!in_mem) {
4588                 printk(KERN_ERR "No source scatterlist\n");
4589                 return -1;
4590         }
4591         sg = (struct scatterlist *)in_mem;
4592
4593         while (cmd_size) {
4594                 se_mem = kmem_cache_zalloc(se_mem_cache, GFP_KERNEL);
4595                 if (!(se_mem)) {
4596                         printk(KERN_ERR "Unable to allocate struct se_mem\n");
4597                         return -1;
4598                 }
4599                 INIT_LIST_HEAD(&se_mem->se_list);
4600                 DEBUG_MEM("sg_to_mem: Starting loop with cmd_size: %u"
4601                         " sg_page: %p offset: %d length: %d\n", cmd_size,
4602                         sg_page(sg), sg->offset, sg->length);
4603
4604                 se_mem->se_page = sg_page(sg);
4605                 se_mem->se_off = sg->offset;
4606
4607                 if (cmd_size > sg->length) {
4608                         se_mem->se_len = sg->length;
4609                         sg = sg_next(sg);
4610                         sg_count++;
4611                 } else
4612                         se_mem->se_len = cmd_size;
4613
4614                 cmd_size -= se_mem->se_len;
4615
4616                 DEBUG_MEM("sg_to_mem: *se_mem_cnt: %u cmd_size: %u\n",
4617                                 *se_mem_cnt, cmd_size);
4618                 DEBUG_MEM("sg_to_mem: Final se_page: %p se_off: %d se_len: %d\n",
4619                                 se_mem->se_page, se_mem->se_off, se_mem->se_len);
4620
4621                 list_add_tail(&se_mem->se_list, se_mem_list);
4622                 (*se_mem_cnt)++;
4623         }
4624
4625         DEBUG_MEM("task[0] - Mapped(%u) struct scatterlist segments to(%u)"
4626                 " struct se_mem\n", sg_count, *se_mem_cnt);
4627
4628         if (sg_count != *se_mem_cnt)
4629                 BUG();
4630
4631         return 0;
4632 }
4633
4634 /*      transport_map_mem_to_sg():
4635  *
4636  *
4637  */
4638 int transport_map_mem_to_sg(
4639         struct se_task *task,
4640         struct list_head *se_mem_list,
4641         void *in_mem,
4642         struct se_mem *in_se_mem,
4643         struct se_mem **out_se_mem,
4644         u32 *se_mem_cnt,
4645         u32 *task_offset)
4646 {
4647         struct se_cmd *se_cmd = task->task_se_cmd;
4648         struct se_mem *se_mem = in_se_mem;
4649         struct scatterlist *sg = (struct scatterlist *)in_mem;
4650         u32 task_size = task->task_size, sg_no = 0;
4651
4652         if (!sg) {
4653                 printk(KERN_ERR "Unable to locate valid struct"
4654                                 " scatterlist pointer\n");
4655                 return -1;
4656         }
4657
4658         while (task_size != 0) {
4659                 /*
4660                  * Setup the contigious array of scatterlists for
4661                  * this struct se_task.
4662                  */
4663                 sg_assign_page(sg, se_mem->se_page);
4664
4665                 if (*task_offset == 0) {
4666                         sg->offset = se_mem->se_off;
4667
4668                         if (task_size >= se_mem->se_len) {
4669                                 sg->length = se_mem->se_len;
4670
4671                                 if (!(list_is_last(&se_mem->se_list,
4672                                                 T_TASK(se_cmd)->t_mem_list))) {
4673                                         se_mem = list_entry(se_mem->se_list.next,
4674                                                         struct se_mem, se_list);
4675                                         (*se_mem_cnt)++;
4676                                 }
4677                         } else {
4678                                 sg->length = task_size;
4679                                 /*
4680                                  * Determine if we need to calculate an offset
4681                                  * into the struct se_mem on the next go around..
4682                                  */
4683                                 task_size -= sg->length;
4684                                 if (!(task_size))
4685                                         *task_offset = sg->length;
4686
4687                                 goto next;
4688                         }
4689
4690                 } else {
4691                         sg->offset = (*task_offset + se_mem->se_off);
4692
4693                         if ((se_mem->se_len - *task_offset) > task_size) {
4694                                 sg->length = task_size;
4695                                 /*
4696                                  * Determine if we need to calculate an offset
4697                                  * into the struct se_mem on the next go around..
4698                                  */
4699                                 task_size -= sg->length;
4700                                 if (!(task_size))
4701                                         *task_offset += sg->length;
4702
4703                                 goto next;
4704                         } else {
4705                                 sg->length = (se_mem->se_len - *task_offset);
4706
4707                                 if (!(list_is_last(&se_mem->se_list,
4708                                                 T_TASK(se_cmd)->t_mem_list))) {
4709                                         se_mem = list_entry(se_mem->se_list.next,
4710                                                         struct se_mem, se_list);
4711                                         (*se_mem_cnt)++;
4712                                 }
4713                         }
4714
4715                         *task_offset = 0;
4716                 }
4717                 task_size -= sg->length;
4718 next:
4719                 DEBUG_MEM("task[%u] mem_to_sg - sg[%u](%p)(%u)(%u) - Reducing"
4720                         " task_size to(%u), task_offset: %u\n", task->task_no, sg_no,
4721                         sg_page(sg), sg->length, sg->offset, task_size, *task_offset);
4722
4723                 sg_no++;
4724                 if (!(task_size))
4725                         break;
4726
4727                 sg = sg_next(sg);
4728
4729                 if (task_size > se_cmd->data_length)
4730                         BUG();
4731         }
4732         *out_se_mem = se_mem;
4733
4734         DEBUG_MEM("task[%u] - Mapped(%u) struct se_mem segments to total(%u)"
4735                 " SGs\n", task->task_no, *se_mem_cnt, sg_no);
4736
4737         return 0;
4738 }
4739
4740 /*
4741  * This function can be used by HW target mode drivers to create a linked
4742  * scatterlist from all contiguously allocated struct se_task->task_sg[].
4743  * This is intended to be called during the completion path by TCM Core
4744  * when struct target_core_fabric_ops->check_task_sg_chaining is enabled.
4745  */
4746 void transport_do_task_sg_chain(struct se_cmd *cmd)
4747 {
4748         struct scatterlist *sg_head = NULL, *sg_link = NULL, *sg_first = NULL;
4749         struct scatterlist *sg_head_cur = NULL, *sg_link_cur = NULL;
4750         struct scatterlist *sg, *sg_end = NULL, *sg_end_cur = NULL;
4751         struct se_task *task;
4752         struct target_core_fabric_ops *tfo = CMD_TFO(cmd);
4753         u32 task_sg_num = 0, sg_count = 0;
4754         int i;
4755
4756         if (tfo->task_sg_chaining == 0) {
4757                 printk(KERN_ERR "task_sg_chaining is diabled for fabric module:"
4758                                 " %s\n", tfo->get_fabric_name());
4759                 dump_stack();
4760                 return;
4761         }
4762         /*
4763          * Walk the struct se_task list and setup scatterlist chains
4764          * for each contiguosly allocated struct se_task->task_sg[].
4765          */
4766         list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
4767                 if (!(task->task_sg) || !(task->task_padded_sg))
4768                         continue;
4769
4770                 if (sg_head && sg_link) {
4771                         sg_head_cur = &task->task_sg[0];
4772                         sg_link_cur = &task->task_sg[task->task_sg_num];
4773                         /*
4774                          * Either add chain or mark end of scatterlist
4775                          */
4776                         if (!(list_is_last(&task->t_list,
4777                                         &T_TASK(cmd)->t_task_list))) {
4778                                 /*
4779                                  * Clear existing SGL termination bit set in
4780                                  * transport_calc_sg_num(), see sg_mark_end()
4781                                  */
4782                                 sg_end_cur = &task->task_sg[task->task_sg_num - 1];
4783                                 sg_end_cur->page_link &= ~0x02;
4784
4785                                 sg_chain(sg_head, task_sg_num, sg_head_cur);
4786                                 sg_count += task->task_sg_num;
4787                                 task_sg_num = (task->task_sg_num + 1);
4788                         } else {
4789                                 sg_chain(sg_head, task_sg_num, sg_head_cur);
4790                                 sg_count += task->task_sg_num;
4791                                 task_sg_num = task->task_sg_num;
4792                         }
4793
4794                         sg_head = sg_head_cur;
4795                         sg_link = sg_link_cur;
4796                         continue;
4797                 }
4798                 sg_head = sg_first = &task->task_sg[0];
4799                 sg_link = &task->task_sg[task->task_sg_num];
4800                 /*
4801                  * Check for single task..
4802                  */
4803                 if (!(list_is_last(&task->t_list, &T_TASK(cmd)->t_task_list))) {
4804                         /*
4805                          * Clear existing SGL termination bit set in
4806                          * transport_calc_sg_num(), see sg_mark_end()
4807                          */
4808                         sg_end = &task->task_sg[task->task_sg_num - 1];
4809                         sg_end->page_link &= ~0x02;
4810                         sg_count += task->task_sg_num;
4811                         task_sg_num = (task->task_sg_num + 1);
4812                 } else {
4813                         sg_count += task->task_sg_num;
4814                         task_sg_num = task->task_sg_num;
4815                 }
4816         }
4817         /*
4818          * Setup the starting pointer and total t_tasks_sg_linked_no including
4819          * padding SGs for linking and to mark the end.
4820          */
4821         T_TASK(cmd)->t_tasks_sg_chained = sg_first;
4822         T_TASK(cmd)->t_tasks_sg_chained_no = sg_count;
4823
4824         DEBUG_CMD_M("Setup cmd: %p T_TASK(cmd)->t_tasks_sg_chained: %p and"
4825                 " t_tasks_sg_chained_no: %u\n", cmd, T_TASK(cmd)->t_tasks_sg_chained,
4826                 T_TASK(cmd)->t_tasks_sg_chained_no);
4827
4828         for_each_sg(T_TASK(cmd)->t_tasks_sg_chained, sg,
4829                         T_TASK(cmd)->t_tasks_sg_chained_no, i) {
4830
4831                 DEBUG_CMD_M("SG[%d]: %p page: %p length: %d offset: %d, magic: 0x%08x\n",
4832                         i, sg, sg_page(sg), sg->length, sg->offset, sg->sg_magic);
4833                 if (sg_is_chain(sg))
4834                         DEBUG_CMD_M("SG: %p sg_is_chain=1\n", sg);
4835                 if (sg_is_last(sg))
4836                         DEBUG_CMD_M("SG: %p sg_is_last=1\n", sg);
4837         }
4838 }
4839 EXPORT_SYMBOL(transport_do_task_sg_chain);
4840
4841 static int transport_do_se_mem_map(
4842         struct se_device *dev,
4843         struct se_task *task,
4844         struct list_head *se_mem_list,
4845         void *in_mem,
4846         struct se_mem *in_se_mem,
4847         struct se_mem **out_se_mem,
4848         u32 *se_mem_cnt,
4849         u32 *task_offset_in)
4850 {
4851         u32 task_offset = *task_offset_in;
4852         int ret = 0;
4853         /*
4854          * se_subsystem_api_t->do_se_mem_map is used when internal allocation
4855          * has been done by the transport plugin.
4856          */
4857         if (TRANSPORT(dev)->do_se_mem_map) {
4858                 ret = TRANSPORT(dev)->do_se_mem_map(task, se_mem_list,
4859                                 in_mem, in_se_mem, out_se_mem, se_mem_cnt,
4860                                 task_offset_in);
4861                 if (ret == 0)
4862                         T_TASK(task->task_se_cmd)->t_tasks_se_num += *se_mem_cnt;
4863
4864                 return ret;
4865         }
4866
4867         BUG_ON(list_empty(se_mem_list));
4868         /*
4869          * This is the normal path for all normal non BIDI and BIDI-COMMAND
4870          * WRITE payloads..  If we need to do BIDI READ passthrough for
4871          * TCM/pSCSI the first call to transport_do_se_mem_map ->
4872          * transport_calc_sg_num() -> transport_map_mem_to_sg() will do the
4873          * allocation for task->task_sg_bidi, and the subsequent call to
4874          * transport_do_se_mem_map() from transport_generic_get_cdb_count()
4875          */
4876         if (!(task->task_sg_bidi)) {
4877                 /*
4878                  * Assume default that transport plugin speaks preallocated
4879                  * scatterlists.
4880                  */
4881                 if (!(transport_calc_sg_num(task, in_se_mem, task_offset)))
4882                         return -1;
4883                 /*
4884                  * struct se_task->task_sg now contains the struct scatterlist array.
4885                  */
4886                 return transport_map_mem_to_sg(task, se_mem_list, task->task_sg,
4887                                         in_se_mem, out_se_mem, se_mem_cnt,
4888                                         task_offset_in);
4889         }
4890         /*
4891          * Handle the se_mem_list -> struct task->task_sg_bidi
4892          * memory map for the extra BIDI READ payload
4893          */
4894         return transport_map_mem_to_sg(task, se_mem_list, task->task_sg_bidi,
4895                                 in_se_mem, out_se_mem, se_mem_cnt,
4896                                 task_offset_in);
4897 }
4898
4899 static u32 transport_generic_get_cdb_count(
4900         struct se_cmd *cmd,
4901         unsigned long long lba,
4902         u32 sectors,
4903         enum dma_data_direction data_direction,
4904         struct list_head *mem_list,
4905         int set_counts)
4906 {
4907         unsigned char *cdb = NULL;
4908         struct se_task *task;
4909         struct se_mem *se_mem = NULL, *se_mem_lout = NULL;
4910         struct se_mem *se_mem_bidi = NULL, *se_mem_bidi_lout = NULL;
4911         struct se_device *dev = SE_DEV(cmd);
4912         int max_sectors_set = 0, ret;
4913         u32 task_offset_in = 0, se_mem_cnt = 0, se_mem_bidi_cnt = 0, task_cdbs = 0;
4914
4915         if (!mem_list) {
4916                 printk(KERN_ERR "mem_list is NULL in transport_generic_get"
4917                                 "_cdb_count()\n");
4918                 return 0;
4919         }
4920         /*
4921          * While using RAMDISK_DR backstores is the only case where
4922          * mem_list will ever be empty at this point.
4923          */
4924         if (!(list_empty(mem_list)))
4925                 se_mem = list_entry(mem_list->next, struct se_mem, se_list);
4926         /*
4927          * Check for extra se_mem_bidi mapping for BIDI-COMMANDs to
4928          * struct se_task->task_sg_bidi for TCM/pSCSI passthrough operation
4929          */
4930         if ((T_TASK(cmd)->t_mem_bidi_list != NULL) &&
4931             !(list_empty(T_TASK(cmd)->t_mem_bidi_list)) &&
4932             (TRANSPORT(dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV))
4933                 se_mem_bidi = list_entry(T_TASK(cmd)->t_mem_bidi_list->next,
4934                                         struct se_mem, se_list);
4935
4936         while (sectors) {
4937                 DEBUG_VOL("ITT[0x%08x] LBA(%llu) SectorsLeft(%u) EOBJ(%llu)\n",
4938                         CMD_TFO(cmd)->get_task_tag(cmd), lba, sectors,
4939                         transport_dev_end_lba(dev));
4940
4941                 task = transport_generic_get_task(cmd, data_direction);
4942                 if (!(task))
4943                         goto out;
4944
4945                 transport_set_tasks_sectors(task, dev, lba, sectors,
4946                                 &max_sectors_set);
4947
4948                 task->task_lba = lba;
4949                 lba += task->task_sectors;
4950                 sectors -= task->task_sectors;
4951                 task->task_size = (task->task_sectors *
4952                                    DEV_ATTRIB(dev)->block_size);
4953
4954                 cdb = TRANSPORT(dev)->get_cdb(task);
4955                 if ((cdb)) {
4956                         memcpy(cdb, T_TASK(cmd)->t_task_cdb,
4957                                 scsi_command_size(T_TASK(cmd)->t_task_cdb));
4958                         cmd->transport_split_cdb(task->task_lba,
4959                                         &task->task_sectors, cdb);
4960                 }
4961
4962                 /*
4963                  * Perform the SE OBJ plugin and/or Transport plugin specific
4964                  * mapping for T_TASK(cmd)->t_mem_list. And setup the
4965                  * task->task_sg and if necessary task->task_sg_bidi
4966                  */
4967                 ret = transport_do_se_mem_map(dev, task, mem_list,
4968                                 NULL, se_mem, &se_mem_lout, &se_mem_cnt,
4969                                 &task_offset_in);
4970                 if (ret < 0)
4971                         goto out;
4972
4973                 se_mem = se_mem_lout;
4974                 /*
4975                  * Setup the T_TASK(cmd)->t_mem_bidi_list -> task->task_sg_bidi
4976                  * mapping for SCSI READ for BIDI-COMMAND passthrough with TCM/pSCSI
4977                  *
4978                  * Note that the first call to transport_do_se_mem_map() above will
4979                  * allocate struct se_task->task_sg_bidi in transport_do_se_mem_map()
4980                  * -> transport_calc_sg_num(), and the second here will do the
4981                  * mapping for SCSI READ for BIDI-COMMAND passthrough with TCM/pSCSI.
4982                  */
4983                 if (task->task_sg_bidi != NULL) {
4984                         ret = transport_do_se_mem_map(dev, task,
4985                                 T_TASK(cmd)->t_mem_bidi_list, NULL,
4986                                 se_mem_bidi, &se_mem_bidi_lout, &se_mem_bidi_cnt,
4987                                 &task_offset_in);
4988                         if (ret < 0)
4989                                 goto out;
4990
4991                         se_mem_bidi = se_mem_bidi_lout;
4992                 }
4993                 task_cdbs++;
4994
4995                 DEBUG_VOL("Incremented task_cdbs(%u) task->task_sg_num(%u)\n",
4996                                 task_cdbs, task->task_sg_num);
4997
4998                 if (max_sectors_set) {
4999                         max_sectors_set = 0;
5000                         continue;
5001                 }
5002
5003                 if (!sectors)
5004                         break;
5005         }
5006
5007         if (set_counts) {
5008                 atomic_inc(&T_TASK(cmd)->t_fe_count);
5009                 atomic_inc(&T_TASK(cmd)->t_se_count);
5010         }
5011
5012         DEBUG_VOL("ITT[0x%08x] total %s cdbs(%u)\n",
5013                 CMD_TFO(cmd)->get_task_tag(cmd), (data_direction == DMA_TO_DEVICE)
5014                 ? "DMA_TO_DEVICE" : "DMA_FROM_DEVICE", task_cdbs);
5015
5016         return task_cdbs;
5017 out:
5018         return 0;
5019 }
5020
5021 static int
5022 transport_map_control_cmd_to_task(struct se_cmd *cmd)
5023 {
5024         struct se_device *dev = SE_DEV(cmd);
5025         unsigned char *cdb;
5026         struct se_task *task;
5027         int ret;
5028
5029         task = transport_generic_get_task(cmd, cmd->data_direction);
5030         if (!task)
5031                 return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
5032
5033         cdb = TRANSPORT(dev)->get_cdb(task);
5034         if (cdb)
5035                 memcpy(cdb, cmd->t_task->t_task_cdb,
5036                         scsi_command_size(cmd->t_task->t_task_cdb));
5037
5038         task->task_size = cmd->data_length;
5039         task->task_sg_num =
5040                 (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB) ? 1 : 0;
5041
5042         atomic_inc(&cmd->t_task->t_fe_count);
5043         atomic_inc(&cmd->t_task->t_se_count);
5044
5045         if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB) {
5046                 struct se_mem *se_mem = NULL, *se_mem_lout = NULL;
5047                 u32 se_mem_cnt = 0, task_offset = 0;
5048
5049                 if (!list_empty(T_TASK(cmd)->t_mem_list))
5050                         se_mem = list_entry(T_TASK(cmd)->t_mem_list->next,
5051                                         struct se_mem, se_list);
5052
5053                 ret = transport_do_se_mem_map(dev, task,
5054                                 cmd->t_task->t_mem_list, NULL, se_mem,
5055                                 &se_mem_lout, &se_mem_cnt, &task_offset);
5056                 if (ret < 0)
5057                         return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
5058
5059                 if (dev->transport->map_task_SG)
5060                         return dev->transport->map_task_SG(task);
5061                 return 0;
5062         } else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB) {
5063                 if (dev->transport->map_task_non_SG)
5064                         return dev->transport->map_task_non_SG(task);
5065                 return 0;
5066         } else if (cmd->se_cmd_flags & SCF_SCSI_NON_DATA_CDB) {
5067                 if (dev->transport->cdb_none)
5068                         return dev->transport->cdb_none(task);
5069                 return 0;
5070         } else {
5071                 BUG();
5072                 return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
5073         }
5074 }
5075
5076 /*       transport_generic_new_cmd(): Called from transport_processing_thread()
5077  *
5078  *       Allocate storage transport resources from a set of values predefined
5079  *       by transport_generic_cmd_sequencer() from the iSCSI Target RX process.
5080  *       Any non zero return here is treated as an "out of resource' op here.
5081  */
5082         /*
5083          * Generate struct se_task(s) and/or their payloads for this CDB.
5084          */
5085 static int transport_generic_new_cmd(struct se_cmd *cmd)
5086 {
5087         struct se_portal_group *se_tpg;
5088         struct se_task *task;
5089         struct se_device *dev = SE_DEV(cmd);
5090         int ret = 0;
5091
5092         /*
5093          * Determine is the TCM fabric module has already allocated physical
5094          * memory, and is directly calling transport_generic_map_mem_to_cmd()
5095          * to setup beforehand the linked list of physical memory at
5096          * T_TASK(cmd)->t_mem_list of struct se_mem->se_page
5097          */
5098         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)) {
5099                 ret = transport_allocate_resources(cmd);
5100                 if (ret < 0)
5101                         return ret;
5102         }
5103
5104         ret = transport_get_sectors(cmd);
5105         if (ret < 0)
5106                 return ret;
5107
5108         ret = transport_new_cmd_obj(cmd);
5109         if (ret < 0)
5110                 return ret;
5111
5112         /*
5113          * Determine if the calling TCM fabric module is talking to
5114          * Linux/NET via kernel sockets and needs to allocate a
5115          * struct iovec array to complete the struct se_cmd
5116          */
5117         se_tpg = SE_LUN(cmd)->lun_sep->sep_tpg;
5118         if (TPG_TFO(se_tpg)->alloc_cmd_iovecs != NULL) {
5119                 ret = TPG_TFO(se_tpg)->alloc_cmd_iovecs(cmd);
5120                 if (ret < 0)
5121                         return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
5122         }
5123
5124         if (cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) {
5125                 list_for_each_entry(task, &T_TASK(cmd)->t_task_list, t_list) {
5126                         if (atomic_read(&task->task_sent))
5127                                 continue;
5128                         if (!dev->transport->map_task_SG)
5129                                 continue;
5130
5131                         ret = dev->transport->map_task_SG(task);
5132                         if (ret < 0)
5133                                 return ret;
5134                 }
5135         } else {
5136                 ret = transport_map_control_cmd_to_task(cmd);
5137                 if (ret < 0)
5138                         return ret;
5139         }
5140
5141         /*
5142          * For WRITEs, let the iSCSI Target RX Thread know its buffer is ready..
5143          * This WRITE struct se_cmd (and all of its associated struct se_task's)
5144          * will be added to the struct se_device execution queue after its WRITE
5145          * data has arrived. (ie: It gets handled by the transport processing
5146          * thread a second time)
5147          */
5148         if (cmd->data_direction == DMA_TO_DEVICE) {
5149                 transport_add_tasks_to_state_queue(cmd);
5150                 return transport_generic_write_pending(cmd);
5151         }
5152         /*
5153          * Everything else but a WRITE, add the struct se_cmd's struct se_task's
5154          * to the execution queue.
5155          */
5156         transport_execute_tasks(cmd);
5157         return 0;
5158 }
5159
5160 /*      transport_generic_process_write():
5161  *
5162  *
5163  */
5164 void transport_generic_process_write(struct se_cmd *cmd)
5165 {
5166 #if 0
5167         /*
5168          * Copy SCSI Presented DTL sector(s) from received buffers allocated to
5169          * original EDTL
5170          */
5171         if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
5172                 if (!T_TASK(cmd)->t_tasks_se_num) {
5173                         unsigned char *dst, *buf =
5174                                 (unsigned char *)T_TASK(cmd)->t_task_buf;
5175
5176                         dst = kzalloc(cmd->cmd_spdtl), GFP_KERNEL);
5177                         if (!(dst)) {
5178                                 printk(KERN_ERR "Unable to allocate memory for"
5179                                                 " WRITE underflow\n");
5180                                 transport_generic_request_failure(cmd, NULL,
5181                                         PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
5182                                 return;
5183                         }
5184                         memcpy(dst, buf, cmd->cmd_spdtl);
5185
5186                         kfree(T_TASK(cmd)->t_task_buf);
5187                         T_TASK(cmd)->t_task_buf = dst;
5188                 } else {
5189                         struct scatterlist *sg =
5190                                 (struct scatterlist *sg)T_TASK(cmd)->t_task_buf;
5191                         struct scatterlist *orig_sg;
5192
5193                         orig_sg = kzalloc(sizeof(struct scatterlist) *
5194                                         T_TASK(cmd)->t_tasks_se_num,
5195                                         GFP_KERNEL))) {
5196                         if (!(orig_sg)) {
5197                                 printk(KERN_ERR "Unable to allocate memory"
5198                                                 " for WRITE underflow\n");
5199                                 transport_generic_request_failure(cmd, NULL,
5200                                         PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
5201                                 return;
5202                         }
5203
5204                         memcpy(orig_sg, T_TASK(cmd)->t_task_buf,
5205                                         sizeof(struct scatterlist) *
5206                                         T_TASK(cmd)->t_tasks_se_num);
5207
5208                         cmd->data_length = cmd->cmd_spdtl;
5209                         /*
5210                          * FIXME, clear out original struct se_task and state
5211                          * information.
5212                          */
5213                         if (transport_generic_new_cmd(cmd) < 0) {
5214                                 transport_generic_request_failure(cmd, NULL,
5215                                         PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
5216                                 kfree(orig_sg);
5217                                 return;
5218                         }
5219
5220                         transport_memcpy_write_sg(cmd, orig_sg);
5221                 }
5222         }
5223 #endif
5224         transport_execute_tasks(cmd);
5225 }
5226 EXPORT_SYMBOL(transport_generic_process_write);
5227
5228 /*      transport_generic_write_pending():
5229  *
5230  *
5231  */
5232 static int transport_generic_write_pending(struct se_cmd *cmd)
5233 {
5234         unsigned long flags;
5235         int ret;
5236
5237         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
5238         cmd->t_state = TRANSPORT_WRITE_PENDING;
5239         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
5240         /*
5241          * For the TCM control CDBs using a contiguous buffer, do the memcpy
5242          * from the passed Linux/SCSI struct scatterlist located at
5243          * T_TASK(se_cmd)->t_task_pt_buf to the contiguous buffer at
5244          * T_TASK(se_cmd)->t_task_buf.
5245          */
5246         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_CONTIG_TO_SG)
5247                 transport_memcpy_read_contig(cmd,
5248                                 T_TASK(cmd)->t_task_buf,
5249                                 T_TASK(cmd)->t_task_pt_sgl);
5250         /*
5251          * Clear the se_cmd for WRITE_PENDING status in order to set
5252          * T_TASK(cmd)->t_transport_active=0 so that transport_generic_handle_data
5253          * can be called from HW target mode interrupt code.  This is safe
5254          * to be called with transport_off=1 before the CMD_TFO(cmd)->write_pending
5255          * because the se_cmd->se_lun pointer is not being cleared.
5256          */
5257         transport_cmd_check_stop(cmd, 1, 0);
5258
5259         /*
5260          * Call the fabric write_pending function here to let the
5261          * frontend know that WRITE buffers are ready.
5262          */
5263         ret = CMD_TFO(cmd)->write_pending(cmd);
5264         if (ret < 0)
5265                 return ret;
5266
5267         return PYX_TRANSPORT_WRITE_PENDING;
5268 }
5269
5270 /*      transport_release_cmd_to_pool():
5271  *
5272  *
5273  */
5274 void transport_release_cmd_to_pool(struct se_cmd *cmd)
5275 {
5276         BUG_ON(!T_TASK(cmd));
5277         BUG_ON(!CMD_TFO(cmd));
5278
5279         transport_free_se_cmd(cmd);
5280         CMD_TFO(cmd)->release_cmd_to_pool(cmd);
5281 }
5282 EXPORT_SYMBOL(transport_release_cmd_to_pool);
5283
5284 /*      transport_generic_free_cmd():
5285  *
5286  *      Called from processing frontend to release storage engine resources
5287  */
5288 void transport_generic_free_cmd(
5289         struct se_cmd *cmd,
5290         int wait_for_tasks,
5291         int release_to_pool,
5292         int session_reinstatement)
5293 {
5294         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) || !T_TASK(cmd))
5295                 transport_release_cmd_to_pool(cmd);
5296         else {
5297                 core_dec_lacl_count(cmd->se_sess->se_node_acl, cmd);
5298
5299                 if (SE_LUN(cmd)) {
5300 #if 0
5301                         printk(KERN_INFO "cmd: %p ITT: 0x%08x contains"
5302                                 " SE_LUN(cmd)\n", cmd,
5303                                 CMD_TFO(cmd)->get_task_tag(cmd));
5304 #endif
5305                         transport_lun_remove_cmd(cmd);
5306                 }
5307
5308                 if (wait_for_tasks && cmd->transport_wait_for_tasks)
5309                         cmd->transport_wait_for_tasks(cmd, 0, 0);
5310
5311                 transport_free_dev_tasks(cmd);
5312
5313                 transport_generic_remove(cmd, release_to_pool,
5314                                 session_reinstatement);
5315         }
5316 }
5317 EXPORT_SYMBOL(transport_generic_free_cmd);
5318
5319 static void transport_nop_wait_for_tasks(
5320         struct se_cmd *cmd,
5321         int remove_cmd,
5322         int session_reinstatement)
5323 {
5324         return;
5325 }
5326
5327 /*      transport_lun_wait_for_tasks():
5328  *
5329  *      Called from ConfigFS context to stop the passed struct se_cmd to allow
5330  *      an struct se_lun to be successfully shutdown.
5331  */
5332 static int transport_lun_wait_for_tasks(struct se_cmd *cmd, struct se_lun *lun)
5333 {
5334         unsigned long flags;
5335         int ret;
5336         /*
5337          * If the frontend has already requested this struct se_cmd to
5338          * be stopped, we can safely ignore this struct se_cmd.
5339          */
5340         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
5341         if (atomic_read(&T_TASK(cmd)->t_transport_stop)) {
5342                 atomic_set(&T_TASK(cmd)->transport_lun_stop, 0);
5343                 DEBUG_TRANSPORT_S("ConfigFS ITT[0x%08x] - t_transport_stop =="
5344                         " TRUE, skipping\n", CMD_TFO(cmd)->get_task_tag(cmd));
5345                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
5346                 transport_cmd_check_stop(cmd, 1, 0);
5347                 return -1;
5348         }
5349         atomic_set(&T_TASK(cmd)->transport_lun_fe_stop, 1);
5350         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
5351
5352         wake_up_interruptible(&SE_DEV(cmd)->dev_queue_obj->thread_wq);
5353
5354         ret = transport_stop_tasks_for_cmd(cmd);
5355
5356         DEBUG_TRANSPORT_S("ConfigFS: cmd: %p t_task_cdbs: %d stop tasks ret:"
5357                         " %d\n", cmd, T_TASK(cmd)->t_task_cdbs, ret);
5358         if (!ret) {
5359                 DEBUG_TRANSPORT_S("ConfigFS: ITT[0x%08x] - stopping cmd....\n",
5360                                 CMD_TFO(cmd)->get_task_tag(cmd));
5361                 wait_for_completion(&T_TASK(cmd)->transport_lun_stop_comp);
5362                 DEBUG_TRANSPORT_S("ConfigFS: ITT[0x%08x] - stopped cmd....\n",
5363                                 CMD_TFO(cmd)->get_task_tag(cmd));
5364         }
5365         transport_remove_cmd_from_queue(cmd, SE_DEV(cmd)->dev_queue_obj);
5366
5367         return 0;
5368 }
5369
5370 /* #define DEBUG_CLEAR_LUN */
5371 #ifdef DEBUG_CLEAR_LUN
5372 #define DEBUG_CLEAR_L(x...) printk(KERN_INFO x)
5373 #else
5374 #define DEBUG_CLEAR_L(x...)
5375 #endif
5376
5377 static void __transport_clear_lun_from_sessions(struct se_lun *lun)
5378 {
5379         struct se_cmd *cmd = NULL;
5380         unsigned long lun_flags, cmd_flags;
5381         /*
5382          * Do exception processing and return CHECK_CONDITION status to the
5383          * Initiator Port.
5384          */
5385         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
5386         while (!list_empty_careful(&lun->lun_cmd_list)) {
5387                 cmd = list_entry(lun->lun_cmd_list.next,
5388                         struct se_cmd, se_lun_list);
5389                 list_del(&cmd->se_lun_list);
5390
5391                 if (!(T_TASK(cmd))) {
5392                         printk(KERN_ERR "ITT: 0x%08x, T_TASK(cmd) = NULL"
5393                                 "[i,t]_state: %u/%u\n",
5394                                 CMD_TFO(cmd)->get_task_tag(cmd),
5395                                 CMD_TFO(cmd)->get_cmd_state(cmd), cmd->t_state);
5396                         BUG();
5397                 }
5398                 atomic_set(&T_TASK(cmd)->transport_lun_active, 0);
5399                 /*
5400                  * This will notify iscsi_target_transport.c:
5401                  * transport_cmd_check_stop() that a LUN shutdown is in
5402                  * progress for the iscsi_cmd_t.
5403                  */
5404                 spin_lock(&T_TASK(cmd)->t_state_lock);
5405                 DEBUG_CLEAR_L("SE_LUN[%d] - Setting T_TASK(cmd)->transport"
5406                         "_lun_stop for  ITT: 0x%08x\n",
5407                         SE_LUN(cmd)->unpacked_lun,
5408                         CMD_TFO(cmd)->get_task_tag(cmd));
5409                 atomic_set(&T_TASK(cmd)->transport_lun_stop, 1);
5410                 spin_unlock(&T_TASK(cmd)->t_state_lock);
5411
5412                 spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
5413
5414                 if (!(SE_LUN(cmd))) {
5415                         printk(KERN_ERR "ITT: 0x%08x, [i,t]_state: %u/%u\n",
5416                                 CMD_TFO(cmd)->get_task_tag(cmd),
5417                                 CMD_TFO(cmd)->get_cmd_state(cmd), cmd->t_state);
5418                         BUG();
5419                 }
5420                 /*
5421                  * If the Storage engine still owns the iscsi_cmd_t, determine
5422                  * and/or stop its context.
5423                  */
5424                 DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x before transport"
5425                         "_lun_wait_for_tasks()\n", SE_LUN(cmd)->unpacked_lun,
5426                         CMD_TFO(cmd)->get_task_tag(cmd));
5427
5428                 if (transport_lun_wait_for_tasks(cmd, SE_LUN(cmd)) < 0) {
5429                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
5430                         continue;
5431                 }
5432
5433                 DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x after transport_lun"
5434                         "_wait_for_tasks(): SUCCESS\n",
5435                         SE_LUN(cmd)->unpacked_lun,
5436                         CMD_TFO(cmd)->get_task_tag(cmd));
5437
5438                 spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, cmd_flags);
5439                 if (!(atomic_read(&T_TASK(cmd)->transport_dev_active))) {
5440                         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, cmd_flags);
5441                         goto check_cond;
5442                 }
5443                 atomic_set(&T_TASK(cmd)->transport_dev_active, 0);
5444                 transport_all_task_dev_remove_state(cmd);
5445                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, cmd_flags);
5446
5447                 transport_free_dev_tasks(cmd);
5448                 /*
5449                  * The Storage engine stopped this struct se_cmd before it was
5450                  * send to the fabric frontend for delivery back to the
5451                  * Initiator Node.  Return this SCSI CDB back with an
5452                  * CHECK_CONDITION status.
5453                  */
5454 check_cond:
5455                 transport_send_check_condition_and_sense(cmd,
5456                                 TCM_NON_EXISTENT_LUN, 0);
5457                 /*
5458                  *  If the fabric frontend is waiting for this iscsi_cmd_t to
5459                  * be released, notify the waiting thread now that LU has
5460                  * finished accessing it.
5461                  */
5462                 spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, cmd_flags);
5463                 if (atomic_read(&T_TASK(cmd)->transport_lun_fe_stop)) {
5464                         DEBUG_CLEAR_L("SE_LUN[%d] - Detected FE stop for"
5465                                 " struct se_cmd: %p ITT: 0x%08x\n",
5466                                 lun->unpacked_lun,
5467                                 cmd, CMD_TFO(cmd)->get_task_tag(cmd));
5468
5469                         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock,
5470                                         cmd_flags);
5471                         transport_cmd_check_stop(cmd, 1, 0);
5472                         complete(&T_TASK(cmd)->transport_lun_fe_stop_comp);
5473                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
5474                         continue;
5475                 }
5476                 DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x finished processing\n",
5477                         lun->unpacked_lun, CMD_TFO(cmd)->get_task_tag(cmd));
5478
5479                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, cmd_flags);
5480                 spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
5481         }
5482         spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
5483 }
5484
5485 static int transport_clear_lun_thread(void *p)
5486 {
5487         struct se_lun *lun = (struct se_lun *)p;
5488
5489         __transport_clear_lun_from_sessions(lun);
5490         complete(&lun->lun_shutdown_comp);
5491
5492         return 0;
5493 }
5494
5495 int transport_clear_lun_from_sessions(struct se_lun *lun)
5496 {
5497         struct task_struct *kt;
5498
5499         kt = kthread_run(transport_clear_lun_thread, (void *)lun,
5500                         "tcm_cl_%u", lun->unpacked_lun);
5501         if (IS_ERR(kt)) {
5502                 printk(KERN_ERR "Unable to start clear_lun thread\n");
5503                 return -1;
5504         }
5505         wait_for_completion(&lun->lun_shutdown_comp);
5506
5507         return 0;
5508 }
5509
5510 /*      transport_generic_wait_for_tasks():
5511  *
5512  *      Called from frontend or passthrough context to wait for storage engine
5513  *      to pause and/or release frontend generated struct se_cmd.
5514  */
5515 static void transport_generic_wait_for_tasks(
5516         struct se_cmd *cmd,
5517         int remove_cmd,
5518         int session_reinstatement)
5519 {
5520         unsigned long flags;
5521
5522         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) && !(cmd->se_tmr_req))
5523                 return;
5524
5525         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
5526         /*
5527          * If we are already stopped due to an external event (ie: LUN shutdown)
5528          * sleep until the connection can have the passed struct se_cmd back.
5529          * The T_TASK(cmd)->transport_lun_stopped_sem will be upped by
5530          * transport_clear_lun_from_sessions() once the ConfigFS context caller
5531          * has completed its operation on the struct se_cmd.
5532          */
5533         if (atomic_read(&T_TASK(cmd)->transport_lun_stop)) {
5534
5535                 DEBUG_TRANSPORT_S("wait_for_tasks: Stopping"
5536                         " wait_for_completion(&T_TASK(cmd)transport_lun_fe"
5537                         "_stop_comp); for ITT: 0x%08x\n",
5538                         CMD_TFO(cmd)->get_task_tag(cmd));
5539                 /*
5540                  * There is a special case for WRITES where a FE exception +
5541                  * LUN shutdown means ConfigFS context is still sleeping on
5542                  * transport_lun_stop_comp in transport_lun_wait_for_tasks().
5543                  * We go ahead and up transport_lun_stop_comp just to be sure
5544                  * here.
5545                  */
5546                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
5547                 complete(&T_TASK(cmd)->transport_lun_stop_comp);
5548                 wait_for_completion(&T_TASK(cmd)->transport_lun_fe_stop_comp);
5549                 spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
5550
5551                 transport_all_task_dev_remove_state(cmd);
5552                 /*
5553                  * At this point, the frontend who was the originator of this
5554                  * struct se_cmd, now owns the structure and can be released through
5555                  * normal means below.
5556                  */
5557                 DEBUG_TRANSPORT_S("wait_for_tasks: Stopped"
5558                         " wait_for_completion(&T_TASK(cmd)transport_lun_fe_"
5559                         "stop_comp); for ITT: 0x%08x\n",
5560                         CMD_TFO(cmd)->get_task_tag(cmd));
5561
5562                 atomic_set(&T_TASK(cmd)->transport_lun_stop, 0);
5563         }
5564         if (!atomic_read(&T_TASK(cmd)->t_transport_active) ||
5565              atomic_read(&T_TASK(cmd)->t_transport_aborted))
5566                 goto remove;
5567
5568         atomic_set(&T_TASK(cmd)->t_transport_stop, 1);
5569
5570         DEBUG_TRANSPORT_S("wait_for_tasks: Stopping %p ITT: 0x%08x"
5571                 " i_state: %d, t_state/def_t_state: %d/%d, t_transport_stop"
5572                 " = TRUE\n", cmd, CMD_TFO(cmd)->get_task_tag(cmd),
5573                 CMD_TFO(cmd)->get_cmd_state(cmd), cmd->t_state,
5574                 cmd->deferred_t_state);
5575
5576         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
5577
5578         wake_up_interruptible(&SE_DEV(cmd)->dev_queue_obj->thread_wq);
5579
5580         wait_for_completion(&T_TASK(cmd)->t_transport_stop_comp);
5581
5582         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
5583         atomic_set(&T_TASK(cmd)->t_transport_active, 0);
5584         atomic_set(&T_TASK(cmd)->t_transport_stop, 0);
5585
5586         DEBUG_TRANSPORT_S("wait_for_tasks: Stopped wait_for_compltion("
5587                 "&T_TASK(cmd)->t_transport_stop_comp) for ITT: 0x%08x\n",
5588                 CMD_TFO(cmd)->get_task_tag(cmd));
5589 remove:
5590         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
5591         if (!remove_cmd)
5592                 return;
5593
5594         transport_generic_free_cmd(cmd, 0, 0, session_reinstatement);
5595 }
5596
5597 static int transport_get_sense_codes(
5598         struct se_cmd *cmd,
5599         u8 *asc,
5600         u8 *ascq)
5601 {
5602         *asc = cmd->scsi_asc;
5603         *ascq = cmd->scsi_ascq;
5604
5605         return 0;
5606 }
5607
5608 static int transport_set_sense_codes(
5609         struct se_cmd *cmd,
5610         u8 asc,
5611         u8 ascq)
5612 {
5613         cmd->scsi_asc = asc;
5614         cmd->scsi_ascq = ascq;
5615
5616         return 0;
5617 }
5618
5619 int transport_send_check_condition_and_sense(
5620         struct se_cmd *cmd,
5621         u8 reason,
5622         int from_transport)
5623 {
5624         unsigned char *buffer = cmd->sense_buffer;
5625         unsigned long flags;
5626         int offset;
5627         u8 asc = 0, ascq = 0;
5628
5629         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
5630         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
5631                 spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
5632                 return 0;
5633         }
5634         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
5635         spin_unlock_irqrestore(&T_TASK(cmd)->t_state_lock, flags);
5636
5637         if (!reason && from_transport)
5638                 goto after_reason;
5639
5640         if (!from_transport)
5641                 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
5642         /*
5643          * Data Segment and SenseLength of the fabric response PDU.
5644          *
5645          * TRANSPORT_SENSE_BUFFER is now set to SCSI_SENSE_BUFFERSIZE
5646          * from include/scsi/scsi_cmnd.h
5647          */
5648         offset = CMD_TFO(cmd)->set_fabric_sense_len(cmd,
5649                                 TRANSPORT_SENSE_BUFFER);
5650         /*
5651          * Actual SENSE DATA, see SPC-3 7.23.2  SPC_SENSE_KEY_OFFSET uses
5652          * SENSE KEY values from include/scsi/scsi.h
5653          */
5654         switch (reason) {
5655         case TCM_NON_EXISTENT_LUN:
5656         case TCM_UNSUPPORTED_SCSI_OPCODE:
5657         case TCM_SECTOR_COUNT_TOO_MANY:
5658                 /* CURRENT ERROR */
5659                 buffer[offset] = 0x70;
5660                 /* ILLEGAL REQUEST */
5661                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
5662                 /* INVALID COMMAND OPERATION CODE */
5663                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x20;
5664                 break;
5665         case TCM_UNKNOWN_MODE_PAGE:
5666                 /* CURRENT ERROR */
5667                 buffer[offset] = 0x70;
5668                 /* ILLEGAL REQUEST */
5669                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
5670                 /* INVALID FIELD IN CDB */
5671                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
5672                 break;
5673         case TCM_CHECK_CONDITION_ABORT_CMD:
5674                 /* CURRENT ERROR */
5675                 buffer[offset] = 0x70;
5676                 /* ABORTED COMMAND */
5677                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5678                 /* BUS DEVICE RESET FUNCTION OCCURRED */
5679                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x29;
5680                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x03;
5681                 break;
5682         case TCM_INCORRECT_AMOUNT_OF_DATA:
5683                 /* CURRENT ERROR */
5684                 buffer[offset] = 0x70;
5685                 /* ABORTED COMMAND */
5686                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5687                 /* WRITE ERROR */
5688                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
5689                 /* NOT ENOUGH UNSOLICITED DATA */
5690                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0d;
5691                 break;
5692         case TCM_INVALID_CDB_FIELD:
5693                 /* CURRENT ERROR */
5694                 buffer[offset] = 0x70;
5695                 /* ABORTED COMMAND */
5696                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5697                 /* INVALID FIELD IN CDB */
5698                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
5699                 break;
5700         case TCM_INVALID_PARAMETER_LIST:
5701                 /* CURRENT ERROR */
5702                 buffer[offset] = 0x70;
5703                 /* ABORTED COMMAND */
5704                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5705                 /* INVALID FIELD IN PARAMETER LIST */
5706                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x26;
5707                 break;
5708         case TCM_UNEXPECTED_UNSOLICITED_DATA:
5709                 /* CURRENT ERROR */
5710                 buffer[offset] = 0x70;
5711                 /* ABORTED COMMAND */
5712                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5713                 /* WRITE ERROR */
5714                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
5715                 /* UNEXPECTED_UNSOLICITED_DATA */
5716                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0c;
5717                 break;
5718         case TCM_SERVICE_CRC_ERROR:
5719                 /* CURRENT ERROR */
5720                 buffer[offset] = 0x70;
5721                 /* ABORTED COMMAND */
5722                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5723                 /* PROTOCOL SERVICE CRC ERROR */
5724                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x47;
5725                 /* N/A */
5726                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x05;
5727                 break;
5728         case TCM_SNACK_REJECTED:
5729                 /* CURRENT ERROR */
5730                 buffer[offset] = 0x70;
5731                 /* ABORTED COMMAND */
5732                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5733                 /* READ ERROR */
5734                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x11;
5735                 /* FAILED RETRANSMISSION REQUEST */
5736                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x13;
5737                 break;
5738         case TCM_WRITE_PROTECTED:
5739                 /* CURRENT ERROR */
5740                 buffer[offset] = 0x70;
5741                 /* DATA PROTECT */
5742                 buffer[offset+SPC_SENSE_KEY_OFFSET] = DATA_PROTECT;
5743                 /* WRITE PROTECTED */
5744                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x27;
5745                 break;
5746         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
5747                 /* CURRENT ERROR */
5748                 buffer[offset] = 0x70;
5749                 /* UNIT ATTENTION */
5750                 buffer[offset+SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION;
5751                 core_scsi3_ua_for_check_condition(cmd, &asc, &ascq);
5752                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
5753                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
5754                 break;
5755         case TCM_CHECK_CONDITION_NOT_READY:
5756                 /* CURRENT ERROR */
5757                 buffer[offset] = 0x70;
5758                 /* Not Ready */
5759                 buffer[offset+SPC_SENSE_KEY_OFFSET] = NOT_READY;
5760                 transport_get_sense_codes(cmd, &asc, &ascq);
5761                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
5762                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
5763                 break;
5764         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
5765         default:
5766                 /* CURRENT ERROR */
5767                 buffer[offset] = 0x70;
5768                 /* ILLEGAL REQUEST */
5769                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
5770                 /* LOGICAL UNIT COMMUNICATION FAILURE */
5771                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x80;
5772                 break;
5773         }
5774         /*
5775          * This code uses linux/include/scsi/scsi.h SAM status codes!
5776          */
5777         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
5778         /*
5779          * Automatically padded, this value is encoded in the fabric's
5780          * data_length response PDU containing the SCSI defined sense data.
5781          */
5782         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER + offset;
5783
5784 after_reason:
5785         CMD_TFO(cmd)->queue_status(cmd);
5786         return 0;
5787 }
5788 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
5789
5790 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
5791 {
5792         int ret = 0;
5793
5794         if (atomic_read(&T_TASK(cmd)->t_transport_aborted) != 0) {
5795                 if (!(send_status) ||
5796                      (cmd->se_cmd_flags & SCF_SENT_DELAYED_TAS))
5797                         return 1;
5798 #if 0
5799                 printk(KERN_INFO "Sending delayed SAM_STAT_TASK_ABORTED"
5800                         " status for CDB: 0x%02x ITT: 0x%08x\n",
5801                         T_TASK(cmd)->t_task_cdb[0],
5802                         CMD_TFO(cmd)->get_task_tag(cmd));
5803 #endif
5804                 cmd->se_cmd_flags |= SCF_SENT_DELAYED_TAS;
5805                 CMD_TFO(cmd)->queue_status(cmd);
5806                 ret = 1;
5807         }
5808         return ret;
5809 }
5810 EXPORT_SYMBOL(transport_check_aborted_status);
5811
5812 void transport_send_task_abort(struct se_cmd *cmd)
5813 {
5814         /*
5815          * If there are still expected incoming fabric WRITEs, we wait
5816          * until until they have completed before sending a TASK_ABORTED
5817          * response.  This response with TASK_ABORTED status will be
5818          * queued back to fabric module by transport_check_aborted_status().
5819          */
5820         if (cmd->data_direction == DMA_TO_DEVICE) {
5821                 if (CMD_TFO(cmd)->write_pending_status(cmd) != 0) {
5822                         atomic_inc(&T_TASK(cmd)->t_transport_aborted);
5823                         smp_mb__after_atomic_inc();
5824                         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
5825                         transport_new_cmd_failure(cmd);
5826                         return;
5827                 }
5828         }
5829         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
5830 #if 0
5831         printk(KERN_INFO "Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x,"
5832                 " ITT: 0x%08x\n", T_TASK(cmd)->t_task_cdb[0],
5833                 CMD_TFO(cmd)->get_task_tag(cmd));
5834 #endif
5835         CMD_TFO(cmd)->queue_status(cmd);
5836 }
5837
5838 /*      transport_generic_do_tmr():
5839  *
5840  *
5841  */
5842 int transport_generic_do_tmr(struct se_cmd *cmd)
5843 {
5844         struct se_cmd *ref_cmd;
5845         struct se_device *dev = SE_DEV(cmd);
5846         struct se_tmr_req *tmr = cmd->se_tmr_req;
5847         int ret;
5848
5849         switch (tmr->function) {
5850         case ABORT_TASK:
5851                 ref_cmd = tmr->ref_cmd;
5852                 tmr->response = TMR_FUNCTION_REJECTED;
5853                 break;
5854         case ABORT_TASK_SET:
5855         case CLEAR_ACA:
5856         case CLEAR_TASK_SET:
5857                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
5858                 break;
5859         case LUN_RESET:
5860                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
5861                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
5862                                          TMR_FUNCTION_REJECTED;
5863                 break;
5864 #if 0
5865         case TARGET_WARM_RESET:
5866                 transport_generic_host_reset(dev->se_hba);
5867                 tmr->response = TMR_FUNCTION_REJECTED;
5868                 break;
5869         case TARGET_COLD_RESET:
5870                 transport_generic_host_reset(dev->se_hba);
5871                 transport_generic_cold_reset(dev->se_hba);
5872                 tmr->response = TMR_FUNCTION_REJECTED;
5873                 break;
5874 #endif
5875         default:
5876                 printk(KERN_ERR "Uknown TMR function: 0x%02x.\n",
5877                                 tmr->function);
5878                 tmr->response = TMR_FUNCTION_REJECTED;
5879                 break;
5880         }
5881
5882         cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
5883         CMD_TFO(cmd)->queue_tm_rsp(cmd);
5884
5885         transport_cmd_check_stop(cmd, 2, 0);
5886         return 0;
5887 }
5888
5889 /*
5890  *      Called with spin_lock_irq(&dev->execute_task_lock); held
5891  *
5892  */
5893 static struct se_task *
5894 transport_get_task_from_state_list(struct se_device *dev)
5895 {
5896         struct se_task *task;
5897
5898         if (list_empty(&dev->state_task_list))
5899                 return NULL;
5900
5901         list_for_each_entry(task, &dev->state_task_list, t_state_list)
5902                 break;
5903
5904         list_del(&task->t_state_list);
5905         atomic_set(&task->task_state_active, 0);
5906
5907         return task;
5908 }
5909
5910 static void transport_processing_shutdown(struct se_device *dev)
5911 {
5912         struct se_cmd *cmd;
5913         struct se_queue_req *qr;
5914         struct se_task *task;
5915         u8 state;
5916         unsigned long flags;
5917         /*
5918          * Empty the struct se_device's struct se_task state list.
5919          */
5920         spin_lock_irqsave(&dev->execute_task_lock, flags);
5921         while ((task = transport_get_task_from_state_list(dev))) {
5922                 if (!(TASK_CMD(task))) {
5923                         printk(KERN_ERR "TASK_CMD(task) is NULL!\n");
5924                         continue;
5925                 }
5926                 cmd = TASK_CMD(task);
5927
5928                 if (!T_TASK(cmd)) {
5929                         printk(KERN_ERR "T_TASK(cmd) is NULL for task: %p cmd:"
5930                                 " %p ITT: 0x%08x\n", task, cmd,
5931                                 CMD_TFO(cmd)->get_task_tag(cmd));
5932                         continue;
5933                 }
5934                 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
5935
5936                 spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
5937
5938                 DEBUG_DO("PT: cmd: %p task: %p ITT/CmdSN: 0x%08x/0x%08x,"
5939                         " i_state/def_i_state: %d/%d, t_state/def_t_state:"
5940                         " %d/%d cdb: 0x%02x\n", cmd, task,
5941                         CMD_TFO(cmd)->get_task_tag(cmd), cmd->cmd_sn,
5942                         CMD_TFO(cmd)->get_cmd_state(cmd), cmd->deferred_i_state,
5943                         cmd->t_state, cmd->deferred_t_state,
5944                         T_TASK(cmd)->t_task_cdb[0]);
5945                 DEBUG_DO("PT: ITT[0x%08x] - t_task_cdbs: %d t_task_cdbs_left:"
5946                         " %d t_task_cdbs_sent: %d -- t_transport_active: %d"
5947                         " t_transport_stop: %d t_transport_sent: %d\n",
5948                         CMD_TFO(cmd)->get_task_tag(cmd),
5949                         T_TASK(cmd)->t_task_cdbs,
5950                         atomic_read(&T_TASK(cmd)->t_task_cdbs_left),
5951                         atomic_read(&T_TASK(cmd)->t_task_cdbs_sent),
5952                         atomic_read(&T_TASK(cmd)->t_transport_active),
5953                         atomic_read(&T_TASK(cmd)->t_transport_stop),
5954                         atomic_read(&T_TASK(cmd)->t_transport_sent));
5955
5956                 if (atomic_read(&task->task_active)) {
5957                         atomic_set(&task->task_stop, 1);
5958                         spin_unlock_irqrestore(
5959                                 &T_TASK(cmd)->t_state_lock, flags);
5960
5961                         DEBUG_DO("Waiting for task: %p to shutdown for dev:"
5962                                 " %p\n", task, dev);
5963                         wait_for_completion(&task->task_stop_comp);
5964                         DEBUG_DO("Completed task: %p shutdown for dev: %p\n",
5965                                 task, dev);
5966
5967                         spin_lock_irqsave(&T_TASK(cmd)->t_state_lock, flags);
5968                         atomic_dec(&T_TASK(cmd)->t_task_cdbs_left);
5969
5970                         atomic_set(&task->task_active, 0);
5971                         atomic_set(&task->task_stop, 0);
5972                 } else {
5973                         if (atomic_read(&task->task_execute_queue) != 0)
5974                                 transport_remove_task_from_execute_queue(task, dev);
5975                 }
5976                 __transport_stop_task_timer(task, &flags);
5977
5978                 if (!(atomic_dec_and_test(&T_TASK(cmd)->t_task_cdbs_ex_left))) {
5979                         spin_unlock_irqrestore(
5980                                         &T_TASK(cmd)->t_state_lock, flags);
5981
5982                         DEBUG_DO("Skipping task: %p, dev: %p for"
5983                                 " t_task_cdbs_ex_left: %d\n", task, dev,
5984                                 atomic_read(&T_TASK(cmd)->t_task_cdbs_ex_left));
5985
5986                         spin_lock_irqsave(&dev->execute_task_lock, flags);
5987                         continue;
5988                 }
5989
5990                 if (atomic_read(&T_TASK(cmd)->t_transport_active)) {
5991                         DEBUG_DO("got t_transport_active = 1 for task: %p, dev:"
5992                                         " %p\n", task, dev);
5993
5994                         if (atomic_read(&T_TASK(cmd)->t_fe_count)) {
5995                                 spin_unlock_irqrestore(
5996                                         &T_TASK(cmd)->t_state_lock, flags);
5997                                 transport_send_check_condition_and_sense(
5998                                         cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE,
5999                                         0);
6000                                 transport_remove_cmd_from_queue(cmd,
6001                                         SE_DEV(cmd)->dev_queue_obj);
6002
6003                                 transport_lun_remove_cmd(cmd);
6004                                 transport_cmd_check_stop(cmd, 1, 0);
6005                         } else {
6006                                 spin_unlock_irqrestore(
6007                                         &T_TASK(cmd)->t_state_lock, flags);
6008
6009                                 transport_remove_cmd_from_queue(cmd,
6010                                         SE_DEV(cmd)->dev_queue_obj);
6011
6012                                 transport_lun_remove_cmd(cmd);
6013
6014                                 if (transport_cmd_check_stop(cmd, 1, 0))
6015                                         transport_generic_remove(cmd, 0, 0);
6016                         }
6017
6018                         spin_lock_irqsave(&dev->execute_task_lock, flags);
6019                         continue;
6020                 }
6021                 DEBUG_DO("Got t_transport_active = 0 for task: %p, dev: %p\n",
6022                                 task, dev);
6023
6024                 if (atomic_read(&T_TASK(cmd)->t_fe_count)) {
6025                         spin_unlock_irqrestore(
6026                                 &T_TASK(cmd)->t_state_lock, flags);
6027                         transport_send_check_condition_and_sense(cmd,
6028                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
6029                         transport_remove_cmd_from_queue(cmd,
6030                                 SE_DEV(cmd)->dev_queue_obj);
6031
6032                         transport_lun_remove_cmd(cmd);
6033                         transport_cmd_check_stop(cmd, 1, 0);
6034                 } else {
6035                         spin_unlock_irqrestore(
6036                                 &T_TASK(cmd)->t_state_lock, flags);
6037
6038                         transport_remove_cmd_from_queue(cmd,
6039                                 SE_DEV(cmd)->dev_queue_obj);
6040                         transport_lun_remove_cmd(cmd);
6041
6042                         if (transport_cmd_check_stop(cmd, 1, 0))
6043                                 transport_generic_remove(cmd, 0, 0);
6044                 }
6045
6046                 spin_lock_irqsave(&dev->execute_task_lock, flags);
6047         }
6048         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
6049         /*
6050          * Empty the struct se_device's struct se_cmd list.
6051          */
6052         spin_lock_irqsave(&dev->dev_queue_obj->cmd_queue_lock, flags);
6053         while ((qr = __transport_get_qr_from_queue(dev->dev_queue_obj))) {
6054                 spin_unlock_irqrestore(
6055                                 &dev->dev_queue_obj->cmd_queue_lock, flags);
6056                 cmd = (struct se_cmd *)qr->cmd;
6057                 state = qr->state;
6058                 kfree(qr);
6059
6060                 DEBUG_DO("From Device Queue: cmd: %p t_state: %d\n",
6061                                 cmd, state);
6062
6063                 if (atomic_read(&T_TASK(cmd)->t_fe_count)) {
6064                         transport_send_check_condition_and_sense(cmd,
6065                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
6066
6067                         transport_lun_remove_cmd(cmd);
6068                         transport_cmd_check_stop(cmd, 1, 0);
6069                 } else {
6070                         transport_lun_remove_cmd(cmd);
6071                         if (transport_cmd_check_stop(cmd, 1, 0))
6072                                 transport_generic_remove(cmd, 0, 0);
6073                 }
6074                 spin_lock_irqsave(&dev->dev_queue_obj->cmd_queue_lock, flags);
6075         }
6076         spin_unlock_irqrestore(&dev->dev_queue_obj->cmd_queue_lock, flags);
6077 }
6078
6079 /*      transport_processing_thread():
6080  *
6081  *
6082  */
6083 static int transport_processing_thread(void *param)
6084 {
6085         int ret, t_state;
6086         struct se_cmd *cmd;
6087         struct se_device *dev = (struct se_device *) param;
6088         struct se_queue_req *qr;
6089
6090         set_user_nice(current, -20);
6091
6092         while (!kthread_should_stop()) {
6093                 ret = wait_event_interruptible(dev->dev_queue_obj->thread_wq,
6094                                 atomic_read(&dev->dev_queue_obj->queue_cnt) ||
6095                                 kthread_should_stop());
6096                 if (ret < 0)
6097                         goto out;
6098
6099                 spin_lock_irq(&dev->dev_status_lock);
6100                 if (dev->dev_status & TRANSPORT_DEVICE_SHUTDOWN) {
6101                         spin_unlock_irq(&dev->dev_status_lock);
6102                         transport_processing_shutdown(dev);
6103                         continue;
6104                 }
6105                 spin_unlock_irq(&dev->dev_status_lock);
6106
6107 get_cmd:
6108                 __transport_execute_tasks(dev);
6109
6110                 qr = transport_get_qr_from_queue(dev->dev_queue_obj);
6111                 if (!(qr))
6112                         continue;
6113
6114                 cmd = (struct se_cmd *)qr->cmd;
6115                 t_state = qr->state;
6116                 kfree(qr);
6117
6118                 switch (t_state) {
6119                 case TRANSPORT_NEW_CMD_MAP:
6120                         if (!(CMD_TFO(cmd)->new_cmd_map)) {
6121                                 printk(KERN_ERR "CMD_TFO(cmd)->new_cmd_map is"
6122                                         " NULL for TRANSPORT_NEW_CMD_MAP\n");
6123                                 BUG();
6124                         }
6125                         ret = CMD_TFO(cmd)->new_cmd_map(cmd);
6126                         if (ret < 0) {
6127                                 cmd->transport_error_status = ret;
6128                                 transport_generic_request_failure(cmd, NULL,
6129                                                 0, (cmd->data_direction !=
6130                                                     DMA_TO_DEVICE));
6131                                 break;
6132                         }
6133                         /* Fall through */
6134                 case TRANSPORT_NEW_CMD:
6135                         ret = transport_generic_new_cmd(cmd);
6136                         if (ret < 0) {
6137                                 cmd->transport_error_status = ret;
6138                                 transport_generic_request_failure(cmd, NULL,
6139                                         0, (cmd->data_direction !=
6140                                          DMA_TO_DEVICE));
6141                         }
6142                         break;
6143                 case TRANSPORT_PROCESS_WRITE:
6144                         transport_generic_process_write(cmd);
6145                         break;
6146                 case TRANSPORT_COMPLETE_OK:
6147                         transport_stop_all_task_timers(cmd);
6148                         transport_generic_complete_ok(cmd);
6149                         break;
6150                 case TRANSPORT_REMOVE:
6151                         transport_generic_remove(cmd, 1, 0);
6152                         break;
6153                 case TRANSPORT_FREE_CMD_INTR:
6154                         transport_generic_free_cmd(cmd, 0, 1, 0);
6155                         break;
6156                 case TRANSPORT_PROCESS_TMR:
6157                         transport_generic_do_tmr(cmd);
6158                         break;
6159                 case TRANSPORT_COMPLETE_FAILURE:
6160                         transport_generic_request_failure(cmd, NULL, 1, 1);
6161                         break;
6162                 case TRANSPORT_COMPLETE_TIMEOUT:
6163                         transport_stop_all_task_timers(cmd);
6164                         transport_generic_request_timeout(cmd);
6165                         break;
6166                 default:
6167                         printk(KERN_ERR "Unknown t_state: %d deferred_t_state:"
6168                                 " %d for ITT: 0x%08x i_state: %d on SE LUN:"
6169                                 " %u\n", t_state, cmd->deferred_t_state,
6170                                 CMD_TFO(cmd)->get_task_tag(cmd),
6171                                 CMD_TFO(cmd)->get_cmd_state(cmd),
6172                                 SE_LUN(cmd)->unpacked_lun);
6173                         BUG();
6174                 }
6175
6176                 goto get_cmd;
6177         }
6178
6179 out:
6180         transport_release_all_cmds(dev);
6181         dev->process_thread = NULL;
6182         return 0;
6183 }