target: remove the unused SCF_* flags
[pandora-kernel.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 release_to_pool, 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, 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, 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         transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD);
1846         return 0;
1847 }
1848 EXPORT_SYMBOL(transport_generic_handle_cdb);
1849
1850 /*
1851  * Used by fabric module frontends defining a TFO->new_cmd_map() caller
1852  * to  queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD_MAP in order to
1853  * complete setup in TCM process context w/ TFO->new_cmd_map().
1854  */
1855 int transport_generic_handle_cdb_map(
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
1864         transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD_MAP);
1865         return 0;
1866 }
1867 EXPORT_SYMBOL(transport_generic_handle_cdb_map);
1868
1869 /*      transport_generic_handle_data():
1870  *
1871  *
1872  */
1873 int transport_generic_handle_data(
1874         struct se_cmd *cmd)
1875 {
1876         /*
1877          * For the software fabric case, then we assume the nexus is being
1878          * failed/shutdown when signals are pending from the kthread context
1879          * caller, so we return a failure.  For the HW target mode case running
1880          * in interrupt code, the signal_pending() check is skipped.
1881          */
1882         if (!in_interrupt() && signal_pending(current))
1883                 return -EPERM;
1884         /*
1885          * If the received CDB has aleady been ABORTED by the generic
1886          * target engine, we now call transport_check_aborted_status()
1887          * to queue any delated TASK_ABORTED status for the received CDB to the
1888          * fabric module as we are expecting no further incoming DATA OUT
1889          * sequences at this point.
1890          */
1891         if (transport_check_aborted_status(cmd, 1) != 0)
1892                 return 0;
1893
1894         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_WRITE);
1895         return 0;
1896 }
1897 EXPORT_SYMBOL(transport_generic_handle_data);
1898
1899 /*      transport_generic_handle_tmr():
1900  *
1901  *
1902  */
1903 int transport_generic_handle_tmr(
1904         struct se_cmd *cmd)
1905 {
1906         /*
1907          * This is needed for early exceptions.
1908          */
1909         cmd->transport_wait_for_tasks = &transport_generic_wait_for_tasks;
1910
1911         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_TMR);
1912         return 0;
1913 }
1914 EXPORT_SYMBOL(transport_generic_handle_tmr);
1915
1916 void transport_generic_free_cmd_intr(
1917         struct se_cmd *cmd)
1918 {
1919         transport_add_cmd_to_queue(cmd, TRANSPORT_FREE_CMD_INTR);
1920 }
1921 EXPORT_SYMBOL(transport_generic_free_cmd_intr);
1922
1923 static int transport_stop_tasks_for_cmd(struct se_cmd *cmd)
1924 {
1925         struct se_task *task, *task_tmp;
1926         unsigned long flags;
1927         int ret = 0;
1928
1929         DEBUG_TS("ITT[0x%08x] - Stopping tasks\n",
1930                 cmd->se_tfo->get_task_tag(cmd));
1931
1932         /*
1933          * No tasks remain in the execution queue
1934          */
1935         spin_lock_irqsave(&cmd->t_state_lock, flags);
1936         list_for_each_entry_safe(task, task_tmp,
1937                                 &cmd->t_task_list, t_list) {
1938                 DEBUG_TS("task_no[%d] - Processing task %p\n",
1939                                 task->task_no, task);
1940                 /*
1941                  * If the struct se_task has not been sent and is not active,
1942                  * remove the struct se_task from the execution queue.
1943                  */
1944                 if (!atomic_read(&task->task_sent) &&
1945                     !atomic_read(&task->task_active)) {
1946                         spin_unlock_irqrestore(&cmd->t_state_lock,
1947                                         flags);
1948                         transport_remove_task_from_execute_queue(task,
1949                                         task->se_dev);
1950
1951                         DEBUG_TS("task_no[%d] - Removed from execute queue\n",
1952                                 task->task_no);
1953                         spin_lock_irqsave(&cmd->t_state_lock, flags);
1954                         continue;
1955                 }
1956
1957                 /*
1958                  * If the struct se_task is active, sleep until it is returned
1959                  * from the plugin.
1960                  */
1961                 if (atomic_read(&task->task_active)) {
1962                         atomic_set(&task->task_stop, 1);
1963                         spin_unlock_irqrestore(&cmd->t_state_lock,
1964                                         flags);
1965
1966                         DEBUG_TS("task_no[%d] - Waiting to complete\n",
1967                                 task->task_no);
1968                         wait_for_completion(&task->task_stop_comp);
1969                         DEBUG_TS("task_no[%d] - Stopped successfully\n",
1970                                 task->task_no);
1971
1972                         spin_lock_irqsave(&cmd->t_state_lock, flags);
1973                         atomic_dec(&cmd->t_task_cdbs_left);
1974
1975                         atomic_set(&task->task_active, 0);
1976                         atomic_set(&task->task_stop, 0);
1977                 } else {
1978                         DEBUG_TS("task_no[%d] - Did nothing\n", task->task_no);
1979                         ret++;
1980                 }
1981
1982                 __transport_stop_task_timer(task, &flags);
1983         }
1984         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1985
1986         return ret;
1987 }
1988
1989 /*
1990  * Handle SAM-esque emulation for generic transport request failures.
1991  */
1992 static void transport_generic_request_failure(
1993         struct se_cmd *cmd,
1994         struct se_device *dev,
1995         int complete,
1996         int sc)
1997 {
1998         DEBUG_GRF("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
1999                 " CDB: 0x%02x\n", cmd, cmd->se_tfo->get_task_tag(cmd),
2000                 cmd->t_task_cdb[0]);
2001         DEBUG_GRF("-----[ i_state: %d t_state/def_t_state:"
2002                 " %d/%d transport_error_status: %d\n",
2003                 cmd->se_tfo->get_cmd_state(cmd),
2004                 cmd->t_state, cmd->deferred_t_state,
2005                 cmd->transport_error_status);
2006         DEBUG_GRF("-----[ t_task_cdbs: %d t_task_cdbs_left: %d"
2007                 " t_task_cdbs_sent: %d t_task_cdbs_ex_left: %d --"
2008                 " t_transport_active: %d t_transport_stop: %d"
2009                 " t_transport_sent: %d\n", cmd->t_task_cdbs,
2010                 atomic_read(&cmd->t_task_cdbs_left),
2011                 atomic_read(&cmd->t_task_cdbs_sent),
2012                 atomic_read(&cmd->t_task_cdbs_ex_left),
2013                 atomic_read(&cmd->t_transport_active),
2014                 atomic_read(&cmd->t_transport_stop),
2015                 atomic_read(&cmd->t_transport_sent));
2016
2017         transport_stop_all_task_timers(cmd);
2018
2019         if (dev)
2020                 atomic_inc(&dev->depth_left);
2021         /*
2022          * For SAM Task Attribute emulation for failed struct se_cmd
2023          */
2024         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
2025                 transport_complete_task_attr(cmd);
2026
2027         if (complete) {
2028                 transport_direct_request_timeout(cmd);
2029                 cmd->transport_error_status = PYX_TRANSPORT_LU_COMM_FAILURE;
2030         }
2031
2032         switch (cmd->transport_error_status) {
2033         case PYX_TRANSPORT_UNKNOWN_SAM_OPCODE:
2034                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
2035                 break;
2036         case PYX_TRANSPORT_REQ_TOO_MANY_SECTORS:
2037                 cmd->scsi_sense_reason = TCM_SECTOR_COUNT_TOO_MANY;
2038                 break;
2039         case PYX_TRANSPORT_INVALID_CDB_FIELD:
2040                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
2041                 break;
2042         case PYX_TRANSPORT_INVALID_PARAMETER_LIST:
2043                 cmd->scsi_sense_reason = TCM_INVALID_PARAMETER_LIST;
2044                 break;
2045         case PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES:
2046                 if (!sc)
2047                         transport_new_cmd_failure(cmd);
2048                 /*
2049                  * Currently for PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES,
2050                  * we force this session to fall back to session
2051                  * recovery.
2052                  */
2053                 cmd->se_tfo->fall_back_to_erl0(cmd->se_sess);
2054                 cmd->se_tfo->stop_session(cmd->se_sess, 0, 0);
2055
2056                 goto check_stop;
2057         case PYX_TRANSPORT_LU_COMM_FAILURE:
2058         case PYX_TRANSPORT_ILLEGAL_REQUEST:
2059                 cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2060                 break;
2061         case PYX_TRANSPORT_UNKNOWN_MODE_PAGE:
2062                 cmd->scsi_sense_reason = TCM_UNKNOWN_MODE_PAGE;
2063                 break;
2064         case PYX_TRANSPORT_WRITE_PROTECTED:
2065                 cmd->scsi_sense_reason = TCM_WRITE_PROTECTED;
2066                 break;
2067         case PYX_TRANSPORT_RESERVATION_CONFLICT:
2068                 /*
2069                  * No SENSE Data payload for this case, set SCSI Status
2070                  * and queue the response to $FABRIC_MOD.
2071                  *
2072                  * Uses linux/include/scsi/scsi.h SAM status codes defs
2073                  */
2074                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2075                 /*
2076                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
2077                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
2078                  * CONFLICT STATUS.
2079                  *
2080                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
2081                  */
2082                 if (cmd->se_sess &&
2083                     cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
2084                         core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
2085                                 cmd->orig_fe_lun, 0x2C,
2086                                 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
2087
2088                 cmd->se_tfo->queue_status(cmd);
2089                 goto check_stop;
2090         case PYX_TRANSPORT_USE_SENSE_REASON:
2091                 /*
2092                  * struct se_cmd->scsi_sense_reason already set
2093                  */
2094                 break;
2095         default:
2096                 printk(KERN_ERR "Unknown transport error for CDB 0x%02x: %d\n",
2097                         cmd->t_task_cdb[0],
2098                         cmd->transport_error_status);
2099                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
2100                 break;
2101         }
2102
2103         if (!sc)
2104                 transport_new_cmd_failure(cmd);
2105         else
2106                 transport_send_check_condition_and_sense(cmd,
2107                         cmd->scsi_sense_reason, 0);
2108 check_stop:
2109         transport_lun_remove_cmd(cmd);
2110         if (!(transport_cmd_check_stop_to_fabric(cmd)))
2111                 ;
2112 }
2113
2114 static void transport_direct_request_timeout(struct se_cmd *cmd)
2115 {
2116         unsigned long flags;
2117
2118         spin_lock_irqsave(&cmd->t_state_lock, flags);
2119         if (!(atomic_read(&cmd->t_transport_timeout))) {
2120                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2121                 return;
2122         }
2123         if (atomic_read(&cmd->t_task_cdbs_timeout_left)) {
2124                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2125                 return;
2126         }
2127
2128         atomic_sub(atomic_read(&cmd->t_transport_timeout),
2129                    &cmd->t_se_count);
2130         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2131 }
2132
2133 static void transport_generic_request_timeout(struct se_cmd *cmd)
2134 {
2135         unsigned long flags;
2136
2137         /*
2138          * Reset cmd->t_se_count to allow transport_generic_remove()
2139          * to allow last call to free memory resources.
2140          */
2141         spin_lock_irqsave(&cmd->t_state_lock, flags);
2142         if (atomic_read(&cmd->t_transport_timeout) > 1) {
2143                 int tmp = (atomic_read(&cmd->t_transport_timeout) - 1);
2144
2145                 atomic_sub(tmp, &cmd->t_se_count);
2146         }
2147         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2148
2149         transport_generic_remove(cmd, 0, 0);
2150 }
2151
2152 static int
2153 transport_generic_allocate_buf(struct se_cmd *cmd, u32 data_length)
2154 {
2155         unsigned char *buf;
2156
2157         buf = kzalloc(data_length, GFP_KERNEL);
2158         if (!(buf)) {
2159                 printk(KERN_ERR "Unable to allocate memory for buffer\n");
2160                 return -ENOMEM;
2161         }
2162
2163         cmd->t_tasks_se_num = 0;
2164         cmd->t_task_buf = buf;
2165
2166         return 0;
2167 }
2168
2169 static inline u32 transport_lba_21(unsigned char *cdb)
2170 {
2171         return ((cdb[1] & 0x1f) << 16) | (cdb[2] << 8) | cdb[3];
2172 }
2173
2174 static inline u32 transport_lba_32(unsigned char *cdb)
2175 {
2176         return (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
2177 }
2178
2179 static inline unsigned long long transport_lba_64(unsigned char *cdb)
2180 {
2181         unsigned int __v1, __v2;
2182
2183         __v1 = (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
2184         __v2 = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
2185
2186         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
2187 }
2188
2189 /*
2190  * For VARIABLE_LENGTH_CDB w/ 32 byte extended CDBs
2191  */
2192 static inline unsigned long long transport_lba_64_ext(unsigned char *cdb)
2193 {
2194         unsigned int __v1, __v2;
2195
2196         __v1 = (cdb[12] << 24) | (cdb[13] << 16) | (cdb[14] << 8) | cdb[15];
2197         __v2 = (cdb[16] << 24) | (cdb[17] << 16) | (cdb[18] << 8) | cdb[19];
2198
2199         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
2200 }
2201
2202 static void transport_set_supported_SAM_opcode(struct se_cmd *se_cmd)
2203 {
2204         unsigned long flags;
2205
2206         spin_lock_irqsave(&se_cmd->t_state_lock, flags);
2207         se_cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
2208         spin_unlock_irqrestore(&se_cmd->t_state_lock, flags);
2209 }
2210
2211 /*
2212  * Called from interrupt context.
2213  */
2214 static void transport_task_timeout_handler(unsigned long data)
2215 {
2216         struct se_task *task = (struct se_task *)data;
2217         struct se_cmd *cmd = task->task_se_cmd;
2218         unsigned long flags;
2219
2220         DEBUG_TT("transport task timeout fired! task: %p cmd: %p\n", task, cmd);
2221
2222         spin_lock_irqsave(&cmd->t_state_lock, flags);
2223         if (task->task_flags & TF_STOP) {
2224                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2225                 return;
2226         }
2227         task->task_flags &= ~TF_RUNNING;
2228
2229         /*
2230          * Determine if transport_complete_task() has already been called.
2231          */
2232         if (!(atomic_read(&task->task_active))) {
2233                 DEBUG_TT("transport task: %p cmd: %p timeout task_active"
2234                                 " == 0\n", task, cmd);
2235                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2236                 return;
2237         }
2238
2239         atomic_inc(&cmd->t_se_count);
2240         atomic_inc(&cmd->t_transport_timeout);
2241         cmd->t_tasks_failed = 1;
2242
2243         atomic_set(&task->task_timeout, 1);
2244         task->task_error_status = PYX_TRANSPORT_TASK_TIMEOUT;
2245         task->task_scsi_status = 1;
2246
2247         if (atomic_read(&task->task_stop)) {
2248                 DEBUG_TT("transport task: %p cmd: %p timeout task_stop"
2249                                 " == 1\n", task, cmd);
2250                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2251                 complete(&task->task_stop_comp);
2252                 return;
2253         }
2254
2255         if (!(atomic_dec_and_test(&cmd->t_task_cdbs_left))) {
2256                 DEBUG_TT("transport task: %p cmd: %p timeout non zero"
2257                                 " t_task_cdbs_left\n", task, cmd);
2258                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2259                 return;
2260         }
2261         DEBUG_TT("transport task: %p cmd: %p timeout ZERO t_task_cdbs_left\n",
2262                         task, cmd);
2263
2264         cmd->t_state = TRANSPORT_COMPLETE_FAILURE;
2265         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2266
2267         transport_add_cmd_to_queue(cmd, TRANSPORT_COMPLETE_FAILURE);
2268 }
2269
2270 /*
2271  * Called with cmd->t_state_lock held.
2272  */
2273 static void transport_start_task_timer(struct se_task *task)
2274 {
2275         struct se_device *dev = task->se_dev;
2276         int timeout;
2277
2278         if (task->task_flags & TF_RUNNING)
2279                 return;
2280         /*
2281          * If the task_timeout is disabled, exit now.
2282          */
2283         timeout = dev->se_sub_dev->se_dev_attrib.task_timeout;
2284         if (!(timeout))
2285                 return;
2286
2287         init_timer(&task->task_timer);
2288         task->task_timer.expires = (get_jiffies_64() + timeout * HZ);
2289         task->task_timer.data = (unsigned long) task;
2290         task->task_timer.function = transport_task_timeout_handler;
2291
2292         task->task_flags |= TF_RUNNING;
2293         add_timer(&task->task_timer);
2294 #if 0
2295         printk(KERN_INFO "Starting task timer for cmd: %p task: %p seconds:"
2296                 " %d\n", task->task_se_cmd, task, timeout);
2297 #endif
2298 }
2299
2300 /*
2301  * Called with spin_lock_irq(&cmd->t_state_lock) held.
2302  */
2303 void __transport_stop_task_timer(struct se_task *task, unsigned long *flags)
2304 {
2305         struct se_cmd *cmd = task->task_se_cmd;
2306
2307         if (!(task->task_flags & TF_RUNNING))
2308                 return;
2309
2310         task->task_flags |= TF_STOP;
2311         spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
2312
2313         del_timer_sync(&task->task_timer);
2314
2315         spin_lock_irqsave(&cmd->t_state_lock, *flags);
2316         task->task_flags &= ~TF_RUNNING;
2317         task->task_flags &= ~TF_STOP;
2318 }
2319
2320 static void transport_stop_all_task_timers(struct se_cmd *cmd)
2321 {
2322         struct se_task *task = NULL, *task_tmp;
2323         unsigned long flags;
2324
2325         spin_lock_irqsave(&cmd->t_state_lock, flags);
2326         list_for_each_entry_safe(task, task_tmp,
2327                                 &cmd->t_task_list, t_list)
2328                 __transport_stop_task_timer(task, &flags);
2329         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2330 }
2331
2332 static inline int transport_tcq_window_closed(struct se_device *dev)
2333 {
2334         if (dev->dev_tcq_window_closed++ <
2335                         PYX_TRANSPORT_WINDOW_CLOSED_THRESHOLD) {
2336                 msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_SHORT);
2337         } else
2338                 msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_LONG);
2339
2340         wake_up_interruptible(&dev->dev_queue_obj.thread_wq);
2341         return 0;
2342 }
2343
2344 /*
2345  * Called from Fabric Module context from transport_execute_tasks()
2346  *
2347  * The return of this function determins if the tasks from struct se_cmd
2348  * get added to the execution queue in transport_execute_tasks(),
2349  * or are added to the delayed or ordered lists here.
2350  */
2351 static inline int transport_execute_task_attr(struct se_cmd *cmd)
2352 {
2353         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
2354                 return 1;
2355         /*
2356          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
2357          * to allow the passed struct se_cmd list of tasks to the front of the list.
2358          */
2359          if (cmd->sam_task_attr == MSG_HEAD_TAG) {
2360                 atomic_inc(&cmd->se_dev->dev_hoq_count);
2361                 smp_mb__after_atomic_inc();
2362                 DEBUG_STA("Added HEAD_OF_QUEUE for CDB:"
2363                         " 0x%02x, se_ordered_id: %u\n",
2364                         cmd->_task_cdb[0],
2365                         cmd->se_ordered_id);
2366                 return 1;
2367         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
2368                 spin_lock(&cmd->se_dev->ordered_cmd_lock);
2369                 list_add_tail(&cmd->se_ordered_node,
2370                                 &cmd->se_dev->ordered_cmd_list);
2371                 spin_unlock(&cmd->se_dev->ordered_cmd_lock);
2372
2373                 atomic_inc(&cmd->se_dev->dev_ordered_sync);
2374                 smp_mb__after_atomic_inc();
2375
2376                 DEBUG_STA("Added ORDERED for CDB: 0x%02x to ordered"
2377                                 " list, se_ordered_id: %u\n",
2378                                 cmd->t_task_cdb[0],
2379                                 cmd->se_ordered_id);
2380                 /*
2381                  * Add ORDERED command to tail of execution queue if
2382                  * no other older commands exist that need to be
2383                  * completed first.
2384                  */
2385                 if (!(atomic_read(&cmd->se_dev->simple_cmds)))
2386                         return 1;
2387         } else {
2388                 /*
2389                  * For SIMPLE and UNTAGGED Task Attribute commands
2390                  */
2391                 atomic_inc(&cmd->se_dev->simple_cmds);
2392                 smp_mb__after_atomic_inc();
2393         }
2394         /*
2395          * Otherwise if one or more outstanding ORDERED task attribute exist,
2396          * add the dormant task(s) built for the passed struct se_cmd to the
2397          * execution queue and become in Active state for this struct se_device.
2398          */
2399         if (atomic_read(&cmd->se_dev->dev_ordered_sync) != 0) {
2400                 /*
2401                  * Otherwise, add cmd w/ tasks to delayed cmd queue that
2402                  * will be drained upon completion of HEAD_OF_QUEUE task.
2403                  */
2404                 spin_lock(&cmd->se_dev->delayed_cmd_lock);
2405                 cmd->se_cmd_flags |= SCF_DELAYED_CMD_FROM_SAM_ATTR;
2406                 list_add_tail(&cmd->se_delayed_node,
2407                                 &cmd->se_dev->delayed_cmd_list);
2408                 spin_unlock(&cmd->se_dev->delayed_cmd_lock);
2409
2410                 DEBUG_STA("Added CDB: 0x%02x Task Attr: 0x%02x to"
2411                         " delayed CMD list, se_ordered_id: %u\n",
2412                         cmd->t_task_cdb[0], cmd->sam_task_attr,
2413                         cmd->se_ordered_id);
2414                 /*
2415                  * Return zero to let transport_execute_tasks() know
2416                  * not to add the delayed tasks to the execution list.
2417                  */
2418                 return 0;
2419         }
2420         /*
2421          * Otherwise, no ORDERED task attributes exist..
2422          */
2423         return 1;
2424 }
2425
2426 /*
2427  * Called from fabric module context in transport_generic_new_cmd() and
2428  * transport_generic_process_write()
2429  */
2430 static int transport_execute_tasks(struct se_cmd *cmd)
2431 {
2432         int add_tasks;
2433
2434         if (se_dev_check_online(cmd->se_orig_obj_ptr) != 0) {
2435                 cmd->transport_error_status = PYX_TRANSPORT_LU_COMM_FAILURE;
2436                 transport_generic_request_failure(cmd, NULL, 0, 1);
2437                 return 0;
2438         }
2439
2440         /*
2441          * Call transport_cmd_check_stop() to see if a fabric exception
2442          * has occurred that prevents execution.
2443          */
2444         if (!(transport_cmd_check_stop(cmd, 0, TRANSPORT_PROCESSING))) {
2445                 /*
2446                  * Check for SAM Task Attribute emulation and HEAD_OF_QUEUE
2447                  * attribute for the tasks of the received struct se_cmd CDB
2448                  */
2449                 add_tasks = transport_execute_task_attr(cmd);
2450                 if (!add_tasks)
2451                         goto execute_tasks;
2452                 /*
2453                  * This calls transport_add_tasks_from_cmd() to handle
2454                  * HEAD_OF_QUEUE ordering for SAM Task Attribute emulation
2455                  * (if enabled) in __transport_add_task_to_execute_queue() and
2456                  * transport_add_task_check_sam_attr().
2457                  */
2458                 transport_add_tasks_from_cmd(cmd);
2459         }
2460         /*
2461          * Kick the execution queue for the cmd associated struct se_device
2462          * storage object.
2463          */
2464 execute_tasks:
2465         __transport_execute_tasks(cmd->se_dev);
2466         return 0;
2467 }
2468
2469 /*
2470  * Called to check struct se_device tcq depth window, and once open pull struct se_task
2471  * from struct se_device->execute_task_list and
2472  *
2473  * Called from transport_processing_thread()
2474  */
2475 static int __transport_execute_tasks(struct se_device *dev)
2476 {
2477         int error;
2478         struct se_cmd *cmd = NULL;
2479         struct se_task *task = NULL;
2480         unsigned long flags;
2481
2482         /*
2483          * Check if there is enough room in the device and HBA queue to send
2484          * struct se_tasks to the selected transport.
2485          */
2486 check_depth:
2487         if (!atomic_read(&dev->depth_left))
2488                 return transport_tcq_window_closed(dev);
2489
2490         dev->dev_tcq_window_closed = 0;
2491
2492         spin_lock_irq(&dev->execute_task_lock);
2493         if (list_empty(&dev->execute_task_list)) {
2494                 spin_unlock_irq(&dev->execute_task_lock);
2495                 return 0;
2496         }
2497         task = list_first_entry(&dev->execute_task_list,
2498                                 struct se_task, t_execute_list);
2499         list_del(&task->t_execute_list);
2500         atomic_set(&task->task_execute_queue, 0);
2501         atomic_dec(&dev->execute_tasks);
2502         spin_unlock_irq(&dev->execute_task_lock);
2503
2504         atomic_dec(&dev->depth_left);
2505
2506         cmd = task->task_se_cmd;
2507
2508         spin_lock_irqsave(&cmd->t_state_lock, flags);
2509         atomic_set(&task->task_active, 1);
2510         atomic_set(&task->task_sent, 1);
2511         atomic_inc(&cmd->t_task_cdbs_sent);
2512
2513         if (atomic_read(&cmd->t_task_cdbs_sent) ==
2514             cmd->t_task_list_num)
2515                 atomic_set(&cmd->transport_sent, 1);
2516
2517         transport_start_task_timer(task);
2518         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2519         /*
2520          * The struct se_cmd->transport_emulate_cdb() function pointer is used
2521          * to grab REPORT_LUNS and other CDBs we want to handle before they hit the
2522          * struct se_subsystem_api->do_task() caller below.
2523          */
2524         if (cmd->transport_emulate_cdb) {
2525                 error = cmd->transport_emulate_cdb(cmd);
2526                 if (error != 0) {
2527                         cmd->transport_error_status = error;
2528                         atomic_set(&task->task_active, 0);
2529                         atomic_set(&cmd->transport_sent, 0);
2530                         transport_stop_tasks_for_cmd(cmd);
2531                         transport_generic_request_failure(cmd, dev, 0, 1);
2532                         goto check_depth;
2533                 }
2534                 /*
2535                  * Handle the successful completion for transport_emulate_cdb()
2536                  * for synchronous operation, following SCF_EMULATE_CDB_ASYNC
2537                  * Otherwise the caller is expected to complete the task with
2538                  * proper status.
2539                  */
2540                 if (!(cmd->se_cmd_flags & SCF_EMULATE_CDB_ASYNC)) {
2541                         cmd->scsi_status = SAM_STAT_GOOD;
2542                         task->task_scsi_status = GOOD;
2543                         transport_complete_task(task, 1);
2544                 }
2545         } else {
2546                 /*
2547                  * Currently for all virtual TCM plugins including IBLOCK, FILEIO and
2548                  * RAMDISK we use the internal transport_emulate_control_cdb() logic
2549                  * with struct se_subsystem_api callers for the primary SPC-3 TYPE_DISK
2550                  * LUN emulation code.
2551                  *
2552                  * For TCM/pSCSI and all other SCF_SCSI_DATA_SG_IO_CDB I/O tasks we
2553                  * call ->do_task() directly and let the underlying TCM subsystem plugin
2554                  * code handle the CDB emulation.
2555                  */
2556                 if ((dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) &&
2557                     (!(task->task_se_cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB)))
2558                         error = transport_emulate_control_cdb(task);
2559                 else
2560                         error = dev->transport->do_task(task);
2561
2562                 if (error != 0) {
2563                         cmd->transport_error_status = error;
2564                         atomic_set(&task->task_active, 0);
2565                         atomic_set(&cmd->transport_sent, 0);
2566                         transport_stop_tasks_for_cmd(cmd);
2567                         transport_generic_request_failure(cmd, dev, 0, 1);
2568                 }
2569         }
2570
2571         goto check_depth;
2572
2573         return 0;
2574 }
2575
2576 void transport_new_cmd_failure(struct se_cmd *se_cmd)
2577 {
2578         unsigned long flags;
2579         /*
2580          * Any unsolicited data will get dumped for failed command inside of
2581          * the fabric plugin
2582          */
2583         spin_lock_irqsave(&se_cmd->t_state_lock, flags);
2584         se_cmd->se_cmd_flags |= SCF_SE_CMD_FAILED;
2585         se_cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2586         spin_unlock_irqrestore(&se_cmd->t_state_lock, flags);
2587 }
2588
2589 static void transport_nop_wait_for_tasks(struct se_cmd *, int, int);
2590
2591 static inline u32 transport_get_sectors_6(
2592         unsigned char *cdb,
2593         struct se_cmd *cmd,
2594         int *ret)
2595 {
2596         struct se_device *dev = cmd->se_dev;
2597
2598         /*
2599          * Assume TYPE_DISK for non struct se_device objects.
2600          * Use 8-bit sector value.
2601          */
2602         if (!dev)
2603                 goto type_disk;
2604
2605         /*
2606          * Use 24-bit allocation length for TYPE_TAPE.
2607          */
2608         if (dev->transport->get_device_type(dev) == TYPE_TAPE)
2609                 return (u32)(cdb[2] << 16) + (cdb[3] << 8) + cdb[4];
2610
2611         /*
2612          * Everything else assume TYPE_DISK Sector CDB location.
2613          * Use 8-bit sector value.
2614          */
2615 type_disk:
2616         return (u32)cdb[4];
2617 }
2618
2619 static inline u32 transport_get_sectors_10(
2620         unsigned char *cdb,
2621         struct se_cmd *cmd,
2622         int *ret)
2623 {
2624         struct se_device *dev = cmd->se_dev;
2625
2626         /*
2627          * Assume TYPE_DISK for non struct se_device objects.
2628          * Use 16-bit sector value.
2629          */
2630         if (!dev)
2631                 goto type_disk;
2632
2633         /*
2634          * XXX_10 is not defined in SSC, throw an exception
2635          */
2636         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2637                 *ret = -EINVAL;
2638                 return 0;
2639         }
2640
2641         /*
2642          * Everything else assume TYPE_DISK Sector CDB location.
2643          * Use 16-bit sector value.
2644          */
2645 type_disk:
2646         return (u32)(cdb[7] << 8) + cdb[8];
2647 }
2648
2649 static inline u32 transport_get_sectors_12(
2650         unsigned char *cdb,
2651         struct se_cmd *cmd,
2652         int *ret)
2653 {
2654         struct se_device *dev = cmd->se_dev;
2655
2656         /*
2657          * Assume TYPE_DISK for non struct se_device objects.
2658          * Use 32-bit sector value.
2659          */
2660         if (!dev)
2661                 goto type_disk;
2662
2663         /*
2664          * XXX_12 is not defined in SSC, throw an exception
2665          */
2666         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2667                 *ret = -EINVAL;
2668                 return 0;
2669         }
2670
2671         /*
2672          * Everything else assume TYPE_DISK Sector CDB location.
2673          * Use 32-bit sector value.
2674          */
2675 type_disk:
2676         return (u32)(cdb[6] << 24) + (cdb[7] << 16) + (cdb[8] << 8) + cdb[9];
2677 }
2678
2679 static inline u32 transport_get_sectors_16(
2680         unsigned char *cdb,
2681         struct se_cmd *cmd,
2682         int *ret)
2683 {
2684         struct se_device *dev = cmd->se_dev;
2685
2686         /*
2687          * Assume TYPE_DISK for non struct se_device objects.
2688          * Use 32-bit sector value.
2689          */
2690         if (!dev)
2691                 goto type_disk;
2692
2693         /*
2694          * Use 24-bit allocation length for TYPE_TAPE.
2695          */
2696         if (dev->transport->get_device_type(dev) == TYPE_TAPE)
2697                 return (u32)(cdb[12] << 16) + (cdb[13] << 8) + cdb[14];
2698
2699 type_disk:
2700         return (u32)(cdb[10] << 24) + (cdb[11] << 16) +
2701                     (cdb[12] << 8) + cdb[13];
2702 }
2703
2704 /*
2705  * Used for VARIABLE_LENGTH_CDB WRITE_32 and READ_32 variants
2706  */
2707 static inline u32 transport_get_sectors_32(
2708         unsigned char *cdb,
2709         struct se_cmd *cmd,
2710         int *ret)
2711 {
2712         /*
2713          * Assume TYPE_DISK for non struct se_device objects.
2714          * Use 32-bit sector value.
2715          */
2716         return (u32)(cdb[28] << 24) + (cdb[29] << 16) +
2717                     (cdb[30] << 8) + cdb[31];
2718
2719 }
2720
2721 static inline u32 transport_get_size(
2722         u32 sectors,
2723         unsigned char *cdb,
2724         struct se_cmd *cmd)
2725 {
2726         struct se_device *dev = cmd->se_dev;
2727
2728         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2729                 if (cdb[1] & 1) { /* sectors */
2730                         return dev->se_sub_dev->se_dev_attrib.block_size * sectors;
2731                 } else /* bytes */
2732                         return sectors;
2733         }
2734 #if 0
2735         printk(KERN_INFO "Returning block_size: %u, sectors: %u == %u for"
2736                         " %s object\n", dev->se_sub_dev->se_dev_attrib.block_size, sectors,
2737                         dev->se_sub_dev->se_dev_attrib.block_size * sectors,
2738                         dev->transport->name);
2739 #endif
2740         return dev->se_sub_dev->se_dev_attrib.block_size * sectors;
2741 }
2742
2743 unsigned char transport_asciihex_to_binaryhex(unsigned char val[2])
2744 {
2745         unsigned char result = 0;
2746         /*
2747          * MSB
2748          */
2749         if ((val[0] >= 'a') && (val[0] <= 'f'))
2750                 result = ((val[0] - 'a' + 10) & 0xf) << 4;
2751         else
2752                 if ((val[0] >= 'A') && (val[0] <= 'F'))
2753                         result = ((val[0] - 'A' + 10) & 0xf) << 4;
2754                 else /* digit */
2755                         result = ((val[0] - '0') & 0xf) << 4;
2756         /*
2757          * LSB
2758          */
2759         if ((val[1] >= 'a') && (val[1] <= 'f'))
2760                 result |= ((val[1] - 'a' + 10) & 0xf);
2761         else
2762                 if ((val[1] >= 'A') && (val[1] <= 'F'))
2763                         result |= ((val[1] - 'A' + 10) & 0xf);
2764                 else /* digit */
2765                         result |= ((val[1] - '0') & 0xf);
2766
2767         return result;
2768 }
2769 EXPORT_SYMBOL(transport_asciihex_to_binaryhex);
2770
2771 static void transport_xor_callback(struct se_cmd *cmd)
2772 {
2773         unsigned char *buf, *addr;
2774         struct se_mem *se_mem;
2775         unsigned int offset;
2776         int i;
2777         /*
2778          * From sbc3r22.pdf section 5.48 XDWRITEREAD (10) command
2779          *
2780          * 1) read the specified logical block(s);
2781          * 2) transfer logical blocks from the data-out buffer;
2782          * 3) XOR the logical blocks transferred from the data-out buffer with
2783          *    the logical blocks read, storing the resulting XOR data in a buffer;
2784          * 4) if the DISABLE WRITE bit is set to zero, then write the logical
2785          *    blocks transferred from the data-out buffer; and
2786          * 5) transfer the resulting XOR data to the data-in buffer.
2787          */
2788         buf = kmalloc(cmd->data_length, GFP_KERNEL);
2789         if (!(buf)) {
2790                 printk(KERN_ERR "Unable to allocate xor_callback buf\n");
2791                 return;
2792         }
2793         /*
2794          * Copy the scatterlist WRITE buffer located at cmd->t_mem_list
2795          * into the locally allocated *buf
2796          */
2797         transport_memcpy_se_mem_read_contig(buf, &cmd->t_mem_list,
2798                                             cmd->data_length);
2799         /*
2800          * Now perform the XOR against the BIDI read memory located at
2801          * cmd->t_mem_bidi_list
2802          */
2803
2804         offset = 0;
2805         list_for_each_entry(se_mem, &cmd->t_mem_bidi_list, se_list) {
2806                 addr = (unsigned char *)kmap_atomic(se_mem->se_page, KM_USER0);
2807                 if (!(addr))
2808                         goto out;
2809
2810                 for (i = 0; i < se_mem->se_len; i++)
2811                         *(addr + se_mem->se_off + i) ^= *(buf + offset + i);
2812
2813                 offset += se_mem->se_len;
2814                 kunmap_atomic(addr, KM_USER0);
2815         }
2816 out:
2817         kfree(buf);
2818 }
2819
2820 /*
2821  * Used to obtain Sense Data from underlying Linux/SCSI struct scsi_cmnd
2822  */
2823 static int transport_get_sense_data(struct se_cmd *cmd)
2824 {
2825         unsigned char *buffer = cmd->sense_buffer, *sense_buffer = NULL;
2826         struct se_device *dev;
2827         struct se_task *task = NULL, *task_tmp;
2828         unsigned long flags;
2829         u32 offset = 0;
2830
2831         WARN_ON(!cmd->se_lun);
2832
2833         spin_lock_irqsave(&cmd->t_state_lock, flags);
2834         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
2835                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2836                 return 0;
2837         }
2838
2839         list_for_each_entry_safe(task, task_tmp,
2840                                 &cmd->t_task_list, t_list) {
2841
2842                 if (!task->task_sense)
2843                         continue;
2844
2845                 dev = task->se_dev;
2846                 if (!(dev))
2847                         continue;
2848
2849                 if (!dev->transport->get_sense_buffer) {
2850                         printk(KERN_ERR "dev->transport->get_sense_buffer"
2851                                         " is NULL\n");
2852                         continue;
2853                 }
2854
2855                 sense_buffer = dev->transport->get_sense_buffer(task);
2856                 if (!(sense_buffer)) {
2857                         printk(KERN_ERR "ITT[0x%08x]_TASK[%d]: Unable to locate"
2858                                 " sense buffer for task with sense\n",
2859                                 cmd->se_tfo->get_task_tag(cmd), task->task_no);
2860                         continue;
2861                 }
2862                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2863
2864                 offset = cmd->se_tfo->set_fabric_sense_len(cmd,
2865                                 TRANSPORT_SENSE_BUFFER);
2866
2867                 memcpy(&buffer[offset], sense_buffer,
2868                                 TRANSPORT_SENSE_BUFFER);
2869                 cmd->scsi_status = task->task_scsi_status;
2870                 /* Automatically padded */
2871                 cmd->scsi_sense_length =
2872                                 (TRANSPORT_SENSE_BUFFER + offset);
2873
2874                 printk(KERN_INFO "HBA_[%u]_PLUG[%s]: Set SAM STATUS: 0x%02x"
2875                                 " and sense\n",
2876                         dev->se_hba->hba_id, dev->transport->name,
2877                                 cmd->scsi_status);
2878                 return 0;
2879         }
2880         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2881
2882         return -1;
2883 }
2884
2885 static int transport_allocate_resources(struct se_cmd *cmd)
2886 {
2887         u32 length = cmd->data_length;
2888
2889         if ((cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) ||
2890             (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB))
2891                 return transport_generic_get_mem(cmd, length);
2892         else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB)
2893                 return transport_generic_allocate_buf(cmd, length);
2894         else
2895                 return 0;
2896 }
2897
2898 static int
2899 transport_handle_reservation_conflict(struct se_cmd *cmd)
2900 {
2901         cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
2902         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2903         cmd->se_cmd_flags |= SCF_SCSI_RESERVATION_CONFLICT;
2904         cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2905         /*
2906          * For UA Interlock Code 11b, a RESERVATION CONFLICT will
2907          * establish a UNIT ATTENTION with PREVIOUS RESERVATION
2908          * CONFLICT STATUS.
2909          *
2910          * See spc4r17, section 7.4.6 Control Mode Page, Table 349
2911          */
2912         if (cmd->se_sess &&
2913             cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
2914                 core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
2915                         cmd->orig_fe_lun, 0x2C,
2916                         ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
2917         return -EINVAL;
2918 }
2919
2920 /*      transport_generic_cmd_sequencer():
2921  *
2922  *      Generic Command Sequencer that should work for most DAS transport
2923  *      drivers.
2924  *
2925  *      Called from transport_generic_allocate_tasks() in the $FABRIC_MOD
2926  *      RX Thread.
2927  *
2928  *      FIXME: Need to support other SCSI OPCODES where as well.
2929  */
2930 static int transport_generic_cmd_sequencer(
2931         struct se_cmd *cmd,
2932         unsigned char *cdb)
2933 {
2934         struct se_device *dev = cmd->se_dev;
2935         struct se_subsystem_dev *su_dev = dev->se_sub_dev;
2936         int ret = 0, sector_ret = 0, passthrough;
2937         u32 sectors = 0, size = 0, pr_reg_type = 0;
2938         u16 service_action;
2939         u8 alua_ascq = 0;
2940         /*
2941          * Check for an existing UNIT ATTENTION condition
2942          */
2943         if (core_scsi3_ua_check(cmd, cdb) < 0) {
2944                 cmd->transport_wait_for_tasks =
2945                                 &transport_nop_wait_for_tasks;
2946                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2947                 cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
2948                 return -EINVAL;
2949         }
2950         /*
2951          * Check status of Asymmetric Logical Unit Assignment port
2952          */
2953         ret = su_dev->t10_alua.alua_state_check(cmd, cdb, &alua_ascq);
2954         if (ret != 0) {
2955                 cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
2956                 /*
2957                  * Set SCSI additional sense code (ASC) to 'LUN Not Accessible';
2958                  * The ALUA additional sense code qualifier (ASCQ) is determined
2959                  * by the ALUA primary or secondary access state..
2960                  */
2961                 if (ret > 0) {
2962 #if 0
2963                         printk(KERN_INFO "[%s]: ALUA TG Port not available,"
2964                                 " SenseKey: NOT_READY, ASC/ASCQ: 0x04/0x%02x\n",
2965                                 cmd->se_tfo->get_fabric_name(), alua_ascq);
2966 #endif
2967                         transport_set_sense_codes(cmd, 0x04, alua_ascq);
2968                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2969                         cmd->scsi_sense_reason = TCM_CHECK_CONDITION_NOT_READY;
2970                         return -EINVAL;
2971                 }
2972                 goto out_invalid_cdb_field;
2973         }
2974         /*
2975          * Check status for SPC-3 Persistent Reservations
2976          */
2977         if (su_dev->t10_pr.pr_ops.t10_reservation_check(cmd, &pr_reg_type) != 0) {
2978                 if (su_dev->t10_pr.pr_ops.t10_seq_non_holder(
2979                                         cmd, cdb, pr_reg_type) != 0)
2980                         return transport_handle_reservation_conflict(cmd);
2981                 /*
2982                  * This means the CDB is allowed for the SCSI Initiator port
2983                  * when said port is *NOT* holding the legacy SPC-2 or
2984                  * SPC-3 Persistent Reservation.
2985                  */
2986         }
2987
2988         switch (cdb[0]) {
2989         case READ_6:
2990                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
2991                 if (sector_ret)
2992                         goto out_unsupported_cdb;
2993                 size = transport_get_size(sectors, cdb, cmd);
2994                 cmd->transport_split_cdb = &split_cdb_XX_6;
2995                 cmd->t_task_lba = transport_lba_21(cdb);
2996                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2997                 break;
2998         case READ_10:
2999                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3000                 if (sector_ret)
3001                         goto out_unsupported_cdb;
3002                 size = transport_get_size(sectors, cdb, cmd);
3003                 cmd->transport_split_cdb = &split_cdb_XX_10;
3004                 cmd->t_task_lba = transport_lba_32(cdb);
3005                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3006                 break;
3007         case READ_12:
3008                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
3009                 if (sector_ret)
3010                         goto out_unsupported_cdb;
3011                 size = transport_get_size(sectors, cdb, cmd);
3012                 cmd->transport_split_cdb = &split_cdb_XX_12;
3013                 cmd->t_task_lba = transport_lba_32(cdb);
3014                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3015                 break;
3016         case READ_16:
3017                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3018                 if (sector_ret)
3019                         goto out_unsupported_cdb;
3020                 size = transport_get_size(sectors, cdb, cmd);
3021                 cmd->transport_split_cdb = &split_cdb_XX_16;
3022                 cmd->t_task_lba = transport_lba_64(cdb);
3023                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3024                 break;
3025         case WRITE_6:
3026                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
3027                 if (sector_ret)
3028                         goto out_unsupported_cdb;
3029                 size = transport_get_size(sectors, cdb, cmd);
3030                 cmd->transport_split_cdb = &split_cdb_XX_6;
3031                 cmd->t_task_lba = transport_lba_21(cdb);
3032                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3033                 break;
3034         case WRITE_10:
3035                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3036                 if (sector_ret)
3037                         goto out_unsupported_cdb;
3038                 size = transport_get_size(sectors, cdb, cmd);
3039                 cmd->transport_split_cdb = &split_cdb_XX_10;
3040                 cmd->t_task_lba = transport_lba_32(cdb);
3041                 cmd->t_tasks_fua = (cdb[1] & 0x8);
3042                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3043                 break;
3044         case WRITE_12:
3045                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
3046                 if (sector_ret)
3047                         goto out_unsupported_cdb;
3048                 size = transport_get_size(sectors, cdb, cmd);
3049                 cmd->transport_split_cdb = &split_cdb_XX_12;
3050                 cmd->t_task_lba = transport_lba_32(cdb);
3051                 cmd->t_tasks_fua = (cdb[1] & 0x8);
3052                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3053                 break;
3054         case WRITE_16:
3055                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3056                 if (sector_ret)
3057                         goto out_unsupported_cdb;
3058                 size = transport_get_size(sectors, cdb, cmd);
3059                 cmd->transport_split_cdb = &split_cdb_XX_16;
3060                 cmd->t_task_lba = transport_lba_64(cdb);
3061                 cmd->t_tasks_fua = (cdb[1] & 0x8);
3062                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3063                 break;
3064         case XDWRITEREAD_10:
3065                 if ((cmd->data_direction != DMA_TO_DEVICE) ||
3066                     !(cmd->t_tasks_bidi))
3067                         goto out_invalid_cdb_field;
3068                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3069                 if (sector_ret)
3070                         goto out_unsupported_cdb;
3071                 size = transport_get_size(sectors, cdb, cmd);
3072                 cmd->transport_split_cdb = &split_cdb_XX_10;
3073                 cmd->t_task_lba = transport_lba_32(cdb);
3074                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3075                 passthrough = (dev->transport->transport_type ==
3076                                 TRANSPORT_PLUGIN_PHBA_PDEV);
3077                 /*
3078                  * Skip the remaining assignments for TCM/PSCSI passthrough
3079                  */
3080                 if (passthrough)
3081                         break;
3082                 /*
3083                  * Setup BIDI XOR callback to be run during transport_generic_complete_ok()
3084                  */
3085                 cmd->transport_complete_callback = &transport_xor_callback;
3086                 cmd->t_tasks_fua = (cdb[1] & 0x8);
3087                 break;
3088         case VARIABLE_LENGTH_CMD:
3089                 service_action = get_unaligned_be16(&cdb[8]);
3090                 /*
3091                  * Determine if this is TCM/PSCSI device and we should disable
3092                  * internal emulation for this CDB.
3093                  */
3094                 passthrough = (dev->transport->transport_type ==
3095                                         TRANSPORT_PLUGIN_PHBA_PDEV);
3096
3097                 switch (service_action) {
3098                 case XDWRITEREAD_32:
3099                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
3100                         if (sector_ret)
3101                                 goto out_unsupported_cdb;
3102                         size = transport_get_size(sectors, cdb, cmd);
3103                         /*
3104                          * Use WRITE_32 and READ_32 opcodes for the emulated
3105                          * XDWRITE_READ_32 logic.
3106                          */
3107                         cmd->transport_split_cdb = &split_cdb_XX_32;
3108                         cmd->t_task_lba = transport_lba_64_ext(cdb);
3109                         cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
3110
3111                         /*
3112                          * Skip the remaining assignments for TCM/PSCSI passthrough
3113                          */
3114                         if (passthrough)
3115                                 break;
3116
3117                         /*
3118                          * Setup BIDI XOR callback to be run during
3119                          * transport_generic_complete_ok()
3120                          */
3121                         cmd->transport_complete_callback = &transport_xor_callback;
3122                         cmd->t_tasks_fua = (cdb[10] & 0x8);
3123                         break;
3124                 case WRITE_SAME_32:
3125                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
3126                         if (sector_ret)
3127                                 goto out_unsupported_cdb;
3128
3129                         if (sectors != 0)
3130                                 size = transport_get_size(sectors, cdb, cmd);
3131                         else
3132                                 size = dev->se_sub_dev->se_dev_attrib.block_size;
3133
3134                         cmd->t_task_lba = get_unaligned_be64(&cdb[12]);
3135                         cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3136
3137                         /*
3138                          * Skip the remaining assignments for TCM/PSCSI passthrough
3139                          */
3140                         if (passthrough)
3141                                 break;
3142
3143                         if ((cdb[10] & 0x04) || (cdb[10] & 0x02)) {
3144                                 printk(KERN_ERR "WRITE_SAME PBDATA and LBDATA"
3145                                         " bits not supported for Block Discard"
3146                                         " Emulation\n");
3147                                 goto out_invalid_cdb_field;
3148                         }
3149                         /*
3150                          * Currently for the emulated case we only accept
3151                          * tpws with the UNMAP=1 bit set.
3152                          */
3153                         if (!(cdb[10] & 0x08)) {
3154                                 printk(KERN_ERR "WRITE_SAME w/o UNMAP bit not"
3155                                         " supported for Block Discard Emulation\n");
3156                                 goto out_invalid_cdb_field;
3157                         }
3158                         break;
3159                 default:
3160                         printk(KERN_ERR "VARIABLE_LENGTH_CMD service action"
3161                                 " 0x%04x not supported\n", service_action);
3162                         goto out_unsupported_cdb;
3163                 }
3164                 break;
3165         case MAINTENANCE_IN:
3166                 if (dev->transport->get_device_type(dev) != TYPE_ROM) {
3167                         /* MAINTENANCE_IN from SCC-2 */
3168                         /*
3169                          * Check for emulated MI_REPORT_TARGET_PGS.
3170                          */
3171                         if (cdb[1] == MI_REPORT_TARGET_PGS) {
3172                                 cmd->transport_emulate_cdb =
3173                                 (su_dev->t10_alua.alua_type ==
3174                                  SPC3_ALUA_EMULATED) ?
3175                                 core_emulate_report_target_port_groups :
3176                                 NULL;
3177                         }
3178                         size = (cdb[6] << 24) | (cdb[7] << 16) |
3179                                (cdb[8] << 8) | cdb[9];
3180                 } else {
3181                         /* GPCMD_SEND_KEY from multi media commands */
3182                         size = (cdb[8] << 8) + cdb[9];
3183                 }
3184                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3185                 break;
3186         case MODE_SELECT:
3187                 size = cdb[4];
3188                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3189                 break;
3190         case MODE_SELECT_10:
3191                 size = (cdb[7] << 8) + cdb[8];
3192                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3193                 break;
3194         case MODE_SENSE:
3195                 size = cdb[4];
3196                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3197                 break;
3198         case MODE_SENSE_10:
3199         case GPCMD_READ_BUFFER_CAPACITY:
3200         case GPCMD_SEND_OPC:
3201         case LOG_SELECT:
3202         case LOG_SENSE:
3203                 size = (cdb[7] << 8) + cdb[8];
3204                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3205                 break;
3206         case READ_BLOCK_LIMITS:
3207                 size = READ_BLOCK_LEN;
3208                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3209                 break;
3210         case GPCMD_GET_CONFIGURATION:
3211         case GPCMD_READ_FORMAT_CAPACITIES:
3212         case GPCMD_READ_DISC_INFO:
3213         case GPCMD_READ_TRACK_RZONE_INFO:
3214                 size = (cdb[7] << 8) + cdb[8];
3215                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3216                 break;
3217         case PERSISTENT_RESERVE_IN:
3218         case PERSISTENT_RESERVE_OUT:
3219                 cmd->transport_emulate_cdb =
3220                         (su_dev->t10_pr.res_type ==
3221                          SPC3_PERSISTENT_RESERVATIONS) ?
3222                         core_scsi3_emulate_pr : NULL;
3223                 size = (cdb[7] << 8) + cdb[8];
3224                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3225                 break;
3226         case GPCMD_MECHANISM_STATUS:
3227         case GPCMD_READ_DVD_STRUCTURE:
3228                 size = (cdb[8] << 8) + cdb[9];
3229                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3230                 break;
3231         case READ_POSITION:
3232                 size = READ_POSITION_LEN;
3233                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3234                 break;
3235         case MAINTENANCE_OUT:
3236                 if (dev->transport->get_device_type(dev) != TYPE_ROM) {
3237                         /* MAINTENANCE_OUT from SCC-2
3238                          *
3239                          * Check for emulated MO_SET_TARGET_PGS.
3240                          */
3241                         if (cdb[1] == MO_SET_TARGET_PGS) {
3242                                 cmd->transport_emulate_cdb =
3243                                 (su_dev->t10_alua.alua_type ==
3244                                         SPC3_ALUA_EMULATED) ?
3245                                 core_emulate_set_target_port_groups :
3246                                 NULL;
3247                         }
3248
3249                         size = (cdb[6] << 24) | (cdb[7] << 16) |
3250                                (cdb[8] << 8) | cdb[9];
3251                 } else  {
3252                         /* GPCMD_REPORT_KEY from multi media commands */
3253                         size = (cdb[8] << 8) + cdb[9];
3254                 }
3255                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3256                 break;
3257         case INQUIRY:
3258                 size = (cdb[3] << 8) + cdb[4];
3259                 /*
3260                  * Do implict HEAD_OF_QUEUE processing for INQUIRY.
3261                  * See spc4r17 section 5.3
3262                  */
3263                 if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3264                         cmd->sam_task_attr = MSG_HEAD_TAG;
3265                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3266                 break;
3267         case READ_BUFFER:
3268                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3269                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3270                 break;
3271         case READ_CAPACITY:
3272                 size = READ_CAP_LEN;
3273                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3274                 break;
3275         case READ_MEDIA_SERIAL_NUMBER:
3276         case SECURITY_PROTOCOL_IN:
3277         case SECURITY_PROTOCOL_OUT:
3278                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
3279                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3280                 break;
3281         case SERVICE_ACTION_IN:
3282         case ACCESS_CONTROL_IN:
3283         case ACCESS_CONTROL_OUT:
3284         case EXTENDED_COPY:
3285         case READ_ATTRIBUTE:
3286         case RECEIVE_COPY_RESULTS:
3287         case WRITE_ATTRIBUTE:
3288                 size = (cdb[10] << 24) | (cdb[11] << 16) |
3289                        (cdb[12] << 8) | cdb[13];
3290                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3291                 break;
3292         case RECEIVE_DIAGNOSTIC:
3293         case SEND_DIAGNOSTIC:
3294                 size = (cdb[3] << 8) | cdb[4];
3295                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3296                 break;
3297 /* #warning FIXME: Figure out correct GPCMD_READ_CD blocksize. */
3298 #if 0
3299         case GPCMD_READ_CD:
3300                 sectors = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3301                 size = (2336 * sectors);
3302                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3303                 break;
3304 #endif
3305         case READ_TOC:
3306                 size = cdb[8];
3307                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3308                 break;
3309         case REQUEST_SENSE:
3310                 size = cdb[4];
3311                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3312                 break;
3313         case READ_ELEMENT_STATUS:
3314                 size = 65536 * cdb[7] + 256 * cdb[8] + cdb[9];
3315                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3316                 break;
3317         case WRITE_BUFFER:
3318                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3319                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3320                 break;
3321         case RESERVE:
3322         case RESERVE_10:
3323                 /*
3324                  * The SPC-2 RESERVE does not contain a size in the SCSI CDB.
3325                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
3326                  */
3327                 if (cdb[0] == RESERVE_10)
3328                         size = (cdb[7] << 8) | cdb[8];
3329                 else
3330                         size = cmd->data_length;
3331
3332                 /*
3333                  * Setup the legacy emulated handler for SPC-2 and
3334                  * >= SPC-3 compatible reservation handling (CRH=1)
3335                  * Otherwise, we assume the underlying SCSI logic is
3336                  * is running in SPC_PASSTHROUGH, and wants reservations
3337                  * emulation disabled.
3338                  */
3339                 cmd->transport_emulate_cdb =
3340                                 (su_dev->t10_pr.res_type !=
3341                                  SPC_PASSTHROUGH) ?
3342                                 core_scsi2_emulate_crh : NULL;
3343                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3344                 break;
3345         case RELEASE:
3346         case RELEASE_10:
3347                 /*
3348                  * The SPC-2 RELEASE 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] == RELEASE_10)
3352                         size = (cdb[7] << 8) | cdb[8];
3353                 else
3354                         size = cmd->data_length;
3355
3356                 cmd->transport_emulate_cdb =
3357                                 (su_dev->t10_pr.res_type !=
3358                                  SPC_PASSTHROUGH) ?
3359                                 core_scsi2_emulate_crh : NULL;
3360                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3361                 break;
3362         case SYNCHRONIZE_CACHE:
3363         case 0x91: /* SYNCHRONIZE_CACHE_16: */
3364                 /*
3365                  * Extract LBA and range to be flushed for emulated SYNCHRONIZE_CACHE
3366                  */
3367                 if (cdb[0] == SYNCHRONIZE_CACHE) {
3368                         sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3369                         cmd->t_task_lba = transport_lba_32(cdb);
3370                 } else {
3371                         sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3372                         cmd->t_task_lba = transport_lba_64(cdb);
3373                 }
3374                 if (sector_ret)
3375                         goto out_unsupported_cdb;
3376
3377                 size = transport_get_size(sectors, cdb, cmd);
3378                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3379
3380                 /*
3381                  * For TCM/pSCSI passthrough, skip cmd->transport_emulate_cdb()
3382                  */
3383                 if (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV)
3384                         break;
3385                 /*
3386                  * Set SCF_EMULATE_CDB_ASYNC to ensure asynchronous operation
3387                  * for SYNCHRONIZE_CACHE* Immed=1 case in __transport_execute_tasks()
3388                  */
3389                 cmd->se_cmd_flags |= SCF_EMULATE_CDB_ASYNC;
3390                 /*
3391                  * Check to ensure that LBA + Range does not exceed past end of
3392                  * device.
3393                  */
3394                 if (!transport_cmd_get_valid_sectors(cmd))
3395                         goto out_invalid_cdb_field;
3396                 break;
3397         case UNMAP:
3398                 size = get_unaligned_be16(&cdb[7]);
3399                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3400                 break;
3401         case WRITE_SAME_16:
3402                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3403                 if (sector_ret)
3404                         goto out_unsupported_cdb;
3405
3406                 if (sectors != 0)
3407                         size = transport_get_size(sectors, cdb, cmd);
3408                 else
3409                         size = dev->se_sub_dev->se_dev_attrib.block_size;
3410
3411                 cmd->t_task_lba = get_unaligned_be16(&cdb[2]);
3412                 passthrough = (dev->transport->transport_type ==
3413                                 TRANSPORT_PLUGIN_PHBA_PDEV);
3414                 /*
3415                  * Determine if the received WRITE_SAME_16 is used to for direct
3416                  * passthrough into Linux/SCSI with struct request via TCM/pSCSI
3417                  * or we are signaling the use of internal WRITE_SAME + UNMAP=1
3418                  * emulation for -> Linux/BLOCK disbard with TCM/IBLOCK and
3419                  * TCM/FILEIO subsystem plugin backstores.
3420                  */
3421                 if (!(passthrough)) {
3422                         if ((cdb[1] & 0x04) || (cdb[1] & 0x02)) {
3423                                 printk(KERN_ERR "WRITE_SAME PBDATA and LBDATA"
3424                                         " bits not supported for Block Discard"
3425                                         " Emulation\n");
3426                                 goto out_invalid_cdb_field;
3427                         }
3428                         /*
3429                          * Currently for the emulated case we only accept
3430                          * tpws with the UNMAP=1 bit set.
3431                          */
3432                         if (!(cdb[1] & 0x08)) {
3433                                 printk(KERN_ERR "WRITE_SAME w/o UNMAP bit not "
3434                                         " supported for Block Discard Emulation\n");
3435                                 goto out_invalid_cdb_field;
3436                         }
3437                 }
3438                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3439                 break;
3440         case ALLOW_MEDIUM_REMOVAL:
3441         case GPCMD_CLOSE_TRACK:
3442         case ERASE:
3443         case INITIALIZE_ELEMENT_STATUS:
3444         case GPCMD_LOAD_UNLOAD:
3445         case REZERO_UNIT:
3446         case SEEK_10:
3447         case GPCMD_SET_SPEED:
3448         case SPACE:
3449         case START_STOP:
3450         case TEST_UNIT_READY:
3451         case VERIFY:
3452         case WRITE_FILEMARKS:
3453         case MOVE_MEDIUM:
3454                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3455                 break;
3456         case REPORT_LUNS:
3457                 cmd->transport_emulate_cdb =
3458                                 transport_core_report_lun_response;
3459                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
3460                 /*
3461                  * Do implict HEAD_OF_QUEUE processing for REPORT_LUNS
3462                  * See spc4r17 section 5.3
3463                  */
3464                 if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3465                         cmd->sam_task_attr = MSG_HEAD_TAG;
3466                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_NONSG_IO_CDB;
3467                 break;
3468         default:
3469                 printk(KERN_WARNING "TARGET_CORE[%s]: Unsupported SCSI Opcode"
3470                         " 0x%02x, sending CHECK_CONDITION.\n",
3471                         cmd->se_tfo->get_fabric_name(), cdb[0]);
3472                 cmd->transport_wait_for_tasks = &transport_nop_wait_for_tasks;
3473                 goto out_unsupported_cdb;
3474         }
3475
3476         if (size != cmd->data_length) {
3477                 printk(KERN_WARNING "TARGET_CORE[%s]: Expected Transfer Length:"
3478                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
3479                         " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
3480                                 cmd->data_length, size, cdb[0]);
3481
3482                 cmd->cmd_spdtl = size;
3483
3484                 if (cmd->data_direction == DMA_TO_DEVICE) {
3485                         printk(KERN_ERR "Rejecting underflow/overflow"
3486                                         " WRITE data\n");
3487                         goto out_invalid_cdb_field;
3488                 }
3489                 /*
3490                  * Reject READ_* or WRITE_* with overflow/underflow for
3491                  * type SCF_SCSI_DATA_SG_IO_CDB.
3492                  */
3493                 if (!(ret) && (dev->se_sub_dev->se_dev_attrib.block_size != 512))  {
3494                         printk(KERN_ERR "Failing OVERFLOW/UNDERFLOW for LBA op"
3495                                 " CDB on non 512-byte sector setup subsystem"
3496                                 " plugin: %s\n", dev->transport->name);
3497                         /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
3498                         goto out_invalid_cdb_field;
3499                 }
3500
3501                 if (size > cmd->data_length) {
3502                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
3503                         cmd->residual_count = (size - cmd->data_length);
3504                 } else {
3505                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
3506                         cmd->residual_count = (cmd->data_length - size);
3507                 }
3508                 cmd->data_length = size;
3509         }
3510
3511         transport_set_supported_SAM_opcode(cmd);
3512         return ret;
3513
3514 out_unsupported_cdb:
3515         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3516         cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
3517         return -EINVAL;
3518 out_invalid_cdb_field:
3519         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3520         cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
3521         return -EINVAL;
3522 }
3523
3524 static inline void transport_release_tasks(struct se_cmd *);
3525
3526 static void transport_memcpy_se_mem_read_contig(
3527         unsigned char *dst,
3528         struct list_head *se_mem_list,
3529         u32 tot_len)
3530 {
3531         struct se_mem *se_mem;
3532         void *src;
3533         u32 length;
3534
3535         list_for_each_entry(se_mem, se_mem_list, se_list) {
3536                 length = min_t(u32, se_mem->se_len, tot_len);
3537                 src = page_address(se_mem->se_page) + se_mem->se_off;
3538                 memcpy(dst, src, length);
3539                 tot_len -= length;
3540                 if (!tot_len)
3541                         break;
3542                 dst += length;
3543         }
3544 }
3545
3546 /*
3547  * Called from transport_generic_complete_ok() and
3548  * transport_generic_request_failure() to determine which dormant/delayed
3549  * and ordered cmds need to have their tasks added to the execution queue.
3550  */
3551 static void transport_complete_task_attr(struct se_cmd *cmd)
3552 {
3553         struct se_device *dev = cmd->se_dev;
3554         struct se_cmd *cmd_p, *cmd_tmp;
3555         int new_active_tasks = 0;
3556
3557         if (cmd->sam_task_attr == MSG_SIMPLE_TAG) {
3558                 atomic_dec(&dev->simple_cmds);
3559                 smp_mb__after_atomic_dec();
3560                 dev->dev_cur_ordered_id++;
3561                 DEBUG_STA("Incremented dev->dev_cur_ordered_id: %u for"
3562                         " SIMPLE: %u\n", dev->dev_cur_ordered_id,
3563                         cmd->se_ordered_id);
3564         } else if (cmd->sam_task_attr == MSG_HEAD_TAG) {
3565                 atomic_dec(&dev->dev_hoq_count);
3566                 smp_mb__after_atomic_dec();
3567                 dev->dev_cur_ordered_id++;
3568                 DEBUG_STA("Incremented dev_cur_ordered_id: %u for"
3569                         " HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id,
3570                         cmd->se_ordered_id);
3571         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
3572                 spin_lock(&dev->ordered_cmd_lock);
3573                 list_del(&cmd->se_ordered_node);
3574                 atomic_dec(&dev->dev_ordered_sync);
3575                 smp_mb__after_atomic_dec();
3576                 spin_unlock(&dev->ordered_cmd_lock);
3577
3578                 dev->dev_cur_ordered_id++;
3579                 DEBUG_STA("Incremented dev_cur_ordered_id: %u for ORDERED:"
3580                         " %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id);
3581         }
3582         /*
3583          * Process all commands up to the last received
3584          * ORDERED task attribute which requires another blocking
3585          * boundary
3586          */
3587         spin_lock(&dev->delayed_cmd_lock);
3588         list_for_each_entry_safe(cmd_p, cmd_tmp,
3589                         &dev->delayed_cmd_list, se_delayed_node) {
3590
3591                 list_del(&cmd_p->se_delayed_node);
3592                 spin_unlock(&dev->delayed_cmd_lock);
3593
3594                 DEBUG_STA("Calling add_tasks() for"
3595                         " cmd_p: 0x%02x Task Attr: 0x%02x"
3596                         " Dormant -> Active, se_ordered_id: %u\n",
3597                         T_TASK(cmd_p)->t_task_cdb[0],
3598                         cmd_p->sam_task_attr, cmd_p->se_ordered_id);
3599
3600                 transport_add_tasks_from_cmd(cmd_p);
3601                 new_active_tasks++;
3602
3603                 spin_lock(&dev->delayed_cmd_lock);
3604                 if (cmd_p->sam_task_attr == MSG_ORDERED_TAG)
3605                         break;
3606         }
3607         spin_unlock(&dev->delayed_cmd_lock);
3608         /*
3609          * If new tasks have become active, wake up the transport thread
3610          * to do the processing of the Active tasks.
3611          */
3612         if (new_active_tasks != 0)
3613                 wake_up_interruptible(&dev->dev_queue_obj.thread_wq);
3614 }
3615
3616 static void transport_generic_complete_ok(struct se_cmd *cmd)
3617 {
3618         int reason = 0;
3619         /*
3620          * Check if we need to move delayed/dormant tasks from cmds on the
3621          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
3622          * Attribute.
3623          */
3624         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3625                 transport_complete_task_attr(cmd);
3626         /*
3627          * Check if we need to retrieve a sense buffer from
3628          * the struct se_cmd in question.
3629          */
3630         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
3631                 if (transport_get_sense_data(cmd) < 0)
3632                         reason = TCM_NON_EXISTENT_LUN;
3633
3634                 /*
3635                  * Only set when an struct se_task->task_scsi_status returned
3636                  * a non GOOD status.
3637                  */
3638                 if (cmd->scsi_status) {
3639                         transport_send_check_condition_and_sense(
3640                                         cmd, reason, 1);
3641                         transport_lun_remove_cmd(cmd);
3642                         transport_cmd_check_stop_to_fabric(cmd);
3643                         return;
3644                 }
3645         }
3646         /*
3647          * Check for a callback, used by amongst other things
3648          * XDWRITE_READ_10 emulation.
3649          */
3650         if (cmd->transport_complete_callback)
3651                 cmd->transport_complete_callback(cmd);
3652
3653         switch (cmd->data_direction) {
3654         case DMA_FROM_DEVICE:
3655                 spin_lock(&cmd->se_lun->lun_sep_lock);
3656                 if (cmd->se_lun->lun_sep) {
3657                         cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
3658                                         cmd->data_length;
3659                 }
3660                 spin_unlock(&cmd->se_lun->lun_sep_lock);
3661                 /*
3662                  * If enabled by TCM fabric module pre-registered SGL
3663                  * memory, perform the memcpy() from the TCM internal
3664                  * contiguous buffer back to the original SGL.
3665                  */
3666                 if (cmd->se_cmd_flags & SCF_PASSTHROUGH_CONTIG_TO_SG)
3667                         sg_copy_from_buffer(cmd->t_task_pt_sgl,
3668                                             cmd->t_task_pt_sgl_num,
3669                                             cmd->t_task_buf,
3670                                             cmd->data_length);
3671
3672                 cmd->se_tfo->queue_data_in(cmd);
3673                 break;
3674         case DMA_TO_DEVICE:
3675                 spin_lock(&cmd->se_lun->lun_sep_lock);
3676                 if (cmd->se_lun->lun_sep) {
3677                         cmd->se_lun->lun_sep->sep_stats.rx_data_octets +=
3678                                 cmd->data_length;
3679                 }
3680                 spin_unlock(&cmd->se_lun->lun_sep_lock);
3681                 /*
3682                  * Check if we need to send READ payload for BIDI-COMMAND
3683                  */
3684                 if (!list_empty(&cmd->t_mem_bidi_list)) {
3685                         spin_lock(&cmd->se_lun->lun_sep_lock);
3686                         if (cmd->se_lun->lun_sep) {
3687                                 cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
3688                                         cmd->data_length;
3689                         }
3690                         spin_unlock(&cmd->se_lun->lun_sep_lock);
3691                         cmd->se_tfo->queue_data_in(cmd);
3692                         break;
3693                 }
3694                 /* Fall through for DMA_TO_DEVICE */
3695         case DMA_NONE:
3696                 cmd->se_tfo->queue_status(cmd);
3697                 break;
3698         default:
3699                 break;
3700         }
3701
3702         transport_lun_remove_cmd(cmd);
3703         transport_cmd_check_stop_to_fabric(cmd);
3704 }
3705
3706 static void transport_free_dev_tasks(struct se_cmd *cmd)
3707 {
3708         struct se_task *task, *task_tmp;
3709         unsigned long flags;
3710
3711         spin_lock_irqsave(&cmd->t_state_lock, flags);
3712         list_for_each_entry_safe(task, task_tmp,
3713                                 &cmd->t_task_list, t_list) {
3714                 if (atomic_read(&task->task_active))
3715                         continue;
3716
3717                 kfree(task->task_sg_bidi);
3718                 kfree(task->task_sg);
3719
3720                 list_del(&task->t_list);
3721
3722                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3723                 if (task->se_dev)
3724                         task->se_dev->transport->free_task(task);
3725                 else
3726                         printk(KERN_ERR "task[%u] - task->se_dev is NULL\n",
3727                                 task->task_no);
3728                 spin_lock_irqsave(&cmd->t_state_lock, flags);
3729         }
3730         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3731 }
3732
3733 static inline void transport_free_pages(struct se_cmd *cmd)
3734 {
3735         struct se_mem *se_mem, *se_mem_tmp;
3736         int free_page = 1;
3737
3738         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)
3739                 free_page = 0;
3740         if (cmd->se_dev->transport->do_se_mem_map)
3741                 free_page = 0;
3742
3743         if (cmd->t_task_buf) {
3744                 kfree(cmd->t_task_buf);
3745                 cmd->t_task_buf = NULL;
3746                 return;
3747         }
3748
3749         list_for_each_entry_safe(se_mem, se_mem_tmp,
3750                         &cmd->t_mem_list, se_list) {
3751                 /*
3752                  * We only release call __free_page(struct se_mem->se_page) when
3753                  * SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC is NOT in use,
3754                  */
3755                 if (free_page)
3756                         __free_page(se_mem->se_page);
3757
3758                 list_del(&se_mem->se_list);
3759                 kmem_cache_free(se_mem_cache, se_mem);
3760         }
3761         cmd->t_tasks_se_num = 0;
3762
3763         list_for_each_entry_safe(se_mem, se_mem_tmp,
3764                                  &cmd->t_mem_bidi_list, se_list) {
3765                 /*
3766                  * We only release call __free_page(struct se_mem->se_page) when
3767                  * SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC is NOT in use,
3768                  */
3769                 if (free_page)
3770                         __free_page(se_mem->se_page);
3771
3772                 list_del(&se_mem->se_list);
3773                 kmem_cache_free(se_mem_cache, se_mem);
3774         }
3775         cmd->t_tasks_se_bidi_num = 0;
3776 }
3777
3778 static inline void transport_release_tasks(struct se_cmd *cmd)
3779 {
3780         transport_free_dev_tasks(cmd);
3781 }
3782
3783 static inline int transport_dec_and_check(struct se_cmd *cmd)
3784 {
3785         unsigned long flags;
3786
3787         spin_lock_irqsave(&cmd->t_state_lock, flags);
3788         if (atomic_read(&cmd->t_fe_count)) {
3789                 if (!(atomic_dec_and_test(&cmd->t_fe_count))) {
3790                         spin_unlock_irqrestore(&cmd->t_state_lock,
3791                                         flags);
3792                         return 1;
3793                 }
3794         }
3795
3796         if (atomic_read(&cmd->t_se_count)) {
3797                 if (!(atomic_dec_and_test(&cmd->t_se_count))) {
3798                         spin_unlock_irqrestore(&cmd->t_state_lock,
3799                                         flags);
3800                         return 1;
3801                 }
3802         }
3803         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3804
3805         return 0;
3806 }
3807
3808 static void transport_release_fe_cmd(struct se_cmd *cmd)
3809 {
3810         unsigned long flags;
3811
3812         if (transport_dec_and_check(cmd))
3813                 return;
3814
3815         spin_lock_irqsave(&cmd->t_state_lock, flags);
3816         if (!(atomic_read(&cmd->transport_dev_active))) {
3817                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3818                 goto free_pages;
3819         }
3820         atomic_set(&cmd->transport_dev_active, 0);
3821         transport_all_task_dev_remove_state(cmd);
3822         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3823
3824         transport_release_tasks(cmd);
3825 free_pages:
3826         transport_free_pages(cmd);
3827         transport_free_se_cmd(cmd);
3828         cmd->se_tfo->release_cmd_direct(cmd);
3829 }
3830
3831 static int transport_generic_remove(
3832         struct se_cmd *cmd,
3833         int release_to_pool,
3834         int session_reinstatement)
3835 {
3836         unsigned long flags;
3837
3838         if (transport_dec_and_check(cmd)) {
3839                 if (session_reinstatement) {
3840                         spin_lock_irqsave(&cmd->t_state_lock, flags);
3841                         transport_all_task_dev_remove_state(cmd);
3842                         spin_unlock_irqrestore(&cmd->t_state_lock,
3843                                         flags);
3844                 }
3845                 return 1;
3846         }
3847
3848         spin_lock_irqsave(&cmd->t_state_lock, flags);
3849         if (!(atomic_read(&cmd->transport_dev_active))) {
3850                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3851                 goto free_pages;
3852         }
3853         atomic_set(&cmd->transport_dev_active, 0);
3854         transport_all_task_dev_remove_state(cmd);
3855         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3856
3857         transport_release_tasks(cmd);
3858
3859 free_pages:
3860         transport_free_pages(cmd);
3861
3862         if (release_to_pool) {
3863                 transport_release_cmd_to_pool(cmd);
3864         } else {
3865                 transport_free_se_cmd(cmd);
3866                 cmd->se_tfo->release_cmd_direct(cmd);
3867         }
3868
3869         return 0;
3870 }
3871
3872 /*
3873  * transport_generic_map_mem_to_cmd - Perform SGL -> struct se_mem map
3874  * @cmd:  Associated se_cmd descriptor
3875  * @mem:  SGL style memory for TCM WRITE / READ
3876  * @sg_mem_num: Number of SGL elements
3877  * @mem_bidi_in: SGL style memory for TCM BIDI READ
3878  * @sg_mem_bidi_num: Number of BIDI READ SGL elements
3879  *
3880  * Return: nonzero return cmd was rejected for -ENOMEM or inproper usage
3881  * of parameters.
3882  */
3883 int transport_generic_map_mem_to_cmd(
3884         struct se_cmd *cmd,
3885         struct scatterlist *sgl,
3886         u32 sgl_count,
3887         struct scatterlist *sgl_bidi,
3888         u32 sgl_bidi_count)
3889 {
3890         int ret;
3891
3892         if (!sgl || !sgl_count)
3893                 return 0;
3894
3895         /*
3896          * Convert sgls (sgl, sgl_bidi) to list of se_mems
3897          */
3898         if ((cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) ||
3899             (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB)) {
3900                 /*
3901                  * For CDB using TCM struct se_mem linked list scatterlist memory
3902                  * processed into a TCM struct se_subsystem_dev, we do the mapping
3903                  * from the passed physical memory to struct se_mem->se_page here.
3904                  */
3905                 ret = transport_map_sg_to_mem(cmd, &cmd->t_mem_list, sgl);
3906                 if (ret < 0)
3907                         return -ENOMEM;
3908
3909                 cmd->t_tasks_se_num = ret;
3910                 /*
3911                  * Setup BIDI READ list of struct se_mem elements
3912                  */
3913                 if (sgl_bidi && sgl_bidi_count) {
3914                         ret = transport_map_sg_to_mem(cmd, &cmd->t_mem_bidi_list, sgl_bidi);
3915                         if (ret < 0)
3916                                 return -ENOMEM;
3917
3918                         cmd->t_tasks_se_bidi_num = ret;
3919                 }
3920                 cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
3921
3922         } else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB) {
3923                 if (sgl_bidi || sgl_bidi_count) {
3924                         printk(KERN_ERR "BIDI-Commands not supported using "
3925                                 "SCF_SCSI_CONTROL_NONSG_IO_CDB\n");
3926                         return -ENOSYS;
3927                 }
3928                 /*
3929                  * For incoming CDBs using a contiguous buffer internal with TCM,
3930                  * save the passed struct scatterlist memory.  After TCM storage object
3931                  * processing has completed for this struct se_cmd, TCM core will call
3932                  * transport_memcpy_[write,read]_contig() as necessary from
3933                  * transport_generic_complete_ok() and transport_write_pending() in order
3934                  * to copy the TCM buffer to/from the original passed *mem in SGL ->
3935                  * struct scatterlist format.
3936                  */
3937                 cmd->se_cmd_flags |= SCF_PASSTHROUGH_CONTIG_TO_SG;
3938                 cmd->t_task_pt_sgl = sgl;
3939                 cmd->t_task_pt_sgl_num = sgl_count;
3940         }
3941
3942         return 0;
3943 }
3944 EXPORT_SYMBOL(transport_generic_map_mem_to_cmd);
3945
3946
3947 static inline long long transport_dev_end_lba(struct se_device *dev)
3948 {
3949         return dev->transport->get_blocks(dev) + 1;
3950 }
3951
3952 static int transport_cmd_get_valid_sectors(struct se_cmd *cmd)
3953 {
3954         struct se_device *dev = cmd->se_dev;
3955         u32 sectors;
3956
3957         if (dev->transport->get_device_type(dev) != TYPE_DISK)
3958                 return 0;
3959
3960         sectors = (cmd->data_length / dev->se_sub_dev->se_dev_attrib.block_size);
3961
3962         if ((cmd->t_task_lba + sectors) >
3963              transport_dev_end_lba(dev)) {
3964                 printk(KERN_ERR "LBA: %llu Sectors: %u exceeds"
3965                         " transport_dev_end_lba(): %llu\n",
3966                         cmd->t_task_lba, sectors,
3967                         transport_dev_end_lba(dev));
3968                 return 0;
3969         }
3970
3971         return sectors;
3972 }
3973
3974 static int transport_new_cmd_obj(struct se_cmd *cmd)
3975 {
3976         struct se_device *dev = cmd->se_dev;
3977         u32 task_cdbs;
3978         u32 rc;
3979
3980         if (!(cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB)) {
3981                 task_cdbs = 1;
3982                 cmd->t_task_list_num = 1;
3983         } else {
3984                 int set_counts = 1;
3985
3986                 /*
3987                  * Setup any BIDI READ tasks and memory from
3988                  * cmd->t_mem_bidi_list so the READ struct se_tasks
3989                  * are queued first for the non pSCSI passthrough case.
3990                  */
3991                 if (!list_empty(&cmd->t_mem_bidi_list) &&
3992                     (dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV)) {
3993                         rc = transport_allocate_tasks(cmd,
3994                                 cmd->t_task_lba,
3995                                 transport_cmd_get_valid_sectors(cmd),
3996                                 DMA_FROM_DEVICE, &cmd->t_mem_bidi_list,
3997                                 set_counts);
3998                         if (!(rc)) {
3999                                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
4000                                 cmd->scsi_sense_reason =
4001                                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
4002                                 return PYX_TRANSPORT_LU_COMM_FAILURE;
4003                         }
4004                         set_counts = 0;
4005                 }
4006                 /*
4007                  * Setup the tasks and memory from cmd->t_mem_list
4008                  * Note for BIDI transfers this will contain the WRITE payload
4009                  */
4010                 task_cdbs = transport_allocate_tasks(cmd,
4011                                 cmd->t_task_lba,
4012                                 transport_cmd_get_valid_sectors(cmd),
4013                                 cmd->data_direction, &cmd->t_mem_list,
4014                                 set_counts);
4015                 if (!(task_cdbs)) {
4016                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
4017                         cmd->scsi_sense_reason =
4018                                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
4019                         return PYX_TRANSPORT_LU_COMM_FAILURE;
4020                 }
4021                 cmd->t_task_list_num = task_cdbs;
4022
4023 #if 0
4024                 printk(KERN_INFO "data_length: %u, LBA: %llu t_tasks_sectors:"
4025                         " %u, t_task_cdbs: %u\n", obj_ptr, cmd->data_length,
4026                         cmd->t_task_lba, cmd->t_tasks_sectors,
4027                         cmd->t_task_cdbs);
4028 #endif
4029         }
4030
4031         atomic_set(&cmd->t_task_cdbs_left, task_cdbs);
4032         atomic_set(&cmd->t_task_cdbs_ex_left, task_cdbs);
4033         atomic_set(&cmd->t_task_cdbs_timeout_left, task_cdbs);
4034         return 0;
4035 }
4036
4037 static int
4038 transport_generic_get_mem(struct se_cmd *cmd, u32 length)
4039 {
4040         struct se_mem *se_mem;
4041
4042         /*
4043          * If the device uses memory mapping this is enough.
4044          */
4045         if (cmd->se_dev->transport->do_se_mem_map)
4046                 return 0;
4047
4048         while (length) {
4049                 se_mem = kmem_cache_zalloc(se_mem_cache, GFP_KERNEL);
4050                 if (!(se_mem)) {
4051                         printk(KERN_ERR "Unable to allocate struct se_mem\n");
4052                         goto out;
4053                 }
4054
4055 /* #warning FIXME Allocate contigous pages for struct se_mem elements */
4056                 se_mem->se_page = alloc_pages(GFP_KERNEL | __GFP_ZERO, 0);
4057                 if (!(se_mem->se_page)) {
4058                         printk(KERN_ERR "alloc_pages() failed\n");
4059                         goto out;
4060                 }
4061
4062                 INIT_LIST_HEAD(&se_mem->se_list);
4063                 se_mem->se_len = min_t(u32, length, PAGE_SIZE);
4064                 list_add_tail(&se_mem->se_list, &cmd->t_mem_list);
4065                 cmd->t_tasks_se_num++;
4066
4067                 DEBUG_MEM("Allocated struct se_mem page(%p) Length(%u)"
4068                         " Offset(%u)\n", se_mem->se_page, se_mem->se_len,
4069                         se_mem->se_off);
4070
4071                 length -= se_mem->se_len;
4072         }
4073
4074         DEBUG_MEM("Allocated total struct se_mem elements(%u)\n",
4075                         cmd->t_tasks_se_num);
4076
4077         return 0;
4078 out:
4079         if (se_mem)
4080                 __free_pages(se_mem->se_page, 0);
4081         kmem_cache_free(se_mem_cache, se_mem);
4082         return -ENOMEM;
4083 }
4084
4085 int transport_init_task_sg(
4086         struct se_task *task,
4087         struct se_mem *in_se_mem,
4088         u32 task_offset)
4089 {
4090         struct se_cmd *se_cmd = task->task_se_cmd;
4091         struct se_device *se_dev = se_cmd->se_dev;
4092         struct se_mem *se_mem = in_se_mem;
4093         struct target_core_fabric_ops *tfo = se_cmd->se_tfo;
4094         u32 sg_length, task_size = task->task_size, task_sg_num_padded;
4095
4096         while (task_size != 0) {
4097                 DEBUG_SC("se_mem->se_page(%p) se_mem->se_len(%u)"
4098                         " se_mem->se_off(%u) task_offset(%u)\n",
4099                         se_mem->se_page, se_mem->se_len,
4100                         se_mem->se_off, task_offset);
4101
4102                 if (task_offset == 0) {
4103                         if (task_size >= se_mem->se_len) {
4104                                 sg_length = se_mem->se_len;
4105
4106                                 if (!(list_is_last(&se_mem->se_list,
4107                                                 &se_cmd->t_mem_list)))
4108                                         se_mem = list_entry(se_mem->se_list.next,
4109                                                         struct se_mem, se_list);
4110                         } else {
4111                                 sg_length = task_size;
4112                                 task_size -= sg_length;
4113                                 goto next;
4114                         }
4115
4116                         DEBUG_SC("sg_length(%u) task_size(%u)\n",
4117                                         sg_length, task_size);
4118                 } else {
4119                         if ((se_mem->se_len - task_offset) > task_size) {
4120                                 sg_length = task_size;
4121                                 task_size -= sg_length;
4122                                 goto next;
4123                          } else {
4124                                 sg_length = (se_mem->se_len - task_offset);
4125
4126                                 if (!(list_is_last(&se_mem->se_list,
4127                                                 &se_cmd->t_mem_list)))
4128                                         se_mem = list_entry(se_mem->se_list.next,
4129                                                         struct se_mem, se_list);
4130                         }
4131
4132                         DEBUG_SC("sg_length(%u) task_size(%u)\n",
4133                                         sg_length, task_size);
4134
4135                         task_offset = 0;
4136                 }
4137                 task_size -= sg_length;
4138 next:
4139                 DEBUG_SC("task[%u] - Reducing task_size to(%u)\n",
4140                         task->task_no, task_size);
4141
4142                 task->task_sg_num++;
4143         }
4144         /*
4145          * Check if the fabric module driver is requesting that all
4146          * struct se_task->task_sg[] be chained together..  If so,
4147          * then allocate an extra padding SG entry for linking and
4148          * marking the end of the chained SGL.
4149          */
4150         if (tfo->task_sg_chaining) {
4151                 task_sg_num_padded = (task->task_sg_num + 1);
4152                 task->task_padded_sg = 1;
4153         } else
4154                 task_sg_num_padded = task->task_sg_num;
4155
4156         task->task_sg = kzalloc(task_sg_num_padded *
4157                         sizeof(struct scatterlist), GFP_KERNEL);
4158         if (!(task->task_sg)) {
4159                 printk(KERN_ERR "Unable to allocate memory for"
4160                                 " task->task_sg\n");
4161                 return -ENOMEM;
4162         }
4163         sg_init_table(&task->task_sg[0], task_sg_num_padded);
4164         /*
4165          * Setup task->task_sg_bidi for SCSI READ payload for
4166          * TCM/pSCSI passthrough if present for BIDI-COMMAND
4167          */
4168         if (!list_empty(&se_cmd->t_mem_bidi_list) &&
4169             (se_dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV)) {
4170                 task->task_sg_bidi = kzalloc(task_sg_num_padded *
4171                                 sizeof(struct scatterlist), GFP_KERNEL);
4172                 if (!(task->task_sg_bidi)) {
4173                         kfree(task->task_sg);
4174                         task->task_sg = NULL;
4175                         printk(KERN_ERR "Unable to allocate memory for"
4176                                 " task->task_sg_bidi\n");
4177                         return -ENOMEM;
4178                 }
4179                 sg_init_table(&task->task_sg_bidi[0], task_sg_num_padded);
4180         }
4181         /*
4182          * For the chaining case, setup the proper end of SGL for the
4183          * initial submission struct task into struct se_subsystem_api.
4184          * This will be cleared later by transport_do_task_sg_chain()
4185          */
4186         if (task->task_padded_sg) {
4187                 sg_mark_end(&task->task_sg[task->task_sg_num - 1]);
4188                 /*
4189                  * Added the 'if' check before marking end of bi-directional
4190                  * scatterlist (which gets created only in case of request
4191                  * (RD + WR).
4192                  */
4193                 if (task->task_sg_bidi)
4194                         sg_mark_end(&task->task_sg_bidi[task->task_sg_num - 1]);
4195         }
4196
4197         DEBUG_SC("Successfully allocated task->task_sg_num(%u),"
4198                 " task_sg_num_padded(%u)\n", task->task_sg_num,
4199                 task_sg_num_padded);
4200
4201         return task->task_sg_num;
4202 }
4203
4204 /* Reduce sectors if they are too long for the device */
4205 static inline sector_t transport_limit_task_sectors(
4206         struct se_device *dev,
4207         unsigned long long lba,
4208         sector_t sectors)
4209 {
4210         sectors = min_t(sector_t, sectors, dev->se_sub_dev->se_dev_attrib.max_sectors);
4211
4212         if (dev->transport->get_device_type(dev) == TYPE_DISK)
4213                 if ((lba + sectors) > transport_dev_end_lba(dev))
4214                         sectors = ((transport_dev_end_lba(dev) - lba) + 1);
4215
4216         return sectors;
4217 }
4218
4219 /*
4220  * Convert a sgl into a linked list of se_mems.
4221  */
4222 static int transport_map_sg_to_mem(
4223         struct se_cmd *cmd,
4224         struct list_head *se_mem_list,
4225         struct scatterlist *sg)
4226 {
4227         struct se_mem *se_mem;
4228         u32 cmd_size = cmd->data_length;
4229         int sg_count = 0;
4230
4231         WARN_ON(!sg);
4232
4233         while (cmd_size) {
4234                 /*
4235                  * NOTE: it is safe to return -ENOMEM at any time in creating this
4236                  * list because transport_free_pages() will eventually be called, and is
4237                  * smart enough to deallocate all list items for sg and sg_bidi lists.
4238                  */
4239                 se_mem = kmem_cache_zalloc(se_mem_cache, GFP_KERNEL);
4240                 if (!(se_mem)) {
4241                         printk(KERN_ERR "Unable to allocate struct se_mem\n");
4242                         return -ENOMEM;
4243                 }
4244                 INIT_LIST_HEAD(&se_mem->se_list);
4245                 DEBUG_MEM("sg_to_mem: Starting loop with cmd_size: %u"
4246                         " sg_page: %p offset: %d length: %d\n", cmd_size,
4247                         sg_page(sg), sg->offset, sg->length);
4248
4249                 se_mem->se_page = sg_page(sg);
4250                 se_mem->se_off = sg->offset;
4251
4252                 if (cmd_size > sg->length) {
4253                         se_mem->se_len = sg->length;
4254                         sg = sg_next(sg);
4255                 } else
4256                         se_mem->se_len = cmd_size;
4257
4258                 cmd_size -= se_mem->se_len;
4259                 sg_count++;
4260
4261                 DEBUG_MEM("sg_to_mem: sg_count: %u cmd_size: %u\n",
4262                                 sg_count, cmd_size);
4263                 DEBUG_MEM("sg_to_mem: Final se_page: %p se_off: %d se_len: %d\n",
4264                                 se_mem->se_page, se_mem->se_off, se_mem->se_len);
4265
4266                 list_add_tail(&se_mem->se_list, se_mem_list);
4267         }
4268
4269         DEBUG_MEM("task[0] - Mapped(%u) struct scatterlist segments\n", sg_count);
4270
4271         return sg_count;
4272 }
4273
4274 /*      transport_map_mem_to_sg():
4275  *
4276  *
4277  */
4278 int transport_map_mem_to_sg(
4279         struct se_task *task,
4280         struct list_head *se_mem_list,
4281         struct scatterlist *sg,
4282         struct se_mem *in_se_mem,
4283         struct se_mem **out_se_mem,
4284         u32 *se_mem_cnt,
4285         u32 *task_offset)
4286 {
4287         struct se_cmd *se_cmd = task->task_se_cmd;
4288         struct se_mem *se_mem = in_se_mem;
4289         u32 task_size = task->task_size, sg_no = 0;
4290
4291         if (!sg) {
4292                 printk(KERN_ERR "Unable to locate valid struct"
4293                                 " scatterlist pointer\n");
4294                 return -EINVAL;
4295         }
4296
4297         while (task_size != 0) {
4298                 /*
4299                  * Setup the contiguous array of scatterlists for
4300                  * this struct se_task.
4301                  */
4302                 sg_assign_page(sg, se_mem->se_page);
4303
4304                 if (*task_offset == 0) {
4305                         sg->offset = se_mem->se_off;
4306
4307                         if (task_size >= se_mem->se_len) {
4308                                 sg->length = se_mem->se_len;
4309
4310                                 if (!(list_is_last(&se_mem->se_list,
4311                                                 &se_cmd->t_mem_list))) {
4312                                         se_mem = list_entry(se_mem->se_list.next,
4313                                                         struct se_mem, se_list);
4314                                         (*se_mem_cnt)++;
4315                                 }
4316                         } else {
4317                                 sg->length = task_size;
4318                                 /*
4319                                  * Determine if we need to calculate an offset
4320                                  * into the struct se_mem on the next go around..
4321                                  */
4322                                 task_size -= sg->length;
4323                                 if (!(task_size))
4324                                         *task_offset = sg->length;
4325
4326                                 goto next;
4327                         }
4328
4329                 } else {
4330                         sg->offset = (*task_offset + se_mem->se_off);
4331
4332                         if ((se_mem->se_len - *task_offset) > task_size) {
4333                                 sg->length = task_size;
4334                                 /*
4335                                  * Determine if we need to calculate an offset
4336                                  * into the struct se_mem on the next go around..
4337                                  */
4338                                 task_size -= sg->length;
4339                                 if (!(task_size))
4340                                         *task_offset += sg->length;
4341
4342                                 goto next;
4343                         } else {
4344                                 sg->length = (se_mem->se_len - *task_offset);
4345
4346                                 if (!(list_is_last(&se_mem->se_list,
4347                                                 &se_cmd->t_mem_list))) {
4348                                         se_mem = list_entry(se_mem->se_list.next,
4349                                                         struct se_mem, se_list);
4350                                         (*se_mem_cnt)++;
4351                                 }
4352                         }
4353
4354                         *task_offset = 0;
4355                 }
4356                 task_size -= sg->length;
4357 next:
4358                 DEBUG_MEM("task[%u] mem_to_sg - sg[%u](%p)(%u)(%u) - Reducing"
4359                         " task_size to(%u), task_offset: %u\n", task->task_no, sg_no,
4360                         sg_page(sg), sg->length, sg->offset, task_size, *task_offset);
4361
4362                 sg_no++;
4363                 if (!(task_size))
4364                         break;
4365
4366                 sg = sg_next(sg);
4367
4368                 if (task_size > se_cmd->data_length)
4369                         BUG();
4370         }
4371         *out_se_mem = se_mem;
4372
4373         DEBUG_MEM("task[%u] - Mapped(%u) struct se_mem segments to total(%u)"
4374                 " SGs\n", task->task_no, *se_mem_cnt, sg_no);
4375
4376         return 0;
4377 }
4378
4379 /*
4380  * This function can be used by HW target mode drivers to create a linked
4381  * scatterlist from all contiguously allocated struct se_task->task_sg[].
4382  * This is intended to be called during the completion path by TCM Core
4383  * when struct target_core_fabric_ops->check_task_sg_chaining is enabled.
4384  */
4385 void transport_do_task_sg_chain(struct se_cmd *cmd)
4386 {
4387         struct scatterlist *sg_head = NULL, *sg_link = NULL, *sg_first = NULL;
4388         struct scatterlist *sg_head_cur = NULL, *sg_link_cur = NULL;
4389         struct scatterlist *sg, *sg_end = NULL, *sg_end_cur = NULL;
4390         struct se_task *task;
4391         struct target_core_fabric_ops *tfo = cmd->se_tfo;
4392         u32 task_sg_num = 0, sg_count = 0;
4393         int i;
4394
4395         if (tfo->task_sg_chaining == 0) {
4396                 printk(KERN_ERR "task_sg_chaining is diabled for fabric module:"
4397                                 " %s\n", tfo->get_fabric_name());
4398                 dump_stack();
4399                 return;
4400         }
4401         /*
4402          * Walk the struct se_task list and setup scatterlist chains
4403          * for each contiguously allocated struct se_task->task_sg[].
4404          */
4405         list_for_each_entry(task, &cmd->t_task_list, t_list) {
4406                 if (!(task->task_sg) || !(task->task_padded_sg))
4407                         continue;
4408
4409                 if (sg_head && sg_link) {
4410                         sg_head_cur = &task->task_sg[0];
4411                         sg_link_cur = &task->task_sg[task->task_sg_num];
4412                         /*
4413                          * Either add chain or mark end of scatterlist
4414                          */
4415                         if (!(list_is_last(&task->t_list,
4416                                         &cmd->t_task_list))) {
4417                                 /*
4418                                  * Clear existing SGL termination bit set in
4419                                  * transport_init_task_sg(), see sg_mark_end()
4420                                  */
4421                                 sg_end_cur = &task->task_sg[task->task_sg_num - 1];
4422                                 sg_end_cur->page_link &= ~0x02;
4423
4424                                 sg_chain(sg_head, task_sg_num, sg_head_cur);
4425                                 sg_count += task->task_sg_num;
4426                                 task_sg_num = (task->task_sg_num + 1);
4427                         } else {
4428                                 sg_chain(sg_head, task_sg_num, sg_head_cur);
4429                                 sg_count += task->task_sg_num;
4430                                 task_sg_num = task->task_sg_num;
4431                         }
4432
4433                         sg_head = sg_head_cur;
4434                         sg_link = sg_link_cur;
4435                         continue;
4436                 }
4437                 sg_head = sg_first = &task->task_sg[0];
4438                 sg_link = &task->task_sg[task->task_sg_num];
4439                 /*
4440                  * Check for single task..
4441                  */
4442                 if (!(list_is_last(&task->t_list, &cmd->t_task_list))) {
4443                         /*
4444                          * Clear existing SGL termination bit set in
4445                          * transport_init_task_sg(), see sg_mark_end()
4446                          */
4447                         sg_end = &task->task_sg[task->task_sg_num - 1];
4448                         sg_end->page_link &= ~0x02;
4449                         sg_count += task->task_sg_num;
4450                         task_sg_num = (task->task_sg_num + 1);
4451                 } else {
4452                         sg_count += task->task_sg_num;
4453                         task_sg_num = task->task_sg_num;
4454                 }
4455         }
4456         /*
4457          * Setup the starting pointer and total t_tasks_sg_linked_no including
4458          * padding SGs for linking and to mark the end.
4459          */
4460         cmd->t_tasks_sg_chained = sg_first;
4461         cmd->t_tasks_sg_chained_no = sg_count;
4462
4463         DEBUG_CMD_M("Setup cmd: %p cmd->t_tasks_sg_chained: %p and"
4464                 " t_tasks_sg_chained_no: %u\n", cmd, cmd->t_tasks_sg_chained,
4465                 cmd->t_tasks_sg_chained_no);
4466
4467         for_each_sg(cmd->t_tasks_sg_chained, sg,
4468                         cmd->t_tasks_sg_chained_no, i) {
4469
4470                 DEBUG_CMD_M("SG[%d]: %p page: %p length: %d offset: %d\n",
4471                         i, sg, sg_page(sg), sg->length, sg->offset);
4472                 if (sg_is_chain(sg))
4473                         DEBUG_CMD_M("SG: %p sg_is_chain=1\n", sg);
4474                 if (sg_is_last(sg))
4475                         DEBUG_CMD_M("SG: %p sg_is_last=1\n", sg);
4476         }
4477 }
4478 EXPORT_SYMBOL(transport_do_task_sg_chain);
4479
4480 static int transport_do_se_mem_map(
4481         struct se_device *dev,
4482         struct se_task *task,
4483         struct list_head *se_mem_list,
4484         void *in_mem,
4485         struct se_mem *in_se_mem,
4486         struct se_mem **out_se_mem,
4487         u32 *se_mem_cnt,
4488         u32 *task_offset_in)
4489 {
4490         u32 task_offset = *task_offset_in;
4491         int ret = 0;
4492         /*
4493          * se_subsystem_api_t->do_se_mem_map is used when internal allocation
4494          * has been done by the transport plugin.
4495          */
4496         if (dev->transport->do_se_mem_map) {
4497                 ret = dev->transport->do_se_mem_map(task, se_mem_list,
4498                                 in_mem, in_se_mem, out_se_mem, se_mem_cnt,
4499                                 task_offset_in);
4500                 if (ret == 0)
4501                         task->task_se_cmd->t_tasks_se_num += *se_mem_cnt;
4502
4503                 return ret;
4504         }
4505
4506         BUG_ON(list_empty(se_mem_list));
4507         /*
4508          * This is the normal path for all normal non BIDI and BIDI-COMMAND
4509          * WRITE payloads..  If we need to do BIDI READ passthrough for
4510          * TCM/pSCSI the first call to transport_do_se_mem_map ->
4511          * transport_init_task_sg() -> transport_map_mem_to_sg() will do the
4512          * allocation for task->task_sg_bidi, and the subsequent call to
4513          * transport_do_se_mem_map() from transport_generic_get_cdb_count()
4514          */
4515         if (!(task->task_sg_bidi)) {
4516                 /*
4517                  * Assume default that transport plugin speaks preallocated
4518                  * scatterlists.
4519                  */
4520                 ret = transport_init_task_sg(task, in_se_mem, task_offset);
4521                 if (ret <= 0)
4522                         return ret;
4523                 /*
4524                  * struct se_task->task_sg now contains the struct scatterlist array.
4525                  */
4526                 return transport_map_mem_to_sg(task, se_mem_list, task->task_sg,
4527                                         in_se_mem, out_se_mem, se_mem_cnt,
4528                                         task_offset_in);
4529         }
4530         /*
4531          * Handle the se_mem_list -> struct task->task_sg_bidi
4532          * memory map for the extra BIDI READ payload
4533          */
4534         return transport_map_mem_to_sg(task, se_mem_list, task->task_sg_bidi,
4535                                 in_se_mem, out_se_mem, se_mem_cnt,
4536                                 task_offset_in);
4537 }
4538
4539 /*
4540  * Break up cmd into chunks transport can handle
4541  */
4542 static u32 transport_allocate_tasks(
4543         struct se_cmd *cmd,
4544         unsigned long long lba,
4545         u32 sectors,
4546         enum dma_data_direction data_direction,
4547         struct list_head *mem_list,
4548         int set_counts)
4549 {
4550         unsigned char *cdb = NULL;
4551         struct se_task *task;
4552         struct se_mem *se_mem = NULL;
4553         struct se_mem *se_mem_lout = NULL;
4554         struct se_mem *se_mem_bidi = NULL;
4555         struct se_mem *se_mem_bidi_lout = NULL;
4556         struct se_device *dev = cmd->se_dev;
4557         int ret;
4558         u32 task_offset_in = 0;
4559         u32 se_mem_cnt = 0;
4560         u32 se_mem_bidi_cnt = 0;
4561         u32 task_cdbs = 0;
4562
4563         BUG_ON(!mem_list);
4564         /*
4565          * While using RAMDISK_DR backstores is the only case where
4566          * mem_list will ever be empty at this point.
4567          */
4568         if (!(list_empty(mem_list)))
4569                 se_mem = list_first_entry(mem_list, struct se_mem, se_list);
4570         /*
4571          * Check for extra se_mem_bidi mapping for BIDI-COMMANDs to
4572          * struct se_task->task_sg_bidi for TCM/pSCSI passthrough operation
4573          */
4574         if (!list_empty(&cmd->t_mem_bidi_list) &&
4575             (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV))
4576                 se_mem_bidi = list_first_entry(&cmd->t_mem_bidi_list,
4577                                         struct se_mem, se_list);
4578
4579         while (sectors) {
4580                 sector_t limited_sectors;
4581
4582                 DEBUG_VOL("ITT[0x%08x] LBA(%llu) SectorsLeft(%u) EOBJ(%llu)\n",
4583                         cmd->se_tfo->get_task_tag(cmd), lba, sectors,
4584                         transport_dev_end_lba(dev));
4585
4586                 limited_sectors = transport_limit_task_sectors(dev, lba, sectors);
4587                 if (!limited_sectors)
4588                         break;
4589
4590                 task = transport_generic_get_task(cmd, data_direction);
4591                 if (!task)
4592                         goto out;
4593
4594                 task->task_lba = lba;
4595                 task->task_sectors = limited_sectors;
4596                 lba += task->task_sectors;
4597                 sectors -= task->task_sectors;
4598                 task->task_size = (task->task_sectors *
4599                                    dev->se_sub_dev->se_dev_attrib.block_size);
4600
4601                 cdb = dev->transport->get_cdb(task);
4602                 /* Should be part of task, can't fail */
4603                 BUG_ON(!cdb);
4604
4605                 memcpy(cdb, cmd->t_task_cdb,
4606                        scsi_command_size(cmd->t_task_cdb));
4607
4608                 /* Update new cdb with updated lba/sectors */
4609                 cmd->transport_split_cdb(task->task_lba,
4610                                          &task->task_sectors, cdb);
4611
4612                 /*
4613                  * Perform the SE OBJ plugin and/or Transport plugin specific
4614                  * mapping for cmd->t_mem_list. And setup the
4615                  * task->task_sg and if necessary task->task_sg_bidi
4616                  */
4617                 ret = transport_do_se_mem_map(dev, task, mem_list,
4618                                 NULL, se_mem, &se_mem_lout, &se_mem_cnt,
4619                                 &task_offset_in);
4620                 if (ret < 0)
4621                         goto out;
4622
4623                 se_mem = se_mem_lout;
4624                 /*
4625                  * Setup the cmd->t_mem_bidi_list -> task->task_sg_bidi
4626                  * mapping for SCSI READ for BIDI-COMMAND passthrough with TCM/pSCSI
4627                  *
4628                  * Note that the first call to transport_do_se_mem_map() above will
4629                  * allocate struct se_task->task_sg_bidi in transport_do_se_mem_map()
4630                  * -> transport_init_task_sg(), and the second here will do the
4631                  * mapping for SCSI READ for BIDI-COMMAND passthrough with TCM/pSCSI.
4632                  */
4633                 if (task->task_sg_bidi != NULL) {
4634                         ret = transport_do_se_mem_map(dev, task,
4635                                 &cmd->t_mem_bidi_list, NULL,
4636                                 se_mem_bidi, &se_mem_bidi_lout, &se_mem_bidi_cnt,
4637                                 &task_offset_in);
4638                         if (ret < 0)
4639                                 goto out;
4640
4641                         se_mem_bidi = se_mem_bidi_lout;
4642                 }
4643                 task_cdbs++;
4644
4645                 DEBUG_VOL("Incremented task_cdbs(%u) task->task_sg_num(%u)\n",
4646                                 task_cdbs, task->task_sg_num);
4647         }
4648
4649         if (set_counts) {
4650                 atomic_inc(&cmd->t_fe_count);
4651                 atomic_inc(&cmd->t_se_count);
4652         }
4653
4654         DEBUG_VOL("ITT[0x%08x] total %s cdbs(%u)\n",
4655                 cmd->se_tfo->get_task_tag(cmd), (data_direction == DMA_TO_DEVICE)
4656                 ? "DMA_TO_DEVICE" : "DMA_FROM_DEVICE", task_cdbs);
4657
4658         return task_cdbs;
4659 out:
4660         return 0;
4661 }
4662
4663 static int
4664 transport_map_control_cmd_to_task(struct se_cmd *cmd)
4665 {
4666         struct se_device *dev = cmd->se_dev;
4667         unsigned char *cdb;
4668         struct se_task *task;
4669         int ret;
4670
4671         task = transport_generic_get_task(cmd, cmd->data_direction);
4672         if (!task)
4673                 return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
4674
4675         cdb = dev->transport->get_cdb(task);
4676         BUG_ON(!cdb);
4677         memcpy(cdb, cmd->t_task_cdb,
4678                scsi_command_size(cmd->t_task_cdb));
4679
4680         task->task_size = cmd->data_length;
4681         task->task_sg_num =
4682                 (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB) ? 1 : 0;
4683
4684         atomic_inc(&cmd->t_fe_count);
4685         atomic_inc(&cmd->t_se_count);
4686
4687         if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB) {
4688                 struct se_mem *se_mem = NULL, *se_mem_lout = NULL;
4689                 u32 se_mem_cnt = 0, task_offset = 0;
4690
4691                 if (!list_empty(&cmd->t_mem_list))
4692                         se_mem = list_first_entry(&cmd->t_mem_list,
4693                                         struct se_mem, se_list);
4694
4695                 ret = transport_do_se_mem_map(dev, task,
4696                                 &cmd->t_mem_list, NULL, se_mem,
4697                                 &se_mem_lout, &se_mem_cnt, &task_offset);
4698                 if (ret < 0)
4699                         return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
4700
4701                 if (dev->transport->map_task_SG)
4702                         return dev->transport->map_task_SG(task);
4703                 return 0;
4704         } else if (cmd->se_cmd_flags & SCF_SCSI_CONTROL_NONSG_IO_CDB) {
4705                 if (dev->transport->map_task_non_SG)
4706                         return dev->transport->map_task_non_SG(task);
4707                 return 0;
4708         } else if (cmd->se_cmd_flags & SCF_SCSI_NON_DATA_CDB) {
4709                 if (dev->transport->cdb_none)
4710                         return dev->transport->cdb_none(task);
4711                 return 0;
4712         } else {
4713                 BUG();
4714                 return PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES;
4715         }
4716 }
4717
4718 /*       transport_generic_new_cmd(): Called from transport_processing_thread()
4719  *
4720  *       Allocate storage transport resources from a set of values predefined
4721  *       by transport_generic_cmd_sequencer() from the iSCSI Target RX process.
4722  *       Any non zero return here is treated as an "out of resource' op here.
4723  */
4724         /*
4725          * Generate struct se_task(s) and/or their payloads for this CDB.
4726          */
4727 int transport_generic_new_cmd(struct se_cmd *cmd)
4728 {
4729         struct se_task *task;
4730         struct se_device *dev = cmd->se_dev;
4731         int ret = 0;
4732
4733         /*
4734          * Determine is the TCM fabric module has already allocated physical
4735          * memory, and is directly calling transport_generic_map_mem_to_cmd()
4736          * to setup beforehand the linked list of physical memory at
4737          * cmd->t_mem_list of struct se_mem->se_page
4738          */
4739         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)) {
4740                 ret = transport_allocate_resources(cmd);
4741                 if (ret < 0)
4742                         return ret;
4743         }
4744
4745         ret = transport_new_cmd_obj(cmd);
4746         if (ret < 0)
4747                 return ret;
4748
4749         if (cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) {
4750                 list_for_each_entry(task, &cmd->t_task_list, t_list) {
4751                         if (atomic_read(&task->task_sent))
4752                                 continue;
4753                         if (!dev->transport->map_task_SG)
4754                                 continue;
4755
4756                         ret = dev->transport->map_task_SG(task);
4757                         if (ret < 0)
4758                                 return ret;
4759                 }
4760         } else {
4761                 ret = transport_map_control_cmd_to_task(cmd);
4762                 if (ret < 0)
4763                         return ret;
4764         }
4765
4766         /*
4767          * For WRITEs, let the fabric know its buffer is ready..
4768          * This WRITE struct se_cmd (and all of its associated struct se_task's)
4769          * will be added to the struct se_device execution queue after its WRITE
4770          * data has arrived. (ie: It gets handled by the transport processing
4771          * thread a second time)
4772          */
4773         if (cmd->data_direction == DMA_TO_DEVICE) {
4774                 transport_add_tasks_to_state_queue(cmd);
4775                 return transport_generic_write_pending(cmd);
4776         }
4777         /*
4778          * Everything else but a WRITE, add the struct se_cmd's struct se_task's
4779          * to the execution queue.
4780          */
4781         transport_execute_tasks(cmd);
4782         return 0;
4783 }
4784 EXPORT_SYMBOL(transport_generic_new_cmd);
4785
4786 /*      transport_generic_process_write():
4787  *
4788  *
4789  */
4790 void transport_generic_process_write(struct se_cmd *cmd)
4791 {
4792 #if 0
4793         /*
4794          * Copy SCSI Presented DTL sector(s) from received buffers allocated to
4795          * original EDTL
4796          */
4797         if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
4798                 if (!cmd->t_tasks_se_num) {
4799                         unsigned char *dst, *buf =
4800                                 (unsigned char *)cmd->t_task_buf;
4801
4802                         dst = kzalloc(cmd->cmd_spdtl), GFP_KERNEL);
4803                         if (!(dst)) {
4804                                 printk(KERN_ERR "Unable to allocate memory for"
4805                                                 " WRITE underflow\n");
4806                                 transport_generic_request_failure(cmd, NULL,
4807                                         PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
4808                                 return;
4809                         }
4810                         memcpy(dst, buf, cmd->cmd_spdtl);
4811
4812                         kfree(cmd->t_task_buf);
4813                         cmd->t_task_buf = dst;
4814                 } else {
4815                         struct scatterlist *sg =
4816                                 (struct scatterlist *sg)cmd->t_task_buf;
4817                         struct scatterlist *orig_sg;
4818
4819                         orig_sg = kzalloc(sizeof(struct scatterlist) *
4820                                         cmd->t_tasks_se_num,
4821                                         GFP_KERNEL))) {
4822                         if (!(orig_sg)) {
4823                                 printk(KERN_ERR "Unable to allocate memory"
4824                                                 " for WRITE underflow\n");
4825                                 transport_generic_request_failure(cmd, NULL,
4826                                         PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
4827                                 return;
4828                         }
4829
4830                         memcpy(orig_sg, cmd->t_task_buf,
4831                                         sizeof(struct scatterlist) *
4832                                         cmd->t_tasks_se_num);
4833
4834                         cmd->data_length = cmd->cmd_spdtl;
4835                         /*
4836                          * FIXME, clear out original struct se_task and state
4837                          * information.
4838                          */
4839                         if (transport_generic_new_cmd(cmd) < 0) {
4840                                 transport_generic_request_failure(cmd, NULL,
4841                                         PYX_TRANSPORT_REQ_TOO_MANY_SECTORS, 1);
4842                                 kfree(orig_sg);
4843                                 return;
4844                         }
4845
4846                         transport_memcpy_write_sg(cmd, orig_sg);
4847                 }
4848         }
4849 #endif
4850         transport_execute_tasks(cmd);
4851 }
4852 EXPORT_SYMBOL(transport_generic_process_write);
4853
4854 /*      transport_generic_write_pending():
4855  *
4856  *
4857  */
4858 static int transport_generic_write_pending(struct se_cmd *cmd)
4859 {
4860         unsigned long flags;
4861         int ret;
4862
4863         spin_lock_irqsave(&cmd->t_state_lock, flags);
4864         cmd->t_state = TRANSPORT_WRITE_PENDING;
4865         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4866         /*
4867          * For the TCM control CDBs using a contiguous buffer, do the memcpy
4868          * from the passed Linux/SCSI struct scatterlist located at
4869          * se_cmd->t_task_pt_sgl to the contiguous buffer at
4870          * se_cmd->t_task_buf.
4871          */
4872         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_CONTIG_TO_SG)
4873                 sg_copy_to_buffer(cmd->t_task_pt_sgl,
4874                                     cmd->t_task_pt_sgl_num,
4875                                     cmd->t_task_buf,
4876                                     cmd->data_length);
4877         /*
4878          * Clear the se_cmd for WRITE_PENDING status in order to set
4879          * cmd->t_transport_active=0 so that transport_generic_handle_data
4880          * can be called from HW target mode interrupt code.  This is safe
4881          * to be called with transport_off=1 before the cmd->se_tfo->write_pending
4882          * because the se_cmd->se_lun pointer is not being cleared.
4883          */
4884         transport_cmd_check_stop(cmd, 1, 0);
4885
4886         /*
4887          * Call the fabric write_pending function here to let the
4888          * frontend know that WRITE buffers are ready.
4889          */
4890         ret = cmd->se_tfo->write_pending(cmd);
4891         if (ret < 0)
4892                 return ret;
4893
4894         return PYX_TRANSPORT_WRITE_PENDING;
4895 }
4896
4897 /*      transport_release_cmd_to_pool():
4898  *
4899  *
4900  */
4901 void transport_release_cmd_to_pool(struct se_cmd *cmd)
4902 {
4903         BUG_ON(!cmd->se_tfo);
4904
4905         transport_free_se_cmd(cmd);
4906         cmd->se_tfo->release_cmd_to_pool(cmd);
4907 }
4908 EXPORT_SYMBOL(transport_release_cmd_to_pool);
4909
4910 /*      transport_generic_free_cmd():
4911  *
4912  *      Called from processing frontend to release storage engine resources
4913  */
4914 void transport_generic_free_cmd(
4915         struct se_cmd *cmd,
4916         int wait_for_tasks,
4917         int release_to_pool,
4918         int session_reinstatement)
4919 {
4920         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD))
4921                 transport_release_cmd_to_pool(cmd);
4922         else {
4923                 core_dec_lacl_count(cmd->se_sess->se_node_acl, cmd);
4924
4925                 if (cmd->se_lun) {
4926 #if 0
4927                         printk(KERN_INFO "cmd: %p ITT: 0x%08x contains"
4928                                 " cmd->se_lun\n", cmd,
4929                                 cmd->se_tfo->get_task_tag(cmd));
4930 #endif
4931                         transport_lun_remove_cmd(cmd);
4932                 }
4933
4934                 if (wait_for_tasks && cmd->transport_wait_for_tasks)
4935                         cmd->transport_wait_for_tasks(cmd, 0, 0);
4936
4937                 transport_free_dev_tasks(cmd);
4938
4939                 transport_generic_remove(cmd, release_to_pool,
4940                                 session_reinstatement);
4941         }
4942 }
4943 EXPORT_SYMBOL(transport_generic_free_cmd);
4944
4945 static void transport_nop_wait_for_tasks(
4946         struct se_cmd *cmd,
4947         int remove_cmd,
4948         int session_reinstatement)
4949 {
4950         return;
4951 }
4952
4953 /*      transport_lun_wait_for_tasks():
4954  *
4955  *      Called from ConfigFS context to stop the passed struct se_cmd to allow
4956  *      an struct se_lun to be successfully shutdown.
4957  */
4958 static int transport_lun_wait_for_tasks(struct se_cmd *cmd, struct se_lun *lun)
4959 {
4960         unsigned long flags;
4961         int ret;
4962         /*
4963          * If the frontend has already requested this struct se_cmd to
4964          * be stopped, we can safely ignore this struct se_cmd.
4965          */
4966         spin_lock_irqsave(&cmd->t_state_lock, flags);
4967         if (atomic_read(&cmd->t_transport_stop)) {
4968                 atomic_set(&cmd->transport_lun_stop, 0);
4969                 DEBUG_TRANSPORT_S("ConfigFS ITT[0x%08x] - t_transport_stop =="
4970                         " TRUE, skipping\n", cmd->se_tfo->get_task_tag(cmd));
4971                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4972                 transport_cmd_check_stop(cmd, 1, 0);
4973                 return -EPERM;
4974         }
4975         atomic_set(&cmd->transport_lun_fe_stop, 1);
4976         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4977
4978         wake_up_interruptible(&cmd->se_dev->dev_queue_obj.thread_wq);
4979
4980         ret = transport_stop_tasks_for_cmd(cmd);
4981
4982         DEBUG_TRANSPORT_S("ConfigFS: cmd: %p t_task_cdbs: %d stop tasks ret:"
4983                         " %d\n", cmd, cmd->t_task_cdbs, ret);
4984         if (!ret) {
4985                 DEBUG_TRANSPORT_S("ConfigFS: ITT[0x%08x] - stopping cmd....\n",
4986                                 cmd->se_tfo->get_task_tag(cmd));
4987                 wait_for_completion(&cmd->transport_lun_stop_comp);
4988                 DEBUG_TRANSPORT_S("ConfigFS: ITT[0x%08x] - stopped cmd....\n",
4989                                 cmd->se_tfo->get_task_tag(cmd));
4990         }
4991         transport_remove_cmd_from_queue(cmd, &cmd->se_dev->dev_queue_obj);
4992
4993         return 0;
4994 }
4995
4996 /* #define DEBUG_CLEAR_LUN */
4997 #ifdef DEBUG_CLEAR_LUN
4998 #define DEBUG_CLEAR_L(x...) printk(KERN_INFO x)
4999 #else
5000 #define DEBUG_CLEAR_L(x...)
5001 #endif
5002
5003 static void __transport_clear_lun_from_sessions(struct se_lun *lun)
5004 {
5005         struct se_cmd *cmd = NULL;
5006         unsigned long lun_flags, cmd_flags;
5007         /*
5008          * Do exception processing and return CHECK_CONDITION status to the
5009          * Initiator Port.
5010          */
5011         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
5012         while (!list_empty(&lun->lun_cmd_list)) {
5013                 cmd = list_first_entry(&lun->lun_cmd_list,
5014                        struct se_cmd, se_lun_node);
5015                 list_del(&cmd->se_lun_node);
5016
5017                 atomic_set(&cmd->transport_lun_active, 0);
5018                 /*
5019                  * This will notify iscsi_target_transport.c:
5020                  * transport_cmd_check_stop() that a LUN shutdown is in
5021                  * progress for the iscsi_cmd_t.
5022                  */
5023                 spin_lock(&cmd->t_state_lock);
5024                 DEBUG_CLEAR_L("SE_LUN[%d] - Setting cmd->transport"
5025                         "_lun_stop for  ITT: 0x%08x\n",
5026                         cmd->se_lun->unpacked_lun,
5027                         cmd->se_tfo->get_task_tag(cmd));
5028                 atomic_set(&cmd->transport_lun_stop, 1);
5029                 spin_unlock(&cmd->t_state_lock);
5030
5031                 spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
5032
5033                 if (!(cmd->se_lun)) {
5034                         printk(KERN_ERR "ITT: 0x%08x, [i,t]_state: %u/%u\n",
5035                                 cmd->se_tfo->get_task_tag(cmd),
5036                                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
5037                         BUG();
5038                 }
5039                 /*
5040                  * If the Storage engine still owns the iscsi_cmd_t, determine
5041                  * and/or stop its context.
5042                  */
5043                 DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x before transport"
5044                         "_lun_wait_for_tasks()\n", cmd->se_lun->unpacked_lun,
5045                         cmd->se_tfo->get_task_tag(cmd));
5046
5047                 if (transport_lun_wait_for_tasks(cmd, cmd->se_lun) < 0) {
5048                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
5049                         continue;
5050                 }
5051
5052                 DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x after transport_lun"
5053                         "_wait_for_tasks(): SUCCESS\n",
5054                         cmd->se_lun->unpacked_lun,
5055                         cmd->se_tfo->get_task_tag(cmd));
5056
5057                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
5058                 if (!(atomic_read(&cmd->transport_dev_active))) {
5059                         spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
5060                         goto check_cond;
5061                 }
5062                 atomic_set(&cmd->transport_dev_active, 0);
5063                 transport_all_task_dev_remove_state(cmd);
5064                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
5065
5066                 transport_free_dev_tasks(cmd);
5067                 /*
5068                  * The Storage engine stopped this struct se_cmd before it was
5069                  * send to the fabric frontend for delivery back to the
5070                  * Initiator Node.  Return this SCSI CDB back with an
5071                  * CHECK_CONDITION status.
5072                  */
5073 check_cond:
5074                 transport_send_check_condition_and_sense(cmd,
5075                                 TCM_NON_EXISTENT_LUN, 0);
5076                 /*
5077                  *  If the fabric frontend is waiting for this iscsi_cmd_t to
5078                  * be released, notify the waiting thread now that LU has
5079                  * finished accessing it.
5080                  */
5081                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
5082                 if (atomic_read(&cmd->transport_lun_fe_stop)) {
5083                         DEBUG_CLEAR_L("SE_LUN[%d] - Detected FE stop for"
5084                                 " struct se_cmd: %p ITT: 0x%08x\n",
5085                                 lun->unpacked_lun,
5086                                 cmd, cmd->se_tfo->get_task_tag(cmd));
5087
5088                         spin_unlock_irqrestore(&cmd->t_state_lock,
5089                                         cmd_flags);
5090                         transport_cmd_check_stop(cmd, 1, 0);
5091                         complete(&cmd->transport_lun_fe_stop_comp);
5092                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
5093                         continue;
5094                 }
5095                 DEBUG_CLEAR_L("SE_LUN[%d] - ITT: 0x%08x finished processing\n",
5096                         lun->unpacked_lun, cmd->se_tfo->get_task_tag(cmd));
5097
5098                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
5099                 spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
5100         }
5101         spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
5102 }
5103
5104 static int transport_clear_lun_thread(void *p)
5105 {
5106         struct se_lun *lun = (struct se_lun *)p;
5107
5108         __transport_clear_lun_from_sessions(lun);
5109         complete(&lun->lun_shutdown_comp);
5110
5111         return 0;
5112 }
5113
5114 int transport_clear_lun_from_sessions(struct se_lun *lun)
5115 {
5116         struct task_struct *kt;
5117
5118         kt = kthread_run(transport_clear_lun_thread, lun,
5119                         "tcm_cl_%u", lun->unpacked_lun);
5120         if (IS_ERR(kt)) {
5121                 printk(KERN_ERR "Unable to start clear_lun thread\n");
5122                 return PTR_ERR(kt);
5123         }
5124         wait_for_completion(&lun->lun_shutdown_comp);
5125
5126         return 0;
5127 }
5128
5129 /*      transport_generic_wait_for_tasks():
5130  *
5131  *      Called from frontend or passthrough context to wait for storage engine
5132  *      to pause and/or release frontend generated struct se_cmd.
5133  */
5134 static void transport_generic_wait_for_tasks(
5135         struct se_cmd *cmd,
5136         int remove_cmd,
5137         int session_reinstatement)
5138 {
5139         unsigned long flags;
5140
5141         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) && !(cmd->se_tmr_req))
5142                 return;
5143
5144         spin_lock_irqsave(&cmd->t_state_lock, flags);
5145         /*
5146          * If we are already stopped due to an external event (ie: LUN shutdown)
5147          * sleep until the connection can have the passed struct se_cmd back.
5148          * The cmd->transport_lun_stopped_sem will be upped by
5149          * transport_clear_lun_from_sessions() once the ConfigFS context caller
5150          * has completed its operation on the struct se_cmd.
5151          */
5152         if (atomic_read(&cmd->transport_lun_stop)) {
5153
5154                 DEBUG_TRANSPORT_S("wait_for_tasks: Stopping"
5155                         " wait_for_completion(&cmd->t_tasktransport_lun_fe"
5156                         "_stop_comp); for ITT: 0x%08x\n",
5157                         cmd->se_tfo->get_task_tag(cmd));
5158                 /*
5159                  * There is a special case for WRITES where a FE exception +
5160                  * LUN shutdown means ConfigFS context is still sleeping on
5161                  * transport_lun_stop_comp in transport_lun_wait_for_tasks().
5162                  * We go ahead and up transport_lun_stop_comp just to be sure
5163                  * here.
5164                  */
5165                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
5166                 complete(&cmd->transport_lun_stop_comp);
5167                 wait_for_completion(&cmd->transport_lun_fe_stop_comp);
5168                 spin_lock_irqsave(&cmd->t_state_lock, flags);
5169
5170                 transport_all_task_dev_remove_state(cmd);
5171                 /*
5172                  * At this point, the frontend who was the originator of this
5173                  * struct se_cmd, now owns the structure and can be released through
5174                  * normal means below.
5175                  */
5176                 DEBUG_TRANSPORT_S("wait_for_tasks: Stopped"
5177                         " wait_for_completion(&cmd->t_tasktransport_lun_fe_"
5178                         "stop_comp); for ITT: 0x%08x\n",
5179                         cmd->se_tfo->get_task_tag(cmd));
5180
5181                 atomic_set(&cmd->transport_lun_stop, 0);
5182         }
5183         if (!atomic_read(&cmd->t_transport_active) ||
5184              atomic_read(&cmd->t_transport_aborted))
5185                 goto remove;
5186
5187         atomic_set(&cmd->t_transport_stop, 1);
5188
5189         DEBUG_TRANSPORT_S("wait_for_tasks: Stopping %p ITT: 0x%08x"
5190                 " i_state: %d, t_state/def_t_state: %d/%d, t_transport_stop"
5191                 " = TRUE\n", cmd, cmd->se_tfo->get_task_tag(cmd),
5192                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state,
5193                 cmd->deferred_t_state);
5194
5195         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
5196
5197         wake_up_interruptible(&cmd->se_dev->dev_queue_obj.thread_wq);
5198
5199         wait_for_completion(&cmd->t_transport_stop_comp);
5200
5201         spin_lock_irqsave(&cmd->t_state_lock, flags);
5202         atomic_set(&cmd->t_transport_active, 0);
5203         atomic_set(&cmd->t_transport_stop, 0);
5204
5205         DEBUG_TRANSPORT_S("wait_for_tasks: Stopped wait_for_compltion("
5206                 "&cmd->t_transport_stop_comp) for ITT: 0x%08x\n",
5207                 cmd->se_tfo->get_task_tag(cmd));
5208 remove:
5209         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
5210         if (!remove_cmd)
5211                 return;
5212
5213         transport_generic_free_cmd(cmd, 0, 0, session_reinstatement);
5214 }
5215
5216 static int transport_get_sense_codes(
5217         struct se_cmd *cmd,
5218         u8 *asc,
5219         u8 *ascq)
5220 {
5221         *asc = cmd->scsi_asc;
5222         *ascq = cmd->scsi_ascq;
5223
5224         return 0;
5225 }
5226
5227 static int transport_set_sense_codes(
5228         struct se_cmd *cmd,
5229         u8 asc,
5230         u8 ascq)
5231 {
5232         cmd->scsi_asc = asc;
5233         cmd->scsi_ascq = ascq;
5234
5235         return 0;
5236 }
5237
5238 int transport_send_check_condition_and_sense(
5239         struct se_cmd *cmd,
5240         u8 reason,
5241         int from_transport)
5242 {
5243         unsigned char *buffer = cmd->sense_buffer;
5244         unsigned long flags;
5245         int offset;
5246         u8 asc = 0, ascq = 0;
5247
5248         spin_lock_irqsave(&cmd->t_state_lock, flags);
5249         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
5250                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
5251                 return 0;
5252         }
5253         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
5254         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
5255
5256         if (!reason && from_transport)
5257                 goto after_reason;
5258
5259         if (!from_transport)
5260                 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
5261         /*
5262          * Data Segment and SenseLength of the fabric response PDU.
5263          *
5264          * TRANSPORT_SENSE_BUFFER is now set to SCSI_SENSE_BUFFERSIZE
5265          * from include/scsi/scsi_cmnd.h
5266          */
5267         offset = cmd->se_tfo->set_fabric_sense_len(cmd,
5268                                 TRANSPORT_SENSE_BUFFER);
5269         /*
5270          * Actual SENSE DATA, see SPC-3 7.23.2  SPC_SENSE_KEY_OFFSET uses
5271          * SENSE KEY values from include/scsi/scsi.h
5272          */
5273         switch (reason) {
5274         case TCM_NON_EXISTENT_LUN:
5275         case TCM_UNSUPPORTED_SCSI_OPCODE:
5276         case TCM_SECTOR_COUNT_TOO_MANY:
5277                 /* CURRENT ERROR */
5278                 buffer[offset] = 0x70;
5279                 /* ILLEGAL REQUEST */
5280                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
5281                 /* INVALID COMMAND OPERATION CODE */
5282                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x20;
5283                 break;
5284         case TCM_UNKNOWN_MODE_PAGE:
5285                 /* CURRENT ERROR */
5286                 buffer[offset] = 0x70;
5287                 /* ILLEGAL REQUEST */
5288                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
5289                 /* INVALID FIELD IN CDB */
5290                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
5291                 break;
5292         case TCM_CHECK_CONDITION_ABORT_CMD:
5293                 /* CURRENT ERROR */
5294                 buffer[offset] = 0x70;
5295                 /* ABORTED COMMAND */
5296                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5297                 /* BUS DEVICE RESET FUNCTION OCCURRED */
5298                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x29;
5299                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x03;
5300                 break;
5301         case TCM_INCORRECT_AMOUNT_OF_DATA:
5302                 /* CURRENT ERROR */
5303                 buffer[offset] = 0x70;
5304                 /* ABORTED COMMAND */
5305                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5306                 /* WRITE ERROR */
5307                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
5308                 /* NOT ENOUGH UNSOLICITED DATA */
5309                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0d;
5310                 break;
5311         case TCM_INVALID_CDB_FIELD:
5312                 /* CURRENT ERROR */
5313                 buffer[offset] = 0x70;
5314                 /* ABORTED COMMAND */
5315                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5316                 /* INVALID FIELD IN CDB */
5317                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
5318                 break;
5319         case TCM_INVALID_PARAMETER_LIST:
5320                 /* CURRENT ERROR */
5321                 buffer[offset] = 0x70;
5322                 /* ABORTED COMMAND */
5323                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5324                 /* INVALID FIELD IN PARAMETER LIST */
5325                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x26;
5326                 break;
5327         case TCM_UNEXPECTED_UNSOLICITED_DATA:
5328                 /* CURRENT ERROR */
5329                 buffer[offset] = 0x70;
5330                 /* ABORTED COMMAND */
5331                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5332                 /* WRITE ERROR */
5333                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
5334                 /* UNEXPECTED_UNSOLICITED_DATA */
5335                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0c;
5336                 break;
5337         case TCM_SERVICE_CRC_ERROR:
5338                 /* CURRENT ERROR */
5339                 buffer[offset] = 0x70;
5340                 /* ABORTED COMMAND */
5341                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5342                 /* PROTOCOL SERVICE CRC ERROR */
5343                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x47;
5344                 /* N/A */
5345                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x05;
5346                 break;
5347         case TCM_SNACK_REJECTED:
5348                 /* CURRENT ERROR */
5349                 buffer[offset] = 0x70;
5350                 /* ABORTED COMMAND */
5351                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
5352                 /* READ ERROR */
5353                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x11;
5354                 /* FAILED RETRANSMISSION REQUEST */
5355                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x13;
5356                 break;
5357         case TCM_WRITE_PROTECTED:
5358                 /* CURRENT ERROR */
5359                 buffer[offset] = 0x70;
5360                 /* DATA PROTECT */
5361                 buffer[offset+SPC_SENSE_KEY_OFFSET] = DATA_PROTECT;
5362                 /* WRITE PROTECTED */
5363                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x27;
5364                 break;
5365         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
5366                 /* CURRENT ERROR */
5367                 buffer[offset] = 0x70;
5368                 /* UNIT ATTENTION */
5369                 buffer[offset+SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION;
5370                 core_scsi3_ua_for_check_condition(cmd, &asc, &ascq);
5371                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
5372                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
5373                 break;
5374         case TCM_CHECK_CONDITION_NOT_READY:
5375                 /* CURRENT ERROR */
5376                 buffer[offset] = 0x70;
5377                 /* Not Ready */
5378                 buffer[offset+SPC_SENSE_KEY_OFFSET] = NOT_READY;
5379                 transport_get_sense_codes(cmd, &asc, &ascq);
5380                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
5381                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
5382                 break;
5383         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
5384         default:
5385                 /* CURRENT ERROR */
5386                 buffer[offset] = 0x70;
5387                 /* ILLEGAL REQUEST */
5388                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
5389                 /* LOGICAL UNIT COMMUNICATION FAILURE */
5390                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x80;
5391                 break;
5392         }
5393         /*
5394          * This code uses linux/include/scsi/scsi.h SAM status codes!
5395          */
5396         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
5397         /*
5398          * Automatically padded, this value is encoded in the fabric's
5399          * data_length response PDU containing the SCSI defined sense data.
5400          */
5401         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER + offset;
5402
5403 after_reason:
5404         cmd->se_tfo->queue_status(cmd);
5405         return 0;
5406 }
5407 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
5408
5409 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
5410 {
5411         int ret = 0;
5412
5413         if (atomic_read(&cmd->t_transport_aborted) != 0) {
5414                 if (!(send_status) ||
5415                      (cmd->se_cmd_flags & SCF_SENT_DELAYED_TAS))
5416                         return 1;
5417 #if 0
5418                 printk(KERN_INFO "Sending delayed SAM_STAT_TASK_ABORTED"
5419                         " status for CDB: 0x%02x ITT: 0x%08x\n",
5420                         cmd->t_task_cdb[0],
5421                         cmd->se_tfo->get_task_tag(cmd));
5422 #endif
5423                 cmd->se_cmd_flags |= SCF_SENT_DELAYED_TAS;
5424                 cmd->se_tfo->queue_status(cmd);
5425                 ret = 1;
5426         }
5427         return ret;
5428 }
5429 EXPORT_SYMBOL(transport_check_aborted_status);
5430
5431 void transport_send_task_abort(struct se_cmd *cmd)
5432 {
5433         /*
5434          * If there are still expected incoming fabric WRITEs, we wait
5435          * until until they have completed before sending a TASK_ABORTED
5436          * response.  This response with TASK_ABORTED status will be
5437          * queued back to fabric module by transport_check_aborted_status().
5438          */
5439         if (cmd->data_direction == DMA_TO_DEVICE) {
5440                 if (cmd->se_tfo->write_pending_status(cmd) != 0) {
5441                         atomic_inc(&cmd->t_transport_aborted);
5442                         smp_mb__after_atomic_inc();
5443                         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
5444                         transport_new_cmd_failure(cmd);
5445                         return;
5446                 }
5447         }
5448         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
5449 #if 0
5450         printk(KERN_INFO "Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x,"
5451                 " ITT: 0x%08x\n", cmd->t_task_cdb[0],
5452                 cmd->se_tfo->get_task_tag(cmd));
5453 #endif
5454         cmd->se_tfo->queue_status(cmd);
5455 }
5456
5457 /*      transport_generic_do_tmr():
5458  *
5459  *
5460  */
5461 int transport_generic_do_tmr(struct se_cmd *cmd)
5462 {
5463         struct se_device *dev = cmd->se_dev;
5464         struct se_tmr_req *tmr = cmd->se_tmr_req;
5465         int ret;
5466
5467         switch (tmr->function) {
5468         case TMR_ABORT_TASK:
5469                 tmr->response = TMR_FUNCTION_REJECTED;
5470                 break;
5471         case TMR_ABORT_TASK_SET:
5472         case TMR_CLEAR_ACA:
5473         case TMR_CLEAR_TASK_SET:
5474                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
5475                 break;
5476         case TMR_LUN_RESET:
5477                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
5478                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
5479                                          TMR_FUNCTION_REJECTED;
5480                 break;
5481         case TMR_TARGET_WARM_RESET:
5482                 tmr->response = TMR_FUNCTION_REJECTED;
5483                 break;
5484         case TMR_TARGET_COLD_RESET:
5485                 tmr->response = TMR_FUNCTION_REJECTED;
5486                 break;
5487         default:
5488                 printk(KERN_ERR "Uknown TMR function: 0x%02x.\n",
5489                                 tmr->function);
5490                 tmr->response = TMR_FUNCTION_REJECTED;
5491                 break;
5492         }
5493
5494         cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
5495         cmd->se_tfo->queue_tm_rsp(cmd);
5496
5497         transport_cmd_check_stop(cmd, 2, 0);
5498         return 0;
5499 }
5500
5501 /*
5502  *      Called with spin_lock_irq(&dev->execute_task_lock); held
5503  *
5504  */
5505 static struct se_task *
5506 transport_get_task_from_state_list(struct se_device *dev)
5507 {
5508         struct se_task *task;
5509
5510         if (list_empty(&dev->state_task_list))
5511                 return NULL;
5512
5513         list_for_each_entry(task, &dev->state_task_list, t_state_list)
5514                 break;
5515
5516         list_del(&task->t_state_list);
5517         atomic_set(&task->task_state_active, 0);
5518
5519         return task;
5520 }
5521
5522 static void transport_processing_shutdown(struct se_device *dev)
5523 {
5524         struct se_cmd *cmd;
5525         struct se_task *task;
5526         unsigned long flags;
5527         /*
5528          * Empty the struct se_device's struct se_task state list.
5529          */
5530         spin_lock_irqsave(&dev->execute_task_lock, flags);
5531         while ((task = transport_get_task_from_state_list(dev))) {
5532                 if (!task->task_se_cmd) {
5533                         printk(KERN_ERR "task->task_se_cmd is NULL!\n");
5534                         continue;
5535                 }
5536                 cmd = task->task_se_cmd;
5537
5538                 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
5539
5540                 spin_lock_irqsave(&cmd->t_state_lock, flags);
5541
5542                 DEBUG_DO("PT: cmd: %p task: %p ITT/CmdSN: 0x%08x/0x%08x,"
5543                         " i_state/def_i_state: %d/%d, t_state/def_t_state:"
5544                         " %d/%d cdb: 0x%02x\n", cmd, task,
5545                         cmd->se_tfo->get_task_tag(cmd), cmd->cmd_sn,
5546                         cmd->se_tfo->get_cmd_state(cmd), cmd->deferred_i_state,
5547                         cmd->t_state, cmd->deferred_t_state,
5548                         cmd->t_task_cdb[0]);
5549                 DEBUG_DO("PT: ITT[0x%08x] - t_task_cdbs: %d t_task_cdbs_left:"
5550                         " %d t_task_cdbs_sent: %d -- t_transport_active: %d"
5551                         " t_transport_stop: %d t_transport_sent: %d\n",
5552                         cmd->se_tfo->get_task_tag(cmd),
5553                         cmd->t_task_cdbs,
5554                         atomic_read(&cmd->t_task_cdbs_left),
5555                         atomic_read(&cmd->t_task_cdbs_sent),
5556                         atomic_read(&cmd->t_transport_active),
5557                         atomic_read(&cmd->t_transport_stop),
5558                         atomic_read(&cmd->t_transport_sent));
5559
5560                 if (atomic_read(&task->task_active)) {
5561                         atomic_set(&task->task_stop, 1);
5562                         spin_unlock_irqrestore(
5563                                 &cmd->t_state_lock, flags);
5564
5565                         DEBUG_DO("Waiting for task: %p to shutdown for dev:"
5566                                 " %p\n", task, dev);
5567                         wait_for_completion(&task->task_stop_comp);
5568                         DEBUG_DO("Completed task: %p shutdown for dev: %p\n",
5569                                 task, dev);
5570
5571                         spin_lock_irqsave(&cmd->t_state_lock, flags);
5572                         atomic_dec(&cmd->t_task_cdbs_left);
5573
5574                         atomic_set(&task->task_active, 0);
5575                         atomic_set(&task->task_stop, 0);
5576                 } else {
5577                         if (atomic_read(&task->task_execute_queue) != 0)
5578                                 transport_remove_task_from_execute_queue(task, dev);
5579                 }
5580                 __transport_stop_task_timer(task, &flags);
5581
5582                 if (!(atomic_dec_and_test(&cmd->t_task_cdbs_ex_left))) {
5583                         spin_unlock_irqrestore(
5584                                         &cmd->t_state_lock, flags);
5585
5586                         DEBUG_DO("Skipping task: %p, dev: %p for"
5587                                 " t_task_cdbs_ex_left: %d\n", task, dev,
5588                                 atomic_read(&cmd->t_task_cdbs_ex_left));
5589
5590                         spin_lock_irqsave(&dev->execute_task_lock, flags);
5591                         continue;
5592                 }
5593
5594                 if (atomic_read(&cmd->t_transport_active)) {
5595                         DEBUG_DO("got t_transport_active = 1 for task: %p, dev:"
5596                                         " %p\n", task, dev);
5597
5598                         if (atomic_read(&cmd->t_fe_count)) {
5599                                 spin_unlock_irqrestore(
5600                                         &cmd->t_state_lock, flags);
5601                                 transport_send_check_condition_and_sense(
5602                                         cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE,
5603                                         0);
5604                                 transport_remove_cmd_from_queue(cmd,
5605                                         &cmd->se_dev->dev_queue_obj);
5606
5607                                 transport_lun_remove_cmd(cmd);
5608                                 transport_cmd_check_stop(cmd, 1, 0);
5609                         } else {
5610                                 spin_unlock_irqrestore(
5611                                         &cmd->t_state_lock, flags);
5612
5613                                 transport_remove_cmd_from_queue(cmd,
5614                                         &cmd->se_dev->dev_queue_obj);
5615
5616                                 transport_lun_remove_cmd(cmd);
5617
5618                                 if (transport_cmd_check_stop(cmd, 1, 0))
5619                                         transport_generic_remove(cmd, 0, 0);
5620                         }
5621
5622                         spin_lock_irqsave(&dev->execute_task_lock, flags);
5623                         continue;
5624                 }
5625                 DEBUG_DO("Got t_transport_active = 0 for task: %p, dev: %p\n",
5626                                 task, dev);
5627
5628                 if (atomic_read(&cmd->t_fe_count)) {
5629                         spin_unlock_irqrestore(
5630                                 &cmd->t_state_lock, flags);
5631                         transport_send_check_condition_and_sense(cmd,
5632                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
5633                         transport_remove_cmd_from_queue(cmd,
5634                                 &cmd->se_dev->dev_queue_obj);
5635
5636                         transport_lun_remove_cmd(cmd);
5637                         transport_cmd_check_stop(cmd, 1, 0);
5638                 } else {
5639                         spin_unlock_irqrestore(
5640                                 &cmd->t_state_lock, flags);
5641
5642                         transport_remove_cmd_from_queue(cmd,
5643                                 &cmd->se_dev->dev_queue_obj);
5644                         transport_lun_remove_cmd(cmd);
5645
5646                         if (transport_cmd_check_stop(cmd, 1, 0))
5647                                 transport_generic_remove(cmd, 0, 0);
5648                 }
5649
5650                 spin_lock_irqsave(&dev->execute_task_lock, flags);
5651         }
5652         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
5653         /*
5654          * Empty the struct se_device's struct se_cmd list.
5655          */
5656         while ((cmd = transport_get_cmd_from_queue(&dev->dev_queue_obj))) {
5657
5658                 DEBUG_DO("From Device Queue: cmd: %p t_state: %d\n",
5659                                 cmd, cmd->t_state);
5660
5661                 if (atomic_read(&cmd->t_fe_count)) {
5662                         transport_send_check_condition_and_sense(cmd,
5663                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE, 0);
5664
5665                         transport_lun_remove_cmd(cmd);
5666                         transport_cmd_check_stop(cmd, 1, 0);
5667                 } else {
5668                         transport_lun_remove_cmd(cmd);
5669                         if (transport_cmd_check_stop(cmd, 1, 0))
5670                                 transport_generic_remove(cmd, 0, 0);
5671                 }
5672         }
5673 }
5674
5675 /*      transport_processing_thread():
5676  *
5677  *
5678  */
5679 static int transport_processing_thread(void *param)
5680 {
5681         int ret;
5682         struct se_cmd *cmd;
5683         struct se_device *dev = (struct se_device *) param;
5684
5685         set_user_nice(current, -20);
5686
5687         while (!kthread_should_stop()) {
5688                 ret = wait_event_interruptible(dev->dev_queue_obj.thread_wq,
5689                                 atomic_read(&dev->dev_queue_obj.queue_cnt) ||
5690                                 kthread_should_stop());
5691                 if (ret < 0)
5692                         goto out;
5693
5694                 spin_lock_irq(&dev->dev_status_lock);
5695                 if (dev->dev_status & TRANSPORT_DEVICE_SHUTDOWN) {
5696                         spin_unlock_irq(&dev->dev_status_lock);
5697                         transport_processing_shutdown(dev);
5698                         continue;
5699                 }
5700                 spin_unlock_irq(&dev->dev_status_lock);
5701
5702 get_cmd:
5703                 __transport_execute_tasks(dev);
5704
5705                 cmd = transport_get_cmd_from_queue(&dev->dev_queue_obj);
5706                 if (!cmd)
5707                         continue;
5708
5709                 switch (cmd->t_state) {
5710                 case TRANSPORT_NEW_CMD_MAP:
5711                         if (!(cmd->se_tfo->new_cmd_map)) {
5712                                 printk(KERN_ERR "cmd->se_tfo->new_cmd_map is"
5713                                         " NULL for TRANSPORT_NEW_CMD_MAP\n");
5714                                 BUG();
5715                         }
5716                         ret = cmd->se_tfo->new_cmd_map(cmd);
5717                         if (ret < 0) {
5718                                 cmd->transport_error_status = ret;
5719                                 transport_generic_request_failure(cmd, NULL,
5720                                                 0, (cmd->data_direction !=
5721                                                     DMA_TO_DEVICE));
5722                                 break;
5723                         }
5724                         /* Fall through */
5725                 case TRANSPORT_NEW_CMD:
5726                         ret = transport_generic_new_cmd(cmd);
5727                         if (ret < 0) {
5728                                 cmd->transport_error_status = ret;
5729                                 transport_generic_request_failure(cmd, NULL,
5730                                         0, (cmd->data_direction !=
5731                                          DMA_TO_DEVICE));
5732                         }
5733                         break;
5734                 case TRANSPORT_PROCESS_WRITE:
5735                         transport_generic_process_write(cmd);
5736                         break;
5737                 case TRANSPORT_COMPLETE_OK:
5738                         transport_stop_all_task_timers(cmd);
5739                         transport_generic_complete_ok(cmd);
5740                         break;
5741                 case TRANSPORT_REMOVE:
5742                         transport_generic_remove(cmd, 1, 0);
5743                         break;
5744                 case TRANSPORT_FREE_CMD_INTR:
5745                         transport_generic_free_cmd(cmd, 0, 1, 0);
5746                         break;
5747                 case TRANSPORT_PROCESS_TMR:
5748                         transport_generic_do_tmr(cmd);
5749                         break;
5750                 case TRANSPORT_COMPLETE_FAILURE:
5751                         transport_generic_request_failure(cmd, NULL, 1, 1);
5752                         break;
5753                 case TRANSPORT_COMPLETE_TIMEOUT:
5754                         transport_stop_all_task_timers(cmd);
5755                         transport_generic_request_timeout(cmd);
5756                         break;
5757                 default:
5758                         printk(KERN_ERR "Unknown t_state: %d deferred_t_state:"
5759                                 " %d for ITT: 0x%08x i_state: %d on SE LUN:"
5760                                 " %u\n", cmd->t_state, cmd->deferred_t_state,
5761                                 cmd->se_tfo->get_task_tag(cmd),
5762                                 cmd->se_tfo->get_cmd_state(cmd),
5763                                 cmd->se_lun->unpacked_lun);
5764                         BUG();
5765                 }
5766
5767                 goto get_cmd;
5768         }
5769
5770 out:
5771         transport_release_all_cmds(dev);
5772         dev->process_thread = NULL;
5773         return 0;
5774 }