target: Add se_sess->sess_kref + get/put helpers
[linux-3.10.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                 spin_lock_irq(&se_nacl->nacl_sess_lock);
286                 /*
287                  * The se_nacl->nacl_sess pointer will be set to the
288                  * last active I_T Nexus for each struct se_node_acl.
289                  */
290                 se_nacl->nacl_sess = se_sess;
291
292                 list_add_tail(&se_sess->sess_acl_list,
293                               &se_nacl->acl_sess_list);
294                 spin_unlock_irq(&se_nacl->nacl_sess_lock);
295         }
296         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
297
298         pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
299                 se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
300 }
301 EXPORT_SYMBOL(__transport_register_session);
302
303 void transport_register_session(
304         struct se_portal_group *se_tpg,
305         struct se_node_acl *se_nacl,
306         struct se_session *se_sess,
307         void *fabric_sess_ptr)
308 {
309         unsigned long flags;
310
311         spin_lock_irqsave(&se_tpg->session_lock, flags);
312         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
313         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
314 }
315 EXPORT_SYMBOL(transport_register_session);
316
317 static void target_release_session(struct kref *kref)
318 {
319         struct se_session *se_sess = container_of(kref,
320                         struct se_session, sess_kref);
321         struct se_portal_group *se_tpg = se_sess->se_tpg;
322
323         se_tpg->se_tpg_tfo->close_session(se_sess);
324 }
325
326 void target_get_session(struct se_session *se_sess)
327 {
328         kref_get(&se_sess->sess_kref);
329 }
330 EXPORT_SYMBOL(target_get_session);
331
332 int target_put_session(struct se_session *se_sess)
333 {
334         return kref_put(&se_sess->sess_kref, target_release_session);
335 }
336 EXPORT_SYMBOL(target_put_session);
337
338 void transport_deregister_session_configfs(struct se_session *se_sess)
339 {
340         struct se_node_acl *se_nacl;
341         unsigned long flags;
342         /*
343          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
344          */
345         se_nacl = se_sess->se_node_acl;
346         if (se_nacl) {
347                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
348                 list_del(&se_sess->sess_acl_list);
349                 /*
350                  * If the session list is empty, then clear the pointer.
351                  * Otherwise, set the struct se_session pointer from the tail
352                  * element of the per struct se_node_acl active session list.
353                  */
354                 if (list_empty(&se_nacl->acl_sess_list))
355                         se_nacl->nacl_sess = NULL;
356                 else {
357                         se_nacl->nacl_sess = container_of(
358                                         se_nacl->acl_sess_list.prev,
359                                         struct se_session, sess_acl_list);
360                 }
361                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
362         }
363 }
364 EXPORT_SYMBOL(transport_deregister_session_configfs);
365
366 void transport_free_session(struct se_session *se_sess)
367 {
368         kmem_cache_free(se_sess_cache, se_sess);
369 }
370 EXPORT_SYMBOL(transport_free_session);
371
372 void transport_deregister_session(struct se_session *se_sess)
373 {
374         struct se_portal_group *se_tpg = se_sess->se_tpg;
375         struct se_node_acl *se_nacl;
376         unsigned long flags;
377
378         if (!se_tpg) {
379                 transport_free_session(se_sess);
380                 return;
381         }
382
383         spin_lock_irqsave(&se_tpg->session_lock, flags);
384         list_del(&se_sess->sess_list);
385         se_sess->se_tpg = NULL;
386         se_sess->fabric_sess_ptr = NULL;
387         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
388
389         /*
390          * Determine if we need to do extra work for this initiator node's
391          * struct se_node_acl if it had been previously dynamically generated.
392          */
393         se_nacl = se_sess->se_node_acl;
394         if (se_nacl) {
395                 spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
396                 if (se_nacl->dynamic_node_acl) {
397                         if (!se_tpg->se_tpg_tfo->tpg_check_demo_mode_cache(
398                                         se_tpg)) {
399                                 list_del(&se_nacl->acl_list);
400                                 se_tpg->num_node_acls--;
401                                 spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
402
403                                 core_tpg_wait_for_nacl_pr_ref(se_nacl);
404                                 core_free_device_list_for_node(se_nacl, se_tpg);
405                                 se_tpg->se_tpg_tfo->tpg_release_fabric_acl(se_tpg,
406                                                 se_nacl);
407                                 spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
408                         }
409                 }
410                 spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
411         }
412
413         transport_free_session(se_sess);
414
415         pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
416                 se_tpg->se_tpg_tfo->get_fabric_name());
417 }
418 EXPORT_SYMBOL(transport_deregister_session);
419
420 /*
421  * Called with cmd->t_state_lock held.
422  */
423 static void transport_all_task_dev_remove_state(struct se_cmd *cmd)
424 {
425         struct se_device *dev = cmd->se_dev;
426         struct se_task *task;
427         unsigned long flags;
428
429         if (!dev)
430                 return;
431
432         list_for_each_entry(task, &cmd->t_task_list, t_list) {
433                 if (task->task_flags & TF_ACTIVE)
434                         continue;
435
436                 spin_lock_irqsave(&dev->execute_task_lock, flags);
437                 if (task->t_state_active) {
438                         pr_debug("Removed ITT: 0x%08x dev: %p task[%p]\n",
439                                 cmd->se_tfo->get_task_tag(cmd), dev, task);
440
441                         list_del(&task->t_state_list);
442                         atomic_dec(&cmd->t_task_cdbs_ex_left);
443                         task->t_state_active = false;
444                 }
445                 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
446         }
447
448 }
449
450 /*      transport_cmd_check_stop():
451  *
452  *      'transport_off = 1' determines if CMD_T_ACTIVE should be cleared.
453  *      'transport_off = 2' determines if task_dev_state should be removed.
454  *
455  *      A non-zero u8 t_state sets cmd->t_state.
456  *      Returns 1 when command is stopped, else 0.
457  */
458 static int transport_cmd_check_stop(
459         struct se_cmd *cmd,
460         int transport_off,
461         u8 t_state)
462 {
463         unsigned long flags;
464
465         spin_lock_irqsave(&cmd->t_state_lock, flags);
466         /*
467          * Determine if IOCTL context caller in requesting the stopping of this
468          * command for LUN shutdown purposes.
469          */
470         if (cmd->transport_state & CMD_T_LUN_STOP) {
471                 pr_debug("%s:%d CMD_T_LUN_STOP for ITT: 0x%08x\n",
472                         __func__, __LINE__, cmd->se_tfo->get_task_tag(cmd));
473
474                 cmd->transport_state &= ~CMD_T_ACTIVE;
475                 if (transport_off == 2)
476                         transport_all_task_dev_remove_state(cmd);
477                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
478
479                 complete(&cmd->transport_lun_stop_comp);
480                 return 1;
481         }
482         /*
483          * Determine if frontend context caller is requesting the stopping of
484          * this command for frontend exceptions.
485          */
486         if (cmd->transport_state & CMD_T_STOP) {
487                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08x\n",
488                         __func__, __LINE__,
489                         cmd->se_tfo->get_task_tag(cmd));
490
491                 if (transport_off == 2)
492                         transport_all_task_dev_remove_state(cmd);
493
494                 /*
495                  * Clear struct se_cmd->se_lun before the transport_off == 2 handoff
496                  * to FE.
497                  */
498                 if (transport_off == 2)
499                         cmd->se_lun = NULL;
500                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
501
502                 complete(&cmd->t_transport_stop_comp);
503                 return 1;
504         }
505         if (transport_off) {
506                 cmd->transport_state &= ~CMD_T_ACTIVE;
507                 if (transport_off == 2) {
508                         transport_all_task_dev_remove_state(cmd);
509                         /*
510                          * Clear struct se_cmd->se_lun before the transport_off == 2
511                          * handoff to fabric module.
512                          */
513                         cmd->se_lun = NULL;
514                         /*
515                          * Some fabric modules like tcm_loop can release
516                          * their internally allocated I/O reference now and
517                          * struct se_cmd now.
518                          *
519                          * Fabric modules are expected to return '1' here if the
520                          * se_cmd being passed is released at this point,
521                          * or zero if not being released.
522                          */
523                         if (cmd->se_tfo->check_stop_free != NULL) {
524                                 spin_unlock_irqrestore(
525                                         &cmd->t_state_lock, flags);
526
527                                 return cmd->se_tfo->check_stop_free(cmd);
528                         }
529                 }
530                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
531
532                 return 0;
533         } else if (t_state)
534                 cmd->t_state = t_state;
535         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
536
537         return 0;
538 }
539
540 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
541 {
542         return transport_cmd_check_stop(cmd, 2, 0);
543 }
544
545 static void transport_lun_remove_cmd(struct se_cmd *cmd)
546 {
547         struct se_lun *lun = cmd->se_lun;
548         unsigned long flags;
549
550         if (!lun)
551                 return;
552
553         spin_lock_irqsave(&cmd->t_state_lock, flags);
554         if (cmd->transport_state & CMD_T_DEV_ACTIVE) {
555                 cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
556                 transport_all_task_dev_remove_state(cmd);
557         }
558         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
559
560         spin_lock_irqsave(&lun->lun_cmd_lock, flags);
561         if (!list_empty(&cmd->se_lun_node))
562                 list_del_init(&cmd->se_lun_node);
563         spin_unlock_irqrestore(&lun->lun_cmd_lock, flags);
564 }
565
566 void transport_cmd_finish_abort(struct se_cmd *cmd, int remove)
567 {
568         if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
569                 transport_lun_remove_cmd(cmd);
570
571         if (transport_cmd_check_stop_to_fabric(cmd))
572                 return;
573         if (remove) {
574                 transport_remove_cmd_from_queue(cmd);
575                 transport_put_cmd(cmd);
576         }
577 }
578
579 static void transport_add_cmd_to_queue(struct se_cmd *cmd, int t_state,
580                 bool at_head)
581 {
582         struct se_device *dev = cmd->se_dev;
583         struct se_queue_obj *qobj = &dev->dev_queue_obj;
584         unsigned long flags;
585
586         if (t_state) {
587                 spin_lock_irqsave(&cmd->t_state_lock, flags);
588                 cmd->t_state = t_state;
589                 cmd->transport_state |= CMD_T_ACTIVE;
590                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
591         }
592
593         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
594
595         /* If the cmd is already on the list, remove it before we add it */
596         if (!list_empty(&cmd->se_queue_node))
597                 list_del(&cmd->se_queue_node);
598         else
599                 atomic_inc(&qobj->queue_cnt);
600
601         if (at_head)
602                 list_add(&cmd->se_queue_node, &qobj->qobj_list);
603         else
604                 list_add_tail(&cmd->se_queue_node, &qobj->qobj_list);
605         cmd->transport_state |= CMD_T_QUEUED;
606         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
607
608         wake_up_interruptible(&qobj->thread_wq);
609 }
610
611 static struct se_cmd *
612 transport_get_cmd_from_queue(struct se_queue_obj *qobj)
613 {
614         struct se_cmd *cmd;
615         unsigned long flags;
616
617         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
618         if (list_empty(&qobj->qobj_list)) {
619                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
620                 return NULL;
621         }
622         cmd = list_first_entry(&qobj->qobj_list, struct se_cmd, se_queue_node);
623
624         cmd->transport_state &= ~CMD_T_QUEUED;
625         list_del_init(&cmd->se_queue_node);
626         atomic_dec(&qobj->queue_cnt);
627         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
628
629         return cmd;
630 }
631
632 static void transport_remove_cmd_from_queue(struct se_cmd *cmd)
633 {
634         struct se_queue_obj *qobj = &cmd->se_dev->dev_queue_obj;
635         unsigned long flags;
636
637         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
638         if (!(cmd->transport_state & CMD_T_QUEUED)) {
639                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
640                 return;
641         }
642         cmd->transport_state &= ~CMD_T_QUEUED;
643         atomic_dec(&qobj->queue_cnt);
644         list_del_init(&cmd->se_queue_node);
645         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
646 }
647
648 /*
649  * Completion function used by TCM subsystem plugins (such as FILEIO)
650  * for queueing up response from struct se_subsystem_api->do_task()
651  */
652 void transport_complete_sync_cache(struct se_cmd *cmd, int good)
653 {
654         struct se_task *task = list_entry(cmd->t_task_list.next,
655                                 struct se_task, t_list);
656
657         if (good) {
658                 cmd->scsi_status = SAM_STAT_GOOD;
659                 task->task_scsi_status = GOOD;
660         } else {
661                 task->task_scsi_status = SAM_STAT_CHECK_CONDITION;
662                 task->task_se_cmd->scsi_sense_reason =
663                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
664
665         }
666
667         transport_complete_task(task, good);
668 }
669 EXPORT_SYMBOL(transport_complete_sync_cache);
670
671 static void target_complete_failure_work(struct work_struct *work)
672 {
673         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
674
675         transport_generic_request_failure(cmd);
676 }
677
678 /*      transport_complete_task():
679  *
680  *      Called from interrupt and non interrupt context depending
681  *      on the transport plugin.
682  */
683 void transport_complete_task(struct se_task *task, int success)
684 {
685         struct se_cmd *cmd = task->task_se_cmd;
686         struct se_device *dev = cmd->se_dev;
687         unsigned long flags;
688
689         spin_lock_irqsave(&cmd->t_state_lock, flags);
690         task->task_flags &= ~TF_ACTIVE;
691
692         /*
693          * See if any sense data exists, if so set the TASK_SENSE flag.
694          * Also check for any other post completion work that needs to be
695          * done by the plugins.
696          */
697         if (dev && dev->transport->transport_complete) {
698                 if (dev->transport->transport_complete(task) != 0) {
699                         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
700                         task->task_flags |= TF_HAS_SENSE;
701                         success = 1;
702                 }
703         }
704
705         /*
706          * See if we are waiting for outstanding struct se_task
707          * to complete for an exception condition
708          */
709         if (task->task_flags & TF_REQUEST_STOP) {
710                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
711                 complete(&task->task_stop_comp);
712                 return;
713         }
714
715         if (!success)
716                 cmd->transport_state |= CMD_T_FAILED;
717
718         /*
719          * Decrement the outstanding t_task_cdbs_left count.  The last
720          * struct se_task from struct se_cmd will complete itself into the
721          * device queue depending upon int success.
722          */
723         if (!atomic_dec_and_test(&cmd->t_task_cdbs_left)) {
724                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
725                 return;
726         }
727         /*
728          * Check for case where an explict ABORT_TASK has been received
729          * and transport_wait_for_tasks() will be waiting for completion..
730          */
731         if (cmd->transport_state & CMD_T_ABORTED &&
732             cmd->transport_state & CMD_T_STOP) {
733                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
734                 complete(&cmd->t_transport_stop_comp);
735                 return;
736         } else if (cmd->transport_state & CMD_T_FAILED) {
737                 cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
738                 INIT_WORK(&cmd->work, target_complete_failure_work);
739         } else {
740                 INIT_WORK(&cmd->work, target_complete_ok_work);
741         }
742
743         cmd->t_state = TRANSPORT_COMPLETE;
744         cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
745         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
746
747         queue_work(target_completion_wq, &cmd->work);
748 }
749 EXPORT_SYMBOL(transport_complete_task);
750
751 /*
752  * Called by transport_add_tasks_from_cmd() once a struct se_cmd's
753  * struct se_task list are ready to be added to the active execution list
754  * struct se_device
755
756  * Called with se_dev_t->execute_task_lock called.
757  */
758 static inline int transport_add_task_check_sam_attr(
759         struct se_task *task,
760         struct se_task *task_prev,
761         struct se_device *dev)
762 {
763         /*
764          * No SAM Task attribute emulation enabled, add to tail of
765          * execution queue
766          */
767         if (dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED) {
768                 list_add_tail(&task->t_execute_list, &dev->execute_task_list);
769                 return 0;
770         }
771         /*
772          * HEAD_OF_QUEUE attribute for received CDB, which means
773          * the first task that is associated with a struct se_cmd goes to
774          * head of the struct se_device->execute_task_list, and task_prev
775          * after that for each subsequent task
776          */
777         if (task->task_se_cmd->sam_task_attr == MSG_HEAD_TAG) {
778                 list_add(&task->t_execute_list,
779                                 (task_prev != NULL) ?
780                                 &task_prev->t_execute_list :
781                                 &dev->execute_task_list);
782
783                 pr_debug("Set HEAD_OF_QUEUE for task CDB: 0x%02x"
784                                 " in execution queue\n",
785                                 task->task_se_cmd->t_task_cdb[0]);
786                 return 1;
787         }
788         /*
789          * For ORDERED, SIMPLE or UNTAGGED attribute tasks once they have been
790          * transitioned from Dermant -> Active state, and are added to the end
791          * of the struct se_device->execute_task_list
792          */
793         list_add_tail(&task->t_execute_list, &dev->execute_task_list);
794         return 0;
795 }
796
797 /*      __transport_add_task_to_execute_queue():
798  *
799  *      Called with se_dev_t->execute_task_lock called.
800  */
801 static void __transport_add_task_to_execute_queue(
802         struct se_task *task,
803         struct se_task *task_prev,
804         struct se_device *dev)
805 {
806         int head_of_queue;
807
808         head_of_queue = transport_add_task_check_sam_attr(task, task_prev, dev);
809         atomic_inc(&dev->execute_tasks);
810
811         if (task->t_state_active)
812                 return;
813         /*
814          * Determine if this task needs to go to HEAD_OF_QUEUE for the
815          * state list as well.  Running with SAM Task Attribute emulation
816          * will always return head_of_queue == 0 here
817          */
818         if (head_of_queue)
819                 list_add(&task->t_state_list, (task_prev) ?
820                                 &task_prev->t_state_list :
821                                 &dev->state_task_list);
822         else
823                 list_add_tail(&task->t_state_list, &dev->state_task_list);
824
825         task->t_state_active = true;
826
827         pr_debug("Added ITT: 0x%08x task[%p] to dev: %p\n",
828                 task->task_se_cmd->se_tfo->get_task_tag(task->task_se_cmd),
829                 task, dev);
830 }
831
832 static void transport_add_tasks_to_state_queue(struct se_cmd *cmd)
833 {
834         struct se_device *dev = cmd->se_dev;
835         struct se_task *task;
836         unsigned long flags;
837
838         spin_lock_irqsave(&cmd->t_state_lock, flags);
839         list_for_each_entry(task, &cmd->t_task_list, t_list) {
840                 spin_lock(&dev->execute_task_lock);
841                 if (!task->t_state_active) {
842                         list_add_tail(&task->t_state_list,
843                                       &dev->state_task_list);
844                         task->t_state_active = true;
845
846                         pr_debug("Added ITT: 0x%08x task[%p] to dev: %p\n",
847                                 task->task_se_cmd->se_tfo->get_task_tag(
848                                 task->task_se_cmd), task, dev);
849                 }
850                 spin_unlock(&dev->execute_task_lock);
851         }
852         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
853 }
854
855 static void __transport_add_tasks_from_cmd(struct se_cmd *cmd)
856 {
857         struct se_device *dev = cmd->se_dev;
858         struct se_task *task, *task_prev = NULL;
859
860         list_for_each_entry(task, &cmd->t_task_list, t_list) {
861                 if (!list_empty(&task->t_execute_list))
862                         continue;
863                 /*
864                  * __transport_add_task_to_execute_queue() handles the
865                  * SAM Task Attribute emulation if enabled
866                  */
867                 __transport_add_task_to_execute_queue(task, task_prev, dev);
868                 task_prev = task;
869         }
870 }
871
872 static void transport_add_tasks_from_cmd(struct se_cmd *cmd)
873 {
874         unsigned long flags;
875         struct se_device *dev = cmd->se_dev;
876
877         spin_lock_irqsave(&dev->execute_task_lock, flags);
878         __transport_add_tasks_from_cmd(cmd);
879         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
880 }
881
882 void __transport_remove_task_from_execute_queue(struct se_task *task,
883                 struct se_device *dev)
884 {
885         list_del_init(&task->t_execute_list);
886         atomic_dec(&dev->execute_tasks);
887 }
888
889 static void transport_remove_task_from_execute_queue(
890         struct se_task *task,
891         struct se_device *dev)
892 {
893         unsigned long flags;
894
895         if (WARN_ON(list_empty(&task->t_execute_list)))
896                 return;
897
898         spin_lock_irqsave(&dev->execute_task_lock, flags);
899         __transport_remove_task_from_execute_queue(task, dev);
900         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
901 }
902
903 /*
904  * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
905  */
906
907 static void target_qf_do_work(struct work_struct *work)
908 {
909         struct se_device *dev = container_of(work, struct se_device,
910                                         qf_work_queue);
911         LIST_HEAD(qf_cmd_list);
912         struct se_cmd *cmd, *cmd_tmp;
913
914         spin_lock_irq(&dev->qf_cmd_lock);
915         list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
916         spin_unlock_irq(&dev->qf_cmd_lock);
917
918         list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
919                 list_del(&cmd->se_qf_node);
920                 atomic_dec(&dev->dev_qf_count);
921                 smp_mb__after_atomic_dec();
922
923                 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
924                         " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
925                         (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
926                         (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
927                         : "UNKNOWN");
928
929                 transport_add_cmd_to_queue(cmd, cmd->t_state, true);
930         }
931 }
932
933 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
934 {
935         switch (cmd->data_direction) {
936         case DMA_NONE:
937                 return "NONE";
938         case DMA_FROM_DEVICE:
939                 return "READ";
940         case DMA_TO_DEVICE:
941                 return "WRITE";
942         case DMA_BIDIRECTIONAL:
943                 return "BIDI";
944         default:
945                 break;
946         }
947
948         return "UNKNOWN";
949 }
950
951 void transport_dump_dev_state(
952         struct se_device *dev,
953         char *b,
954         int *bl)
955 {
956         *bl += sprintf(b + *bl, "Status: ");
957         switch (dev->dev_status) {
958         case TRANSPORT_DEVICE_ACTIVATED:
959                 *bl += sprintf(b + *bl, "ACTIVATED");
960                 break;
961         case TRANSPORT_DEVICE_DEACTIVATED:
962                 *bl += sprintf(b + *bl, "DEACTIVATED");
963                 break;
964         case TRANSPORT_DEVICE_SHUTDOWN:
965                 *bl += sprintf(b + *bl, "SHUTDOWN");
966                 break;
967         case TRANSPORT_DEVICE_OFFLINE_ACTIVATED:
968         case TRANSPORT_DEVICE_OFFLINE_DEACTIVATED:
969                 *bl += sprintf(b + *bl, "OFFLINE");
970                 break;
971         default:
972                 *bl += sprintf(b + *bl, "UNKNOWN=%d", dev->dev_status);
973                 break;
974         }
975
976         *bl += sprintf(b + *bl, "  Execute/Max Queue Depth: %d/%d",
977                 atomic_read(&dev->execute_tasks), dev->queue_depth);
978         *bl += sprintf(b + *bl, "  SectorSize: %u  MaxSectors: %u\n",
979                 dev->se_sub_dev->se_dev_attrib.block_size, dev->se_sub_dev->se_dev_attrib.max_sectors);
980         *bl += sprintf(b + *bl, "        ");
981 }
982
983 void transport_dump_vpd_proto_id(
984         struct t10_vpd *vpd,
985         unsigned char *p_buf,
986         int p_buf_len)
987 {
988         unsigned char buf[VPD_TMP_BUF_SIZE];
989         int len;
990
991         memset(buf, 0, VPD_TMP_BUF_SIZE);
992         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
993
994         switch (vpd->protocol_identifier) {
995         case 0x00:
996                 sprintf(buf+len, "Fibre Channel\n");
997                 break;
998         case 0x10:
999                 sprintf(buf+len, "Parallel SCSI\n");
1000                 break;
1001         case 0x20:
1002                 sprintf(buf+len, "SSA\n");
1003                 break;
1004         case 0x30:
1005                 sprintf(buf+len, "IEEE 1394\n");
1006                 break;
1007         case 0x40:
1008                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
1009                                 " Protocol\n");
1010                 break;
1011         case 0x50:
1012                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
1013                 break;
1014         case 0x60:
1015                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
1016                 break;
1017         case 0x70:
1018                 sprintf(buf+len, "Automation/Drive Interface Transport"
1019                                 " Protocol\n");
1020                 break;
1021         case 0x80:
1022                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
1023                 break;
1024         default:
1025                 sprintf(buf+len, "Unknown 0x%02x\n",
1026                                 vpd->protocol_identifier);
1027                 break;
1028         }
1029
1030         if (p_buf)
1031                 strncpy(p_buf, buf, p_buf_len);
1032         else
1033                 pr_debug("%s", buf);
1034 }
1035
1036 void
1037 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1038 {
1039         /*
1040          * Check if the Protocol Identifier Valid (PIV) bit is set..
1041          *
1042          * from spc3r23.pdf section 7.5.1
1043          */
1044          if (page_83[1] & 0x80) {
1045                 vpd->protocol_identifier = (page_83[0] & 0xf0);
1046                 vpd->protocol_identifier_set = 1;
1047                 transport_dump_vpd_proto_id(vpd, NULL, 0);
1048         }
1049 }
1050 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1051
1052 int transport_dump_vpd_assoc(
1053         struct t10_vpd *vpd,
1054         unsigned char *p_buf,
1055         int p_buf_len)
1056 {
1057         unsigned char buf[VPD_TMP_BUF_SIZE];
1058         int ret = 0;
1059         int len;
1060
1061         memset(buf, 0, VPD_TMP_BUF_SIZE);
1062         len = sprintf(buf, "T10 VPD Identifier Association: ");
1063
1064         switch (vpd->association) {
1065         case 0x00:
1066                 sprintf(buf+len, "addressed logical unit\n");
1067                 break;
1068         case 0x10:
1069                 sprintf(buf+len, "target port\n");
1070                 break;
1071         case 0x20:
1072                 sprintf(buf+len, "SCSI target device\n");
1073                 break;
1074         default:
1075                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1076                 ret = -EINVAL;
1077                 break;
1078         }
1079
1080         if (p_buf)
1081                 strncpy(p_buf, buf, p_buf_len);
1082         else
1083                 pr_debug("%s", buf);
1084
1085         return ret;
1086 }
1087
1088 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1089 {
1090         /*
1091          * The VPD identification association..
1092          *
1093          * from spc3r23.pdf Section 7.6.3.1 Table 297
1094          */
1095         vpd->association = (page_83[1] & 0x30);
1096         return transport_dump_vpd_assoc(vpd, NULL, 0);
1097 }
1098 EXPORT_SYMBOL(transport_set_vpd_assoc);
1099
1100 int transport_dump_vpd_ident_type(
1101         struct t10_vpd *vpd,
1102         unsigned char *p_buf,
1103         int p_buf_len)
1104 {
1105         unsigned char buf[VPD_TMP_BUF_SIZE];
1106         int ret = 0;
1107         int len;
1108
1109         memset(buf, 0, VPD_TMP_BUF_SIZE);
1110         len = sprintf(buf, "T10 VPD Identifier Type: ");
1111
1112         switch (vpd->device_identifier_type) {
1113         case 0x00:
1114                 sprintf(buf+len, "Vendor specific\n");
1115                 break;
1116         case 0x01:
1117                 sprintf(buf+len, "T10 Vendor ID based\n");
1118                 break;
1119         case 0x02:
1120                 sprintf(buf+len, "EUI-64 based\n");
1121                 break;
1122         case 0x03:
1123                 sprintf(buf+len, "NAA\n");
1124                 break;
1125         case 0x04:
1126                 sprintf(buf+len, "Relative target port identifier\n");
1127                 break;
1128         case 0x08:
1129                 sprintf(buf+len, "SCSI name string\n");
1130                 break;
1131         default:
1132                 sprintf(buf+len, "Unsupported: 0x%02x\n",
1133                                 vpd->device_identifier_type);
1134                 ret = -EINVAL;
1135                 break;
1136         }
1137
1138         if (p_buf) {
1139                 if (p_buf_len < strlen(buf)+1)
1140                         return -EINVAL;
1141                 strncpy(p_buf, buf, p_buf_len);
1142         } else {
1143                 pr_debug("%s", buf);
1144         }
1145
1146         return ret;
1147 }
1148
1149 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1150 {
1151         /*
1152          * The VPD identifier type..
1153          *
1154          * from spc3r23.pdf Section 7.6.3.1 Table 298
1155          */
1156         vpd->device_identifier_type = (page_83[1] & 0x0f);
1157         return transport_dump_vpd_ident_type(vpd, NULL, 0);
1158 }
1159 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1160
1161 int transport_dump_vpd_ident(
1162         struct t10_vpd *vpd,
1163         unsigned char *p_buf,
1164         int p_buf_len)
1165 {
1166         unsigned char buf[VPD_TMP_BUF_SIZE];
1167         int ret = 0;
1168
1169         memset(buf, 0, VPD_TMP_BUF_SIZE);
1170
1171         switch (vpd->device_identifier_code_set) {
1172         case 0x01: /* Binary */
1173                 sprintf(buf, "T10 VPD Binary Device Identifier: %s\n",
1174                         &vpd->device_identifier[0]);
1175                 break;
1176         case 0x02: /* ASCII */
1177                 sprintf(buf, "T10 VPD ASCII Device Identifier: %s\n",
1178                         &vpd->device_identifier[0]);
1179                 break;
1180         case 0x03: /* UTF-8 */
1181                 sprintf(buf, "T10 VPD UTF-8 Device Identifier: %s\n",
1182                         &vpd->device_identifier[0]);
1183                 break;
1184         default:
1185                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1186                         " 0x%02x", vpd->device_identifier_code_set);
1187                 ret = -EINVAL;
1188                 break;
1189         }
1190
1191         if (p_buf)
1192                 strncpy(p_buf, buf, p_buf_len);
1193         else
1194                 pr_debug("%s", buf);
1195
1196         return ret;
1197 }
1198
1199 int
1200 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1201 {
1202         static const char hex_str[] = "0123456789abcdef";
1203         int j = 0, i = 4; /* offset to start of the identifer */
1204
1205         /*
1206          * The VPD Code Set (encoding)
1207          *
1208          * from spc3r23.pdf Section 7.6.3.1 Table 296
1209          */
1210         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1211         switch (vpd->device_identifier_code_set) {
1212         case 0x01: /* Binary */
1213                 vpd->device_identifier[j++] =
1214                                 hex_str[vpd->device_identifier_type];
1215                 while (i < (4 + page_83[3])) {
1216                         vpd->device_identifier[j++] =
1217                                 hex_str[(page_83[i] & 0xf0) >> 4];
1218                         vpd->device_identifier[j++] =
1219                                 hex_str[page_83[i] & 0x0f];
1220                         i++;
1221                 }
1222                 break;
1223         case 0x02: /* ASCII */
1224         case 0x03: /* UTF-8 */
1225                 while (i < (4 + page_83[3]))
1226                         vpd->device_identifier[j++] = page_83[i++];
1227                 break;
1228         default:
1229                 break;
1230         }
1231
1232         return transport_dump_vpd_ident(vpd, NULL, 0);
1233 }
1234 EXPORT_SYMBOL(transport_set_vpd_ident);
1235
1236 static void core_setup_task_attr_emulation(struct se_device *dev)
1237 {
1238         /*
1239          * If this device is from Target_Core_Mod/pSCSI, disable the
1240          * SAM Task Attribute emulation.
1241          *
1242          * This is currently not available in upsream Linux/SCSI Target
1243          * mode code, and is assumed to be disabled while using TCM/pSCSI.
1244          */
1245         if (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) {
1246                 dev->dev_task_attr_type = SAM_TASK_ATTR_PASSTHROUGH;
1247                 return;
1248         }
1249
1250         dev->dev_task_attr_type = SAM_TASK_ATTR_EMULATED;
1251         pr_debug("%s: Using SAM_TASK_ATTR_EMULATED for SPC: 0x%02x"
1252                 " device\n", dev->transport->name,
1253                 dev->transport->get_device_rev(dev));
1254 }
1255
1256 static void scsi_dump_inquiry(struct se_device *dev)
1257 {
1258         struct t10_wwn *wwn = &dev->se_sub_dev->t10_wwn;
1259         char buf[17];
1260         int i, device_type;
1261         /*
1262          * Print Linux/SCSI style INQUIRY formatting to the kernel ring buffer
1263          */
1264         for (i = 0; i < 8; i++)
1265                 if (wwn->vendor[i] >= 0x20)
1266                         buf[i] = wwn->vendor[i];
1267                 else
1268                         buf[i] = ' ';
1269         buf[i] = '\0';
1270         pr_debug("  Vendor: %s\n", buf);
1271
1272         for (i = 0; i < 16; i++)
1273                 if (wwn->model[i] >= 0x20)
1274                         buf[i] = wwn->model[i];
1275                 else
1276                         buf[i] = ' ';
1277         buf[i] = '\0';
1278         pr_debug("  Model: %s\n", buf);
1279
1280         for (i = 0; i < 4; i++)
1281                 if (wwn->revision[i] >= 0x20)
1282                         buf[i] = wwn->revision[i];
1283                 else
1284                         buf[i] = ' ';
1285         buf[i] = '\0';
1286         pr_debug("  Revision: %s\n", buf);
1287
1288         device_type = dev->transport->get_device_type(dev);
1289         pr_debug("  Type:   %s ", scsi_device_type(device_type));
1290         pr_debug("                 ANSI SCSI revision: %02x\n",
1291                                 dev->transport->get_device_rev(dev));
1292 }
1293
1294 struct se_device *transport_add_device_to_core_hba(
1295         struct se_hba *hba,
1296         struct se_subsystem_api *transport,
1297         struct se_subsystem_dev *se_dev,
1298         u32 device_flags,
1299         void *transport_dev,
1300         struct se_dev_limits *dev_limits,
1301         const char *inquiry_prod,
1302         const char *inquiry_rev)
1303 {
1304         int force_pt;
1305         struct se_device  *dev;
1306
1307         dev = kzalloc(sizeof(struct se_device), GFP_KERNEL);
1308         if (!dev) {
1309                 pr_err("Unable to allocate memory for se_dev_t\n");
1310                 return NULL;
1311         }
1312
1313         transport_init_queue_obj(&dev->dev_queue_obj);
1314         dev->dev_flags          = device_flags;
1315         dev->dev_status         |= TRANSPORT_DEVICE_DEACTIVATED;
1316         dev->dev_ptr            = transport_dev;
1317         dev->se_hba             = hba;
1318         dev->se_sub_dev         = se_dev;
1319         dev->transport          = transport;
1320         INIT_LIST_HEAD(&dev->dev_list);
1321         INIT_LIST_HEAD(&dev->dev_sep_list);
1322         INIT_LIST_HEAD(&dev->dev_tmr_list);
1323         INIT_LIST_HEAD(&dev->execute_task_list);
1324         INIT_LIST_HEAD(&dev->delayed_cmd_list);
1325         INIT_LIST_HEAD(&dev->state_task_list);
1326         INIT_LIST_HEAD(&dev->qf_cmd_list);
1327         spin_lock_init(&dev->execute_task_lock);
1328         spin_lock_init(&dev->delayed_cmd_lock);
1329         spin_lock_init(&dev->dev_reservation_lock);
1330         spin_lock_init(&dev->dev_status_lock);
1331         spin_lock_init(&dev->se_port_lock);
1332         spin_lock_init(&dev->se_tmr_lock);
1333         spin_lock_init(&dev->qf_cmd_lock);
1334         atomic_set(&dev->dev_ordered_id, 0);
1335
1336         se_dev_set_default_attribs(dev, dev_limits);
1337
1338         dev->dev_index = scsi_get_new_index(SCSI_DEVICE_INDEX);
1339         dev->creation_time = get_jiffies_64();
1340         spin_lock_init(&dev->stats_lock);
1341
1342         spin_lock(&hba->device_lock);
1343         list_add_tail(&dev->dev_list, &hba->hba_dev_list);
1344         hba->dev_count++;
1345         spin_unlock(&hba->device_lock);
1346         /*
1347          * Setup the SAM Task Attribute emulation for struct se_device
1348          */
1349         core_setup_task_attr_emulation(dev);
1350         /*
1351          * Force PR and ALUA passthrough emulation with internal object use.
1352          */
1353         force_pt = (hba->hba_flags & HBA_FLAGS_INTERNAL_USE);
1354         /*
1355          * Setup the Reservations infrastructure for struct se_device
1356          */
1357         core_setup_reservations(dev, force_pt);
1358         /*
1359          * Setup the Asymmetric Logical Unit Assignment for struct se_device
1360          */
1361         if (core_setup_alua(dev, force_pt) < 0)
1362                 goto out;
1363
1364         /*
1365          * Startup the struct se_device processing thread
1366          */
1367         dev->process_thread = kthread_run(transport_processing_thread, dev,
1368                                           "LIO_%s", dev->transport->name);
1369         if (IS_ERR(dev->process_thread)) {
1370                 pr_err("Unable to create kthread: LIO_%s\n",
1371                         dev->transport->name);
1372                 goto out;
1373         }
1374         /*
1375          * Setup work_queue for QUEUE_FULL
1376          */
1377         INIT_WORK(&dev->qf_work_queue, target_qf_do_work);
1378         /*
1379          * Preload the initial INQUIRY const values if we are doing
1380          * anything virtual (IBLOCK, FILEIO, RAMDISK), but not for TCM/pSCSI
1381          * passthrough because this is being provided by the backend LLD.
1382          * This is required so that transport_get_inquiry() copies these
1383          * originals once back into DEV_T10_WWN(dev) for the virtual device
1384          * setup.
1385          */
1386         if (dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
1387                 if (!inquiry_prod || !inquiry_rev) {
1388                         pr_err("All non TCM/pSCSI plugins require"
1389                                 " INQUIRY consts\n");
1390                         goto out;
1391                 }
1392
1393                 strncpy(&dev->se_sub_dev->t10_wwn.vendor[0], "LIO-ORG", 8);
1394                 strncpy(&dev->se_sub_dev->t10_wwn.model[0], inquiry_prod, 16);
1395                 strncpy(&dev->se_sub_dev->t10_wwn.revision[0], inquiry_rev, 4);
1396         }
1397         scsi_dump_inquiry(dev);
1398
1399         return dev;
1400 out:
1401         kthread_stop(dev->process_thread);
1402
1403         spin_lock(&hba->device_lock);
1404         list_del(&dev->dev_list);
1405         hba->dev_count--;
1406         spin_unlock(&hba->device_lock);
1407
1408         se_release_vpd_for_dev(dev);
1409
1410         kfree(dev);
1411
1412         return NULL;
1413 }
1414 EXPORT_SYMBOL(transport_add_device_to_core_hba);
1415
1416 /*      transport_generic_prepare_cdb():
1417  *
1418  *      Since the Initiator sees iSCSI devices as LUNs,  the SCSI CDB will
1419  *      contain the iSCSI LUN in bits 7-5 of byte 1 as per SAM-2.
1420  *      The point of this is since we are mapping iSCSI LUNs to
1421  *      SCSI Target IDs having a non-zero LUN in the CDB will throw the
1422  *      devices and HBAs for a loop.
1423  */
1424 static inline void transport_generic_prepare_cdb(
1425         unsigned char *cdb)
1426 {
1427         switch (cdb[0]) {
1428         case READ_10: /* SBC - RDProtect */
1429         case READ_12: /* SBC - RDProtect */
1430         case READ_16: /* SBC - RDProtect */
1431         case SEND_DIAGNOSTIC: /* SPC - SELF-TEST Code */
1432         case VERIFY: /* SBC - VRProtect */
1433         case VERIFY_16: /* SBC - VRProtect */
1434         case WRITE_VERIFY: /* SBC - VRProtect */
1435         case WRITE_VERIFY_12: /* SBC - VRProtect */
1436                 break;
1437         default:
1438                 cdb[1] &= 0x1f; /* clear logical unit number */
1439                 break;
1440         }
1441 }
1442
1443 static struct se_task *
1444 transport_generic_get_task(struct se_cmd *cmd,
1445                 enum dma_data_direction data_direction)
1446 {
1447         struct se_task *task;
1448         struct se_device *dev = cmd->se_dev;
1449
1450         task = dev->transport->alloc_task(cmd->t_task_cdb);
1451         if (!task) {
1452                 pr_err("Unable to allocate struct se_task\n");
1453                 return NULL;
1454         }
1455
1456         INIT_LIST_HEAD(&task->t_list);
1457         INIT_LIST_HEAD(&task->t_execute_list);
1458         INIT_LIST_HEAD(&task->t_state_list);
1459         init_completion(&task->task_stop_comp);
1460         task->task_se_cmd = cmd;
1461         task->task_data_direction = data_direction;
1462
1463         return task;
1464 }
1465
1466 static int transport_generic_cmd_sequencer(struct se_cmd *, unsigned char *);
1467
1468 /*
1469  * Used by fabric modules containing a local struct se_cmd within their
1470  * fabric dependent per I/O descriptor.
1471  */
1472 void transport_init_se_cmd(
1473         struct se_cmd *cmd,
1474         struct target_core_fabric_ops *tfo,
1475         struct se_session *se_sess,
1476         u32 data_length,
1477         int data_direction,
1478         int task_attr,
1479         unsigned char *sense_buffer)
1480 {
1481         INIT_LIST_HEAD(&cmd->se_lun_node);
1482         INIT_LIST_HEAD(&cmd->se_delayed_node);
1483         INIT_LIST_HEAD(&cmd->se_qf_node);
1484         INIT_LIST_HEAD(&cmd->se_queue_node);
1485         INIT_LIST_HEAD(&cmd->se_cmd_list);
1486         INIT_LIST_HEAD(&cmd->t_task_list);
1487         init_completion(&cmd->transport_lun_fe_stop_comp);
1488         init_completion(&cmd->transport_lun_stop_comp);
1489         init_completion(&cmd->t_transport_stop_comp);
1490         init_completion(&cmd->cmd_wait_comp);
1491         spin_lock_init(&cmd->t_state_lock);
1492         cmd->transport_state = CMD_T_DEV_ACTIVE;
1493
1494         cmd->se_tfo = tfo;
1495         cmd->se_sess = se_sess;
1496         cmd->data_length = data_length;
1497         cmd->data_direction = data_direction;
1498         cmd->sam_task_attr = task_attr;
1499         cmd->sense_buffer = sense_buffer;
1500 }
1501 EXPORT_SYMBOL(transport_init_se_cmd);
1502
1503 static int transport_check_alloc_task_attr(struct se_cmd *cmd)
1504 {
1505         /*
1506          * Check if SAM Task Attribute emulation is enabled for this
1507          * struct se_device storage object
1508          */
1509         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1510                 return 0;
1511
1512         if (cmd->sam_task_attr == MSG_ACA_TAG) {
1513                 pr_debug("SAM Task Attribute ACA"
1514                         " emulation is not supported\n");
1515                 return -EINVAL;
1516         }
1517         /*
1518          * Used to determine when ORDERED commands should go from
1519          * Dormant to Active status.
1520          */
1521         cmd->se_ordered_id = atomic_inc_return(&cmd->se_dev->dev_ordered_id);
1522         smp_mb__after_atomic_inc();
1523         pr_debug("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n",
1524                         cmd->se_ordered_id, cmd->sam_task_attr,
1525                         cmd->se_dev->transport->name);
1526         return 0;
1527 }
1528
1529 /*      transport_generic_allocate_tasks():
1530  *
1531  *      Called from fabric RX Thread.
1532  */
1533 int transport_generic_allocate_tasks(
1534         struct se_cmd *cmd,
1535         unsigned char *cdb)
1536 {
1537         int ret;
1538
1539         transport_generic_prepare_cdb(cdb);
1540         /*
1541          * Ensure that the received CDB is less than the max (252 + 8) bytes
1542          * for VARIABLE_LENGTH_CMD
1543          */
1544         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1545                 pr_err("Received SCSI CDB with command_size: %d that"
1546                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1547                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1548                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1549                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1550                 return -EINVAL;
1551         }
1552         /*
1553          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1554          * allocate the additional extended CDB buffer now..  Otherwise
1555          * setup the pointer from __t_task_cdb to t_task_cdb.
1556          */
1557         if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1558                 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1559                                                 GFP_KERNEL);
1560                 if (!cmd->t_task_cdb) {
1561                         pr_err("Unable to allocate cmd->t_task_cdb"
1562                                 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1563                                 scsi_command_size(cdb),
1564                                 (unsigned long)sizeof(cmd->__t_task_cdb));
1565                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1566                         cmd->scsi_sense_reason =
1567                                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1568                         return -ENOMEM;
1569                 }
1570         } else
1571                 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1572         /*
1573          * Copy the original CDB into cmd->
1574          */
1575         memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1576         /*
1577          * Setup the received CDB based on SCSI defined opcodes and
1578          * perform unit attention, persistent reservations and ALUA
1579          * checks for virtual device backends.  The cmd->t_task_cdb
1580          * pointer is expected to be setup before we reach this point.
1581          */
1582         ret = transport_generic_cmd_sequencer(cmd, cdb);
1583         if (ret < 0)
1584                 return ret;
1585         /*
1586          * Check for SAM Task Attribute Emulation
1587          */
1588         if (transport_check_alloc_task_attr(cmd) < 0) {
1589                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1590                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1591                 return -EINVAL;
1592         }
1593         spin_lock(&cmd->se_lun->lun_sep_lock);
1594         if (cmd->se_lun->lun_sep)
1595                 cmd->se_lun->lun_sep->sep_stats.cmd_pdus++;
1596         spin_unlock(&cmd->se_lun->lun_sep_lock);
1597         return 0;
1598 }
1599 EXPORT_SYMBOL(transport_generic_allocate_tasks);
1600
1601 /*
1602  * Used by fabric module frontends to queue tasks directly.
1603  * Many only be used from process context only
1604  */
1605 int transport_handle_cdb_direct(
1606         struct se_cmd *cmd)
1607 {
1608         int ret;
1609
1610         if (!cmd->se_lun) {
1611                 dump_stack();
1612                 pr_err("cmd->se_lun is NULL\n");
1613                 return -EINVAL;
1614         }
1615         if (in_interrupt()) {
1616                 dump_stack();
1617                 pr_err("transport_generic_handle_cdb cannot be called"
1618                                 " from interrupt context\n");
1619                 return -EINVAL;
1620         }
1621         /*
1622          * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE following
1623          * transport_generic_handle_cdb*() -> transport_add_cmd_to_queue()
1624          * in existing usage to ensure that outstanding descriptors are handled
1625          * correctly during shutdown via transport_wait_for_tasks()
1626          *
1627          * Also, we don't take cmd->t_state_lock here as we only expect
1628          * this to be called for initial descriptor submission.
1629          */
1630         cmd->t_state = TRANSPORT_NEW_CMD;
1631         cmd->transport_state |= CMD_T_ACTIVE;
1632
1633         /*
1634          * transport_generic_new_cmd() is already handling QUEUE_FULL,
1635          * so follow TRANSPORT_NEW_CMD processing thread context usage
1636          * and call transport_generic_request_failure() if necessary..
1637          */
1638         ret = transport_generic_new_cmd(cmd);
1639         if (ret < 0)
1640                 transport_generic_request_failure(cmd);
1641
1642         return 0;
1643 }
1644 EXPORT_SYMBOL(transport_handle_cdb_direct);
1645
1646 /**
1647  * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1648  *
1649  * @se_cmd: command descriptor to submit
1650  * @se_sess: associated se_sess for endpoint
1651  * @cdb: pointer to SCSI CDB
1652  * @sense: pointer to SCSI sense buffer
1653  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1654  * @data_length: fabric expected data transfer length
1655  * @task_addr: SAM task attribute
1656  * @data_dir: DMA data direction
1657  * @flags: flags for command submission from target_sc_flags_tables
1658  *
1659  * This may only be called from process context, and also currently
1660  * assumes internal allocation of fabric payload buffer by target-core.
1661  **/
1662 void target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1663                 unsigned char *cdb, unsigned char *sense, u32 unpacked_lun,
1664                 u32 data_length, int task_attr, int data_dir, int flags)
1665 {
1666         struct se_portal_group *se_tpg;
1667         int rc;
1668
1669         se_tpg = se_sess->se_tpg;
1670         BUG_ON(!se_tpg);
1671         BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1672         BUG_ON(in_interrupt());
1673         /*
1674          * Initialize se_cmd for target operation.  From this point
1675          * exceptions are handled by sending exception status via
1676          * target_core_fabric_ops->queue_status() callback
1677          */
1678         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1679                                 data_length, data_dir, task_attr, sense);
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 = transport_generic_allocate_tasks(se_cmd, cdb);
1706         if (rc != 0) {
1707                 transport_generic_request_failure(se_cmd);
1708                 return;
1709         }
1710         /*
1711          * Dispatch se_cmd descriptor to se_lun->lun_se_dev backend
1712          * for immediate execution of READs, otherwise wait for
1713          * transport_generic_handle_data() to be called for WRITEs
1714          * when fabric has filled the incoming buffer.
1715          */
1716         transport_handle_cdb_direct(se_cmd);
1717         return;
1718 }
1719 EXPORT_SYMBOL(target_submit_cmd);
1720
1721 static void target_complete_tmr_failure(struct work_struct *work)
1722 {
1723         struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1724
1725         se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1726         se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1727         transport_generic_free_cmd(se_cmd, 0);
1728 }
1729
1730 /**
1731  * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1732  *                     for TMR CDBs
1733  *
1734  * @se_cmd: command descriptor to submit
1735  * @se_sess: associated se_sess for endpoint
1736  * @sense: pointer to SCSI sense buffer
1737  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1738  * @fabric_context: fabric context for TMR req
1739  * @tm_type: Type of TM request
1740  * @gfp: gfp type for caller
1741  * @tag: referenced task tag for TMR_ABORT_TASK
1742  * @flags: submit cmd flags
1743  *
1744  * Callable from all contexts.
1745  **/
1746
1747 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1748                 unsigned char *sense, u32 unpacked_lun,
1749                 void *fabric_tmr_ptr, unsigned char tm_type,
1750                 gfp_t gfp, unsigned int tag, int flags)
1751 {
1752         struct se_portal_group *se_tpg;
1753         int ret;
1754
1755         se_tpg = se_sess->se_tpg;
1756         BUG_ON(!se_tpg);
1757
1758         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1759                               0, DMA_NONE, MSG_SIMPLE_TAG, sense);
1760         /*
1761          * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1762          * allocation failure.
1763          */
1764         ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1765         if (ret < 0)
1766                 return -ENOMEM;
1767
1768         if (tm_type == TMR_ABORT_TASK)
1769                 se_cmd->se_tmr_req->ref_task_tag = tag;
1770
1771         /* See target_submit_cmd for commentary */
1772         target_get_sess_cmd(se_sess, se_cmd, (flags & TARGET_SCF_ACK_KREF));
1773
1774         ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun);
1775         if (ret) {
1776                 /*
1777                  * For callback during failure handling, push this work off
1778                  * to process context with TMR_LUN_DOES_NOT_EXIST status.
1779                  */
1780                 INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1781                 schedule_work(&se_cmd->work);
1782                 return 0;
1783         }
1784         transport_generic_handle_tmr(se_cmd);
1785         return 0;
1786 }
1787 EXPORT_SYMBOL(target_submit_tmr);
1788
1789 /*
1790  * Used by fabric module frontends defining a TFO->new_cmd_map() caller
1791  * to  queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD_MAP in order to
1792  * complete setup in TCM process context w/ TFO->new_cmd_map().
1793  */
1794 int transport_generic_handle_cdb_map(
1795         struct se_cmd *cmd)
1796 {
1797         if (!cmd->se_lun) {
1798                 dump_stack();
1799                 pr_err("cmd->se_lun is NULL\n");
1800                 return -EINVAL;
1801         }
1802
1803         transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD_MAP, false);
1804         return 0;
1805 }
1806 EXPORT_SYMBOL(transport_generic_handle_cdb_map);
1807
1808 /*      transport_generic_handle_data():
1809  *
1810  *
1811  */
1812 int transport_generic_handle_data(
1813         struct se_cmd *cmd)
1814 {
1815         /*
1816          * For the software fabric case, then we assume the nexus is being
1817          * failed/shutdown when signals are pending from the kthread context
1818          * caller, so we return a failure.  For the HW target mode case running
1819          * in interrupt code, the signal_pending() check is skipped.
1820          */
1821         if (!in_interrupt() && signal_pending(current))
1822                 return -EPERM;
1823         /*
1824          * If the received CDB has aleady been ABORTED by the generic
1825          * target engine, we now call transport_check_aborted_status()
1826          * to queue any delated TASK_ABORTED status for the received CDB to the
1827          * fabric module as we are expecting no further incoming DATA OUT
1828          * sequences at this point.
1829          */
1830         if (transport_check_aborted_status(cmd, 1) != 0)
1831                 return 0;
1832
1833         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_WRITE, false);
1834         return 0;
1835 }
1836 EXPORT_SYMBOL(transport_generic_handle_data);
1837
1838 /*      transport_generic_handle_tmr():
1839  *
1840  *
1841  */
1842 int transport_generic_handle_tmr(
1843         struct se_cmd *cmd)
1844 {
1845         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_TMR, false);
1846         return 0;
1847 }
1848 EXPORT_SYMBOL(transport_generic_handle_tmr);
1849
1850 /*
1851  * If the task is active, request it to be stopped and sleep until it
1852  * has completed.
1853  */
1854 bool target_stop_task(struct se_task *task, unsigned long *flags)
1855 {
1856         struct se_cmd *cmd = task->task_se_cmd;
1857         bool was_active = false;
1858
1859         if (task->task_flags & TF_ACTIVE) {
1860                 task->task_flags |= TF_REQUEST_STOP;
1861                 spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
1862
1863                 pr_debug("Task %p waiting to complete\n", task);
1864                 wait_for_completion(&task->task_stop_comp);
1865                 pr_debug("Task %p stopped successfully\n", task);
1866
1867                 spin_lock_irqsave(&cmd->t_state_lock, *flags);
1868                 atomic_dec(&cmd->t_task_cdbs_left);
1869                 task->task_flags &= ~(TF_ACTIVE | TF_REQUEST_STOP);
1870                 was_active = true;
1871         }
1872
1873         return was_active;
1874 }
1875
1876 static int transport_stop_tasks_for_cmd(struct se_cmd *cmd)
1877 {
1878         struct se_task *task, *task_tmp;
1879         unsigned long flags;
1880         int ret = 0;
1881
1882         pr_debug("ITT[0x%08x] - Stopping tasks\n",
1883                 cmd->se_tfo->get_task_tag(cmd));
1884
1885         /*
1886          * No tasks remain in the execution queue
1887          */
1888         spin_lock_irqsave(&cmd->t_state_lock, flags);
1889         list_for_each_entry_safe(task, task_tmp,
1890                                 &cmd->t_task_list, t_list) {
1891                 pr_debug("Processing task %p\n", task);
1892                 /*
1893                  * If the struct se_task has not been sent and is not active,
1894                  * remove the struct se_task from the execution queue.
1895                  */
1896                 if (!(task->task_flags & (TF_ACTIVE | TF_SENT))) {
1897                         spin_unlock_irqrestore(&cmd->t_state_lock,
1898                                         flags);
1899                         transport_remove_task_from_execute_queue(task,
1900                                         cmd->se_dev);
1901
1902                         pr_debug("Task %p removed from execute queue\n", task);
1903                         spin_lock_irqsave(&cmd->t_state_lock, flags);
1904                         continue;
1905                 }
1906
1907                 if (!target_stop_task(task, &flags)) {
1908                         pr_debug("Task %p - did nothing\n", task);
1909                         ret++;
1910                 }
1911         }
1912         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1913
1914         return ret;
1915 }
1916
1917 /*
1918  * Handle SAM-esque emulation for generic transport request failures.
1919  */
1920 void transport_generic_request_failure(struct se_cmd *cmd)
1921 {
1922         int ret = 0;
1923
1924         pr_debug("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
1925                 " CDB: 0x%02x\n", cmd, cmd->se_tfo->get_task_tag(cmd),
1926                 cmd->t_task_cdb[0]);
1927         pr_debug("-----[ i_state: %d t_state: %d scsi_sense_reason: %d\n",
1928                 cmd->se_tfo->get_cmd_state(cmd),
1929                 cmd->t_state, cmd->scsi_sense_reason);
1930         pr_debug("-----[ t_tasks: %d t_task_cdbs_left: %d"
1931                 " t_task_cdbs_sent: %d t_task_cdbs_ex_left: %d --"
1932                 " CMD_T_ACTIVE: %d CMD_T_STOP: %d CMD_T_SENT: %d\n",
1933                 cmd->t_task_list_num,
1934                 atomic_read(&cmd->t_task_cdbs_left),
1935                 atomic_read(&cmd->t_task_cdbs_sent),
1936                 atomic_read(&cmd->t_task_cdbs_ex_left),
1937                 (cmd->transport_state & CMD_T_ACTIVE) != 0,
1938                 (cmd->transport_state & CMD_T_STOP) != 0,
1939                 (cmd->transport_state & CMD_T_SENT) != 0);
1940
1941         /*
1942          * For SAM Task Attribute emulation for failed struct se_cmd
1943          */
1944         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1945                 transport_complete_task_attr(cmd);
1946
1947         switch (cmd->scsi_sense_reason) {
1948         case TCM_NON_EXISTENT_LUN:
1949         case TCM_UNSUPPORTED_SCSI_OPCODE:
1950         case TCM_INVALID_CDB_FIELD:
1951         case TCM_INVALID_PARAMETER_LIST:
1952         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1953         case TCM_UNKNOWN_MODE_PAGE:
1954         case TCM_WRITE_PROTECTED:
1955         case TCM_CHECK_CONDITION_ABORT_CMD:
1956         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1957         case TCM_CHECK_CONDITION_NOT_READY:
1958                 break;
1959         case TCM_RESERVATION_CONFLICT:
1960                 /*
1961                  * No SENSE Data payload for this case, set SCSI Status
1962                  * and queue the response to $FABRIC_MOD.
1963                  *
1964                  * Uses linux/include/scsi/scsi.h SAM status codes defs
1965                  */
1966                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1967                 /*
1968                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1969                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1970                  * CONFLICT STATUS.
1971                  *
1972                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1973                  */
1974                 if (cmd->se_sess &&
1975                     cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
1976                         core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
1977                                 cmd->orig_fe_lun, 0x2C,
1978                                 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1979
1980                 ret = cmd->se_tfo->queue_status(cmd);
1981                 if (ret == -EAGAIN || ret == -ENOMEM)
1982                         goto queue_full;
1983                 goto check_stop;
1984         default:
1985                 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1986                         cmd->t_task_cdb[0], cmd->scsi_sense_reason);
1987                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1988                 break;
1989         }
1990         /*
1991          * If a fabric does not define a cmd->se_tfo->new_cmd_map caller,
1992          * make the call to transport_send_check_condition_and_sense()
1993          * directly.  Otherwise expect the fabric to make the call to
1994          * transport_send_check_condition_and_sense() after handling
1995          * possible unsoliticied write data payloads.
1996          */
1997         ret = transport_send_check_condition_and_sense(cmd,
1998                         cmd->scsi_sense_reason, 0);
1999         if (ret == -EAGAIN || ret == -ENOMEM)
2000                 goto queue_full;
2001
2002 check_stop:
2003         transport_lun_remove_cmd(cmd);
2004         if (!transport_cmd_check_stop_to_fabric(cmd))
2005                 ;
2006         return;
2007
2008 queue_full:
2009         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
2010         transport_handle_queue_full(cmd, cmd->se_dev);
2011 }
2012 EXPORT_SYMBOL(transport_generic_request_failure);
2013
2014 static inline u32 transport_lba_21(unsigned char *cdb)
2015 {
2016         return ((cdb[1] & 0x1f) << 16) | (cdb[2] << 8) | cdb[3];
2017 }
2018
2019 static inline u32 transport_lba_32(unsigned char *cdb)
2020 {
2021         return (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
2022 }
2023
2024 static inline unsigned long long transport_lba_64(unsigned char *cdb)
2025 {
2026         unsigned int __v1, __v2;
2027
2028         __v1 = (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
2029         __v2 = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
2030
2031         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
2032 }
2033
2034 /*
2035  * For VARIABLE_LENGTH_CDB w/ 32 byte extended CDBs
2036  */
2037 static inline unsigned long long transport_lba_64_ext(unsigned char *cdb)
2038 {
2039         unsigned int __v1, __v2;
2040
2041         __v1 = (cdb[12] << 24) | (cdb[13] << 16) | (cdb[14] << 8) | cdb[15];
2042         __v2 = (cdb[16] << 24) | (cdb[17] << 16) | (cdb[18] << 8) | cdb[19];
2043
2044         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
2045 }
2046
2047 static void transport_set_supported_SAM_opcode(struct se_cmd *se_cmd)
2048 {
2049         unsigned long flags;
2050
2051         spin_lock_irqsave(&se_cmd->t_state_lock, flags);
2052         se_cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
2053         spin_unlock_irqrestore(&se_cmd->t_state_lock, flags);
2054 }
2055
2056 /*
2057  * Called from Fabric Module context from transport_execute_tasks()
2058  *
2059  * The return of this function determins if the tasks from struct se_cmd
2060  * get added to the execution queue in transport_execute_tasks(),
2061  * or are added to the delayed or ordered lists here.
2062  */
2063 static inline int transport_execute_task_attr(struct se_cmd *cmd)
2064 {
2065         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
2066                 return 1;
2067         /*
2068          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
2069          * to allow the passed struct se_cmd list of tasks to the front of the list.
2070          */
2071          if (cmd->sam_task_attr == MSG_HEAD_TAG) {
2072                 pr_debug("Added HEAD_OF_QUEUE for CDB:"
2073                         " 0x%02x, se_ordered_id: %u\n",
2074                         cmd->t_task_cdb[0],
2075                         cmd->se_ordered_id);
2076                 return 1;
2077         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
2078                 atomic_inc(&cmd->se_dev->dev_ordered_sync);
2079                 smp_mb__after_atomic_inc();
2080
2081                 pr_debug("Added ORDERED for CDB: 0x%02x to ordered"
2082                                 " list, se_ordered_id: %u\n",
2083                                 cmd->t_task_cdb[0],
2084                                 cmd->se_ordered_id);
2085                 /*
2086                  * Add ORDERED command to tail of execution queue if
2087                  * no other older commands exist that need to be
2088                  * completed first.
2089                  */
2090                 if (!atomic_read(&cmd->se_dev->simple_cmds))
2091                         return 1;
2092         } else {
2093                 /*
2094                  * For SIMPLE and UNTAGGED Task Attribute commands
2095                  */
2096                 atomic_inc(&cmd->se_dev->simple_cmds);
2097                 smp_mb__after_atomic_inc();
2098         }
2099         /*
2100          * Otherwise if one or more outstanding ORDERED task attribute exist,
2101          * add the dormant task(s) built for the passed struct se_cmd to the
2102          * execution queue and become in Active state for this struct se_device.
2103          */
2104         if (atomic_read(&cmd->se_dev->dev_ordered_sync) != 0) {
2105                 /*
2106                  * Otherwise, add cmd w/ tasks to delayed cmd queue that
2107                  * will be drained upon completion of HEAD_OF_QUEUE task.
2108                  */
2109                 spin_lock(&cmd->se_dev->delayed_cmd_lock);
2110                 cmd->se_cmd_flags |= SCF_DELAYED_CMD_FROM_SAM_ATTR;
2111                 list_add_tail(&cmd->se_delayed_node,
2112                                 &cmd->se_dev->delayed_cmd_list);
2113                 spin_unlock(&cmd->se_dev->delayed_cmd_lock);
2114
2115                 pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to"
2116                         " delayed CMD list, se_ordered_id: %u\n",
2117                         cmd->t_task_cdb[0], cmd->sam_task_attr,
2118                         cmd->se_ordered_id);
2119                 /*
2120                  * Return zero to let transport_execute_tasks() know
2121                  * not to add the delayed tasks to the execution list.
2122                  */
2123                 return 0;
2124         }
2125         /*
2126          * Otherwise, no ORDERED task attributes exist..
2127          */
2128         return 1;
2129 }
2130
2131 /*
2132  * Called from fabric module context in transport_generic_new_cmd() and
2133  * transport_generic_process_write()
2134  */
2135 static int transport_execute_tasks(struct se_cmd *cmd)
2136 {
2137         int add_tasks;
2138         struct se_device *se_dev = cmd->se_dev;
2139         /*
2140          * Call transport_cmd_check_stop() to see if a fabric exception
2141          * has occurred that prevents execution.
2142          */
2143         if (!transport_cmd_check_stop(cmd, 0, TRANSPORT_PROCESSING)) {
2144                 /*
2145                  * Check for SAM Task Attribute emulation and HEAD_OF_QUEUE
2146                  * attribute for the tasks of the received struct se_cmd CDB
2147                  */
2148                 add_tasks = transport_execute_task_attr(cmd);
2149                 if (!add_tasks)
2150                         goto execute_tasks;
2151                 /*
2152                  * __transport_execute_tasks() -> __transport_add_tasks_from_cmd()
2153                  * adds associated se_tasks while holding dev->execute_task_lock
2154                  * before I/O dispath to avoid a double spinlock access.
2155                  */
2156                 __transport_execute_tasks(se_dev, cmd);
2157                 return 0;
2158         }
2159
2160 execute_tasks:
2161         __transport_execute_tasks(se_dev, NULL);
2162         return 0;
2163 }
2164
2165 /*
2166  * Called to check struct se_device tcq depth window, and once open pull struct se_task
2167  * from struct se_device->execute_task_list and
2168  *
2169  * Called from transport_processing_thread()
2170  */
2171 static int __transport_execute_tasks(struct se_device *dev, struct se_cmd *new_cmd)
2172 {
2173         int error;
2174         struct se_cmd *cmd = NULL;
2175         struct se_task *task = NULL;
2176         unsigned long flags;
2177
2178 check_depth:
2179         spin_lock_irq(&dev->execute_task_lock);
2180         if (new_cmd != NULL)
2181                 __transport_add_tasks_from_cmd(new_cmd);
2182
2183         if (list_empty(&dev->execute_task_list)) {
2184                 spin_unlock_irq(&dev->execute_task_lock);
2185                 return 0;
2186         }
2187         task = list_first_entry(&dev->execute_task_list,
2188                                 struct se_task, t_execute_list);
2189         __transport_remove_task_from_execute_queue(task, dev);
2190         spin_unlock_irq(&dev->execute_task_lock);
2191
2192         cmd = task->task_se_cmd;
2193         spin_lock_irqsave(&cmd->t_state_lock, flags);
2194         task->task_flags |= (TF_ACTIVE | TF_SENT);
2195         atomic_inc(&cmd->t_task_cdbs_sent);
2196
2197         if (atomic_read(&cmd->t_task_cdbs_sent) ==
2198             cmd->t_task_list_num)
2199                 cmd->transport_state |= CMD_T_SENT;
2200
2201         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2202
2203         if (cmd->execute_task)
2204                 error = cmd->execute_task(task);
2205         else
2206                 error = dev->transport->do_task(task);
2207         if (error != 0) {
2208                 spin_lock_irqsave(&cmd->t_state_lock, flags);
2209                 task->task_flags &= ~TF_ACTIVE;
2210                 cmd->transport_state &= ~CMD_T_SENT;
2211                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2212
2213                 transport_stop_tasks_for_cmd(cmd);
2214                 transport_generic_request_failure(cmd);
2215         }
2216
2217         new_cmd = NULL;
2218         goto check_depth;
2219
2220         return 0;
2221 }
2222
2223 static inline u32 transport_get_sectors_6(
2224         unsigned char *cdb,
2225         struct se_cmd *cmd,
2226         int *ret)
2227 {
2228         struct se_device *dev = cmd->se_dev;
2229
2230         /*
2231          * Assume TYPE_DISK for non struct se_device objects.
2232          * Use 8-bit sector value.
2233          */
2234         if (!dev)
2235                 goto type_disk;
2236
2237         /*
2238          * Use 24-bit allocation length for TYPE_TAPE.
2239          */
2240         if (dev->transport->get_device_type(dev) == TYPE_TAPE)
2241                 return (u32)(cdb[2] << 16) + (cdb[3] << 8) + cdb[4];
2242
2243         /*
2244          * Everything else assume TYPE_DISK Sector CDB location.
2245          * Use 8-bit sector value.  SBC-3 says:
2246          *
2247          *   A TRANSFER LENGTH field set to zero specifies that 256
2248          *   logical blocks shall be written.  Any other value
2249          *   specifies the number of logical blocks that shall be
2250          *   written.
2251          */
2252 type_disk:
2253         return cdb[4] ? : 256;
2254 }
2255
2256 static inline u32 transport_get_sectors_10(
2257         unsigned char *cdb,
2258         struct se_cmd *cmd,
2259         int *ret)
2260 {
2261         struct se_device *dev = cmd->se_dev;
2262
2263         /*
2264          * Assume TYPE_DISK for non struct se_device objects.
2265          * Use 16-bit sector value.
2266          */
2267         if (!dev)
2268                 goto type_disk;
2269
2270         /*
2271          * XXX_10 is not defined in SSC, throw an exception
2272          */
2273         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2274                 *ret = -EINVAL;
2275                 return 0;
2276         }
2277
2278         /*
2279          * Everything else assume TYPE_DISK Sector CDB location.
2280          * Use 16-bit sector value.
2281          */
2282 type_disk:
2283         return (u32)(cdb[7] << 8) + cdb[8];
2284 }
2285
2286 static inline u32 transport_get_sectors_12(
2287         unsigned char *cdb,
2288         struct se_cmd *cmd,
2289         int *ret)
2290 {
2291         struct se_device *dev = cmd->se_dev;
2292
2293         /*
2294          * Assume TYPE_DISK for non struct se_device objects.
2295          * Use 32-bit sector value.
2296          */
2297         if (!dev)
2298                 goto type_disk;
2299
2300         /*
2301          * XXX_12 is not defined in SSC, throw an exception
2302          */
2303         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2304                 *ret = -EINVAL;
2305                 return 0;
2306         }
2307
2308         /*
2309          * Everything else assume TYPE_DISK Sector CDB location.
2310          * Use 32-bit sector value.
2311          */
2312 type_disk:
2313         return (u32)(cdb[6] << 24) + (cdb[7] << 16) + (cdb[8] << 8) + cdb[9];
2314 }
2315
2316 static inline u32 transport_get_sectors_16(
2317         unsigned char *cdb,
2318         struct se_cmd *cmd,
2319         int *ret)
2320 {
2321         struct se_device *dev = cmd->se_dev;
2322
2323         /*
2324          * Assume TYPE_DISK for non struct se_device objects.
2325          * Use 32-bit sector value.
2326          */
2327         if (!dev)
2328                 goto type_disk;
2329
2330         /*
2331          * Use 24-bit allocation length for TYPE_TAPE.
2332          */
2333         if (dev->transport->get_device_type(dev) == TYPE_TAPE)
2334                 return (u32)(cdb[12] << 16) + (cdb[13] << 8) + cdb[14];
2335
2336 type_disk:
2337         return (u32)(cdb[10] << 24) + (cdb[11] << 16) +
2338                     (cdb[12] << 8) + cdb[13];
2339 }
2340
2341 /*
2342  * Used for VARIABLE_LENGTH_CDB WRITE_32 and READ_32 variants
2343  */
2344 static inline u32 transport_get_sectors_32(
2345         unsigned char *cdb,
2346         struct se_cmd *cmd,
2347         int *ret)
2348 {
2349         /*
2350          * Assume TYPE_DISK for non struct se_device objects.
2351          * Use 32-bit sector value.
2352          */
2353         return (u32)(cdb[28] << 24) + (cdb[29] << 16) +
2354                     (cdb[30] << 8) + cdb[31];
2355
2356 }
2357
2358 static inline u32 transport_get_size(
2359         u32 sectors,
2360         unsigned char *cdb,
2361         struct se_cmd *cmd)
2362 {
2363         struct se_device *dev = cmd->se_dev;
2364
2365         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2366                 if (cdb[1] & 1) { /* sectors */
2367                         return dev->se_sub_dev->se_dev_attrib.block_size * sectors;
2368                 } else /* bytes */
2369                         return sectors;
2370         }
2371 #if 0
2372         pr_debug("Returning block_size: %u, sectors: %u == %u for"
2373                         " %s object\n", dev->se_sub_dev->se_dev_attrib.block_size, sectors,
2374                         dev->se_sub_dev->se_dev_attrib.block_size * sectors,
2375                         dev->transport->name);
2376 #endif
2377         return dev->se_sub_dev->se_dev_attrib.block_size * sectors;
2378 }
2379
2380 static void transport_xor_callback(struct se_cmd *cmd)
2381 {
2382         unsigned char *buf, *addr;
2383         struct scatterlist *sg;
2384         unsigned int offset;
2385         int i;
2386         int count;
2387         /*
2388          * From sbc3r22.pdf section 5.48 XDWRITEREAD (10) command
2389          *
2390          * 1) read the specified logical block(s);
2391          * 2) transfer logical blocks from the data-out buffer;
2392          * 3) XOR the logical blocks transferred from the data-out buffer with
2393          *    the logical blocks read, storing the resulting XOR data in a buffer;
2394          * 4) if the DISABLE WRITE bit is set to zero, then write the logical
2395          *    blocks transferred from the data-out buffer; and
2396          * 5) transfer the resulting XOR data to the data-in buffer.
2397          */
2398         buf = kmalloc(cmd->data_length, GFP_KERNEL);
2399         if (!buf) {
2400                 pr_err("Unable to allocate xor_callback buf\n");
2401                 return;
2402         }
2403         /*
2404          * Copy the scatterlist WRITE buffer located at cmd->t_data_sg
2405          * into the locally allocated *buf
2406          */
2407         sg_copy_to_buffer(cmd->t_data_sg,
2408                           cmd->t_data_nents,
2409                           buf,
2410                           cmd->data_length);
2411
2412         /*
2413          * Now perform the XOR against the BIDI read memory located at
2414          * cmd->t_mem_bidi_list
2415          */
2416
2417         offset = 0;
2418         for_each_sg(cmd->t_bidi_data_sg, sg, cmd->t_bidi_data_nents, count) {
2419                 addr = kmap_atomic(sg_page(sg), KM_USER0);
2420                 if (!addr)
2421                         goto out;
2422
2423                 for (i = 0; i < sg->length; i++)
2424                         *(addr + sg->offset + i) ^= *(buf + offset + i);
2425
2426                 offset += sg->length;
2427                 kunmap_atomic(addr, KM_USER0);
2428         }
2429
2430 out:
2431         kfree(buf);
2432 }
2433
2434 /*
2435  * Used to obtain Sense Data from underlying Linux/SCSI struct scsi_cmnd
2436  */
2437 static int transport_get_sense_data(struct se_cmd *cmd)
2438 {
2439         unsigned char *buffer = cmd->sense_buffer, *sense_buffer = NULL;
2440         struct se_device *dev = cmd->se_dev;
2441         struct se_task *task = NULL, *task_tmp;
2442         unsigned long flags;
2443         u32 offset = 0;
2444
2445         WARN_ON(!cmd->se_lun);
2446
2447         if (!dev)
2448                 return 0;
2449
2450         spin_lock_irqsave(&cmd->t_state_lock, flags);
2451         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
2452                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2453                 return 0;
2454         }
2455
2456         list_for_each_entry_safe(task, task_tmp,
2457                                 &cmd->t_task_list, t_list) {
2458                 if (!(task->task_flags & TF_HAS_SENSE))
2459                         continue;
2460
2461                 if (!dev->transport->get_sense_buffer) {
2462                         pr_err("dev->transport->get_sense_buffer"
2463                                         " is NULL\n");
2464                         continue;
2465                 }
2466
2467                 sense_buffer = dev->transport->get_sense_buffer(task);
2468                 if (!sense_buffer) {
2469                         pr_err("ITT[0x%08x]_TASK[%p]: Unable to locate"
2470                                 " sense buffer for task with sense\n",
2471                                 cmd->se_tfo->get_task_tag(cmd), task);
2472                         continue;
2473                 }
2474                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2475
2476                 offset = cmd->se_tfo->set_fabric_sense_len(cmd,
2477                                 TRANSPORT_SENSE_BUFFER);
2478
2479                 memcpy(&buffer[offset], sense_buffer,
2480                                 TRANSPORT_SENSE_BUFFER);
2481                 cmd->scsi_status = task->task_scsi_status;
2482                 /* Automatically padded */
2483                 cmd->scsi_sense_length =
2484                                 (TRANSPORT_SENSE_BUFFER + offset);
2485
2486                 pr_debug("HBA_[%u]_PLUG[%s]: Set SAM STATUS: 0x%02x"
2487                                 " and sense\n",
2488                         dev->se_hba->hba_id, dev->transport->name,
2489                                 cmd->scsi_status);
2490                 return 0;
2491         }
2492         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2493
2494         return -1;
2495 }
2496
2497 static inline long long transport_dev_end_lba(struct se_device *dev)
2498 {
2499         return dev->transport->get_blocks(dev) + 1;
2500 }
2501
2502 static int transport_cmd_get_valid_sectors(struct se_cmd *cmd)
2503 {
2504         struct se_device *dev = cmd->se_dev;
2505         u32 sectors;
2506
2507         if (dev->transport->get_device_type(dev) != TYPE_DISK)
2508                 return 0;
2509
2510         sectors = (cmd->data_length / dev->se_sub_dev->se_dev_attrib.block_size);
2511
2512         if ((cmd->t_task_lba + sectors) > transport_dev_end_lba(dev)) {
2513                 pr_err("LBA: %llu Sectors: %u exceeds"
2514                         " transport_dev_end_lba(): %llu\n",
2515                         cmd->t_task_lba, sectors,
2516                         transport_dev_end_lba(dev));
2517                 return -EINVAL;
2518         }
2519
2520         return 0;
2521 }
2522
2523 static int target_check_write_same_discard(unsigned char *flags, struct se_device *dev)
2524 {
2525         /*
2526          * Determine if the received WRITE_SAME is used to for direct
2527          * passthrough into Linux/SCSI with struct request via TCM/pSCSI
2528          * or we are signaling the use of internal WRITE_SAME + UNMAP=1
2529          * emulation for -> Linux/BLOCK disbard with TCM/IBLOCK code.
2530          */
2531         int passthrough = (dev->transport->transport_type ==
2532                                 TRANSPORT_PLUGIN_PHBA_PDEV);
2533
2534         if (!passthrough) {
2535                 if ((flags[0] & 0x04) || (flags[0] & 0x02)) {
2536                         pr_err("WRITE_SAME PBDATA and LBDATA"
2537                                 " bits not supported for Block Discard"
2538                                 " Emulation\n");
2539                         return -ENOSYS;
2540                 }
2541                 /*
2542                  * Currently for the emulated case we only accept
2543                  * tpws with the UNMAP=1 bit set.
2544                  */
2545                 if (!(flags[0] & 0x08)) {
2546                         pr_err("WRITE_SAME w/o UNMAP bit not"
2547                                 " supported for Block Discard Emulation\n");
2548                         return -ENOSYS;
2549                 }
2550         }
2551
2552         return 0;
2553 }
2554
2555 /*      transport_generic_cmd_sequencer():
2556  *
2557  *      Generic Command Sequencer that should work for most DAS transport
2558  *      drivers.
2559  *
2560  *      Called from transport_generic_allocate_tasks() in the $FABRIC_MOD
2561  *      RX Thread.
2562  *
2563  *      FIXME: Need to support other SCSI OPCODES where as well.
2564  */
2565 static int transport_generic_cmd_sequencer(
2566         struct se_cmd *cmd,
2567         unsigned char *cdb)
2568 {
2569         struct se_device *dev = cmd->se_dev;
2570         struct se_subsystem_dev *su_dev = dev->se_sub_dev;
2571         int ret = 0, sector_ret = 0, passthrough;
2572         u32 sectors = 0, size = 0, pr_reg_type = 0;
2573         u16 service_action;
2574         u8 alua_ascq = 0;
2575         /*
2576          * Check for an existing UNIT ATTENTION condition
2577          */
2578         if (core_scsi3_ua_check(cmd, cdb) < 0) {
2579                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2580                 cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
2581                 return -EINVAL;
2582         }
2583         /*
2584          * Check status of Asymmetric Logical Unit Assignment port
2585          */
2586         ret = su_dev->t10_alua.alua_state_check(cmd, cdb, &alua_ascq);
2587         if (ret != 0) {
2588                 /*
2589                  * Set SCSI additional sense code (ASC) to 'LUN Not Accessible';
2590                  * The ALUA additional sense code qualifier (ASCQ) is determined
2591                  * by the ALUA primary or secondary access state..
2592                  */
2593                 if (ret > 0) {
2594 #if 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 #endif
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_sense_reason = TCM_RESERVATION_CONFLICT;
2615                         return -EBUSY;
2616                 }
2617                 /*
2618                  * This means the CDB is allowed for the SCSI Initiator port
2619                  * when said port is *NOT* holding the legacy SPC-2 or
2620                  * SPC-3 Persistent Reservation.
2621                  */
2622         }
2623
2624         /*
2625          * If we operate in passthrough mode we skip most CDB emulation and
2626          * instead hand the commands down to the physical SCSI device.
2627          */
2628         passthrough =
2629                 (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV);
2630
2631         switch (cdb[0]) {
2632         case READ_6:
2633                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
2634                 if (sector_ret)
2635                         goto out_unsupported_cdb;
2636                 size = transport_get_size(sectors, cdb, cmd);
2637                 cmd->t_task_lba = transport_lba_21(cdb);
2638                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2639                 break;
2640         case READ_10:
2641                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2642                 if (sector_ret)
2643                         goto out_unsupported_cdb;
2644                 size = transport_get_size(sectors, cdb, cmd);
2645                 cmd->t_task_lba = transport_lba_32(cdb);
2646                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2647                 break;
2648         case READ_12:
2649                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
2650                 if (sector_ret)
2651                         goto out_unsupported_cdb;
2652                 size = transport_get_size(sectors, cdb, cmd);
2653                 cmd->t_task_lba = transport_lba_32(cdb);
2654                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2655                 break;
2656         case READ_16:
2657                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
2658                 if (sector_ret)
2659                         goto out_unsupported_cdb;
2660                 size = transport_get_size(sectors, cdb, cmd);
2661                 cmd->t_task_lba = transport_lba_64(cdb);
2662                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2663                 break;
2664         case WRITE_6:
2665                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
2666                 if (sector_ret)
2667                         goto out_unsupported_cdb;
2668                 size = transport_get_size(sectors, cdb, cmd);
2669                 cmd->t_task_lba = transport_lba_21(cdb);
2670                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2671                 break;
2672         case WRITE_10:
2673                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2674                 if (sector_ret)
2675                         goto out_unsupported_cdb;
2676                 size = transport_get_size(sectors, cdb, cmd);
2677                 cmd->t_task_lba = transport_lba_32(cdb);
2678                 if (cdb[1] & 0x8)
2679                         cmd->se_cmd_flags |= SCF_FUA;
2680                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2681                 break;
2682         case WRITE_12:
2683                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
2684                 if (sector_ret)
2685                         goto out_unsupported_cdb;
2686                 size = transport_get_size(sectors, cdb, cmd);
2687                 cmd->t_task_lba = transport_lba_32(cdb);
2688                 if (cdb[1] & 0x8)
2689                         cmd->se_cmd_flags |= SCF_FUA;
2690                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2691                 break;
2692         case WRITE_16:
2693                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
2694                 if (sector_ret)
2695                         goto out_unsupported_cdb;
2696                 size = transport_get_size(sectors, cdb, cmd);
2697                 cmd->t_task_lba = transport_lba_64(cdb);
2698                 if (cdb[1] & 0x8)
2699                         cmd->se_cmd_flags |= SCF_FUA;
2700                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2701                 break;
2702         case XDWRITEREAD_10:
2703                 if ((cmd->data_direction != DMA_TO_DEVICE) ||
2704                     !(cmd->se_cmd_flags & SCF_BIDI))
2705                         goto out_invalid_cdb_field;
2706                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2707                 if (sector_ret)
2708                         goto out_unsupported_cdb;
2709                 size = transport_get_size(sectors, cdb, cmd);
2710                 cmd->t_task_lba = transport_lba_32(cdb);
2711                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2712
2713                 /*
2714                  * Do now allow BIDI commands for passthrough mode.
2715                  */
2716                 if (passthrough)
2717                         goto out_unsupported_cdb;
2718
2719                 /*
2720                  * Setup BIDI XOR callback to be run after I/O completion.
2721                  */
2722                 cmd->transport_complete_callback = &transport_xor_callback;
2723                 if (cdb[1] & 0x8)
2724                         cmd->se_cmd_flags |= SCF_FUA;
2725                 break;
2726         case VARIABLE_LENGTH_CMD:
2727                 service_action = get_unaligned_be16(&cdb[8]);
2728                 switch (service_action) {
2729                 case XDWRITEREAD_32:
2730                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
2731                         if (sector_ret)
2732                                 goto out_unsupported_cdb;
2733                         size = transport_get_size(sectors, cdb, cmd);
2734                         /*
2735                          * Use WRITE_32 and READ_32 opcodes for the emulated
2736                          * XDWRITE_READ_32 logic.
2737                          */
2738                         cmd->t_task_lba = transport_lba_64_ext(cdb);
2739                         cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2740
2741                         /*
2742                          * Do now allow BIDI commands for passthrough mode.
2743                          */
2744                         if (passthrough)
2745                                 goto out_unsupported_cdb;
2746
2747                         /*
2748                          * Setup BIDI XOR callback to be run during after I/O
2749                          * completion.
2750                          */
2751                         cmd->transport_complete_callback = &transport_xor_callback;
2752                         if (cdb[1] & 0x8)
2753                                 cmd->se_cmd_flags |= SCF_FUA;
2754                         break;
2755                 case WRITE_SAME_32:
2756                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
2757                         if (sector_ret)
2758                                 goto out_unsupported_cdb;
2759
2760                         if (sectors)
2761                                 size = transport_get_size(1, cdb, cmd);
2762                         else {
2763                                 pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not"
2764                                        " supported\n");
2765                                 goto out_invalid_cdb_field;
2766                         }
2767
2768                         cmd->t_task_lba = get_unaligned_be64(&cdb[12]);
2769                         cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2770
2771                         if (target_check_write_same_discard(&cdb[10], dev) < 0)
2772                                 goto out_unsupported_cdb;
2773                         if (!passthrough)
2774                                 cmd->execute_task = target_emulate_write_same;
2775                         break;
2776                 default:
2777                         pr_err("VARIABLE_LENGTH_CMD service action"
2778                                 " 0x%04x not supported\n", service_action);
2779                         goto out_unsupported_cdb;
2780                 }
2781                 break;
2782         case MAINTENANCE_IN:
2783                 if (dev->transport->get_device_type(dev) != TYPE_ROM) {
2784                         /* MAINTENANCE_IN from SCC-2 */
2785                         /*
2786                          * Check for emulated MI_REPORT_TARGET_PGS.
2787                          */
2788                         if (cdb[1] == MI_REPORT_TARGET_PGS &&
2789                             su_dev->t10_alua.alua_type == SPC3_ALUA_EMULATED) {
2790                                 cmd->execute_task =
2791                                         target_emulate_report_target_port_groups;
2792                         }
2793                         size = (cdb[6] << 24) | (cdb[7] << 16) |
2794                                (cdb[8] << 8) | cdb[9];
2795                 } else {
2796                         /* GPCMD_SEND_KEY from multi media commands */
2797                         size = (cdb[8] << 8) + cdb[9];
2798                 }
2799                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2800                 break;
2801         case MODE_SELECT:
2802                 size = cdb[4];
2803                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2804                 break;
2805         case MODE_SELECT_10:
2806                 size = (cdb[7] << 8) + cdb[8];
2807                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2808                 break;
2809         case MODE_SENSE:
2810                 size = cdb[4];
2811                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2812                 if (!passthrough)
2813                         cmd->execute_task = target_emulate_modesense;
2814                 break;
2815         case MODE_SENSE_10:
2816                 size = (cdb[7] << 8) + cdb[8];
2817                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2818                 if (!passthrough)
2819                         cmd->execute_task = target_emulate_modesense;
2820                 break;
2821         case GPCMD_READ_BUFFER_CAPACITY:
2822         case GPCMD_SEND_OPC:
2823         case LOG_SELECT:
2824         case LOG_SENSE:
2825                 size = (cdb[7] << 8) + cdb[8];
2826                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2827                 break;
2828         case READ_BLOCK_LIMITS:
2829                 size = READ_BLOCK_LEN;
2830                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2831                 break;
2832         case GPCMD_GET_CONFIGURATION:
2833         case GPCMD_READ_FORMAT_CAPACITIES:
2834         case GPCMD_READ_DISC_INFO:
2835         case GPCMD_READ_TRACK_RZONE_INFO:
2836                 size = (cdb[7] << 8) + cdb[8];
2837                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2838                 break;
2839         case PERSISTENT_RESERVE_IN:
2840                 if (su_dev->t10_pr.res_type == SPC3_PERSISTENT_RESERVATIONS)
2841                         cmd->execute_task = target_scsi3_emulate_pr_in;
2842                 size = (cdb[7] << 8) + cdb[8];
2843                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2844                 break;
2845         case PERSISTENT_RESERVE_OUT:
2846                 if (su_dev->t10_pr.res_type == SPC3_PERSISTENT_RESERVATIONS)
2847                         cmd->execute_task = target_scsi3_emulate_pr_out;
2848                 size = (cdb[7] << 8) + cdb[8];
2849                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2850                 break;
2851         case GPCMD_MECHANISM_STATUS:
2852         case GPCMD_READ_DVD_STRUCTURE:
2853                 size = (cdb[8] << 8) + cdb[9];
2854                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2855                 break;
2856         case READ_POSITION:
2857                 size = READ_POSITION_LEN;
2858                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2859                 break;
2860         case MAINTENANCE_OUT:
2861                 if (dev->transport->get_device_type(dev) != TYPE_ROM) {
2862                         /* MAINTENANCE_OUT from SCC-2
2863                          *
2864                          * Check for emulated MO_SET_TARGET_PGS.
2865                          */
2866                         if (cdb[1] == MO_SET_TARGET_PGS &&
2867                             su_dev->t10_alua.alua_type == SPC3_ALUA_EMULATED) {
2868                                 cmd->execute_task =
2869                                         target_emulate_set_target_port_groups;
2870                         }
2871
2872                         size = (cdb[6] << 24) | (cdb[7] << 16) |
2873                                (cdb[8] << 8) | cdb[9];
2874                 } else  {
2875                         /* GPCMD_REPORT_KEY from multi media commands */
2876                         size = (cdb[8] << 8) + cdb[9];
2877                 }
2878                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2879                 break;
2880         case INQUIRY:
2881                 size = (cdb[3] << 8) + cdb[4];
2882                 /*
2883                  * Do implict HEAD_OF_QUEUE processing for INQUIRY.
2884                  * See spc4r17 section 5.3
2885                  */
2886                 if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
2887                         cmd->sam_task_attr = MSG_HEAD_TAG;
2888                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2889                 if (!passthrough)
2890                         cmd->execute_task = target_emulate_inquiry;
2891                 break;
2892         case READ_BUFFER:
2893                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
2894                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2895                 break;
2896         case READ_CAPACITY:
2897                 size = READ_CAP_LEN;
2898                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2899                 if (!passthrough)
2900                         cmd->execute_task = target_emulate_readcapacity;
2901                 break;
2902         case READ_MEDIA_SERIAL_NUMBER:
2903         case SECURITY_PROTOCOL_IN:
2904         case SECURITY_PROTOCOL_OUT:
2905                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
2906                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2907                 break;
2908         case SERVICE_ACTION_IN:
2909                 switch (cmd->t_task_cdb[1] & 0x1f) {
2910                 case SAI_READ_CAPACITY_16:
2911                         if (!passthrough)
2912                                 cmd->execute_task =
2913                                         target_emulate_readcapacity_16;
2914                         break;
2915                 default:
2916                         if (passthrough)
2917                                 break;
2918
2919                         pr_err("Unsupported SA: 0x%02x\n",
2920                                 cmd->t_task_cdb[1] & 0x1f);
2921                         goto out_unsupported_cdb;
2922                 }
2923                 /*FALLTHROUGH*/
2924         case ACCESS_CONTROL_IN:
2925         case ACCESS_CONTROL_OUT:
2926         case EXTENDED_COPY:
2927         case READ_ATTRIBUTE:
2928         case RECEIVE_COPY_RESULTS:
2929         case WRITE_ATTRIBUTE:
2930                 size = (cdb[10] << 24) | (cdb[11] << 16) |
2931                        (cdb[12] << 8) | cdb[13];
2932                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2933                 break;
2934         case RECEIVE_DIAGNOSTIC:
2935         case SEND_DIAGNOSTIC:
2936                 size = (cdb[3] << 8) | cdb[4];
2937                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2938                 break;
2939 /* #warning FIXME: Figure out correct GPCMD_READ_CD blocksize. */
2940 #if 0
2941         case GPCMD_READ_CD:
2942                 sectors = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
2943                 size = (2336 * sectors);
2944                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2945                 break;
2946 #endif
2947         case READ_TOC:
2948                 size = cdb[8];
2949                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2950                 break;
2951         case REQUEST_SENSE:
2952                 size = cdb[4];
2953                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2954                 if (!passthrough)
2955                         cmd->execute_task = target_emulate_request_sense;
2956                 break;
2957         case READ_ELEMENT_STATUS:
2958                 size = 65536 * cdb[7] + 256 * cdb[8] + cdb[9];
2959                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2960                 break;
2961         case WRITE_BUFFER:
2962                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
2963                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2964                 break;
2965         case RESERVE:
2966         case RESERVE_10:
2967                 /*
2968                  * The SPC-2 RESERVE does not contain a size in the SCSI CDB.
2969                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
2970                  */
2971                 if (cdb[0] == RESERVE_10)
2972                         size = (cdb[7] << 8) | cdb[8];
2973                 else
2974                         size = cmd->data_length;
2975
2976                 /*
2977                  * Setup the legacy emulated handler for SPC-2 and
2978                  * >= SPC-3 compatible reservation handling (CRH=1)
2979                  * Otherwise, we assume the underlying SCSI logic is
2980                  * is running in SPC_PASSTHROUGH, and wants reservations
2981                  * emulation disabled.
2982                  */
2983                 if (su_dev->t10_pr.res_type != SPC_PASSTHROUGH)
2984                         cmd->execute_task = target_scsi2_reservation_reserve;
2985                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
2986                 break;
2987         case RELEASE:
2988         case RELEASE_10:
2989                 /*
2990                  * The SPC-2 RELEASE does not contain a size in the SCSI CDB.
2991                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
2992                 */
2993                 if (cdb[0] == RELEASE_10)
2994                         size = (cdb[7] << 8) | cdb[8];
2995                 else
2996                         size = cmd->data_length;
2997
2998                 if (su_dev->t10_pr.res_type != SPC_PASSTHROUGH)
2999                         cmd->execute_task = target_scsi2_reservation_release;
3000                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3001                 break;
3002         case SYNCHRONIZE_CACHE:
3003         case SYNCHRONIZE_CACHE_16:
3004                 /*
3005                  * Extract LBA and range to be flushed for emulated SYNCHRONIZE_CACHE
3006                  */
3007                 if (cdb[0] == SYNCHRONIZE_CACHE) {
3008                         sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3009                         cmd->t_task_lba = transport_lba_32(cdb);
3010                 } else {
3011                         sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3012                         cmd->t_task_lba = transport_lba_64(cdb);
3013                 }
3014                 if (sector_ret)
3015                         goto out_unsupported_cdb;
3016
3017                 size = transport_get_size(sectors, cdb, cmd);
3018                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3019
3020                 if (passthrough)
3021                         break;
3022
3023                 /*
3024                  * Check to ensure that LBA + Range does not exceed past end of
3025                  * device for IBLOCK and FILEIO ->do_sync_cache() backend calls
3026                  */
3027                 if ((cmd->t_task_lba != 0) || (sectors != 0)) {
3028                         if (transport_cmd_get_valid_sectors(cmd) < 0)
3029                                 goto out_invalid_cdb_field;
3030                 }
3031                 cmd->execute_task = target_emulate_synchronize_cache;
3032                 break;
3033         case UNMAP:
3034                 size = get_unaligned_be16(&cdb[7]);
3035                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3036                 if (!passthrough)
3037                         cmd->execute_task = target_emulate_unmap;
3038                 break;
3039         case WRITE_SAME_16:
3040                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3041                 if (sector_ret)
3042                         goto out_unsupported_cdb;
3043
3044                 if (sectors)
3045                         size = transport_get_size(1, cdb, cmd);
3046                 else {
3047                         pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not supported\n");
3048                         goto out_invalid_cdb_field;
3049                 }
3050
3051                 cmd->t_task_lba = get_unaligned_be64(&cdb[2]);
3052                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3053
3054                 if (target_check_write_same_discard(&cdb[1], dev) < 0)
3055                         goto out_unsupported_cdb;
3056                 if (!passthrough)
3057                         cmd->execute_task = target_emulate_write_same;
3058                 break;
3059         case WRITE_SAME:
3060                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3061                 if (sector_ret)
3062                         goto out_unsupported_cdb;
3063
3064                 if (sectors)
3065                         size = transport_get_size(1, cdb, cmd);
3066                 else {
3067                         pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not supported\n");
3068                         goto out_invalid_cdb_field;
3069                 }
3070
3071                 cmd->t_task_lba = get_unaligned_be32(&cdb[2]);
3072                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3073                 /*
3074                  * Follow sbcr26 with WRITE_SAME (10) and check for the existence
3075                  * of byte 1 bit 3 UNMAP instead of original reserved field
3076                  */
3077                 if (target_check_write_same_discard(&cdb[1], dev) < 0)
3078                         goto out_unsupported_cdb;
3079                 if (!passthrough)
3080                         cmd->execute_task = target_emulate_write_same;
3081                 break;
3082         case ALLOW_MEDIUM_REMOVAL:
3083         case ERASE:
3084         case REZERO_UNIT:
3085         case SEEK_10:
3086         case SPACE:
3087         case START_STOP:
3088         case TEST_UNIT_READY:
3089         case VERIFY:
3090         case WRITE_FILEMARKS:
3091                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3092                 if (!passthrough)
3093                         cmd->execute_task = target_emulate_noop;
3094                 break;
3095         case GPCMD_CLOSE_TRACK:
3096         case INITIALIZE_ELEMENT_STATUS:
3097         case GPCMD_LOAD_UNLOAD:
3098         case GPCMD_SET_SPEED:
3099         case MOVE_MEDIUM:
3100                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3101                 break;
3102         case REPORT_LUNS:
3103                 cmd->execute_task = target_report_luns;
3104                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
3105                 /*
3106                  * Do implict HEAD_OF_QUEUE processing for REPORT_LUNS
3107                  * See spc4r17 section 5.3
3108                  */
3109                 if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3110                         cmd->sam_task_attr = MSG_HEAD_TAG;
3111                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3112                 break;
3113         default:
3114                 pr_warn("TARGET_CORE[%s]: Unsupported SCSI Opcode"
3115                         &qu