1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*******************************************************************************
3  * Filename:  target_core_transport.c
4  *
5  * This file contains the Generic Target Engine Core.
6  *
7  * (c) Copyright 2002-2013 Datera, Inc.
8  *
9  * Nicholas A. Bellinger <nab@kernel.org>
10  *
11  ******************************************************************************/
12 
13 #include <linux/net.h>
14 #include <linux/delay.h>
15 #include <linux/string.h>
16 #include <linux/timer.h>
17 #include <linux/slab.h>
18 #include <linux/spinlock.h>
19 #include <linux/kthread.h>
20 #include <linux/in.h>
21 #include <linux/cdrom.h>
22 #include <linux/module.h>
23 #include <linux/ratelimit.h>
24 #include <linux/vmalloc.h>
25 #include <asm/unaligned.h>
26 #include <net/sock.h>
27 #include <net/tcp.h>
28 #include <scsi/scsi_proto.h>
29 #include <scsi/scsi_common.h>
30 
31 #include <target/target_core_base.h>
32 #include <target/target_core_backend.h>
33 #include <target/target_core_fabric.h>
34 
35 #include "target_core_internal.h"
36 #include "target_core_alua.h"
37 #include "target_core_pr.h"
38 #include "target_core_ua.h"
39 
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/target.h>
42 
43 static struct workqueue_struct *target_completion_wq;
44 static struct workqueue_struct *target_submission_wq;
45 static struct kmem_cache *se_sess_cache;
46 struct kmem_cache *se_ua_cache;
47 struct kmem_cache *t10_pr_reg_cache;
48 struct kmem_cache *t10_alua_lu_gp_cache;
49 struct kmem_cache *t10_alua_lu_gp_mem_cache;
50 struct kmem_cache *t10_alua_tg_pt_gp_cache;
51 struct kmem_cache *t10_alua_lba_map_cache;
52 struct kmem_cache *t10_alua_lba_map_mem_cache;
53 
54 static void transport_complete_task_attr(struct se_cmd *cmd);
55 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason);
56 static void transport_handle_queue_full(struct se_cmd *cmd,
57 		struct se_device *dev, int err, bool write_pending);
58 static void target_complete_ok_work(struct work_struct *work);
59 
60 int init_se_kmem_caches(void)
61 {
62 	se_sess_cache = kmem_cache_create("se_sess_cache",
63 			sizeof(struct se_session), __alignof__(struct se_session),
64 			0, NULL);
65 	if (!se_sess_cache) {
66 		pr_err("kmem_cache_create() for struct se_session"
67 				" failed\n");
68 		goto out;
69 	}
70 	se_ua_cache = kmem_cache_create("se_ua_cache",
71 			sizeof(struct se_ua), __alignof__(struct se_ua),
72 			0, NULL);
73 	if (!se_ua_cache) {
74 		pr_err("kmem_cache_create() for struct se_ua failed\n");
75 		goto out_free_sess_cache;
76 	}
77 	t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
78 			sizeof(struct t10_pr_registration),
79 			__alignof__(struct t10_pr_registration), 0, NULL);
80 	if (!t10_pr_reg_cache) {
81 		pr_err("kmem_cache_create() for struct t10_pr_registration"
82 				" failed\n");
83 		goto out_free_ua_cache;
84 	}
85 	t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
86 			sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
87 			0, NULL);
88 	if (!t10_alua_lu_gp_cache) {
89 		pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
90 				" failed\n");
91 		goto out_free_pr_reg_cache;
92 	}
93 	t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
94 			sizeof(struct t10_alua_lu_gp_member),
95 			__alignof__(struct t10_alua_lu_gp_member), 0, NULL);
96 	if (!t10_alua_lu_gp_mem_cache) {
97 		pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
98 				"cache failed\n");
99 		goto out_free_lu_gp_cache;
100 	}
101 	t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
102 			sizeof(struct t10_alua_tg_pt_gp),
103 			__alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
104 	if (!t10_alua_tg_pt_gp_cache) {
105 		pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
106 				"cache failed\n");
107 		goto out_free_lu_gp_mem_cache;
108 	}
109 	t10_alua_lba_map_cache = kmem_cache_create(
110 			"t10_alua_lba_map_cache",
111 			sizeof(struct t10_alua_lba_map),
112 			__alignof__(struct t10_alua_lba_map), 0, NULL);
113 	if (!t10_alua_lba_map_cache) {
114 		pr_err("kmem_cache_create() for t10_alua_lba_map_"
115 				"cache failed\n");
116 		goto out_free_tg_pt_gp_cache;
117 	}
118 	t10_alua_lba_map_mem_cache = kmem_cache_create(
119 			"t10_alua_lba_map_mem_cache",
120 			sizeof(struct t10_alua_lba_map_member),
121 			__alignof__(struct t10_alua_lba_map_member), 0, NULL);
122 	if (!t10_alua_lba_map_mem_cache) {
123 		pr_err("kmem_cache_create() for t10_alua_lba_map_mem_"
124 				"cache failed\n");
125 		goto out_free_lba_map_cache;
126 	}
127 
128 	target_completion_wq = alloc_workqueue("target_completion",
129 					       WQ_MEM_RECLAIM, 0);
130 	if (!target_completion_wq)
131 		goto out_free_lba_map_mem_cache;
132 
133 	target_submission_wq = alloc_workqueue("target_submission",
134 					       WQ_MEM_RECLAIM, 0);
135 	if (!target_submission_wq)
136 		goto out_free_completion_wq;
137 
138 	return 0;
139 
140 out_free_completion_wq:
141 	destroy_workqueue(target_completion_wq);
142 out_free_lba_map_mem_cache:
143 	kmem_cache_destroy(t10_alua_lba_map_mem_cache);
144 out_free_lba_map_cache:
145 	kmem_cache_destroy(t10_alua_lba_map_cache);
146 out_free_tg_pt_gp_cache:
147 	kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
148 out_free_lu_gp_mem_cache:
149 	kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
150 out_free_lu_gp_cache:
151 	kmem_cache_destroy(t10_alua_lu_gp_cache);
152 out_free_pr_reg_cache:
153 	kmem_cache_destroy(t10_pr_reg_cache);
154 out_free_ua_cache:
155 	kmem_cache_destroy(se_ua_cache);
156 out_free_sess_cache:
157 	kmem_cache_destroy(se_sess_cache);
158 out:
159 	return -ENOMEM;
160 }
161 
162 void release_se_kmem_caches(void)
163 {
164 	destroy_workqueue(target_submission_wq);
165 	destroy_workqueue(target_completion_wq);
166 	kmem_cache_destroy(se_sess_cache);
167 	kmem_cache_destroy(se_ua_cache);
168 	kmem_cache_destroy(t10_pr_reg_cache);
169 	kmem_cache_destroy(t10_alua_lu_gp_cache);
170 	kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
171 	kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
172 	kmem_cache_destroy(t10_alua_lba_map_cache);
173 	kmem_cache_destroy(t10_alua_lba_map_mem_cache);
174 }
175 
176 /* This code ensures unique mib indexes are handed out. */
177 static DEFINE_SPINLOCK(scsi_mib_index_lock);
178 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
179 
180 /*
181  * Allocate a new row index for the entry type specified
182  */
183 u32 scsi_get_new_index(scsi_index_t type)
184 {
185 	u32 new_index;
186 
187 	BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
188 
189 	spin_lock(&scsi_mib_index_lock);
190 	new_index = ++scsi_mib_index[type];
191 	spin_unlock(&scsi_mib_index_lock);
192 
193 	return new_index;
194 }
195 
196 void transport_subsystem_check_init(void)
197 {
198 	int ret;
199 	static int sub_api_initialized;
200 
201 	if (sub_api_initialized)
202 		return;
203 
204 	ret = IS_ENABLED(CONFIG_TCM_IBLOCK) && request_module("target_core_iblock");
205 	if (ret != 0)
206 		pr_err("Unable to load target_core_iblock\n");
207 
208 	ret = IS_ENABLED(CONFIG_TCM_FILEIO) && request_module("target_core_file");
209 	if (ret != 0)
210 		pr_err("Unable to load target_core_file\n");
211 
212 	ret = IS_ENABLED(CONFIG_TCM_PSCSI) && request_module("target_core_pscsi");
213 	if (ret != 0)
214 		pr_err("Unable to load target_core_pscsi\n");
215 
216 	ret = IS_ENABLED(CONFIG_TCM_USER2) && request_module("target_core_user");
217 	if (ret != 0)
218 		pr_err("Unable to load target_core_user\n");
219 
220 	sub_api_initialized = 1;
221 }
222 
223 static void target_release_cmd_refcnt(struct percpu_ref *ref)
224 {
225 	struct target_cmd_counter *cmd_cnt  = container_of(ref,
226 							   typeof(*cmd_cnt),
227 							   refcnt);
228 	wake_up(&cmd_cnt->refcnt_wq);
229 }
230 
231 struct target_cmd_counter *target_alloc_cmd_counter(void)
232 {
233 	struct target_cmd_counter *cmd_cnt;
234 	int rc;
235 
236 	cmd_cnt = kzalloc(sizeof(*cmd_cnt), GFP_KERNEL);
237 	if (!cmd_cnt)
238 		return NULL;
239 
240 	init_completion(&cmd_cnt->stop_done);
241 	init_waitqueue_head(&cmd_cnt->refcnt_wq);
242 	atomic_set(&cmd_cnt->stopped, 0);
243 
244 	rc = percpu_ref_init(&cmd_cnt->refcnt, target_release_cmd_refcnt, 0,
245 			     GFP_KERNEL);
246 	if (rc)
247 		goto free_cmd_cnt;
248 
249 	return cmd_cnt;
250 
251 free_cmd_cnt:
252 	kfree(cmd_cnt);
253 	return NULL;
254 }
255 EXPORT_SYMBOL_GPL(target_alloc_cmd_counter);
256 
257 void target_free_cmd_counter(struct target_cmd_counter *cmd_cnt)
258 {
259 	/*
260 	 * Drivers like loop do not call target_stop_session during session
261 	 * shutdown so we have to drop the ref taken at init time here.
262 	 */
263 	if (!atomic_read(&cmd_cnt->stopped))
264 		percpu_ref_put(&cmd_cnt->refcnt);
265 
266 	percpu_ref_exit(&cmd_cnt->refcnt);
267 }
268 EXPORT_SYMBOL_GPL(target_free_cmd_counter);
269 
270 /**
271  * transport_init_session - initialize a session object
272  * @se_sess: Session object pointer.
273  *
274  * The caller must have zero-initialized @se_sess before calling this function.
275  */
276 void transport_init_session(struct se_session *se_sess)
277 {
278 	INIT_LIST_HEAD(&se_sess->sess_list);
279 	INIT_LIST_HEAD(&se_sess->sess_acl_list);
280 	spin_lock_init(&se_sess->sess_cmd_lock);
281 }
282 EXPORT_SYMBOL(transport_init_session);
283 
284 /**
285  * transport_alloc_session - allocate a session object and initialize it
286  * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
287  */
288 struct se_session *transport_alloc_session(enum target_prot_op sup_prot_ops)
289 {
290 	struct se_session *se_sess;
291 
292 	se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
293 	if (!se_sess) {
294 		pr_err("Unable to allocate struct se_session from"
295 				" se_sess_cache\n");
296 		return ERR_PTR(-ENOMEM);
297 	}
298 	transport_init_session(se_sess);
299 	se_sess->sup_prot_ops = sup_prot_ops;
300 
301 	return se_sess;
302 }
303 EXPORT_SYMBOL(transport_alloc_session);
304 
305 /**
306  * transport_alloc_session_tags - allocate target driver private data
307  * @se_sess:  Session pointer.
308  * @tag_num:  Maximum number of in-flight commands between initiator and target.
309  * @tag_size: Size in bytes of the private data a target driver associates with
310  *	      each command.
311  */
312 int transport_alloc_session_tags(struct se_session *se_sess,
313 			         unsigned int tag_num, unsigned int tag_size)
314 {
315 	int rc;
316 
317 	se_sess->sess_cmd_map = kvcalloc(tag_size, tag_num,
318 					 GFP_KERNEL | __GFP_RETRY_MAYFAIL);
319 	if (!se_sess->sess_cmd_map) {
320 		pr_err("Unable to allocate se_sess->sess_cmd_map\n");
321 		return -ENOMEM;
322 	}
323 
324 	rc = sbitmap_queue_init_node(&se_sess->sess_tag_pool, tag_num, -1,
325 			false, GFP_KERNEL, NUMA_NO_NODE);
326 	if (rc < 0) {
327 		pr_err("Unable to init se_sess->sess_tag_pool,"
328 			" tag_num: %u\n", tag_num);
329 		kvfree(se_sess->sess_cmd_map);
330 		se_sess->sess_cmd_map = NULL;
331 		return -ENOMEM;
332 	}
333 
334 	return 0;
335 }
336 EXPORT_SYMBOL(transport_alloc_session_tags);
337 
338 /**
339  * transport_init_session_tags - allocate a session and target driver private data
340  * @tag_num:  Maximum number of in-flight commands between initiator and target.
341  * @tag_size: Size in bytes of the private data a target driver associates with
342  *	      each command.
343  * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
344  */
345 static struct se_session *
346 transport_init_session_tags(unsigned int tag_num, unsigned int tag_size,
347 			    enum target_prot_op sup_prot_ops)
348 {
349 	struct se_session *se_sess;
350 	int rc;
351 
352 	if (tag_num != 0 && !tag_size) {
353 		pr_err("init_session_tags called with percpu-ida tag_num:"
354 		       " %u, but zero tag_size\n", tag_num);
355 		return ERR_PTR(-EINVAL);
356 	}
357 	if (!tag_num && tag_size) {
358 		pr_err("init_session_tags called with percpu-ida tag_size:"
359 		       " %u, but zero tag_num\n", tag_size);
360 		return ERR_PTR(-EINVAL);
361 	}
362 
363 	se_sess = transport_alloc_session(sup_prot_ops);
364 	if (IS_ERR(se_sess))
365 		return se_sess;
366 
367 	rc = transport_alloc_session_tags(se_sess, tag_num, tag_size);
368 	if (rc < 0) {
369 		transport_free_session(se_sess);
370 		return ERR_PTR(-ENOMEM);
371 	}
372 
373 	return se_sess;
374 }
375 
376 /*
377  * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
378  */
379 void __transport_register_session(
380 	struct se_portal_group *se_tpg,
381 	struct se_node_acl *se_nacl,
382 	struct se_session *se_sess,
383 	void *fabric_sess_ptr)
384 {
385 	const struct target_core_fabric_ops *tfo = se_tpg->se_tpg_tfo;
386 	unsigned char buf[PR_REG_ISID_LEN];
387 	unsigned long flags;
388 
389 	se_sess->se_tpg = se_tpg;
390 	se_sess->fabric_sess_ptr = fabric_sess_ptr;
391 	/*
392 	 * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
393 	 *
394 	 * Only set for struct se_session's that will actually be moving I/O.
395 	 * eg: *NOT* discovery sessions.
396 	 */
397 	if (se_nacl) {
398 		/*
399 		 *
400 		 * Determine if fabric allows for T10-PI feature bits exposed to
401 		 * initiators for device backends with !dev->dev_attrib.pi_prot_type.
402 		 *
403 		 * If so, then always save prot_type on a per se_node_acl node
404 		 * basis and re-instate the previous sess_prot_type to avoid
405 		 * disabling PI from below any previously initiator side
406 		 * registered LUNs.
407 		 */
408 		if (se_nacl->saved_prot_type)
409 			se_sess->sess_prot_type = se_nacl->saved_prot_type;
410 		else if (tfo->tpg_check_prot_fabric_only)
411 			se_sess->sess_prot_type = se_nacl->saved_prot_type =
412 					tfo->tpg_check_prot_fabric_only(se_tpg);
413 		/*
414 		 * If the fabric module supports an ISID based TransportID,
415 		 * save this value in binary from the fabric I_T Nexus now.
416 		 */
417 		if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
418 			memset(&buf[0], 0, PR_REG_ISID_LEN);
419 			se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
420 					&buf[0], PR_REG_ISID_LEN);
421 			se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
422 		}
423 
424 		spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
425 		/*
426 		 * The se_nacl->nacl_sess pointer will be set to the
427 		 * last active I_T Nexus for each struct se_node_acl.
428 		 */
429 		se_nacl->nacl_sess = se_sess;
430 
431 		list_add_tail(&se_sess->sess_acl_list,
432 			      &se_nacl->acl_sess_list);
433 		spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
434 	}
435 	list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
436 
437 	pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
438 		se_tpg->se_tpg_tfo->fabric_name, se_sess->fabric_sess_ptr);
439 }
440 EXPORT_SYMBOL(__transport_register_session);
441 
442 void transport_register_session(
443 	struct se_portal_group *se_tpg,
444 	struct se_node_acl *se_nacl,
445 	struct se_session *se_sess,
446 	void *fabric_sess_ptr)
447 {
448 	unsigned long flags;
449 
450 	spin_lock_irqsave(&se_tpg->session_lock, flags);
451 	__transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
452 	spin_unlock_irqrestore(&se_tpg->session_lock, flags);
453 }
454 EXPORT_SYMBOL(transport_register_session);
455 
456 struct se_session *
457 target_setup_session(struct se_portal_group *tpg,
458 		     unsigned int tag_num, unsigned int tag_size,
459 		     enum target_prot_op prot_op,
460 		     const char *initiatorname, void *private,
461 		     int (*callback)(struct se_portal_group *,
462 				     struct se_session *, void *))
463 {
464 	struct target_cmd_counter *cmd_cnt;
465 	struct se_session *sess;
466 	int rc;
467 
468 	cmd_cnt = target_alloc_cmd_counter();
469 	if (!cmd_cnt)
470 		return ERR_PTR(-ENOMEM);
471 	/*
472 	 * If the fabric driver is using percpu-ida based pre allocation
473 	 * of I/O descriptor tags, go ahead and perform that setup now..
474 	 */
475 	if (tag_num != 0)
476 		sess = transport_init_session_tags(tag_num, tag_size, prot_op);
477 	else
478 		sess = transport_alloc_session(prot_op);
479 
480 	if (IS_ERR(sess)) {
481 		rc = PTR_ERR(sess);
482 		goto free_cnt;
483 	}
484 	sess->cmd_cnt = cmd_cnt;
485 
486 	sess->se_node_acl = core_tpg_check_initiator_node_acl(tpg,
487 					(unsigned char *)initiatorname);
488 	if (!sess->se_node_acl) {
489 		rc = -EACCES;
490 		goto free_sess;
491 	}
492 	/*
493 	 * Go ahead and perform any remaining fabric setup that is
494 	 * required before transport_register_session().
495 	 */
496 	if (callback != NULL) {
497 		rc = callback(tpg, sess, private);
498 		if (rc)
499 			goto free_sess;
500 	}
501 
502 	transport_register_session(tpg, sess->se_node_acl, sess, private);
503 	return sess;
504 
505 free_sess:
506 	transport_free_session(sess);
507 	return ERR_PTR(rc);
508 
509 free_cnt:
510 	target_free_cmd_counter(cmd_cnt);
511 	return ERR_PTR(rc);
512 }
513 EXPORT_SYMBOL(target_setup_session);
514 
515 ssize_t target_show_dynamic_sessions(struct se_portal_group *se_tpg, char *page)
516 {
517 	struct se_session *se_sess;
518 	ssize_t len = 0;
519 
520 	spin_lock_bh(&se_tpg->session_lock);
521 	list_for_each_entry(se_sess, &se_tpg->tpg_sess_list, sess_list) {
522 		if (!se_sess->se_node_acl)
523 			continue;
524 		if (!se_sess->se_node_acl->dynamic_node_acl)
525 			continue;
526 		if (strlen(se_sess->se_node_acl->initiatorname) + 1 + len > PAGE_SIZE)
527 			break;
528 
529 		len += snprintf(page + len, PAGE_SIZE - len, "%s\n",
530 				se_sess->se_node_acl->initiatorname);
531 		len += 1; /* Include NULL terminator */
532 	}
533 	spin_unlock_bh(&se_tpg->session_lock);
534 
535 	return len;
536 }
537 EXPORT_SYMBOL(target_show_dynamic_sessions);
538 
539 static void target_complete_nacl(struct kref *kref)
540 {
541 	struct se_node_acl *nacl = container_of(kref,
542 				struct se_node_acl, acl_kref);
543 	struct se_portal_group *se_tpg = nacl->se_tpg;
544 
545 	if (!nacl->dynamic_stop) {
546 		complete(&nacl->acl_free_comp);
547 		return;
548 	}
549 
550 	mutex_lock(&se_tpg->acl_node_mutex);
551 	list_del_init(&nacl->acl_list);
552 	mutex_unlock(&se_tpg->acl_node_mutex);
553 
554 	core_tpg_wait_for_nacl_pr_ref(nacl);
555 	core_free_device_list_for_node(nacl, se_tpg);
556 	kfree(nacl);
557 }
558 
559 void target_put_nacl(struct se_node_acl *nacl)
560 {
561 	kref_put(&nacl->acl_kref, target_complete_nacl);
562 }
563 EXPORT_SYMBOL(target_put_nacl);
564 
565 void transport_deregister_session_configfs(struct se_session *se_sess)
566 {
567 	struct se_node_acl *se_nacl;
568 	unsigned long flags;
569 	/*
570 	 * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
571 	 */
572 	se_nacl = se_sess->se_node_acl;
573 	if (se_nacl) {
574 		spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
575 		if (!list_empty(&se_sess->sess_acl_list))
576 			list_del_init(&se_sess->sess_acl_list);
577 		/*
578 		 * If the session list is empty, then clear the pointer.
579 		 * Otherwise, set the struct se_session pointer from the tail
580 		 * element of the per struct se_node_acl active session list.
581 		 */
582 		if (list_empty(&se_nacl->acl_sess_list))
583 			se_nacl->nacl_sess = NULL;
584 		else {
585 			se_nacl->nacl_sess = container_of(
586 					se_nacl->acl_sess_list.prev,
587 					struct se_session, sess_acl_list);
588 		}
589 		spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
590 	}
591 }
592 EXPORT_SYMBOL(transport_deregister_session_configfs);
593 
594 void transport_free_session(struct se_session *se_sess)
595 {
596 	struct se_node_acl *se_nacl = se_sess->se_node_acl;
597 
598 	/*
599 	 * Drop the se_node_acl->nacl_kref obtained from within
600 	 * core_tpg_get_initiator_node_acl().
601 	 */
602 	if (se_nacl) {
603 		struct se_portal_group *se_tpg = se_nacl->se_tpg;
604 		const struct target_core_fabric_ops *se_tfo = se_tpg->se_tpg_tfo;
605 		unsigned long flags;
606 
607 		se_sess->se_node_acl = NULL;
608 
609 		/*
610 		 * Also determine if we need to drop the extra ->cmd_kref if
611 		 * it had been previously dynamically generated, and
612 		 * the endpoint is not caching dynamic ACLs.
613 		 */
614 		mutex_lock(&se_tpg->acl_node_mutex);
615 		if (se_nacl->dynamic_node_acl &&
616 		    !se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
617 			spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
618 			if (list_empty(&se_nacl->acl_sess_list))
619 				se_nacl->dynamic_stop = true;
620 			spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
621 
622 			if (se_nacl->dynamic_stop)
623 				list_del_init(&se_nacl->acl_list);
624 		}
625 		mutex_unlock(&se_tpg->acl_node_mutex);
626 
627 		if (se_nacl->dynamic_stop)
628 			target_put_nacl(se_nacl);
629 
630 		target_put_nacl(se_nacl);
631 	}
632 	if (se_sess->sess_cmd_map) {
633 		sbitmap_queue_free(&se_sess->sess_tag_pool);
634 		kvfree(se_sess->sess_cmd_map);
635 	}
636 	if (se_sess->cmd_cnt)
637 		target_free_cmd_counter(se_sess->cmd_cnt);
638 	kmem_cache_free(se_sess_cache, se_sess);
639 }
640 EXPORT_SYMBOL(transport_free_session);
641 
642 static int target_release_res(struct se_device *dev, void *data)
643 {
644 	struct se_session *sess = data;
645 
646 	if (dev->reservation_holder == sess)
647 		target_release_reservation(dev);
648 	return 0;
649 }
650 
651 void transport_deregister_session(struct se_session *se_sess)
652 {
653 	struct se_portal_group *se_tpg = se_sess->se_tpg;
654 	unsigned long flags;
655 
656 	if (!se_tpg) {
657 		transport_free_session(se_sess);
658 		return;
659 	}
660 
661 	spin_lock_irqsave(&se_tpg->session_lock, flags);
662 	list_del(&se_sess->sess_list);
663 	se_sess->se_tpg = NULL;
664 	se_sess->fabric_sess_ptr = NULL;
665 	spin_unlock_irqrestore(&se_tpg->session_lock, flags);
666 
667 	/*
668 	 * Since the session is being removed, release SPC-2
669 	 * reservations held by the session that is disappearing.
670 	 */
671 	target_for_each_device(target_release_res, se_sess);
672 
673 	pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
674 		se_tpg->se_tpg_tfo->fabric_name);
675 	/*
676 	 * If last kref is dropping now for an explicit NodeACL, awake sleeping
677 	 * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
678 	 * removal context from within transport_free_session() code.
679 	 *
680 	 * For dynamic ACL, target_put_nacl() uses target_complete_nacl()
681 	 * to release all remaining generate_node_acl=1 created ACL resources.
682 	 */
683 
684 	transport_free_session(se_sess);
685 }
686 EXPORT_SYMBOL(transport_deregister_session);
687 
688 void target_remove_session(struct se_session *se_sess)
689 {
690 	transport_deregister_session_configfs(se_sess);
691 	transport_deregister_session(se_sess);
692 }
693 EXPORT_SYMBOL(target_remove_session);
694 
695 static void target_remove_from_state_list(struct se_cmd *cmd)
696 {
697 	struct se_device *dev = cmd->se_dev;
698 	unsigned long flags;
699 
700 	if (!dev)
701 		return;
702 
703 	spin_lock_irqsave(&dev->queues[cmd->cpuid].lock, flags);
704 	if (cmd->state_active) {
705 		list_del(&cmd->state_list);
706 		cmd->state_active = false;
707 	}
708 	spin_unlock_irqrestore(&dev->queues[cmd->cpuid].lock, flags);
709 }
710 
711 static void target_remove_from_tmr_list(struct se_cmd *cmd)
712 {
713 	struct se_device *dev = NULL;
714 	unsigned long flags;
715 
716 	if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
717 		dev = cmd->se_tmr_req->tmr_dev;
718 
719 	if (dev) {
720 		spin_lock_irqsave(&dev->se_tmr_lock, flags);
721 		if (cmd->se_tmr_req->tmr_dev)
722 			list_del_init(&cmd->se_tmr_req->tmr_list);
723 		spin_unlock_irqrestore(&dev->se_tmr_lock, flags);
724 	}
725 }
726 /*
727  * This function is called by the target core after the target core has
728  * finished processing a SCSI command or SCSI TMF. Both the regular command
729  * processing code and the code for aborting commands can call this
730  * function. CMD_T_STOP is set if and only if another thread is waiting
731  * inside transport_wait_for_tasks() for t_transport_stop_comp.
732  */
733 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
734 {
735 	unsigned long flags;
736 
737 	spin_lock_irqsave(&cmd->t_state_lock, flags);
738 	/*
739 	 * Determine if frontend context caller is requesting the stopping of
740 	 * this command for frontend exceptions.
741 	 */
742 	if (cmd->transport_state & CMD_T_STOP) {
743 		pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
744 			__func__, __LINE__, cmd->tag);
745 
746 		spin_unlock_irqrestore(&cmd->t_state_lock, flags);
747 
748 		complete_all(&cmd->t_transport_stop_comp);
749 		return 1;
750 	}
751 	cmd->transport_state &= ~CMD_T_ACTIVE;
752 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
753 
754 	/*
755 	 * Some fabric modules like tcm_loop can release their internally
756 	 * allocated I/O reference and struct se_cmd now.
757 	 *
758 	 * Fabric modules are expected to return '1' here if the se_cmd being
759 	 * passed is released at this point, or zero if not being released.
760 	 */
761 	return cmd->se_tfo->check_stop_free(cmd);
762 }
763 
764 static void transport_lun_remove_cmd(struct se_cmd *cmd)
765 {
766 	struct se_lun *lun = cmd->se_lun;
767 
768 	if (!lun)
769 		return;
770 
771 	target_remove_from_state_list(cmd);
772 	target_remove_from_tmr_list(cmd);
773 
774 	if (cmpxchg(&cmd->lun_ref_active, true, false))
775 		percpu_ref_put(&lun->lun_ref);
776 
777 	/*
778 	 * Clear struct se_cmd->se_lun before the handoff to FE.
779 	 */
780 	cmd->se_lun = NULL;
781 }
782 
783 static void target_complete_failure_work(struct work_struct *work)
784 {
785 	struct se_cmd *cmd = container_of(work, struct se_cmd, work);
786 
787 	transport_generic_request_failure(cmd, cmd->sense_reason);
788 }
789 
790 /*
791  * Used when asking transport to copy Sense Data from the underlying
792  * Linux/SCSI struct scsi_cmnd
793  */
794 static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd)
795 {
796 	struct se_device *dev = cmd->se_dev;
797 
798 	WARN_ON(!cmd->se_lun);
799 
800 	if (!dev)
801 		return NULL;
802 
803 	if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION)
804 		return NULL;
805 
806 	cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
807 
808 	pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n",
809 		dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
810 	return cmd->sense_buffer;
811 }
812 
813 void transport_copy_sense_to_cmd(struct se_cmd *cmd, unsigned char *sense)
814 {
815 	unsigned char *cmd_sense_buf;
816 	unsigned long flags;
817 
818 	spin_lock_irqsave(&cmd->t_state_lock, flags);
819 	cmd_sense_buf = transport_get_sense_buffer(cmd);
820 	if (!cmd_sense_buf) {
821 		spin_unlock_irqrestore(&cmd->t_state_lock, flags);
822 		return;
823 	}
824 
825 	cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
826 	memcpy(cmd_sense_buf, sense, cmd->scsi_sense_length);
827 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
828 }
829 EXPORT_SYMBOL(transport_copy_sense_to_cmd);
830 
831 static void target_handle_abort(struct se_cmd *cmd)
832 {
833 	bool tas = cmd->transport_state & CMD_T_TAS;
834 	bool ack_kref = cmd->se_cmd_flags & SCF_ACK_KREF;
835 	int ret;
836 
837 	pr_debug("tag %#llx: send_abort_response = %d\n", cmd->tag, tas);
838 
839 	if (tas) {
840 		if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
841 			cmd->scsi_status = SAM_STAT_TASK_ABORTED;
842 			pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x, ITT: 0x%08llx\n",
843 				 cmd->t_task_cdb[0], cmd->tag);
844 			trace_target_cmd_complete(cmd);
845 			ret = cmd->se_tfo->queue_status(cmd);
846 			if (ret) {
847 				transport_handle_queue_full(cmd, cmd->se_dev,
848 							    ret, false);
849 				return;
850 			}
851 		} else {
852 			cmd->se_tmr_req->response = TMR_FUNCTION_REJECTED;
853 			cmd->se_tfo->queue_tm_rsp(cmd);
854 		}
855 	} else {
856 		/*
857 		 * Allow the fabric driver to unmap any resources before
858 		 * releasing the descriptor via TFO->release_cmd().
859 		 */
860 		cmd->se_tfo->aborted_task(cmd);
861 		if (ack_kref)
862 			WARN_ON_ONCE(target_put_sess_cmd(cmd) != 0);
863 		/*
864 		 * To do: establish a unit attention condition on the I_T
865 		 * nexus associated with cmd. See also the paragraph "Aborting
866 		 * commands" in SAM.
867 		 */
868 	}
869 
870 	WARN_ON_ONCE(kref_read(&cmd->cmd_kref) == 0);
871 
872 	transport_lun_remove_cmd(cmd);
873 
874 	transport_cmd_check_stop_to_fabric(cmd);
875 }
876 
877 static void target_abort_work(struct work_struct *work)
878 {
879 	struct se_cmd *cmd = container_of(work, struct se_cmd, work);
880 
881 	target_handle_abort(cmd);
882 }
883 
884 static bool target_cmd_interrupted(struct se_cmd *cmd)
885 {
886 	int post_ret;
887 
888 	if (cmd->transport_state & CMD_T_ABORTED) {
889 		if (cmd->transport_complete_callback)
890 			cmd->transport_complete_callback(cmd, false, &post_ret);
891 		INIT_WORK(&cmd->work, target_abort_work);
892 		queue_work(target_completion_wq, &cmd->work);
893 		return true;
894 	} else if (cmd->transport_state & CMD_T_STOP) {
895 		if (cmd->transport_complete_callback)
896 			cmd->transport_complete_callback(cmd, false, &post_ret);
897 		complete_all(&cmd->t_transport_stop_comp);
898 		return true;
899 	}
900 
901 	return false;
902 }
903 
904 /* May be called from interrupt context so must not sleep. */
905 void target_complete_cmd_with_sense(struct se_cmd *cmd, u8 scsi_status,
906 				    sense_reason_t sense_reason)
907 {
908 	struct se_wwn *wwn = cmd->se_sess->se_tpg->se_tpg_wwn;
909 	int success, cpu;
910 	unsigned long flags;
911 
912 	if (target_cmd_interrupted(cmd))
913 		return;
914 
915 	cmd->scsi_status = scsi_status;
916 	cmd->sense_reason = sense_reason;
917 
918 	spin_lock_irqsave(&cmd->t_state_lock, flags);
919 	switch (cmd->scsi_status) {
920 	case SAM_STAT_CHECK_CONDITION:
921 		if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
922 			success = 1;
923 		else
924 			success = 0;
925 		break;
926 	default:
927 		success = 1;
928 		break;
929 	}
930 
931 	cmd->t_state = TRANSPORT_COMPLETE;
932 	cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
933 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
934 
935 	INIT_WORK(&cmd->work, success ? target_complete_ok_work :
936 		  target_complete_failure_work);
937 
938 	if (!wwn || wwn->cmd_compl_affinity == SE_COMPL_AFFINITY_CPUID)
939 		cpu = cmd->cpuid;
940 	else
941 		cpu = wwn->cmd_compl_affinity;
942 
943 	queue_work_on(cpu, target_completion_wq, &cmd->work);
944 }
945 EXPORT_SYMBOL(target_complete_cmd_with_sense);
946 
947 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
948 {
949 	target_complete_cmd_with_sense(cmd, scsi_status, scsi_status ?
950 			      TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE :
951 			      TCM_NO_SENSE);
952 }
953 EXPORT_SYMBOL(target_complete_cmd);
954 
955 void target_set_cmd_data_length(struct se_cmd *cmd, int length)
956 {
957 	if (length < cmd->data_length) {
958 		if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
959 			cmd->residual_count += cmd->data_length - length;
960 		} else {
961 			cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
962 			cmd->residual_count = cmd->data_length - length;
963 		}
964 
965 		cmd->data_length = length;
966 	}
967 }
968 EXPORT_SYMBOL(target_set_cmd_data_length);
969 
970 void target_complete_cmd_with_length(struct se_cmd *cmd, u8 scsi_status, int length)
971 {
972 	if (scsi_status == SAM_STAT_GOOD ||
973 	    cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) {
974 		target_set_cmd_data_length(cmd, length);
975 	}
976 
977 	target_complete_cmd(cmd, scsi_status);
978 }
979 EXPORT_SYMBOL(target_complete_cmd_with_length);
980 
981 static void target_add_to_state_list(struct se_cmd *cmd)
982 {
983 	struct se_device *dev = cmd->se_dev;
984 	unsigned long flags;
985 
986 	spin_lock_irqsave(&dev->queues[cmd->cpuid].lock, flags);
987 	if (!cmd->state_active) {
988 		list_add_tail(&cmd->state_list,
989 			      &dev->queues[cmd->cpuid].state_list);
990 		cmd->state_active = true;
991 	}
992 	spin_unlock_irqrestore(&dev->queues[cmd->cpuid].lock, flags);
993 }
994 
995 /*
996  * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
997  */
998 static void transport_write_pending_qf(struct se_cmd *cmd);
999 static void transport_complete_qf(struct se_cmd *cmd);
1000 
1001 void target_qf_do_work(struct work_struct *work)
1002 {
1003 	struct se_device *dev = container_of(work, struct se_device,
1004 					qf_work_queue);
1005 	LIST_HEAD(qf_cmd_list);
1006 	struct se_cmd *cmd, *cmd_tmp;
1007 
1008 	spin_lock_irq(&dev->qf_cmd_lock);
1009 	list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
1010 	spin_unlock_irq(&dev->qf_cmd_lock);
1011 
1012 	list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
1013 		list_del(&cmd->se_qf_node);
1014 		atomic_dec_mb(&dev->dev_qf_count);
1015 
1016 		pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
1017 			" context: %s\n", cmd->se_tfo->fabric_name, cmd,
1018 			(cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
1019 			(cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
1020 			: "UNKNOWN");
1021 
1022 		if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
1023 			transport_write_pending_qf(cmd);
1024 		else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK ||
1025 			 cmd->t_state == TRANSPORT_COMPLETE_QF_ERR)
1026 			transport_complete_qf(cmd);
1027 	}
1028 }
1029 
1030 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
1031 {
1032 	switch (cmd->data_direction) {
1033 	case DMA_NONE:
1034 		return "NONE";
1035 	case DMA_FROM_DEVICE:
1036 		return "READ";
1037 	case DMA_TO_DEVICE:
1038 		return "WRITE";
1039 	case DMA_BIDIRECTIONAL:
1040 		return "BIDI";
1041 	default:
1042 		break;
1043 	}
1044 
1045 	return "UNKNOWN";
1046 }
1047 
1048 void transport_dump_dev_state(
1049 	struct se_device *dev,
1050 	char *b,
1051 	int *bl)
1052 {
1053 	*bl += sprintf(b + *bl, "Status: ");
1054 	if (dev->export_count)
1055 		*bl += sprintf(b + *bl, "ACTIVATED");
1056 	else
1057 		*bl += sprintf(b + *bl, "DEACTIVATED");
1058 
1059 	*bl += sprintf(b + *bl, "  Max Queue Depth: %d", dev->queue_depth);
1060 	*bl += sprintf(b + *bl, "  SectorSize: %u  HwMaxSectors: %u\n",
1061 		dev->dev_attrib.block_size,
1062 		dev->dev_attrib.hw_max_sectors);
1063 	*bl += sprintf(b + *bl, "        ");
1064 }
1065 
1066 void transport_dump_vpd_proto_id(
1067 	struct t10_vpd *vpd,
1068 	unsigned char *p_buf,
1069 	int p_buf_len)
1070 {
1071 	unsigned char buf[VPD_TMP_BUF_SIZE];
1072 	int len;
1073 
1074 	memset(buf, 0, VPD_TMP_BUF_SIZE);
1075 	len = sprintf(buf, "T10 VPD Protocol Identifier: ");
1076 
1077 	switch (vpd->protocol_identifier) {
1078 	case 0x00:
1079 		sprintf(buf+len, "Fibre Channel\n");
1080 		break;
1081 	case 0x10:
1082 		sprintf(buf+len, "Parallel SCSI\n");
1083 		break;
1084 	case 0x20:
1085 		sprintf(buf+len, "SSA\n");
1086 		break;
1087 	case 0x30:
1088 		sprintf(buf+len, "IEEE 1394\n");
1089 		break;
1090 	case 0x40:
1091 		sprintf(buf+len, "SCSI Remote Direct Memory Access"
1092 				" Protocol\n");
1093 		break;
1094 	case 0x50:
1095 		sprintf(buf+len, "Internet SCSI (iSCSI)\n");
1096 		break;
1097 	case 0x60:
1098 		sprintf(buf+len, "SAS Serial SCSI Protocol\n");
1099 		break;
1100 	case 0x70:
1101 		sprintf(buf+len, "Automation/Drive Interface Transport"
1102 				" Protocol\n");
1103 		break;
1104 	case 0x80:
1105 		sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
1106 		break;
1107 	default:
1108 		sprintf(buf+len, "Unknown 0x%02x\n",
1109 				vpd->protocol_identifier);
1110 		break;
1111 	}
1112 
1113 	if (p_buf)
1114 		strncpy(p_buf, buf, p_buf_len);
1115 	else
1116 		pr_debug("%s", buf);
1117 }
1118 
1119 void
1120 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1121 {
1122 	/*
1123 	 * Check if the Protocol Identifier Valid (PIV) bit is set..
1124 	 *
1125 	 * from spc3r23.pdf section 7.5.1
1126 	 */
1127 	 if (page_83[1] & 0x80) {
1128 		vpd->protocol_identifier = (page_83[0] & 0xf0);
1129 		vpd->protocol_identifier_set = 1;
1130 		transport_dump_vpd_proto_id(vpd, NULL, 0);
1131 	}
1132 }
1133 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1134 
1135 int transport_dump_vpd_assoc(
1136 	struct t10_vpd *vpd,
1137 	unsigned char *p_buf,
1138 	int p_buf_len)
1139 {
1140 	unsigned char buf[VPD_TMP_BUF_SIZE];
1141 	int ret = 0;
1142 	int len;
1143 
1144 	memset(buf, 0, VPD_TMP_BUF_SIZE);
1145 	len = sprintf(buf, "T10 VPD Identifier Association: ");
1146 
1147 	switch (vpd->association) {
1148 	case 0x00:
1149 		sprintf(buf+len, "addressed logical unit\n");
1150 		break;
1151 	case 0x10:
1152 		sprintf(buf+len, "target port\n");
1153 		break;
1154 	case 0x20:
1155 		sprintf(buf+len, "SCSI target device\n");
1156 		break;
1157 	default:
1158 		sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1159 		ret = -EINVAL;
1160 		break;
1161 	}
1162 
1163 	if (p_buf)
1164 		strncpy(p_buf, buf, p_buf_len);
1165 	else
1166 		pr_debug("%s", buf);
1167 
1168 	return ret;
1169 }
1170 
1171 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1172 {
1173 	/*
1174 	 * The VPD identification association..
1175 	 *
1176 	 * from spc3r23.pdf Section 7.6.3.1 Table 297
1177 	 */
1178 	vpd->association = (page_83[1] & 0x30);
1179 	return transport_dump_vpd_assoc(vpd, NULL, 0);
1180 }
1181 EXPORT_SYMBOL(transport_set_vpd_assoc);
1182 
1183 int transport_dump_vpd_ident_type(
1184 	struct t10_vpd *vpd,
1185 	unsigned char *p_buf,
1186 	int p_buf_len)
1187 {
1188 	unsigned char buf[VPD_TMP_BUF_SIZE];
1189 	int ret = 0;
1190 	int len;
1191 
1192 	memset(buf, 0, VPD_TMP_BUF_SIZE);
1193 	len = sprintf(buf, "T10 VPD Identifier Type: ");
1194 
1195 	switch (vpd->device_identifier_type) {
1196 	case 0x00:
1197 		sprintf(buf+len, "Vendor specific\n");
1198 		break;
1199 	case 0x01:
1200 		sprintf(buf+len, "T10 Vendor ID based\n");
1201 		break;
1202 	case 0x02:
1203 		sprintf(buf+len, "EUI-64 based\n");
1204 		break;
1205 	case 0x03:
1206 		sprintf(buf+len, "NAA\n");
1207 		break;
1208 	case 0x04:
1209 		sprintf(buf+len, "Relative target port identifier\n");
1210 		break;
1211 	case 0x08:
1212 		sprintf(buf+len, "SCSI name string\n");
1213 		break;
1214 	default:
1215 		sprintf(buf+len, "Unsupported: 0x%02x\n",
1216 				vpd->device_identifier_type);
1217 		ret = -EINVAL;
1218 		break;
1219 	}
1220 
1221 	if (p_buf) {
1222 		if (p_buf_len < strlen(buf)+1)
1223 			return -EINVAL;
1224 		strncpy(p_buf, buf, p_buf_len);
1225 	} else {
1226 		pr_debug("%s", buf);
1227 	}
1228 
1229 	return ret;
1230 }
1231 
1232 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1233 {
1234 	/*
1235 	 * The VPD identifier type..
1236 	 *
1237 	 * from spc3r23.pdf Section 7.6.3.1 Table 298
1238 	 */
1239 	vpd->device_identifier_type = (page_83[1] & 0x0f);
1240 	return transport_dump_vpd_ident_type(vpd, NULL, 0);
1241 }
1242 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1243 
1244 int transport_dump_vpd_ident(
1245 	struct t10_vpd *vpd,
1246 	unsigned char *p_buf,
1247 	int p_buf_len)
1248 {
1249 	unsigned char buf[VPD_TMP_BUF_SIZE];
1250 	int ret = 0;
1251 
1252 	memset(buf, 0, VPD_TMP_BUF_SIZE);
1253 
1254 	switch (vpd->device_identifier_code_set) {
1255 	case 0x01: /* Binary */
1256 		snprintf(buf, sizeof(buf),
1257 			"T10 VPD Binary Device Identifier: %s\n",
1258 			&vpd->device_identifier[0]);
1259 		break;
1260 	case 0x02: /* ASCII */
1261 		snprintf(buf, sizeof(buf),
1262 			"T10 VPD ASCII Device Identifier: %s\n",
1263 			&vpd->device_identifier[0]);
1264 		break;
1265 	case 0x03: /* UTF-8 */
1266 		snprintf(buf, sizeof(buf),
1267 			"T10 VPD UTF-8 Device Identifier: %s\n",
1268 			&vpd->device_identifier[0]);
1269 		break;
1270 	default:
1271 		sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1272 			" 0x%02x", vpd->device_identifier_code_set);
1273 		ret = -EINVAL;
1274 		break;
1275 	}
1276 
1277 	if (p_buf)
1278 		strncpy(p_buf, buf, p_buf_len);
1279 	else
1280 		pr_debug("%s", buf);
1281 
1282 	return ret;
1283 }
1284 
1285 int
1286 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1287 {
1288 	static const char hex_str[] = "0123456789abcdef";
1289 	int j = 0, i = 4; /* offset to start of the identifier */
1290 
1291 	/*
1292 	 * The VPD Code Set (encoding)
1293 	 *
1294 	 * from spc3r23.pdf Section 7.6.3.1 Table 296
1295 	 */
1296 	vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1297 	switch (vpd->device_identifier_code_set) {
1298 	case 0x01: /* Binary */
1299 		vpd->device_identifier[j++] =
1300 				hex_str[vpd->device_identifier_type];
1301 		while (i < (4 + page_83[3])) {
1302 			vpd->device_identifier[j++] =
1303 				hex_str[(page_83[i] & 0xf0) >> 4];
1304 			vpd->device_identifier[j++] =
1305 				hex_str[page_83[i] & 0x0f];
1306 			i++;
1307 		}
1308 		break;
1309 	case 0x02: /* ASCII */
1310 	case 0x03: /* UTF-8 */
1311 		while (i < (4 + page_83[3]))
1312 			vpd->device_identifier[j++] = page_83[i++];
1313 		break;
1314 	default:
1315 		break;
1316 	}
1317 
1318 	return transport_dump_vpd_ident(vpd, NULL, 0);
1319 }
1320 EXPORT_SYMBOL(transport_set_vpd_ident);
1321 
1322 static sense_reason_t
1323 target_check_max_data_sg_nents(struct se_cmd *cmd, struct se_device *dev,
1324 			       unsigned int size)
1325 {
1326 	u32 mtl;
1327 
1328 	if (!cmd->se_tfo->max_data_sg_nents)
1329 		return TCM_NO_SENSE;
1330 	/*
1331 	 * Check if fabric enforced maximum SGL entries per I/O descriptor
1332 	 * exceeds se_cmd->data_length.  If true, set SCF_UNDERFLOW_BIT +
1333 	 * residual_count and reduce original cmd->data_length to maximum
1334 	 * length based on single PAGE_SIZE entry scatter-lists.
1335 	 */
1336 	mtl = (cmd->se_tfo->max_data_sg_nents * PAGE_SIZE);
1337 	if (cmd->data_length > mtl) {
1338 		/*
1339 		 * If an existing CDB overflow is present, calculate new residual
1340 		 * based on CDB size minus fabric maximum transfer length.
1341 		 *
1342 		 * If an existing CDB underflow is present, calculate new residual
1343 		 * based on original cmd->data_length minus fabric maximum transfer
1344 		 * length.
1345 		 *
1346 		 * Otherwise, set the underflow residual based on cmd->data_length
1347 		 * minus fabric maximum transfer length.
1348 		 */
1349 		if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1350 			cmd->residual_count = (size - mtl);
1351 		} else if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
1352 			u32 orig_dl = size + cmd->residual_count;
1353 			cmd->residual_count = (orig_dl - mtl);
1354 		} else {
1355 			cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1356 			cmd->residual_count = (cmd->data_length - mtl);
1357 		}
1358 		cmd->data_length = mtl;
1359 		/*
1360 		 * Reset sbc_check_prot() calculated protection payload
1361 		 * length based upon the new smaller MTL.
1362 		 */
1363 		if (cmd->prot_length) {
1364 			u32 sectors = (mtl / dev->dev_attrib.block_size);
1365 			cmd->prot_length = dev->prot_length * sectors;
1366 		}
1367 	}
1368 	return TCM_NO_SENSE;
1369 }
1370 
1371 /**
1372  * target_cmd_size_check - Check whether there will be a residual.
1373  * @cmd: SCSI command.
1374  * @size: Data buffer size derived from CDB. The data buffer size provided by
1375  *   the SCSI transport driver is available in @cmd->data_length.
1376  *
1377  * Compare the data buffer size from the CDB with the data buffer limit from the transport
1378  * header. Set @cmd->residual_count and SCF_OVERFLOW_BIT or SCF_UNDERFLOW_BIT if necessary.
1379  *
1380  * Note: target drivers set @cmd->data_length by calling __target_init_cmd().
1381  *
1382  * Return: TCM_NO_SENSE
1383  */
1384 sense_reason_t
1385 target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1386 {
1387 	struct se_device *dev = cmd->se_dev;
1388 
1389 	if (cmd->unknown_data_length) {
1390 		cmd->data_length = size;
1391 	} else if (size != cmd->data_length) {
1392 		pr_warn_ratelimited("TARGET_CORE[%s]: Expected Transfer Length:"
1393 			" %u does not match SCSI CDB Length: %u for SAM Opcode:"
1394 			" 0x%02x\n", cmd->se_tfo->fabric_name,
1395 				cmd->data_length, size, cmd->t_task_cdb[0]);
1396 		/*
1397 		 * For READ command for the overflow case keep the existing
1398 		 * fabric provided ->data_length. Otherwise for the underflow
1399 		 * case, reset ->data_length to the smaller SCSI expected data
1400 		 * transfer length.
1401 		 */
1402 		if (size > cmd->data_length) {
1403 			cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1404 			cmd->residual_count = (size - cmd->data_length);
1405 		} else {
1406 			cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1407 			cmd->residual_count = (cmd->data_length - size);
1408 			/*
1409 			 * Do not truncate ->data_length for WRITE command to
1410 			 * dump all payload
1411 			 */
1412 			if (cmd->data_direction == DMA_FROM_DEVICE) {
1413 				cmd->data_length = size;
1414 			}
1415 		}
1416 
1417 		if (cmd->data_direction == DMA_TO_DEVICE) {
1418 			if (cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) {
1419 				pr_err_ratelimited("Rejecting underflow/overflow"
1420 						   " for WRITE data CDB\n");
1421 				return TCM_INVALID_FIELD_IN_COMMAND_IU;
1422 			}
1423 			/*
1424 			 * Some fabric drivers like iscsi-target still expect to
1425 			 * always reject overflow writes.  Reject this case until
1426 			 * full fabric driver level support for overflow writes
1427 			 * is introduced tree-wide.
1428 			 */
1429 			if (size > cmd->data_length) {
1430 				pr_err_ratelimited("Rejecting overflow for"
1431 						   " WRITE control CDB\n");
1432 				return TCM_INVALID_CDB_FIELD;
1433 			}
1434 		}
1435 	}
1436 
1437 	return target_check_max_data_sg_nents(cmd, dev, size);
1438 
1439 }
1440 
1441 /*
1442  * Used by fabric modules containing a local struct se_cmd within their
1443  * fabric dependent per I/O descriptor.
1444  *
1445  * Preserves the value of @cmd->tag.
1446  */
1447 void __target_init_cmd(struct se_cmd *cmd,
1448 		       const struct target_core_fabric_ops *tfo,
1449 		       struct se_session *se_sess, u32 data_length,
1450 		       int data_direction, int task_attr,
1451 		       unsigned char *sense_buffer, u64 unpacked_lun,
1452 		       struct target_cmd_counter *cmd_cnt)
1453 {
1454 	INIT_LIST_HEAD(&cmd->se_delayed_node);
1455 	INIT_LIST_HEAD(&cmd->se_qf_node);
1456 	INIT_LIST_HEAD(&cmd->state_list);
1457 	init_completion(&cmd->t_transport_stop_comp);
1458 	cmd->free_compl = NULL;
1459 	cmd->abrt_compl = NULL;
1460 	spin_lock_init(&cmd->t_state_lock);
1461 	INIT_WORK(&cmd->work, NULL);
1462 	kref_init(&cmd->cmd_kref);
1463 
1464 	cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1465 	cmd->se_tfo = tfo;
1466 	cmd->se_sess = se_sess;
1467 	cmd->data_length = data_length;
1468 	cmd->data_direction = data_direction;
1469 	cmd->sam_task_attr = task_attr;
1470 	cmd->sense_buffer = sense_buffer;
1471 	cmd->orig_fe_lun = unpacked_lun;
1472 	cmd->cmd_cnt = cmd_cnt;
1473 
1474 	if (!(cmd->se_cmd_flags & SCF_USE_CPUID))
1475 		cmd->cpuid = raw_smp_processor_id();
1476 
1477 	cmd->state_active = false;
1478 }
1479 EXPORT_SYMBOL(__target_init_cmd);
1480 
1481 static sense_reason_t
1482 transport_check_alloc_task_attr(struct se_cmd *cmd)
1483 {
1484 	struct se_device *dev = cmd->se_dev;
1485 
1486 	/*
1487 	 * Check if SAM Task Attribute emulation is enabled for this
1488 	 * struct se_device storage object
1489 	 */
1490 	if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1491 		return 0;
1492 
1493 	if (cmd->sam_task_attr == TCM_ACA_TAG) {
1494 		pr_debug("SAM Task Attribute ACA"
1495 			" emulation is not supported\n");
1496 		return TCM_INVALID_CDB_FIELD;
1497 	}
1498 
1499 	return 0;
1500 }
1501 
1502 sense_reason_t
1503 target_cmd_init_cdb(struct se_cmd *cmd, unsigned char *cdb, gfp_t gfp)
1504 {
1505 	sense_reason_t ret;
1506 
1507 	/*
1508 	 * Ensure that the received CDB is less than the max (252 + 8) bytes
1509 	 * for VARIABLE_LENGTH_CMD
1510 	 */
1511 	if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1512 		pr_err("Received SCSI CDB with command_size: %d that"
1513 			" exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1514 			scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1515 		ret = TCM_INVALID_CDB_FIELD;
1516 		goto err;
1517 	}
1518 	/*
1519 	 * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1520 	 * allocate the additional extended CDB buffer now..  Otherwise
1521 	 * setup the pointer from __t_task_cdb to t_task_cdb.
1522 	 */
1523 	if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1524 		cmd->t_task_cdb = kzalloc(scsi_command_size(cdb), gfp);
1525 		if (!cmd->t_task_cdb) {
1526 			pr_err("Unable to allocate cmd->t_task_cdb"
1527 				" %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1528 				scsi_command_size(cdb),
1529 				(unsigned long)sizeof(cmd->__t_task_cdb));
1530 			ret = TCM_OUT_OF_RESOURCES;
1531 			goto err;
1532 		}
1533 	}
1534 	/*
1535 	 * Copy the original CDB into cmd->
1536 	 */
1537 	memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1538 
1539 	trace_target_sequencer_start(cmd);
1540 	return 0;
1541 
1542 err:
1543 	/*
1544 	 * Copy the CDB here to allow trace_target_cmd_complete() to
1545 	 * print the cdb to the trace buffers.
1546 	 */
1547 	memcpy(cmd->t_task_cdb, cdb, min(scsi_command_size(cdb),
1548 					 (unsigned int)TCM_MAX_COMMAND_SIZE));
1549 	return ret;
1550 }
1551 EXPORT_SYMBOL(target_cmd_init_cdb);
1552 
1553 sense_reason_t
1554 target_cmd_parse_cdb(struct se_cmd *cmd)
1555 {
1556 	struct se_device *dev = cmd->se_dev;
1557 	sense_reason_t ret;
1558 
1559 	ret = dev->transport->parse_cdb(cmd);
1560 	if (ret == TCM_UNSUPPORTED_SCSI_OPCODE)
1561 		pr_debug_ratelimited("%s/%s: Unsupported SCSI Opcode 0x%02x, sending CHECK_CONDITION.\n",
1562 				     cmd->se_tfo->fabric_name,
1563 				     cmd->se_sess->se_node_acl->initiatorname,
1564 				     cmd->t_task_cdb[0]);
1565 	if (ret)
1566 		return ret;
1567 
1568 	ret = transport_check_alloc_task_attr(cmd);
1569 	if (ret)
1570 		return ret;
1571 
1572 	cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1573 	atomic_long_inc(&cmd->se_lun->lun_stats.cmd_pdus);
1574 	return 0;
1575 }
1576 EXPORT_SYMBOL(target_cmd_parse_cdb);
1577 
1578 /*
1579  * Used by fabric module frontends to queue tasks directly.
1580  * May only be used from process context.
1581  */
1582 int transport_handle_cdb_direct(
1583 	struct se_cmd *cmd)
1584 {
1585 	sense_reason_t ret;
1586 
1587 	might_sleep();
1588 
1589 	if (!cmd->se_lun) {
1590 		dump_stack();
1591 		pr_err("cmd->se_lun is NULL\n");
1592 		return -EINVAL;
1593 	}
1594 
1595 	/*
1596 	 * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1597 	 * outstanding descriptors are handled correctly during shutdown via
1598 	 * transport_wait_for_tasks()
1599 	 *
1600 	 * Also, we don't take cmd->t_state_lock here as we only expect
1601 	 * this to be called for initial descriptor submission.
1602 	 */
1603 	cmd->t_state = TRANSPORT_NEW_CMD;
1604 	cmd->transport_state |= CMD_T_ACTIVE;
1605 
1606 	/*
1607 	 * transport_generic_new_cmd() is already handling QUEUE_FULL,
1608 	 * so follow TRANSPORT_NEW_CMD processing thread context usage
1609 	 * and call transport_generic_request_failure() if necessary..
1610 	 */
1611 	ret = transport_generic_new_cmd(cmd);
1612 	if (ret)
1613 		transport_generic_request_failure(cmd, ret);
1614 	return 0;
1615 }
1616 EXPORT_SYMBOL(transport_handle_cdb_direct);
1617 
1618 sense_reason_t
1619 transport_generic_map_mem_to_cmd(struct se_cmd *cmd, struct scatterlist *sgl,
1620 		u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count)
1621 {
1622 	if (!sgl || !sgl_count)
1623 		return 0;
1624 
1625 	/*
1626 	 * Reject SCSI data overflow with map_mem_to_cmd() as incoming
1627 	 * scatterlists already have been set to follow what the fabric
1628 	 * passes for the original expected data transfer length.
1629 	 */
1630 	if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1631 		pr_warn("Rejecting SCSI DATA overflow for fabric using"
1632 			" SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
1633 		return TCM_INVALID_CDB_FIELD;
1634 	}
1635 
1636 	cmd->t_data_sg = sgl;
1637 	cmd->t_data_nents = sgl_count;
1638 	cmd->t_bidi_data_sg = sgl_bidi;
1639 	cmd->t_bidi_data_nents = sgl_bidi_count;
1640 
1641 	cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
1642 	return 0;
1643 }
1644 
1645 /**
1646  * target_init_cmd - initialize se_cmd
1647  * @se_cmd: command descriptor to init
1648  * @se_sess: associated se_sess for endpoint
1649  * @sense: pointer to SCSI sense buffer
1650  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1651  * @data_length: fabric expected data transfer length
1652  * @task_attr: SAM task attribute
1653  * @data_dir: DMA data direction
1654  * @flags: flags for command submission from target_sc_flags_tables
1655  *
1656  * Task tags are supported if the caller has set @se_cmd->tag.
1657  *
1658  * Returns:
1659  *	- less than zero to signal active I/O shutdown failure.
1660  *	- zero on success.
1661  *
1662  * If the fabric driver calls target_stop_session, then it must check the
1663  * return code and handle failures. This will never fail for other drivers,
1664  * and the return code can be ignored.
1665  */
1666 int target_init_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1667 		    unsigned char *sense, u64 unpacked_lun,
1668 		    u32 data_length, int task_attr, int data_dir, int flags)
1669 {
1670 	struct se_portal_group *se_tpg;
1671 
1672 	se_tpg = se_sess->se_tpg;
1673 	BUG_ON(!se_tpg);
1674 	BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1675 
1676 	if (flags & TARGET_SCF_USE_CPUID)
1677 		se_cmd->se_cmd_flags |= SCF_USE_CPUID;
1678 	/*
1679 	 * Signal bidirectional data payloads to target-core
1680 	 */
1681 	if (flags & TARGET_SCF_BIDI_OP)
1682 		se_cmd->se_cmd_flags |= SCF_BIDI;
1683 
1684 	if (flags & TARGET_SCF_UNKNOWN_SIZE)
1685 		se_cmd->unknown_data_length = 1;
1686 	/*
1687 	 * Initialize se_cmd for target operation.  From this point
1688 	 * exceptions are handled by sending exception status via
1689 	 * target_core_fabric_ops->queue_status() callback
1690 	 */
1691 	__target_init_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess, data_length,
1692 			  data_dir, task_attr, sense, unpacked_lun,
1693 			  se_sess->cmd_cnt);
1694 
1695 	/*
1696 	 * Obtain struct se_cmd->cmd_kref reference. A second kref_get here is
1697 	 * necessary for fabrics using TARGET_SCF_ACK_KREF that expect a second
1698 	 * kref_put() to happen during fabric packet acknowledgement.
1699 	 */
1700 	return target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1701 }
1702 EXPORT_SYMBOL_GPL(target_init_cmd);
1703 
1704 /**
1705  * target_submit_prep - prepare cmd for submission
1706  * @se_cmd: command descriptor to prep
1707  * @cdb: pointer to SCSI CDB
1708  * @sgl: struct scatterlist memory for unidirectional mapping
1709  * @sgl_count: scatterlist count for unidirectional mapping
1710  * @sgl_bidi: struct scatterlist memory for bidirectional READ mapping
1711  * @sgl_bidi_count: scatterlist count for bidirectional READ mapping
1712  * @sgl_prot: struct scatterlist memory protection information
1713  * @sgl_prot_count: scatterlist count for protection information
1714  * @gfp: gfp allocation type
1715  *
1716  * Returns:
1717  *	- less than zero to signal failure.
1718  *	- zero on success.
1719  *
1720  * If failure is returned, lio will the callers queue_status to complete
1721  * the cmd.
1722  */
1723 int target_submit_prep(struct se_cmd *se_cmd, unsigned char *cdb,
1724 		       struct scatterlist *sgl, u32 sgl_count,
1725 		       struct scatterlist *sgl_bidi, u32 sgl_bidi_count,
1726 		       struct scatterlist *sgl_prot, u32 sgl_prot_count,
1727 		       gfp_t gfp)
1728 {
1729 	sense_reason_t rc;
1730 
1731 	rc = target_cmd_init_cdb(se_cmd, cdb, gfp);
1732 	if (rc)
1733 		goto send_cc_direct;
1734 
1735 	/*
1736 	 * Locate se_lun pointer and attach it to struct se_cmd
1737 	 */
1738 	rc = transport_lookup_cmd_lun(se_cmd);
1739 	if (rc)
1740 		goto send_cc_direct;
1741 
1742 	rc = target_cmd_parse_cdb(se_cmd);
1743 	if (rc != 0)
1744 		goto generic_fail;
1745 
1746 	/*
1747 	 * Save pointers for SGLs containing protection information,
1748 	 * if present.
1749 	 */
1750 	if (sgl_prot_count) {
1751 		se_cmd->t_prot_sg = sgl_prot;
1752 		se_cmd->t_prot_nents = sgl_prot_count;
1753 		se_cmd->se_cmd_flags |= SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC;
1754 	}
1755 
1756 	/*
1757 	 * When a non zero sgl_count has been passed perform SGL passthrough
1758 	 * mapping for pre-allocated fabric memory instead of having target
1759 	 * core perform an internal SGL allocation..
1760 	 */
1761 	if (sgl_count != 0) {
1762 		BUG_ON(!sgl);
1763 
1764 		rc = transport_generic_map_mem_to_cmd(se_cmd, sgl, sgl_count,
1765 				sgl_bidi, sgl_bidi_count);
1766 		if (rc != 0)
1767 			goto generic_fail;
1768 	}
1769 
1770 	return 0;
1771 
1772 send_cc_direct:
1773 	transport_send_check_condition_and_sense(se_cmd, rc, 0);
1774 	target_put_sess_cmd(se_cmd);
1775 	return -EIO;
1776 
1777 generic_fail:
1778 	transport_generic_request_failure(se_cmd, rc);
1779 	return -EIO;
1780 }
1781 EXPORT_SYMBOL_GPL(target_submit_prep);
1782 
1783 /**
1784  * target_submit - perform final initialization and submit cmd to LIO core
1785  * @se_cmd: command descriptor to submit
1786  *
1787  * target_submit_prep must have been called on the cmd, and this must be
1788  * called from process context.
1789  */
1790 void target_submit(struct se_cmd *se_cmd)
1791 {
1792 	struct scatterlist *sgl = se_cmd->t_data_sg;
1793 	unsigned char *buf = NULL;
1794 
1795 	might_sleep();
1796 
1797 	if (se_cmd->t_data_nents != 0) {
1798 		BUG_ON(!sgl);
1799 		/*
1800 		 * A work-around for tcm_loop as some userspace code via
1801 		 * scsi-generic do not memset their associated read buffers,
1802 		 * so go ahead and do that here for type non-data CDBs.  Also
1803 		 * note that this is currently guaranteed to be a single SGL
1804 		 * for this case by target core in target_setup_cmd_from_cdb()
1805 		 * -> transport_generic_cmd_sequencer().
1806 		 */
1807 		if (!(se_cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) &&
1808 		     se_cmd->data_direction == DMA_FROM_DEVICE) {
1809 			if (sgl)
1810 				buf = kmap(sg_page(sgl)) + sgl->offset;
1811 
1812 			if (buf) {
1813 				memset(buf, 0, sgl->length);
1814 				kunmap(sg_page(sgl));
1815 			}
1816 		}
1817 
1818 	}
1819 
1820 	/*
1821 	 * Check if we need to delay processing because of ALUA
1822 	 * Active/NonOptimized primary access state..
1823 	 */
1824 	core_alua_check_nonop_delay(se_cmd);
1825 
1826 	transport_handle_cdb_direct(se_cmd);
1827 }
1828 EXPORT_SYMBOL_GPL(target_submit);
1829 
1830 /**
1831  * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1832  *
1833  * @se_cmd: command descriptor to submit
1834  * @se_sess: associated se_sess for endpoint
1835  * @cdb: pointer to SCSI CDB
1836  * @sense: pointer to SCSI sense buffer
1837  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1838  * @data_length: fabric expected data transfer length
1839  * @task_attr: SAM task attribute
1840  * @data_dir: DMA data direction
1841  * @flags: flags for command submission from target_sc_flags_tables
1842  *
1843  * Task tags are supported if the caller has set @se_cmd->tag.
1844  *
1845  * This may only be called from process context, and also currently
1846  * assumes internal allocation of fabric payload buffer by target-core.
1847  *
1848  * It also assumes interal target core SGL memory allocation.
1849  *
1850  * This function must only be used by drivers that do their own
1851  * sync during shutdown and does not use target_stop_session. If there
1852  * is a failure this function will call into the fabric driver's
1853  * queue_status with a CHECK_CONDITION.
1854  */
1855 void target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1856 		unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1857 		u32 data_length, int task_attr, int data_dir, int flags)
1858 {
1859 	int rc;
1860 
1861 	rc = target_init_cmd(se_cmd, se_sess, sense, unpacked_lun, data_length,
1862 			     task_attr, data_dir, flags);
1863 	WARN(rc, "Invalid target_submit_cmd use. Driver must not use target_stop_session or call target_init_cmd directly.\n");
1864 	if (rc)
1865 		return;
1866 
1867 	if (target_submit_prep(se_cmd, cdb, NULL, 0, NULL, 0, NULL, 0,
1868 			       GFP_KERNEL))
1869 		return;
1870 
1871 	target_submit(se_cmd);
1872 }
1873 EXPORT_SYMBOL(target_submit_cmd);
1874 
1875 
1876 static struct se_dev_plug *target_plug_device(struct se_device *se_dev)
1877 {
1878 	struct se_dev_plug *se_plug;
1879 
1880 	if (!se_dev->transport->plug_device)
1881 		return NULL;
1882 
1883 	se_plug = se_dev->transport->plug_device(se_dev);
1884 	if (!se_plug)
1885 		return NULL;
1886 
1887 	se_plug->se_dev = se_dev;
1888 	/*
1889 	 * We have a ref to the lun at this point, but the cmds could
1890 	 * complete before we unplug, so grab a ref to the se_device so we
1891 	 * can call back into the backend.
1892 	 */
1893 	config_group_get(&se_dev->dev_group);
1894 	return se_plug;
1895 }
1896 
1897 static void target_unplug_device(struct se_dev_plug *se_plug)
1898 {
1899 	struct se_device *se_dev = se_plug->se_dev;
1900 
1901 	se_dev->transport->unplug_device(se_plug);
1902 	config_group_put(&se_dev->dev_group);
1903 }
1904 
1905 void target_queued_submit_work(struct work_struct *work)
1906 {
1907 	struct se_cmd_queue *sq = container_of(work, struct se_cmd_queue, work);
1908 	struct se_cmd *se_cmd, *next_cmd;
1909 	struct se_dev_plug *se_plug = NULL;
1910 	struct se_device *se_dev = NULL;
1911 	struct llist_node *cmd_list;
1912 
1913 	cmd_list = llist_del_all(&sq->cmd_list);
1914 	if (!cmd_list)
1915 		/* Previous call took what we were queued to submit */
1916 		return;
1917 
1918 	cmd_list = llist_reverse_order(cmd_list);
1919 	llist_for_each_entry_safe(se_cmd, next_cmd, cmd_list, se_cmd_list) {
1920 		if (!se_dev) {
1921 			se_dev = se_cmd->se_dev;
1922 			se_plug = target_plug_device(se_dev);
1923 		}
1924 
1925 		target_submit(se_cmd);
1926 	}
1927 
1928 	if (se_plug)
1929 		target_unplug_device(se_plug);
1930 }
1931 
1932 /**
1933  * target_queue_submission - queue the cmd to run on the LIO workqueue
1934  * @se_cmd: command descriptor to submit
1935  */
1936 void target_queue_submission(struct se_cmd *se_cmd)
1937 {
1938 	struct se_device *se_dev = se_cmd->se_dev;
1939 	int cpu = se_cmd->cpuid;
1940 	struct se_cmd_queue *sq;
1941 
1942 	sq = &se_dev->queues[cpu].sq;
1943 	llist_add(&se_cmd->se_cmd_list, &sq->cmd_list);
1944 	queue_work_on(cpu, target_submission_wq, &sq->work);
1945 }
1946 EXPORT_SYMBOL_GPL(target_queue_submission);
1947 
1948 static void target_complete_tmr_failure(struct work_struct *work)
1949 {
1950 	struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1951 
1952 	se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1953 	se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1954 
1955 	transport_lun_remove_cmd(se_cmd);
1956 	transport_cmd_check_stop_to_fabric(se_cmd);
1957 }
1958 
1959 /**
1960  * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1961  *                     for TMR CDBs
1962  *
1963  * @se_cmd: command descriptor to submit
1964  * @se_sess: associated se_sess for endpoint
1965  * @sense: pointer to SCSI sense buffer
1966  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1967  * @fabric_tmr_ptr: fabric context for TMR req
1968  * @tm_type: Type of TM request
1969  * @gfp: gfp type for caller
1970  * @tag: referenced task tag for TMR_ABORT_TASK
1971  * @flags: submit cmd flags
1972  *
1973  * Callable from all contexts.
1974  **/
1975 
1976 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1977 		unsigned char *sense, u64 unpacked_lun,
1978 		void *fabric_tmr_ptr, unsigned char tm_type,
1979 		gfp_t gfp, u64 tag, int flags)
1980 {
1981 	struct se_portal_group *se_tpg;
1982 	int ret;
1983 
1984 	se_tpg = se_sess->se_tpg;
1985 	BUG_ON(!se_tpg);
1986 
1987 	__target_init_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1988 			  0, DMA_NONE, TCM_SIMPLE_TAG, sense, unpacked_lun,
1989 			  se_sess->cmd_cnt);
1990 	/*
1991 	 * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1992 	 * allocation failure.
1993 	 */
1994 	ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1995 	if (ret < 0)
1996 		return -ENOMEM;
1997 
1998 	if (tm_type == TMR_ABORT_TASK)
1999 		se_cmd->se_tmr_req->ref_task_tag = tag;
2000 
2001 	/* See target_submit_cmd for commentary */
2002 	ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
2003 	if (ret) {
2004 		core_tmr_release_req(se_cmd->se_tmr_req);
2005 		return ret;
2006 	}
2007 
2008 	ret = transport_lookup_tmr_lun(se_cmd);
2009 	if (ret)
2010 		goto failure;
2011 
2012 	transport_generic_handle_tmr(se_cmd);
2013 	return 0;
2014 
2015 	/*
2016 	 * For callback during failure handling, push this work off
2017 	 * to process context with TMR_LUN_DOES_NOT_EXIST status.
2018 	 */
2019 failure:
2020 	INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
2021 	schedule_work(&se_cmd->work);
2022 	return 0;
2023 }
2024 EXPORT_SYMBOL(target_submit_tmr);
2025 
2026 /*
2027  * Handle SAM-esque emulation for generic transport request failures.
2028  */
2029 void transport_generic_request_failure(struct se_cmd *cmd,
2030 		sense_reason_t sense_reason)
2031 {
2032 	int ret = 0, post_ret;
2033 
2034 	pr_debug("-----[ Storage Engine Exception; sense_reason %d\n",
2035 		 sense_reason);
2036 	target_show_cmd("-----[ ", cmd);
2037 
2038 	/*
2039 	 * For SAM Task Attribute emulation for failed struct se_cmd
2040 	 */
2041 	transport_complete_task_attr(cmd);
2042 
2043 	if (cmd->transport_complete_callback)
2044 		cmd->transport_complete_callback(cmd, false, &post_ret);
2045 
2046 	if (cmd->transport_state & CMD_T_ABORTED) {
2047 		INIT_WORK(&cmd->work, target_abort_work);
2048 		queue_work(target_completion_wq, &cmd->work);
2049 		return;
2050 	}
2051 
2052 	switch (sense_reason) {
2053 	case TCM_NON_EXISTENT_LUN:
2054 	case TCM_UNSUPPORTED_SCSI_OPCODE:
2055 	case TCM_INVALID_CDB_FIELD:
2056 	case TCM_INVALID_PARAMETER_LIST:
2057 	case TCM_PARAMETER_LIST_LENGTH_ERROR:
2058 	case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
2059 	case TCM_UNKNOWN_MODE_PAGE:
2060 	case TCM_WRITE_PROTECTED:
2061 	case TCM_ADDRESS_OUT_OF_RANGE:
2062 	case TCM_CHECK_CONDITION_ABORT_CMD:
2063 	case TCM_CHECK_CONDITION_UNIT_ATTENTION:
2064 	case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED:
2065 	case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED:
2066 	case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED:
2067 	case TCM_COPY_TARGET_DEVICE_NOT_REACHABLE:
2068 	case TCM_TOO_MANY_TARGET_DESCS:
2069 	case TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE:
2070 	case TCM_TOO_MANY_SEGMENT_DESCS:
2071 	case TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE:
2072 	case TCM_INVALID_FIELD_IN_COMMAND_IU:
2073 	case TCM_ALUA_TG_PT_STANDBY:
2074 	case TCM_ALUA_TG_PT_UNAVAILABLE:
2075 	case TCM_ALUA_STATE_TRANSITION:
2076 	case TCM_ALUA_OFFLINE:
2077 		break;
2078 	case TCM_OUT_OF_RESOURCES:
2079 		cmd->scsi_status = SAM_STAT_TASK_SET_FULL;
2080 		goto queue_status;
2081 	case TCM_LUN_BUSY:
2082 		cmd->scsi_status = SAM_STAT_BUSY;
2083 		goto queue_status;
2084 	case TCM_RESERVATION_CONFLICT:
2085 		/*
2086 		 * No SENSE Data payload for this case, set SCSI Status
2087 		 * and queue the response to $FABRIC_MOD.
2088 		 *
2089 		 * Uses linux/include/scsi/scsi.h SAM status codes defs
2090 		 */
2091 		cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2092 		/*
2093 		 * For UA Interlock Code 11b, a RESERVATION CONFLICT will
2094 		 * establish a UNIT ATTENTION with PREVIOUS RESERVATION
2095 		 * CONFLICT STATUS.
2096 		 *
2097 		 * See spc4r17, section 7.4.6 Control Mode Page, Table 349
2098 		 */
2099 		if (cmd->se_sess &&
2100 		    cmd->se_dev->dev_attrib.emulate_ua_intlck_ctrl
2101 					== TARGET_UA_INTLCK_CTRL_ESTABLISH_UA) {
2102 			target_ua_allocate_lun(cmd->se_sess->se_node_acl,
2103 					       cmd->orig_fe_lun, 0x2C,
2104 					ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
2105 		}
2106 
2107 		goto queue_status;
2108 	default:
2109 		pr_err("Unknown transport error for CDB 0x%02x: %d\n",
2110 			cmd->t_task_cdb[0], sense_reason);
2111 		sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
2112 		break;
2113 	}
2114 
2115 	ret = transport_send_check_condition_and_sense(cmd, sense_reason, 0);
2116 	if (ret)
2117 		goto queue_full;
2118 
2119 check_stop:
2120 	transport_lun_remove_cmd(cmd);
2121 	transport_cmd_check_stop_to_fabric(cmd);
2122 	return;
2123 
2124 queue_status:
2125 	trace_target_cmd_complete(cmd);
2126 	ret = cmd->se_tfo->queue_status(cmd);
2127 	if (!ret)
2128 		goto check_stop;
2129 queue_full:
2130 	transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2131 }
2132 EXPORT_SYMBOL(transport_generic_request_failure);
2133 
2134 void __target_execute_cmd(struct se_cmd *cmd, bool do_checks)
2135 {
2136 	sense_reason_t ret;
2137 
2138 	if (!cmd->execute_cmd) {
2139 		ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2140 		goto err;
2141 	}
2142 	if (do_checks) {
2143 		/*
2144 		 * Check for an existing UNIT ATTENTION condition after
2145 		 * target_handle_task_attr() has done SAM task attr
2146 		 * checking, and possibly have already defered execution
2147 		 * out to target_restart_delayed_cmds() context.
2148 		 */
2149 		ret = target_scsi3_ua_check(cmd);
2150 		if (ret)
2151 			goto err;
2152 
2153 		ret = target_alua_state_check(cmd);
2154 		if (ret)
2155 			goto err;
2156 
2157 		ret = target_check_reservation(cmd);
2158 		if (ret) {
2159 			cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2160 			goto err;
2161 		}
2162 	}
2163 
2164 	ret = cmd->execute_cmd(cmd);
2165 	if (!ret)
2166 		return;
2167 err:
2168 	spin_lock_irq(&cmd->t_state_lock);
2169 	cmd->transport_state &= ~CMD_T_SENT;
2170 	spin_unlock_irq(&cmd->t_state_lock);
2171 
2172 	transport_generic_request_failure(cmd, ret);
2173 }
2174 
2175 static int target_write_prot_action(struct se_cmd *cmd)
2176 {
2177 	u32 sectors;
2178 	/*
2179 	 * Perform WRITE_INSERT of PI using software emulation when backend
2180 	 * device has PI enabled, if the transport has not already generated
2181 	 * PI using hardware WRITE_INSERT offload.
2182 	 */
2183 	switch (cmd->prot_op) {
2184 	case TARGET_PROT_DOUT_INSERT:
2185 		if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_INSERT))
2186 			sbc_dif_generate(cmd);
2187 		break;
2188 	case TARGET_PROT_DOUT_STRIP:
2189 		if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_STRIP)
2190 			break;
2191 
2192 		sectors = cmd->data_length >> ilog2(cmd->se_dev->dev_attrib.block_size);
2193 		cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2194 					     sectors, 0, cmd->t_prot_sg, 0);
2195 		if (unlikely(cmd->pi_err)) {
2196 			spin_lock_irq(&cmd->t_state_lock);
2197 			cmd->transport_state &= ~CMD_T_SENT;
2198 			spin_unlock_irq(&cmd->t_state_lock);
2199 			transport_generic_request_failure(cmd, cmd->pi_err);
2200 			return -1;
2201 		}
2202 		break;
2203 	default:
2204 		break;
2205 	}
2206 
2207 	return 0;
2208 }
2209 
2210 static bool target_handle_task_attr(struct se_cmd *cmd)
2211 {
2212 	struct se_device *dev = cmd->se_dev;
2213 
2214 	if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2215 		return false;
2216 
2217 	cmd->se_cmd_flags |= SCF_TASK_ATTR_SET;
2218 
2219 	/*
2220 	 * Check for the existence of HEAD_OF_QUEUE, and if true return 1
2221 	 * to allow the passed struct se_cmd list of tasks to the front of the list.
2222 	 */
2223 	switch (cmd->sam_task_attr) {
2224 	case TCM_HEAD_TAG:
2225 		atomic_inc_mb(&dev->non_ordered);
2226 		pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x\n",
2227 			 cmd->t_task_cdb[0]);
2228 		return false;
2229 	case TCM_ORDERED_TAG:
2230 		atomic_inc_mb(&dev->delayed_cmd_count);
2231 
2232 		pr_debug("Added ORDERED for CDB: 0x%02x to ordered list\n",
2233 			 cmd->t_task_cdb[0]);
2234 		break;
2235 	default:
2236 		/*
2237 		 * For SIMPLE and UNTAGGED Task Attribute commands
2238 		 */
2239 		atomic_inc_mb(&dev->non_ordered);
2240 
2241 		if (atomic_read(&dev->delayed_cmd_count) == 0)
2242 			return false;
2243 		break;
2244 	}
2245 
2246 	if (cmd->sam_task_attr != TCM_ORDERED_TAG) {
2247 		atomic_inc_mb(&dev->delayed_cmd_count);
2248 		/*
2249 		 * We will account for this when we dequeue from the delayed
2250 		 * list.
2251 		 */
2252 		atomic_dec_mb(&dev->non_ordered);
2253 	}
2254 
2255 	spin_lock_irq(&cmd->t_state_lock);
2256 	cmd->transport_state &= ~CMD_T_SENT;
2257 	spin_unlock_irq(&cmd->t_state_lock);
2258 
2259 	spin_lock(&dev->delayed_cmd_lock);
2260 	list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
2261 	spin_unlock(&dev->delayed_cmd_lock);
2262 
2263 	pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to delayed CMD listn",
2264 		cmd->t_task_cdb[0], cmd->sam_task_attr);
2265 	/*
2266 	 * We may have no non ordered cmds when this function started or we
2267 	 * could have raced with the last simple/head cmd completing, so kick
2268 	 * the delayed handler here.
2269 	 */
2270 	schedule_work(&dev->delayed_cmd_work);
2271 	return true;
2272 }
2273 
2274 void target_execute_cmd(struct se_cmd *cmd)
2275 {
2276 	/*
2277 	 * Determine if frontend context caller is requesting the stopping of
2278 	 * this command for frontend exceptions.
2279 	 *
2280 	 * If the received CDB has already been aborted stop processing it here.
2281 	 */
2282 	if (target_cmd_interrupted(cmd))
2283 		return;
2284 
2285 	spin_lock_irq(&cmd->t_state_lock);
2286 	cmd->t_state = TRANSPORT_PROCESSING;
2287 	cmd->transport_state |= CMD_T_ACTIVE | CMD_T_SENT;
2288 	spin_unlock_irq(&cmd->t_state_lock);
2289 
2290 	if (target_write_prot_action(cmd))
2291 		return;
2292 
2293 	if (target_handle_task_attr(cmd))
2294 		return;
2295 
2296 	__target_execute_cmd(cmd, true);
2297 }
2298 EXPORT_SYMBOL(target_execute_cmd);
2299 
2300 /*
2301  * Process all commands up to the last received ORDERED task attribute which
2302  * requires another blocking boundary
2303  */
2304 void target_do_delayed_work(struct work_struct *work)
2305 {
2306 	struct se_device *dev = container_of(work, struct se_device,
2307 					     delayed_cmd_work);
2308 
2309 	spin_lock(&dev->delayed_cmd_lock);
2310 	while (!dev->ordered_sync_in_progress) {
2311 		struct se_cmd *cmd;
2312 
2313 		if (list_empty(&dev->delayed_cmd_list))
2314 			break;
2315 
2316 		cmd = list_entry(dev->delayed_cmd_list.next,
2317 				 struct se_cmd, se_delayed_node);
2318 
2319 		if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2320 			/*
2321 			 * Check if we started with:
2322 			 * [ordered] [simple] [ordered]
2323 			 * and we are now at the last ordered so we have to wait
2324 			 * for the simple cmd.
2325 			 */
2326 			if (atomic_read(&dev->non_ordered) > 0)
2327 				break;
2328 
2329 			dev->ordered_sync_in_progress = true;
2330 		}
2331 
2332 		list_del(&cmd->se_delayed_node);
2333 		atomic_dec_mb(&dev->delayed_cmd_count);
2334 		spin_unlock(&dev->delayed_cmd_lock);
2335 
2336 		if (cmd->sam_task_attr != TCM_ORDERED_TAG)
2337 			atomic_inc_mb(&dev->non_ordered);
2338 
2339 		cmd->transport_state |= CMD_T_SENT;
2340 
2341 		__target_execute_cmd(cmd, true);
2342 
2343 		spin_lock(&dev->delayed_cmd_lock);
2344 	}
2345 	spin_unlock(&dev->delayed_cmd_lock);
2346 }
2347 
2348 /*
2349  * Called from I/O completion to determine which dormant/delayed
2350  * and ordered cmds need to have their tasks added to the execution queue.
2351  */
2352 static void transport_complete_task_attr(struct se_cmd *cmd)
2353 {
2354 	struct se_device *dev = cmd->se_dev;
2355 
2356 	if (dev->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2357 		return;
2358 
2359 	if (!(cmd->se_cmd_flags & SCF_TASK_ATTR_SET))
2360 		goto restart;
2361 
2362 	if (cmd->sam_task_attr == TCM_SIMPLE_TAG) {
2363 		atomic_dec_mb(&dev->non_ordered);
2364 		dev->dev_cur_ordered_id++;
2365 	} else if (cmd->sam_task_attr == TCM_HEAD_TAG) {
2366 		atomic_dec_mb(&dev->non_ordered);
2367 		dev->dev_cur_ordered_id++;
2368 		pr_debug("Incremented dev_cur_ordered_id: %u for HEAD_OF_QUEUE\n",
2369 			 dev->dev_cur_ordered_id);
2370 	} else if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2371 		spin_lock(&dev->delayed_cmd_lock);
2372 		dev->ordered_sync_in_progress = false;
2373 		spin_unlock(&dev->delayed_cmd_lock);
2374 
2375 		dev->dev_cur_ordered_id++;
2376 		pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED\n",
2377 			 dev->dev_cur_ordered_id);
2378 	}
2379 	cmd->se_cmd_flags &= ~SCF_TASK_ATTR_SET;
2380 
2381 restart:
2382 	if (atomic_read(&dev->delayed_cmd_count) > 0)
2383 		schedule_work(&dev->delayed_cmd_work);
2384 }
2385 
2386 static void transport_complete_qf(struct se_cmd *cmd)
2387 {
2388 	int ret = 0;
2389 
2390 	transport_complete_task_attr(cmd);
2391 	/*
2392 	 * If a fabric driver ->write_pending() or ->queue_data_in() callback
2393 	 * has returned neither -ENOMEM or -EAGAIN, assume it's fatal and
2394 	 * the same callbacks should not be retried.  Return CHECK_CONDITION
2395 	 * if a scsi_status is not already set.
2396 	 *
2397 	 * If a fabric driver ->queue_status() has returned non zero, always
2398 	 * keep retrying no matter what..
2399 	 */
2400 	if (cmd->t_state == TRANSPORT_COMPLETE_QF_ERR) {
2401 		if (cmd->scsi_status)
2402 			goto queue_status;
2403 
2404 		translate_sense_reason(cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
2405 		goto queue_status;
2406 	}
2407 
2408 	/*
2409 	 * Check if we need to send a sense buffer from
2410 	 * the struct se_cmd in question. We do NOT want
2411 	 * to take this path of the IO has been marked as
2412 	 * needing to be treated like a "normal read". This
2413 	 * is the case if it's a tape read, and either the
2414 	 * FM, EOM, or ILI bits are set, but there is no
2415 	 * sense data.
2416 	 */
2417 	if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2418 	    cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
2419 		goto queue_status;
2420 
2421 	switch (cmd->data_direction) {
2422 	case DMA_FROM_DEVICE:
2423 		/* queue status if not treating this as a normal read */
2424 		if (cmd->scsi_status &&
2425 		    !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2426 			goto queue_status;
2427 
2428 		trace_target_cmd_complete(cmd);
2429 		ret = cmd->se_tfo->queue_data_in(cmd);
2430 		break;
2431 	case DMA_TO_DEVICE:
2432 		if (cmd->se_cmd_flags & SCF_BIDI) {
2433 			ret = cmd->se_tfo->queue_data_in(cmd);
2434 			break;
2435 		}
2436 		fallthrough;
2437 	case DMA_NONE:
2438 queue_status:
2439 		trace_target_cmd_complete(cmd);
2440 		ret = cmd->se_tfo->queue_status(cmd);
2441 		break;
2442 	default:
2443 		break;
2444 	}
2445 
2446 	if (ret < 0) {
2447 		transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2448 		return;
2449 	}
2450 	transport_lun_remove_cmd(cmd);
2451 	transport_cmd_check_stop_to_fabric(cmd);
2452 }
2453 
2454 static void transport_handle_queue_full(struct se_cmd *cmd, struct se_device *dev,
2455 					int err, bool write_pending)
2456 {
2457 	/*
2458 	 * -EAGAIN or -ENOMEM signals retry of ->write_pending() and/or
2459 	 * ->queue_data_in() callbacks from new process context.
2460 	 *
2461 	 * Otherwise for other errors, transport_complete_qf() will send
2462 	 * CHECK_CONDITION via ->queue_status() instead of attempting to
2463 	 * retry associated fabric driver data-transfer callbacks.
2464 	 */
2465 	if (err == -EAGAIN || err == -ENOMEM) {
2466 		cmd->t_state = (write_pending) ? TRANSPORT_COMPLETE_QF_WP :
2467 						 TRANSPORT_COMPLETE_QF_OK;
2468 	} else {
2469 		pr_warn_ratelimited("Got unknown fabric queue status: %d\n", err);
2470 		cmd->t_state = TRANSPORT_COMPLETE_QF_ERR;
2471 	}
2472 
2473 	spin_lock_irq(&dev->qf_cmd_lock);
2474 	list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
2475 	atomic_inc_mb(&dev->dev_qf_count);
2476 	spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
2477 
2478 	schedule_work(&cmd->se_dev->qf_work_queue);
2479 }
2480 
2481 static bool target_read_prot_action(struct se_cmd *cmd)
2482 {
2483 	switch (cmd->prot_op) {
2484 	case TARGET_PROT_DIN_STRIP:
2485 		if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_STRIP)) {
2486 			u32 sectors = cmd->data_length >>
2487 				  ilog2(cmd->se_dev->dev_attrib.block_size);
2488 
2489 			cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2490 						     sectors, 0, cmd->t_prot_sg,
2491 						     0);
2492 			if (cmd->pi_err)
2493 				return true;
2494 		}
2495 		break;
2496 	case TARGET_PROT_DIN_INSERT:
2497 		if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_INSERT)
2498 			break;
2499 
2500 		sbc_dif_generate(cmd);
2501 		break;
2502 	default:
2503 		break;
2504 	}
2505 
2506 	return false;
2507 }
2508 
2509 static void target_complete_ok_work(struct work_struct *work)
2510 {
2511 	struct se_cmd *cmd = container_of(work, struct se_cmd, work);
2512 	int ret;
2513 
2514 	/*
2515 	 * Check if we need to move delayed/dormant tasks from cmds on the
2516 	 * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
2517 	 * Attribute.
2518 	 */
2519 	transport_complete_task_attr(cmd);
2520 
2521 	/*
2522 	 * Check to schedule QUEUE_FULL work, or execute an existing
2523 	 * cmd->transport_qf_callback()
2524 	 */
2525 	if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
2526 		schedule_work(&cmd->se_dev->qf_work_queue);
2527 
2528 	/*
2529 	 * Check if we need to send a sense buffer from
2530 	 * the struct se_cmd in question. We do NOT want
2531 	 * to take this path of the IO has been marked as
2532 	 * needing to be treated like a "normal read". This
2533 	 * is the case if it's a tape read, and either the
2534 	 * FM, EOM, or ILI bits are set, but there is no
2535 	 * sense data.
2536 	 */
2537 	if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2538 	    cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2539 		WARN_ON(!cmd->scsi_status);
2540 		ret = transport_send_check_condition_and_sense(
2541 					cmd, 0, 1);
2542 		if (ret)
2543 			goto queue_full;
2544 
2545 		transport_lun_remove_cmd(cmd);
2546 		transport_cmd_check_stop_to_fabric(cmd);
2547 		return;
2548 	}
2549 	/*
2550 	 * Check for a callback, used by amongst other things
2551 	 * XDWRITE_READ_10 and COMPARE_AND_WRITE emulation.
2552 	 */
2553 	if (cmd->transport_complete_callback) {
2554 		sense_reason_t rc;
2555 		bool caw = (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE);
2556 		bool zero_dl = !(cmd->data_length);
2557 		int post_ret = 0;
2558 
2559 		rc = cmd->transport_complete_callback(cmd, true, &post_ret);
2560 		if (!rc && !post_ret) {
2561 			if (caw && zero_dl)
2562 				goto queue_rsp;
2563 
2564 			return;
2565 		} else if (rc) {
2566 			ret = transport_send_check_condition_and_sense(cmd,
2567 						rc, 0);
2568 			if (ret)
2569 				goto queue_full;
2570 
2571 			transport_lun_remove_cmd(cmd);
2572 			transport_cmd_check_stop_to_fabric(cmd);
2573 			return;
2574 		}
2575 	}
2576 
2577 queue_rsp:
2578 	switch (cmd->data_direction) {
2579 	case DMA_FROM_DEVICE:
2580 		/*
2581 		 * if this is a READ-type IO, but SCSI status
2582 		 * is set, then skip returning data and just
2583 		 * return the status -- unless this IO is marked
2584 		 * as needing to be treated as a normal read,
2585 		 * in which case we want to go ahead and return
2586 		 * the data. This happens, for example, for tape
2587 		 * reads with the FM, EOM, or ILI bits set, with
2588 		 * no sense data.
2589 		 */
2590 		if (cmd->scsi_status &&
2591 		    !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2592 			goto queue_status;
2593 
2594 		atomic_long_add(cmd->data_length,
2595 				&cmd->se_lun->lun_stats.tx_data_octets);
2596 		/*
2597 		 * Perform READ_STRIP of PI using software emulation when
2598 		 * backend had PI enabled, if the transport will not be
2599 		 * performing hardware READ_STRIP offload.
2600 		 */
2601 		if (target_read_prot_action(cmd)) {
2602 			ret = transport_send_check_condition_and_sense(cmd,
2603 						cmd->pi_err, 0);
2604 			if (ret)
2605 				goto queue_full;
2606 
2607 			transport_lun_remove_cmd(cmd);
2608 			transport_cmd_check_stop_to_fabric(cmd);
2609 			return;
2610 		}
2611 
2612 		trace_target_cmd_complete(cmd);
2613 		ret = cmd->se_tfo->queue_data_in(cmd);
2614 		if (ret)
2615 			goto queue_full;
2616 		break;
2617 	case DMA_TO_DEVICE:
2618 		atomic_long_add(cmd->data_length,
2619 				&cmd->se_lun->lun_stats.rx_data_octets);
2620 		/*
2621 		 * Check if we need to send READ payload for BIDI-COMMAND
2622 		 */
2623 		if (cmd->se_cmd_flags & SCF_BIDI) {
2624 			atomic_long_add(cmd->data_length,
2625 					&cmd->se_lun->lun_stats.tx_data_octets);
2626 			ret = cmd->se_tfo->queue_data_in(cmd);
2627 			if (ret)
2628 				goto queue_full;
2629 			break;
2630 		}
2631 		fallthrough;
2632 	case DMA_NONE:
2633 queue_status:
2634 		trace_target_cmd_complete(cmd);
2635 		ret = cmd->se_tfo->queue_status(cmd);
2636 		if (ret)
2637 			goto queue_full;
2638 		break;
2639 	default:
2640 		break;
2641 	}
2642 
2643 	transport_lun_remove_cmd(cmd);
2644 	transport_cmd_check_stop_to_fabric(cmd);
2645 	return;
2646 
2647 queue_full:
2648 	pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2649 		" data_direction: %d\n", cmd, cmd->data_direction);
2650 
2651 	transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2652 }
2653 
2654 void target_free_sgl(struct scatterlist *sgl, int nents)
2655 {
2656 	sgl_free_n_order(sgl, nents, 0);
2657 }
2658 EXPORT_SYMBOL(target_free_sgl);
2659 
2660 static inline void transport_reset_sgl_orig(struct se_cmd *cmd)
2661 {
2662 	/*
2663 	 * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE
2664 	 * emulation, and free + reset pointers if necessary..
2665 	 */
2666 	if (!cmd->t_data_sg_orig)
2667 		return;
2668 
2669 	kfree(cmd->t_data_sg);
2670 	cmd->t_data_sg = cmd->t_data_sg_orig;
2671 	cmd->t_data_sg_orig = NULL;
2672 	cmd->t_data_nents = cmd->t_data_nents_orig;
2673 	cmd->t_data_nents_orig = 0;
2674 }
2675 
2676 static inline void transport_free_pages(struct se_cmd *cmd)
2677 {
2678 	if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2679 		target_free_sgl(cmd->t_prot_sg, cmd->t_prot_nents);
2680 		cmd->t_prot_sg = NULL;
2681 		cmd->t_prot_nents = 0;
2682 	}
2683 
2684 	if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) {
2685 		/*
2686 		 * Release special case READ buffer payload required for
2687 		 * SG_TO_MEM_NOALLOC to function with COMPARE_AND_WRITE
2688 		 */
2689 		if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
2690 			target_free_sgl(cmd->t_bidi_data_sg,
2691 					   cmd->t_bidi_data_nents);
2692 			cmd->t_bidi_data_sg = NULL;
2693 			cmd->t_bidi_data_nents = 0;
2694 		}
2695 		transport_reset_sgl_orig(cmd);
2696 		return;
2697 	}
2698 	transport_reset_sgl_orig(cmd);
2699 
2700 	target_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2701 	cmd->t_data_sg = NULL;
2702 	cmd->t_data_nents = 0;
2703 
2704 	target_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2705 	cmd->t_bidi_data_sg = NULL;
2706 	cmd->t_bidi_data_nents = 0;
2707 }
2708 
2709 void *transport_kmap_data_sg(struct se_cmd *cmd)
2710 {
2711 	struct scatterlist *sg = cmd->t_data_sg;
2712 	struct page **pages;
2713 	int i;
2714 
2715 	/*
2716 	 * We need to take into account a possible offset here for fabrics like
2717 	 * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2718 	 * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2719 	 */
2720 	if (!cmd->t_data_nents)
2721 		return NULL;
2722 
2723 	BUG_ON(!sg);
2724 	if (cmd->t_data_nents == 1)
2725 		return kmap(sg_page(sg)) + sg->offset;
2726 
2727 	/* >1 page. use vmap */
2728 	pages = kmalloc_array(cmd->t_data_nents, sizeof(*pages), GFP_KERNEL);
2729 	if (!pages)
2730 		return NULL;
2731 
2732 	/* convert sg[] to pages[] */
2733 	for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2734 		pages[i] = sg_page(sg);
2735 	}
2736 
2737 	cmd->t_data_vmap = vmap(pages, cmd->t_data_nents,  VM_MAP, PAGE_KERNEL);
2738 	kfree(pages);
2739 	if (!cmd->t_data_vmap)
2740 		return NULL;
2741 
2742 	return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2743 }
2744 EXPORT_SYMBOL(transport_kmap_data_sg);
2745 
2746 void transport_kunmap_data_sg(struct se_cmd *cmd)
2747 {
2748 	if (!cmd->t_data_nents) {
2749 		return;
2750 	} else if (cmd->t_data_nents == 1) {
2751 		kunmap(sg_page(cmd->t_data_sg));
2752 		return;
2753 	}
2754 
2755 	vunmap(cmd->t_data_vmap);
2756 	cmd->t_data_vmap = NULL;
2757 }
2758 EXPORT_SYMBOL(transport_kunmap_data_sg);
2759 
2760 int
2761 target_alloc_sgl(struct scatterlist **sgl, unsigned int *nents, u32 length,
2762 		 bool zero_page, bool chainable)
2763 {
2764 	gfp_t gfp = GFP_KERNEL | (zero_page ? __GFP_ZERO : 0);
2765 
2766 	*sgl = sgl_alloc_order(length, 0, chainable, gfp, nents);
2767 	return *sgl ? 0 : -ENOMEM;
2768 }
2769 EXPORT_SYMBOL(target_alloc_sgl);
2770 
2771 /*
2772  * Allocate any required resources to execute the command.  For writes we
2773  * might not have the payload yet, so notify the fabric via a call to
2774  * ->write_pending instead. Otherwise place it on the execution queue.
2775  */
2776 sense_reason_t
2777 transport_generic_new_cmd(struct se_cmd *cmd)
2778 {
2779 	unsigned long flags;
2780 	int ret = 0;
2781 	bool zero_flag = !(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB);
2782 
2783 	if (cmd->prot_op != TARGET_PROT_NORMAL &&
2784 	    !(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2785 		ret = target_alloc_sgl(&cmd->t_prot_sg, &cmd->t_prot_nents,
2786 				       cmd->prot_length, true, false);
2787 		if (ret < 0)
2788 			return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2789 	}
2790 
2791 	/*
2792 	 * Determine if the TCM fabric module has already allocated physical
2793 	 * memory, and is directly calling transport_generic_map_mem_to_cmd()
2794 	 * beforehand.
2795 	 */
2796 	if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2797 	    cmd->data_length) {
2798 
2799 		if ((cmd->se_cmd_flags & SCF_BIDI) ||
2800 		    (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)) {
2801 			u32 bidi_length;
2802 
2803 			if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)
2804 				bidi_length = cmd->t_task_nolb *
2805 					      cmd->se_dev->dev_attrib.block_size;
2806 			else
2807 				bidi_length = cmd->data_length;
2808 
2809 			ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2810 					       &cmd->t_bidi_data_nents,
2811 					       bidi_length, zero_flag, false);
2812 			if (ret < 0)
2813 				return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2814 		}
2815 
2816 		ret = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents,
2817 				       cmd->data_length, zero_flag, false);
2818 		if (ret < 0)
2819 			return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2820 	} else if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
2821 		    cmd->data_length) {
2822 		/*
2823 		 * Special case for COMPARE_AND_WRITE with fabrics
2824 		 * using SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC.
2825 		 */
2826 		u32 caw_length = cmd->t_task_nolb *
2827 				 cmd->se_dev->dev_attrib.block_size;
2828 
2829 		ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2830 				       &cmd->t_bidi_data_nents,
2831 				       caw_length, zero_flag, false);
2832 		if (ret < 0)
2833 			return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2834 	}
2835 	/*
2836 	 * If this command is not a write we can execute it right here,
2837 	 * for write buffers we need to notify the fabric driver first
2838 	 * and let it call back once the write buffers are ready.
2839 	 */
2840 	target_add_to_state_list(cmd);
2841 	if (cmd->data_direction != DMA_TO_DEVICE || cmd->data_length == 0) {
2842 		target_execute_cmd(cmd);
2843 		return 0;
2844 	}
2845 
2846 	spin_lock_irqsave(&cmd->t_state_lock, flags);
2847 	cmd->t_state = TRANSPORT_WRITE_PENDING;
2848 	/*
2849 	 * Determine if frontend context caller is requesting the stopping of
2850 	 * this command for frontend exceptions.
2851 	 */
2852 	if (cmd->transport_state & CMD_T_STOP &&
2853 	    !cmd->se_tfo->write_pending_must_be_called) {
2854 		pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2855 			 __func__, __LINE__, cmd->tag);
2856 
2857 		spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2858 
2859 		complete_all(&cmd->t_transport_stop_comp);
2860 		return 0;
2861 	}
2862 	cmd->transport_state &= ~CMD_T_ACTIVE;
2863 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2864 
2865 	ret = cmd->se_tfo->write_pending(cmd);
2866 	if (ret)
2867 		goto queue_full;
2868 
2869 	return 0;
2870 
2871 queue_full:
2872 	pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2873 	transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2874 	return 0;
2875 }
2876 EXPORT_SYMBOL(transport_generic_new_cmd);
2877 
2878 static void transport_write_pending_qf(struct se_cmd *cmd)
2879 {
2880 	unsigned long flags;
2881 	int ret;
2882 	bool stop;
2883 
2884 	spin_lock_irqsave(&cmd->t_state_lock, flags);
2885 	stop = (cmd->transport_state & (CMD_T_STOP | CMD_T_ABORTED));
2886 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2887 
2888 	if (stop) {
2889 		pr_debug("%s:%d CMD_T_STOP|CMD_T_ABORTED for ITT: 0x%08llx\n",
2890 			__func__, __LINE__, cmd->tag);
2891 		complete_all(&cmd->t_transport_stop_comp);
2892 		return;
2893 	}
2894 
2895 	ret = cmd->se_tfo->write_pending(cmd);
2896 	if (ret) {
2897 		pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2898 			 cmd);
2899 		transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2900 	}
2901 }
2902 
2903 static bool
2904 __transport_wait_for_tasks(struct se_cmd *, bool, bool *, bool *,
2905 			   unsigned long *flags);
2906 
2907 static void target_wait_free_cmd(struct se_cmd *cmd, bool *aborted, bool *tas)
2908 {
2909 	unsigned long flags;
2910 
2911 	spin_lock_irqsave(&cmd->t_state_lock, flags);
2912 	__transport_wait_for_tasks(cmd, true, aborted, tas, &flags);
2913 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2914 }
2915 
2916 /*
2917  * Call target_put_sess_cmd() and wait until target_release_cmd_kref(@cmd) has
2918  * finished.
2919  */
2920 void target_put_cmd_and_wait(struct se_cmd *cmd)
2921 {
2922 	DECLARE_COMPLETION_ONSTACK(compl);
2923 
2924 	WARN_ON_ONCE(cmd->abrt_compl);
2925 	cmd->abrt_compl = &compl;
2926 	target_put_sess_cmd(cmd);
2927 	wait_for_completion(&compl);
2928 }
2929 
2930 /*
2931  * This function is called by frontend drivers after processing of a command
2932  * has finished.
2933  *
2934  * The protocol for ensuring that either the regular frontend command
2935  * processing flow or target_handle_abort() code drops one reference is as
2936  * follows:
2937  * - Calling .queue_data_in(), .queue_status() or queue_tm_rsp() will cause
2938  *   the frontend driver to call this function synchronously or asynchronously.
2939  *   That will cause one reference to be dropped.
2940  * - During regular command processing the target core sets CMD_T_COMPLETE
2941  *   before invoking one of the .queue_*() functions.
2942  * - The code that aborts commands skips commands and TMFs for which
2943  *   CMD_T_COMPLETE has been set.
2944  * - CMD_T_ABORTED is set atomically after the CMD_T_COMPLETE check for
2945  *   commands that will be aborted.
2946  * - If the CMD_T_ABORTED flag is set but CMD_T_TAS has not been set
2947  *   transport_generic_free_cmd() skips its call to target_put_sess_cmd().
2948  * - For aborted commands for which CMD_T_TAS has been set .queue_status() will
2949  *   be called and will drop a reference.
2950  * - For aborted commands for which CMD_T_TAS has not been set .aborted_task()
2951  *   will be called. target_handle_abort() will drop the final reference.
2952  */
2953 int transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2954 {
2955 	DECLARE_COMPLETION_ONSTACK(compl);
2956 	int ret = 0;
2957 	bool aborted = false, tas = false;
2958 
2959 	if (wait_for_tasks)
2960 		target_wait_free_cmd(cmd, &aborted, &tas);
2961 
2962 	if (cmd->se_cmd_flags & SCF_SE_LUN_CMD) {
2963 		/*
2964 		 * Handle WRITE failure case where transport_generic_new_cmd()
2965 		 * has already added se_cmd to state_list, but fabric has
2966 		 * failed command before I/O submission.
2967 		 */
2968 		if (cmd->state_active)
2969 			target_remove_from_state_list(cmd);
2970 
2971 		if (cmd->se_lun)
2972 			transport_lun_remove_cmd(cmd);
2973 	}
2974 	if (aborted)
2975 		cmd->free_compl = &compl;
2976 	ret = target_put_sess_cmd(cmd);
2977 	if (aborted) {
2978 		pr_debug("Detected CMD_T_ABORTED for ITT: %llu\n", cmd->tag);
2979 		wait_for_completion(&compl);
2980 		ret = 1;
2981 	}
2982 	return ret;
2983 }
2984 EXPORT_SYMBOL(transport_generic_free_cmd);
2985 
2986 /**
2987  * target_get_sess_cmd - Verify the session is accepting cmds and take ref
2988  * @se_cmd:	command descriptor to add
2989  * @ack_kref:	Signal that fabric will perform an ack target_put_sess_cmd()
2990  */
2991 int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
2992 {
2993 	int ret = 0;
2994 
2995 	/*
2996 	 * Add a second kref if the fabric caller is expecting to handle
2997 	 * fabric acknowledgement that requires two target_put_sess_cmd()
2998 	 * invocations before se_cmd descriptor release.
2999 	 */
3000 	if (ack_kref) {
3001 		kref_get(&se_cmd->cmd_kref);
3002 		se_cmd->se_cmd_flags |= SCF_ACK_KREF;
3003 	}
3004 
3005 	/*
3006 	 * Users like xcopy do not use counters since they never do a stop
3007 	 * and wait.
3008 	 */
3009 	if (se_cmd->cmd_cnt) {
3010 		if (!percpu_ref_tryget_live(&se_cmd->cmd_cnt->refcnt))
3011 			ret = -ESHUTDOWN;
3012 	}
3013 	if (ret && ack_kref)
3014 		target_put_sess_cmd(se_cmd);
3015 
3016 	return ret;
3017 }
3018 EXPORT_SYMBOL(target_get_sess_cmd);
3019 
3020 static void target_free_cmd_mem(struct se_cmd *cmd)
3021 {
3022 	transport_free_pages(cmd);
3023 
3024 	if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
3025 		core_tmr_release_req(cmd->se_tmr_req);
3026 	if (cmd->t_task_cdb != cmd->__t_task_cdb)
3027 		kfree(cmd->t_task_cdb);
3028 }
3029 
3030 static void target_release_cmd_kref(struct kref *kref)
3031 {
3032 	struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
3033 	struct target_cmd_counter *cmd_cnt = se_cmd->cmd_cnt;
3034 	struct completion *free_compl = se_cmd->free_compl;
3035 	struct completion *abrt_compl = se_cmd->abrt_compl;
3036 
3037 	target_free_cmd_mem(se_cmd);
3038 	se_cmd->se_tfo->release_cmd(se_cmd);
3039 	if (free_compl)
3040 		complete(free_compl);
3041 	if (abrt_compl)
3042 		complete(abrt_compl);
3043 
3044 	if (cmd_cnt)
3045 		percpu_ref_put(&cmd_cnt->refcnt);
3046 }
3047 
3048 /**
3049  * target_put_sess_cmd - decrease the command reference count
3050  * @se_cmd:	command to drop a reference from
3051  *
3052  * Returns 1 if and only if this target_put_sess_cmd() call caused the
3053  * refcount to drop to zero. Returns zero otherwise.
3054  */
3055 int target_put_sess_cmd(struct se_cmd *se_cmd)
3056 {
3057 	return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
3058 }
3059 EXPORT_SYMBOL(target_put_sess_cmd);
3060 
3061 static const char *data_dir_name(enum dma_data_direction d)
3062 {
3063 	switch (d) {
3064 	case DMA_BIDIRECTIONAL:	return "BIDI";
3065 	case DMA_TO_DEVICE:	return "WRITE";
3066 	case DMA_FROM_DEVICE:	return "READ";
3067 	case DMA_NONE:		return "NONE";
3068 	}
3069 
3070 	return "(?)";
3071 }
3072 
3073 static const char *cmd_state_name(enum transport_state_table t)
3074 {
3075 	switch (t) {
3076 	case TRANSPORT_NO_STATE:	return "NO_STATE";
3077 	case TRANSPORT_NEW_CMD:		return "NEW_CMD";
3078 	case TRANSPORT_WRITE_PENDING:	return "WRITE_PENDING";
3079 	case TRANSPORT_PROCESSING:	return "PROCESSING";
3080 	case TRANSPORT_COMPLETE:	return "COMPLETE";
3081 	case TRANSPORT_ISTATE_PROCESSING:
3082 					return "ISTATE_PROCESSING";
3083 	case TRANSPORT_COMPLETE_QF_WP:	return "COMPLETE_QF_WP";
3084 	case TRANSPORT_COMPLETE_QF_OK:	return "COMPLETE_QF_OK";
3085 	case TRANSPORT_COMPLETE_QF_ERR:	return "COMPLETE_QF_ERR";
3086 	}
3087 
3088 	return "(?)";
3089 }
3090 
3091 static void target_append_str(char **str, const char *txt)
3092 {
3093 	char *prev = *str;
3094 
3095 	*str = *str ? kasprintf(GFP_ATOMIC, "%s,%s", *str, txt) :
3096 		kstrdup(txt, GFP_ATOMIC);
3097 	kfree(prev);
3098 }
3099 
3100 /*
3101  * Convert a transport state bitmask into a string. The caller is
3102  * responsible for freeing the returned pointer.
3103  */
3104 static char *target_ts_to_str(u32 ts)
3105 {
3106 	char *str = NULL;
3107 
3108 	if (ts & CMD_T_ABORTED)
3109 		target_append_str(&str, "aborted");
3110 	if (ts & CMD_T_ACTIVE)
3111 		target_append_str(&str, "active");
3112 	if (ts & CMD_T_COMPLETE)
3113 		target_append_str(&str, "complete");
3114 	if (ts & CMD_T_SENT)
3115 		target_append_str(&str, "sent");
3116 	if (ts & CMD_T_STOP)
3117 		target_append_str(&str, "stop");
3118 	if (ts & CMD_T_FABRIC_STOP)
3119 		target_append_str(&str, "fabric_stop");
3120 
3121 	return str;
3122 }
3123 
3124 static const char *target_tmf_name(enum tcm_tmreq_table tmf)
3125 {
3126 	switch (tmf) {
3127 	case TMR_ABORT_TASK:		return "ABORT_TASK";
3128 	case TMR_ABORT_TASK_SET:	return "ABORT_TASK_SET";
3129 	case TMR_CLEAR_ACA:		return "CLEAR_ACA";
3130 	case TMR_CLEAR_TASK_SET:	return "CLEAR_TASK_SET";
3131 	case TMR_LUN_RESET:		return "LUN_RESET";
3132 	case TMR_TARGET_WARM_RESET:	return "TARGET_WARM_RESET";
3133 	case TMR_TARGET_COLD_RESET:	return "TARGET_COLD_RESET";
3134 	case TMR_LUN_RESET_PRO:		return "LUN_RESET_PRO";
3135 	case TMR_UNKNOWN:		break;
3136 	}
3137 	return "(?)";
3138 }
3139 
3140 void target_show_cmd(const char *pfx, struct se_cmd *cmd)
3141 {
3142 	char *ts_str = target_ts_to_str(cmd->transport_state);
3143 	const u8 *cdb = cmd->t_task_cdb;
3144 	struct se_tmr_req *tmf = cmd->se_tmr_req;
3145 
3146 	if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
3147 		pr_debug("%scmd %#02x:%#02x with tag %#llx dir %s i_state %d t_state %s len %d refcnt %d transport_state %s\n",
3148 			 pfx, cdb[0], cdb[1], cmd->tag,
3149 			 data_dir_name(cmd->data_direction),
3150 			 cmd->se_tfo->get_cmd_state(cmd),
3151 			 cmd_state_name(cmd->t_state), cmd->data_length,
3152 			 kref_read(&cmd->cmd_kref), ts_str);
3153 	} else {
3154 		pr_debug("%stmf %s with tag %#llx ref_task_tag %#llx i_state %d t_state %s refcnt %d transport_state %s\n",
3155 			 pfx, target_tmf_name(tmf->function), cmd->tag,
3156 			 tmf->ref_task_tag, cmd->se_tfo->get_cmd_state(cmd),
3157 			 cmd_state_name(cmd->t_state),
3158 			 kref_read(&cmd->cmd_kref), ts_str);
3159 	}
3160 	kfree(ts_str);
3161 }
3162 EXPORT_SYMBOL(target_show_cmd);
3163 
3164 static void target_stop_cmd_counter_confirm(struct percpu_ref *ref)
3165 {
3166 	struct target_cmd_counter *cmd_cnt = container_of(ref,
3167 						struct target_cmd_counter,
3168 						refcnt);
3169 	complete_all(&cmd_cnt->stop_done);
3170 }
3171 
3172 /**
3173  * target_stop_cmd_counter - Stop new IO from being added to the counter.
3174  * @cmd_cnt: counter to stop
3175  */
3176 void target_stop_cmd_counter(struct target_cmd_counter *cmd_cnt)
3177 {
3178 	pr_debug("Stopping command counter.\n");
3179 	if (!atomic_cmpxchg(&cmd_cnt->stopped, 0, 1))
3180 		percpu_ref_kill_and_confirm(&cmd_cnt->refcnt,
3181 					    target_stop_cmd_counter_confirm);
3182 }
3183 EXPORT_SYMBOL_GPL(target_stop_cmd_counter);
3184 
3185 /**
3186  * target_stop_session - Stop new IO from being queued on the session.
3187  * @se_sess: session to stop
3188  */
3189 void target_stop_session(struct se_session *se_sess)
3190 {
3191 	target_stop_cmd_counter(se_sess->cmd_cnt);
3192 }
3193 EXPORT_SYMBOL(target_stop_session);
3194 
3195 /**
3196  * target_wait_for_cmds - Wait for outstanding cmds.
3197  * @cmd_cnt: counter to wait for active I/O for.
3198  */
3199 void target_wait_for_cmds(struct target_cmd_counter *cmd_cnt)
3200 {
3201 	int ret;
3202 
3203 	WARN_ON_ONCE(!atomic_read(&cmd_cnt->stopped));
3204 
3205 	do {
3206 		pr_debug("Waiting for running cmds to complete.\n");
3207 		ret = wait_event_timeout(cmd_cnt->refcnt_wq,
3208 					 percpu_ref_is_zero(&cmd_cnt->refcnt),
3209 					 180 * HZ);
3210 	} while (ret <= 0);
3211 
3212 	wait_for_completion(&cmd_cnt->stop_done);
3213 	pr_debug("Waiting for cmds done.\n");
3214 }
3215 EXPORT_SYMBOL_GPL(target_wait_for_cmds);
3216 
3217 /**
3218  * target_wait_for_sess_cmds - Wait for outstanding commands
3219  * @se_sess: session to wait for active I/O
3220  */
3221 void target_wait_for_sess_cmds(struct se_session *se_sess)
3222 {
3223 	target_wait_for_cmds(se_sess->cmd_cnt);
3224 }
3225 EXPORT_SYMBOL(target_wait_for_sess_cmds);
3226 
3227 /*
3228  * Prevent that new percpu_ref_tryget_live() calls succeed and wait until
3229  * all references to the LUN have been released. Called during LUN shutdown.
3230  */
3231 void transport_clear_lun_ref(struct se_lun *lun)
3232 {
3233 	percpu_ref_kill(&lun->lun_ref);
3234 	wait_for_completion(&lun->lun_shutdown_comp);
3235 }
3236 
3237 static bool
3238 __transport_wait_for_tasks(struct se_cmd *cmd, bool fabric_stop,
3239 			   bool *aborted, bool *tas, unsigned long *flags)
3240 	__releases(&cmd->t_state_lock)
3241 	__acquires(&cmd->t_state_lock)
3242 {
3243 	lockdep_assert_held(&cmd->t_state_lock);
3244 
3245 	if (fabric_stop)
3246 		cmd->transport_state |= CMD_T_FABRIC_STOP;
3247 
3248 	if (cmd->transport_state & CMD_T_ABORTED)
3249 		*aborted = true;
3250 
3251 	if (cmd->transport_state & CMD_T_TAS)
3252 		*tas = true;
3253 
3254 	if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
3255 	    !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3256 		return false;
3257 
3258 	if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
3259 	    !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3260 		return false;
3261 
3262 	if (!(cmd->transport_state & CMD_T_ACTIVE))
3263 		return false;
3264 
3265 	if (fabric_stop && *aborted)
3266 		return false;
3267 
3268 	cmd->transport_state |= CMD_T_STOP;
3269 
3270 	target_show_cmd("wait_for_tasks: Stopping ", cmd);
3271 
3272 	spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
3273 
3274 	while (!wait_for_completion_timeout(&cmd->t_transport_stop_comp,
3275 					    180 * HZ))
3276 		target_show_cmd("wait for tasks: ", cmd);
3277 
3278 	spin_lock_irqsave(&cmd->t_state_lock, *flags);
3279 	cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
3280 
3281 	pr_debug("wait_for_tasks: Stopped wait_for_completion(&cmd->"
3282 		 "t_transport_stop_comp) for ITT: 0x%08llx\n", cmd->tag);
3283 
3284 	return true;
3285 }
3286 
3287 /**
3288  * transport_wait_for_tasks - set CMD_T_STOP and wait for t_transport_stop_comp
3289  * @cmd: command to wait on
3290  */
3291 bool transport_wait_for_tasks(struct se_cmd *cmd)
3292 {
3293 	unsigned long flags;
3294 	bool ret, aborted = false, tas = false;
3295 
3296 	spin_lock_irqsave(&cmd->t_state_lock, flags);
3297 	ret = __transport_wait_for_tasks(cmd, false, &aborted, &tas, &flags);
3298 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3299 
3300 	return ret;
3301 }
3302 EXPORT_SYMBOL(transport_wait_for_tasks);
3303 
3304 struct sense_detail {
3305 	u8 key;
3306 	u8 asc;
3307 	u8 ascq;
3308 	bool add_sense_info;
3309 };
3310 
3311 static const struct sense_detail sense_detail_table[] = {
3312 	[TCM_NO_SENSE] = {
3313 		.key = NOT_READY
3314 	},
3315 	[TCM_NON_EXISTENT_LUN] = {
3316 		.key = ILLEGAL_REQUEST,
3317 		.asc = 0x25 /* LOGICAL UNIT NOT SUPPORTED */
3318 	},
3319 	[TCM_UNSUPPORTED_SCSI_OPCODE] = {
3320 		.key = ILLEGAL_REQUEST,
3321 		.asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3322 	},
3323 	[TCM_SECTOR_COUNT_TOO_MANY] = {
3324 		.key = ILLEGAL_REQUEST,
3325 		.asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3326 	},
3327 	[TCM_UNKNOWN_MODE_PAGE] = {
3328 		.key = ILLEGAL_REQUEST,
3329 		.asc = 0x24, /* INVALID FIELD IN CDB */
3330 	},
3331 	[TCM_CHECK_CONDITION_ABORT_CMD] = {
3332 		.key = ABORTED_COMMAND,
3333 		.asc = 0x29, /* BUS DEVICE RESET FUNCTION OCCURRED */
3334 		.ascq = 0x03,
3335 	},
3336 	[TCM_INCORRECT_AMOUNT_OF_DATA] = {
3337 		.key = ABORTED_COMMAND,
3338 		.asc = 0x0c, /* WRITE ERROR */
3339 		.ascq = 0x0d, /* NOT ENOUGH UNSOLICITED DATA */
3340 	},
3341 	[TCM_INVALID_CDB_FIELD] = {
3342 		.key = ILLEGAL_REQUEST,
3343 		.asc = 0x24, /* INVALID FIELD IN CDB */
3344 	},
3345 	[TCM_INVALID_PARAMETER_LIST] = {
3346 		.key = ILLEGAL_REQUEST,
3347 		.asc = 0x26, /* INVALID FIELD IN PARAMETER LIST */
3348 	},
3349 	[TCM_TOO_MANY_TARGET_DESCS] = {
3350 		.key = ILLEGAL_REQUEST,
3351 		.asc = 0x26,
3352 		.ascq = 0x06, /* TOO MANY TARGET DESCRIPTORS */
3353 	},
3354 	[TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE] = {
3355 		.key = ILLEGAL_REQUEST,
3356 		.asc = 0x26,
3357 		.ascq = 0x07, /* UNSUPPORTED TARGET DESCRIPTOR TYPE CODE */
3358 	},
3359 	[TCM_TOO_MANY_SEGMENT_DESCS] = {
3360 		.key = ILLEGAL_REQUEST,
3361 		.asc = 0x26,
3362 		.ascq = 0x08, /* TOO MANY SEGMENT DESCRIPTORS */
3363 	},
3364 	[TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE] = {
3365 		.key = ILLEGAL_REQUEST,
3366 		.asc = 0x26,
3367 		.ascq = 0x09, /* UNSUPPORTED SEGMENT DESCRIPTOR TYPE CODE */
3368 	},
3369 	[TCM_PARAMETER_LIST_LENGTH_ERROR] = {
3370 		.key = ILLEGAL_REQUEST,
3371 		.asc = 0x1a, /* PARAMETER LIST LENGTH ERROR */
3372 	},
3373 	[TCM_UNEXPECTED_UNSOLICITED_DATA] = {
3374 		.key = ILLEGAL_REQUEST,
3375 		.asc = 0x0c, /* WRITE ERROR */
3376 		.ascq = 0x0c, /* UNEXPECTED_UNSOLICITED_DATA */
3377 	},
3378 	[TCM_SERVICE_CRC_ERROR] = {
3379 		.key = ABORTED_COMMAND,
3380 		.asc = 0x47, /* PROTOCOL SERVICE CRC ERROR */
3381 		.ascq = 0x05, /* N/A */
3382 	},
3383 	[TCM_SNACK_REJECTED] = {
3384 		.key = ABORTED_COMMAND,
3385 		.asc = 0x11, /* READ ERROR */
3386 		.ascq = 0x13, /* FAILED RETRANSMISSION REQUEST */
3387 	},
3388 	[TCM_WRITE_PROTECTED] = {
3389 		.key = DATA_PROTECT,
3390 		.asc = 0x27, /* WRITE PROTECTED */
3391 	},
3392 	[TCM_ADDRESS_OUT_OF_RANGE] = {
3393 		.key = ILLEGAL_REQUEST,
3394 		.asc = 0x21, /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3395 	},
3396 	[TCM_CHECK_CONDITION_UNIT_ATTENTION] = {
3397 		.key = UNIT_ATTENTION,
3398 	},
3399 	[TCM_MISCOMPARE_VERIFY] = {
3400 		.key = MISCOMPARE,
3401 		.asc = 0x1d, /* MISCOMPARE DURING VERIFY OPERATION */
3402 		.ascq = 0x00,
3403 		.add_sense_info = true,
3404 	},
3405 	[TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED] = {
3406 		.key = ABORTED_COMMAND,
3407 		.asc = 0x10,
3408 		.ascq = 0x01, /* LOGICAL BLOCK GUARD CHECK FAILED */
3409 		.add_sense_info = true,
3410 	},
3411 	[TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED] = {
3412 		.key = ABORTED_COMMAND,
3413 		.asc = 0x10,
3414 		.ascq = 0x02, /* LOGICAL BLOCK APPLICATION TAG CHECK FAILED */
3415 		.add_sense_info = true,
3416 	},
3417 	[TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED] = {
3418 		.key = ABORTED_COMMAND,
3419 		.asc = 0x10,
3420 		.ascq = 0x03, /* LOGICAL BLOCK REFERENCE TAG CHECK FAILED */
3421 		.add_sense_info = true,
3422 	},
3423 	[TCM_COPY_TARGET_DEVICE_NOT_REACHABLE] = {
3424 		.key = COPY_ABORTED,
3425 		.asc = 0x0d,
3426 		.ascq = 0x02, /* COPY TARGET DEVICE NOT REACHABLE */
3427 
3428 	},
3429 	[TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE] = {
3430 		/*
3431 		 * Returning ILLEGAL REQUEST would cause immediate IO errors on
3432 		 * Solaris initiators.  Returning NOT READY instead means the
3433 		 * operations will be retried a finite number of times and we
3434 		 * can survive intermittent errors.
3435 		 */
3436 		.key = NOT_READY,
3437 		.asc = 0x08, /* LOGICAL UNIT COMMUNICATION FAILURE */
3438 	},
3439 	[TCM_INSUFFICIENT_REGISTRATION_RESOURCES] = {
3440 		/*
3441 		 * From spc4r22 section5.7.7,5.7.8
3442 		 * If a PERSISTENT RESERVE OUT command with a REGISTER service action
3443 		 * or a REGISTER AND IGNORE EXISTING KEY service action or
3444 		 * REGISTER AND MOVE service actionis attempted,
3445 		 * but there are insufficient device server resources to complete the
3446 		 * operation, then the command shall be terminated with CHECK CONDITION
3447 		 * status, with the sense key set to ILLEGAL REQUEST,and the additonal
3448 		 * sense code set to INSUFFICIENT REGISTRATION RESOURCES.
3449 		 */
3450 		.key = ILLEGAL_REQUEST,
3451 		.asc = 0x55,
3452 		.ascq = 0x04, /* INSUFFICIENT REGISTRATION RESOURCES */
3453 	},
3454 	[TCM_INVALID_FIELD_IN_COMMAND_IU] = {
3455 		.key = ILLEGAL_REQUEST,
3456 		.asc = 0x0e,
3457 		.ascq = 0x03, /* INVALID FIELD IN COMMAND INFORMATION UNIT */
3458 	},
3459 	[TCM_ALUA_TG_PT_STANDBY] = {
3460 		.key = NOT_READY,
3461 		.asc = 0x04,
3462 		.ascq = ASCQ_04H_ALUA_TG_PT_STANDBY,
3463 	},
3464 	[TCM_ALUA_TG_PT_UNAVAILABLE] = {
3465 		.key = NOT_READY,
3466 		.asc = 0x04,
3467 		.ascq = ASCQ_04H_ALUA_TG_PT_UNAVAILABLE,
3468 	},
3469 	[TCM_ALUA_STATE_TRANSITION] = {
3470 		.key = NOT_READY,
3471 		.asc = 0x04,
3472 		.ascq = ASCQ_04H_ALUA_STATE_TRANSITION,
3473 	},
3474 	[TCM_ALUA_OFFLINE] = {
3475 		.key = NOT_READY,
3476 		.asc = 0x04,
3477 		.ascq = ASCQ_04H_ALUA_OFFLINE,
3478 	},
3479 };
3480 
3481 /**
3482  * translate_sense_reason - translate a sense reason into T10 key, asc and ascq
3483  * @cmd: SCSI command in which the resulting sense buffer or SCSI status will
3484  *   be stored.
3485  * @reason: LIO sense reason code. If this argument has the value
3486  *   TCM_CHECK_CONDITION_UNIT_ATTENTION, try to dequeue a unit attention. If
3487  *   dequeuing a unit attention fails due to multiple commands being processed
3488  *   concurrently, set the command status to BUSY.
3489  *
3490  * Return: 0 upon success or -EINVAL if the sense buffer is too small.
3491  */
3492 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason)
3493 {
3494 	const struct sense_detail *sd;
3495 	u8 *buffer = cmd->sense_buffer;
3496 	int r = (__force int)reason;
3497 	u8 key, asc, ascq;
3498 	bool desc_format = target_sense_desc_format(cmd->se_dev);
3499 
3500 	if (r < ARRAY_SIZE(sense_detail_table) && sense_detail_table[r].key)
3501 		sd = &sense_detail_table[r];
3502 	else
3503 		sd = &sense_detail_table[(__force int)
3504 				       TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE];
3505 
3506 	key = sd->key;
3507 	if (reason == TCM_CHECK_CONDITION_UNIT_ATTENTION) {
3508 		if (!core_scsi3_ua_for_check_condition(cmd, &key, &asc,
3509 						       &ascq)) {
3510 			cmd->scsi_status = SAM_STAT_BUSY;
3511 			return;
3512 		}
3513 	} else {
3514 		WARN_ON_ONCE(sd->asc == 0);
3515 		asc = sd->asc;
3516 		ascq = sd->ascq;
3517 	}
3518 
3519 	cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
3520 	cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3521 	cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER;
3522 	scsi_build_sense_buffer(desc_format, buffer, key, asc, ascq);
3523 	if (sd->add_sense_info)
3524 		WARN_ON_ONCE(scsi_set_sense_information(buffer,
3525 							cmd->scsi_sense_length,
3526 							cmd->sense_info) < 0);
3527 }
3528 
3529 int
3530 transport_send_check_condition_and_sense(struct se_cmd *cmd,
3531 		sense_reason_t reason, int from_transport)
3532 {
3533 	unsigned long flags;
3534 
3535 	WARN_ON_ONCE(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB);
3536 
3537 	spin_lock_irqsave(&cmd->t_state_lock, flags);
3538 	if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3539 		spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3540 		return 0;
3541 	}
3542 	cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
3543 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3544 
3545 	if (!from_transport)
3546 		translate_sense_reason(cmd, reason);
3547 
3548 	trace_target_cmd_complete(cmd);
3549 	return cmd->se_tfo->queue_status(cmd);
3550 }
3551 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3552 
3553 /**
3554  * target_send_busy - Send SCSI BUSY status back to the initiator
3555  * @cmd: SCSI command for which to send a BUSY reply.
3556  *
3557  * Note: Only call this function if target_submit_cmd*() failed.
3558  */
3559 int target_send_busy(struct se_cmd *cmd)
3560 {
3561 	WARN_ON_ONCE(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB);
3562 
3563 	cmd->scsi_status = SAM_STAT_BUSY;
3564 	trace_target_cmd_complete(cmd);
3565 	return cmd->se_tfo->queue_status(cmd);
3566 }
3567 EXPORT_SYMBOL(target_send_busy);
3568 
3569 static void target_tmr_work(struct work_struct *work)
3570 {
3571 	struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3572 	struct se_device *dev = cmd->se_dev;
3573 	struct se_tmr_req *tmr = cmd->se_tmr_req;
3574 	int ret;
3575 
3576 	if (cmd->transport_state & CMD_T_ABORTED)
3577 		goto aborted;
3578 
3579 	switch (tmr->function) {
3580 	case TMR_ABORT_TASK:
3581 		core_tmr_abort_task(dev, tmr, cmd->se_sess);
3582 		break;
3583 	case TMR_ABORT_TASK_SET:
3584 	case TMR_CLEAR_ACA:
3585 	case TMR_CLEAR_TASK_SET:
3586 		tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3587 		break;
3588 	case TMR_LUN_RESET:
3589 		ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3590 		tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3591 					 TMR_FUNCTION_REJECTED;
3592 		if (tmr->response == TMR_FUNCTION_COMPLETE) {
3593 			target_dev_ua_allocate(dev, 0x29,
3594 					       ASCQ_29H_BUS_DEVICE_RESET_FUNCTION_OCCURRED);
3595 		}
3596 		break;
3597 	case TMR_TARGET_WARM_RESET:
3598 		tmr->response = TMR_FUNCTION_REJECTED;
3599 		break;
3600 	case TMR_TARGET_COLD_RESET:
3601 		tmr->response = TMR_FUNCTION_REJECTED;
3602 		break;
3603 	default:
3604 		pr_err("Unknown TMR function: 0x%02x.\n",
3605 				tmr->function);
3606 		tmr->response = TMR_FUNCTION_REJECTED;
3607 		break;
3608 	}
3609 
3610 	if (cmd->transport_state & CMD_T_ABORTED)
3611 		goto aborted;
3612 
3613 	cmd->se_tfo->queue_tm_rsp(cmd);
3614 
3615 	transport_lun_remove_cmd(cmd);
3616 	transport_cmd_check_stop_to_fabric(cmd);
3617 	return;
3618 
3619 aborted:
3620 	target_handle_abort(cmd);
3621 }
3622 
3623 int transport_generic_handle_tmr(
3624 	struct se_cmd *cmd)
3625 {
3626 	unsigned long flags;
3627 	bool aborted = false;
3628 
3629 	spin_lock_irqsave(&cmd->t_state_lock, flags);
3630 	if (cmd->transport_state & CMD_T_ABORTED) {
3631 		aborted = true;
3632 	} else {
3633 		cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3634 		cmd->transport_state |= CMD_T_ACTIVE;
3635 	}
3636 	spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3637 
3638 	if (aborted) {
3639 		pr_warn_ratelimited("handle_tmr caught CMD_T_ABORTED TMR %d ref_tag: %llu tag: %llu\n",
3640 				    cmd->se_tmr_req->function,
3641 				    cmd->se_tmr_req->ref_task_tag, cmd->tag);
3642 		target_handle_abort(cmd);
3643 		return 0;
3644 	}
3645 
3646 	INIT_WORK(&cmd->work, target_tmr_work);
3647 	schedule_work(&cmd->work);
3648 	return 0;
3649 }
3650 EXPORT_SYMBOL(transport_generic_handle_tmr);
3651 
3652 bool
3653 target_check_wce(struct se_device *dev)
3654 {
3655 	bool wce = false;
3656 
3657 	if (dev->transport->get_write_cache)
3658 		wce = dev->transport->get_write_cache(dev);
3659 	else if (dev->dev_attrib.emulate_write_cache > 0)
3660 		wce = true;
3661 
3662 	return wce;
3663 }
3664 
3665 bool
3666 target_check_fua(struct se_device *dev)
3667 {
3668 	return target_check_wce(dev) && dev->dev_attrib.emulate_fua_write > 0;
3669 }
3670