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