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