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