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