Linux 4.19.133
[linux/fpc-iii.git] / drivers / target / target_core_transport.c
blobf1b730b77a3122b8aee26ae015b3087d9baae512
1 /*******************************************************************************
2 * Filename: target_core_transport.c
4 * This file contains the Generic Target Engine Core.
6 * (c) Copyright 2002-2013 Datera, Inc.
8 * Nicholas A. Bellinger <nab@kernel.org>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 ******************************************************************************/
26 #include <linux/net.h>
27 #include <linux/delay.h>
28 #include <linux/string.h>
29 #include <linux/timer.h>
30 #include <linux/slab.h>
31 #include <linux/spinlock.h>
32 #include <linux/kthread.h>
33 #include <linux/in.h>
34 #include <linux/cdrom.h>
35 #include <linux/module.h>
36 #include <linux/ratelimit.h>
37 #include <linux/vmalloc.h>
38 #include <asm/unaligned.h>
39 #include <net/sock.h>
40 #include <net/tcp.h>
41 #include <scsi/scsi_proto.h>
42 #include <scsi/scsi_common.h>
44 #include <target/target_core_base.h>
45 #include <target/target_core_backend.h>
46 #include <target/target_core_fabric.h>
48 #include "target_core_internal.h"
49 #include "target_core_alua.h"
50 #include "target_core_pr.h"
51 #include "target_core_ua.h"
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/target.h>
56 static struct workqueue_struct *target_completion_wq;
57 static struct kmem_cache *se_sess_cache;
58 struct kmem_cache *se_ua_cache;
59 struct kmem_cache *t10_pr_reg_cache;
60 struct kmem_cache *t10_alua_lu_gp_cache;
61 struct kmem_cache *t10_alua_lu_gp_mem_cache;
62 struct kmem_cache *t10_alua_tg_pt_gp_cache;
63 struct kmem_cache *t10_alua_lba_map_cache;
64 struct kmem_cache *t10_alua_lba_map_mem_cache;
66 static void transport_complete_task_attr(struct se_cmd *cmd);
67 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason);
68 static void transport_handle_queue_full(struct se_cmd *cmd,
69 struct se_device *dev, int err, bool write_pending);
70 static void target_complete_ok_work(struct work_struct *work);
72 int init_se_kmem_caches(void)
74 se_sess_cache = kmem_cache_create("se_sess_cache",
75 sizeof(struct se_session), __alignof__(struct se_session),
76 0, NULL);
77 if (!se_sess_cache) {
78 pr_err("kmem_cache_create() for struct se_session"
79 " failed\n");
80 goto out;
82 se_ua_cache = kmem_cache_create("se_ua_cache",
83 sizeof(struct se_ua), __alignof__(struct se_ua),
84 0, NULL);
85 if (!se_ua_cache) {
86 pr_err("kmem_cache_create() for struct se_ua failed\n");
87 goto out_free_sess_cache;
89 t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
90 sizeof(struct t10_pr_registration),
91 __alignof__(struct t10_pr_registration), 0, NULL);
92 if (!t10_pr_reg_cache) {
93 pr_err("kmem_cache_create() for struct t10_pr_registration"
94 " failed\n");
95 goto out_free_ua_cache;
97 t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
98 sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
99 0, NULL);
100 if (!t10_alua_lu_gp_cache) {
101 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
102 " failed\n");
103 goto out_free_pr_reg_cache;
105 t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
106 sizeof(struct t10_alua_lu_gp_member),
107 __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
108 if (!t10_alua_lu_gp_mem_cache) {
109 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
110 "cache failed\n");
111 goto out_free_lu_gp_cache;
113 t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
114 sizeof(struct t10_alua_tg_pt_gp),
115 __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
116 if (!t10_alua_tg_pt_gp_cache) {
117 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
118 "cache failed\n");
119 goto out_free_lu_gp_mem_cache;
121 t10_alua_lba_map_cache = kmem_cache_create(
122 "t10_alua_lba_map_cache",
123 sizeof(struct t10_alua_lba_map),
124 __alignof__(struct t10_alua_lba_map), 0, NULL);
125 if (!t10_alua_lba_map_cache) {
126 pr_err("kmem_cache_create() for t10_alua_lba_map_"
127 "cache failed\n");
128 goto out_free_tg_pt_gp_cache;
130 t10_alua_lba_map_mem_cache = kmem_cache_create(
131 "t10_alua_lba_map_mem_cache",
132 sizeof(struct t10_alua_lba_map_member),
133 __alignof__(struct t10_alua_lba_map_member), 0, NULL);
134 if (!t10_alua_lba_map_mem_cache) {
135 pr_err("kmem_cache_create() for t10_alua_lba_map_mem_"
136 "cache failed\n");
137 goto out_free_lba_map_cache;
140 target_completion_wq = alloc_workqueue("target_completion",
141 WQ_MEM_RECLAIM, 0);
142 if (!target_completion_wq)
143 goto out_free_lba_map_mem_cache;
145 return 0;
147 out_free_lba_map_mem_cache:
148 kmem_cache_destroy(t10_alua_lba_map_mem_cache);
149 out_free_lba_map_cache:
150 kmem_cache_destroy(t10_alua_lba_map_cache);
151 out_free_tg_pt_gp_cache:
152 kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
153 out_free_lu_gp_mem_cache:
154 kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
155 out_free_lu_gp_cache:
156 kmem_cache_destroy(t10_alua_lu_gp_cache);
157 out_free_pr_reg_cache:
158 kmem_cache_destroy(t10_pr_reg_cache);
159 out_free_ua_cache:
160 kmem_cache_destroy(se_ua_cache);
161 out_free_sess_cache:
162 kmem_cache_destroy(se_sess_cache);
163 out:
164 return -ENOMEM;
167 void release_se_kmem_caches(void)
169 destroy_workqueue(target_completion_wq);
170 kmem_cache_destroy(se_sess_cache);
171 kmem_cache_destroy(se_ua_cache);
172 kmem_cache_destroy(t10_pr_reg_cache);
173 kmem_cache_destroy(t10_alua_lu_gp_cache);
174 kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
175 kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
176 kmem_cache_destroy(t10_alua_lba_map_cache);
177 kmem_cache_destroy(t10_alua_lba_map_mem_cache);
180 /* This code ensures unique mib indexes are handed out. */
181 static DEFINE_SPINLOCK(scsi_mib_index_lock);
182 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
185 * Allocate a new row index for the entry type specified
187 u32 scsi_get_new_index(scsi_index_t type)
189 u32 new_index;
191 BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
193 spin_lock(&scsi_mib_index_lock);
194 new_index = ++scsi_mib_index[type];
195 spin_unlock(&scsi_mib_index_lock);
197 return new_index;
200 void transport_subsystem_check_init(void)
202 int ret;
203 static int sub_api_initialized;
205 if (sub_api_initialized)
206 return;
208 ret = request_module("target_core_iblock");
209 if (ret != 0)
210 pr_err("Unable to load target_core_iblock\n");
212 ret = request_module("target_core_file");
213 if (ret != 0)
214 pr_err("Unable to load target_core_file\n");
216 ret = request_module("target_core_pscsi");
217 if (ret != 0)
218 pr_err("Unable to load target_core_pscsi\n");
220 ret = request_module("target_core_user");
221 if (ret != 0)
222 pr_err("Unable to load target_core_user\n");
224 sub_api_initialized = 1;
227 static void target_release_sess_cmd_refcnt(struct percpu_ref *ref)
229 struct se_session *sess = container_of(ref, typeof(*sess), cmd_count);
231 wake_up(&sess->cmd_list_wq);
235 * transport_init_session - initialize a session object
236 * @se_sess: Session object pointer.
238 * The caller must have zero-initialized @se_sess before calling this function.
240 int transport_init_session(struct se_session *se_sess)
242 INIT_LIST_HEAD(&se_sess->sess_list);
243 INIT_LIST_HEAD(&se_sess->sess_acl_list);
244 INIT_LIST_HEAD(&se_sess->sess_cmd_list);
245 spin_lock_init(&se_sess->sess_cmd_lock);
246 init_waitqueue_head(&se_sess->cmd_list_wq);
247 return percpu_ref_init(&se_sess->cmd_count,
248 target_release_sess_cmd_refcnt, 0, GFP_KERNEL);
250 EXPORT_SYMBOL(transport_init_session);
253 * transport_alloc_session - allocate a session object and initialize it
254 * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
256 struct se_session *transport_alloc_session(enum target_prot_op sup_prot_ops)
258 struct se_session *se_sess;
259 int ret;
261 se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
262 if (!se_sess) {
263 pr_err("Unable to allocate struct se_session from"
264 " se_sess_cache\n");
265 return ERR_PTR(-ENOMEM);
267 ret = transport_init_session(se_sess);
268 if (ret < 0) {
269 kmem_cache_free(se_sess_cache, se_sess);
270 return ERR_PTR(ret);
272 se_sess->sup_prot_ops = sup_prot_ops;
274 return se_sess;
276 EXPORT_SYMBOL(transport_alloc_session);
279 * transport_alloc_session_tags - allocate target driver private data
280 * @se_sess: Session pointer.
281 * @tag_num: Maximum number of in-flight commands between initiator and target.
282 * @tag_size: Size in bytes of the private data a target driver associates with
283 * each command.
285 int transport_alloc_session_tags(struct se_session *se_sess,
286 unsigned int tag_num, unsigned int tag_size)
288 int rc;
290 se_sess->sess_cmd_map = kcalloc(tag_size, tag_num,
291 GFP_KERNEL | __GFP_NOWARN | __GFP_RETRY_MAYFAIL);
292 if (!se_sess->sess_cmd_map) {
293 se_sess->sess_cmd_map = vzalloc(array_size(tag_size, tag_num));
294 if (!se_sess->sess_cmd_map) {
295 pr_err("Unable to allocate se_sess->sess_cmd_map\n");
296 return -ENOMEM;
300 rc = sbitmap_queue_init_node(&se_sess->sess_tag_pool, tag_num, -1,
301 false, GFP_KERNEL, NUMA_NO_NODE);
302 if (rc < 0) {
303 pr_err("Unable to init se_sess->sess_tag_pool,"
304 " tag_num: %u\n", tag_num);
305 kvfree(se_sess->sess_cmd_map);
306 se_sess->sess_cmd_map = NULL;
307 return -ENOMEM;
310 return 0;
312 EXPORT_SYMBOL(transport_alloc_session_tags);
315 * transport_init_session_tags - allocate a session and target driver private data
316 * @tag_num: Maximum number of in-flight commands between initiator and target.
317 * @tag_size: Size in bytes of the private data a target driver associates with
318 * each command.
319 * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
321 static struct se_session *
322 transport_init_session_tags(unsigned int tag_num, unsigned int tag_size,
323 enum target_prot_op sup_prot_ops)
325 struct se_session *se_sess;
326 int rc;
328 if (tag_num != 0 && !tag_size) {
329 pr_err("init_session_tags called with percpu-ida tag_num:"
330 " %u, but zero tag_size\n", tag_num);
331 return ERR_PTR(-EINVAL);
333 if (!tag_num && tag_size) {
334 pr_err("init_session_tags called with percpu-ida tag_size:"
335 " %u, but zero tag_num\n", tag_size);
336 return ERR_PTR(-EINVAL);
339 se_sess = transport_alloc_session(sup_prot_ops);
340 if (IS_ERR(se_sess))
341 return se_sess;
343 rc = transport_alloc_session_tags(se_sess, tag_num, tag_size);
344 if (rc < 0) {
345 transport_free_session(se_sess);
346 return ERR_PTR(-ENOMEM);
349 return se_sess;
353 * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
355 void __transport_register_session(
356 struct se_portal_group *se_tpg,
357 struct se_node_acl *se_nacl,
358 struct se_session *se_sess,
359 void *fabric_sess_ptr)
361 const struct target_core_fabric_ops *tfo = se_tpg->se_tpg_tfo;
362 unsigned char buf[PR_REG_ISID_LEN];
363 unsigned long flags;
365 se_sess->se_tpg = se_tpg;
366 se_sess->fabric_sess_ptr = fabric_sess_ptr;
368 * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
370 * Only set for struct se_session's that will actually be moving I/O.
371 * eg: *NOT* discovery sessions.
373 if (se_nacl) {
376 * Determine if fabric allows for T10-PI feature bits exposed to
377 * initiators for device backends with !dev->dev_attrib.pi_prot_type.
379 * If so, then always save prot_type on a per se_node_acl node
380 * basis and re-instate the previous sess_prot_type to avoid
381 * disabling PI from below any previously initiator side
382 * registered LUNs.
384 if (se_nacl->saved_prot_type)
385 se_sess->sess_prot_type = se_nacl->saved_prot_type;
386 else if (tfo->tpg_check_prot_fabric_only)
387 se_sess->sess_prot_type = se_nacl->saved_prot_type =
388 tfo->tpg_check_prot_fabric_only(se_tpg);
390 * If the fabric module supports an ISID based TransportID,
391 * save this value in binary from the fabric I_T Nexus now.
393 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
394 memset(&buf[0], 0, PR_REG_ISID_LEN);
395 se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
396 &buf[0], PR_REG_ISID_LEN);
397 se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
400 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
402 * The se_nacl->nacl_sess pointer will be set to the
403 * last active I_T Nexus for each struct se_node_acl.
405 se_nacl->nacl_sess = se_sess;
407 list_add_tail(&se_sess->sess_acl_list,
408 &se_nacl->acl_sess_list);
409 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
411 list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
413 pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
414 se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
416 EXPORT_SYMBOL(__transport_register_session);
418 void transport_register_session(
419 struct se_portal_group *se_tpg,
420 struct se_node_acl *se_nacl,
421 struct se_session *se_sess,
422 void *fabric_sess_ptr)
424 unsigned long flags;
426 spin_lock_irqsave(&se_tpg->session_lock, flags);
427 __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
428 spin_unlock_irqrestore(&se_tpg->session_lock, flags);
430 EXPORT_SYMBOL(transport_register_session);
432 struct se_session *
433 target_setup_session(struct se_portal_group *tpg,
434 unsigned int tag_num, unsigned int tag_size,
435 enum target_prot_op prot_op,
436 const char *initiatorname, void *private,
437 int (*callback)(struct se_portal_group *,
438 struct se_session *, void *))
440 struct se_session *sess;
443 * If the fabric driver is using percpu-ida based pre allocation
444 * of I/O descriptor tags, go ahead and perform that setup now..
446 if (tag_num != 0)
447 sess = transport_init_session_tags(tag_num, tag_size, prot_op);
448 else
449 sess = transport_alloc_session(prot_op);
451 if (IS_ERR(sess))
452 return sess;
454 sess->se_node_acl = core_tpg_check_initiator_node_acl(tpg,
455 (unsigned char *)initiatorname);
456 if (!sess->se_node_acl) {
457 transport_free_session(sess);
458 return ERR_PTR(-EACCES);
461 * Go ahead and perform any remaining fabric setup that is
462 * required before transport_register_session().
464 if (callback != NULL) {
465 int rc = callback(tpg, sess, private);
466 if (rc) {
467 transport_free_session(sess);
468 return ERR_PTR(rc);
472 transport_register_session(tpg, sess->se_node_acl, sess, private);
473 return sess;
475 EXPORT_SYMBOL(target_setup_session);
477 ssize_t target_show_dynamic_sessions(struct se_portal_group *se_tpg, char *page)
479 struct se_session *se_sess;
480 ssize_t len = 0;
482 spin_lock_bh(&se_tpg->session_lock);
483 list_for_each_entry(se_sess, &se_tpg->tpg_sess_list, sess_list) {
484 if (!se_sess->se_node_acl)
485 continue;
486 if (!se_sess->se_node_acl->dynamic_node_acl)
487 continue;
488 if (strlen(se_sess->se_node_acl->initiatorname) + 1 + len > PAGE_SIZE)
489 break;
491 len += snprintf(page + len, PAGE_SIZE - len, "%s\n",
492 se_sess->se_node_acl->initiatorname);
493 len += 1; /* Include NULL terminator */
495 spin_unlock_bh(&se_tpg->session_lock);
497 return len;
499 EXPORT_SYMBOL(target_show_dynamic_sessions);
501 static void target_complete_nacl(struct kref *kref)
503 struct se_node_acl *nacl = container_of(kref,
504 struct se_node_acl, acl_kref);
505 struct se_portal_group *se_tpg = nacl->se_tpg;
507 if (!nacl->dynamic_stop) {
508 complete(&nacl->acl_free_comp);
509 return;
512 mutex_lock(&se_tpg->acl_node_mutex);
513 list_del_init(&nacl->acl_list);
514 mutex_unlock(&se_tpg->acl_node_mutex);
516 core_tpg_wait_for_nacl_pr_ref(nacl);
517 core_free_device_list_for_node(nacl, se_tpg);
518 kfree(nacl);
521 void target_put_nacl(struct se_node_acl *nacl)
523 kref_put(&nacl->acl_kref, target_complete_nacl);
525 EXPORT_SYMBOL(target_put_nacl);
527 void transport_deregister_session_configfs(struct se_session *se_sess)
529 struct se_node_acl *se_nacl;
530 unsigned long flags;
532 * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
534 se_nacl = se_sess->se_node_acl;
535 if (se_nacl) {
536 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
537 if (!list_empty(&se_sess->sess_acl_list))
538 list_del_init(&se_sess->sess_acl_list);
540 * If the session list is empty, then clear the pointer.
541 * Otherwise, set the struct se_session pointer from the tail
542 * element of the per struct se_node_acl active session list.
544 if (list_empty(&se_nacl->acl_sess_list))
545 se_nacl->nacl_sess = NULL;
546 else {
547 se_nacl->nacl_sess = container_of(
548 se_nacl->acl_sess_list.prev,
549 struct se_session, sess_acl_list);
551 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
554 EXPORT_SYMBOL(transport_deregister_session_configfs);
556 void transport_free_session(struct se_session *se_sess)
558 struct se_node_acl *se_nacl = se_sess->se_node_acl;
561 * Drop the se_node_acl->nacl_kref obtained from within
562 * core_tpg_get_initiator_node_acl().
564 if (se_nacl) {
565 struct se_portal_group *se_tpg = se_nacl->se_tpg;
566 const struct target_core_fabric_ops *se_tfo = se_tpg->se_tpg_tfo;
567 unsigned long flags;
569 se_sess->se_node_acl = NULL;
572 * Also determine if we need to drop the extra ->cmd_kref if
573 * it had been previously dynamically generated, and
574 * the endpoint is not caching dynamic ACLs.
576 mutex_lock(&se_tpg->acl_node_mutex);
577 if (se_nacl->dynamic_node_acl &&
578 !se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
579 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
580 if (list_empty(&se_nacl->acl_sess_list))
581 se_nacl->dynamic_stop = true;
582 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
584 if (se_nacl->dynamic_stop)
585 list_del_init(&se_nacl->acl_list);
587 mutex_unlock(&se_tpg->acl_node_mutex);
589 if (se_nacl->dynamic_stop)
590 target_put_nacl(se_nacl);
592 target_put_nacl(se_nacl);
594 if (se_sess->sess_cmd_map) {
595 sbitmap_queue_free(&se_sess->sess_tag_pool);
596 kvfree(se_sess->sess_cmd_map);
598 percpu_ref_exit(&se_sess->cmd_count);
599 kmem_cache_free(se_sess_cache, se_sess);
601 EXPORT_SYMBOL(transport_free_session);
603 void transport_deregister_session(struct se_session *se_sess)
605 struct se_portal_group *se_tpg = se_sess->se_tpg;
606 unsigned long flags;
608 if (!se_tpg) {
609 transport_free_session(se_sess);
610 return;
613 spin_lock_irqsave(&se_tpg->session_lock, flags);
614 list_del(&se_sess->sess_list);
615 se_sess->se_tpg = NULL;
616 se_sess->fabric_sess_ptr = NULL;
617 spin_unlock_irqrestore(&se_tpg->session_lock, flags);
619 pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
620 se_tpg->se_tpg_tfo->get_fabric_name());
622 * If last kref is dropping now for an explicit NodeACL, awake sleeping
623 * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
624 * removal context from within transport_free_session() code.
626 * For dynamic ACL, target_put_nacl() uses target_complete_nacl()
627 * to release all remaining generate_node_acl=1 created ACL resources.
630 transport_free_session(se_sess);
632 EXPORT_SYMBOL(transport_deregister_session);
634 void target_remove_session(struct se_session *se_sess)
636 transport_deregister_session_configfs(se_sess);
637 transport_deregister_session(se_sess);
639 EXPORT_SYMBOL(target_remove_session);
641 static void target_remove_from_state_list(struct se_cmd *cmd)
643 struct se_device *dev = cmd->se_dev;
644 unsigned long flags;
646 if (!dev)
647 return;
649 spin_lock_irqsave(&dev->execute_task_lock, flags);
650 if (cmd->state_active) {
651 list_del(&cmd->state_list);
652 cmd->state_active = false;
654 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
658 * This function is called by the target core after the target core has
659 * finished processing a SCSI command or SCSI TMF. Both the regular command
660 * processing code and the code for aborting commands can call this
661 * function. CMD_T_STOP is set if and only if another thread is waiting
662 * inside transport_wait_for_tasks() for t_transport_stop_comp.
664 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
666 unsigned long flags;
668 target_remove_from_state_list(cmd);
671 * Clear struct se_cmd->se_lun before the handoff to FE.
673 cmd->se_lun = NULL;
675 spin_lock_irqsave(&cmd->t_state_lock, flags);
677 * Determine if frontend context caller is requesting the stopping of
678 * this command for frontend exceptions.
680 if (cmd->transport_state & CMD_T_STOP) {
681 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
682 __func__, __LINE__, cmd->tag);
684 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
686 complete_all(&cmd->t_transport_stop_comp);
687 return 1;
689 cmd->transport_state &= ~CMD_T_ACTIVE;
690 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
693 * Some fabric modules like tcm_loop can release their internally
694 * allocated I/O reference and struct se_cmd now.
696 * Fabric modules are expected to return '1' here if the se_cmd being
697 * passed is released at this point, or zero if not being released.
699 return cmd->se_tfo->check_stop_free(cmd);
702 static void transport_lun_remove_cmd(struct se_cmd *cmd)
704 struct se_lun *lun = cmd->se_lun;
706 if (!lun)
707 return;
709 if (cmpxchg(&cmd->lun_ref_active, true, false))
710 percpu_ref_put(&lun->lun_ref);
713 int transport_cmd_finish_abort(struct se_cmd *cmd)
715 bool send_tas = cmd->transport_state & CMD_T_TAS;
716 bool ack_kref = (cmd->se_cmd_flags & SCF_ACK_KREF);
717 int ret = 0;
719 if (send_tas)
720 transport_send_task_abort(cmd);
722 if (cmd->se_cmd_flags & SCF_SE_LUN_CMD)
723 transport_lun_remove_cmd(cmd);
725 * Allow the fabric driver to unmap any resources before
726 * releasing the descriptor via TFO->release_cmd()
728 if (!send_tas)
729 cmd->se_tfo->aborted_task(cmd);
731 if (transport_cmd_check_stop_to_fabric(cmd))
732 return 1;
733 if (!send_tas && ack_kref)
734 ret = target_put_sess_cmd(cmd);
736 return ret;
739 static void target_complete_failure_work(struct work_struct *work)
741 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
743 transport_generic_request_failure(cmd,
744 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
748 * Used when asking transport to copy Sense Data from the underlying
749 * Linux/SCSI struct scsi_cmnd
751 static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd)
753 struct se_device *dev = cmd->se_dev;
755 WARN_ON(!cmd->se_lun);
757 if (!dev)
758 return NULL;
760 if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION)
761 return NULL;
763 cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
765 pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n",
766 dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
767 return cmd->sense_buffer;
770 void transport_copy_sense_to_cmd(struct se_cmd *cmd, unsigned char *sense)
772 unsigned char *cmd_sense_buf;
773 unsigned long flags;
775 spin_lock_irqsave(&cmd->t_state_lock, flags);
776 cmd_sense_buf = transport_get_sense_buffer(cmd);
777 if (!cmd_sense_buf) {
778 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
779 return;
782 cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
783 memcpy(cmd_sense_buf, sense, cmd->scsi_sense_length);
784 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
786 EXPORT_SYMBOL(transport_copy_sense_to_cmd);
788 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
790 struct se_device *dev = cmd->se_dev;
791 int success;
792 unsigned long flags;
794 cmd->scsi_status = scsi_status;
796 spin_lock_irqsave(&cmd->t_state_lock, flags);
797 switch (cmd->scsi_status) {
798 case SAM_STAT_CHECK_CONDITION:
799 if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
800 success = 1;
801 else
802 success = 0;
803 break;
804 default:
805 success = 1;
806 break;
810 * Check for case where an explicit ABORT_TASK has been received
811 * and transport_wait_for_tasks() will be waiting for completion..
813 if (cmd->transport_state & CMD_T_ABORTED ||
814 cmd->transport_state & CMD_T_STOP) {
815 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
817 * If COMPARE_AND_WRITE was stopped by __transport_wait_for_tasks(),
818 * release se_device->caw_sem obtained by sbc_compare_and_write()
819 * since target_complete_ok_work() or target_complete_failure_work()
820 * won't be called to invoke the normal CAW completion callbacks.
822 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
823 up(&dev->caw_sem);
825 complete_all(&cmd->t_transport_stop_comp);
826 return;
827 } else if (!success) {
828 INIT_WORK(&cmd->work, target_complete_failure_work);
829 } else {
830 INIT_WORK(&cmd->work, target_complete_ok_work);
833 cmd->t_state = TRANSPORT_COMPLETE;
834 cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
835 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
837 if (cmd->se_cmd_flags & SCF_USE_CPUID)
838 queue_work_on(cmd->cpuid, target_completion_wq, &cmd->work);
839 else
840 queue_work(target_completion_wq, &cmd->work);
842 EXPORT_SYMBOL(target_complete_cmd);
844 void target_complete_cmd_with_length(struct se_cmd *cmd, u8 scsi_status, int length)
846 if ((scsi_status == SAM_STAT_GOOD ||
847 cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
848 length < cmd->data_length) {
849 if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
850 cmd->residual_count += cmd->data_length - length;
851 } else {
852 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
853 cmd->residual_count = cmd->data_length - length;
856 cmd->data_length = length;
859 target_complete_cmd(cmd, scsi_status);
861 EXPORT_SYMBOL(target_complete_cmd_with_length);
863 static void target_add_to_state_list(struct se_cmd *cmd)
865 struct se_device *dev = cmd->se_dev;
866 unsigned long flags;
868 spin_lock_irqsave(&dev->execute_task_lock, flags);
869 if (!cmd->state_active) {
870 list_add_tail(&cmd->state_list, &dev->state_list);
871 cmd->state_active = true;
873 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
877 * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
879 static void transport_write_pending_qf(struct se_cmd *cmd);
880 static void transport_complete_qf(struct se_cmd *cmd);
882 void target_qf_do_work(struct work_struct *work)
884 struct se_device *dev = container_of(work, struct se_device,
885 qf_work_queue);
886 LIST_HEAD(qf_cmd_list);
887 struct se_cmd *cmd, *cmd_tmp;
889 spin_lock_irq(&dev->qf_cmd_lock);
890 list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
891 spin_unlock_irq(&dev->qf_cmd_lock);
893 list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
894 list_del(&cmd->se_qf_node);
895 atomic_dec_mb(&dev->dev_qf_count);
897 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
898 " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
899 (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
900 (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
901 : "UNKNOWN");
903 if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
904 transport_write_pending_qf(cmd);
905 else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK ||
906 cmd->t_state == TRANSPORT_COMPLETE_QF_ERR)
907 transport_complete_qf(cmd);
911 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
913 switch (cmd->data_direction) {
914 case DMA_NONE:
915 return "NONE";
916 case DMA_FROM_DEVICE:
917 return "READ";
918 case DMA_TO_DEVICE:
919 return "WRITE";
920 case DMA_BIDIRECTIONAL:
921 return "BIDI";
922 default:
923 break;
926 return "UNKNOWN";
929 void transport_dump_dev_state(
930 struct se_device *dev,
931 char *b,
932 int *bl)
934 *bl += sprintf(b + *bl, "Status: ");
935 if (dev->export_count)
936 *bl += sprintf(b + *bl, "ACTIVATED");
937 else
938 *bl += sprintf(b + *bl, "DEACTIVATED");
940 *bl += sprintf(b + *bl, " Max Queue Depth: %d", dev->queue_depth);
941 *bl += sprintf(b + *bl, " SectorSize: %u HwMaxSectors: %u\n",
942 dev->dev_attrib.block_size,
943 dev->dev_attrib.hw_max_sectors);
944 *bl += sprintf(b + *bl, " ");
947 void transport_dump_vpd_proto_id(
948 struct t10_vpd *vpd,
949 unsigned char *p_buf,
950 int p_buf_len)
952 unsigned char buf[VPD_TMP_BUF_SIZE];
953 int len;
955 memset(buf, 0, VPD_TMP_BUF_SIZE);
956 len = sprintf(buf, "T10 VPD Protocol Identifier: ");
958 switch (vpd->protocol_identifier) {
959 case 0x00:
960 sprintf(buf+len, "Fibre Channel\n");
961 break;
962 case 0x10:
963 sprintf(buf+len, "Parallel SCSI\n");
964 break;
965 case 0x20:
966 sprintf(buf+len, "SSA\n");
967 break;
968 case 0x30:
969 sprintf(buf+len, "IEEE 1394\n");
970 break;
971 case 0x40:
972 sprintf(buf+len, "SCSI Remote Direct Memory Access"
973 " Protocol\n");
974 break;
975 case 0x50:
976 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
977 break;
978 case 0x60:
979 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
980 break;
981 case 0x70:
982 sprintf(buf+len, "Automation/Drive Interface Transport"
983 " Protocol\n");
984 break;
985 case 0x80:
986 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
987 break;
988 default:
989 sprintf(buf+len, "Unknown 0x%02x\n",
990 vpd->protocol_identifier);
991 break;
994 if (p_buf)
995 strncpy(p_buf, buf, p_buf_len);
996 else
997 pr_debug("%s", buf);
1000 void
1001 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1004 * Check if the Protocol Identifier Valid (PIV) bit is set..
1006 * from spc3r23.pdf section 7.5.1
1008 if (page_83[1] & 0x80) {
1009 vpd->protocol_identifier = (page_83[0] & 0xf0);
1010 vpd->protocol_identifier_set = 1;
1011 transport_dump_vpd_proto_id(vpd, NULL, 0);
1014 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1016 int transport_dump_vpd_assoc(
1017 struct t10_vpd *vpd,
1018 unsigned char *p_buf,
1019 int p_buf_len)
1021 unsigned char buf[VPD_TMP_BUF_SIZE];
1022 int ret = 0;
1023 int len;
1025 memset(buf, 0, VPD_TMP_BUF_SIZE);
1026 len = sprintf(buf, "T10 VPD Identifier Association: ");
1028 switch (vpd->association) {
1029 case 0x00:
1030 sprintf(buf+len, "addressed logical unit\n");
1031 break;
1032 case 0x10:
1033 sprintf(buf+len, "target port\n");
1034 break;
1035 case 0x20:
1036 sprintf(buf+len, "SCSI target device\n");
1037 break;
1038 default:
1039 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1040 ret = -EINVAL;
1041 break;
1044 if (p_buf)
1045 strncpy(p_buf, buf, p_buf_len);
1046 else
1047 pr_debug("%s", buf);
1049 return ret;
1052 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1055 * The VPD identification association..
1057 * from spc3r23.pdf Section 7.6.3.1 Table 297
1059 vpd->association = (page_83[1] & 0x30);
1060 return transport_dump_vpd_assoc(vpd, NULL, 0);
1062 EXPORT_SYMBOL(transport_set_vpd_assoc);
1064 int transport_dump_vpd_ident_type(
1065 struct t10_vpd *vpd,
1066 unsigned char *p_buf,
1067 int p_buf_len)
1069 unsigned char buf[VPD_TMP_BUF_SIZE];
1070 int ret = 0;
1071 int len;
1073 memset(buf, 0, VPD_TMP_BUF_SIZE);
1074 len = sprintf(buf, "T10 VPD Identifier Type: ");
1076 switch (vpd->device_identifier_type) {
1077 case 0x00:
1078 sprintf(buf+len, "Vendor specific\n");
1079 break;
1080 case 0x01:
1081 sprintf(buf+len, "T10 Vendor ID based\n");
1082 break;
1083 case 0x02:
1084 sprintf(buf+len, "EUI-64 based\n");
1085 break;
1086 case 0x03:
1087 sprintf(buf+len, "NAA\n");
1088 break;
1089 case 0x04:
1090 sprintf(buf+len, "Relative target port identifier\n");
1091 break;
1092 case 0x08:
1093 sprintf(buf+len, "SCSI name string\n");
1094 break;
1095 default:
1096 sprintf(buf+len, "Unsupported: 0x%02x\n",
1097 vpd->device_identifier_type);
1098 ret = -EINVAL;
1099 break;
1102 if (p_buf) {
1103 if (p_buf_len < strlen(buf)+1)
1104 return -EINVAL;
1105 strncpy(p_buf, buf, p_buf_len);
1106 } else {
1107 pr_debug("%s", buf);
1110 return ret;
1113 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1116 * The VPD identifier type..
1118 * from spc3r23.pdf Section 7.6.3.1 Table 298
1120 vpd->device_identifier_type = (page_83[1] & 0x0f);
1121 return transport_dump_vpd_ident_type(vpd, NULL, 0);
1123 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1125 int transport_dump_vpd_ident(
1126 struct t10_vpd *vpd,
1127 unsigned char *p_buf,
1128 int p_buf_len)
1130 unsigned char buf[VPD_TMP_BUF_SIZE];
1131 int ret = 0;
1133 memset(buf, 0, VPD_TMP_BUF_SIZE);
1135 switch (vpd->device_identifier_code_set) {
1136 case 0x01: /* Binary */
1137 snprintf(buf, sizeof(buf),
1138 "T10 VPD Binary Device Identifier: %s\n",
1139 &vpd->device_identifier[0]);
1140 break;
1141 case 0x02: /* ASCII */
1142 snprintf(buf, sizeof(buf),
1143 "T10 VPD ASCII Device Identifier: %s\n",
1144 &vpd->device_identifier[0]);
1145 break;
1146 case 0x03: /* UTF-8 */
1147 snprintf(buf, sizeof(buf),
1148 "T10 VPD UTF-8 Device Identifier: %s\n",
1149 &vpd->device_identifier[0]);
1150 break;
1151 default:
1152 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1153 " 0x%02x", vpd->device_identifier_code_set);
1154 ret = -EINVAL;
1155 break;
1158 if (p_buf)
1159 strncpy(p_buf, buf, p_buf_len);
1160 else
1161 pr_debug("%s", buf);
1163 return ret;
1167 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1169 static const char hex_str[] = "0123456789abcdef";
1170 int j = 0, i = 4; /* offset to start of the identifier */
1173 * The VPD Code Set (encoding)
1175 * from spc3r23.pdf Section 7.6.3.1 Table 296
1177 vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1178 switch (vpd->device_identifier_code_set) {
1179 case 0x01: /* Binary */
1180 vpd->device_identifier[j++] =
1181 hex_str[vpd->device_identifier_type];
1182 while (i < (4 + page_83[3])) {
1183 vpd->device_identifier[j++] =
1184 hex_str[(page_83[i] & 0xf0) >> 4];
1185 vpd->device_identifier[j++] =
1186 hex_str[page_83[i] & 0x0f];
1187 i++;
1189 break;
1190 case 0x02: /* ASCII */
1191 case 0x03: /* UTF-8 */
1192 while (i < (4 + page_83[3]))
1193 vpd->device_identifier[j++] = page_83[i++];
1194 break;
1195 default:
1196 break;
1199 return transport_dump_vpd_ident(vpd, NULL, 0);
1201 EXPORT_SYMBOL(transport_set_vpd_ident);
1203 static sense_reason_t
1204 target_check_max_data_sg_nents(struct se_cmd *cmd, struct se_device *dev,
1205 unsigned int size)
1207 u32 mtl;
1209 if (!cmd->se_tfo->max_data_sg_nents)
1210 return TCM_NO_SENSE;
1212 * Check if fabric enforced maximum SGL entries per I/O descriptor
1213 * exceeds se_cmd->data_length. If true, set SCF_UNDERFLOW_BIT +
1214 * residual_count and reduce original cmd->data_length to maximum
1215 * length based on single PAGE_SIZE entry scatter-lists.
1217 mtl = (cmd->se_tfo->max_data_sg_nents * PAGE_SIZE);
1218 if (cmd->data_length > mtl) {
1220 * If an existing CDB overflow is present, calculate new residual
1221 * based on CDB size minus fabric maximum transfer length.
1223 * If an existing CDB underflow is present, calculate new residual
1224 * based on original cmd->data_length minus fabric maximum transfer
1225 * length.
1227 * Otherwise, set the underflow residual based on cmd->data_length
1228 * minus fabric maximum transfer length.
1230 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1231 cmd->residual_count = (size - mtl);
1232 } else if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
1233 u32 orig_dl = size + cmd->residual_count;
1234 cmd->residual_count = (orig_dl - mtl);
1235 } else {
1236 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1237 cmd->residual_count = (cmd->data_length - mtl);
1239 cmd->data_length = mtl;
1241 * Reset sbc_check_prot() calculated protection payload
1242 * length based upon the new smaller MTL.
1244 if (cmd->prot_length) {
1245 u32 sectors = (mtl / dev->dev_attrib.block_size);
1246 cmd->prot_length = dev->prot_length * sectors;
1249 return TCM_NO_SENSE;
1252 sense_reason_t
1253 target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1255 struct se_device *dev = cmd->se_dev;
1257 if (cmd->unknown_data_length) {
1258 cmd->data_length = size;
1259 } else if (size != cmd->data_length) {
1260 pr_warn_ratelimited("TARGET_CORE[%s]: Expected Transfer Length:"
1261 " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1262 " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
1263 cmd->data_length, size, cmd->t_task_cdb[0]);
1265 if (cmd->data_direction == DMA_TO_DEVICE) {
1266 if (cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) {
1267 pr_err_ratelimited("Rejecting underflow/overflow"
1268 " for WRITE data CDB\n");
1269 return TCM_INVALID_CDB_FIELD;
1272 * Some fabric drivers like iscsi-target still expect to
1273 * always reject overflow writes. Reject this case until
1274 * full fabric driver level support for overflow writes
1275 * is introduced tree-wide.
1277 if (size > cmd->data_length) {
1278 pr_err_ratelimited("Rejecting overflow for"
1279 " WRITE control CDB\n");
1280 return TCM_INVALID_CDB_FIELD;
1284 * Reject READ_* or WRITE_* with overflow/underflow for
1285 * type SCF_SCSI_DATA_CDB.
1287 if (dev->dev_attrib.block_size != 512) {
1288 pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
1289 " CDB on non 512-byte sector setup subsystem"
1290 " plugin: %s\n", dev->transport->name);
1291 /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
1292 return TCM_INVALID_CDB_FIELD;
1295 * For the overflow case keep the existing fabric provided
1296 * ->data_length. Otherwise for the underflow case, reset
1297 * ->data_length to the smaller SCSI expected data transfer
1298 * length.
1300 if (size > cmd->data_length) {
1301 cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1302 cmd->residual_count = (size - cmd->data_length);
1303 } else {
1304 cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1305 cmd->residual_count = (cmd->data_length - size);
1306 cmd->data_length = size;
1310 return target_check_max_data_sg_nents(cmd, dev, size);
1315 * Used by fabric modules containing a local struct se_cmd within their
1316 * fabric dependent per I/O descriptor.
1318 * Preserves the value of @cmd->tag.
1320 void transport_init_se_cmd(
1321 struct se_cmd *cmd,
1322 const struct target_core_fabric_ops *tfo,
1323 struct se_session *se_sess,
1324 u32 data_length,
1325 int data_direction,
1326 int task_attr,
1327 unsigned char *sense_buffer)
1329 INIT_LIST_HEAD(&cmd->se_delayed_node);
1330 INIT_LIST_HEAD(&cmd->se_qf_node);
1331 INIT_LIST_HEAD(&cmd->se_cmd_list);
1332 INIT_LIST_HEAD(&cmd->state_list);
1333 init_completion(&cmd->t_transport_stop_comp);
1334 cmd->compl = NULL;
1335 spin_lock_init(&cmd->t_state_lock);
1336 INIT_WORK(&cmd->work, NULL);
1337 kref_init(&cmd->cmd_kref);
1339 cmd->se_tfo = tfo;
1340 cmd->se_sess = se_sess;
1341 cmd->data_length = data_length;
1342 cmd->data_direction = data_direction;
1343 cmd->sam_task_attr = task_attr;
1344 cmd->sense_buffer = sense_buffer;
1346 cmd->state_active = false;
1348 EXPORT_SYMBOL(transport_init_se_cmd);
1350 static sense_reason_t
1351 transport_check_alloc_task_attr(struct se_cmd *cmd)
1353 struct se_device *dev = cmd->se_dev;
1356 * Check if SAM Task Attribute emulation is enabled for this
1357 * struct se_device storage object
1359 if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1360 return 0;
1362 if (cmd->sam_task_attr == TCM_ACA_TAG) {
1363 pr_debug("SAM Task Attribute ACA"
1364 " emulation is not supported\n");
1365 return TCM_INVALID_CDB_FIELD;
1368 return 0;
1371 sense_reason_t
1372 target_setup_cmd_from_cdb(struct se_cmd *cmd, unsigned char *cdb)
1374 struct se_device *dev = cmd->se_dev;
1375 sense_reason_t ret;
1378 * Ensure that the received CDB is less than the max (252 + 8) bytes
1379 * for VARIABLE_LENGTH_CMD
1381 if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1382 pr_err("Received SCSI CDB with command_size: %d that"
1383 " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1384 scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1385 return TCM_INVALID_CDB_FIELD;
1388 * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1389 * allocate the additional extended CDB buffer now.. Otherwise
1390 * setup the pointer from __t_task_cdb to t_task_cdb.
1392 if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1393 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1394 GFP_KERNEL);
1395 if (!cmd->t_task_cdb) {
1396 pr_err("Unable to allocate cmd->t_task_cdb"
1397 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1398 scsi_command_size(cdb),
1399 (unsigned long)sizeof(cmd->__t_task_cdb));
1400 return TCM_OUT_OF_RESOURCES;
1402 } else
1403 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1405 * Copy the original CDB into cmd->
1407 memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1409 trace_target_sequencer_start(cmd);
1411 ret = dev->transport->parse_cdb(cmd);
1412 if (ret == TCM_UNSUPPORTED_SCSI_OPCODE)
1413 pr_warn_ratelimited("%s/%s: Unsupported SCSI Opcode 0x%02x, sending CHECK_CONDITION.\n",
1414 cmd->se_tfo->get_fabric_name(),
1415 cmd->se_sess->se_node_acl->initiatorname,
1416 cmd->t_task_cdb[0]);
1417 if (ret)
1418 return ret;
1420 ret = transport_check_alloc_task_attr(cmd);
1421 if (ret)
1422 return ret;
1424 cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1425 atomic_long_inc(&cmd->se_lun->lun_stats.cmd_pdus);
1426 return 0;
1428 EXPORT_SYMBOL(target_setup_cmd_from_cdb);
1431 * Used by fabric module frontends to queue tasks directly.
1432 * May only be used from process context.
1434 int transport_handle_cdb_direct(
1435 struct se_cmd *cmd)
1437 sense_reason_t ret;
1439 if (!cmd->se_lun) {
1440 dump_stack();
1441 pr_err("cmd->se_lun is NULL\n");
1442 return -EINVAL;
1444 if (in_interrupt()) {
1445 dump_stack();
1446 pr_err("transport_generic_handle_cdb cannot be called"
1447 " from interrupt context\n");
1448 return -EINVAL;
1451 * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1452 * outstanding descriptors are handled correctly during shutdown via
1453 * transport_wait_for_tasks()
1455 * Also, we don't take cmd->t_state_lock here as we only expect
1456 * this to be called for initial descriptor submission.
1458 cmd->t_state = TRANSPORT_NEW_CMD;
1459 cmd->transport_state |= CMD_T_ACTIVE;
1462 * transport_generic_new_cmd() is already handling QUEUE_FULL,
1463 * so follow TRANSPORT_NEW_CMD processing thread context usage
1464 * and call transport_generic_request_failure() if necessary..
1466 ret = transport_generic_new_cmd(cmd);
1467 if (ret)
1468 transport_generic_request_failure(cmd, ret);
1469 return 0;
1471 EXPORT_SYMBOL(transport_handle_cdb_direct);
1473 sense_reason_t
1474 transport_generic_map_mem_to_cmd(struct se_cmd *cmd, struct scatterlist *sgl,
1475 u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count)
1477 if (!sgl || !sgl_count)
1478 return 0;
1481 * Reject SCSI data overflow with map_mem_to_cmd() as incoming
1482 * scatterlists already have been set to follow what the fabric
1483 * passes for the original expected data transfer length.
1485 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1486 pr_warn("Rejecting SCSI DATA overflow for fabric using"
1487 " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
1488 return TCM_INVALID_CDB_FIELD;
1491 cmd->t_data_sg = sgl;
1492 cmd->t_data_nents = sgl_count;
1493 cmd->t_bidi_data_sg = sgl_bidi;
1494 cmd->t_bidi_data_nents = sgl_bidi_count;
1496 cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
1497 return 0;
1501 * target_submit_cmd_map_sgls - lookup unpacked lun and submit uninitialized
1502 * se_cmd + use pre-allocated SGL memory.
1504 * @se_cmd: command descriptor to submit
1505 * @se_sess: associated se_sess for endpoint
1506 * @cdb: pointer to SCSI CDB
1507 * @sense: pointer to SCSI sense buffer
1508 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1509 * @data_length: fabric expected data transfer length
1510 * @task_attr: SAM task attribute
1511 * @data_dir: DMA data direction
1512 * @flags: flags for command submission from target_sc_flags_tables
1513 * @sgl: struct scatterlist memory for unidirectional mapping
1514 * @sgl_count: scatterlist count for unidirectional mapping
1515 * @sgl_bidi: struct scatterlist memory for bidirectional READ mapping
1516 * @sgl_bidi_count: scatterlist count for bidirectional READ mapping
1517 * @sgl_prot: struct scatterlist memory protection information
1518 * @sgl_prot_count: scatterlist count for protection information
1520 * Task tags are supported if the caller has set @se_cmd->tag.
1522 * Returns non zero to signal active I/O shutdown failure. All other
1523 * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1524 * but still return zero here.
1526 * This may only be called from process context, and also currently
1527 * assumes internal allocation of fabric payload buffer by target-core.
1529 int target_submit_cmd_map_sgls(struct se_cmd *se_cmd, struct se_session *se_sess,
1530 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1531 u32 data_length, int task_attr, int data_dir, int flags,
1532 struct scatterlist *sgl, u32 sgl_count,
1533 struct scatterlist *sgl_bidi, u32 sgl_bidi_count,
1534 struct scatterlist *sgl_prot, u32 sgl_prot_count)
1536 struct se_portal_group *se_tpg;
1537 sense_reason_t rc;
1538 int ret;
1540 se_tpg = se_sess->se_tpg;
1541 BUG_ON(!se_tpg);
1542 BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1543 BUG_ON(in_interrupt());
1545 * Initialize se_cmd for target operation. From this point
1546 * exceptions are handled by sending exception status via
1547 * target_core_fabric_ops->queue_status() callback
1549 transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1550 data_length, data_dir, task_attr, sense);
1552 if (flags & TARGET_SCF_USE_CPUID)
1553 se_cmd->se_cmd_flags |= SCF_USE_CPUID;
1554 else
1555 se_cmd->cpuid = WORK_CPU_UNBOUND;
1557 if (flags & TARGET_SCF_UNKNOWN_SIZE)
1558 se_cmd->unknown_data_length = 1;
1560 * Obtain struct se_cmd->cmd_kref reference and add new cmd to
1561 * se_sess->sess_cmd_list. A second kref_get here is necessary
1562 * for fabrics using TARGET_SCF_ACK_KREF that expect a second
1563 * kref_put() to happen during fabric packet acknowledgement.
1565 ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1566 if (ret)
1567 return ret;
1569 * Signal bidirectional data payloads to target-core
1571 if (flags & TARGET_SCF_BIDI_OP)
1572 se_cmd->se_cmd_flags |= SCF_BIDI;
1574 * Locate se_lun pointer and attach it to struct se_cmd
1576 rc = transport_lookup_cmd_lun(se_cmd, unpacked_lun);
1577 if (rc) {
1578 transport_send_check_condition_and_sense(se_cmd, rc, 0);
1579 target_put_sess_cmd(se_cmd);
1580 return 0;
1583 rc = target_setup_cmd_from_cdb(se_cmd, cdb);
1584 if (rc != 0) {
1585 transport_generic_request_failure(se_cmd, rc);
1586 return 0;
1590 * Save pointers for SGLs containing protection information,
1591 * if present.
1593 if (sgl_prot_count) {
1594 se_cmd->t_prot_sg = sgl_prot;
1595 se_cmd->t_prot_nents = sgl_prot_count;
1596 se_cmd->se_cmd_flags |= SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC;
1600 * When a non zero sgl_count has been passed perform SGL passthrough
1601 * mapping for pre-allocated fabric memory instead of having target
1602 * core perform an internal SGL allocation..
1604 if (sgl_count != 0) {
1605 BUG_ON(!sgl);
1608 * A work-around for tcm_loop as some userspace code via
1609 * scsi-generic do not memset their associated read buffers,
1610 * so go ahead and do that here for type non-data CDBs. Also
1611 * note that this is currently guaranteed to be a single SGL
1612 * for this case by target core in target_setup_cmd_from_cdb()
1613 * -> transport_generic_cmd_sequencer().
1615 if (!(se_cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) &&
1616 se_cmd->data_direction == DMA_FROM_DEVICE) {
1617 unsigned char *buf = NULL;
1619 if (sgl)
1620 buf = kmap(sg_page(sgl)) + sgl->offset;
1622 if (buf) {
1623 memset(buf, 0, sgl->length);
1624 kunmap(sg_page(sgl));
1628 rc = transport_generic_map_mem_to_cmd(se_cmd, sgl, sgl_count,
1629 sgl_bidi, sgl_bidi_count);
1630 if (rc != 0) {
1631 transport_generic_request_failure(se_cmd, rc);
1632 return 0;
1637 * Check if we need to delay processing because of ALUA
1638 * Active/NonOptimized primary access state..
1640 core_alua_check_nonop_delay(se_cmd);
1642 transport_handle_cdb_direct(se_cmd);
1643 return 0;
1645 EXPORT_SYMBOL(target_submit_cmd_map_sgls);
1648 * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1650 * @se_cmd: command descriptor to submit
1651 * @se_sess: associated se_sess for endpoint
1652 * @cdb: pointer to SCSI CDB
1653 * @sense: pointer to SCSI sense buffer
1654 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1655 * @data_length: fabric expected data transfer length
1656 * @task_attr: SAM task attribute
1657 * @data_dir: DMA data direction
1658 * @flags: flags for command submission from target_sc_flags_tables
1660 * Task tags are supported if the caller has set @se_cmd->tag.
1662 * Returns non zero to signal active I/O shutdown failure. All other
1663 * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1664 * but still return zero here.
1666 * This may only be called from process context, and also currently
1667 * assumes internal allocation of fabric payload buffer by target-core.
1669 * It also assumes interal target core SGL memory allocation.
1671 int target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1672 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1673 u32 data_length, int task_attr, int data_dir, int flags)
1675 return target_submit_cmd_map_sgls(se_cmd, se_sess, cdb, sense,
1676 unpacked_lun, data_length, task_attr, data_dir,
1677 flags, NULL, 0, NULL, 0, NULL, 0);
1679 EXPORT_SYMBOL(target_submit_cmd);
1681 static void target_complete_tmr_failure(struct work_struct *work)
1683 struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1685 se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1686 se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1688 transport_lun_remove_cmd(se_cmd);
1689 transport_cmd_check_stop_to_fabric(se_cmd);
1692 static bool target_lookup_lun_from_tag(struct se_session *se_sess, u64 tag,
1693 u64 *unpacked_lun)
1695 struct se_cmd *se_cmd;
1696 unsigned long flags;
1697 bool ret = false;
1699 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
1700 list_for_each_entry(se_cmd, &se_sess->sess_cmd_list, se_cmd_list) {
1701 if (se_cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
1702 continue;
1704 if (se_cmd->tag == tag) {
1705 *unpacked_lun = se_cmd->orig_fe_lun;
1706 ret = true;
1707 break;
1710 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
1712 return ret;
1716 * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1717 * for TMR CDBs
1719 * @se_cmd: command descriptor to submit
1720 * @se_sess: associated se_sess for endpoint
1721 * @sense: pointer to SCSI sense buffer
1722 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1723 * @fabric_tmr_ptr: fabric context for TMR req
1724 * @tm_type: Type of TM request
1725 * @gfp: gfp type for caller
1726 * @tag: referenced task tag for TMR_ABORT_TASK
1727 * @flags: submit cmd flags
1729 * Callable from all contexts.
1732 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1733 unsigned char *sense, u64 unpacked_lun,
1734 void *fabric_tmr_ptr, unsigned char tm_type,
1735 gfp_t gfp, u64 tag, int flags)
1737 struct se_portal_group *se_tpg;
1738 int ret;
1740 se_tpg = se_sess->se_tpg;
1741 BUG_ON(!se_tpg);
1743 transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1744 0, DMA_NONE, TCM_SIMPLE_TAG, sense);
1746 * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1747 * allocation failure.
1749 ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1750 if (ret < 0)
1751 return -ENOMEM;
1753 if (tm_type == TMR_ABORT_TASK)
1754 se_cmd->se_tmr_req->ref_task_tag = tag;
1756 /* See target_submit_cmd for commentary */
1757 ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1758 if (ret) {
1759 core_tmr_release_req(se_cmd->se_tmr_req);
1760 return ret;
1763 * If this is ABORT_TASK with no explicit fabric provided LUN,
1764 * go ahead and search active session tags for a match to figure
1765 * out unpacked_lun for the original se_cmd.
1767 if (tm_type == TMR_ABORT_TASK && (flags & TARGET_SCF_LOOKUP_LUN_FROM_TAG)) {
1768 if (!target_lookup_lun_from_tag(se_sess, tag, &unpacked_lun))
1769 goto failure;
1772 ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun);
1773 if (ret)
1774 goto failure;
1776 transport_generic_handle_tmr(se_cmd);
1777 return 0;
1780 * For callback during failure handling, push this work off
1781 * to process context with TMR_LUN_DOES_NOT_EXIST status.
1783 failure:
1784 INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1785 schedule_work(&se_cmd->work);
1786 return 0;
1788 EXPORT_SYMBOL(target_submit_tmr);
1791 * Handle SAM-esque emulation for generic transport request failures.
1793 void transport_generic_request_failure(struct se_cmd *cmd,
1794 sense_reason_t sense_reason)
1796 int ret = 0, post_ret = 0;
1798 pr_debug("-----[ Storage Engine Exception; sense_reason %d\n",
1799 sense_reason);
1800 target_show_cmd("-----[ ", cmd);
1803 * For SAM Task Attribute emulation for failed struct se_cmd
1805 transport_complete_task_attr(cmd);
1808 * Handle special case for COMPARE_AND_WRITE failure, where the
1809 * callback is expected to drop the per device ->caw_sem.
1811 if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
1812 cmd->transport_complete_callback)
1813 cmd->transport_complete_callback(cmd, false, &post_ret);
1815 if (transport_check_aborted_status(cmd, 1))
1816 return;
1818 switch (sense_reason) {
1819 case TCM_NON_EXISTENT_LUN:
1820 case TCM_UNSUPPORTED_SCSI_OPCODE:
1821 case TCM_INVALID_CDB_FIELD:
1822 case TCM_INVALID_PARAMETER_LIST:
1823 case TCM_PARAMETER_LIST_LENGTH_ERROR:
1824 case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1825 case TCM_UNKNOWN_MODE_PAGE:
1826 case TCM_WRITE_PROTECTED:
1827 case TCM_ADDRESS_OUT_OF_RANGE:
1828 case TCM_CHECK_CONDITION_ABORT_CMD:
1829 case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1830 case TCM_CHECK_CONDITION_NOT_READY:
1831 case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED:
1832 case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED:
1833 case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED:
1834 case TCM_COPY_TARGET_DEVICE_NOT_REACHABLE:
1835 case TCM_TOO_MANY_TARGET_DESCS:
1836 case TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE:
1837 case TCM_TOO_MANY_SEGMENT_DESCS:
1838 case TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE:
1839 break;
1840 case TCM_OUT_OF_RESOURCES:
1841 cmd->scsi_status = SAM_STAT_TASK_SET_FULL;
1842 goto queue_status;
1843 case TCM_LUN_BUSY:
1844 cmd->scsi_status = SAM_STAT_BUSY;
1845 goto queue_status;
1846 case TCM_RESERVATION_CONFLICT:
1848 * No SENSE Data payload for this case, set SCSI Status
1849 * and queue the response to $FABRIC_MOD.
1851 * Uses linux/include/scsi/scsi.h SAM status codes defs
1853 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1855 * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1856 * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1857 * CONFLICT STATUS.
1859 * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1861 if (cmd->se_sess &&
1862 cmd->se_dev->dev_attrib.emulate_ua_intlck_ctrl == 2) {
1863 target_ua_allocate_lun(cmd->se_sess->se_node_acl,
1864 cmd->orig_fe_lun, 0x2C,
1865 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1868 goto queue_status;
1869 default:
1870 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1871 cmd->t_task_cdb[0], sense_reason);
1872 sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1873 break;
1876 ret = transport_send_check_condition_and_sense(cmd, sense_reason, 0);
1877 if (ret)
1878 goto queue_full;
1880 check_stop:
1881 transport_lun_remove_cmd(cmd);
1882 transport_cmd_check_stop_to_fabric(cmd);
1883 return;
1885 queue_status:
1886 trace_target_cmd_complete(cmd);
1887 ret = cmd->se_tfo->queue_status(cmd);
1888 if (!ret)
1889 goto check_stop;
1890 queue_full:
1891 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
1893 EXPORT_SYMBOL(transport_generic_request_failure);
1895 void __target_execute_cmd(struct se_cmd *cmd, bool do_checks)
1897 sense_reason_t ret;
1899 if (!cmd->execute_cmd) {
1900 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1901 goto err;
1903 if (do_checks) {
1905 * Check for an existing UNIT ATTENTION condition after
1906 * target_handle_task_attr() has done SAM task attr
1907 * checking, and possibly have already defered execution
1908 * out to target_restart_delayed_cmds() context.
1910 ret = target_scsi3_ua_check(cmd);
1911 if (ret)
1912 goto err;
1914 ret = target_alua_state_check(cmd);
1915 if (ret)
1916 goto err;
1918 ret = target_check_reservation(cmd);
1919 if (ret) {
1920 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1921 goto err;
1925 ret = cmd->execute_cmd(cmd);
1926 if (!ret)
1927 return;
1928 err:
1929 spin_lock_irq(&cmd->t_state_lock);
1930 cmd->transport_state &= ~CMD_T_SENT;
1931 spin_unlock_irq(&cmd->t_state_lock);
1933 transport_generic_request_failure(cmd, ret);
1936 static int target_write_prot_action(struct se_cmd *cmd)
1938 u32 sectors;
1940 * Perform WRITE_INSERT of PI using software emulation when backend
1941 * device has PI enabled, if the transport has not already generated
1942 * PI using hardware WRITE_INSERT offload.
1944 switch (cmd->prot_op) {
1945 case TARGET_PROT_DOUT_INSERT:
1946 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_INSERT))
1947 sbc_dif_generate(cmd);
1948 break;
1949 case TARGET_PROT_DOUT_STRIP:
1950 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_STRIP)
1951 break;
1953 sectors = cmd->data_length >> ilog2(cmd->se_dev->dev_attrib.block_size);
1954 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
1955 sectors, 0, cmd->t_prot_sg, 0);
1956 if (unlikely(cmd->pi_err)) {
1957 spin_lock_irq(&cmd->t_state_lock);
1958 cmd->transport_state &= ~CMD_T_SENT;
1959 spin_unlock_irq(&cmd->t_state_lock);
1960 transport_generic_request_failure(cmd, cmd->pi_err);
1961 return -1;
1963 break;
1964 default:
1965 break;
1968 return 0;
1971 static bool target_handle_task_attr(struct se_cmd *cmd)
1973 struct se_device *dev = cmd->se_dev;
1975 if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1976 return false;
1978 cmd->se_cmd_flags |= SCF_TASK_ATTR_SET;
1981 * Check for the existence of HEAD_OF_QUEUE, and if true return 1
1982 * to allow the passed struct se_cmd list of tasks to the front of the list.
1984 switch (cmd->sam_task_attr) {
1985 case TCM_HEAD_TAG:
1986 pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x\n",
1987 cmd->t_task_cdb[0]);
1988 return false;
1989 case TCM_ORDERED_TAG:
1990 atomic_inc_mb(&dev->dev_ordered_sync);
1992 pr_debug("Added ORDERED for CDB: 0x%02x to ordered list\n",
1993 cmd->t_task_cdb[0]);
1996 * Execute an ORDERED command if no other older commands
1997 * exist that need to be completed first.
1999 if (!atomic_read(&dev->simple_cmds))
2000 return false;
2001 break;
2002 default:
2004 * For SIMPLE and UNTAGGED Task Attribute commands
2006 atomic_inc_mb(&dev->simple_cmds);
2007 break;
2010 if (atomic_read(&dev->dev_ordered_sync) == 0)
2011 return false;
2013 spin_lock(&dev->delayed_cmd_lock);
2014 list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
2015 spin_unlock(&dev->delayed_cmd_lock);
2017 pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to delayed CMD listn",
2018 cmd->t_task_cdb[0], cmd->sam_task_attr);
2019 return true;
2022 static int __transport_check_aborted_status(struct se_cmd *, int);
2024 void target_execute_cmd(struct se_cmd *cmd)
2027 * Determine if frontend context caller is requesting the stopping of
2028 * this command for frontend exceptions.
2030 * If the received CDB has aleady been aborted stop processing it here.
2032 spin_lock_irq(&cmd->t_state_lock);
2033 if (__transport_check_aborted_status(cmd, 1)) {
2034 spin_unlock_irq(&cmd->t_state_lock);
2035 return;
2037 if (cmd->transport_state & CMD_T_STOP) {
2038 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2039 __func__, __LINE__, cmd->tag);
2041 spin_unlock_irq(&cmd->t_state_lock);
2042 complete_all(&cmd->t_transport_stop_comp);
2043 return;
2046 cmd->t_state = TRANSPORT_PROCESSING;
2047 cmd->transport_state &= ~CMD_T_PRE_EXECUTE;
2048 cmd->transport_state |= CMD_T_ACTIVE | CMD_T_SENT;
2049 spin_unlock_irq(&cmd->t_state_lock);
2051 if (target_write_prot_action(cmd))
2052 return;
2054 if (target_handle_task_attr(cmd)) {
2055 spin_lock_irq(&cmd->t_state_lock);
2056 cmd->transport_state &= ~CMD_T_SENT;
2057 spin_unlock_irq(&cmd->t_state_lock);
2058 return;
2061 __target_execute_cmd(cmd, true);
2063 EXPORT_SYMBOL(target_execute_cmd);
2066 * Process all commands up to the last received ORDERED task attribute which
2067 * requires another blocking boundary
2069 static void target_restart_delayed_cmds(struct se_device *dev)
2071 for (;;) {
2072 struct se_cmd *cmd;
2074 spin_lock(&dev->delayed_cmd_lock);
2075 if (list_empty(&dev->delayed_cmd_list)) {
2076 spin_unlock(&dev->delayed_cmd_lock);
2077 break;
2080 cmd = list_entry(dev->delayed_cmd_list.next,
2081 struct se_cmd, se_delayed_node);
2082 list_del(&cmd->se_delayed_node);
2083 spin_unlock(&dev->delayed_cmd_lock);
2085 cmd->transport_state |= CMD_T_SENT;
2087 __target_execute_cmd(cmd, true);
2089 if (cmd->sam_task_attr == TCM_ORDERED_TAG)
2090 break;
2095 * Called from I/O completion to determine which dormant/delayed
2096 * and ordered cmds need to have their tasks added to the execution queue.
2098 static void transport_complete_task_attr(struct se_cmd *cmd)
2100 struct se_device *dev = cmd->se_dev;
2102 if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2103 return;
2105 if (!(cmd->se_cmd_flags & SCF_TASK_ATTR_SET))
2106 goto restart;
2108 if (cmd->sam_task_attr == TCM_SIMPLE_TAG) {
2109 atomic_dec_mb(&dev->simple_cmds);
2110 dev->dev_cur_ordered_id++;
2111 } else if (cmd->sam_task_attr == TCM_HEAD_TAG) {
2112 dev->dev_cur_ordered_id++;
2113 pr_debug("Incremented dev_cur_ordered_id: %u for HEAD_OF_QUEUE\n",
2114 dev->dev_cur_ordered_id);
2115 } else if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2116 atomic_dec_mb(&dev->dev_ordered_sync);
2118 dev->dev_cur_ordered_id++;
2119 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED\n",
2120 dev->dev_cur_ordered_id);
2122 cmd->se_cmd_flags &= ~SCF_TASK_ATTR_SET;
2124 restart:
2125 target_restart_delayed_cmds(dev);
2128 static void transport_complete_qf(struct se_cmd *cmd)
2130 int ret = 0;
2132 transport_complete_task_attr(cmd);
2134 * If a fabric driver ->write_pending() or ->queue_data_in() callback
2135 * has returned neither -ENOMEM or -EAGAIN, assume it's fatal and
2136 * the same callbacks should not be retried. Return CHECK_CONDITION
2137 * if a scsi_status is not already set.
2139 * If a fabric driver ->queue_status() has returned non zero, always
2140 * keep retrying no matter what..
2142 if (cmd->t_state == TRANSPORT_COMPLETE_QF_ERR) {
2143 if (cmd->scsi_status)
2144 goto queue_status;
2146 translate_sense_reason(cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
2147 goto queue_status;
2151 * Check if we need to send a sense buffer from
2152 * the struct se_cmd in question. We do NOT want
2153 * to take this path of the IO has been marked as
2154 * needing to be treated like a "normal read". This
2155 * is the case if it's a tape read, and either the
2156 * FM, EOM, or ILI bits are set, but there is no
2157 * sense data.
2159 if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2160 cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
2161 goto queue_status;
2163 switch (cmd->data_direction) {
2164 case DMA_FROM_DEVICE:
2165 /* queue status if not treating this as a normal read */
2166 if (cmd->scsi_status &&
2167 !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2168 goto queue_status;
2170 trace_target_cmd_complete(cmd);
2171 ret = cmd->se_tfo->queue_data_in(cmd);
2172 break;
2173 case DMA_TO_DEVICE:
2174 if (cmd->se_cmd_flags & SCF_BIDI) {
2175 ret = cmd->se_tfo->queue_data_in(cmd);
2176 break;
2178 /* fall through */
2179 case DMA_NONE:
2180 queue_status:
2181 trace_target_cmd_complete(cmd);
2182 ret = cmd->se_tfo->queue_status(cmd);
2183 break;
2184 default:
2185 break;
2188 if (ret < 0) {
2189 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2190 return;
2192 transport_lun_remove_cmd(cmd);
2193 transport_cmd_check_stop_to_fabric(cmd);
2196 static void transport_handle_queue_full(struct se_cmd *cmd, struct se_device *dev,
2197 int err, bool write_pending)
2200 * -EAGAIN or -ENOMEM signals retry of ->write_pending() and/or
2201 * ->queue_data_in() callbacks from new process context.
2203 * Otherwise for other errors, transport_complete_qf() will send
2204 * CHECK_CONDITION via ->queue_status() instead of attempting to
2205 * retry associated fabric driver data-transfer callbacks.
2207 if (err == -EAGAIN || err == -ENOMEM) {
2208 cmd->t_state = (write_pending) ? TRANSPORT_COMPLETE_QF_WP :
2209 TRANSPORT_COMPLETE_QF_OK;
2210 } else {
2211 pr_warn_ratelimited("Got unknown fabric queue status: %d\n", err);
2212 cmd->t_state = TRANSPORT_COMPLETE_QF_ERR;
2215 spin_lock_irq(&dev->qf_cmd_lock);
2216 list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
2217 atomic_inc_mb(&dev->dev_qf_count);
2218 spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
2220 schedule_work(&cmd->se_dev->qf_work_queue);
2223 static bool target_read_prot_action(struct se_cmd *cmd)
2225 switch (cmd->prot_op) {
2226 case TARGET_PROT_DIN_STRIP:
2227 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_STRIP)) {
2228 u32 sectors = cmd->data_length >>
2229 ilog2(cmd->se_dev->dev_attrib.block_size);
2231 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2232 sectors, 0, cmd->t_prot_sg,
2234 if (cmd->pi_err)
2235 return true;
2237 break;
2238 case TARGET_PROT_DIN_INSERT:
2239 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_INSERT)
2240 break;
2242 sbc_dif_generate(cmd);
2243 break;
2244 default:
2245 break;
2248 return false;
2251 static void target_complete_ok_work(struct work_struct *work)
2253 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
2254 int ret;
2257 * Check if we need to move delayed/dormant tasks from cmds on the
2258 * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
2259 * Attribute.
2261 transport_complete_task_attr(cmd);
2264 * Check to schedule QUEUE_FULL work, or execute an existing
2265 * cmd->transport_qf_callback()
2267 if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
2268 schedule_work(&cmd->se_dev->qf_work_queue);
2271 * Check if we need to send a sense buffer from
2272 * the struct se_cmd in question. We do NOT want
2273 * to take this path of the IO has been marked as
2274 * needing to be treated like a "normal read". This
2275 * is the case if it's a tape read, and either the
2276 * FM, EOM, or ILI bits are set, but there is no
2277 * sense data.
2279 if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2280 cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2281 WARN_ON(!cmd->scsi_status);
2282 ret = transport_send_check_condition_and_sense(
2283 cmd, 0, 1);
2284 if (ret)
2285 goto queue_full;
2287 transport_lun_remove_cmd(cmd);
2288 transport_cmd_check_stop_to_fabric(cmd);
2289 return;
2292 * Check for a callback, used by amongst other things
2293 * XDWRITE_READ_10 and COMPARE_AND_WRITE emulation.
2295 if (cmd->transport_complete_callback) {
2296 sense_reason_t rc;
2297 bool caw = (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE);
2298 bool zero_dl = !(cmd->data_length);
2299 int post_ret = 0;
2301 rc = cmd->transport_complete_callback(cmd, true, &post_ret);
2302 if (!rc && !post_ret) {
2303 if (caw && zero_dl)
2304 goto queue_rsp;
2306 return;
2307 } else if (rc) {
2308 ret = transport_send_check_condition_and_sense(cmd,
2309 rc, 0);
2310 if (ret)
2311 goto queue_full;
2313 transport_lun_remove_cmd(cmd);
2314 transport_cmd_check_stop_to_fabric(cmd);
2315 return;
2319 queue_rsp:
2320 switch (cmd->data_direction) {
2321 case DMA_FROM_DEVICE:
2323 * if this is a READ-type IO, but SCSI status
2324 * is set, then skip returning data and just
2325 * return the status -- unless this IO is marked
2326 * as needing to be treated as a normal read,
2327 * in which case we want to go ahead and return
2328 * the data. This happens, for example, for tape
2329 * reads with the FM, EOM, or ILI bits set, with
2330 * no sense data.
2332 if (cmd->scsi_status &&
2333 !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2334 goto queue_status;
2336 atomic_long_add(cmd->data_length,
2337 &cmd->se_lun->lun_stats.tx_data_octets);
2339 * Perform READ_STRIP of PI using software emulation when
2340 * backend had PI enabled, if the transport will not be
2341 * performing hardware READ_STRIP offload.
2343 if (target_read_prot_action(cmd)) {
2344 ret = transport_send_check_condition_and_sense(cmd,
2345 cmd->pi_err, 0);
2346 if (ret)
2347 goto queue_full;
2349 transport_lun_remove_cmd(cmd);
2350 transport_cmd_check_stop_to_fabric(cmd);
2351 return;
2354 trace_target_cmd_complete(cmd);
2355 ret = cmd->se_tfo->queue_data_in(cmd);
2356 if (ret)
2357 goto queue_full;
2358 break;
2359 case DMA_TO_DEVICE:
2360 atomic_long_add(cmd->data_length,
2361 &cmd->se_lun->lun_stats.rx_data_octets);
2363 * Check if we need to send READ payload for BIDI-COMMAND
2365 if (cmd->se_cmd_flags & SCF_BIDI) {
2366 atomic_long_add(cmd->data_length,
2367 &cmd->se_lun->lun_stats.tx_data_octets);
2368 ret = cmd->se_tfo->queue_data_in(cmd);
2369 if (ret)
2370 goto queue_full;
2371 break;
2373 /* fall through */
2374 case DMA_NONE:
2375 queue_status:
2376 trace_target_cmd_complete(cmd);
2377 ret = cmd->se_tfo->queue_status(cmd);
2378 if (ret)
2379 goto queue_full;
2380 break;
2381 default:
2382 break;
2385 transport_lun_remove_cmd(cmd);
2386 transport_cmd_check_stop_to_fabric(cmd);
2387 return;
2389 queue_full:
2390 pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2391 " data_direction: %d\n", cmd, cmd->data_direction);
2393 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2396 void target_free_sgl(struct scatterlist *sgl, int nents)
2398 sgl_free_n_order(sgl, nents, 0);
2400 EXPORT_SYMBOL(target_free_sgl);
2402 static inline void transport_reset_sgl_orig(struct se_cmd *cmd)
2405 * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE
2406 * emulation, and free + reset pointers if necessary..
2408 if (!cmd->t_data_sg_orig)
2409 return;
2411 kfree(cmd->t_data_sg);
2412 cmd->t_data_sg = cmd->t_data_sg_orig;
2413 cmd->t_data_sg_orig = NULL;
2414 cmd->t_data_nents = cmd->t_data_nents_orig;
2415 cmd->t_data_nents_orig = 0;
2418 static inline void transport_free_pages(struct se_cmd *cmd)
2420 if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2421 target_free_sgl(cmd->t_prot_sg, cmd->t_prot_nents);
2422 cmd->t_prot_sg = NULL;
2423 cmd->t_prot_nents = 0;
2426 if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) {
2428 * Release special case READ buffer payload required for
2429 * SG_TO_MEM_NOALLOC to function with COMPARE_AND_WRITE
2431 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
2432 target_free_sgl(cmd->t_bidi_data_sg,
2433 cmd->t_bidi_data_nents);
2434 cmd->t_bidi_data_sg = NULL;
2435 cmd->t_bidi_data_nents = 0;
2437 transport_reset_sgl_orig(cmd);
2438 return;
2440 transport_reset_sgl_orig(cmd);
2442 target_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2443 cmd->t_data_sg = NULL;
2444 cmd->t_data_nents = 0;
2446 target_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2447 cmd->t_bidi_data_sg = NULL;
2448 cmd->t_bidi_data_nents = 0;
2451 void *transport_kmap_data_sg(struct se_cmd *cmd)
2453 struct scatterlist *sg = cmd->t_data_sg;
2454 struct page **pages;
2455 int i;
2458 * We need to take into account a possible offset here for fabrics like
2459 * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2460 * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2462 if (!cmd->t_data_nents)
2463 return NULL;
2465 BUG_ON(!sg);
2466 if (cmd->t_data_nents == 1)
2467 return kmap(sg_page(sg)) + sg->offset;
2469 /* >1 page. use vmap */
2470 pages = kmalloc_array(cmd->t_data_nents, sizeof(*pages), GFP_KERNEL);
2471 if (!pages)
2472 return NULL;
2474 /* convert sg[] to pages[] */
2475 for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2476 pages[i] = sg_page(sg);
2479 cmd->t_data_vmap = vmap(pages, cmd->t_data_nents, VM_MAP, PAGE_KERNEL);
2480 kfree(pages);
2481 if (!cmd->t_data_vmap)
2482 return NULL;
2484 return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2486 EXPORT_SYMBOL(transport_kmap_data_sg);
2488 void transport_kunmap_data_sg(struct se_cmd *cmd)
2490 if (!cmd->t_data_nents) {
2491 return;
2492 } else if (cmd->t_data_nents == 1) {
2493 kunmap(sg_page(cmd->t_data_sg));
2494 return;
2497 vunmap(cmd->t_data_vmap);
2498 cmd->t_data_vmap = NULL;
2500 EXPORT_SYMBOL(transport_kunmap_data_sg);
2503 target_alloc_sgl(struct scatterlist **sgl, unsigned int *nents, u32 length,
2504 bool zero_page, bool chainable)
2506 gfp_t gfp = GFP_KERNEL | (zero_page ? __GFP_ZERO : 0);
2508 *sgl = sgl_alloc_order(length, 0, chainable, gfp, nents);
2509 return *sgl ? 0 : -ENOMEM;
2511 EXPORT_SYMBOL(target_alloc_sgl);
2514 * Allocate any required resources to execute the command. For writes we
2515 * might not have the payload yet, so notify the fabric via a call to
2516 * ->write_pending instead. Otherwise place it on the execution queue.
2518 sense_reason_t
2519 transport_generic_new_cmd(struct se_cmd *cmd)
2521 unsigned long flags;
2522 int ret = 0;
2523 bool zero_flag = !(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB);
2525 if (cmd->prot_op != TARGET_PROT_NORMAL &&
2526 !(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2527 ret = target_alloc_sgl(&cmd->t_prot_sg, &cmd->t_prot_nents,
2528 cmd->prot_length, true, false);
2529 if (ret < 0)
2530 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2534 * Determine is the TCM fabric module has already allocated physical
2535 * memory, and is directly calling transport_generic_map_mem_to_cmd()
2536 * beforehand.
2538 if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2539 cmd->data_length) {
2541 if ((cmd->se_cmd_flags & SCF_BIDI) ||
2542 (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)) {
2543 u32 bidi_length;
2545 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)
2546 bidi_length = cmd->t_task_nolb *
2547 cmd->se_dev->dev_attrib.block_size;
2548 else
2549 bidi_length = cmd->data_length;
2551 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2552 &cmd->t_bidi_data_nents,
2553 bidi_length, zero_flag, false);
2554 if (ret < 0)
2555 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2558 ret = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents,
2559 cmd->data_length, zero_flag, false);
2560 if (ret < 0)
2561 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2562 } else if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
2563 cmd->data_length) {
2565 * Special case for COMPARE_AND_WRITE with fabrics
2566 * using SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC.
2568 u32 caw_length = cmd->t_task_nolb *
2569 cmd->se_dev->dev_attrib.block_size;
2571 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2572 &cmd->t_bidi_data_nents,
2573 caw_length, zero_flag, false);
2574 if (ret < 0)
2575 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2578 * If this command is not a write we can execute it right here,
2579 * for write buffers we need to notify the fabric driver first
2580 * and let it call back once the write buffers are ready.
2582 target_add_to_state_list(cmd);
2583 if (cmd->data_direction != DMA_TO_DEVICE || cmd->data_length == 0) {
2584 target_execute_cmd(cmd);
2585 return 0;
2588 spin_lock_irqsave(&cmd->t_state_lock, flags);
2589 cmd->t_state = TRANSPORT_WRITE_PENDING;
2591 * Determine if frontend context caller is requesting the stopping of
2592 * this command for frontend exceptions.
2594 if (cmd->transport_state & CMD_T_STOP) {
2595 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2596 __func__, __LINE__, cmd->tag);
2598 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2600 complete_all(&cmd->t_transport_stop_comp);
2601 return 0;
2603 cmd->transport_state &= ~CMD_T_ACTIVE;
2604 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2606 ret = cmd->se_tfo->write_pending(cmd);
2607 if (ret)
2608 goto queue_full;
2610 return 0;
2612 queue_full:
2613 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2614 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2615 return 0;
2617 EXPORT_SYMBOL(transport_generic_new_cmd);
2619 static void transport_write_pending_qf(struct se_cmd *cmd)
2621 unsigned long flags;
2622 int ret;
2623 bool stop;
2625 spin_lock_irqsave(&cmd->t_state_lock, flags);
2626 stop = (cmd->transport_state & (CMD_T_STOP | CMD_T_ABORTED));
2627 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2629 if (stop) {
2630 pr_debug("%s:%d CMD_T_STOP|CMD_T_ABORTED for ITT: 0x%08llx\n",
2631 __func__, __LINE__, cmd->tag);
2632 complete_all(&cmd->t_transport_stop_comp);
2633 return;
2636 ret = cmd->se_tfo->write_pending(cmd);
2637 if (ret) {
2638 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2639 cmd);
2640 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2644 static bool
2645 __transport_wait_for_tasks(struct se_cmd *, bool, bool *, bool *,
2646 unsigned long *flags);
2648 static void target_wait_free_cmd(struct se_cmd *cmd, bool *aborted, bool *tas)
2650 unsigned long flags;
2652 spin_lock_irqsave(&cmd->t_state_lock, flags);
2653 __transport_wait_for_tasks(cmd, true, aborted, tas, &flags);
2654 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2658 * This function is called by frontend drivers after processing of a command
2659 * has finished.
2661 * The protocol for ensuring that either the regular flow or the TMF
2662 * code drops one reference is as follows:
2663 * - Calling .queue_data_in(), .queue_status() or queue_tm_rsp() will cause
2664 * the frontend driver to drop one reference, synchronously or asynchronously.
2665 * - During regular command processing the target core sets CMD_T_COMPLETE
2666 * before invoking one of the .queue_*() functions.
2667 * - The code that aborts commands skips commands and TMFs for which
2668 * CMD_T_COMPLETE has been set.
2669 * - CMD_T_ABORTED is set atomically after the CMD_T_COMPLETE check for
2670 * commands that will be aborted.
2671 * - If the CMD_T_ABORTED flag is set but CMD_T_TAS has not been set
2672 * transport_generic_free_cmd() skips its call to target_put_sess_cmd().
2673 * - For aborted commands for which CMD_T_TAS has been set .queue_status() will
2674 * be called and will drop a reference.
2675 * - For aborted commands for which CMD_T_TAS has not been set .aborted_task()
2676 * will be called. transport_cmd_finish_abort() will drop the final reference.
2678 int transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2680 DECLARE_COMPLETION_ONSTACK(compl);
2681 int ret = 0;
2682 bool aborted = false, tas = false;
2684 if (wait_for_tasks)
2685 target_wait_free_cmd(cmd, &aborted, &tas);
2687 if (cmd->se_cmd_flags & SCF_SE_LUN_CMD) {
2689 * Handle WRITE failure case where transport_generic_new_cmd()
2690 * has already added se_cmd to state_list, but fabric has
2691 * failed command before I/O submission.
2693 if (cmd->state_active)
2694 target_remove_from_state_list(cmd);
2696 if (cmd->se_lun)
2697 transport_lun_remove_cmd(cmd);
2699 if (aborted)
2700 cmd->compl = &compl;
2701 if (!aborted || tas)
2702 ret = target_put_sess_cmd(cmd);
2703 if (aborted) {
2704 pr_debug("Detected CMD_T_ABORTED for ITT: %llu\n", cmd->tag);
2705 wait_for_completion(&compl);
2706 ret = 1;
2708 return ret;
2710 EXPORT_SYMBOL(transport_generic_free_cmd);
2713 * target_get_sess_cmd - Add command to active ->sess_cmd_list
2714 * @se_cmd: command descriptor to add
2715 * @ack_kref: Signal that fabric will perform an ack target_put_sess_cmd()
2717 int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
2719 struct se_session *se_sess = se_cmd->se_sess;
2720 unsigned long flags;
2721 int ret = 0;
2724 * Add a second kref if the fabric caller is expecting to handle
2725 * fabric acknowledgement that requires two target_put_sess_cmd()
2726 * invocations before se_cmd descriptor release.
2728 if (ack_kref) {
2729 if (!kref_get_unless_zero(&se_cmd->cmd_kref))
2730 return -EINVAL;
2732 se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2735 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2736 if (se_sess->sess_tearing_down) {
2737 ret = -ESHUTDOWN;
2738 goto out;
2740 se_cmd->transport_state |= CMD_T_PRE_EXECUTE;
2741 list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list);
2742 percpu_ref_get(&se_sess->cmd_count);
2743 out:
2744 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2746 if (ret && ack_kref)
2747 target_put_sess_cmd(se_cmd);
2749 return ret;
2751 EXPORT_SYMBOL(target_get_sess_cmd);
2753 static void target_free_cmd_mem(struct se_cmd *cmd)
2755 transport_free_pages(cmd);
2757 if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2758 core_tmr_release_req(cmd->se_tmr_req);
2759 if (cmd->t_task_cdb != cmd->__t_task_cdb)
2760 kfree(cmd->t_task_cdb);
2763 static void target_release_cmd_kref(struct kref *kref)
2765 struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2766 struct se_session *se_sess = se_cmd->se_sess;
2767 struct completion *compl = se_cmd->compl;
2768 unsigned long flags;
2770 if (se_sess) {
2771 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2772 list_del_init(&se_cmd->se_cmd_list);
2773 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2776 target_free_cmd_mem(se_cmd);
2777 se_cmd->se_tfo->release_cmd(se_cmd);
2778 if (compl)
2779 complete(compl);
2781 percpu_ref_put(&se_sess->cmd_count);
2785 * target_put_sess_cmd - decrease the command reference count
2786 * @se_cmd: command to drop a reference from
2788 * Returns 1 if and only if this target_put_sess_cmd() call caused the
2789 * refcount to drop to zero. Returns zero otherwise.
2791 int target_put_sess_cmd(struct se_cmd *se_cmd)
2793 return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2795 EXPORT_SYMBOL(target_put_sess_cmd);
2797 static const char *data_dir_name(enum dma_data_direction d)
2799 switch (d) {
2800 case DMA_BIDIRECTIONAL: return "BIDI";
2801 case DMA_TO_DEVICE: return "WRITE";
2802 case DMA_FROM_DEVICE: return "READ";
2803 case DMA_NONE: return "NONE";
2806 return "(?)";
2809 static const char *cmd_state_name(enum transport_state_table t)
2811 switch (t) {
2812 case TRANSPORT_NO_STATE: return "NO_STATE";
2813 case TRANSPORT_NEW_CMD: return "NEW_CMD";
2814 case TRANSPORT_WRITE_PENDING: return "WRITE_PENDING";
2815 case TRANSPORT_PROCESSING: return "PROCESSING";
2816 case TRANSPORT_COMPLETE: return "COMPLETE";
2817 case TRANSPORT_ISTATE_PROCESSING:
2818 return "ISTATE_PROCESSING";
2819 case TRANSPORT_COMPLETE_QF_WP: return "COMPLETE_QF_WP";
2820 case TRANSPORT_COMPLETE_QF_OK: return "COMPLETE_QF_OK";
2821 case TRANSPORT_COMPLETE_QF_ERR: return "COMPLETE_QF_ERR";
2824 return "(?)";
2827 static void target_append_str(char **str, const char *txt)
2829 char *prev = *str;
2831 *str = *str ? kasprintf(GFP_ATOMIC, "%s,%s", *str, txt) :
2832 kstrdup(txt, GFP_ATOMIC);
2833 kfree(prev);
2837 * Convert a transport state bitmask into a string. The caller is
2838 * responsible for freeing the returned pointer.
2840 static char *target_ts_to_str(u32 ts)
2842 char *str = NULL;
2844 if (ts & CMD_T_ABORTED)
2845 target_append_str(&str, "aborted");
2846 if (ts & CMD_T_ACTIVE)
2847 target_append_str(&str, "active");
2848 if (ts & CMD_T_COMPLETE)
2849 target_append_str(&str, "complete");
2850 if (ts & CMD_T_SENT)
2851 target_append_str(&str, "sent");
2852 if (ts & CMD_T_STOP)
2853 target_append_str(&str, "stop");
2854 if (ts & CMD_T_FABRIC_STOP)
2855 target_append_str(&str, "fabric_stop");
2857 return str;
2860 static const char *target_tmf_name(enum tcm_tmreq_table tmf)
2862 switch (tmf) {
2863 case TMR_ABORT_TASK: return "ABORT_TASK";
2864 case TMR_ABORT_TASK_SET: return "ABORT_TASK_SET";
2865 case TMR_CLEAR_ACA: return "CLEAR_ACA";
2866 case TMR_CLEAR_TASK_SET: return "CLEAR_TASK_SET";
2867 case TMR_LUN_RESET: return "LUN_RESET";
2868 case TMR_TARGET_WARM_RESET: return "TARGET_WARM_RESET";
2869 case TMR_TARGET_COLD_RESET: return "TARGET_COLD_RESET";
2870 case TMR_UNKNOWN: break;
2872 return "(?)";
2875 void target_show_cmd(const char *pfx, struct se_cmd *cmd)
2877 char *ts_str = target_ts_to_str(cmd->transport_state);
2878 const u8 *cdb = cmd->t_task_cdb;
2879 struct se_tmr_req *tmf = cmd->se_tmr_req;
2881 if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
2882 pr_debug("%scmd %#02x:%#02x with tag %#llx dir %s i_state %d t_state %s len %d refcnt %d transport_state %s\n",
2883 pfx, cdb[0], cdb[1], cmd->tag,
2884 data_dir_name(cmd->data_direction),
2885 cmd->se_tfo->get_cmd_state(cmd),
2886 cmd_state_name(cmd->t_state), cmd->data_length,
2887 kref_read(&cmd->cmd_kref), ts_str);
2888 } else {
2889 pr_debug("%stmf %s with tag %#llx ref_task_tag %#llx i_state %d t_state %s refcnt %d transport_state %s\n",
2890 pfx, target_tmf_name(tmf->function), cmd->tag,
2891 tmf->ref_task_tag, cmd->se_tfo->get_cmd_state(cmd),
2892 cmd_state_name(cmd->t_state),
2893 kref_read(&cmd->cmd_kref), ts_str);
2895 kfree(ts_str);
2897 EXPORT_SYMBOL(target_show_cmd);
2900 * target_sess_cmd_list_set_waiting - Set sess_tearing_down so no new commands are queued.
2901 * @se_sess: session to flag
2903 void target_sess_cmd_list_set_waiting(struct se_session *se_sess)
2905 unsigned long flags;
2907 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2908 se_sess->sess_tearing_down = 1;
2909 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2911 percpu_ref_kill(&se_sess->cmd_count);
2913 EXPORT_SYMBOL(target_sess_cmd_list_set_waiting);
2916 * target_wait_for_sess_cmds - Wait for outstanding commands
2917 * @se_sess: session to wait for active I/O
2919 void target_wait_for_sess_cmds(struct se_session *se_sess)
2921 struct se_cmd *cmd;
2922 int ret;
2924 WARN_ON_ONCE(!se_sess->sess_tearing_down);
2926 do {
2927 ret = wait_event_timeout(se_sess->cmd_list_wq,
2928 percpu_ref_is_zero(&se_sess->cmd_count),
2929 180 * HZ);
2930 list_for_each_entry(cmd, &se_sess->sess_cmd_list, se_cmd_list)
2931 target_show_cmd("session shutdown: still waiting for ",
2932 cmd);
2933 } while (ret <= 0);
2935 EXPORT_SYMBOL(target_wait_for_sess_cmds);
2937 static void target_lun_confirm(struct percpu_ref *ref)
2939 struct se_lun *lun = container_of(ref, struct se_lun, lun_ref);
2941 complete(&lun->lun_ref_comp);
2944 void transport_clear_lun_ref(struct se_lun *lun)
2947 * Mark the percpu-ref as DEAD, switch to atomic_t mode, drop
2948 * the initial reference and schedule confirm kill to be
2949 * executed after one full RCU grace period has completed.
2951 percpu_ref_kill_and_confirm(&lun->lun_ref, target_lun_confirm);
2953 * The first completion waits for percpu_ref_switch_to_atomic_rcu()
2954 * to call target_lun_confirm after lun->lun_ref has been marked
2955 * as __PERCPU_REF_DEAD on all CPUs, and switches to atomic_t
2956 * mode so that percpu_ref_tryget_live() lookup of lun->lun_ref
2957 * fails for all new incoming I/O.
2959 wait_for_completion(&lun->lun_ref_comp);
2961 * The second completion waits for percpu_ref_put_many() to
2962 * invoke ->release() after lun->lun_ref has switched to
2963 * atomic_t mode, and lun->lun_ref.count has reached zero.
2965 * At this point all target-core lun->lun_ref references have
2966 * been dropped via transport_lun_remove_cmd(), and it's safe
2967 * to proceed with the remaining LUN shutdown.
2969 wait_for_completion(&lun->lun_shutdown_comp);
2972 static bool
2973 __transport_wait_for_tasks(struct se_cmd *cmd, bool fabric_stop,
2974 bool *aborted, bool *tas, unsigned long *flags)
2975 __releases(&cmd->t_state_lock)
2976 __acquires(&cmd->t_state_lock)
2979 assert_spin_locked(&cmd->t_state_lock);
2980 WARN_ON_ONCE(!irqs_disabled());
2982 if (fabric_stop)
2983 cmd->transport_state |= CMD_T_FABRIC_STOP;
2985 if (cmd->transport_state & CMD_T_ABORTED)
2986 *aborted = true;
2988 if (cmd->transport_state & CMD_T_TAS)
2989 *tas = true;
2991 if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
2992 !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
2993 return false;
2995 if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
2996 !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
2997 return false;
2999 if (!(cmd->transport_state & CMD_T_ACTIVE))
3000 return false;
3002 if (fabric_stop && *aborted)
3003 return false;
3005 cmd->transport_state |= CMD_T_STOP;
3007 target_show_cmd("wait_for_tasks: Stopping ", cmd);
3009 spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
3011 while (!wait_for_completion_timeout(&cmd->t_transport_stop_comp,
3012 180 * HZ))
3013 target_show_cmd("wait for tasks: ", cmd);
3015 spin_lock_irqsave(&cmd->t_state_lock, *flags);
3016 cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
3018 pr_debug("wait_for_tasks: Stopped wait_for_completion(&cmd->"
3019 "t_transport_stop_comp) for ITT: 0x%08llx\n", cmd->tag);
3021 return true;
3025 * transport_wait_for_tasks - set CMD_T_STOP and wait for t_transport_stop_comp
3026 * @cmd: command to wait on
3028 bool transport_wait_for_tasks(struct se_cmd *cmd)
3030 unsigned long flags;
3031 bool ret, aborted = false, tas = false;
3033 spin_lock_irqsave(&cmd->t_state_lock, flags);
3034 ret = __transport_wait_for_tasks(cmd, false, &aborted, &tas, &flags);
3035 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3037 return ret;
3039 EXPORT_SYMBOL(transport_wait_for_tasks);
3041 struct sense_info {
3042 u8 key;
3043 u8 asc;
3044 u8 ascq;
3045 bool add_sector_info;
3048 static const struct sense_info sense_info_table[] = {
3049 [TCM_NO_SENSE] = {
3050 .key = NOT_READY
3052 [TCM_NON_EXISTENT_LUN] = {
3053 .key = ILLEGAL_REQUEST,
3054 .asc = 0x25 /* LOGICAL UNIT NOT SUPPORTED */
3056 [TCM_UNSUPPORTED_SCSI_OPCODE] = {
3057 .key = ILLEGAL_REQUEST,
3058 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3060 [TCM_SECTOR_COUNT_TOO_MANY] = {
3061 .key = ILLEGAL_REQUEST,
3062 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3064 [TCM_UNKNOWN_MODE_PAGE] = {
3065 .key = ILLEGAL_REQUEST,
3066 .asc = 0x24, /* INVALID FIELD IN CDB */
3068 [TCM_CHECK_CONDITION_ABORT_CMD] = {
3069 .key = ABORTED_COMMAND,
3070 .asc = 0x29, /* BUS DEVICE RESET FUNCTION OCCURRED */
3071 .ascq = 0x03,
3073 [TCM_INCORRECT_AMOUNT_OF_DATA] = {
3074 .key = ABORTED_COMMAND,
3075 .asc = 0x0c, /* WRITE ERROR */
3076 .ascq = 0x0d, /* NOT ENOUGH UNSOLICITED DATA */
3078 [TCM_INVALID_CDB_FIELD] = {
3079 .key = ILLEGAL_REQUEST,
3080 .asc = 0x24, /* INVALID FIELD IN CDB */
3082 [TCM_INVALID_PARAMETER_LIST] = {
3083 .key = ILLEGAL_REQUEST,
3084 .asc = 0x26, /* INVALID FIELD IN PARAMETER LIST */
3086 [TCM_TOO_MANY_TARGET_DESCS] = {
3087 .key = ILLEGAL_REQUEST,
3088 .asc = 0x26,
3089 .ascq = 0x06, /* TOO MANY TARGET DESCRIPTORS */
3091 [TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE] = {
3092 .key = ILLEGAL_REQUEST,
3093 .asc = 0x26,
3094 .ascq = 0x07, /* UNSUPPORTED TARGET DESCRIPTOR TYPE CODE */
3096 [TCM_TOO_MANY_SEGMENT_DESCS] = {
3097 .key = ILLEGAL_REQUEST,
3098 .asc = 0x26,
3099 .ascq = 0x08, /* TOO MANY SEGMENT DESCRIPTORS */
3101 [TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE] = {
3102 .key = ILLEGAL_REQUEST,
3103 .asc = 0x26,
3104 .ascq = 0x09, /* UNSUPPORTED SEGMENT DESCRIPTOR TYPE CODE */
3106 [TCM_PARAMETER_LIST_LENGTH_ERROR] = {
3107 .key = ILLEGAL_REQUEST,
3108 .asc = 0x1a, /* PARAMETER LIST LENGTH ERROR */
3110 [TCM_UNEXPECTED_UNSOLICITED_DATA] = {
3111 .key = ILLEGAL_REQUEST,
3112 .asc = 0x0c, /* WRITE ERROR */
3113 .ascq = 0x0c, /* UNEXPECTED_UNSOLICITED_DATA */
3115 [TCM_SERVICE_CRC_ERROR] = {
3116 .key = ABORTED_COMMAND,
3117 .asc = 0x47, /* PROTOCOL SERVICE CRC ERROR */
3118 .ascq = 0x05, /* N/A */
3120 [TCM_SNACK_REJECTED] = {
3121 .key = ABORTED_COMMAND,
3122 .asc = 0x11, /* READ ERROR */
3123 .ascq = 0x13, /* FAILED RETRANSMISSION REQUEST */
3125 [TCM_WRITE_PROTECTED] = {
3126 .key = DATA_PROTECT,
3127 .asc = 0x27, /* WRITE PROTECTED */
3129 [TCM_ADDRESS_OUT_OF_RANGE] = {
3130 .key = ILLEGAL_REQUEST,
3131 .asc = 0x21, /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3133 [TCM_CHECK_CONDITION_UNIT_ATTENTION] = {
3134 .key = UNIT_ATTENTION,
3136 [TCM_CHECK_CONDITION_NOT_READY] = {
3137 .key = NOT_READY,
3139 [TCM_MISCOMPARE_VERIFY] = {
3140 .key = MISCOMPARE,
3141 .asc = 0x1d, /* MISCOMPARE DURING VERIFY OPERATION */
3142 .ascq = 0x00,
3144 [TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED] = {
3145 .key = ABORTED_COMMAND,
3146 .asc = 0x10,
3147 .ascq = 0x01, /* LOGICAL BLOCK GUARD CHECK FAILED */
3148 .add_sector_info = true,
3150 [TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED] = {
3151 .key = ABORTED_COMMAND,
3152 .asc = 0x10,
3153 .ascq = 0x02, /* LOGICAL BLOCK APPLICATION TAG CHECK FAILED */
3154 .add_sector_info = true,
3156 [TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED] = {
3157 .key = ABORTED_COMMAND,
3158 .asc = 0x10,
3159 .ascq = 0x03, /* LOGICAL BLOCK REFERENCE TAG CHECK FAILED */
3160 .add_sector_info = true,
3162 [TCM_COPY_TARGET_DEVICE_NOT_REACHABLE] = {
3163 .key = COPY_ABORTED,
3164 .asc = 0x0d,
3165 .ascq = 0x02, /* COPY TARGET DEVICE NOT REACHABLE */
3168 [TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE] = {
3170 * Returning ILLEGAL REQUEST would cause immediate IO errors on
3171 * Solaris initiators. Returning NOT READY instead means the
3172 * operations will be retried a finite number of times and we
3173 * can survive intermittent errors.
3175 .key = NOT_READY,
3176 .asc = 0x08, /* LOGICAL UNIT COMMUNICATION FAILURE */
3178 [TCM_INSUFFICIENT_REGISTRATION_RESOURCES] = {
3180 * From spc4r22 section5.7.7,5.7.8
3181 * If a PERSISTENT RESERVE OUT command with a REGISTER service action
3182 * or a REGISTER AND IGNORE EXISTING KEY service action or
3183 * REGISTER AND MOVE service actionis attempted,
3184 * but there are insufficient device server resources to complete the
3185 * operation, then the command shall be terminated with CHECK CONDITION
3186 * status, with the sense key set to ILLEGAL REQUEST,and the additonal
3187 * sense code set to INSUFFICIENT REGISTRATION RESOURCES.
3189 .key = ILLEGAL_REQUEST,
3190 .asc = 0x55,
3191 .ascq = 0x04, /* INSUFFICIENT REGISTRATION RESOURCES */
3196 * translate_sense_reason - translate a sense reason into T10 key, asc and ascq
3197 * @cmd: SCSI command in which the resulting sense buffer or SCSI status will
3198 * be stored.
3199 * @reason: LIO sense reason code. If this argument has the value
3200 * TCM_CHECK_CONDITION_UNIT_ATTENTION, try to dequeue a unit attention. If
3201 * dequeuing a unit attention fails due to multiple commands being processed
3202 * concurrently, set the command status to BUSY.
3204 * Return: 0 upon success or -EINVAL if the sense buffer is too small.
3206 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason)
3208 const struct sense_info *si;
3209 u8 *buffer = cmd->sense_buffer;
3210 int r = (__force int)reason;
3211 u8 key, asc, ascq;
3212 bool desc_format = target_sense_desc_format(cmd->se_dev);
3214 if (r < ARRAY_SIZE(sense_info_table) && sense_info_table[r].key)
3215 si = &sense_info_table[r];
3216 else
3217 si = &sense_info_table[(__force int)
3218 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE];
3220 key = si->key;
3221 if (reason == TCM_CHECK_CONDITION_UNIT_ATTENTION) {
3222 if (!core_scsi3_ua_for_check_condition(cmd, &key, &asc,
3223 &ascq)) {
3224 cmd->scsi_status = SAM_STAT_BUSY;
3225 return;
3227 } else if (si->asc == 0) {
3228 WARN_ON_ONCE(cmd->scsi_asc == 0);
3229 asc = cmd->scsi_asc;
3230 ascq = cmd->scsi_ascq;
3231 } else {
3232 asc = si->asc;
3233 ascq = si->ascq;
3236 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
3237 cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3238 cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
3239 scsi_build_sense_buffer(desc_format, buffer, key, asc, ascq);
3240 if (si->add_sector_info)
3241 WARN_ON_ONCE(scsi_set_sense_information(buffer,
3242 cmd->scsi_sense_length,
3243 cmd->bad_sector) < 0);
3247 transport_send_check_condition_and_sense(struct se_cmd *cmd,
3248 sense_reason_t reason, int from_transport)
3250 unsigned long flags;
3252 spin_lock_irqsave(&cmd->t_state_lock, flags);
3253 if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3254 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3255 return 0;
3257 cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
3258 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3260 if (!from_transport)
3261 translate_sense_reason(cmd, reason);
3263 trace_target_cmd_complete(cmd);
3264 return cmd->se_tfo->queue_status(cmd);
3266 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3268 static int __transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3269 __releases(&cmd->t_state_lock)
3270 __acquires(&cmd->t_state_lock)
3272 int ret;
3274 assert_spin_locked(&cmd->t_state_lock);
3275 WARN_ON_ONCE(!irqs_disabled());
3277 if (!(cmd->transport_state & CMD_T_ABORTED))
3278 return 0;
3280 * If cmd has been aborted but either no status is to be sent or it has
3281 * already been sent, just return
3283 if (!send_status || !(cmd->se_cmd_flags & SCF_SEND_DELAYED_TAS)) {
3284 if (send_status)
3285 cmd->se_cmd_flags |= SCF_SEND_DELAYED_TAS;
3286 return 1;
3289 pr_debug("Sending delayed SAM_STAT_TASK_ABORTED status for CDB:"
3290 " 0x%02x ITT: 0x%08llx\n", cmd->t_task_cdb[0], cmd->tag);
3292 cmd->se_cmd_flags &= ~SCF_SEND_DELAYED_TAS;
3293 cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3294 trace_target_cmd_complete(cmd);
3296 spin_unlock_irq(&cmd->t_state_lock);
3297 ret = cmd->se_tfo->queue_status(cmd);
3298 if (ret)
3299 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
3300 spin_lock_irq(&cmd->t_state_lock);
3302 return 1;
3305 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3307 int ret;
3309 spin_lock_irq(&cmd->t_state_lock);
3310 ret = __transport_check_aborted_status(cmd, send_status);
3311 spin_unlock_irq(&cmd->t_state_lock);
3313 return ret;
3315 EXPORT_SYMBOL(transport_check_aborted_status);
3317 void transport_send_task_abort(struct se_cmd *cmd)
3319 unsigned long flags;
3320 int ret;
3322 spin_lock_irqsave(&cmd->t_state_lock, flags);
3323 if (cmd->se_cmd_flags & (SCF_SENT_CHECK_CONDITION)) {
3324 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3325 return;
3327 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3330 * If there are still expected incoming fabric WRITEs, we wait
3331 * until until they have completed before sending a TASK_ABORTED
3332 * response. This response with TASK_ABORTED status will be
3333 * queued back to fabric module by transport_check_aborted_status().
3335 if (cmd->data_direction == DMA_TO_DEVICE) {
3336 if (cmd->se_tfo->write_pending_status(cmd) != 0) {
3337 spin_lock_irqsave(&cmd->t_state_lock, flags);
3338 if (cmd->se_cmd_flags & SCF_SEND_DELAYED_TAS) {
3339 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3340 goto send_abort;
3342 cmd->se_cmd_flags |= SCF_SEND_DELAYED_TAS;
3343 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3344 return;
3347 send_abort:
3348 cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3350 transport_lun_remove_cmd(cmd);
3352 pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x, ITT: 0x%08llx\n",
3353 cmd->t_task_cdb[0], cmd->tag);
3355 trace_target_cmd_complete(cmd);
3356 ret = cmd->se_tfo->queue_status(cmd);
3357 if (ret)
3358 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
3361 static void target_tmr_work(struct work_struct *work)
3363 struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3364 struct se_device *dev = cmd->se_dev;
3365 struct se_tmr_req *tmr = cmd->se_tmr_req;
3366 unsigned long flags;
3367 int ret;
3369 spin_lock_irqsave(&cmd->t_state_lock, flags);
3370 if (cmd->transport_state & CMD_T_ABORTED) {
3371 tmr->response = TMR_FUNCTION_REJECTED;
3372 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3373 goto check_stop;
3375 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3377 switch (tmr->function) {
3378 case TMR_ABORT_TASK:
3379 core_tmr_abort_task(dev, tmr, cmd->se_sess);
3380 break;
3381 case TMR_ABORT_TASK_SET:
3382 case TMR_CLEAR_ACA:
3383 case TMR_CLEAR_TASK_SET:
3384 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3385 break;
3386 case TMR_LUN_RESET:
3387 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3388 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3389 TMR_FUNCTION_REJECTED;
3390 if (tmr->response == TMR_FUNCTION_COMPLETE) {
3391 target_ua_allocate_lun(cmd->se_sess->se_node_acl,
3392 cmd->orig_fe_lun, 0x29,
3393 ASCQ_29H_BUS_DEVICE_RESET_FUNCTION_OCCURRED);
3395 break;
3396 case TMR_TARGET_WARM_RESET:
3397 tmr->response = TMR_FUNCTION_REJECTED;
3398 break;
3399 case TMR_TARGET_COLD_RESET:
3400 tmr->response = TMR_FUNCTION_REJECTED;
3401 break;
3402 default:
3403 pr_err("Unknown TMR function: 0x%02x.\n",
3404 tmr->function);
3405 tmr->response = TMR_FUNCTION_REJECTED;
3406 break;
3409 spin_lock_irqsave(&cmd->t_state_lock, flags);
3410 if (cmd->transport_state & CMD_T_ABORTED) {
3411 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3412 goto check_stop;
3414 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3416 cmd->se_tfo->queue_tm_rsp(cmd);
3418 check_stop:
3419 transport_lun_remove_cmd(cmd);
3420 transport_cmd_check_stop_to_fabric(cmd);
3423 int transport_generic_handle_tmr(
3424 struct se_cmd *cmd)
3426 unsigned long flags;
3427 bool aborted = false;
3429 spin_lock_irqsave(&cmd->t_state_lock, flags);
3430 if (cmd->transport_state & CMD_T_ABORTED) {
3431 aborted = true;
3432 } else {
3433 cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3434 cmd->transport_state |= CMD_T_ACTIVE;
3436 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3438 if (aborted) {
3439 pr_warn_ratelimited("handle_tmr caught CMD_T_ABORTED TMR %d"
3440 "ref_tag: %llu tag: %llu\n", cmd->se_tmr_req->function,
3441 cmd->se_tmr_req->ref_task_tag, cmd->tag);
3442 transport_lun_remove_cmd(cmd);
3443 transport_cmd_check_stop_to_fabric(cmd);
3444 return 0;
3447 INIT_WORK(&cmd->work, target_tmr_work);
3448 queue_work(cmd->se_dev->tmr_wq, &cmd->work);
3449 return 0;
3451 EXPORT_SYMBOL(transport_generic_handle_tmr);
3453 bool
3454 target_check_wce(struct se_device *dev)
3456 bool wce = false;
3458 if (dev->transport->get_write_cache)
3459 wce = dev->transport->get_write_cache(dev);
3460 else if (dev->dev_attrib.emulate_write_cache > 0)
3461 wce = true;
3463 return wce;
3466 bool
3467 target_check_fua(struct se_device *dev)
3469 return target_check_wce(dev) && dev->dev_attrib.emulate_fua_write > 0;