1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*******************************************************************************
3 * Filename: target_core_transport.c
5 * This file contains the Generic Target Engine Core.
7 * (c) Copyright 2002-2013 Datera, Inc.
9 * Nicholas A. Bellinger <nab@kernel.org>
11 ******************************************************************************/
13 #include <linux/net.h>
14 #include <linux/delay.h>
15 #include <linux/string.h>
16 #include <linux/timer.h>
17 #include <linux/slab.h>
18 #include <linux/spinlock.h>
19 #include <linux/kthread.h>
21 #include <linux/cdrom.h>
22 #include <linux/module.h>
23 #include <linux/ratelimit.h>
24 #include <linux/vmalloc.h>
25 #include <asm/unaligned.h>
28 #include <scsi/scsi_proto.h>
29 #include <scsi/scsi_common.h>
31 #include <target/target_core_base.h>
32 #include <target/target_core_backend.h>
33 #include <target/target_core_fabric.h>
35 #include "target_core_internal.h"
36 #include "target_core_alua.h"
37 #include "target_core_pr.h"
38 #include "target_core_ua.h"
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/target.h>
43 static struct workqueue_struct *target_completion_wq;
44 static struct workqueue_struct *target_submission_wq;
45 static struct kmem_cache *se_sess_cache;
46 struct kmem_cache *se_ua_cache;
47 struct kmem_cache *t10_pr_reg_cache;
48 struct kmem_cache *t10_alua_lu_gp_cache;
49 struct kmem_cache *t10_alua_lu_gp_mem_cache;
50 struct kmem_cache *t10_alua_tg_pt_gp_cache;
51 struct kmem_cache *t10_alua_lba_map_cache;
52 struct kmem_cache *t10_alua_lba_map_mem_cache;
54 static void transport_complete_task_attr(struct se_cmd *cmd);
55 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason);
56 static void transport_handle_queue_full(struct se_cmd *cmd,
57 struct se_device *dev, int err, bool write_pending);
58 static void target_complete_ok_work(struct work_struct *work);
60 int init_se_kmem_caches(void)
62 se_sess_cache = kmem_cache_create("se_sess_cache",
63 sizeof(struct se_session), __alignof__(struct se_session),
66 pr_err("kmem_cache_create() for struct se_session"
70 se_ua_cache = kmem_cache_create("se_ua_cache",
71 sizeof(struct se_ua), __alignof__(struct se_ua),
74 pr_err("kmem_cache_create() for struct se_ua failed\n");
75 goto out_free_sess_cache;
77 t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
78 sizeof(struct t10_pr_registration),
79 __alignof__(struct t10_pr_registration), 0, NULL);
80 if (!t10_pr_reg_cache) {
81 pr_err("kmem_cache_create() for struct t10_pr_registration"
83 goto out_free_ua_cache;
85 t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
86 sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
88 if (!t10_alua_lu_gp_cache) {
89 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
91 goto out_free_pr_reg_cache;
93 t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
94 sizeof(struct t10_alua_lu_gp_member),
95 __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
96 if (!t10_alua_lu_gp_mem_cache) {
97 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
99 goto out_free_lu_gp_cache;
101 t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
102 sizeof(struct t10_alua_tg_pt_gp),
103 __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
104 if (!t10_alua_tg_pt_gp_cache) {
105 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
107 goto out_free_lu_gp_mem_cache;
109 t10_alua_lba_map_cache = kmem_cache_create(
110 "t10_alua_lba_map_cache",
111 sizeof(struct t10_alua_lba_map),
112 __alignof__(struct t10_alua_lba_map), 0, NULL);
113 if (!t10_alua_lba_map_cache) {
114 pr_err("kmem_cache_create() for t10_alua_lba_map_"
116 goto out_free_tg_pt_gp_cache;
118 t10_alua_lba_map_mem_cache = kmem_cache_create(
119 "t10_alua_lba_map_mem_cache",
120 sizeof(struct t10_alua_lba_map_member),
121 __alignof__(struct t10_alua_lba_map_member), 0, NULL);
122 if (!t10_alua_lba_map_mem_cache) {
123 pr_err("kmem_cache_create() for t10_alua_lba_map_mem_"
125 goto out_free_lba_map_cache;
128 target_completion_wq = alloc_workqueue("target_completion",
130 if (!target_completion_wq)
131 goto out_free_lba_map_mem_cache;
133 target_submission_wq = alloc_workqueue("target_submission",
135 if (!target_submission_wq)
136 goto out_free_completion_wq;
140 out_free_completion_wq:
141 destroy_workqueue(target_completion_wq);
142 out_free_lba_map_mem_cache:
143 kmem_cache_destroy(t10_alua_lba_map_mem_cache);
144 out_free_lba_map_cache:
145 kmem_cache_destroy(t10_alua_lba_map_cache);
146 out_free_tg_pt_gp_cache:
147 kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
148 out_free_lu_gp_mem_cache:
149 kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
150 out_free_lu_gp_cache:
151 kmem_cache_destroy(t10_alua_lu_gp_cache);
152 out_free_pr_reg_cache:
153 kmem_cache_destroy(t10_pr_reg_cache);
155 kmem_cache_destroy(se_ua_cache);
157 kmem_cache_destroy(se_sess_cache);
162 void release_se_kmem_caches(void)
164 destroy_workqueue(target_submission_wq);
165 destroy_workqueue(target_completion_wq);
166 kmem_cache_destroy(se_sess_cache);
167 kmem_cache_destroy(se_ua_cache);
168 kmem_cache_destroy(t10_pr_reg_cache);
169 kmem_cache_destroy(t10_alua_lu_gp_cache);
170 kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
171 kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
172 kmem_cache_destroy(t10_alua_lba_map_cache);
173 kmem_cache_destroy(t10_alua_lba_map_mem_cache);
176 /* This code ensures unique mib indexes are handed out. */
177 static DEFINE_SPINLOCK(scsi_mib_index_lock);
178 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
181 * Allocate a new row index for the entry type specified
183 u32 scsi_get_new_index(scsi_index_t type)
187 BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
189 spin_lock(&scsi_mib_index_lock);
190 new_index = ++scsi_mib_index[type];
191 spin_unlock(&scsi_mib_index_lock);
196 void transport_subsystem_check_init(void)
199 static int sub_api_initialized;
201 if (sub_api_initialized)
204 ret = IS_ENABLED(CONFIG_TCM_IBLOCK) && request_module("target_core_iblock");
206 pr_err("Unable to load target_core_iblock\n");
208 ret = IS_ENABLED(CONFIG_TCM_FILEIO) && request_module("target_core_file");
210 pr_err("Unable to load target_core_file\n");
212 ret = IS_ENABLED(CONFIG_TCM_PSCSI) && request_module("target_core_pscsi");
214 pr_err("Unable to load target_core_pscsi\n");
216 ret = IS_ENABLED(CONFIG_TCM_USER2) && request_module("target_core_user");
218 pr_err("Unable to load target_core_user\n");
220 sub_api_initialized = 1;
223 static void target_release_sess_cmd_refcnt(struct percpu_ref *ref)
225 struct se_session *sess = container_of(ref, typeof(*sess), cmd_count);
227 wake_up(&sess->cmd_count_wq);
231 * transport_init_session - initialize a session object
232 * @se_sess: Session object pointer.
234 * The caller must have zero-initialized @se_sess before calling this function.
236 int transport_init_session(struct se_session *se_sess)
238 INIT_LIST_HEAD(&se_sess->sess_list);
239 INIT_LIST_HEAD(&se_sess->sess_acl_list);
240 spin_lock_init(&se_sess->sess_cmd_lock);
241 init_waitqueue_head(&se_sess->cmd_count_wq);
242 init_completion(&se_sess->stop_done);
243 atomic_set(&se_sess->stopped, 0);
244 return percpu_ref_init(&se_sess->cmd_count,
245 target_release_sess_cmd_refcnt, 0, GFP_KERNEL);
247 EXPORT_SYMBOL(transport_init_session);
249 void transport_uninit_session(struct se_session *se_sess)
252 * Drivers like iscsi and loop do not call target_stop_session
253 * during session shutdown so we have to drop the ref taken at init
256 if (!atomic_read(&se_sess->stopped))
257 percpu_ref_put(&se_sess->cmd_count);
259 percpu_ref_exit(&se_sess->cmd_count);
263 * transport_alloc_session - allocate a session object and initialize it
264 * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
266 struct se_session *transport_alloc_session(enum target_prot_op sup_prot_ops)
268 struct se_session *se_sess;
271 se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
273 pr_err("Unable to allocate struct se_session from"
275 return ERR_PTR(-ENOMEM);
277 ret = transport_init_session(se_sess);
279 kmem_cache_free(se_sess_cache, se_sess);
282 se_sess->sup_prot_ops = sup_prot_ops;
286 EXPORT_SYMBOL(transport_alloc_session);
289 * transport_alloc_session_tags - allocate target driver private data
290 * @se_sess: Session pointer.
291 * @tag_num: Maximum number of in-flight commands between initiator and target.
292 * @tag_size: Size in bytes of the private data a target driver associates with
295 int transport_alloc_session_tags(struct se_session *se_sess,
296 unsigned int tag_num, unsigned int tag_size)
300 se_sess->sess_cmd_map = kvcalloc(tag_size, tag_num,
301 GFP_KERNEL | __GFP_RETRY_MAYFAIL);
302 if (!se_sess->sess_cmd_map) {
303 pr_err("Unable to allocate se_sess->sess_cmd_map\n");
307 rc = sbitmap_queue_init_node(&se_sess->sess_tag_pool, tag_num, -1,
308 false, GFP_KERNEL, NUMA_NO_NODE);
310 pr_err("Unable to init se_sess->sess_tag_pool,"
311 " tag_num: %u\n", tag_num);
312 kvfree(se_sess->sess_cmd_map);
313 se_sess->sess_cmd_map = NULL;
319 EXPORT_SYMBOL(transport_alloc_session_tags);
322 * transport_init_session_tags - allocate a session and target driver private data
323 * @tag_num: Maximum number of in-flight commands between initiator and target.
324 * @tag_size: Size in bytes of the private data a target driver associates with
326 * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
328 static struct se_session *
329 transport_init_session_tags(unsigned int tag_num, unsigned int tag_size,
330 enum target_prot_op sup_prot_ops)
332 struct se_session *se_sess;
335 if (tag_num != 0 && !tag_size) {
336 pr_err("init_session_tags called with percpu-ida tag_num:"
337 " %u, but zero tag_size\n", tag_num);
338 return ERR_PTR(-EINVAL);
340 if (!tag_num && tag_size) {
341 pr_err("init_session_tags called with percpu-ida tag_size:"
342 " %u, but zero tag_num\n", tag_size);
343 return ERR_PTR(-EINVAL);
346 se_sess = transport_alloc_session(sup_prot_ops);
350 rc = transport_alloc_session_tags(se_sess, tag_num, tag_size);
352 transport_free_session(se_sess);
353 return ERR_PTR(-ENOMEM);
360 * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
362 void __transport_register_session(
363 struct se_portal_group *se_tpg,
364 struct se_node_acl *se_nacl,
365 struct se_session *se_sess,
366 void *fabric_sess_ptr)
368 const struct target_core_fabric_ops *tfo = se_tpg->se_tpg_tfo;
369 unsigned char buf[PR_REG_ISID_LEN];
372 se_sess->se_tpg = se_tpg;
373 se_sess->fabric_sess_ptr = fabric_sess_ptr;
375 * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
377 * Only set for struct se_session's that will actually be moving I/O.
378 * eg: *NOT* discovery sessions.
383 * Determine if fabric allows for T10-PI feature bits exposed to
384 * initiators for device backends with !dev->dev_attrib.pi_prot_type.
386 * If so, then always save prot_type on a per se_node_acl node
387 * basis and re-instate the previous sess_prot_type to avoid
388 * disabling PI from below any previously initiator side
391 if (se_nacl->saved_prot_type)
392 se_sess->sess_prot_type = se_nacl->saved_prot_type;
393 else if (tfo->tpg_check_prot_fabric_only)
394 se_sess->sess_prot_type = se_nacl->saved_prot_type =
395 tfo->tpg_check_prot_fabric_only(se_tpg);
397 * If the fabric module supports an ISID based TransportID,
398 * save this value in binary from the fabric I_T Nexus now.
400 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
401 memset(&buf[0], 0, PR_REG_ISID_LEN);
402 se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
403 &buf[0], PR_REG_ISID_LEN);
404 se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
407 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
409 * The se_nacl->nacl_sess pointer will be set to the
410 * last active I_T Nexus for each struct se_node_acl.
412 se_nacl->nacl_sess = se_sess;
414 list_add_tail(&se_sess->sess_acl_list,
415 &se_nacl->acl_sess_list);
416 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
418 list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
420 pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
421 se_tpg->se_tpg_tfo->fabric_name, se_sess->fabric_sess_ptr);
423 EXPORT_SYMBOL(__transport_register_session);
425 void transport_register_session(
426 struct se_portal_group *se_tpg,
427 struct se_node_acl *se_nacl,
428 struct se_session *se_sess,
429 void *fabric_sess_ptr)
433 spin_lock_irqsave(&se_tpg->session_lock, flags);
434 __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
435 spin_unlock_irqrestore(&se_tpg->session_lock, flags);
437 EXPORT_SYMBOL(transport_register_session);
440 target_setup_session(struct se_portal_group *tpg,
441 unsigned int tag_num, unsigned int tag_size,
442 enum target_prot_op prot_op,
443 const char *initiatorname, void *private,
444 int (*callback)(struct se_portal_group *,
445 struct se_session *, void *))
447 struct se_session *sess;
450 * If the fabric driver is using percpu-ida based pre allocation
451 * of I/O descriptor tags, go ahead and perform that setup now..
454 sess = transport_init_session_tags(tag_num, tag_size, prot_op);
456 sess = transport_alloc_session(prot_op);
461 sess->se_node_acl = core_tpg_check_initiator_node_acl(tpg,
462 (unsigned char *)initiatorname);
463 if (!sess->se_node_acl) {
464 transport_free_session(sess);
465 return ERR_PTR(-EACCES);
468 * Go ahead and perform any remaining fabric setup that is
469 * required before transport_register_session().
471 if (callback != NULL) {
472 int rc = callback(tpg, sess, private);
474 transport_free_session(sess);
479 transport_register_session(tpg, sess->se_node_acl, sess, private);
482 EXPORT_SYMBOL(target_setup_session);
484 ssize_t target_show_dynamic_sessions(struct se_portal_group *se_tpg, char *page)
486 struct se_session *se_sess;
489 spin_lock_bh(&se_tpg->session_lock);
490 list_for_each_entry(se_sess, &se_tpg->tpg_sess_list, sess_list) {
491 if (!se_sess->se_node_acl)
493 if (!se_sess->se_node_acl->dynamic_node_acl)
495 if (strlen(se_sess->se_node_acl->initiatorname) + 1 + len > PAGE_SIZE)
498 len += snprintf(page + len, PAGE_SIZE - len, "%s\n",
499 se_sess->se_node_acl->initiatorname);
500 len += 1; /* Include NULL terminator */
502 spin_unlock_bh(&se_tpg->session_lock);
506 EXPORT_SYMBOL(target_show_dynamic_sessions);
508 static void target_complete_nacl(struct kref *kref)
510 struct se_node_acl *nacl = container_of(kref,
511 struct se_node_acl, acl_kref);
512 struct se_portal_group *se_tpg = nacl->se_tpg;
514 if (!nacl->dynamic_stop) {
515 complete(&nacl->acl_free_comp);
519 mutex_lock(&se_tpg->acl_node_mutex);
520 list_del_init(&nacl->acl_list);
521 mutex_unlock(&se_tpg->acl_node_mutex);
523 core_tpg_wait_for_nacl_pr_ref(nacl);
524 core_free_device_list_for_node(nacl, se_tpg);
528 void target_put_nacl(struct se_node_acl *nacl)
530 kref_put(&nacl->acl_kref, target_complete_nacl);
532 EXPORT_SYMBOL(target_put_nacl);
534 void transport_deregister_session_configfs(struct se_session *se_sess)
536 struct se_node_acl *se_nacl;
539 * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
541 se_nacl = se_sess->se_node_acl;
543 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
544 if (!list_empty(&se_sess->sess_acl_list))
545 list_del_init(&se_sess->sess_acl_list);
547 * If the session list is empty, then clear the pointer.
548 * Otherwise, set the struct se_session pointer from the tail
549 * element of the per struct se_node_acl active session list.
551 if (list_empty(&se_nacl->acl_sess_list))
552 se_nacl->nacl_sess = NULL;
554 se_nacl->nacl_sess = container_of(
555 se_nacl->acl_sess_list.prev,
556 struct se_session, sess_acl_list);
558 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
561 EXPORT_SYMBOL(transport_deregister_session_configfs);
563 void transport_free_session(struct se_session *se_sess)
565 struct se_node_acl *se_nacl = se_sess->se_node_acl;
568 * Drop the se_node_acl->nacl_kref obtained from within
569 * core_tpg_get_initiator_node_acl().
572 struct se_portal_group *se_tpg = se_nacl->se_tpg;
573 const struct target_core_fabric_ops *se_tfo = se_tpg->se_tpg_tfo;
576 se_sess->se_node_acl = NULL;
579 * Also determine if we need to drop the extra ->cmd_kref if
580 * it had been previously dynamically generated, and
581 * the endpoint is not caching dynamic ACLs.
583 mutex_lock(&se_tpg->acl_node_mutex);
584 if (se_nacl->dynamic_node_acl &&
585 !se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
586 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
587 if (list_empty(&se_nacl->acl_sess_list))
588 se_nacl->dynamic_stop = true;
589 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
591 if (se_nacl->dynamic_stop)
592 list_del_init(&se_nacl->acl_list);
594 mutex_unlock(&se_tpg->acl_node_mutex);
596 if (se_nacl->dynamic_stop)
597 target_put_nacl(se_nacl);
599 target_put_nacl(se_nacl);
601 if (se_sess->sess_cmd_map) {
602 sbitmap_queue_free(&se_sess->sess_tag_pool);
603 kvfree(se_sess->sess_cmd_map);
605 transport_uninit_session(se_sess);
606 kmem_cache_free(se_sess_cache, se_sess);
608 EXPORT_SYMBOL(transport_free_session);
610 static int target_release_res(struct se_device *dev, void *data)
612 struct se_session *sess = data;
614 if (dev->reservation_holder == sess)
615 target_release_reservation(dev);
619 void transport_deregister_session(struct se_session *se_sess)
621 struct se_portal_group *se_tpg = se_sess->se_tpg;
625 transport_free_session(se_sess);
629 spin_lock_irqsave(&se_tpg->session_lock, flags);
630 list_del(&se_sess->sess_list);
631 se_sess->se_tpg = NULL;
632 se_sess->fabric_sess_ptr = NULL;
633 spin_unlock_irqrestore(&se_tpg->session_lock, flags);
636 * Since the session is being removed, release SPC-2
637 * reservations held by the session that is disappearing.
639 target_for_each_device(target_release_res, se_sess);
641 pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
642 se_tpg->se_tpg_tfo->fabric_name);
644 * If last kref is dropping now for an explicit NodeACL, awake sleeping
645 * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
646 * removal context from within transport_free_session() code.
648 * For dynamic ACL, target_put_nacl() uses target_complete_nacl()
649 * to release all remaining generate_node_acl=1 created ACL resources.
652 transport_free_session(se_sess);
654 EXPORT_SYMBOL(transport_deregister_session);
656 void target_remove_session(struct se_session *se_sess)
658 transport_deregister_session_configfs(se_sess);
659 transport_deregister_session(se_sess);
661 EXPORT_SYMBOL(target_remove_session);
663 static void target_remove_from_state_list(struct se_cmd *cmd)
665 struct se_device *dev = cmd->se_dev;
671 spin_lock_irqsave(&dev->queues[cmd->cpuid].lock, flags);
672 if (cmd->state_active) {
673 list_del(&cmd->state_list);
674 cmd->state_active = false;
676 spin_unlock_irqrestore(&dev->queues[cmd->cpuid].lock, flags);
680 * This function is called by the target core after the target core has
681 * finished processing a SCSI command or SCSI TMF. Both the regular command
682 * processing code and the code for aborting commands can call this
683 * function. CMD_T_STOP is set if and only if another thread is waiting
684 * inside transport_wait_for_tasks() for t_transport_stop_comp.
686 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
690 target_remove_from_state_list(cmd);
693 * Clear struct se_cmd->se_lun before the handoff to FE.
697 spin_lock_irqsave(&cmd->t_state_lock, flags);
699 * Determine if frontend context caller is requesting the stopping of
700 * this command for frontend exceptions.
702 if (cmd->transport_state & CMD_T_STOP) {
703 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
704 __func__, __LINE__, cmd->tag);
706 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
708 complete_all(&cmd->t_transport_stop_comp);
711 cmd->transport_state &= ~CMD_T_ACTIVE;
712 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
715 * Some fabric modules like tcm_loop can release their internally
716 * allocated I/O reference and struct se_cmd now.
718 * Fabric modules are expected to return '1' here if the se_cmd being
719 * passed is released at this point, or zero if not being released.
721 return cmd->se_tfo->check_stop_free(cmd);
724 static void transport_lun_remove_cmd(struct se_cmd *cmd)
726 struct se_lun *lun = cmd->se_lun;
731 if (cmpxchg(&cmd->lun_ref_active, true, false))
732 percpu_ref_put(&lun->lun_ref);
735 static void target_complete_failure_work(struct work_struct *work)
737 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
739 transport_generic_request_failure(cmd,
740 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
744 * Used when asking transport to copy Sense Data from the underlying
745 * Linux/SCSI struct scsi_cmnd
747 static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd)
749 struct se_device *dev = cmd->se_dev;
751 WARN_ON(!cmd->se_lun);
756 if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION)
759 cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
761 pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n",
762 dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
763 return cmd->sense_buffer;
766 void transport_copy_sense_to_cmd(struct se_cmd *cmd, unsigned char *sense)
768 unsigned char *cmd_sense_buf;
771 spin_lock_irqsave(&cmd->t_state_lock, flags);
772 cmd_sense_buf = transport_get_sense_buffer(cmd);
773 if (!cmd_sense_buf) {
774 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
778 cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
779 memcpy(cmd_sense_buf, sense, cmd->scsi_sense_length);
780 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
782 EXPORT_SYMBOL(transport_copy_sense_to_cmd);
784 static void target_handle_abort(struct se_cmd *cmd)
786 bool tas = cmd->transport_state & CMD_T_TAS;
787 bool ack_kref = cmd->se_cmd_flags & SCF_ACK_KREF;
790 pr_debug("tag %#llx: send_abort_response = %d\n", cmd->tag, tas);
793 if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
794 cmd->scsi_status = SAM_STAT_TASK_ABORTED;
795 pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x, ITT: 0x%08llx\n",
796 cmd->t_task_cdb[0], cmd->tag);
797 trace_target_cmd_complete(cmd);
798 ret = cmd->se_tfo->queue_status(cmd);
800 transport_handle_queue_full(cmd, cmd->se_dev,
805 cmd->se_tmr_req->response = TMR_FUNCTION_REJECTED;
806 cmd->se_tfo->queue_tm_rsp(cmd);
810 * Allow the fabric driver to unmap any resources before
811 * releasing the descriptor via TFO->release_cmd().
813 cmd->se_tfo->aborted_task(cmd);
815 WARN_ON_ONCE(target_put_sess_cmd(cmd) != 0);
817 * To do: establish a unit attention condition on the I_T
818 * nexus associated with cmd. See also the paragraph "Aborting
823 WARN_ON_ONCE(kref_read(&cmd->cmd_kref) == 0);
825 transport_lun_remove_cmd(cmd);
827 transport_cmd_check_stop_to_fabric(cmd);
830 static void target_abort_work(struct work_struct *work)
832 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
834 target_handle_abort(cmd);
837 static bool target_cmd_interrupted(struct se_cmd *cmd)
841 if (cmd->transport_state & CMD_T_ABORTED) {
842 if (cmd->transport_complete_callback)
843 cmd->transport_complete_callback(cmd, false, &post_ret);
844 INIT_WORK(&cmd->work, target_abort_work);
845 queue_work(target_completion_wq, &cmd->work);
847 } else if (cmd->transport_state & CMD_T_STOP) {
848 if (cmd->transport_complete_callback)
849 cmd->transport_complete_callback(cmd, false, &post_ret);
850 complete_all(&cmd->t_transport_stop_comp);
857 /* May be called from interrupt context so must not sleep. */
858 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
860 struct se_wwn *wwn = cmd->se_sess->se_tpg->se_tpg_wwn;
864 if (target_cmd_interrupted(cmd))
867 cmd->scsi_status = scsi_status;
869 spin_lock_irqsave(&cmd->t_state_lock, flags);
870 switch (cmd->scsi_status) {
871 case SAM_STAT_CHECK_CONDITION:
872 if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
882 cmd->t_state = TRANSPORT_COMPLETE;
883 cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
884 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
886 INIT_WORK(&cmd->work, success ? target_complete_ok_work :
887 target_complete_failure_work);
889 if (wwn->cmd_compl_affinity == SE_COMPL_AFFINITY_CPUID)
892 cpu = wwn->cmd_compl_affinity;
894 queue_work_on(cpu, target_completion_wq, &cmd->work);
896 EXPORT_SYMBOL(target_complete_cmd);
898 void target_set_cmd_data_length(struct se_cmd *cmd, int length)
900 if (length < cmd->data_length) {
901 if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
902 cmd->residual_count += cmd->data_length - length;
904 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
905 cmd->residual_count = cmd->data_length - length;
908 cmd->data_length = length;
911 EXPORT_SYMBOL(target_set_cmd_data_length);
913 void target_complete_cmd_with_length(struct se_cmd *cmd, u8 scsi_status, int length)
915 if (scsi_status == SAM_STAT_GOOD ||
916 cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) {
917 target_set_cmd_data_length(cmd, length);
920 target_complete_cmd(cmd, scsi_status);
922 EXPORT_SYMBOL(target_complete_cmd_with_length);
924 static void target_add_to_state_list(struct se_cmd *cmd)
926 struct se_device *dev = cmd->se_dev;
929 spin_lock_irqsave(&dev->queues[cmd->cpuid].lock, flags);
930 if (!cmd->state_active) {
931 list_add_tail(&cmd->state_list,
932 &dev->queues[cmd->cpuid].state_list);
933 cmd->state_active = true;
935 spin_unlock_irqrestore(&dev->queues[cmd->cpuid].lock, flags);
939 * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
941 static void transport_write_pending_qf(struct se_cmd *cmd);
942 static void transport_complete_qf(struct se_cmd *cmd);
944 void target_qf_do_work(struct work_struct *work)
946 struct se_device *dev = container_of(work, struct se_device,
948 LIST_HEAD(qf_cmd_list);
949 struct se_cmd *cmd, *cmd_tmp;
951 spin_lock_irq(&dev->qf_cmd_lock);
952 list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
953 spin_unlock_irq(&dev->qf_cmd_lock);
955 list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
956 list_del(&cmd->se_qf_node);
957 atomic_dec_mb(&dev->dev_qf_count);
959 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
960 " context: %s\n", cmd->se_tfo->fabric_name, cmd,
961 (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
962 (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
965 if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
966 transport_write_pending_qf(cmd);
967 else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK ||
968 cmd->t_state == TRANSPORT_COMPLETE_QF_ERR)
969 transport_complete_qf(cmd);
973 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
975 switch (cmd->data_direction) {
978 case DMA_FROM_DEVICE:
982 case DMA_BIDIRECTIONAL:
991 void transport_dump_dev_state(
992 struct se_device *dev,
996 *bl += sprintf(b + *bl, "Status: ");
997 if (dev->export_count)
998 *bl += sprintf(b + *bl, "ACTIVATED");
1000 *bl += sprintf(b + *bl, "DEACTIVATED");
1002 *bl += sprintf(b + *bl, " Max Queue Depth: %d", dev->queue_depth);
1003 *bl += sprintf(b + *bl, " SectorSize: %u HwMaxSectors: %u\n",
1004 dev->dev_attrib.block_size,
1005 dev->dev_attrib.hw_max_sectors);
1006 *bl += sprintf(b + *bl, " ");
1009 void transport_dump_vpd_proto_id(
1010 struct t10_vpd *vpd,
1011 unsigned char *p_buf,
1014 unsigned char buf[VPD_TMP_BUF_SIZE];
1017 memset(buf, 0, VPD_TMP_BUF_SIZE);
1018 len = sprintf(buf, "T10 VPD Protocol Identifier: ");
1020 switch (vpd->protocol_identifier) {
1022 sprintf(buf+len, "Fibre Channel\n");
1025 sprintf(buf+len, "Parallel SCSI\n");
1028 sprintf(buf+len, "SSA\n");
1031 sprintf(buf+len, "IEEE 1394\n");
1034 sprintf(buf+len, "SCSI Remote Direct Memory Access"
1038 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
1041 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
1044 sprintf(buf+len, "Automation/Drive Interface Transport"
1048 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
1051 sprintf(buf+len, "Unknown 0x%02x\n",
1052 vpd->protocol_identifier);
1057 strncpy(p_buf, buf, p_buf_len);
1059 pr_debug("%s", buf);
1063 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1066 * Check if the Protocol Identifier Valid (PIV) bit is set..
1068 * from spc3r23.pdf section 7.5.1
1070 if (page_83[1] & 0x80) {
1071 vpd->protocol_identifier = (page_83[0] & 0xf0);
1072 vpd->protocol_identifier_set = 1;
1073 transport_dump_vpd_proto_id(vpd, NULL, 0);
1076 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1078 int transport_dump_vpd_assoc(
1079 struct t10_vpd *vpd,
1080 unsigned char *p_buf,
1083 unsigned char buf[VPD_TMP_BUF_SIZE];
1087 memset(buf, 0, VPD_TMP_BUF_SIZE);
1088 len = sprintf(buf, "T10 VPD Identifier Association: ");
1090 switch (vpd->association) {
1092 sprintf(buf+len, "addressed logical unit\n");
1095 sprintf(buf+len, "target port\n");
1098 sprintf(buf+len, "SCSI target device\n");
1101 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1107 strncpy(p_buf, buf, p_buf_len);
1109 pr_debug("%s", buf);
1114 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1117 * The VPD identification association..
1119 * from spc3r23.pdf Section 7.6.3.1 Table 297
1121 vpd->association = (page_83[1] & 0x30);
1122 return transport_dump_vpd_assoc(vpd, NULL, 0);
1124 EXPORT_SYMBOL(transport_set_vpd_assoc);
1126 int transport_dump_vpd_ident_type(
1127 struct t10_vpd *vpd,
1128 unsigned char *p_buf,
1131 unsigned char buf[VPD_TMP_BUF_SIZE];
1135 memset(buf, 0, VPD_TMP_BUF_SIZE);
1136 len = sprintf(buf, "T10 VPD Identifier Type: ");
1138 switch (vpd->device_identifier_type) {
1140 sprintf(buf+len, "Vendor specific\n");
1143 sprintf(buf+len, "T10 Vendor ID based\n");
1146 sprintf(buf+len, "EUI-64 based\n");
1149 sprintf(buf+len, "NAA\n");
1152 sprintf(buf+len, "Relative target port identifier\n");
1155 sprintf(buf+len, "SCSI name string\n");
1158 sprintf(buf+len, "Unsupported: 0x%02x\n",
1159 vpd->device_identifier_type);
1165 if (p_buf_len < strlen(buf)+1)
1167 strncpy(p_buf, buf, p_buf_len);
1169 pr_debug("%s", buf);
1175 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1178 * The VPD identifier type..
1180 * from spc3r23.pdf Section 7.6.3.1 Table 298
1182 vpd->device_identifier_type = (page_83[1] & 0x0f);
1183 return transport_dump_vpd_ident_type(vpd, NULL, 0);
1185 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1187 int transport_dump_vpd_ident(
1188 struct t10_vpd *vpd,
1189 unsigned char *p_buf,
1192 unsigned char buf[VPD_TMP_BUF_SIZE];
1195 memset(buf, 0, VPD_TMP_BUF_SIZE);
1197 switch (vpd->device_identifier_code_set) {
1198 case 0x01: /* Binary */
1199 snprintf(buf, sizeof(buf),
1200 "T10 VPD Binary Device Identifier: %s\n",
1201 &vpd->device_identifier[0]);
1203 case 0x02: /* ASCII */
1204 snprintf(buf, sizeof(buf),
1205 "T10 VPD ASCII Device Identifier: %s\n",
1206 &vpd->device_identifier[0]);
1208 case 0x03: /* UTF-8 */
1209 snprintf(buf, sizeof(buf),
1210 "T10 VPD UTF-8 Device Identifier: %s\n",
1211 &vpd->device_identifier[0]);
1214 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1215 " 0x%02x", vpd->device_identifier_code_set);
1221 strncpy(p_buf, buf, p_buf_len);
1223 pr_debug("%s", buf);
1229 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1231 static const char hex_str[] = "0123456789abcdef";
1232 int j = 0, i = 4; /* offset to start of the identifier */
1235 * The VPD Code Set (encoding)
1237 * from spc3r23.pdf Section 7.6.3.1 Table 296
1239 vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1240 switch (vpd->device_identifier_code_set) {
1241 case 0x01: /* Binary */
1242 vpd->device_identifier[j++] =
1243 hex_str[vpd->device_identifier_type];
1244 while (i < (4 + page_83[3])) {
1245 vpd->device_identifier[j++] =
1246 hex_str[(page_83[i] & 0xf0) >> 4];
1247 vpd->device_identifier[j++] =
1248 hex_str[page_83[i] & 0x0f];
1252 case 0x02: /* ASCII */
1253 case 0x03: /* UTF-8 */
1254 while (i < (4 + page_83[3]))
1255 vpd->device_identifier[j++] = page_83[i++];
1261 return transport_dump_vpd_ident(vpd, NULL, 0);
1263 EXPORT_SYMBOL(transport_set_vpd_ident);
1265 static sense_reason_t
1266 target_check_max_data_sg_nents(struct se_cmd *cmd, struct se_device *dev,
1271 if (!cmd->se_tfo->max_data_sg_nents)
1272 return TCM_NO_SENSE;
1274 * Check if fabric enforced maximum SGL entries per I/O descriptor
1275 * exceeds se_cmd->data_length. If true, set SCF_UNDERFLOW_BIT +
1276 * residual_count and reduce original cmd->data_length to maximum
1277 * length based on single PAGE_SIZE entry scatter-lists.
1279 mtl = (cmd->se_tfo->max_data_sg_nents * PAGE_SIZE);
1280 if (cmd->data_length > mtl) {
1282 * If an existing CDB overflow is present, calculate new residual
1283 * based on CDB size minus fabric maximum transfer length.
1285 * If an existing CDB underflow is present, calculate new residual
1286 * based on original cmd->data_length minus fabric maximum transfer
1289 * Otherwise, set the underflow residual based on cmd->data_length
1290 * minus fabric maximum transfer length.
1292 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1293 cmd->residual_count = (size - mtl);
1294 } else if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
1295 u32 orig_dl = size + cmd->residual_count;
1296 cmd->residual_count = (orig_dl - mtl);
1298 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1299 cmd->residual_count = (cmd->data_length - mtl);
1301 cmd->data_length = mtl;
1303 * Reset sbc_check_prot() calculated protection payload
1304 * length based upon the new smaller MTL.
1306 if (cmd->prot_length) {
1307 u32 sectors = (mtl / dev->dev_attrib.block_size);
1308 cmd->prot_length = dev->prot_length * sectors;
1311 return TCM_NO_SENSE;
1315 * target_cmd_size_check - Check whether there will be a residual.
1316 * @cmd: SCSI command.
1317 * @size: Data buffer size derived from CDB. The data buffer size provided by
1318 * the SCSI transport driver is available in @cmd->data_length.
1320 * Compare the data buffer size from the CDB with the data buffer limit from the transport
1321 * header. Set @cmd->residual_count and SCF_OVERFLOW_BIT or SCF_UNDERFLOW_BIT if necessary.
1323 * Note: target drivers set @cmd->data_length by calling __target_init_cmd().
1325 * Return: TCM_NO_SENSE
1328 target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1330 struct se_device *dev = cmd->se_dev;
1332 if (cmd->unknown_data_length) {
1333 cmd->data_length = size;
1334 } else if (size != cmd->data_length) {
1335 pr_warn_ratelimited("TARGET_CORE[%s]: Expected Transfer Length:"
1336 " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1337 " 0x%02x\n", cmd->se_tfo->fabric_name,
1338 cmd->data_length, size, cmd->t_task_cdb[0]);
1340 * For READ command for the overflow case keep the existing
1341 * fabric provided ->data_length. Otherwise for the underflow
1342 * case, reset ->data_length to the smaller SCSI expected data
1345 if (size > cmd->data_length) {
1346 cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1347 cmd->residual_count = (size - cmd->data_length);
1349 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1350 cmd->residual_count = (cmd->data_length - size);
1352 * Do not truncate ->data_length for WRITE command to
1355 if (cmd->data_direction == DMA_FROM_DEVICE) {
1356 cmd->data_length = size;
1360 if (cmd->data_direction == DMA_TO_DEVICE) {
1361 if (cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) {
1362 pr_err_ratelimited("Rejecting underflow/overflow"
1363 " for WRITE data CDB\n");
1364 return TCM_INVALID_FIELD_IN_COMMAND_IU;
1367 * Some fabric drivers like iscsi-target still expect to
1368 * always reject overflow writes. Reject this case until
1369 * full fabric driver level support for overflow writes
1370 * is introduced tree-wide.
1372 if (size > cmd->data_length) {
1373 pr_err_ratelimited("Rejecting overflow for"
1374 " WRITE control CDB\n");
1375 return TCM_INVALID_CDB_FIELD;
1380 return target_check_max_data_sg_nents(cmd, dev, size);
1385 * Used by fabric modules containing a local struct se_cmd within their
1386 * fabric dependent per I/O descriptor.
1388 * Preserves the value of @cmd->tag.
1390 void __target_init_cmd(
1392 const struct target_core_fabric_ops *tfo,
1393 struct se_session *se_sess,
1397 unsigned char *sense_buffer, u64 unpacked_lun)
1399 INIT_LIST_HEAD(&cmd->se_delayed_node);
1400 INIT_LIST_HEAD(&cmd->se_qf_node);
1401 INIT_LIST_HEAD(&cmd->state_list);
1402 init_completion(&cmd->t_transport_stop_comp);
1403 cmd->free_compl = NULL;
1404 cmd->abrt_compl = NULL;
1405 spin_lock_init(&cmd->t_state_lock);
1406 INIT_WORK(&cmd->work, NULL);
1407 kref_init(&cmd->cmd_kref);
1409 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1411 cmd->se_sess = se_sess;
1412 cmd->data_length = data_length;
1413 cmd->data_direction = data_direction;
1414 cmd->sam_task_attr = task_attr;
1415 cmd->sense_buffer = sense_buffer;
1416 cmd->orig_fe_lun = unpacked_lun;
1418 if (!(cmd->se_cmd_flags & SCF_USE_CPUID))
1419 cmd->cpuid = smp_processor_id();
1421 cmd->state_active = false;
1423 EXPORT_SYMBOL(__target_init_cmd);
1425 static sense_reason_t
1426 transport_check_alloc_task_attr(struct se_cmd *cmd)
1428 struct se_device *dev = cmd->se_dev;
1431 * Check if SAM Task Attribute emulation is enabled for this
1432 * struct se_device storage object
1434 if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1437 if (cmd->sam_task_attr == TCM_ACA_TAG) {
1438 pr_debug("SAM Task Attribute ACA"
1439 " emulation is not supported\n");
1440 return TCM_INVALID_CDB_FIELD;
1447 target_cmd_init_cdb(struct se_cmd *cmd, unsigned char *cdb, gfp_t gfp)
1452 * Ensure that the received CDB is less than the max (252 + 8) bytes
1453 * for VARIABLE_LENGTH_CMD
1455 if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1456 pr_err("Received SCSI CDB with command_size: %d that"
1457 " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1458 scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1459 ret = TCM_INVALID_CDB_FIELD;
1463 * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1464 * allocate the additional extended CDB buffer now.. Otherwise
1465 * setup the pointer from __t_task_cdb to t_task_cdb.
1467 if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1468 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb), gfp);
1469 if (!cmd->t_task_cdb) {
1470 pr_err("Unable to allocate cmd->t_task_cdb"
1471 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1472 scsi_command_size(cdb),
1473 (unsigned long)sizeof(cmd->__t_task_cdb));
1474 ret = TCM_OUT_OF_RESOURCES;
1479 * Copy the original CDB into cmd->
1481 memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1483 trace_target_sequencer_start(cmd);
1488 * Copy the CDB here to allow trace_target_cmd_complete() to
1489 * print the cdb to the trace buffers.
1491 memcpy(cmd->t_task_cdb, cdb, min(scsi_command_size(cdb),
1492 (unsigned int)TCM_MAX_COMMAND_SIZE));
1495 EXPORT_SYMBOL(target_cmd_init_cdb);
1498 target_cmd_parse_cdb(struct se_cmd *cmd)
1500 struct se_device *dev = cmd->se_dev;
1503 ret = dev->transport->parse_cdb(cmd);
1504 if (ret == TCM_UNSUPPORTED_SCSI_OPCODE)
1505 pr_warn_ratelimited("%s/%s: Unsupported SCSI Opcode 0x%02x, sending CHECK_CONDITION.\n",
1506 cmd->se_tfo->fabric_name,
1507 cmd->se_sess->se_node_acl->initiatorname,
1508 cmd->t_task_cdb[0]);
1512 ret = transport_check_alloc_task_attr(cmd);
1516 cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1517 atomic_long_inc(&cmd->se_lun->lun_stats.cmd_pdus);
1520 EXPORT_SYMBOL(target_cmd_parse_cdb);
1523 * Used by fabric module frontends to queue tasks directly.
1524 * May only be used from process context.
1526 int transport_handle_cdb_direct(
1535 pr_err("cmd->se_lun is NULL\n");
1540 * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1541 * outstanding descriptors are handled correctly during shutdown via
1542 * transport_wait_for_tasks()
1544 * Also, we don't take cmd->t_state_lock here as we only expect
1545 * this to be called for initial descriptor submission.
1547 cmd->t_state = TRANSPORT_NEW_CMD;
1548 cmd->transport_state |= CMD_T_ACTIVE;
1551 * transport_generic_new_cmd() is already handling QUEUE_FULL,
1552 * so follow TRANSPORT_NEW_CMD processing thread context usage
1553 * and call transport_generic_request_failure() if necessary..
1555 ret = transport_generic_new_cmd(cmd);
1557 transport_generic_request_failure(cmd, ret);
1560 EXPORT_SYMBOL(transport_handle_cdb_direct);
1563 transport_generic_map_mem_to_cmd(struct se_cmd *cmd, struct scatterlist *sgl,
1564 u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count)
1566 if (!sgl || !sgl_count)
1570 * Reject SCSI data overflow with map_mem_to_cmd() as incoming
1571 * scatterlists already have been set to follow what the fabric
1572 * passes for the original expected data transfer length.
1574 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1575 pr_warn("Rejecting SCSI DATA overflow for fabric using"
1576 " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
1577 return TCM_INVALID_CDB_FIELD;
1580 cmd->t_data_sg = sgl;
1581 cmd->t_data_nents = sgl_count;
1582 cmd->t_bidi_data_sg = sgl_bidi;
1583 cmd->t_bidi_data_nents = sgl_bidi_count;
1585 cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
1590 * target_init_cmd - initialize se_cmd
1591 * @se_cmd: command descriptor to init
1592 * @se_sess: associated se_sess for endpoint
1593 * @sense: pointer to SCSI sense buffer
1594 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1595 * @data_length: fabric expected data transfer length
1596 * @task_attr: SAM task attribute
1597 * @data_dir: DMA data direction
1598 * @flags: flags for command submission from target_sc_flags_tables
1600 * Task tags are supported if the caller has set @se_cmd->tag.
1603 * - less than zero to signal active I/O shutdown failure.
1604 * - zero on success.
1606 * If the fabric driver calls target_stop_session, then it must check the
1607 * return code and handle failures. This will never fail for other drivers,
1608 * and the return code can be ignored.
1610 int target_init_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1611 unsigned char *sense, u64 unpacked_lun,
1612 u32 data_length, int task_attr, int data_dir, int flags)
1614 struct se_portal_group *se_tpg;
1616 se_tpg = se_sess->se_tpg;
1618 BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1620 if (flags & TARGET_SCF_USE_CPUID)
1621 se_cmd->se_cmd_flags |= SCF_USE_CPUID;
1623 * Signal bidirectional data payloads to target-core
1625 if (flags & TARGET_SCF_BIDI_OP)
1626 se_cmd->se_cmd_flags |= SCF_BIDI;
1628 if (flags & TARGET_SCF_UNKNOWN_SIZE)
1629 se_cmd->unknown_data_length = 1;
1631 * Initialize se_cmd for target operation. From this point
1632 * exceptions are handled by sending exception status via
1633 * target_core_fabric_ops->queue_status() callback
1635 __target_init_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess, data_length,
1636 data_dir, task_attr, sense, unpacked_lun);
1639 * Obtain struct se_cmd->cmd_kref reference. A second kref_get here is
1640 * necessary for fabrics using TARGET_SCF_ACK_KREF that expect a second
1641 * kref_put() to happen during fabric packet acknowledgement.
1643 return target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1645 EXPORT_SYMBOL_GPL(target_init_cmd);
1648 * target_submit_prep - prepare cmd for submission
1649 * @se_cmd: command descriptor to prep
1650 * @cdb: pointer to SCSI CDB
1651 * @sgl: struct scatterlist memory for unidirectional mapping
1652 * @sgl_count: scatterlist count for unidirectional mapping
1653 * @sgl_bidi: struct scatterlist memory for bidirectional READ mapping
1654 * @sgl_bidi_count: scatterlist count for bidirectional READ mapping
1655 * @sgl_prot: struct scatterlist memory protection information
1656 * @sgl_prot_count: scatterlist count for protection information
1657 * @gfp: gfp allocation type
1660 * - less than zero to signal failure.
1661 * - zero on success.
1663 * If failure is returned, lio will the callers queue_status to complete
1666 int target_submit_prep(struct se_cmd *se_cmd, unsigned char *cdb,
1667 struct scatterlist *sgl, u32 sgl_count,
1668 struct scatterlist *sgl_bidi, u32 sgl_bidi_count,
1669 struct scatterlist *sgl_prot, u32 sgl_prot_count,
1674 rc = target_cmd_init_cdb(se_cmd, cdb, gfp);
1676 goto send_cc_direct;
1679 * Locate se_lun pointer and attach it to struct se_cmd
1681 rc = transport_lookup_cmd_lun(se_cmd);
1683 goto send_cc_direct;
1685 rc = target_cmd_parse_cdb(se_cmd);
1690 * Save pointers for SGLs containing protection information,
1693 if (sgl_prot_count) {
1694 se_cmd->t_prot_sg = sgl_prot;
1695 se_cmd->t_prot_nents = sgl_prot_count;
1696 se_cmd->se_cmd_flags |= SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC;
1700 * When a non zero sgl_count has been passed perform SGL passthrough
1701 * mapping for pre-allocated fabric memory instead of having target
1702 * core perform an internal SGL allocation..
1704 if (sgl_count != 0) {
1707 rc = transport_generic_map_mem_to_cmd(se_cmd, sgl, sgl_count,
1708 sgl_bidi, sgl_bidi_count);
1716 transport_send_check_condition_and_sense(se_cmd, rc, 0);
1717 target_put_sess_cmd(se_cmd);
1721 transport_generic_request_failure(se_cmd, rc);
1724 EXPORT_SYMBOL_GPL(target_submit_prep);
1727 * target_submit - perform final initialization and submit cmd to LIO core
1728 * @se_cmd: command descriptor to submit
1730 * target_submit_prep must have been called on the cmd, and this must be
1731 * called from process context.
1733 void target_submit(struct se_cmd *se_cmd)
1735 struct scatterlist *sgl = se_cmd->t_data_sg;
1736 unsigned char *buf = NULL;
1740 if (se_cmd->t_data_nents != 0) {
1743 * A work-around for tcm_loop as some userspace code via
1744 * scsi-generic do not memset their associated read buffers,
1745 * so go ahead and do that here for type non-data CDBs. Also
1746 * note that this is currently guaranteed to be a single SGL
1747 * for this case by target core in target_setup_cmd_from_cdb()
1748 * -> transport_generic_cmd_sequencer().
1750 if (!(se_cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) &&
1751 se_cmd->data_direction == DMA_FROM_DEVICE) {
1753 buf = kmap(sg_page(sgl)) + sgl->offset;
1756 memset(buf, 0, sgl->length);
1757 kunmap(sg_page(sgl));
1764 * Check if we need to delay processing because of ALUA
1765 * Active/NonOptimized primary access state..
1767 core_alua_check_nonop_delay(se_cmd);
1769 transport_handle_cdb_direct(se_cmd);
1771 EXPORT_SYMBOL_GPL(target_submit);
1774 * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1776 * @se_cmd: command descriptor to submit
1777 * @se_sess: associated se_sess for endpoint
1778 * @cdb: pointer to SCSI CDB
1779 * @sense: pointer to SCSI sense buffer
1780 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1781 * @data_length: fabric expected data transfer length
1782 * @task_attr: SAM task attribute
1783 * @data_dir: DMA data direction
1784 * @flags: flags for command submission from target_sc_flags_tables
1786 * Task tags are supported if the caller has set @se_cmd->tag.
1788 * This may only be called from process context, and also currently
1789 * assumes internal allocation of fabric payload buffer by target-core.
1791 * It also assumes interal target core SGL memory allocation.
1793 * This function must only be used by drivers that do their own
1794 * sync during shutdown and does not use target_stop_session. If there
1795 * is a failure this function will call into the fabric driver's
1796 * queue_status with a CHECK_CONDITION.
1798 void target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1799 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1800 u32 data_length, int task_attr, int data_dir, int flags)
1804 rc = target_init_cmd(se_cmd, se_sess, sense, unpacked_lun, data_length,
1805 task_attr, data_dir, flags);
1806 WARN(rc, "Invalid target_submit_cmd use. Driver must not use target_stop_session or call target_init_cmd directly.\n");
1810 if (target_submit_prep(se_cmd, cdb, NULL, 0, NULL, 0, NULL, 0,
1814 target_submit(se_cmd);
1816 EXPORT_SYMBOL(target_submit_cmd);
1819 static struct se_dev_plug *target_plug_device(struct se_device *se_dev)
1821 struct se_dev_plug *se_plug;
1823 if (!se_dev->transport->plug_device)
1826 se_plug = se_dev->transport->plug_device(se_dev);
1830 se_plug->se_dev = se_dev;
1832 * We have a ref to the lun at this point, but the cmds could
1833 * complete before we unplug, so grab a ref to the se_device so we
1834 * can call back into the backend.
1836 config_group_get(&se_dev->dev_group);
1840 static void target_unplug_device(struct se_dev_plug *se_plug)
1842 struct se_device *se_dev = se_plug->se_dev;
1844 se_dev->transport->unplug_device(se_plug);
1845 config_group_put(&se_dev->dev_group);
1848 void target_queued_submit_work(struct work_struct *work)
1850 struct se_cmd_queue *sq = container_of(work, struct se_cmd_queue, work);
1851 struct se_cmd *se_cmd, *next_cmd;
1852 struct se_dev_plug *se_plug = NULL;
1853 struct se_device *se_dev = NULL;
1854 struct llist_node *cmd_list;
1856 cmd_list = llist_del_all(&sq->cmd_list);
1858 /* Previous call took what we were queued to submit */
1861 cmd_list = llist_reverse_order(cmd_list);
1862 llist_for_each_entry_safe(se_cmd, next_cmd, cmd_list, se_cmd_list) {
1864 se_dev = se_cmd->se_dev;
1865 se_plug = target_plug_device(se_dev);
1868 target_submit(se_cmd);
1872 target_unplug_device(se_plug);
1876 * target_queue_submission - queue the cmd to run on the LIO workqueue
1877 * @se_cmd: command descriptor to submit
1879 void target_queue_submission(struct se_cmd *se_cmd)
1881 struct se_device *se_dev = se_cmd->se_dev;
1882 int cpu = se_cmd->cpuid;
1883 struct se_cmd_queue *sq;
1885 sq = &se_dev->queues[cpu].sq;
1886 llist_add(&se_cmd->se_cmd_list, &sq->cmd_list);
1887 queue_work_on(cpu, target_submission_wq, &sq->work);
1889 EXPORT_SYMBOL_GPL(target_queue_submission);
1891 static void target_complete_tmr_failure(struct work_struct *work)
1893 struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1895 se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1896 se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1898 transport_lun_remove_cmd(se_cmd);
1899 transport_cmd_check_stop_to_fabric(se_cmd);
1903 * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1906 * @se_cmd: command descriptor to submit
1907 * @se_sess: associated se_sess for endpoint
1908 * @sense: pointer to SCSI sense buffer
1909 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1910 * @fabric_tmr_ptr: fabric context for TMR req
1911 * @tm_type: Type of TM request
1912 * @gfp: gfp type for caller
1913 * @tag: referenced task tag for TMR_ABORT_TASK
1914 * @flags: submit cmd flags
1916 * Callable from all contexts.
1919 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1920 unsigned char *sense, u64 unpacked_lun,
1921 void *fabric_tmr_ptr, unsigned char tm_type,
1922 gfp_t gfp, u64 tag, int flags)
1924 struct se_portal_group *se_tpg;
1927 se_tpg = se_sess->se_tpg;
1930 __target_init_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1931 0, DMA_NONE, TCM_SIMPLE_TAG, sense, unpacked_lun);
1933 * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1934 * allocation failure.
1936 ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1940 if (tm_type == TMR_ABORT_TASK)
1941 se_cmd->se_tmr_req->ref_task_tag = tag;
1943 /* See target_submit_cmd for commentary */
1944 ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1946 core_tmr_release_req(se_cmd->se_tmr_req);
1950 ret = transport_lookup_tmr_lun(se_cmd);
1954 transport_generic_handle_tmr(se_cmd);
1958 * For callback during failure handling, push this work off
1959 * to process context with TMR_LUN_DOES_NOT_EXIST status.
1962 INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1963 schedule_work(&se_cmd->work);
1966 EXPORT_SYMBOL(target_submit_tmr);
1969 * Handle SAM-esque emulation for generic transport request failures.
1971 void transport_generic_request_failure(struct se_cmd *cmd,
1972 sense_reason_t sense_reason)
1974 int ret = 0, post_ret;
1976 pr_debug("-----[ Storage Engine Exception; sense_reason %d\n",
1978 target_show_cmd("-----[ ", cmd);
1981 * For SAM Task Attribute emulation for failed struct se_cmd
1983 transport_complete_task_attr(cmd);
1985 if (cmd->transport_complete_callback)
1986 cmd->transport_complete_callback(cmd, false, &post_ret);
1988 if (cmd->transport_state & CMD_T_ABORTED) {
1989 INIT_WORK(&cmd->work, target_abort_work);
1990 queue_work(target_completion_wq, &cmd->work);
1994 switch (sense_reason) {
1995 case TCM_NON_EXISTENT_LUN:
1996 case TCM_UNSUPPORTED_SCSI_OPCODE:
1997 case TCM_INVALID_CDB_FIELD:
1998 case TCM_INVALID_PARAMETER_LIST:
1999 case TCM_PARAMETER_LIST_LENGTH_ERROR:
2000 case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
2001 case TCM_UNKNOWN_MODE_PAGE:
2002 case TCM_WRITE_PROTECTED:
2003 case TCM_ADDRESS_OUT_OF_RANGE:
2004 case TCM_CHECK_CONDITION_ABORT_CMD:
2005 case TCM_CHECK_CONDITION_UNIT_ATTENTION:
2006 case TCM_CHECK_CONDITION_NOT_READY:
2007 case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED:
2008 case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED:
2009 case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED:
2010 case TCM_COPY_TARGET_DEVICE_NOT_REACHABLE:
2011 case TCM_TOO_MANY_TARGET_DESCS:
2012 case TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE:
2013 case TCM_TOO_MANY_SEGMENT_DESCS:
2014 case TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE:
2015 case TCM_INVALID_FIELD_IN_COMMAND_IU:
2017 case TCM_OUT_OF_RESOURCES:
2018 cmd->scsi_status = SAM_STAT_TASK_SET_FULL;
2021 cmd->scsi_status = SAM_STAT_BUSY;
2023 case TCM_RESERVATION_CONFLICT:
2025 * No SENSE Data payload for this case, set SCSI Status
2026 * and queue the response to $FABRIC_MOD.
2028 * Uses linux/include/scsi/scsi.h SAM status codes defs
2030 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2032 * For UA Interlock Code 11b, a RESERVATION CONFLICT will
2033 * establish a UNIT ATTENTION with PREVIOUS RESERVATION
2036 * See spc4r17, section 7.4.6 Control Mode Page, Table 349
2039 cmd->se_dev->dev_attrib.emulate_ua_intlck_ctrl
2040 == TARGET_UA_INTLCK_CTRL_ESTABLISH_UA) {
2041 target_ua_allocate_lun(cmd->se_sess->se_node_acl,
2042 cmd->orig_fe_lun, 0x2C,
2043 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
2048 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
2049 cmd->t_task_cdb[0], sense_reason);
2050 sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
2054 ret = transport_send_check_condition_and_sense(cmd, sense_reason, 0);
2059 transport_lun_remove_cmd(cmd);
2060 transport_cmd_check_stop_to_fabric(cmd);
2064 trace_target_cmd_complete(cmd);
2065 ret = cmd->se_tfo->queue_status(cmd);
2069 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2071 EXPORT_SYMBOL(transport_generic_request_failure);
2073 void __target_execute_cmd(struct se_cmd *cmd, bool do_checks)
2077 if (!cmd->execute_cmd) {
2078 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2083 * Check for an existing UNIT ATTENTION condition after
2084 * target_handle_task_attr() has done SAM task attr
2085 * checking, and possibly have already defered execution
2086 * out to target_restart_delayed_cmds() context.
2088 ret = target_scsi3_ua_check(cmd);
2092 ret = target_alua_state_check(cmd);
2096 ret = target_check_reservation(cmd);
2098 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2103 ret = cmd->execute_cmd(cmd);
2107 spin_lock_irq(&cmd->t_state_lock);
2108 cmd->transport_state &= ~CMD_T_SENT;
2109 spin_unlock_irq(&cmd->t_state_lock);
2111 transport_generic_request_failure(cmd, ret);
2114 static int target_write_prot_action(struct se_cmd *cmd)
2118 * Perform WRITE_INSERT of PI using software emulation when backend
2119 * device has PI enabled, if the transport has not already generated
2120 * PI using hardware WRITE_INSERT offload.
2122 switch (cmd->prot_op) {
2123 case TARGET_PROT_DOUT_INSERT:
2124 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_INSERT))
2125 sbc_dif_generate(cmd);
2127 case TARGET_PROT_DOUT_STRIP:
2128 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_STRIP)
2131 sectors = cmd->data_length >> ilog2(cmd->se_dev->dev_attrib.block_size);
2132 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2133 sectors, 0, cmd->t_prot_sg, 0);
2134 if (unlikely(cmd->pi_err)) {
2135 spin_lock_irq(&cmd->t_state_lock);
2136 cmd->transport_state &= ~CMD_T_SENT;
2137 spin_unlock_irq(&cmd->t_state_lock);
2138 transport_generic_request_failure(cmd, cmd->pi_err);
2149 static bool target_handle_task_attr(struct se_cmd *cmd)
2151 struct se_device *dev = cmd->se_dev;
2153 if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2156 cmd->se_cmd_flags |= SCF_TASK_ATTR_SET;
2159 * Check for the existence of HEAD_OF_QUEUE, and if true return 1
2160 * to allow the passed struct se_cmd list of tasks to the front of the list.
2162 switch (cmd->sam_task_attr) {
2164 pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x\n",
2165 cmd->t_task_cdb[0]);
2167 case TCM_ORDERED_TAG:
2168 atomic_inc_mb(&dev->dev_ordered_sync);
2170 pr_debug("Added ORDERED for CDB: 0x%02x to ordered list\n",
2171 cmd->t_task_cdb[0]);
2174 * Execute an ORDERED command if no other older commands
2175 * exist that need to be completed first.
2177 if (!atomic_read(&dev->simple_cmds))
2182 * For SIMPLE and UNTAGGED Task Attribute commands
2184 atomic_inc_mb(&dev->simple_cmds);
2188 if (atomic_read(&dev->dev_ordered_sync) == 0)
2191 spin_lock(&dev->delayed_cmd_lock);
2192 list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
2193 spin_unlock(&dev->delayed_cmd_lock);
2195 pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to delayed CMD listn",
2196 cmd->t_task_cdb[0], cmd->sam_task_attr);
2200 void target_execute_cmd(struct se_cmd *cmd)
2203 * Determine if frontend context caller is requesting the stopping of
2204 * this command for frontend exceptions.
2206 * If the received CDB has already been aborted stop processing it here.
2208 if (target_cmd_interrupted(cmd))
2211 spin_lock_irq(&cmd->t_state_lock);
2212 cmd->t_state = TRANSPORT_PROCESSING;
2213 cmd->transport_state |= CMD_T_ACTIVE | CMD_T_SENT;
2214 spin_unlock_irq(&cmd->t_state_lock);
2216 if (target_write_prot_action(cmd))
2219 if (target_handle_task_attr(cmd)) {
2220 spin_lock_irq(&cmd->t_state_lock);
2221 cmd->transport_state &= ~CMD_T_SENT;
2222 spin_unlock_irq(&cmd->t_state_lock);
2226 __target_execute_cmd(cmd, true);
2228 EXPORT_SYMBOL(target_execute_cmd);
2231 * Process all commands up to the last received ORDERED task attribute which
2232 * requires another blocking boundary
2234 static void target_restart_delayed_cmds(struct se_device *dev)
2239 spin_lock(&dev->delayed_cmd_lock);
2240 if (list_empty(&dev->delayed_cmd_list)) {
2241 spin_unlock(&dev->delayed_cmd_lock);
2245 cmd = list_entry(dev->delayed_cmd_list.next,
2246 struct se_cmd, se_delayed_node);
2247 list_del(&cmd->se_delayed_node);
2248 spin_unlock(&dev->delayed_cmd_lock);
2250 cmd->transport_state |= CMD_T_SENT;
2252 __target_execute_cmd(cmd, true);
2254 if (cmd->sam_task_attr == TCM_ORDERED_TAG)
2260 * Called from I/O completion to determine which dormant/delayed
2261 * and ordered cmds need to have their tasks added to the execution queue.
2263 static void transport_complete_task_attr(struct se_cmd *cmd)
2265 struct se_device *dev = cmd->se_dev;
2267 if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2270 if (!(cmd->se_cmd_flags & SCF_TASK_ATTR_SET))
2273 if (cmd->sam_task_attr == TCM_SIMPLE_TAG) {
2274 atomic_dec_mb(&dev->simple_cmds);
2275 dev->dev_cur_ordered_id++;
2276 } else if (cmd->sam_task_attr == TCM_HEAD_TAG) {
2277 dev->dev_cur_ordered_id++;
2278 pr_debug("Incremented dev_cur_ordered_id: %u for HEAD_OF_QUEUE\n",
2279 dev->dev_cur_ordered_id);
2280 } else if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2281 atomic_dec_mb(&dev->dev_ordered_sync);
2283 dev->dev_cur_ordered_id++;
2284 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED\n",
2285 dev->dev_cur_ordered_id);
2287 cmd->se_cmd_flags &= ~SCF_TASK_ATTR_SET;
2290 target_restart_delayed_cmds(dev);
2293 static void transport_complete_qf(struct se_cmd *cmd)
2297 transport_complete_task_attr(cmd);
2299 * If a fabric driver ->write_pending() or ->queue_data_in() callback
2300 * has returned neither -ENOMEM or -EAGAIN, assume it's fatal and
2301 * the same callbacks should not be retried. Return CHECK_CONDITION
2302 * if a scsi_status is not already set.
2304 * If a fabric driver ->queue_status() has returned non zero, always
2305 * keep retrying no matter what..
2307 if (cmd->t_state == TRANSPORT_COMPLETE_QF_ERR) {
2308 if (cmd->scsi_status)
2311 translate_sense_reason(cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
2316 * Check if we need to send a sense buffer from
2317 * the struct se_cmd in question. We do NOT want
2318 * to take this path of the IO has been marked as
2319 * needing to be treated like a "normal read". This
2320 * is the case if it's a tape read, and either the
2321 * FM, EOM, or ILI bits are set, but there is no
2324 if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2325 cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
2328 switch (cmd->data_direction) {
2329 case DMA_FROM_DEVICE:
2330 /* queue status if not treating this as a normal read */
2331 if (cmd->scsi_status &&
2332 !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2335 trace_target_cmd_complete(cmd);
2336 ret = cmd->se_tfo->queue_data_in(cmd);
2339 if (cmd->se_cmd_flags & SCF_BIDI) {
2340 ret = cmd->se_tfo->queue_data_in(cmd);
2346 trace_target_cmd_complete(cmd);
2347 ret = cmd->se_tfo->queue_status(cmd);
2354 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2357 transport_lun_remove_cmd(cmd);
2358 transport_cmd_check_stop_to_fabric(cmd);
2361 static void transport_handle_queue_full(struct se_cmd *cmd, struct se_device *dev,
2362 int err, bool write_pending)
2365 * -EAGAIN or -ENOMEM signals retry of ->write_pending() and/or
2366 * ->queue_data_in() callbacks from new process context.
2368 * Otherwise for other errors, transport_complete_qf() will send
2369 * CHECK_CONDITION via ->queue_status() instead of attempting to
2370 * retry associated fabric driver data-transfer callbacks.
2372 if (err == -EAGAIN || err == -ENOMEM) {
2373 cmd->t_state = (write_pending) ? TRANSPORT_COMPLETE_QF_WP :
2374 TRANSPORT_COMPLETE_QF_OK;
2376 pr_warn_ratelimited("Got unknown fabric queue status: %d\n", err);
2377 cmd->t_state = TRANSPORT_COMPLETE_QF_ERR;
2380 spin_lock_irq(&dev->qf_cmd_lock);
2381 list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
2382 atomic_inc_mb(&dev->dev_qf_count);
2383 spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
2385 schedule_work(&cmd->se_dev->qf_work_queue);
2388 static bool target_read_prot_action(struct se_cmd *cmd)
2390 switch (cmd->prot_op) {
2391 case TARGET_PROT_DIN_STRIP:
2392 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_STRIP)) {
2393 u32 sectors = cmd->data_length >>
2394 ilog2(cmd->se_dev->dev_attrib.block_size);
2396 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2397 sectors, 0, cmd->t_prot_sg,
2403 case TARGET_PROT_DIN_INSERT:
2404 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_INSERT)
2407 sbc_dif_generate(cmd);
2416 static void target_complete_ok_work(struct work_struct *work)
2418 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
2422 * Check if we need to move delayed/dormant tasks from cmds on the
2423 * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
2426 transport_complete_task_attr(cmd);
2429 * Check to schedule QUEUE_FULL work, or execute an existing
2430 * cmd->transport_qf_callback()
2432 if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
2433 schedule_work(&cmd->se_dev->qf_work_queue);
2436 * Check if we need to send a sense buffer from
2437 * the struct se_cmd in question. We do NOT want
2438 * to take this path of the IO has been marked as
2439 * needing to be treated like a "normal read". This
2440 * is the case if it's a tape read, and either the
2441 * FM, EOM, or ILI bits are set, but there is no
2444 if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2445 cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2446 WARN_ON(!cmd->scsi_status);
2447 ret = transport_send_check_condition_and_sense(
2452 transport_lun_remove_cmd(cmd);
2453 transport_cmd_check_stop_to_fabric(cmd);
2457 * Check for a callback, used by amongst other things
2458 * XDWRITE_READ_10 and COMPARE_AND_WRITE emulation.
2460 if (cmd->transport_complete_callback) {
2462 bool caw = (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE);
2463 bool zero_dl = !(cmd->data_length);
2466 rc = cmd->transport_complete_callback(cmd, true, &post_ret);
2467 if (!rc && !post_ret) {
2473 ret = transport_send_check_condition_and_sense(cmd,
2478 transport_lun_remove_cmd(cmd);
2479 transport_cmd_check_stop_to_fabric(cmd);
2485 switch (cmd->data_direction) {
2486 case DMA_FROM_DEVICE:
2488 * if this is a READ-type IO, but SCSI status
2489 * is set, then skip returning data and just
2490 * return the status -- unless this IO is marked
2491 * as needing to be treated as a normal read,
2492 * in which case we want to go ahead and return
2493 * the data. This happens, for example, for tape
2494 * reads with the FM, EOM, or ILI bits set, with
2497 if (cmd->scsi_status &&
2498 !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2501 atomic_long_add(cmd->data_length,
2502 &cmd->se_lun->lun_stats.tx_data_octets);
2504 * Perform READ_STRIP of PI using software emulation when
2505 * backend had PI enabled, if the transport will not be
2506 * performing hardware READ_STRIP offload.
2508 if (target_read_prot_action(cmd)) {
2509 ret = transport_send_check_condition_and_sense(cmd,
2514 transport_lun_remove_cmd(cmd);
2515 transport_cmd_check_stop_to_fabric(cmd);
2519 trace_target_cmd_complete(cmd);
2520 ret = cmd->se_tfo->queue_data_in(cmd);
2525 atomic_long_add(cmd->data_length,
2526 &cmd->se_lun->lun_stats.rx_data_octets);
2528 * Check if we need to send READ payload for BIDI-COMMAND
2530 if (cmd->se_cmd_flags & SCF_BIDI) {
2531 atomic_long_add(cmd->data_length,
2532 &cmd->se_lun->lun_stats.tx_data_octets);
2533 ret = cmd->se_tfo->queue_data_in(cmd);
2541 trace_target_cmd_complete(cmd);
2542 ret = cmd->se_tfo->queue_status(cmd);
2550 transport_lun_remove_cmd(cmd);
2551 transport_cmd_check_stop_to_fabric(cmd);
2555 pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2556 " data_direction: %d\n", cmd, cmd->data_direction);
2558 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2561 void target_free_sgl(struct scatterlist *sgl, int nents)
2563 sgl_free_n_order(sgl, nents, 0);
2565 EXPORT_SYMBOL(target_free_sgl);
2567 static inline void transport_reset_sgl_orig(struct se_cmd *cmd)
2570 * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE
2571 * emulation, and free + reset pointers if necessary..
2573 if (!cmd->t_data_sg_orig)
2576 kfree(cmd->t_data_sg);
2577 cmd->t_data_sg = cmd->t_data_sg_orig;
2578 cmd->t_data_sg_orig = NULL;
2579 cmd->t_data_nents = cmd->t_data_nents_orig;
2580 cmd->t_data_nents_orig = 0;
2583 static inline void transport_free_pages(struct se_cmd *cmd)
2585 if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2586 target_free_sgl(cmd->t_prot_sg, cmd->t_prot_nents);
2587 cmd->t_prot_sg = NULL;
2588 cmd->t_prot_nents = 0;
2591 if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) {
2593 * Release special case READ buffer payload required for
2594 * SG_TO_MEM_NOALLOC to function with COMPARE_AND_WRITE
2596 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
2597 target_free_sgl(cmd->t_bidi_data_sg,
2598 cmd->t_bidi_data_nents);
2599 cmd->t_bidi_data_sg = NULL;
2600 cmd->t_bidi_data_nents = 0;
2602 transport_reset_sgl_orig(cmd);
2605 transport_reset_sgl_orig(cmd);
2607 target_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2608 cmd->t_data_sg = NULL;
2609 cmd->t_data_nents = 0;
2611 target_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2612 cmd->t_bidi_data_sg = NULL;
2613 cmd->t_bidi_data_nents = 0;
2616 void *transport_kmap_data_sg(struct se_cmd *cmd)
2618 struct scatterlist *sg = cmd->t_data_sg;
2619 struct page **pages;
2623 * We need to take into account a possible offset here for fabrics like
2624 * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2625 * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2627 if (!cmd->t_data_nents)
2631 if (cmd->t_data_nents == 1)
2632 return kmap(sg_page(sg)) + sg->offset;
2634 /* >1 page. use vmap */
2635 pages = kmalloc_array(cmd->t_data_nents, sizeof(*pages), GFP_KERNEL);
2639 /* convert sg[] to pages[] */
2640 for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2641 pages[i] = sg_page(sg);
2644 cmd->t_data_vmap = vmap(pages, cmd->t_data_nents, VM_MAP, PAGE_KERNEL);
2646 if (!cmd->t_data_vmap)
2649 return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2651 EXPORT_SYMBOL(transport_kmap_data_sg);
2653 void transport_kunmap_data_sg(struct se_cmd *cmd)
2655 if (!cmd->t_data_nents) {
2657 } else if (cmd->t_data_nents == 1) {
2658 kunmap(sg_page(cmd->t_data_sg));
2662 vunmap(cmd->t_data_vmap);
2663 cmd->t_data_vmap = NULL;
2665 EXPORT_SYMBOL(transport_kunmap_data_sg);
2668 target_alloc_sgl(struct scatterlist **sgl, unsigned int *nents, u32 length,
2669 bool zero_page, bool chainable)
2671 gfp_t gfp = GFP_KERNEL | (zero_page ? __GFP_ZERO : 0);
2673 *sgl = sgl_alloc_order(length, 0, chainable, gfp, nents);
2674 return *sgl ? 0 : -ENOMEM;
2676 EXPORT_SYMBOL(target_alloc_sgl);
2679 * Allocate any required resources to execute the command. For writes we
2680 * might not have the payload yet, so notify the fabric via a call to
2681 * ->write_pending instead. Otherwise place it on the execution queue.
2684 transport_generic_new_cmd(struct se_cmd *cmd)
2686 unsigned long flags;
2688 bool zero_flag = !(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB);
2690 if (cmd->prot_op != TARGET_PROT_NORMAL &&
2691 !(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2692 ret = target_alloc_sgl(&cmd->t_prot_sg, &cmd->t_prot_nents,
2693 cmd->prot_length, true, false);
2695 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2699 * Determine if the TCM fabric module has already allocated physical
2700 * memory, and is directly calling transport_generic_map_mem_to_cmd()
2703 if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2706 if ((cmd->se_cmd_flags & SCF_BIDI) ||
2707 (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)) {
2710 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)
2711 bidi_length = cmd->t_task_nolb *
2712 cmd->se_dev->dev_attrib.block_size;
2714 bidi_length = cmd->data_length;
2716 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2717 &cmd->t_bidi_data_nents,
2718 bidi_length, zero_flag, false);
2720 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2723 ret = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents,
2724 cmd->data_length, zero_flag, false);
2726 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2727 } else if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
2730 * Special case for COMPARE_AND_WRITE with fabrics
2731 * using SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC.
2733 u32 caw_length = cmd->t_task_nolb *
2734 cmd->se_dev->dev_attrib.block_size;
2736 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2737 &cmd->t_bidi_data_nents,
2738 caw_length, zero_flag, false);
2740 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2743 * If this command is not a write we can execute it right here,
2744 * for write buffers we need to notify the fabric driver first
2745 * and let it call back once the write buffers are ready.
2747 target_add_to_state_list(cmd);
2748 if (cmd->data_direction != DMA_TO_DEVICE || cmd->data_length == 0) {
2749 target_execute_cmd(cmd);
2753 spin_lock_irqsave(&cmd->t_state_lock, flags);
2754 cmd->t_state = TRANSPORT_WRITE_PENDING;
2756 * Determine if frontend context caller is requesting the stopping of
2757 * this command for frontend exceptions.
2759 if (cmd->transport_state & CMD_T_STOP &&
2760 !cmd->se_tfo->write_pending_must_be_called) {
2761 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2762 __func__, __LINE__, cmd->tag);
2764 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2766 complete_all(&cmd->t_transport_stop_comp);
2769 cmd->transport_state &= ~CMD_T_ACTIVE;
2770 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2772 ret = cmd->se_tfo->write_pending(cmd);
2779 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2780 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2783 EXPORT_SYMBOL(transport_generic_new_cmd);
2785 static void transport_write_pending_qf(struct se_cmd *cmd)
2787 unsigned long flags;
2791 spin_lock_irqsave(&cmd->t_state_lock, flags);
2792 stop = (cmd->transport_state & (CMD_T_STOP | CMD_T_ABORTED));
2793 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2796 pr_debug("%s:%d CMD_T_STOP|CMD_T_ABORTED for ITT: 0x%08llx\n",
2797 __func__, __LINE__, cmd->tag);
2798 complete_all(&cmd->t_transport_stop_comp);
2802 ret = cmd->se_tfo->write_pending(cmd);
2804 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2806 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2811 __transport_wait_for_tasks(struct se_cmd *, bool, bool *, bool *,
2812 unsigned long *flags);
2814 static void target_wait_free_cmd(struct se_cmd *cmd, bool *aborted, bool *tas)
2816 unsigned long flags;
2818 spin_lock_irqsave(&cmd->t_state_lock, flags);
2819 __transport_wait_for_tasks(cmd, true, aborted, tas, &flags);
2820 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2824 * Call target_put_sess_cmd() and wait until target_release_cmd_kref(@cmd) has
2827 void target_put_cmd_and_wait(struct se_cmd *cmd)
2829 DECLARE_COMPLETION_ONSTACK(compl);
2831 WARN_ON_ONCE(cmd->abrt_compl);
2832 cmd->abrt_compl = &compl;
2833 target_put_sess_cmd(cmd);
2834 wait_for_completion(&compl);
2838 * This function is called by frontend drivers after processing of a command
2841 * The protocol for ensuring that either the regular frontend command
2842 * processing flow or target_handle_abort() code drops one reference is as
2844 * - Calling .queue_data_in(), .queue_status() or queue_tm_rsp() will cause
2845 * the frontend driver to call this function synchronously or asynchronously.
2846 * That will cause one reference to be dropped.
2847 * - During regular command processing the target core sets CMD_T_COMPLETE
2848 * before invoking one of the .queue_*() functions.
2849 * - The code that aborts commands skips commands and TMFs for which
2850 * CMD_T_COMPLETE has been set.
2851 * - CMD_T_ABORTED is set atomically after the CMD_T_COMPLETE check for
2852 * commands that will be aborted.
2853 * - If the CMD_T_ABORTED flag is set but CMD_T_TAS has not been set
2854 * transport_generic_free_cmd() skips its call to target_put_sess_cmd().
2855 * - For aborted commands for which CMD_T_TAS has been set .queue_status() will
2856 * be called and will drop a reference.
2857 * - For aborted commands for which CMD_T_TAS has not been set .aborted_task()
2858 * will be called. target_handle_abort() will drop the final reference.
2860 int transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2862 DECLARE_COMPLETION_ONSTACK(compl);
2864 bool aborted = false, tas = false;
2867 target_wait_free_cmd(cmd, &aborted, &tas);
2869 if (cmd->se_cmd_flags & SCF_SE_LUN_CMD) {
2871 * Handle WRITE failure case where transport_generic_new_cmd()
2872 * has already added se_cmd to state_list, but fabric has
2873 * failed command before I/O submission.
2875 if (cmd->state_active)
2876 target_remove_from_state_list(cmd);
2879 transport_lun_remove_cmd(cmd);
2882 cmd->free_compl = &compl;
2883 ret = target_put_sess_cmd(cmd);
2885 pr_debug("Detected CMD_T_ABORTED for ITT: %llu\n", cmd->tag);
2886 wait_for_completion(&compl);
2891 EXPORT_SYMBOL(transport_generic_free_cmd);
2894 * target_get_sess_cmd - Verify the session is accepting cmds and take ref
2895 * @se_cmd: command descriptor to add
2896 * @ack_kref: Signal that fabric will perform an ack target_put_sess_cmd()
2898 int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
2900 struct se_session *se_sess = se_cmd->se_sess;
2904 * Add a second kref if the fabric caller is expecting to handle
2905 * fabric acknowledgement that requires two target_put_sess_cmd()
2906 * invocations before se_cmd descriptor release.
2909 kref_get(&se_cmd->cmd_kref);
2910 se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2913 if (!percpu_ref_tryget_live(&se_sess->cmd_count))
2916 if (ret && ack_kref)
2917 target_put_sess_cmd(se_cmd);
2921 EXPORT_SYMBOL(target_get_sess_cmd);
2923 static void target_free_cmd_mem(struct se_cmd *cmd)
2925 transport_free_pages(cmd);
2927 if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2928 core_tmr_release_req(cmd->se_tmr_req);
2929 if (cmd->t_task_cdb != cmd->__t_task_cdb)
2930 kfree(cmd->t_task_cdb);
2933 static void target_release_cmd_kref(struct kref *kref)
2935 struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2936 struct se_session *se_sess = se_cmd->se_sess;
2937 struct completion *free_compl = se_cmd->free_compl;
2938 struct completion *abrt_compl = se_cmd->abrt_compl;
2940 target_free_cmd_mem(se_cmd);
2941 se_cmd->se_tfo->release_cmd(se_cmd);
2943 complete(free_compl);
2945 complete(abrt_compl);
2947 percpu_ref_put(&se_sess->cmd_count);
2951 * target_put_sess_cmd - decrease the command reference count
2952 * @se_cmd: command to drop a reference from
2954 * Returns 1 if and only if this target_put_sess_cmd() call caused the
2955 * refcount to drop to zero. Returns zero otherwise.
2957 int target_put_sess_cmd(struct se_cmd *se_cmd)
2959 return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2961 EXPORT_SYMBOL(target_put_sess_cmd);
2963 static const char *data_dir_name(enum dma_data_direction d)
2966 case DMA_BIDIRECTIONAL: return "BIDI";
2967 case DMA_TO_DEVICE: return "WRITE";
2968 case DMA_FROM_DEVICE: return "READ";
2969 case DMA_NONE: return "NONE";
2975 static const char *cmd_state_name(enum transport_state_table t)
2978 case TRANSPORT_NO_STATE: return "NO_STATE";
2979 case TRANSPORT_NEW_CMD: return "NEW_CMD";
2980 case TRANSPORT_WRITE_PENDING: return "WRITE_PENDING";
2981 case TRANSPORT_PROCESSING: return "PROCESSING";
2982 case TRANSPORT_COMPLETE: return "COMPLETE";
2983 case TRANSPORT_ISTATE_PROCESSING:
2984 return "ISTATE_PROCESSING";
2985 case TRANSPORT_COMPLETE_QF_WP: return "COMPLETE_QF_WP";
2986 case TRANSPORT_COMPLETE_QF_OK: return "COMPLETE_QF_OK";
2987 case TRANSPORT_COMPLETE_QF_ERR: return "COMPLETE_QF_ERR";
2993 static void target_append_str(char **str, const char *txt)
2997 *str = *str ? kasprintf(GFP_ATOMIC, "%s,%s", *str, txt) :
2998 kstrdup(txt, GFP_ATOMIC);
3003 * Convert a transport state bitmask into a string. The caller is
3004 * responsible for freeing the returned pointer.
3006 static char *target_ts_to_str(u32 ts)
3010 if (ts & CMD_T_ABORTED)
3011 target_append_str(&str, "aborted");
3012 if (ts & CMD_T_ACTIVE)
3013 target_append_str(&str, "active");
3014 if (ts & CMD_T_COMPLETE)
3015 target_append_str(&str, "complete");
3016 if (ts & CMD_T_SENT)
3017 target_append_str(&str, "sent");
3018 if (ts & CMD_T_STOP)
3019 target_append_str(&str, "stop");
3020 if (ts & CMD_T_FABRIC_STOP)
3021 target_append_str(&str, "fabric_stop");
3026 static const char *target_tmf_name(enum tcm_tmreq_table tmf)
3029 case TMR_ABORT_TASK: return "ABORT_TASK";
3030 case TMR_ABORT_TASK_SET: return "ABORT_TASK_SET";
3031 case TMR_CLEAR_ACA: return "CLEAR_ACA";
3032 case TMR_CLEAR_TASK_SET: return "CLEAR_TASK_SET";
3033 case TMR_LUN_RESET: return "LUN_RESET";
3034 case TMR_TARGET_WARM_RESET: return "TARGET_WARM_RESET";
3035 case TMR_TARGET_COLD_RESET: return "TARGET_COLD_RESET";
3036 case TMR_LUN_RESET_PRO: return "LUN_RESET_PRO";
3037 case TMR_UNKNOWN: break;
3042 void target_show_cmd(const char *pfx, struct se_cmd *cmd)
3044 char *ts_str = target_ts_to_str(cmd->transport_state);
3045 const u8 *cdb = cmd->t_task_cdb;
3046 struct se_tmr_req *tmf = cmd->se_tmr_req;
3048 if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
3049 pr_debug("%scmd %#02x:%#02x with tag %#llx dir %s i_state %d t_state %s len %d refcnt %d transport_state %s\n",
3050 pfx, cdb[0], cdb[1], cmd->tag,
3051 data_dir_name(cmd->data_direction),
3052 cmd->se_tfo->get_cmd_state(cmd),
3053 cmd_state_name(cmd->t_state), cmd->data_length,
3054 kref_read(&cmd->cmd_kref), ts_str);
3056 pr_debug("%stmf %s with tag %#llx ref_task_tag %#llx i_state %d t_state %s refcnt %d transport_state %s\n",
3057 pfx, target_tmf_name(tmf->function), cmd->tag,
3058 tmf->ref_task_tag, cmd->se_tfo->get_cmd_state(cmd),
3059 cmd_state_name(cmd->t_state),
3060 kref_read(&cmd->cmd_kref), ts_str);
3064 EXPORT_SYMBOL(target_show_cmd);
3066 static void target_stop_session_confirm(struct percpu_ref *ref)
3068 struct se_session *se_sess = container_of(ref, struct se_session,
3070 complete_all(&se_sess->stop_done);
3074 * target_stop_session - Stop new IO from being queued on the session.
3075 * @se_sess: session to stop
3077 void target_stop_session(struct se_session *se_sess)
3079 pr_debug("Stopping session queue.\n");
3080 if (atomic_cmpxchg(&se_sess->stopped, 0, 1) == 0)
3081 percpu_ref_kill_and_confirm(&se_sess->cmd_count,
3082 target_stop_session_confirm);
3084 EXPORT_SYMBOL(target_stop_session);
3087 * target_wait_for_sess_cmds - Wait for outstanding commands
3088 * @se_sess: session to wait for active I/O
3090 void target_wait_for_sess_cmds(struct se_session *se_sess)
3094 WARN_ON_ONCE(!atomic_read(&se_sess->stopped));
3097 pr_debug("Waiting for running cmds to complete.\n");
3098 ret = wait_event_timeout(se_sess->cmd_count_wq,
3099 percpu_ref_is_zero(&se_sess->cmd_count),
3103 wait_for_completion(&se_sess->stop_done);
3104 pr_debug("Waiting for cmds done.\n");
3106 EXPORT_SYMBOL(target_wait_for_sess_cmds);
3109 * Prevent that new percpu_ref_tryget_live() calls succeed and wait until
3110 * all references to the LUN have been released. Called during LUN shutdown.
3112 void transport_clear_lun_ref(struct se_lun *lun)
3114 percpu_ref_kill(&lun->lun_ref);
3115 wait_for_completion(&lun->lun_shutdown_comp);
3119 __transport_wait_for_tasks(struct se_cmd *cmd, bool fabric_stop,
3120 bool *aborted, bool *tas, unsigned long *flags)
3121 __releases(&cmd->t_state_lock)
3122 __acquires(&cmd->t_state_lock)
3125 assert_spin_locked(&cmd->t_state_lock);
3126 WARN_ON_ONCE(!irqs_disabled());
3129 cmd->transport_state |= CMD_T_FABRIC_STOP;
3131 if (cmd->transport_state & CMD_T_ABORTED)
3134 if (cmd->transport_state & CMD_T_TAS)
3137 if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
3138 !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3141 if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
3142 !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3145 if (!(cmd->transport_state & CMD_T_ACTIVE))
3148 if (fabric_stop && *aborted)
3151 cmd->transport_state |= CMD_T_STOP;
3153 target_show_cmd("wait_for_tasks: Stopping ", cmd);
3155 spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
3157 while (!wait_for_completion_timeout(&cmd->t_transport_stop_comp,
3159 target_show_cmd("wait for tasks: ", cmd);
3161 spin_lock_irqsave(&cmd->t_state_lock, *flags);
3162 cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
3164 pr_debug("wait_for_tasks: Stopped wait_for_completion(&cmd->"
3165 "t_transport_stop_comp) for ITT: 0x%08llx\n", cmd->tag);
3171 * transport_wait_for_tasks - set CMD_T_STOP and wait for t_transport_stop_comp
3172 * @cmd: command to wait on
3174 bool transport_wait_for_tasks(struct se_cmd *cmd)
3176 unsigned long flags;
3177 bool ret, aborted = false, tas = false;
3179 spin_lock_irqsave(&cmd->t_state_lock, flags);
3180 ret = __transport_wait_for_tasks(cmd, false, &aborted, &tas, &flags);
3181 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3185 EXPORT_SYMBOL(transport_wait_for_tasks);
3187 struct sense_detail {
3191 bool add_sense_info;
3194 static const struct sense_detail sense_detail_table[] = {
3198 [TCM_NON_EXISTENT_LUN] = {
3199 .key = ILLEGAL_REQUEST,
3200 .asc = 0x25 /* LOGICAL UNIT NOT SUPPORTED */
3202 [TCM_UNSUPPORTED_SCSI_OPCODE] = {
3203 .key = ILLEGAL_REQUEST,
3204 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3206 [TCM_SECTOR_COUNT_TOO_MANY] = {
3207 .key = ILLEGAL_REQUEST,
3208 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3210 [TCM_UNKNOWN_MODE_PAGE] = {
3211 .key = ILLEGAL_REQUEST,
3212 .asc = 0x24, /* INVALID FIELD IN CDB */
3214 [TCM_CHECK_CONDITION_ABORT_CMD] = {
3215 .key = ABORTED_COMMAND,
3216 .asc = 0x29, /* BUS DEVICE RESET FUNCTION OCCURRED */
3219 [TCM_INCORRECT_AMOUNT_OF_DATA] = {
3220 .key = ABORTED_COMMAND,
3221 .asc = 0x0c, /* WRITE ERROR */
3222 .ascq = 0x0d, /* NOT ENOUGH UNSOLICITED DATA */
3224 [TCM_INVALID_CDB_FIELD] = {
3225 .key = ILLEGAL_REQUEST,
3226 .asc = 0x24, /* INVALID FIELD IN CDB */
3228 [TCM_INVALID_PARAMETER_LIST] = {
3229 .key = ILLEGAL_REQUEST,
3230 .asc = 0x26, /* INVALID FIELD IN PARAMETER LIST */
3232 [TCM_TOO_MANY_TARGET_DESCS] = {
3233 .key = ILLEGAL_REQUEST,
3235 .ascq = 0x06, /* TOO MANY TARGET DESCRIPTORS */
3237 [TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE] = {
3238 .key = ILLEGAL_REQUEST,
3240 .ascq = 0x07, /* UNSUPPORTED TARGET DESCRIPTOR TYPE CODE */
3242 [TCM_TOO_MANY_SEGMENT_DESCS] = {
3243 .key = ILLEGAL_REQUEST,
3245 .ascq = 0x08, /* TOO MANY SEGMENT DESCRIPTORS */
3247 [TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE] = {
3248 .key = ILLEGAL_REQUEST,
3250 .ascq = 0x09, /* UNSUPPORTED SEGMENT DESCRIPTOR TYPE CODE */
3252 [TCM_PARAMETER_LIST_LENGTH_ERROR] = {
3253 .key = ILLEGAL_REQUEST,
3254 .asc = 0x1a, /* PARAMETER LIST LENGTH ERROR */
3256 [TCM_UNEXPECTED_UNSOLICITED_DATA] = {
3257 .key = ILLEGAL_REQUEST,
3258 .asc = 0x0c, /* WRITE ERROR */
3259 .ascq = 0x0c, /* UNEXPECTED_UNSOLICITED_DATA */
3261 [TCM_SERVICE_CRC_ERROR] = {
3262 .key = ABORTED_COMMAND,
3263 .asc = 0x47, /* PROTOCOL SERVICE CRC ERROR */
3264 .ascq = 0x05, /* N/A */
3266 [TCM_SNACK_REJECTED] = {
3267 .key = ABORTED_COMMAND,
3268 .asc = 0x11, /* READ ERROR */
3269 .ascq = 0x13, /* FAILED RETRANSMISSION REQUEST */
3271 [TCM_WRITE_PROTECTED] = {
3272 .key = DATA_PROTECT,
3273 .asc = 0x27, /* WRITE PROTECTED */
3275 [TCM_ADDRESS_OUT_OF_RANGE] = {
3276 .key = ILLEGAL_REQUEST,
3277 .asc = 0x21, /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3279 [TCM_CHECK_CONDITION_UNIT_ATTENTION] = {
3280 .key = UNIT_ATTENTION,
3282 [TCM_CHECK_CONDITION_NOT_READY] = {
3285 [TCM_MISCOMPARE_VERIFY] = {
3287 .asc = 0x1d, /* MISCOMPARE DURING VERIFY OPERATION */
3289 .add_sense_info = true,
3291 [TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED] = {
3292 .key = ABORTED_COMMAND,
3294 .ascq = 0x01, /* LOGICAL BLOCK GUARD CHECK FAILED */
3295 .add_sense_info = true,
3297 [TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED] = {
3298 .key = ABORTED_COMMAND,
3300 .ascq = 0x02, /* LOGICAL BLOCK APPLICATION TAG CHECK FAILED */
3301 .add_sense_info = true,
3303 [TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED] = {
3304 .key = ABORTED_COMMAND,
3306 .ascq = 0x03, /* LOGICAL BLOCK REFERENCE TAG CHECK FAILED */
3307 .add_sense_info = true,
3309 [TCM_COPY_TARGET_DEVICE_NOT_REACHABLE] = {
3310 .key = COPY_ABORTED,
3312 .ascq = 0x02, /* COPY TARGET DEVICE NOT REACHABLE */
3315 [TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE] = {
3317 * Returning ILLEGAL REQUEST would cause immediate IO errors on
3318 * Solaris initiators. Returning NOT READY instead means the
3319 * operations will be retried a finite number of times and we
3320 * can survive intermittent errors.
3323 .asc = 0x08, /* LOGICAL UNIT COMMUNICATION FAILURE */
3325 [TCM_INSUFFICIENT_REGISTRATION_RESOURCES] = {
3327 * From spc4r22 section5.7.7,5.7.8
3328 * If a PERSISTENT RESERVE OUT command with a REGISTER service action
3329 * or a REGISTER AND IGNORE EXISTING KEY service action or
3330 * REGISTER AND MOVE service actionis attempted,
3331 * but there are insufficient device server resources to complete the
3332 * operation, then the command shall be terminated with CHECK CONDITION
3333 * status, with the sense key set to ILLEGAL REQUEST,and the additonal
3334 * sense code set to INSUFFICIENT REGISTRATION RESOURCES.
3336 .key = ILLEGAL_REQUEST,
3338 .ascq = 0x04, /* INSUFFICIENT REGISTRATION RESOURCES */
3340 [TCM_INVALID_FIELD_IN_COMMAND_IU] = {
3341 .key = ILLEGAL_REQUEST,
3343 .ascq = 0x03, /* INVALID FIELD IN COMMAND INFORMATION UNIT */
3348 * translate_sense_reason - translate a sense reason into T10 key, asc and ascq
3349 * @cmd: SCSI command in which the resulting sense buffer or SCSI status will
3351 * @reason: LIO sense reason code. If this argument has the value
3352 * TCM_CHECK_CONDITION_UNIT_ATTENTION, try to dequeue a unit attention. If
3353 * dequeuing a unit attention fails due to multiple commands being processed
3354 * concurrently, set the command status to BUSY.
3356 * Return: 0 upon success or -EINVAL if the sense buffer is too small.
3358 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason)
3360 const struct sense_detail *sd;
3361 u8 *buffer = cmd->sense_buffer;
3362 int r = (__force int)reason;
3364 bool desc_format = target_sense_desc_format(cmd->se_dev);
3366 if (r < ARRAY_SIZE(sense_detail_table) && sense_detail_table[r].key)
3367 sd = &sense_detail_table[r];
3369 sd = &sense_detail_table[(__force int)
3370 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE];
3373 if (reason == TCM_CHECK_CONDITION_UNIT_ATTENTION) {
3374 if (!core_scsi3_ua_for_check_condition(cmd, &key, &asc,
3376 cmd->scsi_status = SAM_STAT_BUSY;
3379 } else if (sd->asc == 0) {
3380 WARN_ON_ONCE(cmd->scsi_asc == 0);
3381 asc = cmd->scsi_asc;
3382 ascq = cmd->scsi_ascq;
3388 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
3389 cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3390 cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
3391 scsi_build_sense_buffer(desc_format, buffer, key, asc, ascq);
3392 if (sd->add_sense_info)
3393 WARN_ON_ONCE(scsi_set_sense_information(buffer,
3394 cmd->scsi_sense_length,
3395 cmd->sense_info) < 0);
3399 transport_send_check_condition_and_sense(struct se_cmd *cmd,
3400 sense_reason_t reason, int from_transport)
3402 unsigned long flags;
3404 WARN_ON_ONCE(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB);
3406 spin_lock_irqsave(&cmd->t_state_lock, flags);
3407 if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3408 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3411 cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
3412 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3414 if (!from_transport)
3415 translate_sense_reason(cmd, reason);
3417 trace_target_cmd_complete(cmd);
3418 return cmd->se_tfo->queue_status(cmd);
3420 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3423 * target_send_busy - Send SCSI BUSY status back to the initiator
3424 * @cmd: SCSI command for which to send a BUSY reply.
3426 * Note: Only call this function if target_submit_cmd*() failed.
3428 int target_send_busy(struct se_cmd *cmd)
3430 WARN_ON_ONCE(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB);
3432 cmd->scsi_status = SAM_STAT_BUSY;
3433 trace_target_cmd_complete(cmd);
3434 return cmd->se_tfo->queue_status(cmd);
3436 EXPORT_SYMBOL(target_send_busy);
3438 static void target_tmr_work(struct work_struct *work)
3440 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3441 struct se_device *dev = cmd->se_dev;
3442 struct se_tmr_req *tmr = cmd->se_tmr_req;
3445 if (cmd->transport_state & CMD_T_ABORTED)
3448 switch (tmr->function) {
3449 case TMR_ABORT_TASK:
3450 core_tmr_abort_task(dev, tmr, cmd->se_sess);
3452 case TMR_ABORT_TASK_SET:
3454 case TMR_CLEAR_TASK_SET:
3455 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3458 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3459 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3460 TMR_FUNCTION_REJECTED;
3461 if (tmr->response == TMR_FUNCTION_COMPLETE) {
3462 target_ua_allocate_lun(cmd->se_sess->se_node_acl,
3463 cmd->orig_fe_lun, 0x29,
3464 ASCQ_29H_BUS_DEVICE_RESET_FUNCTION_OCCURRED);
3467 case TMR_TARGET_WARM_RESET:
3468 tmr->response = TMR_FUNCTION_REJECTED;
3470 case TMR_TARGET_COLD_RESET:
3471 tmr->response = TMR_FUNCTION_REJECTED;
3474 pr_err("Unknown TMR function: 0x%02x.\n",
3476 tmr->response = TMR_FUNCTION_REJECTED;
3480 if (cmd->transport_state & CMD_T_ABORTED)
3483 cmd->se_tfo->queue_tm_rsp(cmd);
3485 transport_lun_remove_cmd(cmd);
3486 transport_cmd_check_stop_to_fabric(cmd);
3490 target_handle_abort(cmd);
3493 int transport_generic_handle_tmr(
3496 unsigned long flags;
3497 bool aborted = false;
3499 spin_lock_irqsave(&cmd->t_state_lock, flags);
3500 if (cmd->transport_state & CMD_T_ABORTED) {
3503 cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3504 cmd->transport_state |= CMD_T_ACTIVE;
3506 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3509 pr_warn_ratelimited("handle_tmr caught CMD_T_ABORTED TMR %d ref_tag: %llu tag: %llu\n",
3510 cmd->se_tmr_req->function,
3511 cmd->se_tmr_req->ref_task_tag, cmd->tag);
3512 target_handle_abort(cmd);
3516 INIT_WORK(&cmd->work, target_tmr_work);
3517 schedule_work(&cmd->work);
3520 EXPORT_SYMBOL(transport_generic_handle_tmr);
3523 target_check_wce(struct se_device *dev)
3527 if (dev->transport->get_write_cache)
3528 wce = dev->transport->get_write_cache(dev);
3529 else if (dev->dev_attrib.emulate_write_cache > 0)
3536 target_check_fua(struct se_device *dev)
3538 return target_check_wce(dev) && dev->dev_attrib.emulate_fua_write > 0;