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