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