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