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