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