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