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