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