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