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