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