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