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