target: remove the se_obj_ptr and se_orig_obj_ptr se_cmd fields
[linux-2.6.git] / drivers / target / target_core_transport.c
1 /*******************************************************************************
2  * Filename:  target_core_transport.c
3  *
4  * This file contains the Generic Target Engine Core.
5  *
6  * Copyright (c) 2002, 2003, 2004, 2005 PyX Technologies, Inc.
7  * Copyright (c) 2005, 2006, 2007 SBE, Inc.
8  * Copyright (c) 2007-2010 Rising Tide Systems
9  * Copyright (c) 2008-2010 Linux-iSCSI.org
10  *
11  * Nicholas A. Bellinger <nab@kernel.org>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26  *
27  ******************************************************************************/
28
29 #include <linux/net.h>
30 #include <linux/delay.h>
31 #include <linux/string.h>
32 #include <linux/timer.h>
33 #include <linux/slab.h>
34 #include <linux/blkdev.h>
35 #include <linux/spinlock.h>
36 #include <linux/kthread.h>
37 #include <linux/in.h>
38 #include <linux/cdrom.h>
39 #include <linux/module.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_cdb.h"
57 #include "target_core_hba.h"
58 #include "target_core_pr.h"
59 #include "target_core_ua.h"
60
61 static int sub_api_initialized;
62
63 static struct workqueue_struct *target_completion_wq;
64 static struct kmem_cache *se_sess_cache;
65 struct kmem_cache *se_tmr_req_cache;
66 struct kmem_cache *se_ua_cache;
67 struct kmem_cache *t10_pr_reg_cache;
68 struct kmem_cache *t10_alua_lu_gp_cache;
69 struct kmem_cache *t10_alua_lu_gp_mem_cache;
70 struct kmem_cache *t10_alua_tg_pt_gp_cache;
71 struct kmem_cache *t10_alua_tg_pt_gp_mem_cache;
72
73 static int transport_generic_write_pending(struct se_cmd *);
74 static int transport_processing_thread(void *param);
75 static int __transport_execute_tasks(struct se_device *dev);
76 static void transport_complete_task_attr(struct se_cmd *cmd);
77 static void transport_handle_queue_full(struct se_cmd *cmd,
78                 struct se_device *dev);
79 static void transport_free_dev_tasks(struct se_cmd *cmd);
80 static int transport_generic_get_mem(struct se_cmd *cmd);
81 static void transport_put_cmd(struct se_cmd *cmd);
82 static void transport_remove_cmd_from_queue(struct se_cmd *cmd);
83 static int transport_set_sense_codes(struct se_cmd *cmd, u8 asc, u8 ascq);
84 static void transport_generic_request_failure(struct se_cmd *);
85 static void target_complete_ok_work(struct work_struct *work);
86
87 int init_se_kmem_caches(void)
88 {
89         se_tmr_req_cache = kmem_cache_create("se_tmr_cache",
90                         sizeof(struct se_tmr_req), __alignof__(struct se_tmr_req),
91                         0, NULL);
92         if (!se_tmr_req_cache) {
93                 pr_err("kmem_cache_create() for struct se_tmr_req"
94                                 " failed\n");
95                 goto out;
96         }
97         se_sess_cache = kmem_cache_create("se_sess_cache",
98                         sizeof(struct se_session), __alignof__(struct se_session),
99                         0, NULL);
100         if (!se_sess_cache) {
101                 pr_err("kmem_cache_create() for struct se_session"
102                                 " failed\n");
103                 goto out_free_tmr_req_cache;
104         }
105         se_ua_cache = kmem_cache_create("se_ua_cache",
106                         sizeof(struct se_ua), __alignof__(struct se_ua),
107                         0, NULL);
108         if (!se_ua_cache) {
109                 pr_err("kmem_cache_create() for struct se_ua failed\n");
110                 goto out_free_sess_cache;
111         }
112         t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
113                         sizeof(struct t10_pr_registration),
114                         __alignof__(struct t10_pr_registration), 0, NULL);
115         if (!t10_pr_reg_cache) {
116                 pr_err("kmem_cache_create() for struct t10_pr_registration"
117                                 " failed\n");
118                 goto out_free_ua_cache;
119         }
120         t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
121                         sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
122                         0, NULL);
123         if (!t10_alua_lu_gp_cache) {
124                 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
125                                 " failed\n");
126                 goto out_free_pr_reg_cache;
127         }
128         t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
129                         sizeof(struct t10_alua_lu_gp_member),
130                         __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
131         if (!t10_alua_lu_gp_mem_cache) {
132                 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
133                                 "cache failed\n");
134                 goto out_free_lu_gp_cache;
135         }
136         t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
137                         sizeof(struct t10_alua_tg_pt_gp),
138                         __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
139         if (!t10_alua_tg_pt_gp_cache) {
140                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
141                                 "cache failed\n");
142                 goto out_free_lu_gp_mem_cache;
143         }
144         t10_alua_tg_pt_gp_mem_cache = kmem_cache_create(
145                         "t10_alua_tg_pt_gp_mem_cache",
146                         sizeof(struct t10_alua_tg_pt_gp_member),
147                         __alignof__(struct t10_alua_tg_pt_gp_member),
148                         0, NULL);
149         if (!t10_alua_tg_pt_gp_mem_cache) {
150                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
151                                 "mem_t failed\n");
152                 goto out_free_tg_pt_gp_cache;
153         }
154
155         target_completion_wq = alloc_workqueue("target_completion",
156                                                WQ_MEM_RECLAIM, 0);
157         if (!target_completion_wq)
158                 goto out_free_tg_pt_gp_mem_cache;
159
160         return 0;
161
162 out_free_tg_pt_gp_mem_cache:
163         kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
164 out_free_tg_pt_gp_cache:
165         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
166 out_free_lu_gp_mem_cache:
167         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
168 out_free_lu_gp_cache:
169         kmem_cache_destroy(t10_alua_lu_gp_cache);
170 out_free_pr_reg_cache:
171         kmem_cache_destroy(t10_pr_reg_cache);
172 out_free_ua_cache:
173         kmem_cache_destroy(se_ua_cache);
174 out_free_sess_cache:
175         kmem_cache_destroy(se_sess_cache);
176 out_free_tmr_req_cache:
177         kmem_cache_destroy(se_tmr_req_cache);
178 out:
179         return -ENOMEM;
180 }
181
182 void release_se_kmem_caches(void)
183 {
184         destroy_workqueue(target_completion_wq);
185         kmem_cache_destroy(se_tmr_req_cache);
186         kmem_cache_destroy(se_sess_cache);
187         kmem_cache_destroy(se_ua_cache);
188         kmem_cache_destroy(t10_pr_reg_cache);
189         kmem_cache_destroy(t10_alua_lu_gp_cache);
190         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
191         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
192         kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
193 }
194
195 /* This code ensures unique mib indexes are handed out. */
196 static DEFINE_SPINLOCK(scsi_mib_index_lock);
197 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
198
199 /*
200  * Allocate a new row index for the entry type specified
201  */
202 u32 scsi_get_new_index(scsi_index_t type)
203 {
204         u32 new_index;
205
206         BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
207
208         spin_lock(&scsi_mib_index_lock);
209         new_index = ++scsi_mib_index[type];
210         spin_unlock(&scsi_mib_index_lock);
211
212         return new_index;
213 }
214
215 void transport_init_queue_obj(struct se_queue_obj *qobj)
216 {
217         atomic_set(&qobj->queue_cnt, 0);
218         INIT_LIST_HEAD(&qobj->qobj_list);
219         init_waitqueue_head(&qobj->thread_wq);
220         spin_lock_init(&qobj->cmd_queue_lock);
221 }
222 EXPORT_SYMBOL(transport_init_queue_obj);
223
224 void transport_subsystem_check_init(void)
225 {
226         int ret;
227
228         if (sub_api_initialized)
229                 return;
230
231         ret = request_module("target_core_iblock");
232         if (ret != 0)
233                 pr_err("Unable to load target_core_iblock\n");
234
235         ret = request_module("target_core_file");
236         if (ret != 0)
237                 pr_err("Unable to load target_core_file\n");
238
239         ret = request_module("target_core_pscsi");
240         if (ret != 0)
241                 pr_err("Unable to load target_core_pscsi\n");
242
243         ret = request_module("target_core_stgt");
244         if (ret != 0)
245                 pr_err("Unable to load target_core_stgt\n");
246
247         sub_api_initialized = 1;
248         return;
249 }
250
251 struct se_session *transport_init_session(void)
252 {
253         struct se_session *se_sess;
254
255         se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
256         if (!se_sess) {
257                 pr_err("Unable to allocate struct se_session from"
258                                 " se_sess_cache\n");
259                 return ERR_PTR(-ENOMEM);
260         }
261         INIT_LIST_HEAD(&se_sess->sess_list);
262         INIT_LIST_HEAD(&se_sess->sess_acl_list);
263         INIT_LIST_HEAD(&se_sess->sess_cmd_list);
264         INIT_LIST_HEAD(&se_sess->sess_wait_list);
265         spin_lock_init(&se_sess->sess_cmd_lock);
266
267         return se_sess;
268 }
269 EXPORT_SYMBOL(transport_init_session);
270
271 /*
272  * Called with spin_lock_bh(&struct se_portal_group->session_lock called.
273  */
274 void __transport_register_session(
275         struct se_portal_group *se_tpg,
276         struct se_node_acl *se_nacl,
277         struct se_session *se_sess,
278         void *fabric_sess_ptr)
279 {
280         unsigned char buf[PR_REG_ISID_LEN];
281
282         se_sess->se_tpg = se_tpg;
283         se_sess->fabric_sess_ptr = fabric_sess_ptr;
284         /*
285          * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
286          *
287          * Only set for struct se_session's that will actually be moving I/O.
288          * eg: *NOT* discovery sessions.
289          */
290         if (se_nacl) {
291                 /*
292                  * If the fabric module supports an ISID based TransportID,
293                  * save this value in binary from the fabric I_T Nexus now.
294                  */
295                 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
296                         memset(&buf[0], 0, PR_REG_ISID_LEN);
297                         se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
298                                         &buf[0], PR_REG_ISID_LEN);
299                         se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
300                 }
301                 spin_lock_irq(&se_nacl->nacl_sess_lock);
302                 /*
303                  * The se_nacl->nacl_sess pointer will be set to the
304                  * last active I_T Nexus for each struct se_node_acl.
305                  */
306                 se_nacl->nacl_sess = se_sess;
307
308                 list_add_tail(&se_sess->sess_acl_list,
309                               &se_nacl->acl_sess_list);
310                 spin_unlock_irq(&se_nacl->nacl_sess_lock);
311         }
312         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
313
314         pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
315                 se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
316 }
317 EXPORT_SYMBOL(__transport_register_session);
318
319 void transport_register_session(
320         struct se_portal_group *se_tpg,
321         struct se_node_acl *se_nacl,
322         struct se_session *se_sess,
323         void *fabric_sess_ptr)
324 {
325         spin_lock_bh(&se_tpg->session_lock);
326         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
327         spin_unlock_bh(&se_tpg->session_lock);
328 }
329 EXPORT_SYMBOL(transport_register_session);
330
331 void transport_deregister_session_configfs(struct se_session *se_sess)
332 {
333         struct se_node_acl *se_nacl;
334         unsigned long flags;
335         /*
336          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
337          */
338         se_nacl = se_sess->se_node_acl;
339         if (se_nacl) {
340                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
341                 list_del(&se_sess->sess_acl_list);
342                 /*
343                  * If the session list is empty, then clear the pointer.
344                  * Otherwise, set the struct se_session pointer from the tail
345                  * element of the per struct se_node_acl active session list.
346                  */
347                 if (list_empty(&se_nacl->acl_sess_list))
348                         se_nacl->nacl_sess = NULL;
349                 else {
350                         se_nacl->nacl_sess = container_of(
351                                         se_nacl->acl_sess_list.prev,
352                                         struct se_session, sess_acl_list);
353                 }
354                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
355         }
356 }
357 EXPORT_SYMBOL(transport_deregister_session_configfs);
358
359 void transport_free_session(struct se_session *se_sess)
360 {
361         kmem_cache_free(se_sess_cache, se_sess);
362 }
363 EXPORT_SYMBOL(transport_free_session);
364
365 void transport_deregister_session(struct se_session *se_sess)
366 {
367         struct se_portal_group *se_tpg = se_sess->se_tpg;
368         struct se_node_acl *se_nacl;
369         unsigned long flags;
370
371         if (!se_tpg) {
372                 transport_free_session(se_sess);
373                 return;
374         }
375
376         spin_lock_irqsave(&se_tpg->session_lock, flags);
377         list_del(&se_sess->sess_list);
378         se_sess->se_tpg = NULL;
379         se_sess->fabric_sess_ptr = NULL;
380         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
381
382         /*
383          * Determine if we need to do extra work for this initiator node's
384          * struct se_node_acl if it had been previously dynamically generated.
385          */
386         se_nacl = se_sess->se_node_acl;
387         if (se_nacl) {
388                 spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
389                 if (se_nacl->dynamic_node_acl) {
390                         if (!se_tpg->se_tpg_tfo->tpg_check_demo_mode_cache(
391                                         se_tpg)) {
392                                 list_del(&se_nacl->acl_list);
393                                 se_tpg->num_node_acls--;
394                                 spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
395
396                                 core_tpg_wait_for_nacl_pr_ref(se_nacl);
397                                 core_free_device_list_for_node(se_nacl, se_tpg);
398                                 se_tpg->se_tpg_tfo->tpg_release_fabric_acl(se_tpg,
399                                                 se_nacl);
400                                 spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
401                         }
402                 }
403                 spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
404         }
405
406         transport_free_session(se_sess);
407
408         pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
409                 se_tpg->se_tpg_tfo->get_fabric_name());
410 }
411 EXPORT_SYMBOL(transport_deregister_session);
412
413 /*
414  * Called with cmd->t_state_lock held.
415  */
416 static void transport_all_task_dev_remove_state(struct se_cmd *cmd)
417 {
418         struct se_device *dev = cmd->se_dev;
419         struct se_task *task;
420         unsigned long flags;
421
422         if (!dev)
423                 return;
424
425         list_for_each_entry(task, &cmd->t_task_list, t_list) {
426                 if (task->task_flags & TF_ACTIVE)
427                         continue;
428
429                 if (!atomic_read(&task->task_state_active))
430                         continue;
431
432                 spin_lock_irqsave(&dev->execute_task_lock, flags);
433                 list_del(&task->t_state_list);
434                 pr_debug("Removed ITT: 0x%08x dev: %p task[%p]\n",
435                         cmd->se_tfo->get_task_tag(cmd), dev, task);
436                 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
437
438                 atomic_set(&task->task_state_active, 0);
439                 atomic_dec(&cmd->t_task_cdbs_ex_left);
440         }
441 }
442
443 /*      transport_cmd_check_stop():
444  *
445  *      'transport_off = 1' determines if t_transport_active should be cleared.
446  *      'transport_off = 2' determines if task_dev_state should be removed.
447  *
448  *      A non-zero u8 t_state sets cmd->t_state.
449  *      Returns 1 when command is stopped, else 0.
450  */
451 static int transport_cmd_check_stop(
452         struct se_cmd *cmd,
453         int transport_off,
454         u8 t_state)
455 {
456         unsigned long flags;
457
458         spin_lock_irqsave(&cmd->t_state_lock, flags);
459         /*
460          * Determine if IOCTL context caller in requesting the stopping of this
461          * command for LUN shutdown purposes.
462          */
463         if (atomic_read(&cmd->transport_lun_stop)) {
464                 pr_debug("%s:%d atomic_read(&cmd->transport_lun_stop)"
465                         " == TRUE for ITT: 0x%08x\n", __func__, __LINE__,
466                         cmd->se_tfo->get_task_tag(cmd));
467
468                 atomic_set(&cmd->t_transport_active, 0);
469                 if (transport_off == 2)
470                         transport_all_task_dev_remove_state(cmd);
471                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
472
473                 complete(&cmd->transport_lun_stop_comp);
474                 return 1;
475         }
476         /*
477          * Determine if frontend context caller is requesting the stopping of
478          * this command for frontend exceptions.
479          */
480         if (atomic_read(&cmd->t_transport_stop)) {
481                 pr_debug("%s:%d atomic_read(&cmd->t_transport_stop) =="
482                         " TRUE for ITT: 0x%08x\n", __func__, __LINE__,
483                         cmd->se_tfo->get_task_tag(cmd));
484
485                 if (transport_off == 2)
486                         transport_all_task_dev_remove_state(cmd);
487
488                 /*
489                  * Clear struct se_cmd->se_lun before the transport_off == 2 handoff
490                  * to FE.
491                  */
492                 if (transport_off == 2)
493                         cmd->se_lun = NULL;
494                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
495
496                 complete(&cmd->t_transport_stop_comp);
497                 return 1;
498         }
499         if (transport_off) {
500                 atomic_set(&cmd->t_transport_active, 0);
501                 if (transport_off == 2) {
502                         transport_all_task_dev_remove_state(cmd);
503                         /*
504                          * Clear struct se_cmd->se_lun before the transport_off == 2
505                          * handoff to fabric module.
506                          */
507                         cmd->se_lun = NULL;
508                         /*
509                          * Some fabric modules like tcm_loop can release
510                          * their internally allocated I/O reference now and
511                          * struct se_cmd now.
512                          *
513                          * Fabric modules are expected to return '1' here if the
514                          * se_cmd being passed is released at this point,
515                          * or zero if not being released.
516                          */
517                         if (cmd->se_tfo->check_stop_free != NULL) {
518                                 spin_unlock_irqrestore(
519                                         &cmd->t_state_lock, flags);
520
521                                 return cmd->se_tfo->check_stop_free(cmd);
522                         }
523                 }
524                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
525
526                 return 0;
527         } else if (t_state)
528                 cmd->t_state = t_state;
529         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
530
531         return 0;
532 }
533
534 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
535 {
536         return transport_cmd_check_stop(cmd, 2, 0);
537 }
538
539 static void transport_lun_remove_cmd(struct se_cmd *cmd)
540 {
541         struct se_lun *lun = cmd->se_lun;
542         unsigned long flags;
543
544         if (!lun)
545                 return;
546
547         spin_lock_irqsave(&cmd->t_state_lock, flags);
548         if (!atomic_read(&cmd->transport_dev_active)) {
549                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
550                 goto check_lun;
551         }
552         atomic_set(&cmd->transport_dev_active, 0);
553         transport_all_task_dev_remove_state(cmd);
554         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
555
556
557 check_lun:
558         spin_lock_irqsave(&lun->lun_cmd_lock, flags);
559         if (atomic_read(&cmd->transport_lun_active)) {
560                 list_del(&cmd->se_lun_node);
561                 atomic_set(&cmd->transport_lun_active, 0);
562 #if 0
563                 pr_debug("Removed ITT: 0x%08x from LUN LIST[%d]\n"
564                         cmd->se_tfo->get_task_tag(cmd), lun->unpacked_lun);
565 #endif
566         }
567         spin_unlock_irqrestore(&lun->lun_cmd_lock, flags);
568 }
569
570 void transport_cmd_finish_abort(struct se_cmd *cmd, int remove)
571 {
572         if (!cmd->se_tmr_req)
573                 transport_lun_remove_cmd(cmd);
574
575         if (transport_cmd_check_stop_to_fabric(cmd))
576                 return;
577         if (remove) {
578                 transport_remove_cmd_from_queue(cmd);
579                 transport_put_cmd(cmd);
580         }
581 }
582
583 static void transport_add_cmd_to_queue(struct se_cmd *cmd, int t_state,
584                 bool at_head)
585 {
586         struct se_device *dev = cmd->se_dev;
587         struct se_queue_obj *qobj = &dev->dev_queue_obj;
588         unsigned long flags;
589
590         if (t_state) {
591                 spin_lock_irqsave(&cmd->t_state_lock, flags);
592                 cmd->t_state = t_state;
593                 atomic_set(&cmd->t_transport_active, 1);
594                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
595         }
596
597         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
598
599         /* If the cmd is already on the list, remove it before we add it */
600         if (!list_empty(&cmd->se_queue_node))
601                 list_del(&cmd->se_queue_node);
602         else
603                 atomic_inc(&qobj->queue_cnt);
604
605         if (at_head)
606                 list_add(&cmd->se_queue_node, &qobj->qobj_list);
607         else
608                 list_add_tail(&cmd->se_queue_node, &qobj->qobj_list);
609         atomic_set(&cmd->t_transport_queue_active, 1);
610         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
611
612         wake_up_interruptible(&qobj->thread_wq);
613 }
614
615 static struct se_cmd *
616 transport_get_cmd_from_queue(struct se_queue_obj *qobj)
617 {
618         struct se_cmd *cmd;
619         unsigned long flags;
620
621         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
622         if (list_empty(&qobj->qobj_list)) {
623                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
624                 return NULL;
625         }
626         cmd = list_first_entry(&qobj->qobj_list, struct se_cmd, se_queue_node);
627
628         atomic_set(&cmd->t_transport_queue_active, 0);
629
630         list_del_init(&cmd->se_queue_node);
631         atomic_dec(&qobj->queue_cnt);
632         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
633
634         return cmd;
635 }
636
637 static void transport_remove_cmd_from_queue(struct se_cmd *cmd)
638 {
639         struct se_queue_obj *qobj = &cmd->se_dev->dev_queue_obj;
640         unsigned long flags;
641
642         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
643         if (!atomic_read(&cmd->t_transport_queue_active)) {
644                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
645                 return;
646         }
647         atomic_set(&cmd->t_transport_queue_active, 0);
648         atomic_dec(&qobj->queue_cnt);
649         list_del_init(&cmd->se_queue_node);
650         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
651
652         if (atomic_read(&cmd->t_transport_queue_active)) {
653                 pr_err("ITT: 0x%08x t_transport_queue_active: %d\n",
654                         cmd->se_tfo->get_task_tag(cmd),
655                         atomic_read(&cmd->t_transport_queue_active));
656         }
657 }
658
659 /*
660  * Completion function used by TCM subsystem plugins (such as FILEIO)
661  * for queueing up response from struct se_subsystem_api->do_task()
662  */
663 void transport_complete_sync_cache(struct se_cmd *cmd, int good)
664 {
665         struct se_task *task = list_entry(cmd->t_task_list.next,
666                                 struct se_task, t_list);
667
668         if (good) {
669                 cmd->scsi_status = SAM_STAT_GOOD;
670                 task->task_scsi_status = GOOD;
671         } else {
672                 task->task_scsi_status = SAM_STAT_CHECK_CONDITION;
673                 task->task_se_cmd->scsi_sense_reason =
674                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
675
676         }
677
678         transport_complete_task(task, good);
679 }
680 EXPORT_SYMBOL(transport_complete_sync_cache);
681
682 static void target_complete_failure_work(struct work_struct *work)
683 {
684         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
685
686         transport_generic_request_failure(cmd);
687 }
688
689 /*      transport_complete_task():
690  *
691  *      Called from interrupt and non interrupt context depending
692  *      on the transport plugin.
693  */
694 void transport_complete_task(struct se_task *task, int success)
695 {
696         struct se_cmd *cmd = task->task_se_cmd;
697         struct se_device *dev = cmd->se_dev;
698         unsigned long flags;
699 #if 0
700         pr_debug("task: %p CDB: 0x%02x obj_ptr: %p\n", task,
701                         cmd->t_task_cdb[0], dev);
702 #endif
703         if (dev)
704                 atomic_inc(&dev->depth_left);
705
706         spin_lock_irqsave(&cmd->t_state_lock, flags);
707         task->task_flags &= ~TF_ACTIVE;
708
709         /*
710          * See if any sense data exists, if so set the TASK_SENSE flag.
711          * Also check for any other post completion work that needs to be
712          * done by the plugins.
713          */
714         if (dev && dev->transport->transport_complete) {
715                 if (dev->transport->transport_complete(task) != 0) {
716                         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
717                         task->task_sense = 1;
718                         success = 1;
719                 }
720         }
721
722         /*
723          * See if we are waiting for outstanding struct se_task
724          * to complete for an exception condition
725          */
726         if (task->task_flags & TF_REQUEST_STOP) {
727                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
728                 complete(&task->task_stop_comp);
729                 return;
730         }
731
732         if (!success)
733                 cmd->t_tasks_failed = 1;
734
735         /*
736          * Decrement the outstanding t_task_cdbs_left count.  The last
737          * struct se_task from struct se_cmd will complete itself into the
738          * device queue depending upon int success.
739          */
740         if (!atomic_dec_and_test(&cmd->t_task_cdbs_left)) {
741                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
742                 return;
743         }
744
745         if (cmd->t_tasks_failed) {
746                 if (!task->task_error_status) {
747                         task->task_error_status =
748                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
749                         cmd->scsi_sense_reason =
750                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
751                 }
752
753                 INIT_WORK(&cmd->work, target_complete_failure_work);
754         } else {
755                 atomic_set(&cmd->t_transport_complete, 1);
756                 INIT_WORK(&cmd->work, target_complete_ok_work);
757         }
758
759         cmd->t_state = TRANSPORT_COMPLETE;
760         atomic_set(&cmd->t_transport_active, 1);
761         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
762
763         queue_work(target_completion_wq, &cmd->work);
764 }
765 EXPORT_SYMBOL(transport_complete_task);
766
767 /*
768  * Called by transport_add_tasks_from_cmd() once a struct se_cmd's
769  * struct se_task list are ready to be added to the active execution list
770  * struct se_device
771
772  * Called with se_dev_t->execute_task_lock called.
773  */
774 static inline int transport_add_task_check_sam_attr(
775         struct se_task *task,
776         struct se_task *task_prev,
777         struct se_device *dev)
778 {
779         /*
780          * No SAM Task attribute emulation enabled, add to tail of
781          * execution queue
782          */
783         if (dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED) {
784                 list_add_tail(&task->t_execute_list, &dev->execute_task_list);
785                 return 0;
786         }
787         /*
788          * HEAD_OF_QUEUE attribute for received CDB, which means
789          * the first task that is associated with a struct se_cmd goes to
790          * head of the struct se_device->execute_task_list, and task_prev
791          * after that for each subsequent task
792          */
793         if (task->task_se_cmd->sam_task_attr == MSG_HEAD_TAG) {
794                 list_add(&task->t_execute_list,
795                                 (task_prev != NULL) ?
796                                 &task_prev->t_execute_list :
797                                 &dev->execute_task_list);
798
799                 pr_debug("Set HEAD_OF_QUEUE for task CDB: 0x%02x"
800                                 " in execution queue\n",
801                                 task->task_se_cmd->t_task_cdb[0]);
802                 return 1;
803         }
804         /*
805          * For ORDERED, SIMPLE or UNTAGGED attribute tasks once they have been
806          * transitioned from Dermant -> Active state, and are added to the end
807          * of the struct se_device->execute_task_list
808          */
809         list_add_tail(&task->t_execute_list, &dev->execute_task_list);
810         return 0;
811 }
812
813 /*      __transport_add_task_to_execute_queue():
814  *
815  *      Called with se_dev_t->execute_task_lock called.
816  */
817 static void __transport_add_task_to_execute_queue(
818         struct se_task *task,
819         struct se_task *task_prev,
820         struct se_device *dev)
821 {
822         int head_of_queue;
823
824         head_of_queue = transport_add_task_check_sam_attr(task, task_prev, dev);
825         atomic_inc(&dev->execute_tasks);
826
827         if (atomic_read(&task->task_state_active))
828                 return;
829         /*
830          * Determine if this task needs to go to HEAD_OF_QUEUE for the
831          * state list as well.  Running with SAM Task Attribute emulation
832          * will always return head_of_queue == 0 here
833          */
834         if (head_of_queue)
835                 list_add(&task->t_state_list, (task_prev) ?
836                                 &task_prev->t_state_list :
837                                 &dev->state_task_list);
838         else
839                 list_add_tail(&task->t_state_list, &dev->state_task_list);
840
841         atomic_set(&task->task_state_active, 1);
842
843         pr_debug("Added ITT: 0x%08x task[%p] to dev: %p\n",
844                 task->task_se_cmd->se_tfo->get_task_tag(task->task_se_cmd),
845                 task, dev);
846 }
847
848 static void transport_add_tasks_to_state_queue(struct se_cmd *cmd)
849 {
850         struct se_device *dev = cmd->se_dev;
851         struct se_task *task;
852         unsigned long flags;
853
854         spin_lock_irqsave(&cmd->t_state_lock, flags);
855         list_for_each_entry(task, &cmd->t_task_list, t_list) {
856                 if (atomic_read(&task->task_state_active))
857                         continue;
858
859                 spin_lock(&dev->execute_task_lock);
860                 list_add_tail(&task->t_state_list, &dev->state_task_list);
861                 atomic_set(&task->task_state_active, 1);
862
863                 pr_debug("Added ITT: 0x%08x task[%p] to dev: %p\n",
864                         task->task_se_cmd->se_tfo->get_task_tag(
865                         task->task_se_cmd), task, dev);
866
867                 spin_unlock(&dev->execute_task_lock);
868         }
869         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
870 }
871
872 static void transport_add_tasks_from_cmd(struct se_cmd *cmd)
873 {
874         struct se_device *dev = cmd->se_dev;
875         struct se_task *task, *task_prev = NULL;
876         unsigned long flags;
877
878         spin_lock_irqsave(&dev->execute_task_lock, flags);
879         list_for_each_entry(task, &cmd->t_task_list, t_list) {
880                 if (!list_empty(&task->t_execute_list))
881                         continue;
882                 /*
883                  * __transport_add_task_to_execute_queue() handles the
884                  * SAM Task Attribute emulation if enabled
885                  */
886                 __transport_add_task_to_execute_queue(task, task_prev, dev);
887                 task_prev = task;
888         }
889         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
890 }
891
892 void __transport_remove_task_from_execute_queue(struct se_task *task,
893                 struct se_device *dev)
894 {
895         list_del_init(&task->t_execute_list);
896         atomic_dec(&dev->execute_tasks);
897 }
898
899 void transport_remove_task_from_execute_queue(
900         struct se_task *task,
901         struct se_device *dev)
902 {
903         unsigned long flags;
904
905         if (WARN_ON(list_empty(&task->t_execute_list)))
906                 return;
907
908         spin_lock_irqsave(&dev->execute_task_lock, flags);
909         __transport_remove_task_from_execute_queue(task, dev);
910         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
911 }
912
913 /*
914  * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
915  */
916
917 static void target_qf_do_work(struct work_struct *work)
918 {
919         struct se_device *dev = container_of(work, struct se_device,
920                                         qf_work_queue);
921         LIST_HEAD(qf_cmd_list);
922         struct se_cmd *cmd, *cmd_tmp;
923
924         spin_lock_irq(&dev->qf_cmd_lock);
925         list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
926         spin_unlock_irq(&dev->qf_cmd_lock);
927
928         list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
929                 list_del(&cmd->se_qf_node);
930                 atomic_dec(&dev->dev_qf_count);
931                 smp_mb__after_atomic_dec();
932
933                 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
934                         " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
935                         (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
936                         (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
937                         : "UNKNOWN");
938
939                 transport_add_cmd_to_queue(cmd, cmd->t_state, true);
940         }
941 }
942
943 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
944 {
945         switch (cmd->data_direction) {
946         case DMA_NONE:
947                 return "NONE";
948         case DMA_FROM_DEVICE:
949                 return "READ";
950         case DMA_TO_DEVICE:
951                 return "WRITE";
952         case DMA_BIDIRECTIONAL:
953                 return "BIDI";
954         default:
955                 break;
956         }
957
958         return "UNKNOWN";
959 }
960
961 void transport_dump_dev_state(
962         struct se_device *dev,
963         char *b,
964         int *bl)
965 {
966         *bl += sprintf(b + *bl, "Status: ");
967         switch (dev->dev_status) {
968         case TRANSPORT_DEVICE_ACTIVATED:
969                 *bl += sprintf(b + *bl, "ACTIVATED");
970                 break;
971         case TRANSPORT_DEVICE_DEACTIVATED:
972                 *bl += sprintf(b + *bl, "DEACTIVATED");
973                 break;
974         case TRANSPORT_DEVICE_SHUTDOWN:
975                 *bl += sprintf(b + *bl, "SHUTDOWN");
976                 break;
977         case TRANSPORT_DEVICE_OFFLINE_ACTIVATED:
978         case TRANSPORT_DEVICE_OFFLINE_DEACTIVATED:
979                 *bl += sprintf(b + *bl, "OFFLINE");
980                 break;
981         default:
982                 *bl += sprintf(b + *bl, "UNKNOWN=%d", dev->dev_status);
983                 break;
984         }
985
986         *bl += sprintf(b + *bl, "  Execute/Left/Max Queue Depth: %d/%d/%d",
987                 atomic_read(&dev->execute_tasks), atomic_read(&dev->depth_left),
988                 dev->queue_depth);
989         *bl += sprintf(b + *bl, "  SectorSize: %u  MaxSectors: %u\n",
990                 dev->se_sub_dev->se_dev_attrib.block_size, dev->se_sub_dev->se_dev_attrib.max_sectors);
991         *bl += sprintf(b + *bl, "        ");
992 }
993
994 void transport_dump_vpd_proto_id(
995         struct t10_vpd *vpd,
996         unsigned char *p_buf,
997         int p_buf_len)
998 {
999         unsigned char buf[VPD_TMP_BUF_SIZE];
1000         int len;
1001
1002         memset(buf, 0, VPD_TMP_BUF_SIZE);
1003         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
1004
1005         switch (vpd->protocol_identifier) {
1006         case 0x00:
1007                 sprintf(buf+len, "Fibre Channel\n");
1008                 break;
1009         case 0x10:
1010                 sprintf(buf+len, "Parallel SCSI\n");
1011                 break;
1012         case 0x20:
1013                 sprintf(buf+len, "SSA\n");
1014                 break;
1015         case 0x30:
1016                 sprintf(buf+len, "IEEE 1394\n");
1017                 break;
1018         case 0x40:
1019                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
1020                                 " Protocol\n");
1021                 break;
1022         case 0x50:
1023                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
1024                 break;
1025         case 0x60:
1026                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
1027                 break;
1028         case 0x70:
1029                 sprintf(buf+len, "Automation/Drive Interface Transport"
1030                                 " Protocol\n");
1031                 break;
1032         case 0x80:
1033                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
1034                 break;
1035         default:
1036                 sprintf(buf+len, "Unknown 0x%02x\n",
1037                                 vpd->protocol_identifier);
1038                 break;
1039         }
1040
1041         if (p_buf)
1042                 strncpy(p_buf, buf, p_buf_len);
1043         else
1044                 pr_debug("%s", buf);
1045 }
1046
1047 void
1048 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1049 {
1050         /*
1051          * Check if the Protocol Identifier Valid (PIV) bit is set..
1052          *
1053          * from spc3r23.pdf section 7.5.1
1054          */
1055          if (page_83[1] & 0x80) {
1056                 vpd->protocol_identifier = (page_83[0] & 0xf0);
1057                 vpd->protocol_identifier_set = 1;
1058                 transport_dump_vpd_proto_id(vpd, NULL, 0);
1059         }
1060 }
1061 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1062
1063 int transport_dump_vpd_assoc(
1064         struct t10_vpd *vpd,
1065         unsigned char *p_buf,
1066         int p_buf_len)
1067 {
1068         unsigned char buf[VPD_TMP_BUF_SIZE];
1069         int ret = 0;
1070         int len;
1071
1072         memset(buf, 0, VPD_TMP_BUF_SIZE);
1073         len = sprintf(buf, "T10 VPD Identifier Association: ");
1074
1075         switch (vpd->association) {
1076         case 0x00:
1077                 sprintf(buf+len, "addressed logical unit\n");
1078                 break;
1079         case 0x10:
1080                 sprintf(buf+len, "target port\n");
1081                 break;
1082         case 0x20:
1083                 sprintf(buf+len, "SCSI target device\n");
1084                 break;
1085         default:
1086                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1087                 ret = -EINVAL;
1088                 break;
1089         }
1090
1091         if (p_buf)
1092                 strncpy(p_buf, buf, p_buf_len);
1093         else
1094                 pr_debug("%s", buf);
1095
1096         return ret;
1097 }
1098
1099 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1100 {
1101         /*
1102          * The VPD identification association..
1103          *
1104          * from spc3r23.pdf Section 7.6.3.1 Table 297
1105          */
1106         vpd->association = (page_83[1] & 0x30);
1107         return transport_dump_vpd_assoc(vpd, NULL, 0);
1108 }
1109 EXPORT_SYMBOL(transport_set_vpd_assoc);
1110
1111 int transport_dump_vpd_ident_type(
1112         struct t10_vpd *vpd,
1113         unsigned char *p_buf,
1114         int p_buf_len)
1115 {
1116         unsigned char buf[VPD_TMP_BUF_SIZE];
1117         int ret = 0;
1118         int len;
1119
1120         memset(buf, 0, VPD_TMP_BUF_SIZE);
1121         len = sprintf(buf, "T10 VPD Identifier Type: ");
1122
1123         switch (vpd->device_identifier_type) {
1124         case 0x00:
1125                 sprintf(buf+len, "Vendor specific\n");
1126                 break;
1127         case 0x01:
1128                 sprintf(buf+len, "T10 Vendor ID based\n");
1129                 break;
1130         case 0x02:
1131                 sprintf(buf+len, "EUI-64 based\n");
1132                 break;
1133         case 0x03:
1134                 sprintf(buf+len, "NAA\n");
1135                 break;
1136         case 0x04:
1137                 sprintf(buf+len, "Relative target port identifier\n");
1138                 break;
1139         case 0x08:
1140                 sprintf(buf+len, "SCSI name string\n");
1141                 break;
1142         default:
1143                 sprintf(buf+len, "Unsupported: 0x%02x\n",
1144                                 vpd->device_identifier_type);
1145                 ret = -EINVAL;
1146                 break;
1147         }
1148
1149         if (p_buf) {
1150                 if (p_buf_len < strlen(buf)+1)
1151                         return -EINVAL;
1152                 strncpy(p_buf, buf, p_buf_len);
1153         } else {
1154                 pr_debug("%s", buf);
1155         }
1156
1157         return ret;
1158 }
1159
1160 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1161 {
1162         /*
1163          * The VPD identifier type..
1164          *
1165          * from spc3r23.pdf Section 7.6.3.1 Table 298
1166          */
1167         vpd->device_identifier_type = (page_83[1] & 0x0f);
1168         return transport_dump_vpd_ident_type(vpd, NULL, 0);
1169 }
1170 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1171
1172 int transport_dump_vpd_ident(
1173         struct t10_vpd *vpd,
1174         unsigned char *p_buf,
1175         int p_buf_len)
1176 {
1177         unsigned char buf[VPD_TMP_BUF_SIZE];
1178         int ret = 0;
1179
1180         memset(buf, 0, VPD_TMP_BUF_SIZE);
1181
1182         switch (vpd->device_identifier_code_set) {
1183         case 0x01: /* Binary */
1184                 sprintf(buf, "T10 VPD Binary Device Identifier: %s\n",
1185                         &vpd->device_identifier[0]);
1186                 break;
1187         case 0x02: /* ASCII */
1188                 sprintf(buf, "T10 VPD ASCII Device Identifier: %s\n",
1189                         &vpd->device_identifier[0]);
1190                 break;
1191         case 0x03: /* UTF-8 */
1192                 sprintf(buf, "T10 VPD UTF-8 Device Identifier: %s\n",
1193                         &vpd->device_identifier[0]);
1194                 break;
1195         default:
1196                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1197                         " 0x%02x", vpd->device_identifier_code_set);
1198                 ret = -EINVAL;
1199                 break;
1200         }
1201
1202         if (p_buf)
1203                 strncpy(p_buf, buf, p_buf_len);
1204         else
1205                 pr_debug("%s", buf);
1206
1207         return ret;
1208 }
1209
1210 int
1211 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1212 {
1213         static const char hex_str[] = "0123456789abcdef";
1214         int j = 0, i = 4; /* offset to start of the identifer */
1215
1216         /*
1217          * The VPD Code Set (encoding)
1218          *
1219          * from spc3r23.pdf Section 7.6.3.1 Table 296
1220          */
1221         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1222         switch (vpd->device_identifier_code_set) {
1223         case 0x01: /* Binary */
1224                 vpd->device_identifier[j++] =
1225                                 hex_str[vpd->device_identifier_type];
1226                 while (i < (4 + page_83[3])) {
1227                         vpd->device_identifier[j++] =
1228                                 hex_str[(page_83[i] & 0xf0) >> 4];
1229                         vpd->device_identifier[j++] =
1230                                 hex_str[page_83[i] & 0x0f];
1231                         i++;
1232                 }
1233                 break;
1234         case 0x02: /* ASCII */
1235         case 0x03: /* UTF-8 */
1236                 while (i < (4 + page_83[3]))
1237                         vpd->device_identifier[j++] = page_83[i++];
1238                 break;
1239         default:
1240                 break;
1241         }
1242
1243         return transport_dump_vpd_ident(vpd, NULL, 0);
1244 }
1245 EXPORT_SYMBOL(transport_set_vpd_ident);
1246
1247 static void core_setup_task_attr_emulation(struct se_device *dev)
1248 {
1249         /*
1250          * If this device is from Target_Core_Mod/pSCSI, disable the
1251          * SAM Task Attribute emulation.
1252          *
1253          * This is currently not available in upsream Linux/SCSI Target
1254          * mode code, and is assumed to be disabled while using TCM/pSCSI.
1255          */
1256         if (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) {
1257                 dev->dev_task_attr_type = SAM_TASK_ATTR_PASSTHROUGH;
1258                 return;
1259         }
1260
1261         dev->dev_task_attr_type = SAM_TASK_ATTR_EMULATED;
1262         pr_debug("%s: Using SAM_TASK_ATTR_EMULATED for SPC: 0x%02x"
1263                 " device\n", dev->transport->name,
1264                 dev->transport->get_device_rev(dev));
1265 }
1266
1267 static void scsi_dump_inquiry(struct se_device *dev)
1268 {
1269         struct t10_wwn *wwn = &dev->se_sub_dev->t10_wwn;
1270         int i, device_type;
1271         /*
1272          * Print Linux/SCSI style INQUIRY formatting to the kernel ring buffer
1273          */
1274         pr_debug("  Vendor: ");
1275         for (i = 0; i < 8; i++)
1276                 if (wwn->vendor[i] >= 0x20)
1277                         pr_debug("%c", wwn->vendor[i]);
1278                 else
1279                         pr_debug(" ");
1280
1281         pr_debug("  Model: ");
1282         for (i = 0; i < 16; i++)
1283                 if (wwn->model[i] >= 0x20)
1284                         pr_debug("%c", wwn->model[i]);
1285                 else
1286                         pr_debug(" ");
1287
1288         pr_debug("  Revision: ");
1289         for (i = 0; i < 4; i++)
1290                 if (wwn->revision[i] >= 0x20)
1291                         pr_debug("%c", wwn->revision[i]);
1292                 else
1293                         pr_debug(" ");
1294
1295         pr_debug("\n");
1296
1297         device_type = dev->transport->get_device_type(dev);
1298         pr_debug("  Type:   %s ", scsi_device_type(device_type));
1299         pr_debug("                 ANSI SCSI revision: %02x\n",
1300                                 dev->transport->get_device_rev(dev));
1301 }
1302
1303 struct se_device *transport_add_device_to_core_hba(
1304         struct se_hba *hba,
1305         struct se_subsystem_api *transport,
1306         struct se_subsystem_dev *se_dev,
1307         u32 device_flags,
1308         void *transport_dev,
1309         struct se_dev_limits *dev_limits,
1310         const char *inquiry_prod,
1311         const char *inquiry_rev)
1312 {
1313         int force_pt;
1314         struct se_device  *dev;
1315
1316         dev = kzalloc(sizeof(struct se_device), GFP_KERNEL);
1317         if (!dev) {
1318                 pr_err("Unable to allocate memory for se_dev_t\n");
1319                 return NULL;
1320         }
1321
1322         transport_init_queue_obj(&dev->dev_queue_obj);
1323         dev->dev_flags          = device_flags;
1324         dev->dev_status         |= TRANSPORT_DEVICE_DEACTIVATED;
1325         dev->dev_ptr            = transport_dev;
1326         dev->se_hba             = hba;
1327         dev->se_sub_dev         = se_dev;
1328         dev->transport          = transport;
1329         atomic_set(&dev->active_cmds, 0);
1330         INIT_LIST_HEAD(&dev->dev_list);
1331         INIT_LIST_HEAD(&dev->dev_sep_list);
1332         INIT_LIST_HEAD(&dev->dev_tmr_list);
1333         INIT_LIST_HEAD(&dev->execute_task_list);
1334         INIT_LIST_HEAD(&dev->delayed_cmd_list);
1335         INIT_LIST_HEAD(&dev->ordered_cmd_list);
1336         INIT_LIST_HEAD(&dev->state_task_list);
1337         INIT_LIST_HEAD(&dev->qf_cmd_list);
1338         spin_lock_init(&dev->execute_task_lock);
1339         spin_lock_init(&dev->delayed_cmd_lock);
1340         spin_lock_init(&dev->ordered_cmd_lock);
1341         spin_lock_init(&dev->state_task_lock);
1342         spin_lock_init(&dev->dev_alua_lock);
1343         spin_lock_init(&dev->dev_reservation_lock);
1344         spin_lock_init(&dev->dev_status_lock);
1345         spin_lock_init(&dev->dev_status_thr_lock);
1346         spin_lock_init(&dev->se_port_lock);
1347         spin_lock_init(&dev->se_tmr_lock);
1348         spin_lock_init(&dev->qf_cmd_lock);
1349
1350         dev->queue_depth        = dev_limits->queue_depth;
1351         atomic_set(&dev->depth_left, dev->queue_depth);
1352         atomic_set(&dev->dev_ordered_id, 0);
1353
1354         se_dev_set_default_attribs(dev, dev_limits);
1355
1356         dev->dev_index = scsi_get_new_index(SCSI_DEVICE_INDEX);
1357         dev->creation_time = get_jiffies_64();
1358         spin_lock_init(&dev->stats_lock);
1359
1360         spin_lock(&hba->device_lock);
1361         list_add_tail(&dev->dev_list, &hba->hba_dev_list);
1362         hba->dev_count++;
1363         spin_unlock(&hba->device_lock);
1364         /*
1365          * Setup the SAM Task Attribute emulation for struct se_device
1366          */
1367         core_setup_task_attr_emulation(dev);
1368         /*
1369          * Force PR and ALUA passthrough emulation with internal object use.
1370          */
1371         force_pt = (hba->hba_flags & HBA_FLAGS_INTERNAL_USE);
1372         /*
1373          * Setup the Reservations infrastructure for struct se_device
1374          */
1375         core_setup_reservations(dev, force_pt);
1376         /*
1377          * Setup the Asymmetric Logical Unit Assignment for struct se_device
1378          */
1379         if (core_setup_alua(dev, force_pt) < 0)
1380                 goto out;
1381
1382         /*
1383          * Startup the struct se_device processing thread
1384          */
1385         dev->process_thread = kthread_run(transport_processing_thread, dev,
1386                                           "LIO_%s", dev->transport->name);
1387         if (IS_ERR(dev->process_thread)) {
1388                 pr_err("Unable to create kthread: LIO_%s\n",
1389                         dev->transport->name);
1390                 goto out;
1391         }
1392         /*
1393          * Setup work_queue for QUEUE_FULL
1394          */
1395         INIT_WORK(&dev->qf_work_queue, target_qf_do_work);
1396         /*
1397          * Preload the initial INQUIRY const values if we are doing
1398          * anything virtual (IBLOCK, FILEIO, RAMDISK), but not for TCM/pSCSI
1399          * passthrough because this is being provided by the backend LLD.
1400          * This is required so that transport_get_inquiry() copies these
1401          * originals once back into DEV_T10_WWN(dev) for the virtual device
1402          * setup.
1403          */
1404         if (dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
1405                 if (!inquiry_prod || !inquiry_rev) {
1406                         pr_err("All non TCM/pSCSI plugins require"
1407                                 " INQUIRY consts\n");
1408                         goto out;
1409                 }
1410
1411                 strncpy(&dev->se_sub_dev->t10_wwn.vendor[0], "LIO-ORG", 8);
1412                 strncpy(&dev->se_sub_dev->t10_wwn.model[0], inquiry_prod, 16);
1413                 strncpy(&dev->se_sub_dev->t10_wwn.revision[0], inquiry_rev, 4);
1414         }
1415         scsi_dump_inquiry(dev);
1416
1417         return dev;
1418 out:
1419         kthread_stop(dev->process_thread);
1420
1421         spin_lock(&hba->device_lock);
1422         list_del(&dev->dev_list);
1423         hba->dev_count--;
1424         spin_unlock(&hba->device_lock);
1425
1426         se_release_vpd_for_dev(dev);
1427
1428         kfree(dev);
1429
1430         return NULL;
1431 }
1432 EXPORT_SYMBOL(transport_add_device_to_core_hba);
1433
1434 /*      transport_generic_prepare_cdb():
1435  *
1436  *      Since the Initiator sees iSCSI devices as LUNs,  the SCSI CDB will
1437  *      contain the iSCSI LUN in bits 7-5 of byte 1 as per SAM-2.
1438  *      The point of this is since we are mapping iSCSI LUNs to
1439  *      SCSI Target IDs having a non-zero LUN in the CDB will throw the
1440  *      devices and HBAs for a loop.
1441  */
1442 static inline void transport_generic_prepare_cdb(
1443         unsigned char *cdb)
1444 {
1445         switch (cdb[0]) {
1446         case READ_10: /* SBC - RDProtect */
1447         case READ_12: /* SBC - RDProtect */
1448         case READ_16: /* SBC - RDProtect */
1449         case SEND_DIAGNOSTIC: /* SPC - SELF-TEST Code */
1450         case VERIFY: /* SBC - VRProtect */
1451         case VERIFY_16: /* SBC - VRProtect */
1452         case WRITE_VERIFY: /* SBC - VRProtect */
1453         case WRITE_VERIFY_12: /* SBC - VRProtect */
1454                 break;
1455         default:
1456                 cdb[1] &= 0x1f; /* clear logical unit number */
1457                 break;
1458         }
1459 }
1460
1461 static struct se_task *
1462 transport_generic_get_task(struct se_cmd *cmd,
1463                 enum dma_data_direction data_direction)
1464 {
1465         struct se_task *task;
1466         struct se_device *dev = cmd->se_dev;
1467
1468         task = dev->transport->alloc_task(cmd->t_task_cdb);
1469         if (!task) {
1470                 pr_err("Unable to allocate struct se_task\n");
1471                 return NULL;
1472         }
1473
1474         INIT_LIST_HEAD(&task->t_list);
1475         INIT_LIST_HEAD(&task->t_execute_list);
1476         INIT_LIST_HEAD(&task->t_state_list);
1477         init_completion(&task->task_stop_comp);
1478         task->task_se_cmd = cmd;
1479         task->task_data_direction = data_direction;
1480
1481         return task;
1482 }
1483
1484 static int transport_generic_cmd_sequencer(struct se_cmd *, unsigned char *);
1485
1486 /*
1487  * Used by fabric modules containing a local struct se_cmd within their
1488  * fabric dependent per I/O descriptor.
1489  */
1490 void transport_init_se_cmd(
1491         struct se_cmd *cmd,
1492         struct target_core_fabric_ops *tfo,
1493         struct se_session *se_sess,
1494         u32 data_length,
1495         int data_direction,
1496         int task_attr,
1497         unsigned char *sense_buffer)
1498 {
1499         INIT_LIST_HEAD(&cmd->se_lun_node);
1500         INIT_LIST_HEAD(&cmd->se_delayed_node);
1501         INIT_LIST_HEAD(&cmd->se_ordered_node);
1502         INIT_LIST_HEAD(&cmd->se_qf_node);
1503         INIT_LIST_HEAD(&cmd->se_queue_node);
1504         INIT_LIST_HEAD(&cmd->se_cmd_list);
1505         INIT_LIST_HEAD(&cmd->t_task_list);
1506         init_completion(&cmd->transport_lun_fe_stop_comp);
1507         init_completion(&cmd->transport_lun_stop_comp);
1508         init_completion(&cmd->t_transport_stop_comp);
1509         init_completion(&cmd->cmd_wait_comp);
1510         spin_lock_init(&cmd->t_state_lock);
1511         atomic_set(&cmd->transport_dev_active, 1);
1512
1513         cmd->se_tfo = tfo;
1514         cmd->se_sess = se_sess;
1515         cmd->data_length = data_length;
1516         cmd->data_direction = data_direction;
1517         cmd->sam_task_attr = task_attr;
1518         cmd->sense_buffer = sense_buffer;
1519 }
1520 EXPORT_SYMBOL(transport_init_se_cmd);
1521
1522 static int transport_check_alloc_task_attr(struct se_cmd *cmd)
1523 {
1524         /*
1525          * Check if SAM Task Attribute emulation is enabled for this
1526          * struct se_device storage object
1527          */
1528         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1529                 return 0;
1530
1531         if (cmd->sam_task_attr == MSG_ACA_TAG) {
1532                 pr_debug("SAM Task Attribute ACA"
1533                         " emulation is not supported\n");
1534                 return -EINVAL;
1535         }
1536         /*
1537          * Used to determine when ORDERED commands should go from
1538          * Dormant to Active status.
1539          */
1540         cmd->se_ordered_id = atomic_inc_return(&cmd->se_dev->dev_ordered_id);
1541         smp_mb__after_atomic_inc();
1542         pr_debug("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n",
1543                         cmd->se_ordered_id, cmd->sam_task_attr,
1544                         cmd->se_dev->transport->name);
1545         return 0;
1546 }
1547
1548 /*      transport_generic_allocate_tasks():
1549  *
1550  *      Called from fabric RX Thread.
1551  */
1552 int transport_generic_allocate_tasks(
1553         struct se_cmd *cmd,
1554         unsigned char *cdb)
1555 {
1556         int ret;
1557
1558         transport_generic_prepare_cdb(cdb);
1559         /*
1560          * Ensure that the received CDB is less than the max (252 + 8) bytes
1561          * for VARIABLE_LENGTH_CMD
1562          */
1563         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1564                 pr_err("Received SCSI CDB with command_size: %d that"
1565                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1566                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1567                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1568                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1569                 return -EINVAL;
1570         }
1571         /*
1572          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1573          * allocate the additional extended CDB buffer now..  Otherwise
1574          * setup the pointer from __t_task_cdb to t_task_cdb.
1575          */
1576         if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1577                 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1578                                                 GFP_KERNEL);
1579                 if (!cmd->t_task_cdb) {
1580                         pr_err("Unable to allocate cmd->t_task_cdb"
1581                                 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1582                                 scsi_command_size(cdb),
1583                                 (unsigned long)sizeof(cmd->__t_task_cdb));
1584                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1585                         cmd->scsi_sense_reason =
1586                                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1587                         return -ENOMEM;
1588                 }
1589         } else
1590                 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1591         /*
1592          * Copy the original CDB into cmd->
1593          */
1594         memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1595         /*
1596          * Setup the received CDB based on SCSI defined opcodes and
1597          * perform unit attention, persistent reservations and ALUA
1598          * checks for virtual device backends.  The cmd->t_task_cdb
1599          * pointer is expected to be setup before we reach this point.
1600          */
1601         ret = transport_generic_cmd_sequencer(cmd, cdb);
1602         if (ret < 0)
1603                 return ret;
1604         /*
1605          * Check for SAM Task Attribute Emulation
1606          */
1607         if (transport_check_alloc_task_attr(cmd) < 0) {
1608                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1609                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1610                 return -EINVAL;
1611         }
1612         spin_lock(&cmd->se_lun->lun_sep_lock);
1613         if (cmd->se_lun->lun_sep)
1614                 cmd->se_lun->lun_sep->sep_stats.cmd_pdus++;
1615         spin_unlock(&cmd->se_lun->lun_sep_lock);
1616         return 0;
1617 }
1618 EXPORT_SYMBOL(transport_generic_allocate_tasks);
1619
1620 /*
1621  * Used by fabric module frontends to queue tasks directly.
1622  * Many only be used from process context only
1623  */
1624 int transport_handle_cdb_direct(
1625         struct se_cmd *cmd)
1626 {
1627         int ret;
1628
1629         if (!cmd->se_lun) {
1630                 dump_stack();
1631                 pr_err("cmd->se_lun is NULL\n");
1632                 return -EINVAL;
1633         }
1634         if (in_interrupt()) {
1635                 dump_stack();
1636                 pr_err("transport_generic_handle_cdb cannot be called"
1637                                 " from interrupt context\n");
1638                 return -EINVAL;
1639         }
1640         /*
1641          * Set TRANSPORT_NEW_CMD state and cmd->t_transport_active=1 following
1642          * transport_generic_handle_cdb*() -> transport_add_cmd_to_queue()
1643          * in existing usage to ensure that outstanding descriptors are handled
1644          * correctly during shutdown via transport_wait_for_tasks()
1645          *
1646          * Also, we don't take cmd->t_state_lock here as we only expect
1647          * this to be called for initial descriptor submission.
1648          */
1649         cmd->t_state = TRANSPORT_NEW_CMD;
1650         atomic_set(&cmd->t_transport_active, 1);
1651         /*
1652          * transport_generic_new_cmd() is already handling QUEUE_FULL,
1653          * so follow TRANSPORT_NEW_CMD processing thread context usage
1654          * and call transport_generic_request_failure() if necessary..
1655          */
1656         ret = transport_generic_new_cmd(cmd);
1657         if (ret < 0)
1658                 transport_generic_request_failure(cmd);
1659
1660         return 0;
1661 }
1662 EXPORT_SYMBOL(transport_handle_cdb_direct);
1663
1664 /*
1665  * Used by fabric module frontends defining a TFO->new_cmd_map() caller
1666  * to  queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD_MAP in order to
1667  * complete setup in TCM process context w/ TFO->new_cmd_map().
1668  */
1669 int transport_generic_handle_cdb_map(
1670         struct se_cmd *cmd)
1671 {
1672         if (!cmd->se_lun) {
1673                 dump_stack();
1674                 pr_err("cmd->se_lun is NULL\n");
1675                 return -EINVAL;
1676         }
1677
1678         transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD_MAP, false);
1679         return 0;
1680 }
1681 EXPORT_SYMBOL(transport_generic_handle_cdb_map);
1682
1683 /*      transport_generic_handle_data():
1684  *
1685  *
1686  */
1687 int transport_generic_handle_data(
1688         struct se_cmd *cmd)
1689 {
1690         /*
1691          * For the software fabric case, then we assume the nexus is being
1692          * failed/shutdown when signals are pending from the kthread context
1693          * caller, so we return a failure.  For the HW target mode case running
1694          * in interrupt code, the signal_pending() check is skipped.
1695          */
1696         if (!in_interrupt() && signal_pending(current))
1697                 return -EPERM;
1698         /*
1699          * If the received CDB has aleady been ABORTED by the generic
1700          * target engine, we now call transport_check_aborted_status()
1701          * to queue any delated TASK_ABORTED status for the received CDB to the
1702          * fabric module as we are expecting no further incoming DATA OUT
1703          * sequences at this point.
1704          */
1705         if (transport_check_aborted_status(cmd, 1) != 0)
1706                 return 0;
1707
1708         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_WRITE, false);
1709         return 0;
1710 }
1711 EXPORT_SYMBOL(transport_generic_handle_data);
1712
1713 /*      transport_generic_handle_tmr():
1714  *
1715  *
1716  */
1717 int transport_generic_handle_tmr(
1718         struct se_cmd *cmd)
1719 {
1720         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_TMR, false);
1721         return 0;
1722 }
1723 EXPORT_SYMBOL(transport_generic_handle_tmr);
1724
1725 /*
1726  * If the task is active, request it to be stopped and sleep until it
1727  * has completed.
1728  */
1729 bool target_stop_task(struct se_task *task, unsigned long *flags)
1730 {
1731         struct se_cmd *cmd = task->task_se_cmd;
1732         bool was_active = false;
1733
1734         if (task->task_flags & TF_ACTIVE) {
1735                 task->task_flags |= TF_REQUEST_STOP;
1736                 spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
1737
1738                 pr_debug("Task %p waiting to complete\n", task);
1739                 wait_for_completion(&task->task_stop_comp);
1740                 pr_debug("Task %p stopped successfully\n", task);
1741
1742                 spin_lock_irqsave(&cmd->t_state_lock, *flags);
1743                 atomic_dec(&cmd->t_task_cdbs_left);
1744                 task->task_flags &= ~(TF_ACTIVE | TF_REQUEST_STOP);
1745                 was_active = true;
1746         }
1747
1748         return was_active;
1749 }
1750
1751 static int transport_stop_tasks_for_cmd(struct se_cmd *cmd)
1752 {
1753         struct se_task *task, *task_tmp;
1754         unsigned long flags;
1755         int ret = 0;
1756
1757         pr_debug("ITT[0x%08x] - Stopping tasks\n",
1758                 cmd->se_tfo->get_task_tag(cmd));
1759
1760         /*
1761          * No tasks remain in the execution queue
1762          */
1763         spin_lock_irqsave(&cmd->t_state_lock, flags);
1764         list_for_each_entry_safe(task, task_tmp,
1765                                 &cmd->t_task_list, t_list) {
1766                 pr_debug("Processing task %p\n", task);
1767                 /*
1768                  * If the struct se_task has not been sent and is not active,
1769                  * remove the struct se_task from the execution queue.
1770                  */
1771                 if (!(task->task_flags & (TF_ACTIVE | TF_SENT))) {
1772                         spin_unlock_irqrestore(&cmd->t_state_lock,
1773                                         flags);
1774                         transport_remove_task_from_execute_queue(task,
1775                                         cmd->se_dev);
1776
1777                         pr_debug("Task %p removed from execute queue\n", task);
1778                         spin_lock_irqsave(&cmd->t_state_lock, flags);
1779                         continue;
1780                 }
1781
1782                 if (!target_stop_task(task, &flags)) {
1783                         pr_debug("Task %p - did nothing\n", task);
1784                         ret++;
1785                 }
1786         }
1787         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1788
1789         return ret;
1790 }
1791
1792 /*
1793  * Handle SAM-esque emulation for generic transport request failures.
1794  */
1795 static void transport_generic_request_failure(struct se_cmd *cmd)
1796 {
1797         int ret = 0;
1798
1799         pr_debug("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
1800                 " CDB: 0x%02x\n", cmd, cmd->se_tfo->get_task_tag(cmd),
1801                 cmd->t_task_cdb[0]);
1802         pr_debug("-----[ i_state: %d t_state: %d scsi_sense_reason: %d\n",
1803                 cmd->se_tfo->get_cmd_state(cmd),
1804                 cmd->t_state, cmd->scsi_sense_reason);
1805         pr_debug("-----[ t_tasks: %d t_task_cdbs_left: %d"
1806                 " t_task_cdbs_sent: %d t_task_cdbs_ex_left: %d --"
1807                 " t_transport_active: %d t_transport_stop: %d"
1808                 " t_transport_sent: %d\n", cmd->t_task_list_num,
1809                 atomic_read(&cmd->t_task_cdbs_left),
1810                 atomic_read(&cmd->t_task_cdbs_sent),
1811                 atomic_read(&cmd->t_task_cdbs_ex_left),
1812                 atomic_read(&cmd->t_transport_active),
1813                 atomic_read(&cmd->t_transport_stop),
1814                 atomic_read(&cmd->t_transport_sent));
1815
1816         /*
1817          * For SAM Task Attribute emulation for failed struct se_cmd
1818          */
1819         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1820                 transport_complete_task_attr(cmd);
1821
1822         switch (cmd->scsi_sense_reason) {
1823         case TCM_NON_EXISTENT_LUN:
1824         case TCM_UNSUPPORTED_SCSI_OPCODE:
1825         case TCM_INVALID_CDB_FIELD:
1826         case TCM_INVALID_PARAMETER_LIST:
1827         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1828         case TCM_UNKNOWN_MODE_PAGE:
1829         case TCM_WRITE_PROTECTED:
1830         case TCM_CHECK_CONDITION_ABORT_CMD:
1831         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1832         case TCM_CHECK_CONDITION_NOT_READY:
1833                 break;
1834         case TCM_RESERVATION_CONFLICT:
1835                 /*
1836                  * No SENSE Data payload for this case, set SCSI Status
1837                  * and queue the response to $FABRIC_MOD.
1838                  *
1839                  * Uses linux/include/scsi/scsi.h SAM status codes defs
1840                  */
1841                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1842                 /*
1843                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1844                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1845                  * CONFLICT STATUS.
1846                  *
1847                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1848                  */
1849                 if (cmd->se_sess &&
1850                     cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
1851                         core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
1852                                 cmd->orig_fe_lun, 0x2C,
1853                                 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1854
1855                 ret = cmd->se_tfo->queue_status(cmd);
1856                 if (ret == -EAGAIN || ret == -ENOMEM)
1857                         goto queue_full;
1858                 goto check_stop;
1859         default:
1860                 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1861                         cmd->t_task_cdb[0], cmd->scsi_sense_reason);
1862                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1863                 break;
1864         }
1865         /*
1866          * If a fabric does not define a cmd->se_tfo->new_cmd_map caller,
1867          * make the call to transport_send_check_condition_and_sense()
1868          * directly.  Otherwise expect the fabric to make the call to
1869          * transport_send_check_condition_and_sense() after handling
1870          * possible unsoliticied write data payloads.
1871          */
1872         ret = transport_send_check_condition_and_sense(cmd,
1873                         cmd->scsi_sense_reason, 0);
1874         if (ret == -EAGAIN || ret == -ENOMEM)
1875                 goto queue_full;
1876
1877 check_stop:
1878         transport_lun_remove_cmd(cmd);
1879         if (!transport_cmd_check_stop_to_fabric(cmd))
1880                 ;
1881         return;
1882
1883 queue_full:
1884         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
1885         transport_handle_queue_full(cmd, cmd->se_dev);
1886 }
1887
1888 static inline u32 transport_lba_21(unsigned char *cdb)
1889 {
1890         return ((cdb[1] & 0x1f) << 16) | (cdb[2] << 8) | cdb[3];
1891 }
1892
1893 static inline u32 transport_lba_32(unsigned char *cdb)
1894 {
1895         return (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
1896 }
1897
1898 static inline unsigned long long transport_lba_64(unsigned char *cdb)
1899 {
1900         unsigned int __v1, __v2;
1901
1902         __v1 = (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
1903         __v2 = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
1904
1905         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
1906 }
1907
1908 /*
1909  * For VARIABLE_LENGTH_CDB w/ 32 byte extended CDBs
1910  */
1911 static inline unsigned long long transport_lba_64_ext(unsigned char *cdb)
1912 {
1913         unsigned int __v1, __v2;
1914
1915         __v1 = (cdb[12] << 24) | (cdb[13] << 16) | (cdb[14] << 8) | cdb[15];
1916         __v2 = (cdb[16] << 24) | (cdb[17] << 16) | (cdb[18] << 8) | cdb[19];
1917
1918         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
1919 }
1920
1921 static void transport_set_supported_SAM_opcode(struct se_cmd *se_cmd)
1922 {
1923         unsigned long flags;
1924
1925         spin_lock_irqsave(&se_cmd->t_state_lock, flags);
1926         se_cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1927         spin_unlock_irqrestore(&se_cmd->t_state_lock, flags);
1928 }
1929
1930 static inline int transport_tcq_window_closed(struct se_device *dev)
1931 {
1932         if (dev->dev_tcq_window_closed++ <
1933                         PYX_TRANSPORT_WINDOW_CLOSED_THRESHOLD) {
1934                 msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_SHORT);
1935         } else
1936                 msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_LONG);
1937
1938         wake_up_interruptible(&dev->dev_queue_obj.thread_wq);
1939         return 0;
1940 }
1941
1942 /*
1943  * Called from Fabric Module context from transport_execute_tasks()
1944  *
1945  * The return of this function determins if the tasks from struct se_cmd
1946  * get added to the execution queue in transport_execute_tasks(),
1947  * or are added to the delayed or ordered lists here.
1948  */
1949 static inline int transport_execute_task_attr(struct se_cmd *cmd)
1950 {
1951         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1952                 return 1;
1953         /*
1954          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
1955          * to allow the passed struct se_cmd list of tasks to the front of the list.
1956          */
1957          if (cmd->sam_task_attr == MSG_HEAD_TAG) {
1958                 atomic_inc(&cmd->se_dev->dev_hoq_count);
1959                 smp_mb__after_atomic_inc();
1960                 pr_debug("Added HEAD_OF_QUEUE for CDB:"
1961                         " 0x%02x, se_ordered_id: %u\n",
1962                         cmd->t_task_cdb[0],
1963                         cmd->se_ordered_id);
1964                 return 1;
1965         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
1966                 spin_lock(&cmd->se_dev->ordered_cmd_lock);
1967                 list_add_tail(&cmd->se_ordered_node,
1968                                 &cmd->se_dev->ordered_cmd_list);
1969                 spin_unlock(&cmd->se_dev->ordered_cmd_lock);
1970
1971                 atomic_inc(&cmd->se_dev->dev_ordered_sync);
1972                 smp_mb__after_atomic_inc();
1973
1974                 pr_debug("Added ORDERED for CDB: 0x%02x to ordered"
1975                                 " list, se_ordered_id: %u\n",
1976                                 cmd->t_task_cdb[0],
1977                                 cmd->se_ordered_id);
1978                 /*
1979                  * Add ORDERED command to tail of execution queue if
1980                  * no other older commands exist that need to be
1981                  * completed first.
1982                  */
1983                 if (!atomic_read(&cmd->se_dev->simple_cmds))
1984                         return 1;
1985         } else {
1986                 /*
1987                  * For SIMPLE and UNTAGGED Task Attribute commands
1988                  */
1989                 atomic_inc(&cmd->se_dev->simple_cmds);
1990                 smp_mb__after_atomic_inc();
1991         }
1992         /*
1993          * Otherwise if one or more outstanding ORDERED task attribute exist,
1994          * add the dormant task(s) built for the passed struct se_cmd to the
1995          * execution queue and become in Active state for this struct se_device.
1996          */
1997         if (atomic_read(&cmd->se_dev->dev_ordered_sync) != 0) {
1998                 /*
1999                  * Otherwise, add cmd w/ tasks to delayed cmd queue that
2000                  * will be drained upon completion of HEAD_OF_QUEUE task.
2001                  */
2002                 spin_lock(&cmd->se_dev->delayed_cmd_lock);
2003                 cmd->se_cmd_flags |= SCF_DELAYED_CMD_FROM_SAM_ATTR;
2004                 list_add_tail(&cmd->se_delayed_node,
2005                                 &cmd->se_dev->delayed_cmd_list);
2006                 spin_unlock(&cmd->se_dev->delayed_cmd_lock);
2007
2008                 pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to"
2009                         " delayed CMD list, se_ordered_id: %u\n",
2010                         cmd->t_task_cdb[0], cmd->sam_task_attr,
2011                         cmd->se_ordered_id);
2012                 /*
2013                  * Return zero to let transport_execute_tasks() know
2014                  * not to add the delayed tasks to the execution list.
2015                  */
2016                 return 0;
2017         }
2018         /*
2019          * Otherwise, no ORDERED task attributes exist..
2020          */
2021         return 1;
2022 }
2023
2024 /*
2025  * Called from fabric module context in transport_generic_new_cmd() and
2026  * transport_generic_process_write()
2027  */
2028 static int transport_execute_tasks(struct se_cmd *cmd)
2029 {
2030         int add_tasks;
2031
2032         if (se_dev_check_online(cmd->se_dev) != 0) {
2033                 cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2034                 transport_generic_request_failure(cmd);
2035                 return 0;
2036         }
2037
2038         /*
2039          * Call transport_cmd_check_stop() to see if a fabric exception
2040          * has occurred that prevents execution.
2041          */
2042         if (!transport_cmd_check_stop(cmd, 0, TRANSPORT_PROCESSING)) {
2043                 /*
2044                  * Check for SAM Task Attribute emulation and HEAD_OF_QUEUE
2045                  * attribute for the tasks of the received struct se_cmd CDB
2046                  */
2047                 add_tasks = transport_execute_task_attr(cmd);
2048                 if (!add_tasks)
2049                         goto execute_tasks;
2050                 /*
2051                  * This calls transport_add_tasks_from_cmd() to handle
2052                  * HEAD_OF_QUEUE ordering for SAM Task Attribute emulation
2053                  * (if enabled) in __transport_add_task_to_execute_queue() and
2054                  * transport_add_task_check_sam_attr().
2055                  */
2056                 transport_add_tasks_from_cmd(cmd);
2057         }
2058         /*
2059          * Kick the execution queue for the cmd associated struct se_device
2060          * storage object.
2061          */
2062 execute_tasks:
2063         __transport_execute_tasks(cmd->se_dev);
2064         return 0;
2065 }
2066
2067 /*
2068  * Called to check struct se_device tcq depth window, and once open pull struct se_task
2069  * from struct se_device->execute_task_list and
2070  *
2071  * Called from transport_processing_thread()
2072  */
2073 static int __transport_execute_tasks(struct se_device *dev)
2074 {
2075         int error;
2076         struct se_cmd *cmd = NULL;
2077         struct se_task *task = NULL;
2078         unsigned long flags;
2079
2080         /*
2081          * Check if there is enough room in the device and HBA queue to send
2082          * struct se_tasks to the selected transport.
2083          */
2084 check_depth:
2085         if (!atomic_read(&dev->depth_left))
2086                 return transport_tcq_window_closed(dev);
2087
2088         dev->dev_tcq_window_closed = 0;
2089
2090         spin_lock_irq(&dev->execute_task_lock);
2091         if (list_empty(&dev->execute_task_list)) {
2092                 spin_unlock_irq(&dev->execute_task_lock);
2093                 return 0;
2094         }
2095         task = list_first_entry(&dev->execute_task_list,
2096                                 struct se_task, t_execute_list);
2097         __transport_remove_task_from_execute_queue(task, dev);
2098         spin_unlock_irq(&dev->execute_task_lock);
2099
2100         atomic_dec(&dev->depth_left);
2101
2102         cmd = task->task_se_cmd;
2103
2104         spin_lock_irqsave(&cmd->t_state_lock, flags);
2105         task->task_flags |= (TF_ACTIVE | TF_SENT);
2106         atomic_inc(&cmd->t_task_cdbs_sent);
2107
2108         if (atomic_read(&cmd->t_task_cdbs_sent) ==
2109             cmd->t_task_list_num)
2110                 atomic_set(&cmd->t_transport_sent, 1);
2111
2112         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2113
2114         if (cmd->execute_task)
2115                 error = cmd->execute_task(task);
2116         else
2117                 error = dev->transport->do_task(task);
2118         if (error != 0) {
2119                 spin_lock_irqsave(&cmd->t_state_lock, flags);
2120                 task->task_flags &= ~TF_ACTIVE;
2121                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2122                 atomic_set(&cmd->t_transport_sent, 0);
2123                 transport_stop_tasks_for_cmd(cmd);
2124                 atomic_inc(&dev->depth_left);
2125                 transport_generic_request_failure(cmd);
2126         }
2127
2128         goto check_depth;
2129
2130         return 0;
2131 }
2132
2133 static inline u32 transport_get_sectors_6(
2134         unsigned char *cdb,
2135         struct se_cmd *cmd,
2136         int *ret)
2137 {
2138         struct se_device *dev = cmd->se_dev;
2139
2140         /*
2141          * Assume TYPE_DISK for non struct se_device objects.
2142          * Use 8-bit sector value.
2143          */
2144         if (!dev)
2145                 goto type_disk;
2146
2147         /*
2148          * Use 24-bit allocation length for TYPE_TAPE.
2149          */
2150         if (dev->transport->get_device_type(dev) == TYPE_TAPE)
2151                 return (u32)(cdb[2] << 16) + (cdb[3] << 8) + cdb[4];
2152
2153         /*
2154          * Everything else assume TYPE_DISK Sector CDB location.
2155          * Use 8-bit sector value.
2156          */
2157 type_disk:
2158         return (u32)cdb[4];
2159 }
2160
2161 static inline u32 transport_get_sectors_10(
2162         unsigned char *cdb,
2163         struct se_cmd *cmd,
2164         int *ret)
2165 {
2166         struct se_device *dev = cmd->se_dev;
2167
2168         /*
2169          * Assume TYPE_DISK for non struct se_device objects.
2170          * Use 16-bit sector value.
2171          */
2172         if (!dev)
2173                 goto type_disk;
2174
2175         /*
2176          * XXX_10 is not defined in SSC, throw an exception
2177          */
2178         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2179                 *ret = -EINVAL;
2180                 return 0;
2181         }
2182
2183         /*
2184          * Everything else assume TYPE_DISK Sector CDB location.
2185          * Use 16-bit sector value.
2186          */
2187 type_disk:
2188         return (u32)(cdb[7] << 8) + cdb[8];
2189 }
2190
2191 static inline u32 transport_get_sectors_12(
2192         unsigned char *cdb,
2193         struct se_cmd *cmd,
2194         int *ret)
2195 {
2196         struct se_device *dev = cmd->se_dev;
2197
2198         /*
2199          * Assume TYPE_DISK for non struct se_device objects.
2200          * Use 32-bit sector value.
2201          */
2202         if (!dev)
2203                 goto type_disk;
2204
2205         /*
2206          * XXX_12 is not defined in SSC, throw an exception
2207          */
2208         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2209                 *ret = -EINVAL;
2210                 return 0;
2211         }
2212
2213         /*
2214          * Everything else assume TYPE_DISK Sector CDB location.
2215          * Use 32-bit sector value.
2216          */
2217 type_disk:
2218         return (u32)(cdb[6] << 24) + (cdb[7] << 16) + (cdb[8] << 8) + cdb[9];
2219 }
2220
2221 static inline u32 transport_get_sectors_16(
2222         unsigned char *cdb,
2223         struct se_cmd *cmd,
2224         int *ret)
2225 {
2226         struct se_device *dev = cmd->se_dev;
2227
2228         /*
2229          * Assume TYPE_DISK for non struct se_device objects.
2230          * Use 32-bit sector value.
2231          */
2232         if (!dev)
2233                 goto type_disk;
2234
2235         /*
2236          * Use 24-bit allocation length for TYPE_TAPE.
2237          */
2238         if (dev->transport->get_device_type(dev) == TYPE_TAPE)
2239                 return (u32)(cdb[12] << 16) + (cdb[13] << 8) + cdb[14];
2240
2241 type_disk:
2242         return (u32)(cdb[10] << 24) + (cdb[11] << 16) +
2243                     (cdb[12] << 8) + cdb[13];
2244 }
2245
2246 /*
2247  * Used for VARIABLE_LENGTH_CDB WRITE_32 and READ_32 variants
2248  */
2249 static inline u32 transport_get_sectors_32(
2250         unsigned char *cdb,
2251         struct se_cmd *cmd,
2252         int *ret)
2253 {
2254         /*
2255          * Assume TYPE_DISK for non struct se_device objects.
2256          * Use 32-bit sector value.
2257          */
2258         return (u32)(cdb[28] << 24) + (cdb[29] << 16) +
2259                     (cdb[30] << 8) + cdb[31];
2260
2261 }
2262
2263 static inline u32 transport_get_size(
2264         u32 sectors,
2265         unsigned char *cdb,
2266         struct se_cmd *cmd)
2267 {
2268         struct se_device *dev = cmd->se_dev;
2269
2270         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2271                 if (cdb[1] & 1) { /* sectors */
2272                         return dev->se_sub_dev->se_dev_attrib.block_size * sectors;
2273                 } else /* bytes */
2274                         return sectors;
2275         }
2276 #if 0
2277         pr_debug("Returning block_size: %u, sectors: %u == %u for"
2278                         " %s object\n", dev->se_sub_dev->se_dev_attrib.block_size, sectors,
2279                         dev->se_sub_dev->se_dev_attrib.block_size * sectors,
2280                         dev->transport->name);
2281 #endif
2282         return dev->se_sub_dev->se_dev_attrib.block_size * sectors;
2283 }
2284
2285 static void transport_xor_callback(struct se_cmd *cmd)
2286 {
2287         unsigned char *buf, *addr;
2288         struct scatterlist *sg;
2289         unsigned int offset;
2290         int i;
2291         int count;
2292         /*
2293          * From sbc3r22.pdf section 5.48 XDWRITEREAD (10) command
2294          *
2295          * 1) read the specified logical block(s);
2296          * 2) transfer logical blocks from the data-out buffer;
2297          * 3) XOR the logical blocks transferred from the data-out buffer with
2298          *    the logical blocks read, storing the resulting XOR data in a buffer;
2299          * 4) if the DISABLE WRITE bit is set to zero, then write the logical
2300          *    blocks transferred from the data-out buffer; and
2301          * 5) transfer the resulting XOR data to the data-in buffer.
2302          */
2303         buf = kmalloc(cmd->data_length, GFP_KERNEL);
2304         if (!buf) {
2305                 pr_err("Unable to allocate xor_callback buf\n");
2306                 return;
2307         }
2308         /*
2309          * Copy the scatterlist WRITE buffer located at cmd->t_data_sg
2310          * into the locally allocated *buf
2311          */
2312         sg_copy_to_buffer(cmd->t_data_sg,
2313                           cmd->t_data_nents,
2314                           buf,
2315                           cmd->data_length);
2316
2317         /*
2318          * Now perform the XOR against the BIDI read memory located at
2319          * cmd->t_mem_bidi_list
2320          */
2321
2322         offset = 0;
2323         for_each_sg(cmd->t_bidi_data_sg, sg, cmd->t_bidi_data_nents, count) {
2324                 addr = kmap_atomic(sg_page(sg), KM_USER0);
2325                 if (!addr)
2326                         goto out;
2327
2328                 for (i = 0; i < sg->length; i++)
2329                         *(addr + sg->offset + i) ^= *(buf + offset + i);
2330
2331                 offset += sg->length;
2332                 kunmap_atomic(addr, KM_USER0);
2333         }
2334
2335 out:
2336         kfree(buf);
2337 }
2338
2339 /*
2340  * Used to obtain Sense Data from underlying Linux/SCSI struct scsi_cmnd
2341  */
2342 static int transport_get_sense_data(struct se_cmd *cmd)
2343 {
2344         unsigned char *buffer = cmd->sense_buffer, *sense_buffer = NULL;
2345         struct se_device *dev = cmd->se_dev;
2346         struct se_task *task = NULL, *task_tmp;
2347         unsigned long flags;
2348         u32 offset = 0;
2349
2350         WARN_ON(!cmd->se_lun);
2351
2352         if (!dev)
2353                 return 0;
2354
2355         spin_lock_irqsave(&cmd->t_state_lock, flags);
2356         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
2357                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2358                 return 0;
2359         }
2360
2361         list_for_each_entry_safe(task, task_tmp,
2362                                 &cmd->t_task_list, t_list) {
2363                 if (!task->task_sense)
2364                         continue;
2365
2366                 if (!dev->transport->get_sense_buffer) {
2367                         pr_err("dev->transport->get_sense_buffer"
2368                                         " is NULL\n");
2369                         continue;
2370                 }
2371
2372                 sense_buffer = dev->transport->get_sense_buffer(task);
2373                 if (!sense_buffer) {
2374                         pr_err("ITT[0x%08x]_TASK[%p]: Unable to locate"
2375                                 " sense buffer for task with sense\n",
2376                                 cmd->se_tfo->get_task_tag(cmd), task);
2377                         continue;
2378                 }
2379                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2380
2381                 offset = cmd->se_tfo->set_fabric_sense_len(cmd,
2382                                 TRANSPORT_SENSE_BUFFER);
2383
2384                 memcpy(&buffer[offset], sense_buffer,
2385                                 TRANSPORT_SENSE_BUFFER);
2386                 cmd->scsi_status = task->task_scsi_status;
2387                 /* Automatically padded */
2388                 cmd->scsi_sense_length =
2389                                 (TRANSPORT_SENSE_BUFFER + offset);
2390
2391                 pr_debug("HBA_[%u]_PLUG[%s]: Set SAM STATUS: 0x%02x"
2392                                 " and sense\n",
2393                         dev->se_hba->hba_id, dev->transport->name,
2394                                 cmd->scsi_status);
2395                 return 0;
2396         }
2397         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2398
2399         return -1;
2400 }
2401
2402 static inline long long transport_dev_end_lba(struct se_device *dev)
2403 {
2404         return dev->transport->get_blocks(dev) + 1;
2405 }
2406
2407 static int transport_cmd_get_valid_sectors(struct se_cmd *cmd)
2408 {
2409         struct se_device *dev = cmd->se_dev;
2410         u32 sectors;
2411
2412         if (dev->transport->get_device_type(dev) != TYPE_DISK)
2413                 return 0;
2414
2415         sectors = (cmd->data_length / dev->se_sub_dev->se_dev_attrib.block_size);
2416
2417         if ((cmd->t_task_lba + sectors) > transport_dev_end_lba(dev)) {
2418                 pr_err("LBA: %llu Sectors: %u exceeds"
2419                         " transport_dev_end_lba(): %llu\n",
2420                         cmd->t_task_lba, sectors,
2421                         transport_dev_end_lba(dev));
2422                 return -EINVAL;
2423         }
2424
2425         return 0;
2426 }
2427
2428 static int target_check_write_same_discard(unsigned char *flags, struct se_device *dev)
2429 {
2430         /*
2431          * Determine if the received WRITE_SAME is used to for direct
2432          * passthrough into Linux/SCSI with struct request via TCM/pSCSI
2433          * or we are signaling the use of internal WRITE_SAME + UNMAP=1
2434          * emulation for -> Linux/BLOCK disbard with TCM/IBLOCK code.
2435          */
2436         int passthrough = (dev->transport->transport_type ==
2437                                 TRANSPORT_PLUGIN_PHBA_PDEV);
2438
2439         if (!passthrough) {
2440                 if ((flags[0] & 0x04) || (flags[0] & 0x02)) {
2441                         pr_err("WRITE_SAME PBDATA and LBDATA"
2442                                 " bits not supported for Block Discard"
2443                                 " Emulation\n");
2444                         return -ENOSYS;
2445                 }
2446                 /*
2447                  * Currently for the emulated case we only accept
2448                  * tpws with the UNMAP=1 bit set.
2449                  */
2450                 if (!(flags[0] & 0x08)) {
2451                         pr_err("WRITE_SAME w/o UNMAP bit not"
2452                                 " supported for Block Discard Emulation\n");
2453                         return -ENOSYS;
2454                 }
2455         }
2456
2457         return 0;
2458 }
2459
2460 /*      transport_generic_cmd_sequencer():
2461  *
2462  *      Generic Command Sequencer that should work for most DAS transport
2463  *      drivers.
2464  *
2465  *      Called from transport_generic_allocate_tasks() in the $FABRIC_MOD
2466  *      RX Thread.
2467  *
2468  *      FIXME: Need to support other SCSI OPCODES where as well.
2469  */
2470 static int transport_generic_cmd_sequencer(
2471         struct se_cmd *cmd,
2472         unsigned char *cdb)
2473 {
2474         struct se_device *dev = cmd->se_dev;
2475         struct se_subsystem_dev *su_dev = dev->se_sub_dev;
2476         int ret = 0, sector_ret = 0, passthrough;
2477         u32 sectors = 0, size = 0, pr_reg_type = 0;
2478         u16 service_action;
2479         u8 alua_ascq = 0;
2480         /*
2481          * Check for an existing UNIT ATTENTION condition
2482          */
2483         if (core_scsi3_ua_check(cmd, cdb) < 0) {
2484                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2485                 cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
2486                 return -EINVAL;
2487         }
2488         /*
2489          * Check status of Asymmetric Logical Unit Assignment port
2490          */
2491         ret = su_dev->t10_alua.alua_state_check(cmd, cdb, &alua_ascq);
2492         if (ret != 0) {
2493                 /*
2494                  * Set SCSI additional sense code (ASC) to 'LUN Not Accessible';
2495                  * The ALUA additional sense code qualifier (ASCQ) is determined
2496                  * by the ALUA primary or secondary access state..
2497                  */
2498                 if (ret > 0) {
2499 #if 0
2500                         pr_debug("[%s]: ALUA TG Port not available,"
2501                                 " SenseKey: NOT_READY, ASC/ASCQ: 0x04/0x%02x\n",
2502                                 cmd->se_tfo->get_fabric_name(), alua_ascq);
2503 #endif
2504                         transport_set_sense_codes(cmd, 0x04, alua_ascq);
2505                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2506                         cmd->scsi_sense_reason = TCM_CHECK_CONDITION_NOT_READY;
2507                         return -EINVAL;
2508                 }
2509                 goto out_invalid_cdb_field;
2510         }
2511         /*
2512          * Check status for SPC-3 Persistent Reservations
2513          */
2514         if (su_dev->t10_pr.pr_ops.t10_reservation_check(cmd, &pr_reg_type) != 0) {
2515                 if (su_dev->t10_pr.pr_ops.t10_seq_non_holder(
2516                                         cmd, cdb, pr_reg_type) != 0) {
2517                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2518                         cmd->se_cmd_flags |= SCF_SCSI_RESERVATION_CONFLICT;
2519                         cmd->scsi_sense_reason = TCM_RESERVATION_CONFLICT;
2520                         return -EBUSY;
2521                 }
2522                 /*
2523                  * This means the CDB is allowed for the SCSI Initiator port
2524                  * when said port is *NOT* holding the legacy SPC-2 or
2525                  * SPC-3 Persistent Reservation.
2526                  */
2527         }
2528
2529         /*
2530          * If we operate in passthrough mode we skip most CDB emulation and
2531          * instead hand the commands down to the physical SCSI device.
2532          */
2533         passthrough =
2534                 (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV);
2535
2536         switch (cdb[0]) {
2537         case READ_6:
2538                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
2539                 if (sector_ret)
2540                         goto out_unsupported_cdb;
2541                 size = transport_get_size(sectors, cdb, cmd);
2542                 cmd->t_task_lba = transport_lba_21(cdb);
2543                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2544                 break;
2545         case READ_10:
2546                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2547                 if (sector_ret)
2548                         goto out_unsupported_cdb;
2549                 size = transport_get_size(sectors, cdb, cmd);
2550                 cmd->t_task_lba = transport_lba_32(cdb);
2551                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2552                 break;
2553         case READ_12:
2554                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
2555                 if (sector_ret)
2556                         goto out_unsupported_cdb;
2557                 size = transport_get_size(sectors, cdb, cmd);
2558                 cmd->t_task_lba = transport_lba_32(cdb);
2559                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2560                 break;
2561         case READ_16:
2562                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
2563                 if (sector_ret)
2564                         goto out_unsupported_cdb;
2565                 size = transport_get_size(sectors, cdb, cmd);
2566                 cmd->t_task_lba = transport_lba_64(cdb);
2567                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2568                 break;
2569         case WRITE_6:
2570                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
2571                 if (sector_ret)
2572                         goto out_unsupported_cdb;
2573                 size = transport_get_size(sectors, cdb, cmd);
2574                 cmd->t_task_lba = transport_lba_21(cdb);
2575                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2576                 break;
2577         case WRITE_10:
2578                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2579                 if (sector_ret)
2580                         goto out_unsupported_cdb;
2581                 size = transport_get_size(sectors, cdb, cmd);
2582                 cmd->t_task_lba = transport_lba_32(cdb);
2583                 cmd->t_tasks_fua = (cdb[1] & 0x8);
2584                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2585                 break;
2586         case WRITE_12:
2587                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
2588                 if (sector_ret)
2589                         goto out_unsupported_cdb;
2590                 size = transport_get_size(sectors, cdb, cmd);
2591                 cmd->t_task_lba = transport_lba_32(cdb);
2592                 cmd->t_tasks_fua = (cdb[1] & 0x8);
2593                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2594                 break;
2595         case WRITE_16:
2596                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
2597                 if (sector_ret)
2598                         goto out_unsupported_cdb;
2599                 size = transport_get_size(sectors, cdb, cmd);
2600                 cmd->t_task_lba = transport_lba_64(cdb);
2601                 cmd->t_tasks_fua = (cdb[1] & 0x8);
2602                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2603                 break;
2604         case XDWRITEREAD_10:
2605                 if ((cmd->data_direction != DMA_TO_DEVICE) ||
2606                     !(cmd->t_tasks_bidi))
2607                         goto out_invalid_cdb_field;
2608                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2609                 if (sector_ret)
2610                         goto out_unsupported_cdb;
2611                 size = transport_get_size(sectors, cdb, cmd);
2612                 cmd->t_task_lba = transport_lba_32(cdb);
2613                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2614
2615                 /*
2616                  * Do now allow BIDI commands for passthrough mode.
2617                  */
2618                 if (passthrough)
2619                         goto out_unsupported_cdb;
2620
2621                 /*
2622                  * Setup BIDI XOR callback to be run after I/O completion.
2623                  */
2624                 cmd->transport_complete_callback = &transport_xor_callback;
2625                 cmd->t_tasks_fua = (cdb[1] & 0x8);
2626                 break;
2627         case VARIABLE_LENGTH_CMD:
2628                 service_action = get_unaligned_be16(&cdb[8]);
2629                 switch (service_action) {
2630                 case XDWRITEREAD_32:
2631                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
2632                         if (sector_ret)
2633                                 goto out_unsupported_cdb;
2634                         size = transport_get_size(sectors, cdb, cmd);
2635                         /*
2636                          * Use WRITE_32 and READ_32 opcodes for the emulated
2637                          * XDWRITE_READ_32 logic.
2638                          */
2639                         cmd->t_task_lba = transport_lba_64_ext(cdb);
2640                         cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2641
2642                         /*
2643                          * Do now allow BIDI commands for passthrough mode.
2644                          */
2645                         if (passthrough)
2646                                 goto out_unsupported_cdb;
2647
2648                         /*
2649                          * Setup BIDI XOR callback to be run during after I/O
2650                          * completion.
2651                          */
2652                         cmd->transport_complete_callback = &transport_xor_callback;
2653                         cmd->t_tasks_fua = (cdb[10] & 0x8);
2654                         break;
2655                 case WRITE_SAME_32:
2656                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
2657                         if (sector_ret)
2658                                 goto out_unsupported_cdb;
2659
2660                         if (sectors)
2661                                 size = transport_get_size(1, cdb, cmd);
2662                         else {
2663                                 pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not"
2664                                        " supported\n");
2665                                 goto out_invalid_cdb_field;
2666                         }
2667
2668                         cmd->t_task_lba = get_unaligned_be64(&cdb[12]);
2669                         cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2670
2671                         if (target_check_write_same_discard(&cdb[10], dev) < 0)
2672                                 goto out_invalid_cdb_field;
2673                         if (!passthrough)
2674                                 cmd->execute_task = target_emulate_write_same;
2675                         break;
2676                 default:
2677                         pr_err("VARIABLE_LENGTH_CMD service action"
2678                                 " 0x%04x not supported\n", service_action);
2679                         goto out_unsupported_cdb;
2680                 }
2681                 break;
2682         case MAINTENANCE_IN:
2683                 if (dev->transport->get_device_type(dev) != TYPE_ROM) {
2684                         /* MAINTENANCE_IN from SCC-2 */
2685                         /*
2686                          * Check for emulated MI_REPORT_TARGET_PGS.
2687                          */
2688                         if (cdb[1] == MI_REPORT_TARGET_PGS &&
2689                             su_dev->t10_alua.alua_type == SPC3_ALUA_EMULATED) {
2690                                 cmd->execute_task =
2691                                         target_emulate_report_target_port_groups;
2692                         }
2693                         size = (cdb[6] << 24) | (cdb[7] << 16) |
2694                                (cdb[8] << 8) | cdb[9];
2695                 } else {
2696                         /* GPCMD_SEND_KEY from multi media commands */
2697                         size = (cdb[8] << 8) + cdb[9];
2698                 }
2699                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2700                 break;
2701         case MODE_SELECT:
2702                 size = cdb[4];
2703                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2704                 break;
2705         case MODE_SELECT_10:
2706                 size = (cdb[7] << 8) + cdb[8];
2707                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2708                 break;
2709         case MODE_SENSE:
2710                 size = cdb[4];
2711                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2712                 if (!passthrough)
2713                         cmd->execute_task = target_emulate_modesense;
2714                 break;
2715         case MODE_SENSE_10:
2716                 size = (cdb[7] << 8) + cdb[8];
2717                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2718                 if (!passthrough)
2719                         cmd->execute_task = target_emulate_modesense;
2720                 break;
2721         case GPCMD_READ_BUFFER_CAPACITY:
2722         case GPCMD_SEND_OPC:
2723         case LOG_SELECT:
2724         case LOG_SENSE:
2725                 size = (cdb[7] << 8) + cdb[8];
2726                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2727                 break;
2728         case READ_BLOCK_LIMITS:
2729                 size = READ_BLOCK_LEN;
2730                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2731                 break;
2732         case GPCMD_GET_CONFIGURATION:
2733         case GPCMD_READ_FORMAT_CAPACITIES:
2734         case GPCMD_READ_DISC_INFO:
2735         case GPCMD_READ_TRACK_RZONE_INFO:
2736                 size = (cdb[7] << 8) + cdb[8];
2737                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2738                 break;
2739         case PERSISTENT_RESERVE_IN:
2740                 if (su_dev->t10_pr.res_type == SPC3_PERSISTENT_RESERVATIONS)
2741                         cmd->execute_task = target_scsi3_emulate_pr_in;
2742                 size = (cdb[7] << 8) + cdb[8];
2743                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2744                 break;
2745         case PERSISTENT_RESERVE_OUT:
2746                 if (su_dev->t10_pr.res_type == SPC3_PERSISTENT_RESERVATIONS)
2747                         cmd->execute_task = target_scsi3_emulate_pr_out;
2748                 size = (cdb[7] << 8) + cdb[8];
2749                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2750                 break;
2751         case GPCMD_MECHANISM_STATUS:
2752         case GPCMD_READ_DVD_STRUCTURE:
2753                 size = (cdb[8] << 8) + cdb[9];
2754                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2755                 break;
2756         case READ_POSITION:
2757                 size = READ_POSITION_LEN;
2758                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2759                 break;
2760         case MAINTENANCE_OUT:
2761                 if (dev->transport->get_device_type(dev) != TYPE_ROM) {
2762                         /* MAINTENANCE_OUT from SCC-2
2763                          *
2764                          * Check for emulated MO_SET_TARGET_PGS.
2765                          */
2766                         if (cdb[1] == MO_SET_TARGET_PGS &&
2767                             su_dev->t10_alua.alua_type == SPC3_ALUA_EMULATED) {
2768                                 cmd->execute_task =
2769                                         target_emulate_set_target_port_groups;
2770                         }
2771
2772                         size = (cdb[6] << 24) | (cdb[7] << 16) |
2773                                (cdb[8] << 8) | cdb[9];
2774                 } else  {
2775                         /* GPCMD_REPORT_KEY from multi media commands */
2776                         size = (cdb[8] << 8) + cdb[9];
2777                 }
2778                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2779                 break;
2780         case INQUIRY:
2781                 size = (cdb[3] << 8) + cdb[4];
2782                 /*
2783                  * Do implict HEAD_OF_QUEUE processing for INQUIRY.
2784                  * See spc4r17 section 5.3
2785                  */
2786                 if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
2787                         cmd->sam_task_attr = MSG_HEAD_TAG;
2788                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2789                 if (!passthrough)
2790                         cmd->execute_task = target_emulate_inquiry;
2791                 break;
2792         case READ_BUFFER:
2793                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
2794                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2795                 break;
2796         case READ_CAPACITY:
2797                 size = READ_CAP_LEN;
2798                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2799                 if (!passthrough)
2800                         cmd->execute_task = target_emulate_readcapacity;
2801                 break;
2802         case READ_MEDIA_SERIAL_NUMBER:
2803         case SECURITY_PROTOCOL_IN:
2804         case SECURITY_PROTOCOL_OUT:
2805                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
2806                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2807                 break;
2808         case SERVICE_ACTION_IN:
2809                 switch (cmd->t_task_cdb[1] & 0x1f) {
2810                 case SAI_READ_CAPACITY_16:
2811                         if (!passthrough)
2812                                 cmd->execute_task =
2813                                         target_emulate_readcapacity_16;
2814                         break;
2815                 default:
2816                         if (passthrough)
2817                                 break;
2818
2819                         pr_err("Unsupported SA: 0x%02x\n",
2820                                 cmd->t_task_cdb[1] & 0x1f);
2821                         goto out_unsupported_cdb;
2822                 }
2823                 /*FALLTHROUGH*/
2824         case ACCESS_CONTROL_IN:
2825         case ACCESS_CONTROL_OUT:
2826         case EXTENDED_COPY:
2827         case READ_ATTRIBUTE:
2828         case RECEIVE_COPY_RESULTS:
2829         case WRITE_ATTRIBUTE:
2830                 size = (cdb[10] << 24) | (cdb[11] << 16) |
2831                        (cdb[12] << 8) | cdb[13];
2832                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2833                 break;
2834         case RECEIVE_DIAGNOSTIC:
2835         case SEND_DIAGNOSTIC:
2836                 size = (cdb[3] << 8) | cdb[4];
2837                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2838                 break;
2839 /* #warning FIXME: Figure out correct GPCMD_READ_CD blocksize. */
2840 #if 0
2841         case GPCMD_READ_CD:
2842                 sectors = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
2843                 size = (2336 * sectors);
2844                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2845                 break;
2846 #endif
2847         case READ_TOC:
2848                 size = cdb[8];
2849                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2850                 break;
2851         case REQUEST_SENSE:
2852                 size = cdb[4];
2853                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2854                 if (!passthrough)
2855                         cmd->execute_task = target_emulate_request_sense;
2856                 break;
2857         case READ_ELEMENT_STATUS:
2858                 size = 65536 * cdb[7] + 256 * cdb[8] + cdb[9];
2859                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2860                 break;
2861         case WRITE_BUFFER:
2862                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
2863                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2864                 break;
2865         case RESERVE:
2866         case RESERVE_10:
2867                 /*
2868                  * The SPC-2 RESERVE does not contain a size in the SCSI CDB.
2869                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
2870                  */
2871                 if (cdb[0] == RESERVE_10)
2872                         size = (cdb[7] << 8) | cdb[8];
2873                 else
2874                         size = cmd->data_length;
2875
2876                 /*
2877                  * Setup the legacy emulated handler for SPC-2 and
2878                  * >= SPC-3 compatible reservation handling (CRH=1)
2879                  * Otherwise, we assume the underlying SCSI logic is
2880                  * is running in SPC_PASSTHROUGH, and wants reservations
2881                  * emulation disabled.
2882                  */
2883                 if (su_dev->t10_pr.res_type != SPC_PASSTHROUGH)
2884                         cmd->execute_task = target_scsi2_reservation_reserve;
2885                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
2886                 break;
2887         case RELEASE:
2888         case RELEASE_10:
2889                 /*
2890                  * The SPC-2 RELEASE does not contain a size in the SCSI CDB.
2891                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
2892                 */
2893                 if (cdb[0] == RELEASE_10)
2894                         size = (cdb[7] << 8) | cdb[8];
2895                 else
2896                         size = cmd->data_length;
2897
2898                 if (su_dev->t10_pr.res_type != SPC_PASSTHROUGH)
2899                         cmd->execute_task = target_scsi2_reservation_release;
2900                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
2901                 break;
2902         case SYNCHRONIZE_CACHE:
2903         case 0x91: /* SYNCHRONIZE_CACHE_16: */
2904                 /*
2905                  * Extract LBA and range to be flushed for emulated SYNCHRONIZE_CACHE
2906                  */
2907                 if (cdb[0] == SYNCHRONIZE_CACHE) {
2908                         sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2909                         cmd->t_task_lba = transport_lba_32(cdb);
2910                 } else {
2911                         sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
2912                         cmd->t_task_lba = transport_lba_64(cdb);
2913                 }
2914                 if (sector_ret)
2915                         goto out_unsupported_cdb;
2916
2917                 size = transport_get_size(sectors, cdb, cmd);
2918                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
2919
2920                 if (passthrough)
2921                         break;
2922
2923                 /*
2924                  * Check to ensure that LBA + Range does not exceed past end of
2925                  * device for IBLOCK and FILEIO ->do_sync_cache() backend calls
2926                  */
2927                 if ((cmd->t_task_lba != 0) || (sectors != 0)) {
2928                         if (transport_cmd_get_valid_sectors(cmd) < 0)
2929                                 goto out_invalid_cdb_field;
2930                 }
2931                 cmd->execute_task = target_emulate_synchronize_cache;
2932                 break;
2933         case UNMAP:
2934                 size = get_unaligned_be16(&cdb[7]);
2935                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2936                 if (!passthrough)
2937                         cmd->execute_task = target_emulate_unmap;
2938                 break;
2939         case WRITE_SAME_16:
2940                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
2941                 if (sector_ret)
2942                         goto out_unsupported_cdb;
2943
2944                 if (sectors)
2945                         size = transport_get_size(1, cdb, cmd);
2946                 else {
2947                         pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not supported\n");
2948                         goto out_invalid_cdb_field;
2949                 }
2950
2951                 cmd->t_task_lba = get_unaligned_be64(&cdb[2]);
2952                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2953
2954                 if (target_check_write_same_discard(&cdb[1], dev) < 0)
2955                         goto out_invalid_cdb_field;
2956                 if (!passthrough)
2957                         cmd->execute_task = target_emulate_write_same;
2958                 break;
2959         case WRITE_SAME:
2960                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2961                 if (sector_ret)
2962                         goto out_unsupported_cdb;
2963
2964                 if (sectors)
2965                         size = transport_get_size(1, cdb, cmd);
2966                 else {
2967                         pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not supported\n");
2968                         goto out_invalid_cdb_field;
2969                 }
2970
2971                 cmd->t_task_lba = get_unaligned_be32(&cdb[2]);
2972                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2973                 /*
2974                  * Follow sbcr26 with WRITE_SAME (10) and check for the existence
2975                  * of byte 1 bit 3 UNMAP instead of original reserved field
2976                  */
2977                 if (target_check_write_same_discard(&cdb[1], dev) < 0)
2978                         goto out_invalid_cdb_field;
2979                 if (!passthrough)
2980                         cmd->execute_task = target_emulate_write_same;
2981                 break;
2982         case ALLOW_MEDIUM_REMOVAL:
2983         case ERASE:
2984         case REZERO_UNIT:
2985         case SEEK_10:
2986         case SPACE:
2987         case START_STOP:
2988         case TEST_UNIT_READY:
2989         case VERIFY:
2990         case WRITE_FILEMARKS:
2991                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
2992                 if (!passthrough)
2993                         cmd->execute_task = target_emulate_noop;
2994                 break;
2995         case GPCMD_CLOSE_TRACK:
2996         case INITIALIZE_ELEMENT_STATUS:
2997         case GPCMD_LOAD_UNLOAD:
2998         case GPCMD_SET_SPEED:
2999         case MOVE_MEDIUM:
3000                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3001                 break;
3002         case REPORT_LUNS:
3003                 cmd->execute_task = target_report_luns;
3004                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
3005                 /*
3006                  * Do implict HEAD_OF_QUEUE processing for REPORT_LUNS
3007                  * See spc4r17 section 5.3
3008                  */
3009                 if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3010                         cmd->sam_task_attr = MSG_HEAD_TAG;
3011                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3012                 break;
3013         default:
3014                 pr_warn("TARGET_CORE[%s]: Unsupported SCSI Opcode"
3015                         " 0x%02x, sending CHECK_CONDITION.\n",
3016                         cmd->se_tfo->get_fabric_name(), cdb[0]);
3017                 goto out_unsupported_cdb;
3018         }
3019
3020         if (size != cmd->data_length) {
3021                 pr_warn("TARGET_CORE[%s]: Expected Transfer Length:"
3022                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
3023                         " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
3024                                 cmd->data_length, size, cdb[0]);
3025
3026                 cmd->cmd_spdtl = size;
3027
3028                 if (cmd->data_direction == DMA_TO_DEVICE) {
3029                         pr_err("Rejecting underflow/overflow"
3030                                         " WRITE data\n");
3031                         goto out_invalid_cdb_field;
3032                 }
3033                 /*
3034                  * Reject READ_* or WRITE_* with overflow/underflow for
3035                  * type SCF_SCSI_DATA_SG_IO_CDB.
3036                  */
3037                 if (!ret && (dev->se_sub_dev->se_dev_attrib.block_size != 512))  {
3038                         pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
3039                                 " CDB on non 512-byte sector setup subsystem"
3040                                 " plugin: %s\n", dev->transport->name);
3041                         /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
3042                         goto out_invalid_cdb_field;
3043                 }
3044
3045                 if (size > cmd->data_length) {
3046                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
3047                         cmd->residual_count = (size - cmd->data_length);
3048                 } else {
3049                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
3050                         cmd->residual_count = (cmd->data_length - size);
3051                 }
3052                 cmd->data_length = size;
3053         }
3054
3055         /* reject any command that we don't have a handler for */
3056         if (!(passthrough || cmd->execute_task ||
3057              (cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB)))
3058                 goto out_unsupported_cdb;
3059
3060         /* Let's limit control cdbs to a page, for simplicity's sake. */
3061         if ((cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB) &&
3062             size > PAGE_SIZE)
3063                 goto out_invalid_cdb_field;
3064
3065         transport_set_supported_SAM_opcode(cmd);
3066         return ret;
3067
3068 out_unsupported_cdb:
3069         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3070         cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
3071         return -EINVAL;
3072 out_invalid_cdb_field:
3073         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3074         cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
3075         return -EINVAL;
3076 }
3077
3078 /*
3079  * Called from I/O completion to determine which dormant/delayed
3080  * and ordered cmds need to have their tasks added to the execution queue.
3081  */
3082 static void transport_complete_task_attr(struct se_cmd *cmd)
3083 {
3084         struct se_device *dev = cmd->se_dev;
3085         struct se_cmd *cmd_p, *cmd_tmp;
3086         int new_active_tasks = 0;
3087
3088         if (cmd->sam_task_attr == MSG_SIMPLE_TAG) {
3089                 atomic_dec(&dev->simple_cmds);
3090                 smp_mb__after_atomic_dec();
3091                 dev->dev_cur_ordered_id++;
3092                 pr_debug("Incremented dev->dev_cur_ordered_id: %u for"
3093                         " SIMPLE: %u\n", dev->dev_cur_ordered_id,
3094                         cmd->se_ordered_id);
3095         } else if (cmd->sam_task_attr == MSG_HEAD_TAG) {
3096                 atomic_dec(&dev->dev_hoq_count);
3097                 smp_mb__after_atomic_dec();
3098                 dev->dev_cur_ordered_id++;
3099                 pr_debug("Incremented dev_cur_ordered_id: %u for"
3100                         " HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id,
3101                         cmd->se_ordered_id);
3102         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
3103                 spin_lock(&dev->ordered_cmd_lock);
3104                 list_del(&cmd->se_ordered_node);
3105                 atomic_dec(&dev->dev_ordered_sync);
3106                 smp_mb__after_atomic_dec();
3107                 spin_unlock(&dev->ordered_cmd_lock);
3108
3109                 dev->dev_cur_ordered_id++;
3110                 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED:"
3111                         " %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id);
3112         }
3113         /*
3114          * Process all commands up to the last received
3115          * ORDERED task attribute which requires another blocking
3116          * boundary
3117          */
3118         spin_lock(&dev->delayed_cmd_lock);
3119         list_for_each_entry_safe(cmd_p, cmd_tmp,
3120                         &dev->delayed_cmd_list, se_delayed_node) {
3121
3122                 list_del(&cmd_p->se_delayed_node);
3123                 spin_unlock(&dev->delayed_cmd_lock);
3124
3125                 pr_debug("Calling add_tasks() for"
3126                         " cmd_p: 0x%02x Task Attr: 0x%02x"
3127                         " Dormant -> Active, se_ordered_id: %u\n",
3128                         cmd_p->t_task_cdb[0],
3129                         cmd_p->sam_task_attr, cmd_p->se_ordered_id);
3130
3131                 transport_add_tasks_from_cmd(cmd_p);
3132                 new_active_tasks++;
3133
3134                 spin_lock(&dev->delayed_cmd_lock);
3135                 if (cmd_p->sam_task_attr == MSG_ORDERED_TAG)
3136                         break;
3137         }
3138         spin_unlock(&dev->delayed_cmd_lock);
3139         /*
3140          * If new tasks have become active, wake up the transport thread
3141          * to do the processing of the Active tasks.
3142          */
3143         if (new_active_tasks != 0)
3144                 wake_up_interruptible(&dev->dev_queue_obj.thread_wq);
3145 }
3146
3147 static void transport_complete_qf(struct se_cmd *cmd)
3148 {
3149         int ret = 0;
3150
3151         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3152                 transport_complete_task_attr(cmd);
3153
3154         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
3155                 ret = cmd->se_tfo->queue_status(cmd);
3156                 if (ret)
3157                         goto out;
3158         }
3159
3160         switch (cmd->data_direction) {
3161         case DMA_FROM_DEVICE:
3162                 ret = cmd->se_tfo->queue_data_in(cmd);
3163                 break;
3164         case DMA_TO_DEVICE:
3165                 if (cmd->t_bidi_data_sg) {
3166                         ret = cmd->se_tfo->queue_data_in(cmd);
3167                         if (ret < 0)
3168                                 break;
3169                 }
3170                 /* Fall through for DMA_TO_DEVICE */
3171         case DMA_NONE:
3172                 ret = cmd->se_tfo->queue_status(cmd);
3173                 break;
3174         default:
3175                 break;
3176         }
3177
3178 out:
3179         if (ret < 0) {
3180                 transport_handle_queue_full(cmd, cmd->se_dev);
3181                 return;
3182         }
3183         transport_lun_remove_cmd(cmd);
3184         transport_cmd_check_stop_to_fabric(cmd);
3185 }
3186
3187 static void transport_handle_queue_full(
3188         struct se_cmd *cmd,
3189         struct se_device *dev)
3190 {
3191         spin_lock_irq(&dev->qf_cmd_lock);
3192         list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
3193         atomic_inc(&dev->dev_qf_count);
3194         smp_mb__after_atomic_inc();
3195         spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
3196
3197         schedule_work(&cmd->se_dev->qf_work_queue);
3198 }
3199
3200 static void target_complete_ok_work(struct work_struct *work)
3201 {
3202         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3203         int reason = 0, ret;
3204
3205         /*
3206          * Check if we need to move delayed/dormant tasks from cmds on the
3207          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
3208          * Attribute.
3209          */
3210         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3211                 transport_complete_task_attr(cmd);
3212         /*
3213          * Check to schedule QUEUE_FULL work, or execute an existing
3214          * cmd->transport_qf_callback()
3215          */
3216         if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
3217                 schedule_work(&cmd->se_dev->qf_work_queue);
3218
3219         /*
3220          * Check if we need to retrieve a sense buffer from
3221          * the struct se_cmd in question.
3222          */
3223         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
3224                 if (transport_get_sense_data(cmd) < 0)
3225                         reason = TCM_NON_EXISTENT_LUN;
3226
3227                 /*
3228                  * Only set when an struct se_task->task_scsi_status returned
3229                  * a non GOOD status.
3230                  */
3231                 if (cmd->scsi_status) {
3232                         ret = transport_send_check_condition_and_sense(
3233                                         cmd, reason, 1);
3234                         if (ret == -EAGAIN || ret == -ENOMEM)
3235                                 goto queue_full;
3236
3237                         transport_lun_remove_cmd(cmd);
3238                         transport_cmd_check_stop_to_fabric(cmd);
3239                         return;
3240                 }
3241         }
3242         /*
3243          * Check for a callback, used by amongst other things
3244          * XDWRITE_READ_10 emulation.
3245          */
3246         if (cmd->transport_complete_callback)
3247                 cmd->transport_complete_callback(cmd);
3248
3249         switch (cmd->data_direction) {
3250         case DMA_FROM_DEVICE:
3251                 spin_lock(&cmd->se_lun->lun_sep_lock);
3252                 if (cmd->se_lun->lun_sep) {
3253                         cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
3254                                         cmd->data_length;
3255                 }
3256                 spin_unlock(&cmd->se_lun->lun_sep_lock);
3257
3258                 ret = cmd->se_tfo->queue_data_in(cmd);
3259                 if (ret == -EAGAIN || ret == -ENOMEM)
3260                         goto queue_full;
3261                 break;
3262         case DMA_TO_DEVICE:
3263                 spin_lock(&cmd->se_lun->lun_sep_lock);
3264                 if (cmd->se_lun->lun_sep) {
3265                         cmd->se_lun->lun_sep->sep_stats.rx_data_octets +=
3266                                 cmd->data_length;
3267                 }
3268                 spin_unlock(&cmd->se_lun->lun_sep_lock);
3269                 /*
3270                  * Check if we need to send READ payload for BIDI-COMMAND
3271                  */
3272                 if (cmd->t_bidi_data_sg) {
3273                         spin_lock(&cmd->se_lun->lun_sep_lock);
3274                         if (cmd->se_lun->lun_sep) {
3275                                 cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
3276                                         cmd->data_length;
3277                         }
3278                         spin_unlock(&cmd->se_lun->lun_sep_lock);
3279                         ret = cmd->se_tfo->queue_data_in(cmd);
3280                         if (ret == -EAGAIN || ret == -ENOMEM)
3281                                 goto queue_full;
3282                         break;
3283                 }
3284                 /* Fall through for DMA_TO_DEVICE */
3285         case DMA_NONE:
3286                 ret = cmd->se_tfo->queue_status(cmd);
3287                 if (ret == -EAGAIN || ret == -ENOMEM)
3288                         goto queue_full;
3289                 break;
3290         default:
3291                 break;
3292         }
3293
3294         transport_lun_remove_cmd(cmd);
3295         transport_cmd_check_stop_to_fabric(cmd);
3296         return;
3297
3298 queue_full:
3299         pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
3300                 " data_direction: %d\n", cmd, cmd->data_direction);
3301         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
3302         transport_handle_queue_full(cmd, cmd->se_dev);
3303 }
3304
3305 static void transport_free_dev_tasks(struct se_cmd *cmd)
3306 {
3307         struct se_task *task, *task_tmp;
3308         unsigned long flags;
3309         LIST_HEAD(dispose_list);
3310
3311         spin_lock_irqsave(&cmd->t_state_lock, flags);
3312         list_for_each_entry_safe(task, task_tmp,
3313                                 &cmd->t_task_list, t_list) {
3314                 if (!(task->task_flags & TF_ACTIVE))
3315                         list_move_tail(&task->t_list, &dispose_list);
3316         }
3317         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3318
3319         while (!list_empty(&dispose_list)) {
3320                 task = list_first_entry(&dispose_list, struct se_task, t_list);
3321
3322                 if (task->task_sg != cmd->t_data_sg &&
3323                     task->task_sg != cmd->t_bidi_data_sg)
3324                         kfree(task->task_sg);
3325
3326                 list_del(&task->t_list);
3327
3328                 cmd->se_dev->transport->free_task(task);
3329         }
3330 }
3331
3332 static inline void transport_free_sgl(struct scatterlist *sgl, int nents)
3333 {
3334         struct scatterlist *sg;
3335         int count;
3336
3337         for_each_sg(sgl, sg, nents, count)
3338                 __free_page(sg_page(sg));
3339
3340         kfree(sgl);
3341 }
3342
3343 static inline void transport_free_pages(struct se_cmd *cmd)
3344 {
3345         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)
3346                 return;
3347
3348         transport_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
3349         cmd->t_data_sg = NULL;
3350         cmd->t_data_nents = 0;
3351
3352         transport_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
3353         cmd->t_bidi_data_sg = NULL;
3354         cmd->t_bidi_data_nents = 0;
3355 }
3356
3357 /**
3358  * transport_put_cmd - release a reference to a command
3359  * @cmd:       command to release
3360  *
3361  * This routine releases our reference to the command and frees it if possible.
3362  */
3363 static void transport_put_cmd(struct se_cmd *cmd)
3364 {
3365         unsigned long flags;
3366         int free_tasks = 0;
3367
3368         spin_lock_irqsave(&cmd->t_state_lock, flags);
3369         if (atomic_read(&cmd->t_fe_count)) {
3370                 if (!atomic_dec_and_test(&cmd->t_fe_count))
3371                         goto out_busy;
3372         }
3373
3374         if (atomic_read(&cmd->t_se_count)) {
3375                 if (!atomic_dec_and_test(&cmd->t_se_count))
3376                         goto out_busy;
3377         }
3378
3379         if (atomic_read(&cmd->transport_dev_active)) {
3380                 atomic_set(&cmd->transport_dev_active, 0);
3381                 transport_all_task_dev_remove_state(cmd);
3382                 free_tasks = 1;
3383         }
3384         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3385
3386         if (free_tasks != 0)
3387                 transport_free_dev_tasks(cmd);
3388
3389         transport_free_pages(cmd);
3390         transport_release_cmd(cmd);
3391         return;
3392 out_busy:
3393         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3394 }
3395
3396 /*
3397  * transport_generic_map_mem_to_cmd - Use fabric-alloced pages instead of
3398  * allocating in the core.
3399  * @cmd:  Associated se_cmd descriptor
3400  * @mem:  SGL style memory for TCM WRITE / READ
3401  * @sg_mem_num: Number of SGL elements
3402  * @mem_bidi_in: SGL style memory for TCM BIDI READ
3403  * @sg_mem_bidi_num: Number of BIDI READ SGL elements
3404  *
3405  * Return: nonzero return cmd was rejected for -ENOMEM or inproper usage
3406  * of parameters.
3407  */
3408 int transport_generic_map_mem_to_cmd(
3409         struct se_cmd *cmd,
3410         struct scatterlist *sgl,
3411         u32 sgl_count,
3412         struct scatterlist *sgl_bidi,
3413         u32 sgl_bidi_count)
3414 {
3415         if (!sgl || !sgl_count)
3416                 return 0;
3417
3418         if ((cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) ||
3419             (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB)) {
3420
3421                 cmd->t_data_sg = sgl;
3422                 cmd->t_data_nents = sgl_count;
3423
3424                 if (sgl_bidi && sgl_bidi_count) {
3425                         cmd->t_bidi_data_sg = sgl_bidi;
3426                         cmd->t_bidi_data_nents = sgl_bidi_count;
3427                 }
3428                 cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
3429         }
3430
3431         return 0;
3432 }
3433 EXPORT_SYMBOL(transport_generic_map_mem_to_cmd);
3434
3435 void *transport_kmap_first_data_page(struct se_cmd *cmd)
3436 {
3437         struct scatterlist *sg = cmd->t_data_sg;
3438
3439         BUG_ON(!sg);
3440         /*
3441          * We need to take into account a possible offset here for fabrics like
3442          * tcm_loop who may be using a contig buffer from the SCSI midlayer for
3443          * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
3444          */
3445         return kmap(sg_page(sg)) + sg->offset;
3446 }
3447 EXPORT_SYMBOL(transport_kmap_first_data_page);
3448
3449 void transport_kunmap_first_data_page(struct se_cmd *cmd)
3450 {
3451         kunmap(sg_page(cmd->t_data_sg));
3452 }
3453 EXPORT_SYMBOL(transport_kunmap_first_data_page);
3454
3455 static int
3456 transport_generic_get_mem(struct se_cmd *cmd)
3457 {
3458         u32 length = cmd->data_length;
3459         unsigned int nents;
3460         struct page *page;
3461         int i = 0;
3462
3463         nents = DIV_ROUND_UP(length, PAGE_SIZE);
3464         cmd->t_data_sg = kmalloc(sizeof(struct scatterlist) * nents, GFP_KERNEL);
3465         if (!cmd->t_data_sg)
3466                 return -ENOMEM;
3467
3468         cmd->t_data_nents = nents;
3469         sg_init_table(cmd->t_data_sg, nents);
3470
3471         while (length) {
3472                 u32 page_len = min_t(u32, length, PAGE_SIZE);
3473                 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3474                 if (!page)
3475                         goto out;
3476
3477                 sg_set_page(&cmd->t_data_sg[i], page, page_len, 0);
3478                 length -= page_len;
3479                 i++;
3480         }
3481         return 0;
3482
3483 out:
3484         while (i >= 0) {
3485                 __free_page(sg_page(&cmd->t_data_sg[i]));
3486                 i--;
3487         }
3488         kfree(cmd->t_data_sg);
3489         cmd->t_data_sg = NULL;
3490         return -ENOMEM;
3491 }
3492
3493 /* Reduce sectors if they are too long for the device */
3494 static inline sector_t transport_limit_task_sectors(
3495         struct se_device *dev,
3496         unsigned long long lba,
3497         sector_t sectors)
3498 {
3499         sectors = min_t(sector_t, sectors, dev->se_sub_dev->se_dev_attrib.max_sectors);
3500
3501         if (dev->transport->get_device_type(dev) == TYPE_DISK)
3502                 if ((lba + sectors) > transport_dev_end_lba(dev))
3503                         sectors = ((transport_dev_end_lba(dev) - lba) + 1);
3504
3505         return sectors;
3506 }
3507
3508
3509 /*
3510  * This function can be used by HW target mode drivers to create a linked
3511  * scatterlist from all contiguously allocated struct se_task->task_sg[].
3512  * This is intended to be called during the completion path by TCM Core
3513  * when struct target_core_fabric_ops->check_task_sg_chaining is enabled.
3514  */
3515 void transport_do_task_sg_chain(struct se_cmd *cmd)
3516 {
3517         struct scatterlist *sg_first = NULL;
3518         struct scatterlist *sg_prev = NULL;
3519         int sg_prev_nents = 0;
3520         struct scatterlist *sg;
3521         struct se_task *task;
3522         u32 chained_nents = 0;
3523         int i;
3524
3525         BUG_ON(!cmd->se_tfo->task_sg_chaining);
3526
3527         /*
3528          * Walk the struct se_task list and setup scatterlist chains
3529          * for each contiguously allocated struct se_task->task_sg[].
3530          */
3531         list_for_each_entry(task, &cmd->t_task_list, t_list) {
3532                 if (!task->task_sg)
3533                         continue;
3534
3535                 if (!sg_first) {
3536                         sg_first = task->task_sg;
3537                         chained_nents = task->task_sg_nents;
3538                 } else {
3539                         sg_chain(sg_prev, sg_prev_nents, task->task_sg);
3540                         chained_nents += task->task_sg_nents;
3541                 }
3542                 /*
3543                  * For the padded tasks, use the extra SGL vector allocated
3544                  * in transport_allocate_data_tasks() for the sg_prev_nents
3545                  * offset into sg_chain() above.
3546                  *
3547                  * We do not need the padding for the last task (or a single
3548                  * task), but in that case we will never use the sg_prev_nents
3549                  * value below which would be incorrect.
3550                  */
3551                 sg_prev_nents = (task->task_sg_nents + 1);
3552                 sg_prev = task->task_sg;
3553         }
3554         /*
3555          * Setup the starting pointer and total t_tasks_sg_linked_no including
3556          * padding SGs for linking and to mark the end.
3557          */
3558         cmd->t_tasks_sg_chained = sg_first;
3559         cmd->t_tasks_sg_chained_no = chained_nents;
3560
3561         pr_debug("Setup cmd: %p cmd->t_tasks_sg_chained: %p and"
3562                 " t_tasks_sg_chained_no: %u\n", cmd, cmd->t_tasks_sg_chained,
3563                 cmd->t_tasks_sg_chained_no);
3564
3565         for_each_sg(cmd->t_tasks_sg_chained, sg,
3566                         cmd->t_tasks_sg_chained_no, i) {
3567
3568                 pr_debug("SG[%d]: %p page: %p length: %d offset: %d\n",
3569                         i, sg, sg_page(sg), sg->length, sg->offset);
3570                 if (sg_is_chain(sg))
3571                         pr_debug("SG: %p sg_is_chain=1\n", sg);
3572                 if (sg_is_last(sg))
3573                         pr_debug("SG: %p sg_is_last=1\n", sg);
3574         }
3575 }
3576 EXPORT_SYMBOL(transport_do_task_sg_chain);
3577
3578 /*
3579  * Break up cmd into chunks transport can handle
3580  */
3581 static int
3582 transport_allocate_data_tasks(struct se_cmd *cmd,
3583         enum dma_data_direction data_direction,
3584         struct scatterlist *cmd_sg, unsigned int sgl_nents)
3585 {
3586         struct se_device *dev = cmd->se_dev;
3587         int task_count, i;
3588         unsigned long long lba;
3589         sector_t sectors, dev_max_sectors;
3590         u32 sector_size;
3591
3592         if (transport_cmd_get_valid_sectors(cmd) < 0)
3593                 return -EINVAL;
3594
3595         dev_max_sectors = dev->se_sub_dev->se_dev_attrib.max_sectors;
3596         sector_size = dev->se_sub_dev->se_dev_attrib.block_size;
3597
3598         WARN_ON(cmd->data_length % sector_size);
3599
3600         lba = cmd->t_task_lba;
3601         sectors = DIV_ROUND_UP(cmd->data_length, sector_size);
3602         task_count = DIV_ROUND_UP_SECTOR_T(sectors, dev_max_sectors);
3603
3604         /*
3605          * If we need just a single task reuse the SG list in the command
3606          * and avoid a lot of work.
3607          */
3608         if (task_count == 1) {
3609                 struct se_task *task;
3610                 unsigned long flags;
3611
3612                 task = transport_generic_get_task(cmd, data_direction);
3613                 if (!task)
3614                         return -ENOMEM;
3615
3616                 task->task_sg = cmd_sg;
3617                 task->task_sg_nents = sgl_nents;
3618
3619                 task->task_lba = lba;
3620                 task->task_sectors = sectors;
3621                 task->task_size = task->task_sectors * sector_size;
3622
3623                 spin_lock_irqsave(&cmd->t_state_lock, flags);
3624                 list_add_tail(&task->t_list, &cmd->t_task_list);
3625                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3626
3627                 return task_count;
3628         }
3629
3630         for (i = 0; i < task_count; i++) {
3631                 struct se_task *task;
3632                 unsigned int task_size, task_sg_nents_padded;
3633                 struct scatterlist *sg;
3634                 unsigned long flags;
3635                 int count;
3636
3637                 task = transport_generic_get_task(cmd, data_direction);
3638                 if (!task)
3639                         return -ENOMEM;
3640
3641                 task->task_lba = lba;
3642                 task->task_sectors = min(sectors, dev_max_sectors);
3643                 task->task_size = task->task_sectors * sector_size;
3644
3645                 /*
3646                  * This now assumes that passed sg_ents are in PAGE_SIZE chunks
3647                  * in order to calculate the number per task SGL entries
3648                  */
3649                 task->task_sg_nents = DIV_ROUND_UP(task->task_size, PAGE_SIZE);
3650                 /*
3651                  * Check if the fabric module driver is requesting that all
3652                  * struct se_task->task_sg[] be chained together..  If so,
3653                  * then allocate an extra padding SG entry for linking and
3654                  * marking the end of the chained SGL for every task except
3655                  * the last one for (task_count > 1) operation, or skipping
3656                  * the extra padding for the (task_count == 1) case.
3657                  */
3658                 if (cmd->se_tfo->task_sg_chaining && (i < (task_count - 1))) {
3659                         task_sg_nents_padded = (task->task_sg_nents + 1);
3660                 } else
3661                         task_sg_nents_padded = task->task_sg_nents;
3662
3663                 task->task_sg = kmalloc(sizeof(struct scatterlist) *
3664                                         task_sg_nents_padded, GFP_KERNEL);
3665                 if (!task->task_sg) {
3666                         cmd->se_dev->transport->free_task(task);
3667                         return -ENOMEM;
3668                 }
3669
3670                 sg_init_table(task->task_sg, task_sg_nents_padded);
3671
3672                 task_size = task->task_size;
3673
3674                 /* Build new sgl, only up to task_size */
3675                 for_each_sg(task->task_sg, sg, task->task_sg_nents, count) {
3676                         if (cmd_sg->length > task_size)
3677                                 break;
3678
3679                         *sg = *cmd_sg;
3680                         task_size -= cmd_sg->length;
3681                         cmd_sg = sg_next(cmd_sg);
3682                 }
3683
3684                 lba += task->task_sectors;
3685                 sectors -= task->task_sectors;
3686
3687                 spin_lock_irqsave(&cmd->t_state_lock, flags);
3688                 list_add_tail(&task->t_list, &cmd->t_task_list);
3689                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3690         }
3691
3692         return task_count;
3693 }
3694
3695 static int
3696 transport_allocate_control_task(struct se_cmd *cmd)
3697 {
3698         struct se_task *task;
3699         unsigned long flags;
3700
3701         task = transport_generic_get_task(cmd, cmd->data_direction);
3702         if (!task)
3703                 return -ENOMEM;
3704
3705         task->task_sg = cmd->t_data_sg;
3706         task->task_size = cmd->data_length;
3707         task->task_sg_nents = cmd->t_data_nents;
3708
3709         spin_lock_irqsave(&cmd->t_state_lock, flags);
3710         list_add_tail(&task->t_list, &cmd->t_task_list);
3711         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3712
3713         /* Success! Return number of tasks allocated */
3714         return 1;
3715 }
3716
3717 /*
3718  * Allocate any required ressources to execute the command, and either place
3719  * it on the execution queue if possible.  For writes we might not have the
3720  * payload yet, thus notify the fabric via a call to ->write_pending instead.
3721  */
3722 int transport_generic_new_cmd(struct se_cmd *cmd)
3723 {
3724         struct se_device *dev = cmd->se_dev;
3725         int task_cdbs, task_cdbs_bidi = 0;
3726         int set_counts = 1;
3727         int ret = 0;
3728
3729         /*
3730          * Determine is the TCM fabric module has already allocated physical
3731          * memory, and is directly calling transport_generic_map_mem_to_cmd()
3732          * beforehand.
3733          */
3734         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
3735             cmd->data_length) {
3736                 ret = transport_generic_get_mem(cmd);
3737                 if (ret < 0)
3738                         goto out_fail;
3739         }
3740
3741         /*
3742          * For BIDI command set up the read tasks first.
3743          */
3744         if (cmd->t_bidi_data_sg &&
3745             dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
3746                 BUG_ON(!(cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB));
3747
3748                 task_cdbs_bidi = transport_allocate_data_tasks(cmd,
3749                                 DMA_FROM_DEVICE, cmd->t_bidi_data_sg,
3750                                 cmd->t_bidi_data_nents);
3751                 if (task_cdbs_bidi <= 0)
3752                         goto out_fail;
3753
3754                 atomic_inc(&cmd->t_fe_count);
3755                 atomic_inc(&cmd->t_se_count);
3756                 set_counts = 0;
3757         }
3758
3759         if (cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) {
3760                 task_cdbs = transport_allocate_data_tasks(cmd,
3761                                         cmd->data_direction, cmd->t_data_sg,
3762                                         cmd->t_data_nents);
3763         } else {
3764                 task_cdbs = transport_allocate_control_task(cmd);
3765         }
3766
3767         if (task_cdbs <= 0)
3768                 goto out_fail;
3769
3770         if (set_counts) {
3771                 atomic_inc(&cmd->t_fe_count);
3772                 atomic_inc(&cmd->t_se_count);
3773         }
3774
3775         cmd->t_task_list_num = (task_cdbs + task_cdbs_bidi);
3776         atomic_set(&cmd->t_task_cdbs_left, cmd->t_task_list_num);
3777         atomic_set(&cmd->t_task_cdbs_ex_left, cmd->t_task_list_num);
3778
3779         /*
3780          * For WRITEs, let the fabric know its buffer is ready..
3781          * This WRITE struct se_cmd (and all of its associated struct se_task's)
3782          * will be added to the struct se_device execution queue after its WRITE
3783          * data has arrived. (ie: It gets handled by the transport processing
3784          * thread a second time)
3785          */
3786         if (cmd->data_direction == DMA_TO_DEVICE) {
3787                 transport_add_tasks_to_state_queue(cmd);
3788                 return transport_generic_write_pending(cmd);
3789         }
3790         /*
3791          * Everything else but a WRITE, add the struct se_cmd's struct se_task's
3792          * to the execution queue.
3793          */
3794         transport_execute_tasks(cmd);
3795         return 0;
3796
3797 out_fail:
3798         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3799         cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3800         return -EINVAL;
3801 }
3802 EXPORT_SYMBOL(transport_generic_new_cmd);
3803
3804 /*      transport_generic_process_write():
3805  *
3806  *
3807  */
3808 void transport_generic_process_write(struct se_cmd *cmd)
3809 {
3810         transport_execute_tasks(cmd);
3811 }
3812 EXPORT_SYMBOL(transport_generic_process_write);
3813
3814 static void transport_write_pending_qf(struct se_cmd *cmd)
3815 {
3816         int ret;
3817
3818         ret = cmd->se_tfo->write_pending(cmd);
3819         if (ret == -EAGAIN || ret == -ENOMEM) {
3820                 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
3821                          cmd);
3822                 transport_handle_queue_full(cmd, cmd->se_dev);
3823         }
3824 }
3825
3826 static int transport_generic_write_pending(struct se_cmd *cmd)
3827 {
3828         unsigned long flags;
3829         int ret;
3830
3831         spin_lock_irqsave(&cmd->t_state_lock, flags);
3832         cmd->t_state = TRANSPORT_WRITE_PENDING;
3833         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3834
3835         /*
3836          * Clear the se_cmd for WRITE_PENDING status in order to set
3837          * cmd->t_transport_active=0 so that transport_generic_handle_data
3838          * can be called from HW target mode interrupt code.  This is safe
3839          * to be called with transport_off=1 before the cmd->se_tfo->write_pending
3840          * because the se_cmd->se_lun pointer is not being cleared.
3841          */
3842         transport_cmd_check_stop(cmd, 1, 0);
3843
3844         /*
3845          * Call the fabric write_pending function here to let the
3846          * frontend know that WRITE buffers are ready.
3847          */
3848         ret = cmd->se_tfo->write_pending(cmd);
3849         if (ret == -EAGAIN || ret == -ENOMEM)
3850                 goto queue_full;
3851         else if (ret < 0)
3852                 return ret;
3853
3854         return 1;
3855
3856 queue_full:
3857         pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
3858         cmd->t_state = TRANSPORT_COMPLETE_QF_WP;
3859         transport_handle_queue_full(cmd, cmd->se_dev);
3860         return 0;
3861 }
3862
3863 /**
3864  * transport_release_cmd - free a command
3865  * @cmd:       command to free
3866  *
3867  * This routine unconditionally frees a command, and reference counting
3868  * or list removal must be done in the caller.
3869  */
3870 void transport_release_cmd(struct se_cmd *cmd)
3871 {
3872         BUG_ON(!cmd->se_tfo);
3873
3874         if (cmd->se_tmr_req)
3875                 core_tmr_release_req(cmd->se_tmr_req);
3876         if (cmd->t_task_cdb != cmd->__t_task_cdb)
3877                 kfree(cmd->t_task_cdb);
3878         /*
3879          * Check if target_wait_for_sess_cmds() is expecting to
3880          * release se_cmd directly here..
3881          */
3882         if (cmd->check_release != 0 && cmd->se_tfo->check_release_cmd)
3883                 if (cmd->se_tfo->check_release_cmd(cmd) != 0)
3884                         return;
3885
3886         cmd->se_tfo->release_cmd(cmd);
3887 }
3888 EXPORT_SYMBOL(transport_release_cmd);
3889
3890 void transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
3891 {
3892         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD)) {
3893                 if (wait_for_tasks && cmd->se_tmr_req)
3894                          transport_wait_for_tasks(cmd);
3895
3896                 transport_release_cmd(cmd);
3897         } else {
3898                 if (wait_for_tasks)
3899                         transport_wait_for_tasks(cmd);
3900
3901                 core_dec_lacl_count(cmd->se_sess->se_node_acl, cmd);
3902
3903                 if (cmd->se_lun)
3904                         transport_lun_remove_cmd(cmd);
3905
3906                 transport_free_dev_tasks(cmd);
3907
3908                 transport_put_cmd(cmd);
3909         }
3910 }
3911 EXPORT_SYMBOL(transport_generic_free_cmd);
3912
3913 /* target_get_sess_cmd - Add command to active ->sess_cmd_list
3914  * @se_sess:    session to reference
3915  * @se_cmd:     command descriptor to add
3916  */
3917 void target_get_sess_cmd(struct se_session *se_sess, struct se_cmd *se_cmd)
3918 {
3919         unsigned long flags;
3920
3921         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
3922         list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list);
3923         se_cmd->check_release = 1;
3924         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
3925 }
3926 EXPORT_SYMBOL(target_get_sess_cmd);
3927
3928 /* target_put_sess_cmd - Check for active I/O shutdown or list delete
3929  * @se_sess:    session to reference
3930  * @se_cmd:     command descriptor to drop
3931  */
3932 int target_put_sess_cmd(struct se_session *se_sess, struct se_cmd *se_cmd)
3933 {
3934         unsigned long flags;
3935
3936         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
3937         if (list_empty(&se_cmd->se_cmd_list)) {
3938                 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
3939                 WARN_ON(1);
3940                 return 0;
3941         }
3942
3943         if (se_sess->sess_tearing_down && se_cmd->cmd_wait_set) {
3944                 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
3945                 complete(&se_cmd->cmd_wait_comp);
3946                 return 1;
3947         }
3948         list_del(&se_cmd->se_cmd_list);
3949         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
3950
3951         return 0;
3952 }
3953 EXPORT_SYMBOL(target_put_sess_cmd);
3954
3955 /* target_splice_sess_cmd_list - Split active cmds into sess_wait_list
3956  * @se_sess:    session to split
3957  */
3958 void target_splice_sess_cmd_list(struct se_session *se_sess)
3959 {
3960         struct se_cmd *se_cmd;
3961         unsigned long flags;
3962
3963         WARN_ON(!list_empty(&se_sess->sess_wait_list));
3964         INIT_LIST_HEAD(&se_sess->sess_wait_list);
3965
3966         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
3967         se_sess->sess_tearing_down = 1;
3968
3969         list_splice_init(&se_sess->sess_cmd_list, &se_sess->sess_wait_list);
3970
3971         list_for_each_entry(se_cmd, &se_sess->sess_wait_list, se_cmd_list)
3972                 se_cmd->cmd_wait_set = 1;
3973
3974         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
3975 }
3976 EXPORT_SYMBOL(target_splice_sess_cmd_list);
3977
3978 /* target_wait_for_sess_cmds - Wait for outstanding descriptors
3979  * @se_sess:    session to wait for active I/O
3980  * @wait_for_tasks:     Make extra transport_wait_for_tasks call
3981  */
3982 void target_wait_for_sess_cmds(
3983         struct se_session *se_sess,
3984         int wait_for_tasks)
3985 {
3986         struct se_cmd *se_cmd, *tmp_cmd;
3987         bool rc = false;
3988
3989         list_for_each_entry_safe(se_cmd, tmp_cmd,
3990                                 &se_sess->sess_wait_list, se_cmd_list) {
3991                 list_del(&se_cmd->se_cmd_list);
3992
3993                 pr_debug("Waiting for se_cmd: %p t_state: %d, fabric state:"
3994                         " %d\n", se_cmd, se_cmd->t_state,
3995                         se_cmd->se_tfo->get_cmd_state(se_cmd));
3996
3997                 if (wait_for_tasks) {
3998                         pr_debug("Calling transport_wait_for_tasks se_cmd: %p t_state: %d,"
3999                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
4000                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
4001
4002                         rc = transport_wait_for_tasks(se_cmd);
4003
4004                         pr_debug("After transport_wait_for_tasks se_cmd: %p t_state: %d,"
4005                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
4006                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
4007                 }
4008
4009                 if (!rc) {
4010                         wait_for_completion(&se_cmd->cmd_wait_comp);
4011                         pr_debug("After cmd_wait_comp: se_cmd: %p t_state: %d"
4012                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
4013                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
4014                 }
4015
4016                 se_cmd->se_tfo->release_cmd(se_cmd);
4017         }
4018 }
4019 EXPORT_SYMBOL(target_wait_for_sess_cmds);
4020
4021 /*      transport_lun_wait_for_tasks():
4022  *
4023  *      Called from ConfigFS context to stop the passed struct se_cmd to allow
4024  *      an struct se_lun to be successfully shutdown.
4025  */
4026 static int transport_lun_wait_for_tasks(struct se_cmd *cmd, struct se_lun *lun)
4027 {
4028         unsigned long flags;
4029         int ret;
4030         /*
4031          * If the frontend has already requested this struct se_cmd to
4032          * be stopped, we can safely ignore this struct se_cmd.
4033          */
4034         spin_lock_irqsave(&cmd->t_state_lock, flags);
4035         if (atomic_read(&cmd->t_transport_stop)) {
4036                 atomic_set(&cmd->transport_lun_stop, 0);
4037                 pr_debug("ConfigFS ITT[0x%08x] - t_transport_stop =="
4038                         " TRUE, skipping\n", cmd->se_tfo->get_task_tag(cmd));
4039                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4040                 transport_cmd_check_stop(cmd, 1, 0);
4041                 return -EPERM;
4042         }
4043         atomic_set(&cmd->transport_lun_fe_stop, 1);
4044         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4045
4046         wake_up_interruptible(&cmd->se_dev->dev_queue_obj.thread_wq);
4047
4048         ret = transport_stop_tasks_for_cmd(cmd);
4049
4050         pr_debug("ConfigFS: cmd: %p t_tasks: %d stop tasks ret:"
4051                         " %d\n", cmd, cmd->t_task_list_num, ret);
4052         if (!ret) {
4053                 pr_debug("ConfigFS: ITT[0x%08x] - stopping cmd....\n",
4054                                 cmd->se_tfo->get_task_tag(cmd));
4055                 wait_for_completion(&cmd->transport_lun_stop_comp);
4056                 pr_debug("ConfigFS: ITT[0x%08x] - stopped cmd....\n",
4057                                 cmd->se_tfo->get_task_tag(cmd));
4058         }
4059         transport_remove_cmd_from_queue(cmd);
4060
4061         return 0;
4062 }
4063
4064 static void __transport_clear_lun_from_sessions(struct se_lun *lun)
4065 {
4066         struct se_cmd *cmd = NULL;
4067         unsigned long lun_flags, cmd_flags;
4068         /*
4069          * Do exception processing and return CHECK_CONDITION status to the
4070          * Initiator Port.
4071          */
4072         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
4073         while (!list_empty(&lun->lun_cmd_list)) {
4074                 cmd = list_first_entry(&lun->lun_cmd_list,
4075                        struct se_cmd, se_lun_node);
4076                 list_del(&cmd->se_lun_node);
4077
4078                 atomic_set(&cmd->transport_lun_active, 0);
4079                 /*
4080                  * This will notify iscsi_target_transport.c:
4081                  * transport_cmd_check_stop() that a LUN shutdown is in
4082                  * progress for the iscsi_cmd_t.
4083                  */
4084                 spin_lock(&cmd->t_state_lock);
4085                 pr_debug("SE_LUN[%d] - Setting cmd->transport"
4086                         "_lun_stop for  ITT: 0x%08x\n",
4087                         cmd->se_lun->unpacked_lun,
4088                         cmd->se_tfo->get_task_tag(cmd));
4089                 atomic_set(&cmd->transport_lun_stop, 1);
4090                 spin_unlock(&cmd->t_state_lock);
4091
4092                 spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
4093
4094                 if (!cmd->se_lun) {
4095                         pr_err("ITT: 0x%08x, [i,t]_state: %u/%u\n",
4096                                 cmd->se_tfo->get_task_tag(cmd),
4097                                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
4098                         BUG();
4099                 }
4100                 /*
4101                  * If the Storage engine still owns the iscsi_cmd_t, determine
4102                  * and/or stop its context.
4103                  */
4104                 pr_debug("SE_LUN[%d] - ITT: 0x%08x before transport"
4105                         "_lun_wait_for_tasks()\n", cmd->se_lun->unpacked_lun,
4106                         cmd->se_tfo->get_task_tag(cmd));
4107
4108                 if (transport_lun_wait_for_tasks(cmd, cmd->se_lun) < 0) {
4109                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
4110                         continue;
4111                 }
4112
4113                 pr_debug("SE_LUN[%d] - ITT: 0x%08x after transport_lun"
4114                         "_wait_for_tasks(): SUCCESS\n",
4115                         cmd->se_lun->unpacked_lun,
4116                         cmd->se_tfo->get_task_tag(cmd));
4117
4118                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
4119                 if (!atomic_read(&cmd->transport_dev_active)) {
4120                         spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
4121                         goto check_cond;
4122                 }
4123                 atomic_set(&cmd->transport_dev_active, 0);
4124                 transport_all_task_dev_remove_state(cmd);
4125                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
4126
4127                 transport_free_dev_tasks(cmd);
4128                 /*
4129                  * The Storage engine stopped this struct se_cmd before it was
4130                  * send to the fabric frontend for delivery back to the
4131                  * Initiator Node.  Return this SCSI CDB back with an
4132                  * CHECK_CONDITION status.
4133                  */
4134 check_cond:
4135                 transport_send_check_condition_and_sense(cmd,
4136                                 TCM_NON_EXISTENT_LUN, 0);
4137                 /*
4138                  *  If the fabric frontend is waiting for this iscsi_cmd_t to
4139                  * be released, notify the waiting thread now that LU has
4140                  * finished accessing it.
4141                  */
4142                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
4143                 if (atomic_read(&cmd->transport_lun_fe_stop)) {
4144                         pr_debug("SE_LUN[%d] - Detected FE stop for"
4145                                 " struct se_cmd: %p ITT: 0x%08x\n",
4146                                 lun->unpacked_lun,
4147                                 cmd, cmd->se_tfo->get_task_tag(cmd));
4148
4149                         spin_unlock_irqrestore(&cmd->t_state_lock,
4150                                         cmd_flags);
4151                         transport_cmd_check_stop(cmd, 1, 0);
4152                         complete(&cmd->transport_lun_fe_stop_comp);
4153                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
4154                         continue;
4155                 }
4156                 pr_debug("SE_LUN[%d] - ITT: 0x%08x finished processing\n",
4157                         lun->unpacked_lun, cmd->se_tfo->get_task_tag(cmd));
4158
4159                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
4160                 spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
4161         }
4162         spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
4163 }
4164
4165 static int transport_clear_lun_thread(void *p)
4166 {
4167         struct se_lun *lun = (struct se_lun *)p;
4168
4169         __transport_clear_lun_from_sessions(lun);
4170         complete(&lun->lun_shutdown_comp);
4171
4172         return 0;
4173 }
4174
4175 int transport_clear_lun_from_sessions(struct se_lun *lun)
4176 {
4177         struct task_struct *kt;
4178
4179         kt = kthread_run(transport_clear_lun_thread, lun,
4180                         "tcm_cl_%u", lun->unpacked_lun);
4181         if (IS_ERR(kt)) {
4182                 pr_err("Unable to start clear_lun thread\n");
4183                 return PTR_ERR(kt);
4184         }
4185         wait_for_completion(&lun->lun_shutdown_comp);
4186
4187         return 0;
4188 }
4189
4190 /**
4191  * transport_wait_for_tasks - wait for completion to occur
4192  * @cmd:        command to wait
4193  *
4194  * Called from frontend fabric context to wait for storage engine
4195  * to pause and/or release frontend generated struct se_cmd.
4196  */
4197 bool transport_wait_for_tasks(struct se_cmd *cmd)
4198 {
4199         unsigned long flags;
4200
4201         spin_lock_irqsave(&cmd->t_state_lock, flags);
4202         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) && !(cmd->se_tmr_req)) {
4203                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4204                 return false;
4205         }
4206         /*
4207          * Only perform a possible wait_for_tasks if SCF_SUPPORTED_SAM_OPCODE
4208          * has been set in transport_set_supported_SAM_opcode().
4209          */
4210         if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) && !cmd->se_tmr_req) {
4211                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4212                 return false;
4213         }
4214         /*
4215          * If we are already stopped due to an external event (ie: LUN shutdown)
4216          * sleep until the connection can have the passed struct se_cmd back.
4217          * The cmd->transport_lun_stopped_sem will be upped by
4218          * transport_clear_lun_from_sessions() once the ConfigFS context caller
4219          * has completed its operation on the struct se_cmd.
4220          */
4221         if (atomic_read(&cmd->transport_lun_stop)) {
4222
4223                 pr_debug("wait_for_tasks: Stopping"
4224                         " wait_for_completion(&cmd->t_tasktransport_lun_fe"
4225                         "_stop_comp); for ITT: 0x%08x\n",
4226                         cmd->se_tfo->get_task_tag(cmd));
4227                 /*
4228                  * There is a special case for WRITES where a FE exception +
4229                  * LUN shutdown means ConfigFS context is still sleeping on
4230                  * transport_lun_stop_comp in transport_lun_wait_for_tasks().
4231                  * We go ahead and up transport_lun_stop_comp just to be sure
4232                  * here.
4233                  */
4234                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4235                 complete(&cmd->transport_lun_stop_comp);
4236                 wait_for_completion(&cmd->transport_lun_fe_stop_comp);
4237                 spin_lock_irqsave(&cmd->t_state_lock, flags);
4238
4239                 transport_all_task_dev_remove_state(cmd);
4240                 /*
4241                  * At this point, the frontend who was the originator of this
4242                  * struct se_cmd, now owns the structure and can be released through
4243                  * normal means below.
4244                  */
4245                 pr_debug("wait_for_tasks: Stopped"
4246                         " wait_for_completion(&cmd->t_tasktransport_lun_fe_"
4247                         "stop_comp); for ITT: 0x%08x\n",
4248                         cmd->se_tfo->get_task_tag(cmd));
4249
4250                 atomic_set(&cmd->transport_lun_stop, 0);
4251         }
4252         if (!atomic_read(&cmd->t_transport_active) ||
4253              atomic_read(&cmd->t_transport_aborted)) {
4254                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4255                 return false;
4256         }
4257
4258         atomic_set(&cmd->t_transport_stop, 1);
4259
4260         pr_debug("wait_for_tasks: Stopping %p ITT: 0x%08x"
4261                 " i_state: %d, t_state: %d, t_transport_stop = TRUE\n",
4262                 cmd, cmd->se_tfo->get_task_tag(cmd),
4263                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
4264
4265         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4266
4267         wake_up_interruptible(&cmd->se_dev->dev_queue_obj.thread_wq);
4268
4269         wait_for_completion(&cmd->t_transport_stop_comp);
4270
4271         spin_lock_irqsave(&cmd->t_state_lock, flags);
4272         atomic_set(&cmd->t_transport_active, 0);
4273         atomic_set(&cmd->t_transport_stop, 0);
4274
4275         pr_debug("wait_for_tasks: Stopped wait_for_compltion("
4276                 "&cmd->t_transport_stop_comp) for ITT: 0x%08x\n",
4277                 cmd->se_tfo->get_task_tag(cmd));
4278
4279         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4280
4281         return true;
4282 }
4283 EXPORT_SYMBOL(transport_wait_for_tasks);
4284
4285 static int transport_get_sense_codes(
4286         struct se_cmd *cmd,
4287         u8 *asc,
4288         u8 *ascq)
4289 {
4290         *asc = cmd->scsi_asc;
4291         *ascq = cmd->scsi_ascq;
4292
4293         return 0;
4294 }
4295
4296 static int transport_set_sense_codes(
4297         struct se_cmd *cmd,
4298         u8 asc,
4299         u8 ascq)
4300 {
4301         cmd->scsi_asc = asc;
4302         cmd->scsi_ascq = ascq;
4303
4304         return 0;
4305 }
4306
4307 int transport_send_check_condition_and_sense(
4308         struct se_cmd *cmd,
4309         u8 reason,
4310         int from_transport)
4311 {
4312         unsigned char *buffer = cmd->sense_buffer;
4313         unsigned long flags;
4314         int offset;
4315         u8 asc = 0, ascq = 0;
4316
4317         spin_lock_irqsave(&cmd->t_state_lock, flags);
4318         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
4319                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4320                 return 0;
4321         }
4322         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
4323         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4324
4325         if (!reason && from_transport)
4326                 goto after_reason;
4327
4328         if (!from_transport)
4329                 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
4330         /*
4331          * Data Segment and SenseLength of the fabric response PDU.
4332          *
4333          * TRANSPORT_SENSE_BUFFER is now set to SCSI_SENSE_BUFFERSIZE
4334          * from include/scsi/scsi_cmnd.h
4335          */
4336         offset = cmd->se_tfo->set_fabric_sense_len(cmd,
4337                                 TRANSPORT_SENSE_BUFFER);
4338         /*
4339          * Actual SENSE DATA, see SPC-3 7.23.2  SPC_SENSE_KEY_OFFSET uses
4340          * SENSE KEY values from include/scsi/scsi.h
4341          */
4342         switch (reason) {
4343         case TCM_NON_EXISTENT_LUN:
4344                 /* CURRENT ERROR */
4345                 buffer[offset] = 0x70;
4346                 /* ILLEGAL REQUEST */
4347                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
4348                 /* LOGICAL UNIT NOT SUPPORTED */
4349                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x25;
4350                 break;
4351         case TCM_UNSUPPORTED_SCSI_OPCODE:
4352         case TCM_SECTOR_COUNT_TOO_MANY:
4353                 /* CURRENT ERROR */
4354                 buffer[offset] = 0x70;
4355                 /* ILLEGAL REQUEST */
4356                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
4357                 /* INVALID COMMAND OPERATION CODE */
4358                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x20;
4359                 break;
4360         case TCM_UNKNOWN_MODE_PAGE:
4361                 /* CURRENT ERROR */
4362                 buffer[offset] = 0x70;
4363                 /* ILLEGAL REQUEST */
4364                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
4365                 /* INVALID FIELD IN CDB */
4366                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
4367                 break;
4368         case TCM_CHECK_CONDITION_ABORT_CMD:
4369                 /* CURRENT ERROR */
4370                 buffer[offset] = 0x70;
4371                 /* ABORTED COMMAND */
4372                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4373                 /* BUS DEVICE RESET FUNCTION OCCURRED */
4374                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x29;
4375                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x03;
4376                 break;
4377         case TCM_INCORRECT_AMOUNT_OF_DATA:
4378                 /* CURRENT ERROR */
4379                 buffer[offset] = 0x70;
4380                 /* ABORTED COMMAND */
4381                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4382                 /* WRITE ERROR */
4383                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
4384                 /* NOT ENOUGH UNSOLICITED DATA */
4385                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0d;
4386                 break;
4387         case TCM_INVALID_CDB_FIELD:
4388                 /* CURRENT ERROR */
4389                 buffer[offset] = 0x70;
4390                 /* ABORTED COMMAND */
4391                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4392                 /* INVALID FIELD IN CDB */
4393                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
4394                 break;
4395         case TCM_INVALID_PARAMETER_LIST:
4396                 /* CURRENT ERROR */
4397                 buffer[offset] = 0x70;
4398                 /* ABORTED COMMAND */
4399                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4400                 /* INVALID FIELD IN PARAMETER LIST */
4401                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x26;
4402                 break;
4403         case TCM_UNEXPECTED_UNSOLICITED_DATA:
4404                 /* CURRENT ERROR */
4405                 buffer[offset] = 0x70;
4406                 /* ABORTED COMMAND */
4407                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4408                 /* WRITE ERROR */
4409                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
4410                 /* UNEXPECTED_UNSOLICITED_DATA */
4411                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0c;
4412                 break;
4413         case TCM_SERVICE_CRC_ERROR:
4414                 /* CURRENT ERROR */
4415                 buffer[offset] = 0x70;
4416                 /* ABORTED COMMAND */
4417                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4418                 /* PROTOCOL SERVICE CRC ERROR */
4419                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x47;
4420                 /* N/A */
4421                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x05;
4422                 break;
4423         case TCM_SNACK_REJECTED:
4424                 /* CURRENT ERROR */
4425                 buffer[offset] = 0x70;
4426                 /* ABORTED COMMAND */
4427                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4428                 /* READ ERROR */
4429                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x11;
4430                 /* FAILED RETRANSMISSION REQUEST */
4431                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x13;
4432                 break;
4433         case TCM_WRITE_PROTECTED:
4434                 /* CURRENT ERROR */
4435                 buffer[offset] = 0x70;
4436                 /* DATA PROTECT */
4437                 buffer[offset+SPC_SENSE_KEY_OFFSET] = DATA_PROTECT;
4438                 /* WRITE PROTECTED */
4439                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x27;
4440                 break;
4441         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
4442                 /* CURRENT ERROR */
4443                 buffer[offset] = 0x70;
4444                 /* UNIT ATTENTION */
4445                 buffer[offset+SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION;
4446                 core_scsi3_ua_for_check_condition(cmd, &asc, &ascq);
4447                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
4448                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
4449                 break;
4450         case TCM_CHECK_CONDITION_NOT_READY:
4451                 /* CURRENT ERROR */
4452                 buffer[offset] = 0x70;
4453                 /* Not Ready */
4454                 buffer[offset+SPC_SENSE_KEY_OFFSET] = NOT_READY;
4455                 transport_get_sense_codes(cmd, &asc, &ascq);
4456                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
4457                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
4458                 break;
4459         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
4460         default:
4461                 /* CURRENT ERROR */
4462                 buffer[offset] = 0x70;
4463                 /* ILLEGAL REQUEST */
4464                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
4465                 /* LOGICAL UNIT COMMUNICATION FAILURE */
4466                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x80;
4467                 break;
4468         }
4469         /*
4470          * This code uses linux/include/scsi/scsi.h SAM status codes!
4471          */
4472         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
4473         /*
4474          * Automatically padded, this value is encoded in the fabric's
4475          * data_length response PDU containing the SCSI defined sense data.
4476          */
4477         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER + offset;
4478
4479 after_reason:
4480         return cmd->se_tfo->queue_status(cmd);
4481 }
4482 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
4483
4484 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
4485 {
4486         int ret = 0;
4487
4488         if (atomic_read(&cmd->t_transport_aborted) != 0) {
4489                 if (!send_status ||
4490                      (cmd->se_cmd_flags & SCF_SENT_DELAYED_TAS))
4491                         return 1;
4492 #if 0
4493                 pr_debug("Sending delayed SAM_STAT_TASK_ABORTED"
4494                         " status for CDB: 0x%02x ITT: 0x%08x\n",
4495                         cmd->t_task_cdb[0],
4496                         cmd->se_tfo->get_task_tag(cmd));
4497 #endif
4498                 cmd->se_cmd_flags |= SCF_SENT_DELAYED_TAS;
4499                 cmd->se_tfo->queue_status(cmd);
4500                 ret = 1;
4501         }
4502         return ret;
4503 }
4504 EXPORT_SYMBOL(transport_check_aborted_status);
4505
4506 void transport_send_task_abort(struct se_cmd *cmd)
4507 {
4508         unsigned long flags;
4509
4510         spin_lock_irqsave(&cmd->t_state_lock, flags);
4511         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
4512                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4513                 return;
4514         }
4515         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4516
4517         /*
4518          * If there are still expected incoming fabric WRITEs, we wait
4519          * until until they have completed before sending a TASK_ABORTED
4520          * response.  This response with TASK_ABORTED status will be
4521          * queued back to fabric module by transport_check_aborted_status().
4522          */
4523         if (cmd->data_direction == DMA_TO_DEVICE) {
4524                 if (cmd->se_tfo->write_pending_status(cmd) != 0) {
4525                         atomic_inc(&cmd->t_transport_aborted);
4526                         smp_mb__after_atomic_inc();
4527                 }
4528         }
4529         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
4530 #if 0
4531         pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x,"
4532                 " ITT: 0x%08x\n", cmd->t_task_cdb[0],
4533                 cmd->se_tfo->get_task_tag(cmd));
4534 #endif
4535         cmd->se_tfo->queue_status(cmd);
4536 }
4537
4538 /*      transport_generic_do_tmr():
4539  *
4540  *
4541  */
4542 int transport_generic_do_tmr(struct se_cmd *cmd)
4543 {
4544         struct se_device *dev = cmd->se_dev;
4545         struct se_tmr_req *tmr = cmd->se_tmr_req;
4546         int ret;
4547
4548         switch (tmr->function) {
4549         case TMR_ABORT_TASK:
4550                 tmr->response = TMR_FUNCTION_REJECTED;
4551                 break;
4552         case TMR_ABORT_TASK_SET:
4553         case TMR_CLEAR_ACA:
4554         case TMR_CLEAR_TASK_SET:
4555                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
4556                 break;
4557         case TMR_LUN_RESET:
4558                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
4559                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
4560                                          TMR_FUNCTION_REJECTED;
4561                 break;
4562         case TMR_TARGET_WARM_RESET:
4563                 tmr->response = TMR_FUNCTION_REJECTED;
4564                 break;
4565         case TMR_TARGET_COLD_RESET:
4566                 tmr->response = TMR_FUNCTION_REJECTED;
4567                 break;
4568         default:
4569                 pr_err("Uknown TMR function: 0x%02x.\n",
4570                                 tmr->function);
4571                 tmr->response = TMR_FUNCTION_REJECTED;
4572                 break;
4573         }
4574
4575         cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
4576         cmd->se_tfo->queue_tm_rsp(cmd);
4577
4578         transport_cmd_check_stop_to_fabric(cmd);
4579         return 0;
4580 }
4581
4582 /*      transport_processing_thread():
4583  *
4584  *
4585  */
4586 static int transport_processing_thread(void *param)
4587 {
4588         int ret;
4589         struct se_cmd *cmd;
4590         struct se_device *dev = (struct se_device *) param;
4591
4592         while (!kthread_should_stop()) {
4593                 ret = wait_event_interruptible(dev->dev_queue_obj.thread_wq,
4594                                 atomic_read(&dev->dev_queue_obj.queue_cnt) ||
4595                                 kthread_should_stop());
4596                 if (ret < 0)
4597                         goto out;
4598
4599 get_cmd:
4600                 __transport_execute_tasks(dev);
4601
4602                 cmd = transport_get_cmd_from_queue(&dev->dev_queue_obj);
4603                 if (!cmd)
4604                         continue;
4605
4606                 switch (cmd->t_state) {
4607                 case TRANSPORT_NEW_CMD:
4608                         BUG();
4609                         break;
4610                 case TRANSPORT_NEW_CMD_MAP:
4611                         if (!cmd->se_tfo->new_cmd_map) {
4612                                 pr_err("cmd->se_tfo->new_cmd_map is"
4613                                         " NULL for TRANSPORT_NEW_CMD_MAP\n");
4614                                 BUG();
4615                         }
4616                         ret = cmd->se_tfo->new_cmd_map(cmd);
4617                         if (ret < 0) {
4618                                 transport_generic_request_failure(cmd);
4619                                 break;
4620                         }
4621                         ret = transport_generic_new_cmd(cmd);
4622                         if (ret < 0) {
4623                                 transport_generic_request_failure(cmd);
4624                                 break;
4625                         }
4626                         break;
4627                 case TRANSPORT_PROCESS_WRITE:
4628                         transport_generic_process_write(cmd);
4629                         break;
4630                 case TRANSPORT_PROCESS_TMR:
4631                         transport_generic_do_tmr(cmd);
4632                         break;
4633                 case TRANSPORT_COMPLETE_QF_WP:
4634                         transport_write_pending_qf(cmd);
4635                         break;
4636                 case TRANSPORT_COMPLETE_QF_OK:
4637                         transport_complete_qf(cmd);
4638                         break;
4639                 default:
4640                         pr_err("Unknown t_state: %d  for ITT: 0x%08x "
4641                                 "i_state: %d on SE LUN: %u\n",
4642                                 cmd->t_state,
4643                                 cmd->se_tfo->get_task_tag(cmd),
4644                                 cmd->se_tfo->get_cmd_state(cmd),
4645                                 cmd->se_lun->unpacked_lun);
4646                         BUG();
4647                 }
4648
4649                 goto get_cmd;
4650         }
4651
4652 out:
4653         WARN_ON(!list_empty(&dev->state_task_list));
4654         WARN_ON(!list_empty(&dev->dev_queue_obj.qobj_list));
4655         dev->process_thread = NULL;
4656         return 0;
4657 }