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