1 /*******************************************************************************
2 * Filename: target_core_transport.c
4 * This file contains the Generic Target Engine Core.
6 * (c) Copyright 2002-2013 Datera, Inc.
8 * Nicholas A. Bellinger <nab@kernel.org>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 ******************************************************************************/
26 #include <linux/net.h>
27 #include <linux/delay.h>
28 #include <linux/string.h>
29 #include <linux/timer.h>
30 #include <linux/slab.h>
31 #include <linux/spinlock.h>
32 #include <linux/kthread.h>
34 #include <linux/cdrom.h>
35 #include <linux/module.h>
36 #include <linux/ratelimit.h>
37 #include <linux/vmalloc.h>
38 #include <asm/unaligned.h>
41 #include <scsi/scsi_proto.h>
42 #include <scsi/scsi_common.h>
44 #include <target/target_core_base.h>
45 #include <target/target_core_backend.h>
46 #include <target/target_core_fabric.h>
48 #include "target_core_internal.h"
49 #include "target_core_alua.h"
50 #include "target_core_pr.h"
51 #include "target_core_ua.h"
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/target.h>
56 static struct workqueue_struct *target_completion_wq;
57 static struct kmem_cache *se_sess_cache;
58 struct kmem_cache *se_ua_cache;
59 struct kmem_cache *t10_pr_reg_cache;
60 struct kmem_cache *t10_alua_lu_gp_cache;
61 struct kmem_cache *t10_alua_lu_gp_mem_cache;
62 struct kmem_cache *t10_alua_tg_pt_gp_cache;
63 struct kmem_cache *t10_alua_lba_map_cache;
64 struct kmem_cache *t10_alua_lba_map_mem_cache;
66 static void transport_complete_task_attr(struct se_cmd *cmd);
67 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason);
68 static void transport_handle_queue_full(struct se_cmd *cmd,
69 struct se_device *dev, int err, bool write_pending);
70 static void target_complete_ok_work(struct work_struct *work);
72 int init_se_kmem_caches(void)
74 se_sess_cache = kmem_cache_create("se_sess_cache",
75 sizeof(struct se_session), __alignof__(struct se_session),
78 pr_err("kmem_cache_create() for struct se_session"
82 se_ua_cache = kmem_cache_create("se_ua_cache",
83 sizeof(struct se_ua), __alignof__(struct se_ua),
86 pr_err("kmem_cache_create() for struct se_ua failed\n");
87 goto out_free_sess_cache;
89 t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
90 sizeof(struct t10_pr_registration),
91 __alignof__(struct t10_pr_registration), 0, NULL);
92 if (!t10_pr_reg_cache) {
93 pr_err("kmem_cache_create() for struct t10_pr_registration"
95 goto out_free_ua_cache;
97 t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
98 sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
100 if (!t10_alua_lu_gp_cache) {
101 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
103 goto out_free_pr_reg_cache;
105 t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
106 sizeof(struct t10_alua_lu_gp_member),
107 __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
108 if (!t10_alua_lu_gp_mem_cache) {
109 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
111 goto out_free_lu_gp_cache;
113 t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
114 sizeof(struct t10_alua_tg_pt_gp),
115 __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
116 if (!t10_alua_tg_pt_gp_cache) {
117 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
119 goto out_free_lu_gp_mem_cache;
121 t10_alua_lba_map_cache = kmem_cache_create(
122 "t10_alua_lba_map_cache",
123 sizeof(struct t10_alua_lba_map),
124 __alignof__(struct t10_alua_lba_map), 0, NULL);
125 if (!t10_alua_lba_map_cache) {
126 pr_err("kmem_cache_create() for t10_alua_lba_map_"
128 goto out_free_tg_pt_gp_cache;
130 t10_alua_lba_map_mem_cache = kmem_cache_create(
131 "t10_alua_lba_map_mem_cache",
132 sizeof(struct t10_alua_lba_map_member),
133 __alignof__(struct t10_alua_lba_map_member), 0, NULL);
134 if (!t10_alua_lba_map_mem_cache) {
135 pr_err("kmem_cache_create() for t10_alua_lba_map_mem_"
137 goto out_free_lba_map_cache;
140 target_completion_wq = alloc_workqueue("target_completion",
142 if (!target_completion_wq)
143 goto out_free_lba_map_mem_cache;
147 out_free_lba_map_mem_cache:
148 kmem_cache_destroy(t10_alua_lba_map_mem_cache);
149 out_free_lba_map_cache:
150 kmem_cache_destroy(t10_alua_lba_map_cache);
151 out_free_tg_pt_gp_cache:
152 kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
153 out_free_lu_gp_mem_cache:
154 kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
155 out_free_lu_gp_cache:
156 kmem_cache_destroy(t10_alua_lu_gp_cache);
157 out_free_pr_reg_cache:
158 kmem_cache_destroy(t10_pr_reg_cache);
160 kmem_cache_destroy(se_ua_cache);
162 kmem_cache_destroy(se_sess_cache);
167 void release_se_kmem_caches(void)
169 destroy_workqueue(target_completion_wq);
170 kmem_cache_destroy(se_sess_cache);
171 kmem_cache_destroy(se_ua_cache);
172 kmem_cache_destroy(t10_pr_reg_cache);
173 kmem_cache_destroy(t10_alua_lu_gp_cache);
174 kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
175 kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
176 kmem_cache_destroy(t10_alua_lba_map_cache);
177 kmem_cache_destroy(t10_alua_lba_map_mem_cache);
180 /* This code ensures unique mib indexes are handed out. */
181 static DEFINE_SPINLOCK(scsi_mib_index_lock);
182 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
185 * Allocate a new row index for the entry type specified
187 u32 scsi_get_new_index(scsi_index_t type)
191 BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
193 spin_lock(&scsi_mib_index_lock);
194 new_index = ++scsi_mib_index[type];
195 spin_unlock(&scsi_mib_index_lock);
200 void transport_subsystem_check_init(void)
203 static int sub_api_initialized;
205 if (sub_api_initialized)
208 ret = IS_ENABLED(CONFIG_TCM_IBLOCK) && request_module("target_core_iblock");
210 pr_err("Unable to load target_core_iblock\n");
212 ret = IS_ENABLED(CONFIG_TCM_FILEIO) && request_module("target_core_file");
214 pr_err("Unable to load target_core_file\n");
216 ret = IS_ENABLED(CONFIG_TCM_PSCSI) && request_module("target_core_pscsi");
218 pr_err("Unable to load target_core_pscsi\n");
220 ret = IS_ENABLED(CONFIG_TCM_USER2) && request_module("target_core_user");
222 pr_err("Unable to load target_core_user\n");
224 sub_api_initialized = 1;
227 static void target_release_sess_cmd_refcnt(struct percpu_ref *ref)
229 struct se_session *sess = container_of(ref, typeof(*sess), cmd_count);
231 wake_up(&sess->cmd_list_wq);
235 * transport_init_session - initialize a session object
236 * @se_sess: Session object pointer.
238 * The caller must have zero-initialized @se_sess before calling this function.
240 int transport_init_session(struct se_session *se_sess)
242 INIT_LIST_HEAD(&se_sess->sess_list);
243 INIT_LIST_HEAD(&se_sess->sess_acl_list);
244 INIT_LIST_HEAD(&se_sess->sess_cmd_list);
245 spin_lock_init(&se_sess->sess_cmd_lock);
246 init_waitqueue_head(&se_sess->cmd_list_wq);
247 return percpu_ref_init(&se_sess->cmd_count,
248 target_release_sess_cmd_refcnt, 0, GFP_KERNEL);
250 EXPORT_SYMBOL(transport_init_session);
253 * transport_alloc_session - allocate a session object and initialize it
254 * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
256 struct se_session *transport_alloc_session(enum target_prot_op sup_prot_ops)
258 struct se_session *se_sess;
261 se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
263 pr_err("Unable to allocate struct se_session from"
265 return ERR_PTR(-ENOMEM);
267 ret = transport_init_session(se_sess);
269 kmem_cache_free(se_sess_cache, se_sess);
272 se_sess->sup_prot_ops = sup_prot_ops;
276 EXPORT_SYMBOL(transport_alloc_session);
279 * transport_alloc_session_tags - allocate target driver private data
280 * @se_sess: Session pointer.
281 * @tag_num: Maximum number of in-flight commands between initiator and target.
282 * @tag_size: Size in bytes of the private data a target driver associates with
285 int transport_alloc_session_tags(struct se_session *se_sess,
286 unsigned int tag_num, unsigned int tag_size)
290 se_sess->sess_cmd_map = kvcalloc(tag_size, tag_num,
291 GFP_KERNEL | __GFP_RETRY_MAYFAIL);
292 if (!se_sess->sess_cmd_map) {
293 pr_err("Unable to allocate se_sess->sess_cmd_map\n");
297 rc = sbitmap_queue_init_node(&se_sess->sess_tag_pool, tag_num, -1,
298 false, GFP_KERNEL, NUMA_NO_NODE);
300 pr_err("Unable to init se_sess->sess_tag_pool,"
301 " tag_num: %u\n", tag_num);
302 kvfree(se_sess->sess_cmd_map);
303 se_sess->sess_cmd_map = NULL;
309 EXPORT_SYMBOL(transport_alloc_session_tags);
312 * transport_init_session_tags - allocate a session and target driver private data
313 * @tag_num: Maximum number of in-flight commands between initiator and target.
314 * @tag_size: Size in bytes of the private data a target driver associates with
316 * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
318 static struct se_session *
319 transport_init_session_tags(unsigned int tag_num, unsigned int tag_size,
320 enum target_prot_op sup_prot_ops)
322 struct se_session *se_sess;
325 if (tag_num != 0 && !tag_size) {
326 pr_err("init_session_tags called with percpu-ida tag_num:"
327 " %u, but zero tag_size\n", tag_num);
328 return ERR_PTR(-EINVAL);
330 if (!tag_num && tag_size) {
331 pr_err("init_session_tags called with percpu-ida tag_size:"
332 " %u, but zero tag_num\n", tag_size);
333 return ERR_PTR(-EINVAL);
336 se_sess = transport_alloc_session(sup_prot_ops);
340 rc = transport_alloc_session_tags(se_sess, tag_num, tag_size);
342 transport_free_session(se_sess);
343 return ERR_PTR(-ENOMEM);
350 * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
352 void __transport_register_session(
353 struct se_portal_group *se_tpg,
354 struct se_node_acl *se_nacl,
355 struct se_session *se_sess,
356 void *fabric_sess_ptr)
358 const struct target_core_fabric_ops *tfo = se_tpg->se_tpg_tfo;
359 unsigned char buf[PR_REG_ISID_LEN];
362 se_sess->se_tpg = se_tpg;
363 se_sess->fabric_sess_ptr = fabric_sess_ptr;
365 * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
367 * Only set for struct se_session's that will actually be moving I/O.
368 * eg: *NOT* discovery sessions.
373 * Determine if fabric allows for T10-PI feature bits exposed to
374 * initiators for device backends with !dev->dev_attrib.pi_prot_type.
376 * If so, then always save prot_type on a per se_node_acl node
377 * basis and re-instate the previous sess_prot_type to avoid
378 * disabling PI from below any previously initiator side
381 if (se_nacl->saved_prot_type)
382 se_sess->sess_prot_type = se_nacl->saved_prot_type;
383 else if (tfo->tpg_check_prot_fabric_only)
384 se_sess->sess_prot_type = se_nacl->saved_prot_type =
385 tfo->tpg_check_prot_fabric_only(se_tpg);
387 * If the fabric module supports an ISID based TransportID,
388 * save this value in binary from the fabric I_T Nexus now.
390 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
391 memset(&buf[0], 0, PR_REG_ISID_LEN);
392 se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
393 &buf[0], PR_REG_ISID_LEN);
394 se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
397 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
399 * The se_nacl->nacl_sess pointer will be set to the
400 * last active I_T Nexus for each struct se_node_acl.
402 se_nacl->nacl_sess = se_sess;
404 list_add_tail(&se_sess->sess_acl_list,
405 &se_nacl->acl_sess_list);
406 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
408 list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
410 pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
411 se_tpg->se_tpg_tfo->fabric_name, se_sess->fabric_sess_ptr);
413 EXPORT_SYMBOL(__transport_register_session);
415 void transport_register_session(
416 struct se_portal_group *se_tpg,
417 struct se_node_acl *se_nacl,
418 struct se_session *se_sess,
419 void *fabric_sess_ptr)
423 spin_lock_irqsave(&se_tpg->session_lock, flags);
424 __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
425 spin_unlock_irqrestore(&se_tpg->session_lock, flags);
427 EXPORT_SYMBOL(transport_register_session);
430 target_setup_session(struct se_portal_group *tpg,
431 unsigned int tag_num, unsigned int tag_size,
432 enum target_prot_op prot_op,
433 const char *initiatorname, void *private,
434 int (*callback)(struct se_portal_group *,
435 struct se_session *, void *))
437 struct se_session *sess;
440 * If the fabric driver is using percpu-ida based pre allocation
441 * of I/O descriptor tags, go ahead and perform that setup now..
444 sess = transport_init_session_tags(tag_num, tag_size, prot_op);
446 sess = transport_alloc_session(prot_op);
451 sess->se_node_acl = core_tpg_check_initiator_node_acl(tpg,
452 (unsigned char *)initiatorname);
453 if (!sess->se_node_acl) {
454 transport_free_session(sess);
455 return ERR_PTR(-EACCES);
458 * Go ahead and perform any remaining fabric setup that is
459 * required before transport_register_session().
461 if (callback != NULL) {
462 int rc = callback(tpg, sess, private);
464 transport_free_session(sess);
469 transport_register_session(tpg, sess->se_node_acl, sess, private);
472 EXPORT_SYMBOL(target_setup_session);
474 ssize_t target_show_dynamic_sessions(struct se_portal_group *se_tpg, char *page)
476 struct se_session *se_sess;
479 spin_lock_bh(&se_tpg->session_lock);
480 list_for_each_entry(se_sess, &se_tpg->tpg_sess_list, sess_list) {
481 if (!se_sess->se_node_acl)
483 if (!se_sess->se_node_acl->dynamic_node_acl)
485 if (strlen(se_sess->se_node_acl->initiatorname) + 1 + len > PAGE_SIZE)
488 len += snprintf(page + len, PAGE_SIZE - len, "%s\n",
489 se_sess->se_node_acl->initiatorname);
490 len += 1; /* Include NULL terminator */
492 spin_unlock_bh(&se_tpg->session_lock);
496 EXPORT_SYMBOL(target_show_dynamic_sessions);
498 static void target_complete_nacl(struct kref *kref)
500 struct se_node_acl *nacl = container_of(kref,
501 struct se_node_acl, acl_kref);
502 struct se_portal_group *se_tpg = nacl->se_tpg;
504 if (!nacl->dynamic_stop) {
505 complete(&nacl->acl_free_comp);
509 mutex_lock(&se_tpg->acl_node_mutex);
510 list_del_init(&nacl->acl_list);
511 mutex_unlock(&se_tpg->acl_node_mutex);
513 core_tpg_wait_for_nacl_pr_ref(nacl);
514 core_free_device_list_for_node(nacl, se_tpg);
518 void target_put_nacl(struct se_node_acl *nacl)
520 kref_put(&nacl->acl_kref, target_complete_nacl);
522 EXPORT_SYMBOL(target_put_nacl);
524 void transport_deregister_session_configfs(struct se_session *se_sess)
526 struct se_node_acl *se_nacl;
529 * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
531 se_nacl = se_sess->se_node_acl;
533 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
534 if (!list_empty(&se_sess->sess_acl_list))
535 list_del_init(&se_sess->sess_acl_list);
537 * If the session list is empty, then clear the pointer.
538 * Otherwise, set the struct se_session pointer from the tail
539 * element of the per struct se_node_acl active session list.
541 if (list_empty(&se_nacl->acl_sess_list))
542 se_nacl->nacl_sess = NULL;
544 se_nacl->nacl_sess = container_of(
545 se_nacl->acl_sess_list.prev,
546 struct se_session, sess_acl_list);
548 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
551 EXPORT_SYMBOL(transport_deregister_session_configfs);
553 void transport_free_session(struct se_session *se_sess)
555 struct se_node_acl *se_nacl = se_sess->se_node_acl;
558 * Drop the se_node_acl->nacl_kref obtained from within
559 * core_tpg_get_initiator_node_acl().
562 struct se_portal_group *se_tpg = se_nacl->se_tpg;
563 const struct target_core_fabric_ops *se_tfo = se_tpg->se_tpg_tfo;
566 se_sess->se_node_acl = NULL;
569 * Also determine if we need to drop the extra ->cmd_kref if
570 * it had been previously dynamically generated, and
571 * the endpoint is not caching dynamic ACLs.
573 mutex_lock(&se_tpg->acl_node_mutex);
574 if (se_nacl->dynamic_node_acl &&
575 !se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
576 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
577 if (list_empty(&se_nacl->acl_sess_list))
578 se_nacl->dynamic_stop = true;
579 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
581 if (se_nacl->dynamic_stop)
582 list_del_init(&se_nacl->acl_list);
584 mutex_unlock(&se_tpg->acl_node_mutex);
586 if (se_nacl->dynamic_stop)
587 target_put_nacl(se_nacl);
589 target_put_nacl(se_nacl);
591 if (se_sess->sess_cmd_map) {
592 sbitmap_queue_free(&se_sess->sess_tag_pool);
593 kvfree(se_sess->sess_cmd_map);
595 percpu_ref_exit(&se_sess->cmd_count);
596 kmem_cache_free(se_sess_cache, se_sess);
598 EXPORT_SYMBOL(transport_free_session);
600 void transport_deregister_session(struct se_session *se_sess)
602 struct se_portal_group *se_tpg = se_sess->se_tpg;
606 transport_free_session(se_sess);
610 spin_lock_irqsave(&se_tpg->session_lock, flags);
611 list_del(&se_sess->sess_list);
612 se_sess->se_tpg = NULL;
613 se_sess->fabric_sess_ptr = NULL;
614 spin_unlock_irqrestore(&se_tpg->session_lock, flags);
616 pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
617 se_tpg->se_tpg_tfo->fabric_name);
619 * If last kref is dropping now for an explicit NodeACL, awake sleeping
620 * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
621 * removal context from within transport_free_session() code.
623 * For dynamic ACL, target_put_nacl() uses target_complete_nacl()
624 * to release all remaining generate_node_acl=1 created ACL resources.
627 transport_free_session(se_sess);
629 EXPORT_SYMBOL(transport_deregister_session);
631 void target_remove_session(struct se_session *se_sess)
633 transport_deregister_session_configfs(se_sess);
634 transport_deregister_session(se_sess);
636 EXPORT_SYMBOL(target_remove_session);
638 static void target_remove_from_state_list(struct se_cmd *cmd)
640 struct se_device *dev = cmd->se_dev;
646 spin_lock_irqsave(&dev->execute_task_lock, flags);
647 if (cmd->state_active) {
648 list_del(&cmd->state_list);
649 cmd->state_active = false;
651 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
655 * This function is called by the target core after the target core has
656 * finished processing a SCSI command or SCSI TMF. Both the regular command
657 * processing code and the code for aborting commands can call this
658 * function. CMD_T_STOP is set if and only if another thread is waiting
659 * inside transport_wait_for_tasks() for t_transport_stop_comp.
661 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
665 target_remove_from_state_list(cmd);
668 * Clear struct se_cmd->se_lun before the handoff to FE.
672 spin_lock_irqsave(&cmd->t_state_lock, flags);
674 * Determine if frontend context caller is requesting the stopping of
675 * this command for frontend exceptions.
677 if (cmd->transport_state & CMD_T_STOP) {
678 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
679 __func__, __LINE__, cmd->tag);
681 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
683 complete_all(&cmd->t_transport_stop_comp);
686 cmd->transport_state &= ~CMD_T_ACTIVE;
687 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
690 * Some fabric modules like tcm_loop can release their internally
691 * allocated I/O reference and struct se_cmd now.
693 * Fabric modules are expected to return '1' here if the se_cmd being
694 * passed is released at this point, or zero if not being released.
696 return cmd->se_tfo->check_stop_free(cmd);
699 static void transport_lun_remove_cmd(struct se_cmd *cmd)
701 struct se_lun *lun = cmd->se_lun;
706 if (cmpxchg(&cmd->lun_ref_active, true, false))
707 percpu_ref_put(&lun->lun_ref);
710 static void target_complete_failure_work(struct work_struct *work)
712 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
714 transport_generic_request_failure(cmd,
715 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
719 * Used when asking transport to copy Sense Data from the underlying
720 * Linux/SCSI struct scsi_cmnd
722 static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd)
724 struct se_device *dev = cmd->se_dev;
726 WARN_ON(!cmd->se_lun);
731 if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION)
734 cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
736 pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n",
737 dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
738 return cmd->sense_buffer;
741 void transport_copy_sense_to_cmd(struct se_cmd *cmd, unsigned char *sense)
743 unsigned char *cmd_sense_buf;
746 spin_lock_irqsave(&cmd->t_state_lock, flags);
747 cmd_sense_buf = transport_get_sense_buffer(cmd);
748 if (!cmd_sense_buf) {
749 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
753 cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
754 memcpy(cmd_sense_buf, sense, cmd->scsi_sense_length);
755 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
757 EXPORT_SYMBOL(transport_copy_sense_to_cmd);
759 static void target_handle_abort(struct se_cmd *cmd)
761 bool tas = cmd->transport_state & CMD_T_TAS;
762 bool ack_kref = cmd->se_cmd_flags & SCF_ACK_KREF;
765 pr_debug("tag %#llx: send_abort_response = %d\n", cmd->tag, tas);
768 if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
769 cmd->scsi_status = SAM_STAT_TASK_ABORTED;
770 pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x, ITT: 0x%08llx\n",
771 cmd->t_task_cdb[0], cmd->tag);
772 trace_target_cmd_complete(cmd);
773 ret = cmd->se_tfo->queue_status(cmd);
775 transport_handle_queue_full(cmd, cmd->se_dev,
780 cmd->se_tmr_req->response = TMR_FUNCTION_REJECTED;
781 cmd->se_tfo->queue_tm_rsp(cmd);
785 * Allow the fabric driver to unmap any resources before
786 * releasing the descriptor via TFO->release_cmd().
788 cmd->se_tfo->aborted_task(cmd);
790 WARN_ON_ONCE(target_put_sess_cmd(cmd) != 0);
792 * To do: establish a unit attention condition on the I_T
793 * nexus associated with cmd. See also the paragraph "Aborting
798 WARN_ON_ONCE(kref_read(&cmd->cmd_kref) == 0);
800 transport_lun_remove_cmd(cmd);
802 transport_cmd_check_stop_to_fabric(cmd);
805 static void target_abort_work(struct work_struct *work)
807 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
809 target_handle_abort(cmd);
812 static bool target_cmd_interrupted(struct se_cmd *cmd)
816 if (cmd->transport_state & CMD_T_ABORTED) {
817 if (cmd->transport_complete_callback)
818 cmd->transport_complete_callback(cmd, false, &post_ret);
819 INIT_WORK(&cmd->work, target_abort_work);
820 queue_work(target_completion_wq, &cmd->work);
822 } else if (cmd->transport_state & CMD_T_STOP) {
823 if (cmd->transport_complete_callback)
824 cmd->transport_complete_callback(cmd, false, &post_ret);
825 complete_all(&cmd->t_transport_stop_comp);
832 /* May be called from interrupt context so must not sleep. */
833 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
838 if (target_cmd_interrupted(cmd))
841 cmd->scsi_status = scsi_status;
843 spin_lock_irqsave(&cmd->t_state_lock, flags);
844 switch (cmd->scsi_status) {
845 case SAM_STAT_CHECK_CONDITION:
846 if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
856 cmd->t_state = TRANSPORT_COMPLETE;
857 cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
858 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
860 INIT_WORK(&cmd->work, success ? target_complete_ok_work :
861 target_complete_failure_work);
862 if (cmd->se_cmd_flags & SCF_USE_CPUID)
863 queue_work_on(cmd->cpuid, target_completion_wq, &cmd->work);
865 queue_work(target_completion_wq, &cmd->work);
867 EXPORT_SYMBOL(target_complete_cmd);
869 void target_complete_cmd_with_length(struct se_cmd *cmd, u8 scsi_status, int length)
871 if ((scsi_status == SAM_STAT_GOOD ||
872 cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
873 length < cmd->data_length) {
874 if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
875 cmd->residual_count += cmd->data_length - length;
877 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
878 cmd->residual_count = cmd->data_length - length;
881 cmd->data_length = length;
884 target_complete_cmd(cmd, scsi_status);
886 EXPORT_SYMBOL(target_complete_cmd_with_length);
888 static void target_add_to_state_list(struct se_cmd *cmd)
890 struct se_device *dev = cmd->se_dev;
893 spin_lock_irqsave(&dev->execute_task_lock, flags);
894 if (!cmd->state_active) {
895 list_add_tail(&cmd->state_list, &dev->state_list);
896 cmd->state_active = true;
898 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
902 * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
904 static void transport_write_pending_qf(struct se_cmd *cmd);
905 static void transport_complete_qf(struct se_cmd *cmd);
907 void target_qf_do_work(struct work_struct *work)
909 struct se_device *dev = container_of(work, struct se_device,
911 LIST_HEAD(qf_cmd_list);
912 struct se_cmd *cmd, *cmd_tmp;
914 spin_lock_irq(&dev->qf_cmd_lock);
915 list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
916 spin_unlock_irq(&dev->qf_cmd_lock);
918 list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
919 list_del(&cmd->se_qf_node);
920 atomic_dec_mb(&dev->dev_qf_count);
922 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
923 " context: %s\n", cmd->se_tfo->fabric_name, cmd,
924 (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
925 (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
928 if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
929 transport_write_pending_qf(cmd);
930 else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK ||
931 cmd->t_state == TRANSPORT_COMPLETE_QF_ERR)
932 transport_complete_qf(cmd);
936 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
938 switch (cmd->data_direction) {
941 case DMA_FROM_DEVICE:
945 case DMA_BIDIRECTIONAL:
954 void transport_dump_dev_state(
955 struct se_device *dev,
959 *bl += sprintf(b + *bl, "Status: ");
960 if (dev->export_count)
961 *bl += sprintf(b + *bl, "ACTIVATED");
963 *bl += sprintf(b + *bl, "DEACTIVATED");
965 *bl += sprintf(b + *bl, " Max Queue Depth: %d", dev->queue_depth);
966 *bl += sprintf(b + *bl, " SectorSize: %u HwMaxSectors: %u\n",
967 dev->dev_attrib.block_size,
968 dev->dev_attrib.hw_max_sectors);
969 *bl += sprintf(b + *bl, " ");
972 void transport_dump_vpd_proto_id(
974 unsigned char *p_buf,
977 unsigned char buf[VPD_TMP_BUF_SIZE];
980 memset(buf, 0, VPD_TMP_BUF_SIZE);
981 len = sprintf(buf, "T10 VPD Protocol Identifier: ");
983 switch (vpd->protocol_identifier) {
985 sprintf(buf+len, "Fibre Channel\n");
988 sprintf(buf+len, "Parallel SCSI\n");
991 sprintf(buf+len, "SSA\n");
994 sprintf(buf+len, "IEEE 1394\n");
997 sprintf(buf+len, "SCSI Remote Direct Memory Access"
1001 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
1004 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
1007 sprintf(buf+len, "Automation/Drive Interface Transport"
1011 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
1014 sprintf(buf+len, "Unknown 0x%02x\n",
1015 vpd->protocol_identifier);
1020 strncpy(p_buf, buf, p_buf_len);
1022 pr_debug("%s", buf);
1026 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1029 * Check if the Protocol Identifier Valid (PIV) bit is set..
1031 * from spc3r23.pdf section 7.5.1
1033 if (page_83[1] & 0x80) {
1034 vpd->protocol_identifier = (page_83[0] & 0xf0);
1035 vpd->protocol_identifier_set = 1;
1036 transport_dump_vpd_proto_id(vpd, NULL, 0);
1039 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1041 int transport_dump_vpd_assoc(
1042 struct t10_vpd *vpd,
1043 unsigned char *p_buf,
1046 unsigned char buf[VPD_TMP_BUF_SIZE];
1050 memset(buf, 0, VPD_TMP_BUF_SIZE);
1051 len = sprintf(buf, "T10 VPD Identifier Association: ");
1053 switch (vpd->association) {
1055 sprintf(buf+len, "addressed logical unit\n");
1058 sprintf(buf+len, "target port\n");
1061 sprintf(buf+len, "SCSI target device\n");
1064 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1070 strncpy(p_buf, buf, p_buf_len);
1072 pr_debug("%s", buf);
1077 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1080 * The VPD identification association..
1082 * from spc3r23.pdf Section 7.6.3.1 Table 297
1084 vpd->association = (page_83[1] & 0x30);
1085 return transport_dump_vpd_assoc(vpd, NULL, 0);
1087 EXPORT_SYMBOL(transport_set_vpd_assoc);
1089 int transport_dump_vpd_ident_type(
1090 struct t10_vpd *vpd,
1091 unsigned char *p_buf,
1094 unsigned char buf[VPD_TMP_BUF_SIZE];
1098 memset(buf, 0, VPD_TMP_BUF_SIZE);
1099 len = sprintf(buf, "T10 VPD Identifier Type: ");
1101 switch (vpd->device_identifier_type) {
1103 sprintf(buf+len, "Vendor specific\n");
1106 sprintf(buf+len, "T10 Vendor ID based\n");
1109 sprintf(buf+len, "EUI-64 based\n");
1112 sprintf(buf+len, "NAA\n");
1115 sprintf(buf+len, "Relative target port identifier\n");
1118 sprintf(buf+len, "SCSI name string\n");
1121 sprintf(buf+len, "Unsupported: 0x%02x\n",
1122 vpd->device_identifier_type);
1128 if (p_buf_len < strlen(buf)+1)
1130 strncpy(p_buf, buf, p_buf_len);
1132 pr_debug("%s", buf);
1138 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1141 * The VPD identifier type..
1143 * from spc3r23.pdf Section 7.6.3.1 Table 298
1145 vpd->device_identifier_type = (page_83[1] & 0x0f);
1146 return transport_dump_vpd_ident_type(vpd, NULL, 0);
1148 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1150 int transport_dump_vpd_ident(
1151 struct t10_vpd *vpd,
1152 unsigned char *p_buf,
1155 unsigned char buf[VPD_TMP_BUF_SIZE];
1158 memset(buf, 0, VPD_TMP_BUF_SIZE);
1160 switch (vpd->device_identifier_code_set) {
1161 case 0x01: /* Binary */
1162 snprintf(buf, sizeof(buf),
1163 "T10 VPD Binary Device Identifier: %s\n",
1164 &vpd->device_identifier[0]);
1166 case 0x02: /* ASCII */
1167 snprintf(buf, sizeof(buf),
1168 "T10 VPD ASCII Device Identifier: %s\n",
1169 &vpd->device_identifier[0]);
1171 case 0x03: /* UTF-8 */
1172 snprintf(buf, sizeof(buf),
1173 "T10 VPD UTF-8 Device Identifier: %s\n",
1174 &vpd->device_identifier[0]);
1177 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1178 " 0x%02x", vpd->device_identifier_code_set);
1184 strncpy(p_buf, buf, p_buf_len);
1186 pr_debug("%s", buf);
1192 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1194 static const char hex_str[] = "0123456789abcdef";
1195 int j = 0, i = 4; /* offset to start of the identifier */
1198 * The VPD Code Set (encoding)
1200 * from spc3r23.pdf Section 7.6.3.1 Table 296
1202 vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1203 switch (vpd->device_identifier_code_set) {
1204 case 0x01: /* Binary */
1205 vpd->device_identifier[j++] =
1206 hex_str[vpd->device_identifier_type];
1207 while (i < (4 + page_83[3])) {
1208 vpd->device_identifier[j++] =
1209 hex_str[(page_83[i] & 0xf0) >> 4];
1210 vpd->device_identifier[j++] =
1211 hex_str[page_83[i] & 0x0f];
1215 case 0x02: /* ASCII */
1216 case 0x03: /* UTF-8 */
1217 while (i < (4 + page_83[3]))
1218 vpd->device_identifier[j++] = page_83[i++];
1224 return transport_dump_vpd_ident(vpd, NULL, 0);
1226 EXPORT_SYMBOL(transport_set_vpd_ident);
1228 static sense_reason_t
1229 target_check_max_data_sg_nents(struct se_cmd *cmd, struct se_device *dev,
1234 if (!cmd->se_tfo->max_data_sg_nents)
1235 return TCM_NO_SENSE;
1237 * Check if fabric enforced maximum SGL entries per I/O descriptor
1238 * exceeds se_cmd->data_length. If true, set SCF_UNDERFLOW_BIT +
1239 * residual_count and reduce original cmd->data_length to maximum
1240 * length based on single PAGE_SIZE entry scatter-lists.
1242 mtl = (cmd->se_tfo->max_data_sg_nents * PAGE_SIZE);
1243 if (cmd->data_length > mtl) {
1245 * If an existing CDB overflow is present, calculate new residual
1246 * based on CDB size minus fabric maximum transfer length.
1248 * If an existing CDB underflow is present, calculate new residual
1249 * based on original cmd->data_length minus fabric maximum transfer
1252 * Otherwise, set the underflow residual based on cmd->data_length
1253 * minus fabric maximum transfer length.
1255 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1256 cmd->residual_count = (size - mtl);
1257 } else if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
1258 u32 orig_dl = size + cmd->residual_count;
1259 cmd->residual_count = (orig_dl - mtl);
1261 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1262 cmd->residual_count = (cmd->data_length - mtl);
1264 cmd->data_length = mtl;
1266 * Reset sbc_check_prot() calculated protection payload
1267 * length based upon the new smaller MTL.
1269 if (cmd->prot_length) {
1270 u32 sectors = (mtl / dev->dev_attrib.block_size);
1271 cmd->prot_length = dev->prot_length * sectors;
1274 return TCM_NO_SENSE;
1278 target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1280 struct se_device *dev = cmd->se_dev;
1282 if (cmd->unknown_data_length) {
1283 cmd->data_length = size;
1284 } else if (size != cmd->data_length) {
1285 pr_warn_ratelimited("TARGET_CORE[%s]: Expected Transfer Length:"
1286 " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1287 " 0x%02x\n", cmd->se_tfo->fabric_name,
1288 cmd->data_length, size, cmd->t_task_cdb[0]);
1290 if (cmd->data_direction == DMA_TO_DEVICE) {
1291 if (cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) {
1292 pr_err_ratelimited("Rejecting underflow/overflow"
1293 " for WRITE data CDB\n");
1294 return TCM_INVALID_CDB_FIELD;
1297 * Some fabric drivers like iscsi-target still expect to
1298 * always reject overflow writes. Reject this case until
1299 * full fabric driver level support for overflow writes
1300 * is introduced tree-wide.
1302 if (size > cmd->data_length) {
1303 pr_err_ratelimited("Rejecting overflow for"
1304 " WRITE control CDB\n");
1305 return TCM_INVALID_CDB_FIELD;
1309 * Reject READ_* or WRITE_* with overflow/underflow for
1310 * type SCF_SCSI_DATA_CDB.
1312 if (dev->dev_attrib.block_size != 512) {
1313 pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
1314 " CDB on non 512-byte sector setup subsystem"
1315 " plugin: %s\n", dev->transport->name);
1316 /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
1317 return TCM_INVALID_CDB_FIELD;
1320 * For the overflow case keep the existing fabric provided
1321 * ->data_length. Otherwise for the underflow case, reset
1322 * ->data_length to the smaller SCSI expected data transfer
1325 if (size > cmd->data_length) {
1326 cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1327 cmd->residual_count = (size - cmd->data_length);
1329 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1330 cmd->residual_count = (cmd->data_length - size);
1331 cmd->data_length = size;
1335 return target_check_max_data_sg_nents(cmd, dev, size);
1340 * Used by fabric modules containing a local struct se_cmd within their
1341 * fabric dependent per I/O descriptor.
1343 * Preserves the value of @cmd->tag.
1345 void transport_init_se_cmd(
1347 const struct target_core_fabric_ops *tfo,
1348 struct se_session *se_sess,
1352 unsigned char *sense_buffer)
1354 INIT_LIST_HEAD(&cmd->se_delayed_node);
1355 INIT_LIST_HEAD(&cmd->se_qf_node);
1356 INIT_LIST_HEAD(&cmd->se_cmd_list);
1357 INIT_LIST_HEAD(&cmd->state_list);
1358 init_completion(&cmd->t_transport_stop_comp);
1359 cmd->free_compl = NULL;
1360 cmd->abrt_compl = NULL;
1361 spin_lock_init(&cmd->t_state_lock);
1362 INIT_WORK(&cmd->work, NULL);
1363 kref_init(&cmd->cmd_kref);
1366 cmd->se_sess = se_sess;
1367 cmd->data_length = data_length;
1368 cmd->data_direction = data_direction;
1369 cmd->sam_task_attr = task_attr;
1370 cmd->sense_buffer = sense_buffer;
1372 cmd->state_active = false;
1374 EXPORT_SYMBOL(transport_init_se_cmd);
1376 static sense_reason_t
1377 transport_check_alloc_task_attr(struct se_cmd *cmd)
1379 struct se_device *dev = cmd->se_dev;
1382 * Check if SAM Task Attribute emulation is enabled for this
1383 * struct se_device storage object
1385 if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1388 if (cmd->sam_task_attr == TCM_ACA_TAG) {
1389 pr_debug("SAM Task Attribute ACA"
1390 " emulation is not supported\n");
1391 return TCM_INVALID_CDB_FIELD;
1398 target_setup_cmd_from_cdb(struct se_cmd *cmd, unsigned char *cdb)
1400 struct se_device *dev = cmd->se_dev;
1404 * Ensure that the received CDB is less than the max (252 + 8) bytes
1405 * for VARIABLE_LENGTH_CMD
1407 if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1408 pr_err("Received SCSI CDB with command_size: %d that"
1409 " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1410 scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1411 return TCM_INVALID_CDB_FIELD;
1414 * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1415 * allocate the additional extended CDB buffer now.. Otherwise
1416 * setup the pointer from __t_task_cdb to t_task_cdb.
1418 if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1419 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1421 if (!cmd->t_task_cdb) {
1422 pr_err("Unable to allocate cmd->t_task_cdb"
1423 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1424 scsi_command_size(cdb),
1425 (unsigned long)sizeof(cmd->__t_task_cdb));
1426 return TCM_OUT_OF_RESOURCES;
1429 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1431 * Copy the original CDB into cmd->
1433 memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1435 trace_target_sequencer_start(cmd);
1437 ret = dev->transport->parse_cdb(cmd);
1438 if (ret == TCM_UNSUPPORTED_SCSI_OPCODE)
1439 pr_warn_ratelimited("%s/%s: Unsupported SCSI Opcode 0x%02x, sending CHECK_CONDITION.\n",
1440 cmd->se_tfo->fabric_name,
1441 cmd->se_sess->se_node_acl->initiatorname,
1442 cmd->t_task_cdb[0]);
1446 ret = transport_check_alloc_task_attr(cmd);
1450 cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1451 atomic_long_inc(&cmd->se_lun->lun_stats.cmd_pdus);
1454 EXPORT_SYMBOL(target_setup_cmd_from_cdb);
1457 * Used by fabric module frontends to queue tasks directly.
1458 * May only be used from process context.
1460 int transport_handle_cdb_direct(
1467 pr_err("cmd->se_lun is NULL\n");
1470 if (in_interrupt()) {
1472 pr_err("transport_generic_handle_cdb cannot be called"
1473 " from interrupt context\n");
1477 * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1478 * outstanding descriptors are handled correctly during shutdown via
1479 * transport_wait_for_tasks()
1481 * Also, we don't take cmd->t_state_lock here as we only expect
1482 * this to be called for initial descriptor submission.
1484 cmd->t_state = TRANSPORT_NEW_CMD;
1485 cmd->transport_state |= CMD_T_ACTIVE;
1488 * transport_generic_new_cmd() is already handling QUEUE_FULL,
1489 * so follow TRANSPORT_NEW_CMD processing thread context usage
1490 * and call transport_generic_request_failure() if necessary..
1492 ret = transport_generic_new_cmd(cmd);
1494 transport_generic_request_failure(cmd, ret);
1497 EXPORT_SYMBOL(transport_handle_cdb_direct);
1500 transport_generic_map_mem_to_cmd(struct se_cmd *cmd, struct scatterlist *sgl,
1501 u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count)
1503 if (!sgl || !sgl_count)
1507 * Reject SCSI data overflow with map_mem_to_cmd() as incoming
1508 * scatterlists already have been set to follow what the fabric
1509 * passes for the original expected data transfer length.
1511 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1512 pr_warn("Rejecting SCSI DATA overflow for fabric using"
1513 " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
1514 return TCM_INVALID_CDB_FIELD;
1517 cmd->t_data_sg = sgl;
1518 cmd->t_data_nents = sgl_count;
1519 cmd->t_bidi_data_sg = sgl_bidi;
1520 cmd->t_bidi_data_nents = sgl_bidi_count;
1522 cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
1527 * target_submit_cmd_map_sgls - lookup unpacked lun and submit uninitialized
1528 * se_cmd + use pre-allocated SGL memory.
1530 * @se_cmd: command descriptor to submit
1531 * @se_sess: associated se_sess for endpoint
1532 * @cdb: pointer to SCSI CDB
1533 * @sense: pointer to SCSI sense buffer
1534 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1535 * @data_length: fabric expected data transfer length
1536 * @task_attr: SAM task attribute
1537 * @data_dir: DMA data direction
1538 * @flags: flags for command submission from target_sc_flags_tables
1539 * @sgl: struct scatterlist memory for unidirectional mapping
1540 * @sgl_count: scatterlist count for unidirectional mapping
1541 * @sgl_bidi: struct scatterlist memory for bidirectional READ mapping
1542 * @sgl_bidi_count: scatterlist count for bidirectional READ mapping
1543 * @sgl_prot: struct scatterlist memory protection information
1544 * @sgl_prot_count: scatterlist count for protection information
1546 * Task tags are supported if the caller has set @se_cmd->tag.
1548 * Returns non zero to signal active I/O shutdown failure. All other
1549 * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1550 * but still return zero here.
1552 * This may only be called from process context, and also currently
1553 * assumes internal allocation of fabric payload buffer by target-core.
1555 int target_submit_cmd_map_sgls(struct se_cmd *se_cmd, struct se_session *se_sess,
1556 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1557 u32 data_length, int task_attr, int data_dir, int flags,
1558 struct scatterlist *sgl, u32 sgl_count,
1559 struct scatterlist *sgl_bidi, u32 sgl_bidi_count,
1560 struct scatterlist *sgl_prot, u32 sgl_prot_count)
1562 struct se_portal_group *se_tpg;
1566 se_tpg = se_sess->se_tpg;
1568 BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1569 BUG_ON(in_interrupt());
1571 * Initialize se_cmd for target operation. From this point
1572 * exceptions are handled by sending exception status via
1573 * target_core_fabric_ops->queue_status() callback
1575 transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1576 data_length, data_dir, task_attr, sense);
1578 if (flags & TARGET_SCF_USE_CPUID)
1579 se_cmd->se_cmd_flags |= SCF_USE_CPUID;
1581 se_cmd->cpuid = WORK_CPU_UNBOUND;
1583 if (flags & TARGET_SCF_UNKNOWN_SIZE)
1584 se_cmd->unknown_data_length = 1;
1586 * Obtain struct se_cmd->cmd_kref reference and add new cmd to
1587 * se_sess->sess_cmd_list. A second kref_get here is necessary
1588 * for fabrics using TARGET_SCF_ACK_KREF that expect a second
1589 * kref_put() to happen during fabric packet acknowledgement.
1591 ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1595 * Signal bidirectional data payloads to target-core
1597 if (flags & TARGET_SCF_BIDI_OP)
1598 se_cmd->se_cmd_flags |= SCF_BIDI;
1600 * Locate se_lun pointer and attach it to struct se_cmd
1602 rc = transport_lookup_cmd_lun(se_cmd, unpacked_lun);
1604 transport_send_check_condition_and_sense(se_cmd, rc, 0);
1605 target_put_sess_cmd(se_cmd);
1609 rc = target_setup_cmd_from_cdb(se_cmd, cdb);
1611 transport_generic_request_failure(se_cmd, rc);
1616 * Save pointers for SGLs containing protection information,
1619 if (sgl_prot_count) {
1620 se_cmd->t_prot_sg = sgl_prot;
1621 se_cmd->t_prot_nents = sgl_prot_count;
1622 se_cmd->se_cmd_flags |= SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC;
1626 * When a non zero sgl_count has been passed perform SGL passthrough
1627 * mapping for pre-allocated fabric memory instead of having target
1628 * core perform an internal SGL allocation..
1630 if (sgl_count != 0) {
1634 * A work-around for tcm_loop as some userspace code via
1635 * scsi-generic do not memset their associated read buffers,
1636 * so go ahead and do that here for type non-data CDBs. Also
1637 * note that this is currently guaranteed to be a single SGL
1638 * for this case by target core in target_setup_cmd_from_cdb()
1639 * -> transport_generic_cmd_sequencer().
1641 if (!(se_cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) &&
1642 se_cmd->data_direction == DMA_FROM_DEVICE) {
1643 unsigned char *buf = NULL;
1646 buf = kmap(sg_page(sgl)) + sgl->offset;
1649 memset(buf, 0, sgl->length);
1650 kunmap(sg_page(sgl));
1654 rc = transport_generic_map_mem_to_cmd(se_cmd, sgl, sgl_count,
1655 sgl_bidi, sgl_bidi_count);
1657 transport_generic_request_failure(se_cmd, rc);
1663 * Check if we need to delay processing because of ALUA
1664 * Active/NonOptimized primary access state..
1666 core_alua_check_nonop_delay(se_cmd);
1668 transport_handle_cdb_direct(se_cmd);
1671 EXPORT_SYMBOL(target_submit_cmd_map_sgls);
1674 * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1676 * @se_cmd: command descriptor to submit
1677 * @se_sess: associated se_sess for endpoint
1678 * @cdb: pointer to SCSI CDB
1679 * @sense: pointer to SCSI sense buffer
1680 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1681 * @data_length: fabric expected data transfer length
1682 * @task_attr: SAM task attribute
1683 * @data_dir: DMA data direction
1684 * @flags: flags for command submission from target_sc_flags_tables
1686 * Task tags are supported if the caller has set @se_cmd->tag.
1688 * Returns non zero to signal active I/O shutdown failure. All other
1689 * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1690 * but still return zero here.
1692 * This may only be called from process context, and also currently
1693 * assumes internal allocation of fabric payload buffer by target-core.
1695 * It also assumes interal target core SGL memory allocation.
1697 int target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1698 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1699 u32 data_length, int task_attr, int data_dir, int flags)
1701 return target_submit_cmd_map_sgls(se_cmd, se_sess, cdb, sense,
1702 unpacked_lun, data_length, task_attr, data_dir,
1703 flags, NULL, 0, NULL, 0, NULL, 0);
1705 EXPORT_SYMBOL(target_submit_cmd);
1707 static void target_complete_tmr_failure(struct work_struct *work)
1709 struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1711 se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1712 se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1714 transport_lun_remove_cmd(se_cmd);
1715 transport_cmd_check_stop_to_fabric(se_cmd);
1718 static bool target_lookup_lun_from_tag(struct se_session *se_sess, u64 tag,
1721 struct se_cmd *se_cmd;
1722 unsigned long flags;
1725 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
1726 list_for_each_entry(se_cmd, &se_sess->sess_cmd_list, se_cmd_list) {
1727 if (se_cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
1730 if (se_cmd->tag == tag) {
1731 *unpacked_lun = se_cmd->orig_fe_lun;
1736 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
1742 * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1745 * @se_cmd: command descriptor to submit
1746 * @se_sess: associated se_sess for endpoint
1747 * @sense: pointer to SCSI sense buffer
1748 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1749 * @fabric_tmr_ptr: fabric context for TMR req
1750 * @tm_type: Type of TM request
1751 * @gfp: gfp type for caller
1752 * @tag: referenced task tag for TMR_ABORT_TASK
1753 * @flags: submit cmd flags
1755 * Callable from all contexts.
1758 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1759 unsigned char *sense, u64 unpacked_lun,
1760 void *fabric_tmr_ptr, unsigned char tm_type,
1761 gfp_t gfp, u64 tag, int flags)
1763 struct se_portal_group *se_tpg;
1766 se_tpg = se_sess->se_tpg;
1769 transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1770 0, DMA_NONE, TCM_SIMPLE_TAG, sense);
1772 * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1773 * allocation failure.
1775 ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1779 if (tm_type == TMR_ABORT_TASK)
1780 se_cmd->se_tmr_req->ref_task_tag = tag;
1782 /* See target_submit_cmd for commentary */
1783 ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1785 core_tmr_release_req(se_cmd->se_tmr_req);
1789 * If this is ABORT_TASK with no explicit fabric provided LUN,
1790 * go ahead and search active session tags for a match to figure
1791 * out unpacked_lun for the original se_cmd.
1793 if (tm_type == TMR_ABORT_TASK && (flags & TARGET_SCF_LOOKUP_LUN_FROM_TAG)) {
1794 if (!target_lookup_lun_from_tag(se_sess, tag, &unpacked_lun))
1798 ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun);
1802 transport_generic_handle_tmr(se_cmd);
1806 * For callback during failure handling, push this work off
1807 * to process context with TMR_LUN_DOES_NOT_EXIST status.
1810 INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1811 schedule_work(&se_cmd->work);
1814 EXPORT_SYMBOL(target_submit_tmr);
1817 * Handle SAM-esque emulation for generic transport request failures.
1819 void transport_generic_request_failure(struct se_cmd *cmd,
1820 sense_reason_t sense_reason)
1822 int ret = 0, post_ret;
1824 pr_debug("-----[ Storage Engine Exception; sense_reason %d\n",
1826 target_show_cmd("-----[ ", cmd);
1829 * For SAM Task Attribute emulation for failed struct se_cmd
1831 transport_complete_task_attr(cmd);
1833 if (cmd->transport_complete_callback)
1834 cmd->transport_complete_callback(cmd, false, &post_ret);
1836 if (cmd->transport_state & CMD_T_ABORTED) {
1837 INIT_WORK(&cmd->work, target_abort_work);
1838 queue_work(target_completion_wq, &cmd->work);
1842 switch (sense_reason) {
1843 case TCM_NON_EXISTENT_LUN:
1844 case TCM_UNSUPPORTED_SCSI_OPCODE:
1845 case TCM_INVALID_CDB_FIELD:
1846 case TCM_INVALID_PARAMETER_LIST:
1847 case TCM_PARAMETER_LIST_LENGTH_ERROR:
1848 case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1849 case TCM_UNKNOWN_MODE_PAGE:
1850 case TCM_WRITE_PROTECTED:
1851 case TCM_ADDRESS_OUT_OF_RANGE:
1852 case TCM_CHECK_CONDITION_ABORT_CMD:
1853 case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1854 case TCM_CHECK_CONDITION_NOT_READY:
1855 case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED:
1856 case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED:
1857 case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED:
1858 case TCM_COPY_TARGET_DEVICE_NOT_REACHABLE:
1859 case TCM_TOO_MANY_TARGET_DESCS:
1860 case TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE:
1861 case TCM_TOO_MANY_SEGMENT_DESCS:
1862 case TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE:
1864 case TCM_OUT_OF_RESOURCES:
1865 cmd->scsi_status = SAM_STAT_TASK_SET_FULL;
1868 cmd->scsi_status = SAM_STAT_BUSY;
1870 case TCM_RESERVATION_CONFLICT:
1872 * No SENSE Data payload for this case, set SCSI Status
1873 * and queue the response to $FABRIC_MOD.
1875 * Uses linux/include/scsi/scsi.h SAM status codes defs
1877 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1879 * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1880 * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1883 * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1886 cmd->se_dev->dev_attrib.emulate_ua_intlck_ctrl == 2) {
1887 target_ua_allocate_lun(cmd->se_sess->se_node_acl,
1888 cmd->orig_fe_lun, 0x2C,
1889 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1894 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1895 cmd->t_task_cdb[0], sense_reason);
1896 sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1900 ret = transport_send_check_condition_and_sense(cmd, sense_reason, 0);
1905 transport_lun_remove_cmd(cmd);
1906 transport_cmd_check_stop_to_fabric(cmd);
1910 trace_target_cmd_complete(cmd);
1911 ret = cmd->se_tfo->queue_status(cmd);
1915 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
1917 EXPORT_SYMBOL(transport_generic_request_failure);
1919 void __target_execute_cmd(struct se_cmd *cmd, bool do_checks)
1923 if (!cmd->execute_cmd) {
1924 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1929 * Check for an existing UNIT ATTENTION condition after
1930 * target_handle_task_attr() has done SAM task attr
1931 * checking, and possibly have already defered execution
1932 * out to target_restart_delayed_cmds() context.
1934 ret = target_scsi3_ua_check(cmd);
1938 ret = target_alua_state_check(cmd);
1942 ret = target_check_reservation(cmd);
1944 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1949 ret = cmd->execute_cmd(cmd);
1953 spin_lock_irq(&cmd->t_state_lock);
1954 cmd->transport_state &= ~CMD_T_SENT;
1955 spin_unlock_irq(&cmd->t_state_lock);
1957 transport_generic_request_failure(cmd, ret);
1960 static int target_write_prot_action(struct se_cmd *cmd)
1964 * Perform WRITE_INSERT of PI using software emulation when backend
1965 * device has PI enabled, if the transport has not already generated
1966 * PI using hardware WRITE_INSERT offload.
1968 switch (cmd->prot_op) {
1969 case TARGET_PROT_DOUT_INSERT:
1970 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_INSERT))
1971 sbc_dif_generate(cmd);
1973 case TARGET_PROT_DOUT_STRIP:
1974 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_STRIP)
1977 sectors = cmd->data_length >> ilog2(cmd->se_dev->dev_attrib.block_size);
1978 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
1979 sectors, 0, cmd->t_prot_sg, 0);
1980 if (unlikely(cmd->pi_err)) {
1981 spin_lock_irq(&cmd->t_state_lock);
1982 cmd->transport_state &= ~CMD_T_SENT;
1983 spin_unlock_irq(&cmd->t_state_lock);
1984 transport_generic_request_failure(cmd, cmd->pi_err);
1995 static bool target_handle_task_attr(struct se_cmd *cmd)
1997 struct se_device *dev = cmd->se_dev;
1999 if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2002 cmd->se_cmd_flags |= SCF_TASK_ATTR_SET;
2005 * Check for the existence of HEAD_OF_QUEUE, and if true return 1
2006 * to allow the passed struct se_cmd list of tasks to the front of the list.
2008 switch (cmd->sam_task_attr) {
2010 pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x\n",
2011 cmd->t_task_cdb[0]);
2013 case TCM_ORDERED_TAG:
2014 atomic_inc_mb(&dev->dev_ordered_sync);
2016 pr_debug("Added ORDERED for CDB: 0x%02x to ordered list\n",
2017 cmd->t_task_cdb[0]);
2020 * Execute an ORDERED command if no other older commands
2021 * exist that need to be completed first.
2023 if (!atomic_read(&dev->simple_cmds))
2028 * For SIMPLE and UNTAGGED Task Attribute commands
2030 atomic_inc_mb(&dev->simple_cmds);
2034 if (atomic_read(&dev->dev_ordered_sync) == 0)
2037 spin_lock(&dev->delayed_cmd_lock);
2038 list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
2039 spin_unlock(&dev->delayed_cmd_lock);
2041 pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to delayed CMD listn",
2042 cmd->t_task_cdb[0], cmd->sam_task_attr);
2046 void target_execute_cmd(struct se_cmd *cmd)
2049 * Determine if frontend context caller is requesting the stopping of
2050 * this command for frontend exceptions.
2052 * If the received CDB has already been aborted stop processing it here.
2054 if (target_cmd_interrupted(cmd))
2057 spin_lock_irq(&cmd->t_state_lock);
2058 cmd->t_state = TRANSPORT_PROCESSING;
2059 cmd->transport_state |= CMD_T_ACTIVE | CMD_T_SENT;
2060 spin_unlock_irq(&cmd->t_state_lock);
2062 if (target_write_prot_action(cmd))
2065 if (target_handle_task_attr(cmd)) {
2066 spin_lock_irq(&cmd->t_state_lock);
2067 cmd->transport_state &= ~CMD_T_SENT;
2068 spin_unlock_irq(&cmd->t_state_lock);
2072 __target_execute_cmd(cmd, true);
2074 EXPORT_SYMBOL(target_execute_cmd);
2077 * Process all commands up to the last received ORDERED task attribute which
2078 * requires another blocking boundary
2080 static void target_restart_delayed_cmds(struct se_device *dev)
2085 spin_lock(&dev->delayed_cmd_lock);
2086 if (list_empty(&dev->delayed_cmd_list)) {
2087 spin_unlock(&dev->delayed_cmd_lock);
2091 cmd = list_entry(dev->delayed_cmd_list.next,
2092 struct se_cmd, se_delayed_node);
2093 list_del(&cmd->se_delayed_node);
2094 spin_unlock(&dev->delayed_cmd_lock);
2096 cmd->transport_state |= CMD_T_SENT;
2098 __target_execute_cmd(cmd, true);
2100 if (cmd->sam_task_attr == TCM_ORDERED_TAG)
2106 * Called from I/O completion to determine which dormant/delayed
2107 * and ordered cmds need to have their tasks added to the execution queue.
2109 static void transport_complete_task_attr(struct se_cmd *cmd)
2111 struct se_device *dev = cmd->se_dev;
2113 if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2116 if (!(cmd->se_cmd_flags & SCF_TASK_ATTR_SET))
2119 if (cmd->sam_task_attr == TCM_SIMPLE_TAG) {
2120 atomic_dec_mb(&dev->simple_cmds);
2121 dev->dev_cur_ordered_id++;
2122 } else if (cmd->sam_task_attr == TCM_HEAD_TAG) {
2123 dev->dev_cur_ordered_id++;
2124 pr_debug("Incremented dev_cur_ordered_id: %u for HEAD_OF_QUEUE\n",
2125 dev->dev_cur_ordered_id);
2126 } else if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2127 atomic_dec_mb(&dev->dev_ordered_sync);
2129 dev->dev_cur_ordered_id++;
2130 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED\n",
2131 dev->dev_cur_ordered_id);
2133 cmd->se_cmd_flags &= ~SCF_TASK_ATTR_SET;
2136 target_restart_delayed_cmds(dev);
2139 static void transport_complete_qf(struct se_cmd *cmd)
2143 transport_complete_task_attr(cmd);
2145 * If a fabric driver ->write_pending() or ->queue_data_in() callback
2146 * has returned neither -ENOMEM or -EAGAIN, assume it's fatal and
2147 * the same callbacks should not be retried. Return CHECK_CONDITION
2148 * if a scsi_status is not already set.
2150 * If a fabric driver ->queue_status() has returned non zero, always
2151 * keep retrying no matter what..
2153 if (cmd->t_state == TRANSPORT_COMPLETE_QF_ERR) {
2154 if (cmd->scsi_status)
2157 translate_sense_reason(cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
2162 * Check if we need to send a sense buffer from
2163 * the struct se_cmd in question. We do NOT want
2164 * to take this path of the IO has been marked as
2165 * needing to be treated like a "normal read". This
2166 * is the case if it's a tape read, and either the
2167 * FM, EOM, or ILI bits are set, but there is no
2170 if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2171 cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
2174 switch (cmd->data_direction) {
2175 case DMA_FROM_DEVICE:
2176 /* queue status if not treating this as a normal read */
2177 if (cmd->scsi_status &&
2178 !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2181 trace_target_cmd_complete(cmd);
2182 ret = cmd->se_tfo->queue_data_in(cmd);
2185 if (cmd->se_cmd_flags & SCF_BIDI) {
2186 ret = cmd->se_tfo->queue_data_in(cmd);
2192 trace_target_cmd_complete(cmd);
2193 ret = cmd->se_tfo->queue_status(cmd);
2200 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2203 transport_lun_remove_cmd(cmd);
2204 transport_cmd_check_stop_to_fabric(cmd);
2207 static void transport_handle_queue_full(struct se_cmd *cmd, struct se_device *dev,
2208 int err, bool write_pending)
2211 * -EAGAIN or -ENOMEM signals retry of ->write_pending() and/or
2212 * ->queue_data_in() callbacks from new process context.
2214 * Otherwise for other errors, transport_complete_qf() will send
2215 * CHECK_CONDITION via ->queue_status() instead of attempting to
2216 * retry associated fabric driver data-transfer callbacks.
2218 if (err == -EAGAIN || err == -ENOMEM) {
2219 cmd->t_state = (write_pending) ? TRANSPORT_COMPLETE_QF_WP :
2220 TRANSPORT_COMPLETE_QF_OK;
2222 pr_warn_ratelimited("Got unknown fabric queue status: %d\n", err);
2223 cmd->t_state = TRANSPORT_COMPLETE_QF_ERR;
2226 spin_lock_irq(&dev->qf_cmd_lock);
2227 list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
2228 atomic_inc_mb(&dev->dev_qf_count);
2229 spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
2231 schedule_work(&cmd->se_dev->qf_work_queue);
2234 static bool target_read_prot_action(struct se_cmd *cmd)
2236 switch (cmd->prot_op) {
2237 case TARGET_PROT_DIN_STRIP:
2238 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_STRIP)) {
2239 u32 sectors = cmd->data_length >>
2240 ilog2(cmd->se_dev->dev_attrib.block_size);
2242 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2243 sectors, 0, cmd->t_prot_sg,
2249 case TARGET_PROT_DIN_INSERT:
2250 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_INSERT)
2253 sbc_dif_generate(cmd);
2262 static void target_complete_ok_work(struct work_struct *work)
2264 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
2268 * Check if we need to move delayed/dormant tasks from cmds on the
2269 * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
2272 transport_complete_task_attr(cmd);
2275 * Check to schedule QUEUE_FULL work, or execute an existing
2276 * cmd->transport_qf_callback()
2278 if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
2279 schedule_work(&cmd->se_dev->qf_work_queue);
2282 * Check if we need to send a sense buffer from
2283 * the struct se_cmd in question. We do NOT want
2284 * to take this path of the IO has been marked as
2285 * needing to be treated like a "normal read". This
2286 * is the case if it's a tape read, and either the
2287 * FM, EOM, or ILI bits are set, but there is no
2290 if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2291 cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2292 WARN_ON(!cmd->scsi_status);
2293 ret = transport_send_check_condition_and_sense(
2298 transport_lun_remove_cmd(cmd);
2299 transport_cmd_check_stop_to_fabric(cmd);
2303 * Check for a callback, used by amongst other things
2304 * XDWRITE_READ_10 and COMPARE_AND_WRITE emulation.
2306 if (cmd->transport_complete_callback) {
2308 bool caw = (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE);
2309 bool zero_dl = !(cmd->data_length);
2312 rc = cmd->transport_complete_callback(cmd, true, &post_ret);
2313 if (!rc && !post_ret) {
2319 ret = transport_send_check_condition_and_sense(cmd,
2324 transport_lun_remove_cmd(cmd);
2325 transport_cmd_check_stop_to_fabric(cmd);
2331 switch (cmd->data_direction) {
2332 case DMA_FROM_DEVICE:
2334 * if this is a READ-type IO, but SCSI status
2335 * is set, then skip returning data and just
2336 * return the status -- unless this IO is marked
2337 * as needing to be treated as a normal read,
2338 * in which case we want to go ahead and return
2339 * the data. This happens, for example, for tape
2340 * reads with the FM, EOM, or ILI bits set, with
2343 if (cmd->scsi_status &&
2344 !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2347 atomic_long_add(cmd->data_length,
2348 &cmd->se_lun->lun_stats.tx_data_octets);
2350 * Perform READ_STRIP of PI using software emulation when
2351 * backend had PI enabled, if the transport will not be
2352 * performing hardware READ_STRIP offload.
2354 if (target_read_prot_action(cmd)) {
2355 ret = transport_send_check_condition_and_sense(cmd,
2360 transport_lun_remove_cmd(cmd);
2361 transport_cmd_check_stop_to_fabric(cmd);
2365 trace_target_cmd_complete(cmd);
2366 ret = cmd->se_tfo->queue_data_in(cmd);
2371 atomic_long_add(cmd->data_length,
2372 &cmd->se_lun->lun_stats.rx_data_octets);
2374 * Check if we need to send READ payload for BIDI-COMMAND
2376 if (cmd->se_cmd_flags & SCF_BIDI) {
2377 atomic_long_add(cmd->data_length,
2378 &cmd->se_lun->lun_stats.tx_data_octets);
2379 ret = cmd->se_tfo->queue_data_in(cmd);
2387 trace_target_cmd_complete(cmd);
2388 ret = cmd->se_tfo->queue_status(cmd);
2396 transport_lun_remove_cmd(cmd);
2397 transport_cmd_check_stop_to_fabric(cmd);
2401 pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2402 " data_direction: %d\n", cmd, cmd->data_direction);
2404 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2407 void target_free_sgl(struct scatterlist *sgl, int nents)
2409 sgl_free_n_order(sgl, nents, 0);
2411 EXPORT_SYMBOL(target_free_sgl);
2413 static inline void transport_reset_sgl_orig(struct se_cmd *cmd)
2416 * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE
2417 * emulation, and free + reset pointers if necessary..
2419 if (!cmd->t_data_sg_orig)
2422 kfree(cmd->t_data_sg);
2423 cmd->t_data_sg = cmd->t_data_sg_orig;
2424 cmd->t_data_sg_orig = NULL;
2425 cmd->t_data_nents = cmd->t_data_nents_orig;
2426 cmd->t_data_nents_orig = 0;
2429 static inline void transport_free_pages(struct se_cmd *cmd)
2431 if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2432 target_free_sgl(cmd->t_prot_sg, cmd->t_prot_nents);
2433 cmd->t_prot_sg = NULL;
2434 cmd->t_prot_nents = 0;
2437 if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) {
2439 * Release special case READ buffer payload required for
2440 * SG_TO_MEM_NOALLOC to function with COMPARE_AND_WRITE
2442 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
2443 target_free_sgl(cmd->t_bidi_data_sg,
2444 cmd->t_bidi_data_nents);
2445 cmd->t_bidi_data_sg = NULL;
2446 cmd->t_bidi_data_nents = 0;
2448 transport_reset_sgl_orig(cmd);
2451 transport_reset_sgl_orig(cmd);
2453 target_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2454 cmd->t_data_sg = NULL;
2455 cmd->t_data_nents = 0;
2457 target_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2458 cmd->t_bidi_data_sg = NULL;
2459 cmd->t_bidi_data_nents = 0;
2462 void *transport_kmap_data_sg(struct se_cmd *cmd)
2464 struct scatterlist *sg = cmd->t_data_sg;
2465 struct page **pages;
2469 * We need to take into account a possible offset here for fabrics like
2470 * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2471 * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2473 if (!cmd->t_data_nents)
2477 if (cmd->t_data_nents == 1)
2478 return kmap(sg_page(sg)) + sg->offset;
2480 /* >1 page. use vmap */
2481 pages = kmalloc_array(cmd->t_data_nents, sizeof(*pages), GFP_KERNEL);
2485 /* convert sg[] to pages[] */
2486 for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2487 pages[i] = sg_page(sg);
2490 cmd->t_data_vmap = vmap(pages, cmd->t_data_nents, VM_MAP, PAGE_KERNEL);
2492 if (!cmd->t_data_vmap)
2495 return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2497 EXPORT_SYMBOL(transport_kmap_data_sg);
2499 void transport_kunmap_data_sg(struct se_cmd *cmd)
2501 if (!cmd->t_data_nents) {
2503 } else if (cmd->t_data_nents == 1) {
2504 kunmap(sg_page(cmd->t_data_sg));
2508 vunmap(cmd->t_data_vmap);
2509 cmd->t_data_vmap = NULL;
2511 EXPORT_SYMBOL(transport_kunmap_data_sg);
2514 target_alloc_sgl(struct scatterlist **sgl, unsigned int *nents, u32 length,
2515 bool zero_page, bool chainable)
2517 gfp_t gfp = GFP_KERNEL | (zero_page ? __GFP_ZERO : 0);
2519 *sgl = sgl_alloc_order(length, 0, chainable, gfp, nents);
2520 return *sgl ? 0 : -ENOMEM;
2522 EXPORT_SYMBOL(target_alloc_sgl);
2525 * Allocate any required resources to execute the command. For writes we
2526 * might not have the payload yet, so notify the fabric via a call to
2527 * ->write_pending instead. Otherwise place it on the execution queue.
2530 transport_generic_new_cmd(struct se_cmd *cmd)
2532 unsigned long flags;
2534 bool zero_flag = !(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB);
2536 if (cmd->prot_op != TARGET_PROT_NORMAL &&
2537 !(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2538 ret = target_alloc_sgl(&cmd->t_prot_sg, &cmd->t_prot_nents,
2539 cmd->prot_length, true, false);
2541 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2545 * Determine if the TCM fabric module has already allocated physical
2546 * memory, and is directly calling transport_generic_map_mem_to_cmd()
2549 if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2552 if ((cmd->se_cmd_flags & SCF_BIDI) ||
2553 (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)) {
2556 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)
2557 bidi_length = cmd->t_task_nolb *
2558 cmd->se_dev->dev_attrib.block_size;
2560 bidi_length = cmd->data_length;
2562 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2563 &cmd->t_bidi_data_nents,
2564 bidi_length, zero_flag, false);
2566 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2569 ret = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents,
2570 cmd->data_length, zero_flag, false);
2572 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2573 } else if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
2576 * Special case for COMPARE_AND_WRITE with fabrics
2577 * using SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC.
2579 u32 caw_length = cmd->t_task_nolb *
2580 cmd->se_dev->dev_attrib.block_size;
2582 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2583 &cmd->t_bidi_data_nents,
2584 caw_length, zero_flag, false);
2586 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2589 * If this command is not a write we can execute it right here,
2590 * for write buffers we need to notify the fabric driver first
2591 * and let it call back once the write buffers are ready.
2593 target_add_to_state_list(cmd);
2594 if (cmd->data_direction != DMA_TO_DEVICE || cmd->data_length == 0) {
2595 target_execute_cmd(cmd);
2599 spin_lock_irqsave(&cmd->t_state_lock, flags);
2600 cmd->t_state = TRANSPORT_WRITE_PENDING;
2602 * Determine if frontend context caller is requesting the stopping of
2603 * this command for frontend exceptions.
2605 if (cmd->transport_state & CMD_T_STOP &&
2606 !cmd->se_tfo->write_pending_must_be_called) {
2607 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2608 __func__, __LINE__, cmd->tag);
2610 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2612 complete_all(&cmd->t_transport_stop_comp);
2615 cmd->transport_state &= ~CMD_T_ACTIVE;
2616 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2618 ret = cmd->se_tfo->write_pending(cmd);
2625 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2626 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2629 EXPORT_SYMBOL(transport_generic_new_cmd);
2631 static void transport_write_pending_qf(struct se_cmd *cmd)
2633 unsigned long flags;
2637 spin_lock_irqsave(&cmd->t_state_lock, flags);
2638 stop = (cmd->transport_state & (CMD_T_STOP | CMD_T_ABORTED));
2639 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2642 pr_debug("%s:%d CMD_T_STOP|CMD_T_ABORTED for ITT: 0x%08llx\n",
2643 __func__, __LINE__, cmd->tag);
2644 complete_all(&cmd->t_transport_stop_comp);
2648 ret = cmd->se_tfo->write_pending(cmd);
2650 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2652 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2657 __transport_wait_for_tasks(struct se_cmd *, bool, bool *, bool *,
2658 unsigned long *flags);
2660 static void target_wait_free_cmd(struct se_cmd *cmd, bool *aborted, bool *tas)
2662 unsigned long flags;
2664 spin_lock_irqsave(&cmd->t_state_lock, flags);
2665 __transport_wait_for_tasks(cmd, true, aborted, tas, &flags);
2666 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2670 * Call target_put_sess_cmd() and wait until target_release_cmd_kref(@cmd) has
2673 void target_put_cmd_and_wait(struct se_cmd *cmd)
2675 DECLARE_COMPLETION_ONSTACK(compl);
2677 WARN_ON_ONCE(cmd->abrt_compl);
2678 cmd->abrt_compl = &compl;
2679 target_put_sess_cmd(cmd);
2680 wait_for_completion(&compl);
2684 * This function is called by frontend drivers after processing of a command
2687 * The protocol for ensuring that either the regular frontend command
2688 * processing flow or target_handle_abort() code drops one reference is as
2690 * - Calling .queue_data_in(), .queue_status() or queue_tm_rsp() will cause
2691 * the frontend driver to call this function synchronously or asynchronously.
2692 * That will cause one reference to be dropped.
2693 * - During regular command processing the target core sets CMD_T_COMPLETE
2694 * before invoking one of the .queue_*() functions.
2695 * - The code that aborts commands skips commands and TMFs for which
2696 * CMD_T_COMPLETE has been set.
2697 * - CMD_T_ABORTED is set atomically after the CMD_T_COMPLETE check for
2698 * commands that will be aborted.
2699 * - If the CMD_T_ABORTED flag is set but CMD_T_TAS has not been set
2700 * transport_generic_free_cmd() skips its call to target_put_sess_cmd().
2701 * - For aborted commands for which CMD_T_TAS has been set .queue_status() will
2702 * be called and will drop a reference.
2703 * - For aborted commands for which CMD_T_TAS has not been set .aborted_task()
2704 * will be called. target_handle_abort() will drop the final reference.
2706 int transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2708 DECLARE_COMPLETION_ONSTACK(compl);
2710 bool aborted = false, tas = false;
2713 target_wait_free_cmd(cmd, &aborted, &tas);
2715 if (cmd->se_cmd_flags & SCF_SE_LUN_CMD) {
2717 * Handle WRITE failure case where transport_generic_new_cmd()
2718 * has already added se_cmd to state_list, but fabric has
2719 * failed command before I/O submission.
2721 if (cmd->state_active)
2722 target_remove_from_state_list(cmd);
2725 transport_lun_remove_cmd(cmd);
2728 cmd->free_compl = &compl;
2729 ret = target_put_sess_cmd(cmd);
2731 pr_debug("Detected CMD_T_ABORTED for ITT: %llu\n", cmd->tag);
2732 wait_for_completion(&compl);
2737 EXPORT_SYMBOL(transport_generic_free_cmd);
2740 * target_get_sess_cmd - Add command to active ->sess_cmd_list
2741 * @se_cmd: command descriptor to add
2742 * @ack_kref: Signal that fabric will perform an ack target_put_sess_cmd()
2744 int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
2746 struct se_session *se_sess = se_cmd->se_sess;
2747 unsigned long flags;
2751 * Add a second kref if the fabric caller is expecting to handle
2752 * fabric acknowledgement that requires two target_put_sess_cmd()
2753 * invocations before se_cmd descriptor release.
2756 if (!kref_get_unless_zero(&se_cmd->cmd_kref))
2759 se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2762 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2763 if (se_sess->sess_tearing_down) {
2767 list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list);
2768 percpu_ref_get(&se_sess->cmd_count);
2770 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2772 if (ret && ack_kref)
2773 target_put_sess_cmd(se_cmd);
2777 EXPORT_SYMBOL(target_get_sess_cmd);
2779 static void target_free_cmd_mem(struct se_cmd *cmd)
2781 transport_free_pages(cmd);
2783 if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2784 core_tmr_release_req(cmd->se_tmr_req);
2785 if (cmd->t_task_cdb != cmd->__t_task_cdb)
2786 kfree(cmd->t_task_cdb);
2789 static void target_release_cmd_kref(struct kref *kref)
2791 struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2792 struct se_session *se_sess = se_cmd->se_sess;
2793 struct completion *free_compl = se_cmd->free_compl;
2794 struct completion *abrt_compl = se_cmd->abrt_compl;
2795 unsigned long flags;
2798 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2799 list_del_init(&se_cmd->se_cmd_list);
2800 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2803 target_free_cmd_mem(se_cmd);
2804 se_cmd->se_tfo->release_cmd(se_cmd);
2806 complete(free_compl);
2808 complete(abrt_compl);
2810 percpu_ref_put(&se_sess->cmd_count);
2814 * target_put_sess_cmd - decrease the command reference count
2815 * @se_cmd: command to drop a reference from
2817 * Returns 1 if and only if this target_put_sess_cmd() call caused the
2818 * refcount to drop to zero. Returns zero otherwise.
2820 int target_put_sess_cmd(struct se_cmd *se_cmd)
2822 return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2824 EXPORT_SYMBOL(target_put_sess_cmd);
2826 static const char *data_dir_name(enum dma_data_direction d)
2829 case DMA_BIDIRECTIONAL: return "BIDI";
2830 case DMA_TO_DEVICE: return "WRITE";
2831 case DMA_FROM_DEVICE: return "READ";
2832 case DMA_NONE: return "NONE";
2838 static const char *cmd_state_name(enum transport_state_table t)
2841 case TRANSPORT_NO_STATE: return "NO_STATE";
2842 case TRANSPORT_NEW_CMD: return "NEW_CMD";
2843 case TRANSPORT_WRITE_PENDING: return "WRITE_PENDING";
2844 case TRANSPORT_PROCESSING: return "PROCESSING";
2845 case TRANSPORT_COMPLETE: return "COMPLETE";
2846 case TRANSPORT_ISTATE_PROCESSING:
2847 return "ISTATE_PROCESSING";
2848 case TRANSPORT_COMPLETE_QF_WP: return "COMPLETE_QF_WP";
2849 case TRANSPORT_COMPLETE_QF_OK: return "COMPLETE_QF_OK";
2850 case TRANSPORT_COMPLETE_QF_ERR: return "COMPLETE_QF_ERR";
2856 static void target_append_str(char **str, const char *txt)
2860 *str = *str ? kasprintf(GFP_ATOMIC, "%s,%s", *str, txt) :
2861 kstrdup(txt, GFP_ATOMIC);
2866 * Convert a transport state bitmask into a string. The caller is
2867 * responsible for freeing the returned pointer.
2869 static char *target_ts_to_str(u32 ts)
2873 if (ts & CMD_T_ABORTED)
2874 target_append_str(&str, "aborted");
2875 if (ts & CMD_T_ACTIVE)
2876 target_append_str(&str, "active");
2877 if (ts & CMD_T_COMPLETE)
2878 target_append_str(&str, "complete");
2879 if (ts & CMD_T_SENT)
2880 target_append_str(&str, "sent");
2881 if (ts & CMD_T_STOP)
2882 target_append_str(&str, "stop");
2883 if (ts & CMD_T_FABRIC_STOP)
2884 target_append_str(&str, "fabric_stop");
2889 static const char *target_tmf_name(enum tcm_tmreq_table tmf)
2892 case TMR_ABORT_TASK: return "ABORT_TASK";
2893 case TMR_ABORT_TASK_SET: return "ABORT_TASK_SET";
2894 case TMR_CLEAR_ACA: return "CLEAR_ACA";
2895 case TMR_CLEAR_TASK_SET: return "CLEAR_TASK_SET";
2896 case TMR_LUN_RESET: return "LUN_RESET";
2897 case TMR_TARGET_WARM_RESET: return "TARGET_WARM_RESET";
2898 case TMR_TARGET_COLD_RESET: return "TARGET_COLD_RESET";
2899 case TMR_UNKNOWN: break;
2904 void target_show_cmd(const char *pfx, struct se_cmd *cmd)
2906 char *ts_str = target_ts_to_str(cmd->transport_state);
2907 const u8 *cdb = cmd->t_task_cdb;
2908 struct se_tmr_req *tmf = cmd->se_tmr_req;
2910 if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
2911 pr_debug("%scmd %#02x:%#02x with tag %#llx dir %s i_state %d t_state %s len %d refcnt %d transport_state %s\n",
2912 pfx, cdb[0], cdb[1], cmd->tag,
2913 data_dir_name(cmd->data_direction),
2914 cmd->se_tfo->get_cmd_state(cmd),
2915 cmd_state_name(cmd->t_state), cmd->data_length,
2916 kref_read(&cmd->cmd_kref), ts_str);
2918 pr_debug("%stmf %s with tag %#llx ref_task_tag %#llx i_state %d t_state %s refcnt %d transport_state %s\n",
2919 pfx, target_tmf_name(tmf->function), cmd->tag,
2920 tmf->ref_task_tag, cmd->se_tfo->get_cmd_state(cmd),
2921 cmd_state_name(cmd->t_state),
2922 kref_read(&cmd->cmd_kref), ts_str);
2926 EXPORT_SYMBOL(target_show_cmd);
2929 * target_sess_cmd_list_set_waiting - Set sess_tearing_down so no new commands are queued.
2930 * @se_sess: session to flag
2932 void target_sess_cmd_list_set_waiting(struct se_session *se_sess)
2934 unsigned long flags;
2936 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2937 se_sess->sess_tearing_down = 1;
2938 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2940 percpu_ref_kill(&se_sess->cmd_count);
2942 EXPORT_SYMBOL(target_sess_cmd_list_set_waiting);
2945 * target_wait_for_sess_cmds - Wait for outstanding commands
2946 * @se_sess: session to wait for active I/O
2948 void target_wait_for_sess_cmds(struct se_session *se_sess)
2953 WARN_ON_ONCE(!se_sess->sess_tearing_down);
2956 ret = wait_event_timeout(se_sess->cmd_list_wq,
2957 percpu_ref_is_zero(&se_sess->cmd_count),
2959 list_for_each_entry(cmd, &se_sess->sess_cmd_list, se_cmd_list)
2960 target_show_cmd("session shutdown: still waiting for ",
2964 EXPORT_SYMBOL(target_wait_for_sess_cmds);
2967 * Prevent that new percpu_ref_tryget_live() calls succeed and wait until
2968 * all references to the LUN have been released. Called during LUN shutdown.
2970 void transport_clear_lun_ref(struct se_lun *lun)
2972 percpu_ref_kill(&lun->lun_ref);
2973 wait_for_completion(&lun->lun_shutdown_comp);
2977 __transport_wait_for_tasks(struct se_cmd *cmd, bool fabric_stop,
2978 bool *aborted, bool *tas, unsigned long *flags)
2979 __releases(&cmd->t_state_lock)
2980 __acquires(&cmd->t_state_lock)
2983 assert_spin_locked(&cmd->t_state_lock);
2984 WARN_ON_ONCE(!irqs_disabled());
2987 cmd->transport_state |= CMD_T_FABRIC_STOP;
2989 if (cmd->transport_state & CMD_T_ABORTED)
2992 if (cmd->transport_state & CMD_T_TAS)
2995 if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
2996 !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
2999 if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
3000 !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3003 if (!(cmd->transport_state & CMD_T_ACTIVE))
3006 if (fabric_stop && *aborted)
3009 cmd->transport_state |= CMD_T_STOP;
3011 target_show_cmd("wait_for_tasks: Stopping ", cmd);
3013 spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
3015 while (!wait_for_completion_timeout(&cmd->t_transport_stop_comp,
3017 target_show_cmd("wait for tasks: ", cmd);
3019 spin_lock_irqsave(&cmd->t_state_lock, *flags);
3020 cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
3022 pr_debug("wait_for_tasks: Stopped wait_for_completion(&cmd->"
3023 "t_transport_stop_comp) for ITT: 0x%08llx\n", cmd->tag);
3029 * transport_wait_for_tasks - set CMD_T_STOP and wait for t_transport_stop_comp
3030 * @cmd: command to wait on
3032 bool transport_wait_for_tasks(struct se_cmd *cmd)
3034 unsigned long flags;
3035 bool ret, aborted = false, tas = false;
3037 spin_lock_irqsave(&cmd->t_state_lock, flags);
3038 ret = __transport_wait_for_tasks(cmd, false, &aborted, &tas, &flags);
3039 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3043 EXPORT_SYMBOL(transport_wait_for_tasks);
3049 bool add_sector_info;
3052 static const struct sense_info sense_info_table[] = {
3056 [TCM_NON_EXISTENT_LUN] = {
3057 .key = ILLEGAL_REQUEST,
3058 .asc = 0x25 /* LOGICAL UNIT NOT SUPPORTED */
3060 [TCM_UNSUPPORTED_SCSI_OPCODE] = {
3061 .key = ILLEGAL_REQUEST,
3062 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3064 [TCM_SECTOR_COUNT_TOO_MANY] = {
3065 .key = ILLEGAL_REQUEST,
3066 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3068 [TCM_UNKNOWN_MODE_PAGE] = {
3069 .key = ILLEGAL_REQUEST,
3070 .asc = 0x24, /* INVALID FIELD IN CDB */
3072 [TCM_CHECK_CONDITION_ABORT_CMD] = {
3073 .key = ABORTED_COMMAND,
3074 .asc = 0x29, /* BUS DEVICE RESET FUNCTION OCCURRED */
3077 [TCM_INCORRECT_AMOUNT_OF_DATA] = {
3078 .key = ABORTED_COMMAND,
3079 .asc = 0x0c, /* WRITE ERROR */
3080 .ascq = 0x0d, /* NOT ENOUGH UNSOLICITED DATA */
3082 [TCM_INVALID_CDB_FIELD] = {
3083 .key = ILLEGAL_REQUEST,
3084 .asc = 0x24, /* INVALID FIELD IN CDB */
3086 [TCM_INVALID_PARAMETER_LIST] = {
3087 .key = ILLEGAL_REQUEST,
3088 .asc = 0x26, /* INVALID FIELD IN PARAMETER LIST */
3090 [TCM_TOO_MANY_TARGET_DESCS] = {
3091 .key = ILLEGAL_REQUEST,
3093 .ascq = 0x06, /* TOO MANY TARGET DESCRIPTORS */
3095 [TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE] = {
3096 .key = ILLEGAL_REQUEST,
3098 .ascq = 0x07, /* UNSUPPORTED TARGET DESCRIPTOR TYPE CODE */
3100 [TCM_TOO_MANY_SEGMENT_DESCS] = {
3101 .key = ILLEGAL_REQUEST,
3103 .ascq = 0x08, /* TOO MANY SEGMENT DESCRIPTORS */
3105 [TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE] = {
3106 .key = ILLEGAL_REQUEST,
3108 .ascq = 0x09, /* UNSUPPORTED SEGMENT DESCRIPTOR TYPE CODE */
3110 [TCM_PARAMETER_LIST_LENGTH_ERROR] = {
3111 .key = ILLEGAL_REQUEST,
3112 .asc = 0x1a, /* PARAMETER LIST LENGTH ERROR */
3114 [TCM_UNEXPECTED_UNSOLICITED_DATA] = {
3115 .key = ILLEGAL_REQUEST,
3116 .asc = 0x0c, /* WRITE ERROR */
3117 .ascq = 0x0c, /* UNEXPECTED_UNSOLICITED_DATA */
3119 [TCM_SERVICE_CRC_ERROR] = {
3120 .key = ABORTED_COMMAND,
3121 .asc = 0x47, /* PROTOCOL SERVICE CRC ERROR */
3122 .ascq = 0x05, /* N/A */
3124 [TCM_SNACK_REJECTED] = {
3125 .key = ABORTED_COMMAND,
3126 .asc = 0x11, /* READ ERROR */
3127 .ascq = 0x13, /* FAILED RETRANSMISSION REQUEST */
3129 [TCM_WRITE_PROTECTED] = {
3130 .key = DATA_PROTECT,
3131 .asc = 0x27, /* WRITE PROTECTED */
3133 [TCM_ADDRESS_OUT_OF_RANGE] = {
3134 .key = ILLEGAL_REQUEST,
3135 .asc = 0x21, /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3137 [TCM_CHECK_CONDITION_UNIT_ATTENTION] = {
3138 .key = UNIT_ATTENTION,
3140 [TCM_CHECK_CONDITION_NOT_READY] = {
3143 [TCM_MISCOMPARE_VERIFY] = {
3145 .asc = 0x1d, /* MISCOMPARE DURING VERIFY OPERATION */
3148 [TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED] = {
3149 .key = ABORTED_COMMAND,
3151 .ascq = 0x01, /* LOGICAL BLOCK GUARD CHECK FAILED */
3152 .add_sector_info = true,
3154 [TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED] = {
3155 .key = ABORTED_COMMAND,
3157 .ascq = 0x02, /* LOGICAL BLOCK APPLICATION TAG CHECK FAILED */
3158 .add_sector_info = true,
3160 [TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED] = {
3161 .key = ABORTED_COMMAND,
3163 .ascq = 0x03, /* LOGICAL BLOCK REFERENCE TAG CHECK FAILED */
3164 .add_sector_info = true,
3166 [TCM_COPY_TARGET_DEVICE_NOT_REACHABLE] = {
3167 .key = COPY_ABORTED,
3169 .ascq = 0x02, /* COPY TARGET DEVICE NOT REACHABLE */
3172 [TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE] = {
3174 * Returning ILLEGAL REQUEST would cause immediate IO errors on
3175 * Solaris initiators. Returning NOT READY instead means the
3176 * operations will be retried a finite number of times and we
3177 * can survive intermittent errors.
3180 .asc = 0x08, /* LOGICAL UNIT COMMUNICATION FAILURE */
3182 [TCM_INSUFFICIENT_REGISTRATION_RESOURCES] = {
3184 * From spc4r22 section5.7.7,5.7.8
3185 * If a PERSISTENT RESERVE OUT command with a REGISTER service action
3186 * or a REGISTER AND IGNORE EXISTING KEY service action or
3187 * REGISTER AND MOVE service actionis attempted,
3188 * but there are insufficient device server resources to complete the
3189 * operation, then the command shall be terminated with CHECK CONDITION
3190 * status, with the sense key set to ILLEGAL REQUEST,and the additonal
3191 * sense code set to INSUFFICIENT REGISTRATION RESOURCES.
3193 .key = ILLEGAL_REQUEST,
3195 .ascq = 0x04, /* INSUFFICIENT REGISTRATION RESOURCES */
3200 * translate_sense_reason - translate a sense reason into T10 key, asc and ascq
3201 * @cmd: SCSI command in which the resulting sense buffer or SCSI status will
3203 * @reason: LIO sense reason code. If this argument has the value
3204 * TCM_CHECK_CONDITION_UNIT_ATTENTION, try to dequeue a unit attention. If
3205 * dequeuing a unit attention fails due to multiple commands being processed
3206 * concurrently, set the command status to BUSY.
3208 * Return: 0 upon success or -EINVAL if the sense buffer is too small.
3210 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason)
3212 const struct sense_info *si;
3213 u8 *buffer = cmd->sense_buffer;
3214 int r = (__force int)reason;
3216 bool desc_format = target_sense_desc_format(cmd->se_dev);
3218 if (r < ARRAY_SIZE(sense_info_table) && sense_info_table[r].key)
3219 si = &sense_info_table[r];
3221 si = &sense_info_table[(__force int)
3222 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE];
3225 if (reason == TCM_CHECK_CONDITION_UNIT_ATTENTION) {
3226 if (!core_scsi3_ua_for_check_condition(cmd, &key, &asc,
3228 cmd->scsi_status = SAM_STAT_BUSY;
3231 } else if (si->asc == 0) {
3232 WARN_ON_ONCE(cmd->scsi_asc == 0);
3233 asc = cmd->scsi_asc;
3234 ascq = cmd->scsi_ascq;
3240 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
3241 cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3242 cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
3243 scsi_build_sense_buffer(desc_format, buffer, key, asc, ascq);
3244 if (si->add_sector_info)
3245 WARN_ON_ONCE(scsi_set_sense_information(buffer,
3246 cmd->scsi_sense_length,
3247 cmd->bad_sector) < 0);
3251 transport_send_check_condition_and_sense(struct se_cmd *cmd,
3252 sense_reason_t reason, int from_transport)
3254 unsigned long flags;
3256 WARN_ON_ONCE(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB);
3258 spin_lock_irqsave(&cmd->t_state_lock, flags);
3259 if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3260 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3263 cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
3264 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3266 if (!from_transport)
3267 translate_sense_reason(cmd, reason);
3269 trace_target_cmd_complete(cmd);
3270 return cmd->se_tfo->queue_status(cmd);
3272 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3274 static void target_tmr_work(struct work_struct *work)
3276 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3277 struct se_device *dev = cmd->se_dev;
3278 struct se_tmr_req *tmr = cmd->se_tmr_req;
3281 if (cmd->transport_state & CMD_T_ABORTED)
3284 switch (tmr->function) {
3285 case TMR_ABORT_TASK:
3286 core_tmr_abort_task(dev, tmr, cmd->se_sess);
3288 case TMR_ABORT_TASK_SET:
3290 case TMR_CLEAR_TASK_SET:
3291 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3294 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3295 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3296 TMR_FUNCTION_REJECTED;
3297 if (tmr->response == TMR_FUNCTION_COMPLETE) {
3298 target_ua_allocate_lun(cmd->se_sess->se_node_acl,
3299 cmd->orig_fe_lun, 0x29,
3300 ASCQ_29H_BUS_DEVICE_RESET_FUNCTION_OCCURRED);
3303 case TMR_TARGET_WARM_RESET:
3304 tmr->response = TMR_FUNCTION_REJECTED;
3306 case TMR_TARGET_COLD_RESET:
3307 tmr->response = TMR_FUNCTION_REJECTED;
3310 pr_err("Unknown TMR function: 0x%02x.\n",
3312 tmr->response = TMR_FUNCTION_REJECTED;
3316 if (cmd->transport_state & CMD_T_ABORTED)
3319 cmd->se_tfo->queue_tm_rsp(cmd);
3321 transport_cmd_check_stop_to_fabric(cmd);
3325 target_handle_abort(cmd);
3328 int transport_generic_handle_tmr(
3331 unsigned long flags;
3332 bool aborted = false;
3334 spin_lock_irqsave(&cmd->t_state_lock, flags);
3335 if (cmd->transport_state & CMD_T_ABORTED) {
3338 cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3339 cmd->transport_state |= CMD_T_ACTIVE;
3341 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3344 pr_warn_ratelimited("handle_tmr caught CMD_T_ABORTED TMR %d ref_tag: %llu tag: %llu\n",
3345 cmd->se_tmr_req->function,
3346 cmd->se_tmr_req->ref_task_tag, cmd->tag);
3347 target_handle_abort(cmd);
3351 INIT_WORK(&cmd->work, target_tmr_work);
3352 schedule_work(&cmd->work);
3355 EXPORT_SYMBOL(transport_generic_handle_tmr);
3358 target_check_wce(struct se_device *dev)
3362 if (dev->transport->get_write_cache)
3363 wce = dev->transport->get_write_cache(dev);
3364 else if (dev->dev_attrib.emulate_write_cache > 0)
3371 target_check_fua(struct se_device *dev)
3373 return target_check_wce(dev) && dev->dev_attrib.emulate_fua_write > 0;