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