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