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