target: move code for CDB emulation
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / target / target_core_transport.c
1 /*******************************************************************************
2  * Filename:  target_core_transport.c
3  *
4  * This file contains the Generic Target Engine Core.
5  *
6  * Copyright (c) 2002, 2003, 2004, 2005 PyX Technologies, Inc.
7  * Copyright (c) 2005, 2006, 2007 SBE, Inc.
8  * Copyright (c) 2007-2010 Rising Tide Systems
9  * Copyright (c) 2008-2010 Linux-iSCSI.org
10  *
11  * Nicholas A. Bellinger <nab@kernel.org>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26  *
27  ******************************************************************************/
28
29 #include <linux/net.h>
30 #include <linux/delay.h>
31 #include <linux/string.h>
32 #include <linux/timer.h>
33 #include <linux/slab.h>
34 #include <linux/blkdev.h>
35 #include <linux/spinlock.h>
36 #include <linux/kthread.h>
37 #include <linux/in.h>
38 #include <linux/cdrom.h>
39 #include <linux/module.h>
40 #include <linux/ratelimit.h>
41 #include <asm/unaligned.h>
42 #include <net/sock.h>
43 #include <net/tcp.h>
44 #include <scsi/scsi.h>
45 #include <scsi/scsi_cmnd.h>
46 #include <scsi/scsi_tcq.h>
47
48 #include <target/target_core_base.h>
49 #include <target/target_core_backend.h>
50 #include <target/target_core_fabric.h>
51 #include <target/target_core_configfs.h>
52
53 #include "target_core_internal.h"
54 #include "target_core_alua.h"
55 #include "target_core_pr.h"
56 #include "target_core_ua.h"
57
58 static int sub_api_initialized;
59
60 static struct workqueue_struct *target_completion_wq;
61 static struct kmem_cache *se_sess_cache;
62 struct kmem_cache *se_ua_cache;
63 struct kmem_cache *t10_pr_reg_cache;
64 struct kmem_cache *t10_alua_lu_gp_cache;
65 struct kmem_cache *t10_alua_lu_gp_mem_cache;
66 struct kmem_cache *t10_alua_tg_pt_gp_cache;
67 struct kmem_cache *t10_alua_tg_pt_gp_mem_cache;
68
69 static int transport_generic_write_pending(struct se_cmd *);
70 static int transport_processing_thread(void *param);
71 static int __transport_execute_tasks(struct se_device *dev, struct se_cmd *);
72 static void transport_complete_task_attr(struct se_cmd *cmd);
73 static void transport_handle_queue_full(struct se_cmd *cmd,
74                 struct se_device *dev);
75 static 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         kref_init(&se_sess->sess_kref);
249
250         return se_sess;
251 }
252 EXPORT_SYMBOL(transport_init_session);
253
254 /*
255  * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
256  */
257 void __transport_register_session(
258         struct se_portal_group *se_tpg,
259         struct se_node_acl *se_nacl,
260         struct se_session *se_sess,
261         void *fabric_sess_ptr)
262 {
263         unsigned char buf[PR_REG_ISID_LEN];
264
265         se_sess->se_tpg = se_tpg;
266         se_sess->fabric_sess_ptr = fabric_sess_ptr;
267         /*
268          * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
269          *
270          * Only set for struct se_session's that will actually be moving I/O.
271          * eg: *NOT* discovery sessions.
272          */
273         if (se_nacl) {
274                 /*
275                  * If the fabric module supports an ISID based TransportID,
276                  * save this value in binary from the fabric I_T Nexus now.
277                  */
278                 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
279                         memset(&buf[0], 0, PR_REG_ISID_LEN);
280                         se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
281                                         &buf[0], PR_REG_ISID_LEN);
282                         se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
283                 }
284                 kref_get(&se_nacl->acl_kref);
285
286                 spin_lock_irq(&se_nacl->nacl_sess_lock);
287                 /*
288                  * The se_nacl->nacl_sess pointer will be set to the
289                  * last active I_T Nexus for each struct se_node_acl.
290                  */
291                 se_nacl->nacl_sess = se_sess;
292
293                 list_add_tail(&se_sess->sess_acl_list,
294                               &se_nacl->acl_sess_list);
295                 spin_unlock_irq(&se_nacl->nacl_sess_lock);
296         }
297         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
298
299         pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
300                 se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
301 }
302 EXPORT_SYMBOL(__transport_register_session);
303
304 void transport_register_session(
305         struct se_portal_group *se_tpg,
306         struct se_node_acl *se_nacl,
307         struct se_session *se_sess,
308         void *fabric_sess_ptr)
309 {
310         unsigned long flags;
311
312         spin_lock_irqsave(&se_tpg->session_lock, flags);
313         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
314         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
315 }
316 EXPORT_SYMBOL(transport_register_session);
317
318 void target_release_session(struct kref *kref)
319 {
320         struct se_session *se_sess = container_of(kref,
321                         struct se_session, sess_kref);
322         struct se_portal_group *se_tpg = se_sess->se_tpg;
323
324         se_tpg->se_tpg_tfo->close_session(se_sess);
325 }
326
327 void target_get_session(struct se_session *se_sess)
328 {
329         kref_get(&se_sess->sess_kref);
330 }
331 EXPORT_SYMBOL(target_get_session);
332
333 void target_put_session(struct se_session *se_sess)
334 {
335         struct se_portal_group *tpg = se_sess->se_tpg;
336
337         if (tpg->se_tpg_tfo->put_session != NULL) {
338                 tpg->se_tpg_tfo->put_session(se_sess);
339                 return;
340         }
341         kref_put(&se_sess->sess_kref, target_release_session);
342 }
343 EXPORT_SYMBOL(target_put_session);
344
345 static void target_complete_nacl(struct kref *kref)
346 {
347         struct se_node_acl *nacl = container_of(kref,
348                                 struct se_node_acl, acl_kref);
349
350         complete(&nacl->acl_free_comp);
351 }
352
353 void target_put_nacl(struct se_node_acl *nacl)
354 {
355         kref_put(&nacl->acl_kref, target_complete_nacl);
356 }
357
358 void transport_deregister_session_configfs(struct se_session *se_sess)
359 {
360         struct se_node_acl *se_nacl;
361         unsigned long flags;
362         /*
363          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
364          */
365         se_nacl = se_sess->se_node_acl;
366         if (se_nacl) {
367                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
368                 if (se_nacl->acl_stop == 0)
369                         list_del(&se_sess->sess_acl_list);
370                 /*
371                  * If the session list is empty, then clear the pointer.
372                  * Otherwise, set the struct se_session pointer from the tail
373                  * element of the per struct se_node_acl active session list.
374                  */
375                 if (list_empty(&se_nacl->acl_sess_list))
376                         se_nacl->nacl_sess = NULL;
377                 else {
378                         se_nacl->nacl_sess = container_of(
379                                         se_nacl->acl_sess_list.prev,
380                                         struct se_session, sess_acl_list);
381                 }
382                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
383         }
384 }
385 EXPORT_SYMBOL(transport_deregister_session_configfs);
386
387 void transport_free_session(struct se_session *se_sess)
388 {
389         kmem_cache_free(se_sess_cache, se_sess);
390 }
391 EXPORT_SYMBOL(transport_free_session);
392
393 void transport_deregister_session(struct se_session *se_sess)
394 {
395         struct se_portal_group *se_tpg = se_sess->se_tpg;
396         struct target_core_fabric_ops *se_tfo;
397         struct se_node_acl *se_nacl;
398         unsigned long flags;
399         bool comp_nacl = true;
400
401         if (!se_tpg) {
402                 transport_free_session(se_sess);
403                 return;
404         }
405         se_tfo = se_tpg->se_tpg_tfo;
406
407         spin_lock_irqsave(&se_tpg->session_lock, flags);
408         list_del(&se_sess->sess_list);
409         se_sess->se_tpg = NULL;
410         se_sess->fabric_sess_ptr = NULL;
411         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
412
413         /*
414          * Determine if we need to do extra work for this initiator node's
415          * struct se_node_acl if it had been previously dynamically generated.
416          */
417         se_nacl = se_sess->se_node_acl;
418
419         spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
420         if (se_nacl && se_nacl->dynamic_node_acl) {
421                 if (!se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
422                         list_del(&se_nacl->acl_list);
423                         se_tpg->num_node_acls--;
424                         spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
425                         core_tpg_wait_for_nacl_pr_ref(se_nacl);
426                         core_free_device_list_for_node(se_nacl, se_tpg);
427                         se_tfo->tpg_release_fabric_acl(se_tpg, se_nacl);
428
429                         comp_nacl = false;
430                         spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
431                 }
432         }
433         spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
434
435         pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
436                 se_tpg->se_tpg_tfo->get_fabric_name());
437         /*
438          * If last kref is dropping now for an explict NodeACL, awake sleeping
439          * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
440          * removal context.
441          */
442         if (se_nacl && comp_nacl == true)
443                 target_put_nacl(se_nacl);
444
445         transport_free_session(se_sess);
446 }
447 EXPORT_SYMBOL(transport_deregister_session);
448
449 /*
450  * Called with cmd->t_state_lock held.
451  */
452 static void target_remove_from_state_list(struct se_cmd *cmd)
453 {
454         struct se_device *dev = cmd->se_dev;
455         unsigned long flags;
456
457         if (!dev)
458                 return;
459
460         if (cmd->transport_state & CMD_T_BUSY)
461                 return;
462
463         spin_lock_irqsave(&dev->execute_task_lock, flags);
464         if (cmd->state_active) {
465                 list_del(&cmd->state_list);
466                 cmd->state_active = false;
467         }
468         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
469 }
470
471 /*      transport_cmd_check_stop():
472  *
473  *      'transport_off = 1' determines if CMD_T_ACTIVE should be cleared.
474  *      'transport_off = 2' determines if task_dev_state should be removed.
475  *
476  *      A non-zero u8 t_state sets cmd->t_state.
477  *      Returns 1 when command is stopped, else 0.
478  */
479 static int transport_cmd_check_stop(
480         struct se_cmd *cmd,
481         int transport_off,
482         u8 t_state)
483 {
484         unsigned long flags;
485
486         spin_lock_irqsave(&cmd->t_state_lock, flags);
487         /*
488          * Determine if IOCTL context caller in requesting the stopping of this
489          * command for LUN shutdown purposes.
490          */
491         if (cmd->transport_state & CMD_T_LUN_STOP) {
492                 pr_debug("%s:%d CMD_T_LUN_STOP for ITT: 0x%08x\n",
493                         __func__, __LINE__, cmd->se_tfo->get_task_tag(cmd));
494
495                 cmd->transport_state &= ~CMD_T_ACTIVE;
496                 if (transport_off == 2)
497                         target_remove_from_state_list(cmd);
498                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
499
500                 complete(&cmd->transport_lun_stop_comp);
501                 return 1;
502         }
503         /*
504          * Determine if frontend context caller is requesting the stopping of
505          * this command for frontend exceptions.
506          */
507         if (cmd->transport_state & CMD_T_STOP) {
508                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08x\n",
509                         __func__, __LINE__,
510                         cmd->se_tfo->get_task_tag(cmd));
511
512                 if (transport_off == 2)
513                         target_remove_from_state_list(cmd);
514
515                 /*
516                  * Clear struct se_cmd->se_lun before the transport_off == 2 handoff
517                  * to FE.
518                  */
519                 if (transport_off == 2)
520                         cmd->se_lun = NULL;
521                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
522
523                 complete(&cmd->t_transport_stop_comp);
524                 return 1;
525         }
526         if (transport_off) {
527                 cmd->transport_state &= ~CMD_T_ACTIVE;
528                 if (transport_off == 2) {
529                         target_remove_from_state_list(cmd);
530                         /*
531                          * Clear struct se_cmd->se_lun before the transport_off == 2
532                          * handoff to fabric module.
533                          */
534                         cmd->se_lun = NULL;
535                         /*
536                          * Some fabric modules like tcm_loop can release
537                          * their internally allocated I/O reference now and
538                          * struct se_cmd now.
539                          *
540                          * Fabric modules are expected to return '1' here if the
541                          * se_cmd being passed is released at this point,
542                          * or zero if not being released.
543                          */
544                         if (cmd->se_tfo->check_stop_free != NULL) {
545                                 spin_unlock_irqrestore(
546                                         &cmd->t_state_lock, flags);
547
548                                 return cmd->se_tfo->check_stop_free(cmd);
549                         }
550                 }
551                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
552
553                 return 0;
554         } else if (t_state)
555                 cmd->t_state = t_state;
556         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
557
558         return 0;
559 }
560
561 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
562 {
563         return transport_cmd_check_stop(cmd, 2, 0);
564 }
565
566 static void transport_lun_remove_cmd(struct se_cmd *cmd)
567 {
568         struct se_lun *lun = cmd->se_lun;
569         unsigned long flags;
570
571         if (!lun)
572                 return;
573
574         spin_lock_irqsave(&cmd->t_state_lock, flags);
575         if (cmd->transport_state & CMD_T_DEV_ACTIVE) {
576                 cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
577                 target_remove_from_state_list(cmd);
578         }
579         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
580
581         spin_lock_irqsave(&lun->lun_cmd_lock, flags);
582         if (!list_empty(&cmd->se_lun_node))
583                 list_del_init(&cmd->se_lun_node);
584         spin_unlock_irqrestore(&lun->lun_cmd_lock, flags);
585 }
586
587 void transport_cmd_finish_abort(struct se_cmd *cmd, int remove)
588 {
589         if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
590                 transport_lun_remove_cmd(cmd);
591
592         if (transport_cmd_check_stop_to_fabric(cmd))
593                 return;
594         if (remove) {
595                 transport_remove_cmd_from_queue(cmd);
596                 transport_put_cmd(cmd);
597         }
598 }
599
600 static void transport_add_cmd_to_queue(struct se_cmd *cmd, int t_state,
601                 bool at_head)
602 {
603         struct se_device *dev = cmd->se_dev;
604         struct se_queue_obj *qobj = &dev->dev_queue_obj;
605         unsigned long flags;
606
607         if (t_state) {
608                 spin_lock_irqsave(&cmd->t_state_lock, flags);
609                 cmd->t_state = t_state;
610                 cmd->transport_state |= CMD_T_ACTIVE;
611                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
612         }
613
614         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
615
616         /* If the cmd is already on the list, remove it before we add it */
617         if (!list_empty(&cmd->se_queue_node))
618                 list_del(&cmd->se_queue_node);
619         else
620                 atomic_inc(&qobj->queue_cnt);
621
622         if (at_head)
623                 list_add(&cmd->se_queue_node, &qobj->qobj_list);
624         else
625                 list_add_tail(&cmd->se_queue_node, &qobj->qobj_list);
626         cmd->transport_state |= CMD_T_QUEUED;
627         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
628
629         wake_up_interruptible(&qobj->thread_wq);
630 }
631
632 static struct se_cmd *
633 transport_get_cmd_from_queue(struct se_queue_obj *qobj)
634 {
635         struct se_cmd *cmd;
636         unsigned long flags;
637
638         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
639         if (list_empty(&qobj->qobj_list)) {
640                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
641                 return NULL;
642         }
643         cmd = list_first_entry(&qobj->qobj_list, struct se_cmd, se_queue_node);
644
645         cmd->transport_state &= ~CMD_T_QUEUED;
646         list_del_init(&cmd->se_queue_node);
647         atomic_dec(&qobj->queue_cnt);
648         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
649
650         return cmd;
651 }
652
653 static void transport_remove_cmd_from_queue(struct se_cmd *cmd)
654 {
655         struct se_queue_obj *qobj = &cmd->se_dev->dev_queue_obj;
656         unsigned long flags;
657
658         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
659         if (!(cmd->transport_state & CMD_T_QUEUED)) {
660                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
661                 return;
662         }
663         cmd->transport_state &= ~CMD_T_QUEUED;
664         atomic_dec(&qobj->queue_cnt);
665         list_del_init(&cmd->se_queue_node);
666         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
667 }
668
669 static void target_complete_failure_work(struct work_struct *work)
670 {
671         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
672
673         transport_generic_request_failure(cmd);
674 }
675
676 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
677 {
678         struct se_device *dev = cmd->se_dev;
679         int success = scsi_status == GOOD;
680         unsigned long flags;
681
682         cmd->scsi_status = scsi_status;
683
684
685         spin_lock_irqsave(&cmd->t_state_lock, flags);
686         cmd->transport_state &= ~CMD_T_BUSY;
687
688         if (dev && dev->transport->transport_complete) {
689                 if (dev->transport->transport_complete(cmd,
690                                 cmd->t_data_sg) != 0) {
691                         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
692                         success = 1;
693                 }
694         }
695
696         /*
697          * See if we are waiting to complete for an exception condition.
698          */
699         if (cmd->transport_state & CMD_T_REQUEST_STOP) {
700                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
701                 complete(&cmd->task_stop_comp);
702                 return;
703         }
704
705         if (!success)
706                 cmd->transport_state |= CMD_T_FAILED;
707
708         /*
709          * Check for case where an explict ABORT_TASK has been received
710          * and transport_wait_for_tasks() will be waiting for completion..
711          */
712         if (cmd->transport_state & CMD_T_ABORTED &&
713             cmd->transport_state & CMD_T_STOP) {
714                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
715                 complete(&cmd->t_transport_stop_comp);
716                 return;
717         } else if (cmd->transport_state & CMD_T_FAILED) {
718                 cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
719                 INIT_WORK(&cmd->work, target_complete_failure_work);
720         } else {
721                 INIT_WORK(&cmd->work, target_complete_ok_work);
722         }
723
724         cmd->t_state = TRANSPORT_COMPLETE;
725         cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
726         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
727
728         queue_work(target_completion_wq, &cmd->work);
729 }
730 EXPORT_SYMBOL(target_complete_cmd);
731
732 static void target_add_to_state_list(struct se_cmd *cmd)
733 {
734         struct se_device *dev = cmd->se_dev;
735         unsigned long flags;
736
737         spin_lock_irqsave(&dev->execute_task_lock, flags);
738         if (!cmd->state_active) {
739                 list_add_tail(&cmd->state_list, &dev->state_list);
740                 cmd->state_active = true;
741         }
742         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
743 }
744
745 static void __target_add_to_execute_list(struct se_cmd *cmd)
746 {
747         struct se_device *dev = cmd->se_dev;
748         bool head_of_queue = false;
749
750         if (!list_empty(&cmd->execute_list))
751                 return;
752
753         if (dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED &&
754             cmd->sam_task_attr == MSG_HEAD_TAG)
755                 head_of_queue = true;
756
757         if (head_of_queue)
758                 list_add(&cmd->execute_list, &dev->execute_list);
759         else
760                 list_add_tail(&cmd->execute_list, &dev->execute_list);
761
762         atomic_inc(&dev->execute_tasks);
763
764         if (cmd->state_active)
765                 return;
766
767         if (head_of_queue)
768                 list_add(&cmd->state_list, &dev->state_list);
769         else
770                 list_add_tail(&cmd->state_list, &dev->state_list);
771
772         cmd->state_active = true;
773 }
774
775 static void target_add_to_execute_list(struct se_cmd *cmd)
776 {
777         unsigned long flags;
778         struct se_device *dev = cmd->se_dev;
779
780         spin_lock_irqsave(&dev->execute_task_lock, flags);
781         __target_add_to_execute_list(cmd);
782         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
783 }
784
785 void __target_remove_from_execute_list(struct se_cmd *cmd)
786 {
787         list_del_init(&cmd->execute_list);
788         atomic_dec(&cmd->se_dev->execute_tasks);
789 }
790
791 static void target_remove_from_execute_list(struct se_cmd *cmd)
792 {
793         struct se_device *dev = cmd->se_dev;
794         unsigned long flags;
795
796         if (WARN_ON(list_empty(&cmd->execute_list)))
797                 return;
798
799         spin_lock_irqsave(&dev->execute_task_lock, flags);
800         __target_remove_from_execute_list(cmd);
801         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
802 }
803
804 /*
805  * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
806  */
807
808 static void target_qf_do_work(struct work_struct *work)
809 {
810         struct se_device *dev = container_of(work, struct se_device,
811                                         qf_work_queue);
812         LIST_HEAD(qf_cmd_list);
813         struct se_cmd *cmd, *cmd_tmp;
814
815         spin_lock_irq(&dev->qf_cmd_lock);
816         list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
817         spin_unlock_irq(&dev->qf_cmd_lock);
818
819         list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
820                 list_del(&cmd->se_qf_node);
821                 atomic_dec(&dev->dev_qf_count);
822                 smp_mb__after_atomic_dec();
823
824                 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
825                         " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
826                         (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
827                         (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
828                         : "UNKNOWN");
829
830                 transport_add_cmd_to_queue(cmd, cmd->t_state, true);
831         }
832 }
833
834 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
835 {
836         switch (cmd->data_direction) {
837         case DMA_NONE:
838                 return "NONE";
839         case DMA_FROM_DEVICE:
840                 return "READ";
841         case DMA_TO_DEVICE:
842                 return "WRITE";
843         case DMA_BIDIRECTIONAL:
844                 return "BIDI";
845         default:
846                 break;
847         }
848
849         return "UNKNOWN";
850 }
851
852 void transport_dump_dev_state(
853         struct se_device *dev,
854         char *b,
855         int *bl)
856 {
857         *bl += sprintf(b + *bl, "Status: ");
858         switch (dev->dev_status) {
859         case TRANSPORT_DEVICE_ACTIVATED:
860                 *bl += sprintf(b + *bl, "ACTIVATED");
861                 break;
862         case TRANSPORT_DEVICE_DEACTIVATED:
863                 *bl += sprintf(b + *bl, "DEACTIVATED");
864                 break;
865         case TRANSPORT_DEVICE_SHUTDOWN:
866                 *bl += sprintf(b + *bl, "SHUTDOWN");
867                 break;
868         case TRANSPORT_DEVICE_OFFLINE_ACTIVATED:
869         case TRANSPORT_DEVICE_OFFLINE_DEACTIVATED:
870                 *bl += sprintf(b + *bl, "OFFLINE");
871                 break;
872         default:
873                 *bl += sprintf(b + *bl, "UNKNOWN=%d", dev->dev_status);
874                 break;
875         }
876
877         *bl += sprintf(b + *bl, "  Execute/Max Queue Depth: %d/%d",
878                 atomic_read(&dev->execute_tasks), dev->queue_depth);
879         *bl += sprintf(b + *bl, "  SectorSize: %u  HwMaxSectors: %u\n",
880                 dev->se_sub_dev->se_dev_attrib.block_size,
881                 dev->se_sub_dev->se_dev_attrib.hw_max_sectors);
882         *bl += sprintf(b + *bl, "        ");
883 }
884
885 void transport_dump_vpd_proto_id(
886         struct t10_vpd *vpd,
887         unsigned char *p_buf,
888         int p_buf_len)
889 {
890         unsigned char buf[VPD_TMP_BUF_SIZE];
891         int len;
892
893         memset(buf, 0, VPD_TMP_BUF_SIZE);
894         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
895
896         switch (vpd->protocol_identifier) {
897         case 0x00:
898                 sprintf(buf+len, "Fibre Channel\n");
899                 break;
900         case 0x10:
901                 sprintf(buf+len, "Parallel SCSI\n");
902                 break;
903         case 0x20:
904                 sprintf(buf+len, "SSA\n");
905                 break;
906         case 0x30:
907                 sprintf(buf+len, "IEEE 1394\n");
908                 break;
909         case 0x40:
910                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
911                                 " Protocol\n");
912                 break;
913         case 0x50:
914                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
915                 break;
916         case 0x60:
917                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
918                 break;
919         case 0x70:
920                 sprintf(buf+len, "Automation/Drive Interface Transport"
921                                 " Protocol\n");
922                 break;
923         case 0x80:
924                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
925                 break;
926         default:
927                 sprintf(buf+len, "Unknown 0x%02x\n",
928                                 vpd->protocol_identifier);
929                 break;
930         }
931
932         if (p_buf)
933                 strncpy(p_buf, buf, p_buf_len);
934         else
935                 pr_debug("%s", buf);
936 }
937
938 void
939 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
940 {
941         /*
942          * Check if the Protocol Identifier Valid (PIV) bit is set..
943          *
944          * from spc3r23.pdf section 7.5.1
945          */
946          if (page_83[1] & 0x80) {
947                 vpd->protocol_identifier = (page_83[0] & 0xf0);
948                 vpd->protocol_identifier_set = 1;
949                 transport_dump_vpd_proto_id(vpd, NULL, 0);
950         }
951 }
952 EXPORT_SYMBOL(transport_set_vpd_proto_id);
953
954 int transport_dump_vpd_assoc(
955         struct t10_vpd *vpd,
956         unsigned char *p_buf,
957         int p_buf_len)
958 {
959         unsigned char buf[VPD_TMP_BUF_SIZE];
960         int ret = 0;
961         int len;
962
963         memset(buf, 0, VPD_TMP_BUF_SIZE);
964         len = sprintf(buf, "T10 VPD Identifier Association: ");
965
966         switch (vpd->association) {
967         case 0x00:
968                 sprintf(buf+len, "addressed logical unit\n");
969                 break;
970         case 0x10:
971                 sprintf(buf+len, "target port\n");
972                 break;
973         case 0x20:
974                 sprintf(buf+len, "SCSI target device\n");
975                 break;
976         default:
977                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
978                 ret = -EINVAL;
979                 break;
980         }
981
982         if (p_buf)
983                 strncpy(p_buf, buf, p_buf_len);
984         else
985                 pr_debug("%s", buf);
986
987         return ret;
988 }
989
990 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
991 {
992         /*
993          * The VPD identification association..
994          *
995          * from spc3r23.pdf Section 7.6.3.1 Table 297
996          */
997         vpd->association = (page_83[1] & 0x30);
998         return transport_dump_vpd_assoc(vpd, NULL, 0);
999 }
1000 EXPORT_SYMBOL(transport_set_vpd_assoc);
1001
1002 int transport_dump_vpd_ident_type(
1003         struct t10_vpd *vpd,
1004         unsigned char *p_buf,
1005         int p_buf_len)
1006 {
1007         unsigned char buf[VPD_TMP_BUF_SIZE];
1008         int ret = 0;
1009         int len;
1010
1011         memset(buf, 0, VPD_TMP_BUF_SIZE);
1012         len = sprintf(buf, "T10 VPD Identifier Type: ");
1013
1014         switch (vpd->device_identifier_type) {
1015         case 0x00:
1016                 sprintf(buf+len, "Vendor specific\n");
1017                 break;
1018         case 0x01:
1019                 sprintf(buf+len, "T10 Vendor ID based\n");
1020                 break;
1021         case 0x02:
1022                 sprintf(buf+len, "EUI-64 based\n");
1023                 break;
1024         case 0x03:
1025                 sprintf(buf+len, "NAA\n");
1026                 break;
1027         case 0x04:
1028                 sprintf(buf+len, "Relative target port identifier\n");
1029                 break;
1030         case 0x08:
1031                 sprintf(buf+len, "SCSI name string\n");
1032                 break;
1033         default:
1034                 sprintf(buf+len, "Unsupported: 0x%02x\n",
1035                                 vpd->device_identifier_type);
1036                 ret = -EINVAL;
1037                 break;
1038         }
1039
1040         if (p_buf) {
1041                 if (p_buf_len < strlen(buf)+1)
1042                         return -EINVAL;
1043                 strncpy(p_buf, buf, p_buf_len);
1044         } else {
1045                 pr_debug("%s", buf);
1046         }
1047
1048         return ret;
1049 }
1050
1051 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1052 {
1053         /*
1054          * The VPD identifier type..
1055          *
1056          * from spc3r23.pdf Section 7.6.3.1 Table 298
1057          */
1058         vpd->device_identifier_type = (page_83[1] & 0x0f);
1059         return transport_dump_vpd_ident_type(vpd, NULL, 0);
1060 }
1061 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1062
1063 int transport_dump_vpd_ident(
1064         struct t10_vpd *vpd,
1065         unsigned char *p_buf,
1066         int p_buf_len)
1067 {
1068         unsigned char buf[VPD_TMP_BUF_SIZE];
1069         int ret = 0;
1070
1071         memset(buf, 0, VPD_TMP_BUF_SIZE);
1072
1073         switch (vpd->device_identifier_code_set) {
1074         case 0x01: /* Binary */
1075                 sprintf(buf, "T10 VPD Binary Device Identifier: %s\n",
1076                         &vpd->device_identifier[0]);
1077                 break;
1078         case 0x02: /* ASCII */
1079                 sprintf(buf, "T10 VPD ASCII Device Identifier: %s\n",
1080                         &vpd->device_identifier[0]);
1081                 break;
1082         case 0x03: /* UTF-8 */
1083                 sprintf(buf, "T10 VPD UTF-8 Device Identifier: %s\n",
1084                         &vpd->device_identifier[0]);
1085                 break;
1086         default:
1087                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1088                         " 0x%02x", vpd->device_identifier_code_set);
1089                 ret = -EINVAL;
1090                 break;
1091         }
1092
1093         if (p_buf)
1094                 strncpy(p_buf, buf, p_buf_len);
1095         else
1096                 pr_debug("%s", buf);
1097
1098         return ret;
1099 }
1100
1101 int
1102 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1103 {
1104         static const char hex_str[] = "0123456789abcdef";
1105         int j = 0, i = 4; /* offset to start of the identifer */
1106
1107         /*
1108          * The VPD Code Set (encoding)
1109          *
1110          * from spc3r23.pdf Section 7.6.3.1 Table 296
1111          */
1112         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1113         switch (vpd->device_identifier_code_set) {
1114         case 0x01: /* Binary */
1115                 vpd->device_identifier[j++] =
1116                                 hex_str[vpd->device_identifier_type];
1117                 while (i < (4 + page_83[3])) {
1118                         vpd->device_identifier[j++] =
1119                                 hex_str[(page_83[i] & 0xf0) >> 4];
1120                         vpd->device_identifier[j++] =
1121                                 hex_str[page_83[i] & 0x0f];
1122                         i++;
1123                 }
1124                 break;
1125         case 0x02: /* ASCII */
1126         case 0x03: /* UTF-8 */
1127                 while (i < (4 + page_83[3]))
1128                         vpd->device_identifier[j++] = page_83[i++];
1129                 break;
1130         default:
1131                 break;
1132         }
1133
1134         return transport_dump_vpd_ident(vpd, NULL, 0);
1135 }
1136 EXPORT_SYMBOL(transport_set_vpd_ident);
1137
1138 static void core_setup_task_attr_emulation(struct se_device *dev)
1139 {
1140         /*
1141          * If this device is from Target_Core_Mod/pSCSI, disable the
1142          * SAM Task Attribute emulation.
1143          *
1144          * This is currently not available in upsream Linux/SCSI Target
1145          * mode code, and is assumed to be disabled while using TCM/pSCSI.
1146          */
1147         if (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) {
1148                 dev->dev_task_attr_type = SAM_TASK_ATTR_PASSTHROUGH;
1149                 return;
1150         }
1151
1152         dev->dev_task_attr_type = SAM_TASK_ATTR_EMULATED;
1153         pr_debug("%s: Using SAM_TASK_ATTR_EMULATED for SPC: 0x%02x"
1154                 " device\n", dev->transport->name,
1155                 dev->transport->get_device_rev(dev));
1156 }
1157
1158 static void scsi_dump_inquiry(struct se_device *dev)
1159 {
1160         struct t10_wwn *wwn = &dev->se_sub_dev->t10_wwn;
1161         char buf[17];
1162         int i, device_type;
1163         /*
1164          * Print Linux/SCSI style INQUIRY formatting to the kernel ring buffer
1165          */
1166         for (i = 0; i < 8; i++)
1167                 if (wwn->vendor[i] >= 0x20)
1168                         buf[i] = wwn->vendor[i];
1169                 else
1170                         buf[i] = ' ';
1171         buf[i] = '\0';
1172         pr_debug("  Vendor: %s\n", buf);
1173
1174         for (i = 0; i < 16; i++)
1175                 if (wwn->model[i] >= 0x20)
1176                         buf[i] = wwn->model[i];
1177                 else
1178                         buf[i] = ' ';
1179         buf[i] = '\0';
1180         pr_debug("  Model: %s\n", buf);
1181
1182         for (i = 0; i < 4; i++)
1183                 if (wwn->revision[i] >= 0x20)
1184                         buf[i] = wwn->revision[i];
1185                 else
1186                         buf[i] = ' ';
1187         buf[i] = '\0';
1188         pr_debug("  Revision: %s\n", buf);
1189
1190         device_type = dev->transport->get_device_type(dev);
1191         pr_debug("  Type:   %s ", scsi_device_type(device_type));
1192         pr_debug("                 ANSI SCSI revision: %02x\n",
1193                                 dev->transport->get_device_rev(dev));
1194 }
1195
1196 struct se_device *transport_add_device_to_core_hba(
1197         struct se_hba *hba,
1198         struct se_subsystem_api *transport,
1199         struct se_subsystem_dev *se_dev,
1200         u32 device_flags,
1201         void *transport_dev,
1202         struct se_dev_limits *dev_limits,
1203         const char *inquiry_prod,
1204         const char *inquiry_rev)
1205 {
1206         int force_pt;
1207         struct se_device  *dev;
1208
1209         dev = kzalloc(sizeof(struct se_device), GFP_KERNEL);
1210         if (!dev) {
1211                 pr_err("Unable to allocate memory for se_dev_t\n");
1212                 return NULL;
1213         }
1214
1215         transport_init_queue_obj(&dev->dev_queue_obj);
1216         dev->dev_flags          = device_flags;
1217         dev->dev_status         |= TRANSPORT_DEVICE_DEACTIVATED;
1218         dev->dev_ptr            = transport_dev;
1219         dev->se_hba             = hba;
1220         dev->se_sub_dev         = se_dev;
1221         dev->transport          = transport;
1222         INIT_LIST_HEAD(&dev->dev_list);
1223         INIT_LIST_HEAD(&dev->dev_sep_list);
1224         INIT_LIST_HEAD(&dev->dev_tmr_list);
1225         INIT_LIST_HEAD(&dev->execute_list);
1226         INIT_LIST_HEAD(&dev->delayed_cmd_list);
1227         INIT_LIST_HEAD(&dev->state_list);
1228         INIT_LIST_HEAD(&dev->qf_cmd_list);
1229         spin_lock_init(&dev->execute_task_lock);
1230         spin_lock_init(&dev->delayed_cmd_lock);
1231         spin_lock_init(&dev->dev_reservation_lock);
1232         spin_lock_init(&dev->dev_status_lock);
1233         spin_lock_init(&dev->se_port_lock);
1234         spin_lock_init(&dev->se_tmr_lock);
1235         spin_lock_init(&dev->qf_cmd_lock);
1236         atomic_set(&dev->dev_ordered_id, 0);
1237
1238         se_dev_set_default_attribs(dev, dev_limits);
1239
1240         dev->dev_index = scsi_get_new_index(SCSI_DEVICE_INDEX);
1241         dev->creation_time = get_jiffies_64();
1242         spin_lock_init(&dev->stats_lock);
1243
1244         spin_lock(&hba->device_lock);
1245         list_add_tail(&dev->dev_list, &hba->hba_dev_list);
1246         hba->dev_count++;
1247         spin_unlock(&hba->device_lock);
1248         /*
1249          * Setup the SAM Task Attribute emulation for struct se_device
1250          */
1251         core_setup_task_attr_emulation(dev);
1252         /*
1253          * Force PR and ALUA passthrough emulation with internal object use.
1254          */
1255         force_pt = (hba->hba_flags & HBA_FLAGS_INTERNAL_USE);
1256         /*
1257          * Setup the Reservations infrastructure for struct se_device
1258          */
1259         core_setup_reservations(dev, force_pt);
1260         /*
1261          * Setup the Asymmetric Logical Unit Assignment for struct se_device
1262          */
1263         if (core_setup_alua(dev, force_pt) < 0)
1264                 goto out;
1265
1266         /*
1267          * Startup the struct se_device processing thread
1268          */
1269         dev->process_thread = kthread_run(transport_processing_thread, dev,
1270                                           "LIO_%s", dev->transport->name);
1271         if (IS_ERR(dev->process_thread)) {
1272                 pr_err("Unable to create kthread: LIO_%s\n",
1273                         dev->transport->name);
1274                 goto out;
1275         }
1276         /*
1277          * Setup work_queue for QUEUE_FULL
1278          */
1279         INIT_WORK(&dev->qf_work_queue, target_qf_do_work);
1280         /*
1281          * Preload the initial INQUIRY const values if we are doing
1282          * anything virtual (IBLOCK, FILEIO, RAMDISK), but not for TCM/pSCSI
1283          * passthrough because this is being provided by the backend LLD.
1284          * This is required so that transport_get_inquiry() copies these
1285          * originals once back into DEV_T10_WWN(dev) for the virtual device
1286          * setup.
1287          */
1288         if (dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
1289                 if (!inquiry_prod || !inquiry_rev) {
1290                         pr_err("All non TCM/pSCSI plugins require"
1291                                 " INQUIRY consts\n");
1292                         goto out;
1293                 }
1294
1295                 strncpy(&dev->se_sub_dev->t10_wwn.vendor[0], "LIO-ORG", 8);
1296                 strncpy(&dev->se_sub_dev->t10_wwn.model[0], inquiry_prod, 16);
1297                 strncpy(&dev->se_sub_dev->t10_wwn.revision[0], inquiry_rev, 4);
1298         }
1299         scsi_dump_inquiry(dev);
1300
1301         return dev;
1302 out:
1303         kthread_stop(dev->process_thread);
1304
1305         spin_lock(&hba->device_lock);
1306         list_del(&dev->dev_list);
1307         hba->dev_count--;
1308         spin_unlock(&hba->device_lock);
1309
1310         se_release_vpd_for_dev(dev);
1311
1312         kfree(dev);
1313
1314         return NULL;
1315 }
1316 EXPORT_SYMBOL(transport_add_device_to_core_hba);
1317
1318 /*      transport_generic_prepare_cdb():
1319  *
1320  *      Since the Initiator sees iSCSI devices as LUNs,  the SCSI CDB will
1321  *      contain the iSCSI LUN in bits 7-5 of byte 1 as per SAM-2.
1322  *      The point of this is since we are mapping iSCSI LUNs to
1323  *      SCSI Target IDs having a non-zero LUN in the CDB will throw the
1324  *      devices and HBAs for a loop.
1325  */
1326 static inline void transport_generic_prepare_cdb(
1327         unsigned char *cdb)
1328 {
1329         switch (cdb[0]) {
1330         case READ_10: /* SBC - RDProtect */
1331         case READ_12: /* SBC - RDProtect */
1332         case READ_16: /* SBC - RDProtect */
1333         case SEND_DIAGNOSTIC: /* SPC - SELF-TEST Code */
1334         case VERIFY: /* SBC - VRProtect */
1335         case VERIFY_16: /* SBC - VRProtect */
1336         case WRITE_VERIFY: /* SBC - VRProtect */
1337         case WRITE_VERIFY_12: /* SBC - VRProtect */
1338         case MAINTENANCE_IN: /* SPC - Parameter Data Format for SA RTPG */
1339                 break;
1340         default:
1341                 cdb[1] &= 0x1f; /* clear logical unit number */
1342                 break;
1343         }
1344 }
1345
1346 int target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1347 {
1348         struct se_device *dev = cmd->se_dev;
1349
1350         if (cmd->unknown_data_length) {
1351                 cmd->data_length = size;
1352         } else if (size != cmd->data_length) {
1353                 pr_warn("TARGET_CORE[%s]: Expected Transfer Length:"
1354                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1355                         " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
1356                                 cmd->data_length, size, cmd->t_task_cdb[0]);
1357
1358                 cmd->cmd_spdtl = size;
1359
1360                 if (cmd->data_direction == DMA_TO_DEVICE) {
1361                         pr_err("Rejecting underflow/overflow"
1362                                         " WRITE data\n");
1363                         goto out_invalid_cdb_field;
1364                 }
1365                 /*
1366                  * Reject READ_* or WRITE_* with overflow/underflow for
1367                  * type SCF_SCSI_DATA_CDB.
1368                  */
1369                 if (dev->se_sub_dev->se_dev_attrib.block_size != 512)  {
1370                         pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
1371                                 " CDB on non 512-byte sector setup subsystem"
1372                                 " plugin: %s\n", dev->transport->name);
1373                         /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
1374                         goto out_invalid_cdb_field;
1375                 }
1376
1377                 if (size > cmd->data_length) {
1378                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1379                         cmd->residual_count = (size - cmd->data_length);
1380                 } else {
1381                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1382                         cmd->residual_count = (cmd->data_length - size);
1383                 }
1384                 cmd->data_length = size;
1385         }
1386
1387         return 0;
1388
1389 out_invalid_cdb_field:
1390         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1391         cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1392         return -EINVAL;
1393 }
1394
1395 /*
1396  * Used by fabric modules containing a local struct se_cmd within their
1397  * fabric dependent per I/O descriptor.
1398  */
1399 void transport_init_se_cmd(
1400         struct se_cmd *cmd,
1401         struct target_core_fabric_ops *tfo,
1402         struct se_session *se_sess,
1403         u32 data_length,
1404         int data_direction,
1405         int task_attr,
1406         unsigned char *sense_buffer)
1407 {
1408         INIT_LIST_HEAD(&cmd->se_lun_node);
1409         INIT_LIST_HEAD(&cmd->se_delayed_node);
1410         INIT_LIST_HEAD(&cmd->se_qf_node);
1411         INIT_LIST_HEAD(&cmd->se_queue_node);
1412         INIT_LIST_HEAD(&cmd->se_cmd_list);
1413         INIT_LIST_HEAD(&cmd->execute_list);
1414         INIT_LIST_HEAD(&cmd->state_list);
1415         init_completion(&cmd->transport_lun_fe_stop_comp);
1416         init_completion(&cmd->transport_lun_stop_comp);
1417         init_completion(&cmd->t_transport_stop_comp);
1418         init_completion(&cmd->cmd_wait_comp);
1419         init_completion(&cmd->task_stop_comp);
1420         spin_lock_init(&cmd->t_state_lock);
1421         cmd->transport_state = CMD_T_DEV_ACTIVE;
1422
1423         cmd->se_tfo = tfo;
1424         cmd->se_sess = se_sess;
1425         cmd->data_length = data_length;
1426         cmd->data_direction = data_direction;
1427         cmd->sam_task_attr = task_attr;
1428         cmd->sense_buffer = sense_buffer;
1429
1430         cmd->state_active = false;
1431 }
1432 EXPORT_SYMBOL(transport_init_se_cmd);
1433
1434 static int transport_check_alloc_task_attr(struct se_cmd *cmd)
1435 {
1436         /*
1437          * Check if SAM Task Attribute emulation is enabled for this
1438          * struct se_device storage object
1439          */
1440         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1441                 return 0;
1442
1443         if (cmd->sam_task_attr == MSG_ACA_TAG) {
1444                 pr_debug("SAM Task Attribute ACA"
1445                         " emulation is not supported\n");
1446                 return -EINVAL;
1447         }
1448         /*
1449          * Used to determine when ORDERED commands should go from
1450          * Dormant to Active status.
1451          */
1452         cmd->se_ordered_id = atomic_inc_return(&cmd->se_dev->dev_ordered_id);
1453         smp_mb__after_atomic_inc();
1454         pr_debug("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n",
1455                         cmd->se_ordered_id, cmd->sam_task_attr,
1456                         cmd->se_dev->transport->name);
1457         return 0;
1458 }
1459
1460 /*      target_setup_cmd_from_cdb():
1461  *
1462  *      Called from fabric RX Thread.
1463  */
1464 int target_setup_cmd_from_cdb(
1465         struct se_cmd *cmd,
1466         unsigned char *cdb)
1467 {
1468         struct se_subsystem_dev *su_dev = cmd->se_dev->se_sub_dev;
1469         u32 pr_reg_type = 0;
1470         u8 alua_ascq = 0;
1471         unsigned long flags;
1472         int ret;
1473
1474         transport_generic_prepare_cdb(cdb);
1475         /*
1476          * Ensure that the received CDB is less than the max (252 + 8) bytes
1477          * for VARIABLE_LENGTH_CMD
1478          */
1479         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1480                 pr_err("Received SCSI CDB with command_size: %d that"
1481                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1482                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1483                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1484                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1485                 return -EINVAL;
1486         }
1487         /*
1488          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1489          * allocate the additional extended CDB buffer now..  Otherwise
1490          * setup the pointer from __t_task_cdb to t_task_cdb.
1491          */
1492         if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1493                 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1494                                                 GFP_KERNEL);
1495                 if (!cmd->t_task_cdb) {
1496                         pr_err("Unable to allocate cmd->t_task_cdb"
1497                                 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1498                                 scsi_command_size(cdb),
1499                                 (unsigned long)sizeof(cmd->__t_task_cdb));
1500                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1501                         cmd->scsi_sense_reason =
1502                                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1503                         return -ENOMEM;
1504                 }
1505         } else
1506                 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1507         /*
1508          * Copy the original CDB into cmd->
1509          */
1510         memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1511
1512         /*
1513          * Check for an existing UNIT ATTENTION condition
1514          */
1515         if (core_scsi3_ua_check(cmd, cdb) < 0) {
1516                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1517                 cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
1518                 return -EINVAL;
1519         }
1520
1521         ret = su_dev->t10_alua.alua_state_check(cmd, cdb, &alua_ascq);
1522         if (ret != 0) {
1523                 /*
1524                  * Set SCSI additional sense code (ASC) to 'LUN Not Accessible';
1525                  * The ALUA additional sense code qualifier (ASCQ) is determined
1526                  * by the ALUA primary or secondary access state..
1527                  */
1528                 if (ret > 0) {
1529                         pr_debug("[%s]: ALUA TG Port not available, "
1530                                 "SenseKey: NOT_READY, ASC/ASCQ: "
1531                                 "0x04/0x%02x\n",
1532                                 cmd->se_tfo->get_fabric_name(), alua_ascq);
1533
1534                         transport_set_sense_codes(cmd, 0x04, alua_ascq);
1535                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1536                         cmd->scsi_sense_reason = TCM_CHECK_CONDITION_NOT_READY;
1537                         return -EINVAL;
1538                 }
1539                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1540                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1541                 return -EINVAL;
1542         }
1543
1544         /*
1545          * Check status for SPC-3 Persistent Reservations
1546          */
1547         if (su_dev->t10_pr.pr_ops.t10_reservation_check(cmd, &pr_reg_type)) {
1548                 if (su_dev->t10_pr.pr_ops.t10_seq_non_holder(
1549                                         cmd, cdb, pr_reg_type) != 0) {
1550                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1551                         cmd->se_cmd_flags |= SCF_SCSI_RESERVATION_CONFLICT;
1552                         cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1553                         cmd->scsi_sense_reason = TCM_RESERVATION_CONFLICT;
1554                         return -EBUSY;
1555                 }
1556                 /*
1557                  * This means the CDB is allowed for the SCSI Initiator port
1558                  * when said port is *NOT* holding the legacy SPC-2 or
1559                  * SPC-3 Persistent Reservation.
1560                  */
1561         }
1562
1563         ret = cmd->se_dev->transport->parse_cdb(cmd);
1564         if (ret < 0)
1565                 return ret;
1566
1567         spin_lock_irqsave(&cmd->t_state_lock, flags);
1568         cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1569         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1570
1571         /*
1572          * Check for SAM Task Attribute Emulation
1573          */
1574         if (transport_check_alloc_task_attr(cmd) < 0) {
1575                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1576                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1577                 return -EINVAL;
1578         }
1579         spin_lock(&cmd->se_lun->lun_sep_lock);
1580         if (cmd->se_lun->lun_sep)
1581                 cmd->se_lun->lun_sep->sep_stats.cmd_pdus++;
1582         spin_unlock(&cmd->se_lun->lun_sep_lock);
1583         return 0;
1584 }
1585 EXPORT_SYMBOL(target_setup_cmd_from_cdb);
1586
1587 /*
1588  * Used by fabric module frontends to queue tasks directly.
1589  * Many only be used from process context only
1590  */
1591 int transport_handle_cdb_direct(
1592         struct se_cmd *cmd)
1593 {
1594         int ret;
1595
1596         if (!cmd->se_lun) {
1597                 dump_stack();
1598                 pr_err("cmd->se_lun is NULL\n");
1599                 return -EINVAL;
1600         }
1601         if (in_interrupt()) {
1602                 dump_stack();
1603                 pr_err("transport_generic_handle_cdb cannot be called"
1604                                 " from interrupt context\n");
1605                 return -EINVAL;
1606         }
1607         /*
1608          * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE following
1609          * transport_generic_handle_cdb*() -> transport_add_cmd_to_queue()
1610          * in existing usage to ensure that outstanding descriptors are handled
1611          * correctly during shutdown via transport_wait_for_tasks()
1612          *
1613          * Also, we don't take cmd->t_state_lock here as we only expect
1614          * this to be called for initial descriptor submission.
1615          */
1616         cmd->t_state = TRANSPORT_NEW_CMD;
1617         cmd->transport_state |= CMD_T_ACTIVE;
1618
1619         /*
1620          * transport_generic_new_cmd() is already handling QUEUE_FULL,
1621          * so follow TRANSPORT_NEW_CMD processing thread context usage
1622          * and call transport_generic_request_failure() if necessary..
1623          */
1624         ret = transport_generic_new_cmd(cmd);
1625         if (ret < 0)
1626                 transport_generic_request_failure(cmd);
1627
1628         return 0;
1629 }
1630 EXPORT_SYMBOL(transport_handle_cdb_direct);
1631
1632 /**
1633  * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1634  *
1635  * @se_cmd: command descriptor to submit
1636  * @se_sess: associated se_sess for endpoint
1637  * @cdb: pointer to SCSI CDB
1638  * @sense: pointer to SCSI sense buffer
1639  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1640  * @data_length: fabric expected data transfer length
1641  * @task_addr: SAM task attribute
1642  * @data_dir: DMA data direction
1643  * @flags: flags for command submission from target_sc_flags_tables
1644  *
1645  * This may only be called from process context, and also currently
1646  * assumes internal allocation of fabric payload buffer by target-core.
1647  **/
1648 void target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1649                 unsigned char *cdb, unsigned char *sense, u32 unpacked_lun,
1650                 u32 data_length, int task_attr, int data_dir, int flags)
1651 {
1652         struct se_portal_group *se_tpg;
1653         int rc;
1654
1655         se_tpg = se_sess->se_tpg;
1656         BUG_ON(!se_tpg);
1657         BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1658         BUG_ON(in_interrupt());
1659         /*
1660          * Initialize se_cmd for target operation.  From this point
1661          * exceptions are handled by sending exception status via
1662          * target_core_fabric_ops->queue_status() callback
1663          */
1664         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1665                                 data_length, data_dir, task_attr, sense);
1666         if (flags & TARGET_SCF_UNKNOWN_SIZE)
1667                 se_cmd->unknown_data_length = 1;
1668         /*
1669          * Obtain struct se_cmd->cmd_kref reference and add new cmd to
1670          * se_sess->sess_cmd_list.  A second kref_get here is necessary
1671          * for fabrics using TARGET_SCF_ACK_KREF that expect a second
1672          * kref_put() to happen during fabric packet acknowledgement.
1673          */
1674         target_get_sess_cmd(se_sess, se_cmd, (flags & TARGET_SCF_ACK_KREF));
1675         /*
1676          * Signal bidirectional data payloads to target-core
1677          */
1678         if (flags & TARGET_SCF_BIDI_OP)
1679                 se_cmd->se_cmd_flags |= SCF_BIDI;
1680         /*
1681          * Locate se_lun pointer and attach it to struct se_cmd
1682          */
1683         if (transport_lookup_cmd_lun(se_cmd, unpacked_lun) < 0) {
1684                 transport_send_check_condition_and_sense(se_cmd,
1685                                 se_cmd->scsi_sense_reason, 0);
1686                 target_put_sess_cmd(se_sess, se_cmd);
1687                 return;
1688         }
1689
1690         rc = target_setup_cmd_from_cdb(se_cmd, cdb);
1691         if (rc != 0) {
1692                 transport_generic_request_failure(se_cmd);
1693                 return;
1694         }
1695
1696         /*
1697          * Check if we need to delay processing because of ALUA
1698          * Active/NonOptimized primary access state..
1699          */
1700         core_alua_check_nonop_delay(se_cmd);
1701
1702         /*
1703          * Dispatch se_cmd descriptor to se_lun->lun_se_dev backend
1704          * for immediate execution of READs, otherwise wait for
1705          * transport_generic_handle_data() to be called for WRITEs
1706          * when fabric has filled the incoming buffer.
1707          */
1708         transport_handle_cdb_direct(se_cmd);
1709         return;
1710 }
1711 EXPORT_SYMBOL(target_submit_cmd);
1712
1713 static void target_complete_tmr_failure(struct work_struct *work)
1714 {
1715         struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1716
1717         se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1718         se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1719         transport_generic_free_cmd(se_cmd, 0);
1720 }
1721
1722 /**
1723  * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1724  *                     for TMR CDBs
1725  *
1726  * @se_cmd: command descriptor to submit
1727  * @se_sess: associated se_sess for endpoint
1728  * @sense: pointer to SCSI sense buffer
1729  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1730  * @fabric_context: fabric context for TMR req
1731  * @tm_type: Type of TM request
1732  * @gfp: gfp type for caller
1733  * @tag: referenced task tag for TMR_ABORT_TASK
1734  * @flags: submit cmd flags
1735  *
1736  * Callable from all contexts.
1737  **/
1738
1739 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1740                 unsigned char *sense, u32 unpacked_lun,
1741                 void *fabric_tmr_ptr, unsigned char tm_type,
1742                 gfp_t gfp, unsigned int tag, int flags)
1743 {
1744         struct se_portal_group *se_tpg;
1745         int ret;
1746
1747         se_tpg = se_sess->se_tpg;
1748         BUG_ON(!se_tpg);
1749
1750         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1751                               0, DMA_NONE, MSG_SIMPLE_TAG, sense);
1752         /*
1753          * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1754          * allocation failure.
1755          */
1756         ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1757         if (ret < 0)
1758                 return -ENOMEM;
1759
1760         if (tm_type == TMR_ABORT_TASK)
1761                 se_cmd->se_tmr_req->ref_task_tag = tag;
1762
1763         /* See target_submit_cmd for commentary */
1764         target_get_sess_cmd(se_sess, se_cmd, (flags & TARGET_SCF_ACK_KREF));
1765
1766         ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun);
1767         if (ret) {
1768                 /*
1769                  * For callback during failure handling, push this work off
1770                  * to process context with TMR_LUN_DOES_NOT_EXIST status.
1771                  */
1772                 INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1773                 schedule_work(&se_cmd->work);
1774                 return 0;
1775         }
1776         transport_generic_handle_tmr(se_cmd);
1777         return 0;
1778 }
1779 EXPORT_SYMBOL(target_submit_tmr);
1780
1781 /*
1782  * Used by fabric module frontends defining a TFO->new_cmd_map() caller
1783  * to  queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD_MAP in order to
1784  * complete setup in TCM process context w/ TFO->new_cmd_map().
1785  */
1786 int transport_generic_handle_cdb_map(
1787         struct se_cmd *cmd)
1788 {
1789         if (!cmd->se_lun) {
1790                 dump_stack();
1791                 pr_err("cmd->se_lun is NULL\n");
1792                 return -EINVAL;
1793         }
1794
1795         transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD_MAP, false);
1796         return 0;
1797 }
1798 EXPORT_SYMBOL(transport_generic_handle_cdb_map);
1799
1800 /*      transport_generic_handle_data():
1801  *
1802  *
1803  */
1804 int transport_generic_handle_data(
1805         struct se_cmd *cmd)
1806 {
1807         /*
1808          * For the software fabric case, then we assume the nexus is being
1809          * failed/shutdown when signals are pending from the kthread context
1810          * caller, so we return a failure.  For the HW target mode case running
1811          * in interrupt code, the signal_pending() check is skipped.
1812          */
1813         if (!in_interrupt() && signal_pending(current))
1814                 return -EPERM;
1815         /*
1816          * If the received CDB has aleady been ABORTED by the generic
1817          * target engine, we now call transport_check_aborted_status()
1818          * to queue any delated TASK_ABORTED status for the received CDB to the
1819          * fabric module as we are expecting no further incoming DATA OUT
1820          * sequences at this point.
1821          */
1822         if (transport_check_aborted_status(cmd, 1) != 0)
1823                 return 0;
1824
1825         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_WRITE, false);
1826         return 0;
1827 }
1828 EXPORT_SYMBOL(transport_generic_handle_data);
1829
1830 /*      transport_generic_handle_tmr():
1831  *
1832  *
1833  */
1834 int transport_generic_handle_tmr(
1835         struct se_cmd *cmd)
1836 {
1837         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_TMR, false);
1838         return 0;
1839 }
1840 EXPORT_SYMBOL(transport_generic_handle_tmr);
1841
1842 /*
1843  * If the cmd is active, request it to be stopped and sleep until it
1844  * has completed.
1845  */
1846 bool target_stop_cmd(struct se_cmd *cmd, unsigned long *flags)
1847 {
1848         bool was_active = false;
1849
1850         if (cmd->transport_state & CMD_T_BUSY) {
1851                 cmd->transport_state |= CMD_T_REQUEST_STOP;
1852                 spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
1853
1854                 pr_debug("cmd %p waiting to complete\n", cmd);
1855                 wait_for_completion(&cmd->task_stop_comp);
1856                 pr_debug("cmd %p stopped successfully\n", cmd);
1857
1858                 spin_lock_irqsave(&cmd->t_state_lock, *flags);
1859                 cmd->transport_state &= ~CMD_T_REQUEST_STOP;
1860                 cmd->transport_state &= ~CMD_T_BUSY;
1861                 was_active = true;
1862         }
1863
1864         return was_active;
1865 }
1866
1867 /*
1868  * Handle SAM-esque emulation for generic transport request failures.
1869  */
1870 void transport_generic_request_failure(struct se_cmd *cmd)
1871 {
1872         int ret = 0;
1873
1874         pr_debug("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
1875                 " CDB: 0x%02x\n", cmd, cmd->se_tfo->get_task_tag(cmd),
1876                 cmd->t_task_cdb[0]);
1877         pr_debug("-----[ i_state: %d t_state: %d scsi_sense_reason: %d\n",
1878                 cmd->se_tfo->get_cmd_state(cmd),
1879                 cmd->t_state, cmd->scsi_sense_reason);
1880         pr_debug("-----[ CMD_T_ACTIVE: %d CMD_T_STOP: %d CMD_T_SENT: %d\n",
1881                 (cmd->transport_state & CMD_T_ACTIVE) != 0,
1882                 (cmd->transport_state & CMD_T_STOP) != 0,
1883                 (cmd->transport_state & CMD_T_SENT) != 0);
1884
1885         /*
1886          * For SAM Task Attribute emulation for failed struct se_cmd
1887          */
1888         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1889                 transport_complete_task_attr(cmd);
1890
1891         switch (cmd->scsi_sense_reason) {
1892         case TCM_NON_EXISTENT_LUN:
1893         case TCM_UNSUPPORTED_SCSI_OPCODE:
1894         case TCM_INVALID_CDB_FIELD:
1895         case TCM_INVALID_PARAMETER_LIST:
1896         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1897         case TCM_UNKNOWN_MODE_PAGE:
1898         case TCM_WRITE_PROTECTED:
1899         case TCM_CHECK_CONDITION_ABORT_CMD:
1900         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1901         case TCM_CHECK_CONDITION_NOT_READY:
1902                 break;
1903         case TCM_RESERVATION_CONFLICT:
1904                 /*
1905                  * No SENSE Data payload for this case, set SCSI Status
1906                  * and queue the response to $FABRIC_MOD.
1907                  *
1908                  * Uses linux/include/scsi/scsi.h SAM status codes defs
1909                  */
1910                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1911                 /*
1912                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1913                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1914                  * CONFLICT STATUS.
1915                  *
1916                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1917                  */
1918                 if (cmd->se_sess &&
1919                     cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
1920                         core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
1921                                 cmd->orig_fe_lun, 0x2C,
1922                                 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1923
1924                 ret = cmd->se_tfo->queue_status(cmd);
1925                 if (ret == -EAGAIN || ret == -ENOMEM)
1926                         goto queue_full;
1927                 goto check_stop;
1928         default:
1929                 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1930                         cmd->t_task_cdb[0], cmd->scsi_sense_reason);
1931                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1932                 break;
1933         }
1934         /*
1935          * If a fabric does not define a cmd->se_tfo->new_cmd_map caller,
1936          * make the call to transport_send_check_condition_and_sense()
1937          * directly.  Otherwise expect the fabric to make the call to
1938          * transport_send_check_condition_and_sense() after handling
1939          * possible unsoliticied write data payloads.
1940          */
1941         ret = transport_send_check_condition_and_sense(cmd,
1942                         cmd->scsi_sense_reason, 0);
1943         if (ret == -EAGAIN || ret == -ENOMEM)
1944                 goto queue_full;
1945
1946 check_stop:
1947         transport_lun_remove_cmd(cmd);
1948         if (!transport_cmd_check_stop_to_fabric(cmd))
1949                 ;
1950         return;
1951
1952 queue_full:
1953         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
1954         transport_handle_queue_full(cmd, cmd->se_dev);
1955 }
1956 EXPORT_SYMBOL(transport_generic_request_failure);
1957
1958 /*
1959  * Called from Fabric Module context from transport_execute_tasks()
1960  *
1961  * The return of this function determins if the tasks from struct se_cmd
1962  * get added to the execution queue in transport_execute_tasks(),
1963  * or are added to the delayed or ordered lists here.
1964  */
1965 static inline int transport_execute_task_attr(struct se_cmd *cmd)
1966 {
1967         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1968                 return 1;
1969         /*
1970          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
1971          * to allow the passed struct se_cmd list of tasks to the front of the list.
1972          */
1973          if (cmd->sam_task_attr == MSG_HEAD_TAG) {
1974                 pr_debug("Added HEAD_OF_QUEUE for CDB:"
1975                         " 0x%02x, se_ordered_id: %u\n",
1976                         cmd->t_task_cdb[0],
1977                         cmd->se_ordered_id);
1978                 return 1;
1979         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
1980                 atomic_inc(&cmd->se_dev->dev_ordered_sync);
1981                 smp_mb__after_atomic_inc();
1982
1983                 pr_debug("Added ORDERED for CDB: 0x%02x to ordered"
1984                                 " list, se_ordered_id: %u\n",
1985                                 cmd->t_task_cdb[0],
1986                                 cmd->se_ordered_id);
1987                 /*
1988                  * Add ORDERED command to tail of execution queue if
1989                  * no other older commands exist that need to be
1990                  * completed first.
1991                  */
1992                 if (!atomic_read(&cmd->se_dev->simple_cmds))
1993                         return 1;
1994         } else {
1995                 /*
1996                  * For SIMPLE and UNTAGGED Task Attribute commands
1997                  */
1998                 atomic_inc(&cmd->se_dev->simple_cmds);
1999                 smp_mb__after_atomic_inc();
2000         }
2001         /*
2002          * Otherwise if one or more outstanding ORDERED task attribute exist,
2003          * add the dormant task(s) built for the passed struct se_cmd to the
2004          * execution queue and become in Active state for this struct se_device.
2005          */
2006         if (atomic_read(&cmd->se_dev->dev_ordered_sync) != 0) {
2007                 /*
2008                  * Otherwise, add cmd w/ tasks to delayed cmd queue that
2009                  * will be drained upon completion of HEAD_OF_QUEUE task.
2010                  */
2011                 spin_lock(&cmd->se_dev->delayed_cmd_lock);
2012                 cmd->se_cmd_flags |= SCF_DELAYED_CMD_FROM_SAM_ATTR;
2013                 list_add_tail(&cmd->se_delayed_node,
2014                                 &cmd->se_dev->delayed_cmd_list);
2015                 spin_unlock(&cmd->se_dev->delayed_cmd_lock);
2016
2017                 pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to"
2018                         " delayed CMD list, se_ordered_id: %u\n",
2019                         cmd->t_task_cdb[0], cmd->sam_task_attr,
2020                         cmd->se_ordered_id);
2021                 /*
2022                  * Return zero to let transport_execute_tasks() know
2023                  * not to add the delayed tasks to the execution list.
2024                  */
2025                 return 0;
2026         }
2027         /*
2028          * Otherwise, no ORDERED task attributes exist..
2029          */
2030         return 1;
2031 }
2032
2033 /*
2034  * Called from fabric module context in transport_generic_new_cmd() and
2035  * transport_generic_process_write()
2036  */
2037 static void transport_execute_tasks(struct se_cmd *cmd)
2038 {
2039         int add_tasks;
2040         struct se_device *se_dev = cmd->se_dev;
2041         /*
2042          * Call transport_cmd_check_stop() to see if a fabric exception
2043          * has occurred that prevents execution.
2044          */
2045         if (!transport_cmd_check_stop(cmd, 0, TRANSPORT_PROCESSING)) {
2046                 /*
2047                  * Check for SAM Task Attribute emulation and HEAD_OF_QUEUE
2048                  * attribute for the tasks of the received struct se_cmd CDB
2049                  */
2050                 add_tasks = transport_execute_task_attr(cmd);
2051                 if (add_tasks) {
2052                         __transport_execute_tasks(se_dev, cmd);
2053                         return;
2054                 }
2055         }
2056         __transport_execute_tasks(se_dev, NULL);
2057 }
2058
2059 static int __transport_execute_tasks(struct se_device *dev, struct se_cmd *new_cmd)
2060 {
2061         int error;
2062         struct se_cmd *cmd = NULL;
2063         unsigned long flags;
2064
2065 check_depth:
2066         spin_lock_irq(&dev->execute_task_lock);
2067         if (new_cmd != NULL)
2068                 __target_add_to_execute_list(new_cmd);
2069
2070         if (list_empty(&dev->execute_list)) {
2071                 spin_unlock_irq(&dev->execute_task_lock);
2072                 return 0;
2073         }
2074         cmd = list_first_entry(&dev->execute_list, struct se_cmd, execute_list);
2075         __target_remove_from_execute_list(cmd);
2076         spin_unlock_irq(&dev->execute_task_lock);
2077
2078         spin_lock_irqsave(&cmd->t_state_lock, flags);
2079         cmd->transport_state |= CMD_T_BUSY;
2080         cmd->transport_state |= CMD_T_SENT;
2081
2082         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2083
2084         if (cmd->execute_cmd)
2085                 error = cmd->execute_cmd(cmd);
2086         else {
2087                 error = dev->transport->execute_cmd(cmd, cmd->t_data_sg,
2088                                 cmd->t_data_nents, cmd->data_direction);
2089         }
2090
2091         if (error != 0) {
2092                 spin_lock_irqsave(&cmd->t_state_lock, flags);
2093                 cmd->transport_state &= ~CMD_T_BUSY;
2094                 cmd->transport_state &= ~CMD_T_SENT;
2095                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2096
2097                 transport_generic_request_failure(cmd);
2098         }
2099
2100         new_cmd = NULL;
2101         goto check_depth;
2102
2103         return 0;
2104 }
2105
2106 /*
2107  * Used to obtain Sense Data from underlying Linux/SCSI struct scsi_cmnd
2108  */
2109 static int transport_get_sense_data(struct se_cmd *cmd)
2110 {
2111         unsigned char *buffer = cmd->sense_buffer, *sense_buffer = NULL;
2112         struct se_device *dev = cmd->se_dev;
2113         unsigned long flags;
2114         u32 offset = 0;
2115
2116         WARN_ON(!cmd->se_lun);
2117
2118         if (!dev)
2119                 return 0;
2120
2121         spin_lock_irqsave(&cmd->t_state_lock, flags);
2122         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
2123                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2124                 return 0;
2125         }
2126
2127         if (!(cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE))
2128                 goto out;
2129
2130         if (!dev->transport->get_sense_buffer) {
2131                 pr_err("dev->transport->get_sense_buffer is NULL\n");
2132                 goto out;
2133         }
2134
2135         sense_buffer = dev->transport->get_sense_buffer(cmd);
2136         if (!sense_buffer) {
2137                 pr_err("ITT 0x%08x cmd %p: Unable to locate"
2138                         " sense buffer for task with sense\n",
2139                         cmd->se_tfo->get_task_tag(cmd), cmd);
2140                 goto out;
2141         }
2142
2143         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2144
2145         offset = cmd->se_tfo->set_fabric_sense_len(cmd, TRANSPORT_SENSE_BUFFER);
2146
2147         memcpy(&buffer[offset], sense_buffer, TRANSPORT_SENSE_BUFFER);
2148
2149         /* Automatically padded */
2150         cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER + offset;
2151
2152         pr_debug("HBA_[%u]_PLUG[%s]: Set SAM STATUS: 0x%02x and sense\n",
2153                 dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
2154         return 0;
2155
2156 out:
2157         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2158         return -1;
2159 }
2160
2161 /*
2162  * Called from I/O completion to determine which dormant/delayed
2163  * and ordered cmds need to have their tasks added to the execution queue.
2164  */
2165 static void transport_complete_task_attr(struct se_cmd *cmd)
2166 {
2167         struct se_device *dev = cmd->se_dev;
2168         struct se_cmd *cmd_p, *cmd_tmp;
2169         int new_active_tasks = 0;
2170
2171         if (cmd->sam_task_attr == MSG_SIMPLE_TAG) {
2172                 atomic_dec(&dev->simple_cmds);
2173                 smp_mb__after_atomic_dec();
2174                 dev->dev_cur_ordered_id++;
2175                 pr_debug("Incremented dev->dev_cur_ordered_id: %u for"
2176                         " SIMPLE: %u\n", dev->dev_cur_ordered_id,
2177                         cmd->se_ordered_id);
2178         } else if (cmd->sam_task_attr == MSG_HEAD_TAG) {
2179                 dev->dev_cur_ordered_id++;
2180                 pr_debug("Incremented dev_cur_ordered_id: %u for"
2181                         " HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id,
2182                         cmd->se_ordered_id);
2183         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
2184                 atomic_dec(&dev->dev_ordered_sync);
2185                 smp_mb__after_atomic_dec();
2186
2187                 dev->dev_cur_ordered_id++;
2188                 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED:"
2189                         " %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id);
2190         }
2191         /*
2192          * Process all commands up to the last received
2193          * ORDERED task attribute which requires another blocking
2194          * boundary
2195          */
2196         spin_lock(&dev->delayed_cmd_lock);
2197         list_for_each_entry_safe(cmd_p, cmd_tmp,
2198                         &dev->delayed_cmd_list, se_delayed_node) {
2199
2200                 list_del(&cmd_p->se_delayed_node);
2201                 spin_unlock(&dev->delayed_cmd_lock);
2202
2203                 pr_debug("Calling add_tasks() for"
2204                         " cmd_p: 0x%02x Task Attr: 0x%02x"
2205                         " Dormant -> Active, se_ordered_id: %u\n",
2206                         cmd_p->t_task_cdb[0],
2207                         cmd_p->sam_task_attr, cmd_p->se_ordered_id);
2208
2209                 target_add_to_execute_list(cmd_p);
2210                 new_active_tasks++;
2211
2212                 spin_lock(&dev->delayed_cmd_lock);
2213                 if (cmd_p->sam_task_attr == MSG_ORDERED_TAG)
2214                         break;
2215         }
2216         spin_unlock(&dev->delayed_cmd_lock);
2217         /*
2218          * If new tasks have become active, wake up the transport thread
2219          * to do the processing of the Active tasks.
2220          */
2221         if (new_active_tasks != 0)
2222                 wake_up_interruptible(&dev->dev_queue_obj.thread_wq);
2223 }
2224
2225 static void transport_complete_qf(struct se_cmd *cmd)
2226 {
2227         int ret = 0;
2228
2229         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
2230                 transport_complete_task_attr(cmd);
2231
2232         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2233                 ret = cmd->se_tfo->queue_status(cmd);
2234                 if (ret)
2235                         goto out;
2236         }
2237
2238         switch (cmd->data_direction) {
2239         case DMA_FROM_DEVICE:
2240                 ret = cmd->se_tfo->queue_data_in(cmd);
2241                 break;
2242         case DMA_TO_DEVICE:
2243                 if (cmd->t_bidi_data_sg) {
2244                         ret = cmd->se_tfo->queue_data_in(cmd);
2245                         if (ret < 0)
2246                                 break;
2247                 }
2248                 /* Fall through for DMA_TO_DEVICE */
2249         case DMA_NONE:
2250                 ret = cmd->se_tfo->queue_status(cmd);
2251                 break;
2252         default:
2253                 break;
2254         }
2255
2256 out:
2257         if (ret < 0) {
2258                 transport_handle_queue_full(cmd, cmd->se_dev);
2259                 return;
2260         }
2261         transport_lun_remove_cmd(cmd);
2262         transport_cmd_check_stop_to_fabric(cmd);
2263 }
2264
2265 static void transport_handle_queue_full(
2266         struct se_cmd *cmd,
2267         struct se_device *dev)
2268 {
2269         spin_lock_irq(&dev->qf_cmd_lock);
2270         list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
2271         atomic_inc(&dev->dev_qf_count);
2272         smp_mb__after_atomic_inc();
2273         spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
2274
2275         schedule_work(&cmd->se_dev->qf_work_queue);
2276 }
2277
2278 static void target_complete_ok_work(struct work_struct *work)
2279 {
2280         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
2281         int reason = 0, ret;
2282
2283         /*
2284          * Check if we need to move delayed/dormant tasks from cmds on the
2285          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
2286          * Attribute.
2287          */
2288         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
2289                 transport_complete_task_attr(cmd);
2290         /*
2291          * Check to schedule QUEUE_FULL work, or execute an existing
2292          * cmd->transport_qf_callback()
2293          */
2294         if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
2295                 schedule_work(&cmd->se_dev->qf_work_queue);
2296
2297         /*
2298          * Check if we need to retrieve a sense buffer from
2299          * the struct se_cmd in question.
2300          */
2301         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2302                 if (transport_get_sense_data(cmd) < 0)
2303                         reason = TCM_NON_EXISTENT_LUN;
2304
2305                 if (cmd->scsi_status) {
2306                         ret = transport_send_check_condition_and_sense(
2307                                         cmd, reason, 1);
2308                         if (ret == -EAGAIN || ret == -ENOMEM)
2309                                 goto queue_full;
2310
2311                         transport_lun_remove_cmd(cmd);
2312                         transport_cmd_check_stop_to_fabric(cmd);
2313                         return;
2314                 }
2315         }
2316         /*
2317          * Check for a callback, used by amongst other things
2318          * XDWRITE_READ_10 emulation.
2319          */
2320         if (cmd->transport_complete_callback)
2321                 cmd->transport_complete_callback(cmd);
2322
2323         switch (cmd->data_direction) {
2324         case DMA_FROM_DEVICE:
2325                 spin_lock(&cmd->se_lun->lun_sep_lock);
2326                 if (cmd->se_lun->lun_sep) {
2327                         cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
2328                                         cmd->data_length;
2329                 }
2330                 spin_unlock(&cmd->se_lun->lun_sep_lock);
2331
2332                 ret = cmd->se_tfo->queue_data_in(cmd);
2333                 if (ret == -EAGAIN || ret == -ENOMEM)
2334                         goto queue_full;
2335                 break;
2336         case DMA_TO_DEVICE:
2337                 spin_lock(&cmd->se_lun->lun_sep_lock);
2338                 if (cmd->se_lun->lun_sep) {
2339                         cmd->se_lun->lun_sep->sep_stats.rx_data_octets +=
2340                                 cmd->data_length;
2341                 }
2342                 spin_unlock(&cmd->se_lun->lun_sep_lock);
2343                 /*
2344                  * Check if we need to send READ payload for BIDI-COMMAND
2345                  */
2346                 if (cmd->t_bidi_data_sg) {
2347                         spin_lock(&cmd->se_lun->lun_sep_lock);
2348                         if (cmd->se_lun->lun_sep) {
2349                                 cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
2350                                         cmd->data_length;
2351                         }
2352                         spin_unlock(&cmd->se_lun->lun_sep_lock);
2353                         ret = cmd->se_tfo->queue_data_in(cmd);
2354                         if (ret == -EAGAIN || ret == -ENOMEM)
2355                                 goto queue_full;
2356                         break;
2357                 }
2358                 /* Fall through for DMA_TO_DEVICE */
2359         case DMA_NONE:
2360                 ret = cmd->se_tfo->queue_status(cmd);
2361                 if (ret == -EAGAIN || ret == -ENOMEM)
2362                         goto queue_full;
2363                 break;
2364         default:
2365                 break;
2366         }
2367
2368         transport_lun_remove_cmd(cmd);
2369         transport_cmd_check_stop_to_fabric(cmd);
2370         return;
2371
2372 queue_full:
2373         pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2374                 " data_direction: %d\n", cmd, cmd->data_direction);
2375         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
2376         transport_handle_queue_full(cmd, cmd->se_dev);
2377 }
2378
2379 static inline void transport_free_sgl(struct scatterlist *sgl, int nents)
2380 {
2381         struct scatterlist *sg;
2382         int count;
2383
2384         for_each_sg(sgl, sg, nents, count)
2385                 __free_page(sg_page(sg));
2386
2387         kfree(sgl);
2388 }
2389
2390 static inline void transport_free_pages(struct se_cmd *cmd)
2391 {
2392         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)
2393                 return;
2394
2395         transport_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2396         cmd->t_data_sg = NULL;
2397         cmd->t_data_nents = 0;
2398
2399         transport_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2400         cmd->t_bidi_data_sg = NULL;
2401         cmd->t_bidi_data_nents = 0;
2402 }
2403
2404 /**
2405  * transport_release_cmd - free a command
2406  * @cmd:       command to free
2407  *
2408  * This routine unconditionally frees a command, and reference counting
2409  * or list removal must be done in the caller.
2410  */
2411 static void transport_release_cmd(struct se_cmd *cmd)
2412 {
2413         BUG_ON(!cmd->se_tfo);
2414
2415         if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2416                 core_tmr_release_req(cmd->se_tmr_req);
2417         if (cmd->t_task_cdb != cmd->__t_task_cdb)
2418                 kfree(cmd->t_task_cdb);
2419         /*
2420          * If this cmd has been setup with target_get_sess_cmd(), drop
2421          * the kref and call ->release_cmd() in kref callback.
2422          */
2423          if (cmd->check_release != 0) {
2424                 target_put_sess_cmd(cmd->se_sess, cmd);
2425                 return;
2426         }
2427         cmd->se_tfo->release_cmd(cmd);
2428 }
2429
2430 /**
2431  * transport_put_cmd - release a reference to a command
2432  * @cmd:       command to release
2433  *
2434  * This routine releases our reference to the command and frees it if possible.
2435  */
2436 static void transport_put_cmd(struct se_cmd *cmd)
2437 {
2438         unsigned long flags;
2439
2440         spin_lock_irqsave(&cmd->t_state_lock, flags);
2441         if (atomic_read(&cmd->t_fe_count)) {
2442                 if (!atomic_dec_and_test(&cmd->t_fe_count))
2443                         goto out_busy;
2444         }
2445
2446         if (cmd->transport_state & CMD_T_DEV_ACTIVE) {
2447                 cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
2448                 target_remove_from_state_list(cmd);
2449         }
2450         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2451
2452         transport_free_pages(cmd);
2453         transport_release_cmd(cmd);
2454         return;
2455 out_busy:
2456         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2457 }
2458
2459 /*
2460  * transport_generic_map_mem_to_cmd - Use fabric-alloced pages instead of
2461  * allocating in the core.
2462  * @cmd:  Associated se_cmd descriptor
2463  * @mem:  SGL style memory for TCM WRITE / READ
2464  * @sg_mem_num: Number of SGL elements
2465  * @mem_bidi_in: SGL style memory for TCM BIDI READ
2466  * @sg_mem_bidi_num: Number of BIDI READ SGL elements
2467  *
2468  * Return: nonzero return cmd was rejected for -ENOMEM or inproper usage
2469  * of parameters.
2470  */
2471 int transport_generic_map_mem_to_cmd(
2472         struct se_cmd *cmd,
2473         struct scatterlist *sgl,
2474         u32 sgl_count,
2475         struct scatterlist *sgl_bidi,
2476         u32 sgl_bidi_count)
2477 {
2478         if (!sgl || !sgl_count)
2479                 return 0;
2480
2481         /*
2482          * Reject SCSI data overflow with map_mem_to_cmd() as incoming
2483          * scatterlists already have been set to follow what the fabric
2484          * passes for the original expected data transfer length.
2485          */
2486         if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
2487                 pr_warn("Rejecting SCSI DATA overflow for fabric using"
2488                         " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
2489                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2490                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
2491                 return -EINVAL;
2492         }
2493
2494         cmd->t_data_sg = sgl;
2495         cmd->t_data_nents = sgl_count;
2496
2497         if (sgl_bidi && sgl_bidi_count) {
2498                 cmd->t_bidi_data_sg = sgl_bidi;
2499                 cmd->t_bidi_data_nents = sgl_bidi_count;
2500         }
2501         cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
2502         return 0;
2503 }
2504 EXPORT_SYMBOL(transport_generic_map_mem_to_cmd);
2505
2506 void *transport_kmap_data_sg(struct se_cmd *cmd)
2507 {
2508         struct scatterlist *sg = cmd->t_data_sg;
2509         struct page **pages;
2510         int i;
2511
2512         BUG_ON(!sg);
2513         /*
2514          * We need to take into account a possible offset here for fabrics like
2515          * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2516          * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2517          */
2518         if (!cmd->t_data_nents)
2519                 return NULL;
2520         else if (cmd->t_data_nents == 1)
2521                 return kmap(sg_page(sg)) + sg->offset;
2522
2523         /* >1 page. use vmap */
2524         pages = kmalloc(sizeof(*pages) * cmd->t_data_nents, GFP_KERNEL);
2525         if (!pages)
2526                 return NULL;
2527
2528         /* convert sg[] to pages[] */
2529         for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2530                 pages[i] = sg_page(sg);
2531         }
2532
2533         cmd->t_data_vmap = vmap(pages, cmd->t_data_nents,  VM_MAP, PAGE_KERNEL);
2534         kfree(pages);
2535         if (!cmd->t_data_vmap)
2536                 return NULL;
2537
2538         return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2539 }
2540 EXPORT_SYMBOL(transport_kmap_data_sg);
2541
2542 void transport_kunmap_data_sg(struct se_cmd *cmd)
2543 {
2544         if (!cmd->t_data_nents) {
2545                 return;
2546         } else if (cmd->t_data_nents == 1) {
2547                 kunmap(sg_page(cmd->t_data_sg));
2548                 return;
2549         }
2550
2551         vunmap(cmd->t_data_vmap);
2552         cmd->t_data_vmap = NULL;
2553 }
2554 EXPORT_SYMBOL(transport_kunmap_data_sg);
2555
2556 static int
2557 transport_generic_get_mem(struct se_cmd *cmd)
2558 {
2559         u32 length = cmd->data_length;
2560         unsigned int nents;
2561         struct page *page;
2562         gfp_t zero_flag;
2563         int i = 0;
2564
2565         nents = DIV_ROUND_UP(length, PAGE_SIZE);
2566         cmd->t_data_sg = kmalloc(sizeof(struct scatterlist) * nents, GFP_KERNEL);
2567         if (!cmd->t_data_sg)
2568                 return -ENOMEM;
2569
2570         cmd->t_data_nents = nents;
2571         sg_init_table(cmd->t_data_sg, nents);
2572
2573         zero_flag = cmd->se_cmd_flags & SCF_SCSI_DATA_CDB ? 0 : __GFP_ZERO;
2574
2575         while (length) {
2576                 u32 page_len = min_t(u32, length, PAGE_SIZE);
2577                 page = alloc_page(GFP_KERNEL | zero_flag);
2578                 if (!page)
2579                         goto out;
2580
2581                 sg_set_page(&cmd->t_data_sg[i], page, page_len, 0);
2582                 length -= page_len;
2583                 i++;
2584         }
2585         return 0;
2586
2587 out:
2588         while (i >= 0) {
2589                 __free_page(sg_page(&cmd->t_data_sg[i]));
2590                 i--;
2591         }
2592         kfree(cmd->t_data_sg);
2593         cmd->t_data_sg = NULL;
2594         return -ENOMEM;
2595 }
2596
2597 /*
2598  * Allocate any required resources to execute the command.  For writes we
2599  * might not have the payload yet, so notify the fabric via a call to
2600  * ->write_pending instead. Otherwise place it on the execution queue.
2601  */
2602 int transport_generic_new_cmd(struct se_cmd *cmd)
2603 {
2604         int ret = 0;
2605
2606         /*
2607          * Determine is the TCM fabric module has already allocated physical
2608          * memory, and is directly calling transport_generic_map_mem_to_cmd()
2609          * beforehand.
2610          */
2611         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2612             cmd->data_length) {
2613                 ret = transport_generic_get_mem(cmd);
2614                 if (ret < 0)
2615                         goto out_fail;
2616         }
2617
2618         /* Workaround for handling zero-length control CDBs */
2619         if (!(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) && !cmd->data_length) {
2620                 spin_lock_irq(&cmd->t_state_lock);
2621                 cmd->t_state = TRANSPORT_COMPLETE;
2622                 cmd->transport_state |= CMD_T_ACTIVE;
2623                 spin_unlock_irq(&cmd->t_state_lock);
2624
2625                 if (cmd->t_task_cdb[0] == REQUEST_SENSE) {
2626                         u8 ua_asc = 0, ua_ascq = 0;
2627
2628                         core_scsi3_ua_clear_for_request_sense(cmd,
2629                                         &ua_asc, &ua_ascq);
2630                 }
2631
2632                 INIT_WORK(&cmd->work, target_complete_ok_work);
2633                 queue_work(target_completion_wq, &cmd->work);
2634                 return 0;
2635         }
2636
2637         atomic_inc(&cmd->t_fe_count);
2638
2639         /*
2640          * For WRITEs, let the fabric know its buffer is ready.
2641          *
2642          * The command will be added to the execution queue after its write
2643          * data has arrived.
2644          */
2645         if (cmd->data_direction == DMA_TO_DEVICE) {
2646                 target_add_to_state_list(cmd);
2647                 return transport_generic_write_pending(cmd);
2648         }
2649         /*
2650          * Everything else but a WRITE, add the command to the execution queue.
2651          */
2652         transport_execute_tasks(cmd);
2653         return 0;
2654
2655 out_fail:
2656         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2657         cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2658         return -EINVAL;
2659 }
2660 EXPORT_SYMBOL(transport_generic_new_cmd);
2661
2662 /*      transport_generic_process_write():
2663  *
2664  *
2665  */
2666 void transport_generic_process_write(struct se_cmd *cmd)
2667 {
2668         transport_execute_tasks(cmd);
2669 }
2670 EXPORT_SYMBOL(transport_generic_process_write);
2671
2672 static void transport_write_pending_qf(struct se_cmd *cmd)
2673 {
2674         int ret;
2675
2676         ret = cmd->se_tfo->write_pending(cmd);
2677         if (ret == -EAGAIN || ret == -ENOMEM) {
2678                 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2679                          cmd);
2680                 transport_handle_queue_full(cmd, cmd->se_dev);
2681         }
2682 }
2683
2684 static int transport_generic_write_pending(struct se_cmd *cmd)
2685 {
2686         unsigned long flags;
2687         int ret;
2688
2689         spin_lock_irqsave(&cmd->t_state_lock, flags);
2690         cmd->t_state = TRANSPORT_WRITE_PENDING;
2691         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2692
2693         /*
2694          * Clear the se_cmd for WRITE_PENDING status in order to set
2695          * CMD_T_ACTIVE so that transport_generic_handle_data can be called
2696          * from HW target mode interrupt code.  This is safe to be called
2697          * with transport_off=1 before the cmd->se_tfo->write_pending
2698          * because the se_cmd->se_lun pointer is not being cleared.
2699          */
2700         transport_cmd_check_stop(cmd, 1, 0);
2701
2702         /*
2703          * Call the fabric write_pending function here to let the
2704          * frontend know that WRITE buffers are ready.
2705          */
2706         ret = cmd->se_tfo->write_pending(cmd);
2707         if (ret == -EAGAIN || ret == -ENOMEM)
2708                 goto queue_full;
2709         else if (ret < 0)
2710                 return ret;
2711
2712         return 1;
2713
2714 queue_full:
2715         pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2716         cmd->t_state = TRANSPORT_COMPLETE_QF_WP;
2717         transport_handle_queue_full(cmd, cmd->se_dev);
2718         return 0;
2719 }
2720
2721 void transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2722 {
2723         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD)) {
2724                 if (wait_for_tasks && (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
2725                          transport_wait_for_tasks(cmd);
2726
2727                 transport_release_cmd(cmd);
2728         } else {
2729                 if (wait_for_tasks)
2730                         transport_wait_for_tasks(cmd);
2731
2732                 core_dec_lacl_count(cmd->se_sess->se_node_acl, cmd);
2733
2734                 if (cmd->se_lun)
2735                         transport_lun_remove_cmd(cmd);
2736
2737                 transport_put_cmd(cmd);
2738         }
2739 }
2740 EXPORT_SYMBOL(transport_generic_free_cmd);
2741
2742 /* target_get_sess_cmd - Add command to active ->sess_cmd_list
2743  * @se_sess:    session to reference
2744  * @se_cmd:     command descriptor to add
2745  * @ack_kref:   Signal that fabric will perform an ack target_put_sess_cmd()
2746  */
2747 void target_get_sess_cmd(struct se_session *se_sess, struct se_cmd *se_cmd,
2748                         bool ack_kref)
2749 {
2750         unsigned long flags;
2751
2752         kref_init(&se_cmd->cmd_kref);
2753         /*
2754          * Add a second kref if the fabric caller is expecting to handle
2755          * fabric acknowledgement that requires two target_put_sess_cmd()
2756          * invocations before se_cmd descriptor release.
2757          */
2758         if (ack_kref == true) {
2759                 kref_get(&se_cmd->cmd_kref);
2760                 se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2761         }
2762
2763         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2764         list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list);
2765         se_cmd->check_release = 1;
2766         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2767 }
2768 EXPORT_SYMBOL(target_get_sess_cmd);
2769
2770 static void target_release_cmd_kref(struct kref *kref)
2771 {
2772         struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2773         struct se_session *se_sess = se_cmd->se_sess;
2774         unsigned long flags;
2775
2776         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2777         if (list_empty(&se_cmd->se_cmd_list)) {
2778                 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2779                 se_cmd->se_tfo->release_cmd(se_cmd);
2780                 return;
2781         }
2782         if (se_sess->sess_tearing_down && se_cmd->cmd_wait_set) {
2783                 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2784                 complete(&se_cmd->cmd_wait_comp);
2785                 return;
2786         }
2787         list_del(&se_cmd->se_cmd_list);
2788         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2789
2790         se_cmd->se_tfo->release_cmd(se_cmd);
2791 }
2792
2793 /* target_put_sess_cmd - Check for active I/O shutdown via kref_put
2794  * @se_sess:    session to reference
2795  * @se_cmd:     command descriptor to drop
2796  */
2797 int target_put_sess_cmd(struct se_session *se_sess, struct se_cmd *se_cmd)
2798 {
2799         return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2800 }
2801 EXPORT_SYMBOL(target_put_sess_cmd);
2802
2803 /* target_splice_sess_cmd_list - Split active cmds into sess_wait_list
2804  * @se_sess:    session to split
2805  */
2806 void target_splice_sess_cmd_list(struct se_session *se_sess)
2807 {
2808         struct se_cmd *se_cmd;
2809         unsigned long flags;
2810
2811         WARN_ON(!list_empty(&se_sess->sess_wait_list));
2812         INIT_LIST_HEAD(&se_sess->sess_wait_list);
2813
2814         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2815         se_sess->sess_tearing_down = 1;
2816
2817         list_splice_init(&se_sess->sess_cmd_list, &se_sess->sess_wait_list);
2818
2819         list_for_each_entry(se_cmd, &se_sess->sess_wait_list, se_cmd_list)
2820                 se_cmd->cmd_wait_set = 1;
2821
2822         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2823 }
2824 EXPORT_SYMBOL(target_splice_sess_cmd_list);
2825
2826 /* target_wait_for_sess_cmds - Wait for outstanding descriptors
2827  * @se_sess:    session to wait for active I/O
2828  * @wait_for_tasks:     Make extra transport_wait_for_tasks call
2829  */
2830 void target_wait_for_sess_cmds(
2831         struct se_session *se_sess,
2832         int wait_for_tasks)
2833 {
2834         struct se_cmd *se_cmd, *tmp_cmd;
2835         bool rc = false;
2836
2837         list_for_each_entry_safe(se_cmd, tmp_cmd,
2838                                 &se_sess->sess_wait_list, se_cmd_list) {
2839                 list_del(&se_cmd->se_cmd_list);
2840
2841                 pr_debug("Waiting for se_cmd: %p t_state: %d, fabric state:"
2842                         " %d\n", se_cmd, se_cmd->t_state,
2843                         se_cmd->se_tfo->get_cmd_state(se_cmd));
2844
2845                 if (wait_for_tasks) {
2846                         pr_debug("Calling transport_wait_for_tasks se_cmd: %p t_state: %d,"
2847                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
2848                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
2849
2850                         rc = transport_wait_for_tasks(se_cmd);
2851
2852                         pr_debug("After transport_wait_for_tasks se_cmd: %p t_state: %d,"
2853                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
2854                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
2855                 }
2856
2857                 if (!rc) {
2858                         wait_for_completion(&se_cmd->cmd_wait_comp);
2859                         pr_debug("After cmd_wait_comp: se_cmd: %p t_state: %d"
2860                                 " fabric state: %d\n", se_cmd, se_cmd->t_state,
2861                                 se_cmd->se_tfo->get_cmd_state(se_cmd));
2862                 }
2863
2864                 se_cmd->se_tfo->release_cmd(se_cmd);
2865         }
2866 }
2867 EXPORT_SYMBOL(target_wait_for_sess_cmds);
2868
2869 /*      transport_lun_wait_for_tasks():
2870  *
2871  *      Called from ConfigFS context to stop the passed struct se_cmd to allow
2872  *      an struct se_lun to be successfully shutdown.
2873  */
2874 static int transport_lun_wait_for_tasks(struct se_cmd *cmd, struct se_lun *lun)
2875 {
2876         unsigned long flags;
2877         int ret = 0;
2878
2879         /*
2880          * If the frontend has already requested this struct se_cmd to
2881          * be stopped, we can safely ignore this struct se_cmd.
2882          */
2883         spin_lock_irqsave(&cmd->t_state_lock, flags);
2884         if (cmd->transport_state & CMD_T_STOP) {
2885                 cmd->transport_state &= ~CMD_T_LUN_STOP;
2886
2887                 pr_debug("ConfigFS ITT[0x%08x] - CMD_T_STOP, skipping\n",
2888                          cmd->se_tfo->get_task_tag(cmd));
2889                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2890                 transport_cmd_check_stop(cmd, 1, 0);
2891                 return -EPERM;
2892         }
2893         cmd->transport_state |= CMD_T_LUN_FE_STOP;
2894         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2895
2896         wake_up_interruptible(&cmd->se_dev->dev_queue_obj.thread_wq);
2897
2898         // XXX: audit task_flags checks.
2899         spin_lock_irqsave(&cmd->t_state_lock, flags);
2900         if ((cmd->transport_state & CMD_T_BUSY) &&
2901             (cmd->transport_state & CMD_T_SENT)) {
2902                 if (!target_stop_cmd(cmd, &flags))
2903                         ret++;
2904                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2905         } else {
2906                 spin_unlock_irqrestore(&cmd->t_state_lock,
2907                                 flags);
2908                 target_remove_from_execute_list(cmd);
2909         }
2910
2911         pr_debug("ConfigFS: cmd: %p stop tasks ret:"
2912                         " %d\n", cmd, ret);
2913         if (!ret) {
2914                 pr_debug("ConfigFS: ITT[0x%08x] - stopping cmd....\n",
2915                                 cmd->se_tfo->get_task_tag(cmd));
2916                 wait_for_completion(&cmd->transport_lun_stop_comp);
2917                 pr_debug("ConfigFS: ITT[0x%08x] - stopped cmd....\n",
2918                                 cmd->se_tfo->get_task_tag(cmd));
2919         }
2920         transport_remove_cmd_from_queue(cmd);
2921
2922         return 0;
2923 }
2924
2925 static void __transport_clear_lun_from_sessions(struct se_lun *lun)
2926 {
2927         struct se_cmd *cmd = NULL;
2928         unsigned long lun_flags, cmd_flags;
2929         /*
2930          * Do exception processing and return CHECK_CONDITION status to the
2931          * Initiator Port.
2932          */
2933         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2934         while (!list_empty(&lun->lun_cmd_list)) {
2935                 cmd = list_first_entry(&lun->lun_cmd_list,
2936                        struct se_cmd, se_lun_node);
2937                 list_del_init(&cmd->se_lun_node);
2938
2939                 /*
2940                  * This will notify iscsi_target_transport.c:
2941                  * transport_cmd_check_stop() that a LUN shutdown is in
2942                  * progress for the iscsi_cmd_t.
2943                  */
2944                 spin_lock(&cmd->t_state_lock);
2945                 pr_debug("SE_LUN[%d] - Setting cmd->transport"
2946                         "_lun_stop for  ITT: 0x%08x\n",
2947                         cmd->se_lun->unpacked_lun,
2948                         cmd->se_tfo->get_task_tag(cmd));
2949                 cmd->transport_state |= CMD_T_LUN_STOP;
2950                 spin_unlock(&cmd->t_state_lock);
2951
2952                 spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
2953
2954                 if (!cmd->se_lun) {
2955                         pr_err("ITT: 0x%08x, [i,t]_state: %u/%u\n",
2956                                 cmd->se_tfo->get_task_tag(cmd),
2957                                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
2958                         BUG();
2959                 }
2960                 /*
2961                  * If the Storage engine still owns the iscsi_cmd_t, determine
2962                  * and/or stop its context.
2963                  */
2964                 pr_debug("SE_LUN[%d] - ITT: 0x%08x before transport"
2965                         "_lun_wait_for_tasks()\n", cmd->se_lun->unpacked_lun,
2966                         cmd->se_tfo->get_task_tag(cmd));
2967
2968                 if (transport_lun_wait_for_tasks(cmd, cmd->se_lun) < 0) {
2969                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2970                         continue;
2971                 }
2972
2973                 pr_debug("SE_LUN[%d] - ITT: 0x%08x after transport_lun"
2974                         "_wait_for_tasks(): SUCCESS\n",
2975                         cmd->se_lun->unpacked_lun,
2976                         cmd->se_tfo->get_task_tag(cmd));
2977
2978                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
2979                 if (!(cmd->transport_state & CMD_T_DEV_ACTIVE)) {
2980                         spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
2981                         goto check_cond;
2982                 }
2983                 cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
2984                 target_remove_from_state_list(cmd);
2985                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
2986
2987                 /*
2988                  * The Storage engine stopped this struct se_cmd before it was
2989                  * send to the fabric frontend for delivery back to the
2990                  * Initiator Node.  Return this SCSI CDB back with an
2991                  * CHECK_CONDITION status.
2992                  */
2993 check_cond:
2994                 transport_send_check_condition_and_sense(cmd,
2995                                 TCM_NON_EXISTENT_LUN, 0);
2996                 /*
2997                  *  If the fabric frontend is waiting for this iscsi_cmd_t to
2998                  * be released, notify the waiting thread now that LU has
2999                  * finished accessing it.
3000                  */
3001                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
3002                 if (cmd->transport_state & CMD_T_LUN_FE_STOP) {
3003                         pr_debug("SE_LUN[%d] - Detected FE stop for"
3004                                 " struct se_cmd: %p ITT: 0x%08x\n",
3005                                 lun->unpacked_lun,
3006                                 cmd, cmd->se_tfo->get_task_tag(cmd));
3007
3008                         spin_unlock_irqrestore(&cmd->t_state_lock,
3009                                         cmd_flags);
3010                         transport_cmd_check_stop(cmd, 1, 0);
3011                         complete(&cmd->transport_lun_fe_stop_comp);
3012                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
3013                         continue;
3014                 }
3015                 pr_debug("SE_LUN[%d] - ITT: 0x%08x finished processing\n",
3016                         lun->unpacked_lun, cmd->se_tfo->get_task_tag(cmd));
3017
3018                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
3019                 spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
3020         }
3021         spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
3022 }
3023
3024 static int transport_clear_lun_thread(void *p)
3025 {
3026         struct se_lun *lun = p;
3027
3028         __transport_clear_lun_from_sessions(lun);
3029         complete(&lun->lun_shutdown_comp);
3030
3031         return 0;
3032 }
3033
3034 int transport_clear_lun_from_sessions(struct se_lun *lun)
3035 {
3036         struct task_struct *kt;
3037
3038         kt = kthread_run(transport_clear_lun_thread, lun,
3039                         "tcm_cl_%u", lun->unpacked_lun);
3040         if (IS_ERR(kt)) {
3041                 pr_err("Unable to start clear_lun thread\n");
3042                 return PTR_ERR(kt);
3043         }
3044         wait_for_completion(&lun->lun_shutdown_comp);
3045
3046         return 0;
3047 }
3048
3049 /**
3050  * transport_wait_for_tasks - wait for completion to occur
3051  * @cmd:        command to wait
3052  *
3053  * Called from frontend fabric context to wait for storage engine
3054  * to pause and/or release frontend generated struct se_cmd.
3055  */
3056 bool transport_wait_for_tasks(struct se_cmd *cmd)
3057 {
3058         unsigned long flags;
3059
3060         spin_lock_irqsave(&cmd->t_state_lock, flags);
3061         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
3062             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
3063                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3064                 return false;
3065         }
3066
3067         if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
3068             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
3069                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3070                 return false;
3071         }
3072         /*
3073          * If we are already stopped due to an external event (ie: LUN shutdown)
3074          * sleep until the connection can have the passed struct se_cmd back.
3075          * The cmd->transport_lun_stopped_sem will be upped by
3076          * transport_clear_lun_from_sessions() once the ConfigFS context caller
3077          * has completed its operation on the struct se_cmd.
3078          */
3079         if (cmd->transport_state & CMD_T_LUN_STOP) {
3080                 pr_debug("wait_for_tasks: Stopping"
3081                         " wait_for_completion(&cmd->t_tasktransport_lun_fe"
3082                         "_stop_comp); for ITT: 0x%08x\n",
3083                         cmd->se_tfo->get_task_tag(cmd));
3084                 /*
3085                  * There is a special case for WRITES where a FE exception +
3086                  * LUN shutdown means ConfigFS context is still sleeping on
3087                  * transport_lun_stop_comp in transport_lun_wait_for_tasks().
3088                  * We go ahead and up transport_lun_stop_comp just to be sure
3089                  * here.
3090                  */
3091                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3092                 complete(&cmd->transport_lun_stop_comp);
3093                 wait_for_completion(&cmd->transport_lun_fe_stop_comp);
3094                 spin_lock_irqsave(&cmd->t_state_lock, flags);
3095
3096                 target_remove_from_state_list(cmd);
3097                 /*
3098                  * At this point, the frontend who was the originator of this
3099                  * struct se_cmd, now owns the structure and can be released through
3100                  * normal means below.
3101                  */
3102                 pr_debug("wait_for_tasks: Stopped"
3103                         " wait_for_completion(&cmd->t_tasktransport_lun_fe_"
3104                         "stop_comp); for ITT: 0x%08x\n",
3105                         cmd->se_tfo->get_task_tag(cmd));
3106
3107                 cmd->transport_state &= ~CMD_T_LUN_STOP;
3108         }
3109
3110         if (!(cmd->transport_state & CMD_T_ACTIVE)) {
3111                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3112                 return false;
3113         }
3114
3115         cmd->transport_state |= CMD_T_STOP;
3116
3117         pr_debug("wait_for_tasks: Stopping %p ITT: 0x%08x"
3118                 " i_state: %d, t_state: %d, CMD_T_STOP\n",
3119                 cmd, cmd->se_tfo->get_task_tag(cmd),
3120                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
3121
3122         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3123
3124         wake_up_interruptible(&cmd->se_dev->dev_queue_obj.thread_wq);
3125
3126         wait_for_completion(&cmd->t_transport_stop_comp);
3127
3128         spin_lock_irqsave(&cmd->t_state_lock, flags);
3129         cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
3130
3131         pr_debug("wait_for_tasks: Stopped wait_for_compltion("
3132                 "&cmd->t_transport_stop_comp) for ITT: 0x%08x\n",
3133                 cmd->se_tfo->get_task_tag(cmd));
3134
3135         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3136
3137         return true;
3138 }
3139 EXPORT_SYMBOL(transport_wait_for_tasks);
3140
3141 static int transport_get_sense_codes(
3142         struct se_cmd *cmd,
3143         u8 *asc,
3144         u8 *ascq)
3145 {
3146         *asc = cmd->scsi_asc;
3147         *ascq = cmd->scsi_ascq;
3148
3149         return 0;
3150 }
3151
3152 static int transport_set_sense_codes(
3153         struct se_cmd *cmd,
3154         u8 asc,
3155         u8 ascq)
3156 {
3157         cmd->scsi_asc = asc;
3158         cmd->scsi_ascq = ascq;
3159
3160         return 0;
3161 }
3162
3163 int transport_send_check_condition_and_sense(
3164         struct se_cmd *cmd,
3165         u8 reason,
3166         int from_transport)
3167 {
3168         unsigned char *buffer = cmd->sense_buffer;
3169         unsigned long flags;
3170         int offset;
3171         u8 asc = 0, ascq = 0;
3172
3173         spin_lock_irqsave(&cmd->t_state_lock, flags);
3174         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3175                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3176                 return 0;
3177         }
3178         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
3179         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3180
3181         if (!reason && from_transport)
3182                 goto after_reason;
3183
3184         if (!from_transport)
3185                 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
3186         /*
3187          * Data Segment and SenseLength of the fabric response PDU.
3188          *
3189          * TRANSPORT_SENSE_BUFFER is now set to SCSI_SENSE_BUFFERSIZE
3190          * from include/scsi/scsi_cmnd.h
3191          */
3192         offset = cmd->se_tfo->set_fabric_sense_len(cmd,
3193                                 TRANSPORT_SENSE_BUFFER);
3194         /*
3195          * Actual SENSE DATA, see SPC-3 7.23.2  SPC_SENSE_KEY_OFFSET uses
3196          * SENSE KEY values from include/scsi/scsi.h
3197          */
3198         switch (reason) {
3199         case TCM_NON_EXISTENT_LUN:
3200                 /* CURRENT ERROR */
3201                 buffer[offset] = 0x70;
3202                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3203                 /* ILLEGAL REQUEST */
3204                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
3205                 /* LOGICAL UNIT NOT SUPPORTED */
3206                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x25;
3207                 break;
3208         case TCM_UNSUPPORTED_SCSI_OPCODE:
3209         case TCM_SECTOR_COUNT_TOO_MANY:
3210                 /* CURRENT ERROR */
3211                 buffer[offset] = 0x70;
3212                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3213                 /* ILLEGAL REQUEST */
3214                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
3215                 /* INVALID COMMAND OPERATION CODE */
3216                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x20;
3217                 break;
3218         case TCM_UNKNOWN_MODE_PAGE:
3219                 /* CURRENT ERROR */
3220                 buffer[offset] = 0x70;
3221                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3222                 /* ILLEGAL REQUEST */
3223                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
3224                 /* INVALID FIELD IN CDB */
3225                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
3226                 break;
3227         case TCM_CHECK_CONDITION_ABORT_CMD:
3228                 /* CURRENT ERROR */
3229                 buffer[offset] = 0x70;
3230                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3231                 /* ABORTED COMMAND */
3232                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
3233                 /* BUS DEVICE RESET FUNCTION OCCURRED */
3234                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x29;
3235                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x03;
3236                 break;
3237         case TCM_INCORRECT_AMOUNT_OF_DATA:
3238                 /* CURRENT ERROR */
3239                 buffer[offset] = 0x70;
3240                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3241                 /* ABORTED COMMAND */
3242                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
3243                 /* WRITE ERROR */
3244                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
3245                 /* NOT ENOUGH UNSOLICITED DATA */
3246                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0d;
3247                 break;
3248         case TCM_INVALID_CDB_FIELD:
3249                 /* CURRENT ERROR */
3250                 buffer[offset] = 0x70;
3251                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3252                 /* ILLEGAL REQUEST */
3253                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
3254                 /* INVALID FIELD IN CDB */
3255                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
3256                 break;
3257         case TCM_INVALID_PARAMETER_LIST:
3258                 /* CURRENT ERROR */
3259                 buffer[offset] = 0x70;
3260                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3261                 /* ILLEGAL REQUEST */
3262                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
3263                 /* INVALID FIELD IN PARAMETER LIST */
3264                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x26;
3265                 break;
3266         case TCM_UNEXPECTED_UNSOLICITED_DATA:
3267                 /* CURRENT ERROR */
3268                 buffer[offset] = 0x70;
3269                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3270                 /* ABORTED COMMAND */
3271                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
3272                 /* WRITE ERROR */
3273                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
3274                 /* UNEXPECTED_UNSOLICITED_DATA */
3275                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0c;
3276                 break;
3277         case TCM_SERVICE_CRC_ERROR:
3278                 /* CURRENT ERROR */
3279                 buffer[offset] = 0x70;
3280                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3281                 /* ABORTED COMMAND */
3282                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
3283                 /* PROTOCOL SERVICE CRC ERROR */
3284                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x47;
3285                 /* N/A */
3286                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x05;
3287                 break;
3288         case TCM_SNACK_REJECTED:
3289                 /* CURRENT ERROR */
3290                 buffer[offset] = 0x70;
3291                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3292                 /* ABORTED COMMAND */
3293                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
3294                 /* READ ERROR */
3295                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x11;
3296                 /* FAILED RETRANSMISSION REQUEST */
3297                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x13;
3298                 break;
3299         case TCM_WRITE_PROTECTED:
3300                 /* CURRENT ERROR */
3301                 buffer[offset] = 0x70;
3302                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3303                 /* DATA PROTECT */
3304                 buffer[offset+SPC_SENSE_KEY_OFFSET] = DATA_PROTECT;
3305                 /* WRITE PROTECTED */
3306                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x27;
3307                 break;
3308         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
3309                 /* CURRENT ERROR */
3310                 buffer[offset] = 0x70;
3311                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3312                 /* UNIT ATTENTION */
3313                 buffer[offset+SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION;
3314                 core_scsi3_ua_for_check_condition(cmd, &asc, &ascq);
3315                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
3316                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
3317                 break;
3318         case TCM_CHECK_CONDITION_NOT_READY:
3319                 /* CURRENT ERROR */
3320                 buffer[offset] = 0x70;
3321                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3322                 /* Not Ready */
3323                 buffer[offset+SPC_SENSE_KEY_OFFSET] = NOT_READY;
3324                 transport_get_sense_codes(cmd, &asc, &ascq);
3325                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
3326                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
3327                 break;
3328         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
3329         default:
3330                 /* CURRENT ERROR */
3331                 buffer[offset] = 0x70;
3332                 buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
3333                 /* ILLEGAL REQUEST */
3334                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
3335                 /* LOGICAL UNIT COMMUNICATION FAILURE */
3336                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x80;
3337                 break;
3338         }
3339         /*
3340          * This code uses linux/include/scsi/scsi.h SAM status codes!
3341          */
3342         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3343         /*
3344          * Automatically padded, this value is encoded in the fabric's
3345          * data_length response PDU containing the SCSI defined sense data.
3346          */
3347         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER + offset;
3348
3349 after_reason:
3350         return cmd->se_tfo->queue_status(cmd);
3351 }
3352 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3353
3354 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3355 {
3356         int ret = 0;
3357
3358         if (cmd->transport_state & CMD_T_ABORTED) {
3359                 if (!send_status ||
3360                      (cmd->se_cmd_flags & SCF_SENT_DELAYED_TAS))
3361                         return 1;
3362
3363                 pr_debug("Sending delayed SAM_STAT_TASK_ABORTED"
3364                         " status for CDB: 0x%02x ITT: 0x%08x\n",
3365                         cmd->t_task_cdb[0],
3366                         cmd->se_tfo->get_task_tag(cmd));
3367
3368                 cmd->se_cmd_flags |= SCF_SENT_DELAYED_TAS;
3369                 cmd->se_tfo->queue_status(cmd);
3370                 ret = 1;
3371         }
3372         return ret;
3373 }
3374 EXPORT_SYMBOL(transport_check_aborted_status);
3375
3376 void transport_send_task_abort(struct se_cmd *cmd)
3377 {
3378         unsigned long flags;
3379
3380         spin_lock_irqsave(&cmd->t_state_lock, flags);
3381         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3382                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3383                 return;
3384         }
3385         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3386
3387         /*
3388          * If there are still expected incoming fabric WRITEs, we wait
3389          * until until they have completed before sending a TASK_ABORTED
3390          * response.  This response with TASK_ABORTED status will be
3391          * queued back to fabric module by transport_check_aborted_status().
3392          */
3393         if (cmd->data_direction == DMA_TO_DEVICE) {
3394                 if (cmd->se_tfo->write_pending_status(cmd) != 0) {
3395                         cmd->transport_state |= CMD_T_ABORTED;
3396                         smp_mb__after_atomic_inc();
3397                 }
3398         }
3399         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3400
3401         pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x,"
3402                 " ITT: 0x%08x\n", cmd->t_task_cdb[0],
3403                 cmd->se_tfo->get_task_tag(cmd));
3404
3405         cmd->se_tfo->queue_status(cmd);
3406 }
3407
3408 static int transport_generic_do_tmr(struct se_cmd *cmd)
3409 {
3410         struct se_device *dev = cmd->se_dev;
3411         struct se_tmr_req *tmr = cmd->se_tmr_req;
3412         int ret;
3413
3414         switch (tmr->function) {
3415         case TMR_ABORT_TASK:
3416                 core_tmr_abort_task(dev, tmr, cmd->se_sess);
3417                 break;
3418         case TMR_ABORT_TASK_SET:
3419         case TMR_CLEAR_ACA:
3420         case TMR_CLEAR_TASK_SET:
3421                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3422                 break;
3423         case TMR_LUN_RESET:
3424                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3425                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3426                                          TMR_FUNCTION_REJECTED;
3427                 break;
3428         case TMR_TARGET_WARM_RESET:
3429                 tmr->response = TMR_FUNCTION_REJECTED;
3430                 break;
3431         case TMR_TARGET_COLD_RESET:
3432                 tmr->response = TMR_FUNCTION_REJECTED;
3433                 break;
3434         default:
3435                 pr_err("Uknown TMR function: 0x%02x.\n",
3436                                 tmr->function);
3437                 tmr->response = TMR_FUNCTION_REJECTED;
3438                 break;
3439         }
3440
3441         cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3442         cmd->se_tfo->queue_tm_rsp(cmd);
3443
3444         transport_cmd_check_stop_to_fabric(cmd);
3445         return 0;
3446 }
3447
3448 /*      transport_processing_thread():
3449  *
3450  *
3451  */
3452 static int transport_processing_thread(void *param)
3453 {
3454         int ret;
3455         struct se_cmd *cmd;
3456         struct se_device *dev = param;
3457
3458         while (!kthread_should_stop()) {
3459                 ret = wait_event_interruptible(dev->dev_queue_obj.thread_wq,
3460                                 atomic_read(&dev->dev_queue_obj.queue_cnt) ||
3461                                 kthread_should_stop());
3462                 if (ret < 0)
3463                         goto out;
3464
3465 get_cmd:
3466                 cmd = transport_get_cmd_from_queue(&dev->dev_queue_obj);
3467                 if (!cmd)
3468                         continue;
3469
3470                 switch (cmd->t_state) {
3471                 case TRANSPORT_NEW_CMD:
3472                         BUG();
3473                         break;
3474                 case TRANSPORT_NEW_CMD_MAP:
3475                         if (!cmd->se_tfo->new_cmd_map) {
3476                                 pr_err("cmd->se_tfo->new_cmd_map is"
3477                                         " NULL for TRANSPORT_NEW_CMD_MAP\n");
3478                                 BUG();
3479                         }
3480                         ret = cmd->se_tfo->new_cmd_map(cmd);
3481                         if (ret < 0) {
3482                                 transport_generic_request_failure(cmd);
3483                                 break;
3484                         }
3485                         ret = transport_generic_new_cmd(cmd);
3486                         if (ret < 0) {
3487                                 transport_generic_request_failure(cmd);
3488                                 break;
3489                         }
3490                         break;
3491                 case TRANSPORT_PROCESS_WRITE:
3492                         transport_generic_process_write(cmd);
3493                         break;
3494                 case TRANSPORT_PROCESS_TMR:
3495                         transport_generic_do_tmr(cmd);
3496                         break;
3497                 case TRANSPORT_COMPLETE_QF_WP:
3498                         transport_write_pending_qf(cmd);
3499                         break;
3500                 case TRANSPORT_COMPLETE_QF_OK:
3501                         transport_complete_qf(cmd);
3502                         break;
3503                 default:
3504                         pr_err("Unknown t_state: %d  for ITT: 0x%08x "
3505                                 "i_state: %d on SE LUN: %u\n",
3506                                 cmd->t_state,
3507                                 cmd->se_tfo->get_task_tag(cmd),
3508                                 cmd->se_tfo->get_cmd_state(cmd),
3509                                 cmd->se_lun->unpacked_lun);
3510                         BUG();
3511                 }
3512
3513                 goto get_cmd;
3514         }
3515
3516 out:
3517         WARN_ON(!list_empty(&dev->state_list));
3518         WARN_ON(!list_empty(&dev->dev_queue_obj.qobj_list));
3519         dev->process_thread = NULL;
3520         return 0;
3521 }