xref: /linux-6.15/drivers/usb/gadget/function/f_tcm.c (revision 29ed1705)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Target based USB-Gadget
3  *
4  * UAS protocol handling, target callbacks, configfs handling,
5  * BBB (USB Mass Storage Class Bulk-Only (BBB) and Transport protocol handling.
6  *
7  * Author: Sebastian Andrzej Siewior <bigeasy at linutronix dot de>
8  */
9 #include <linux/kernel.h>
10 #include <linux/module.h>
11 #include <linux/types.h>
12 #include <linux/string.h>
13 #include <linux/configfs.h>
14 #include <linux/ctype.h>
15 #include <linux/delay.h>
16 #include <linux/usb/ch9.h>
17 #include <linux/usb/composite.h>
18 #include <linux/usb/gadget.h>
19 #include <linux/usb/storage.h>
20 #include <scsi/scsi_tcq.h>
21 #include <target/target_core_base.h>
22 #include <target/target_core_fabric.h>
23 #include <linux/unaligned.h>
24 
25 #include "tcm.h"
26 #include "u_tcm.h"
27 #include "configfs.h"
28 
29 #define TPG_INSTANCES		1
30 
31 struct tpg_instance {
32 	struct usb_function_instance	*func_inst;
33 	struct usbg_tpg			*tpg;
34 };
35 
36 static struct tpg_instance tpg_instances[TPG_INSTANCES];
37 
38 static DEFINE_MUTEX(tpg_instances_lock);
39 
40 static inline struct f_uas *to_f_uas(struct usb_function *f)
41 {
42 	return container_of(f, struct f_uas, function);
43 }
44 
45 /* Start bot.c code */
46 
47 static int bot_enqueue_cmd_cbw(struct f_uas *fu)
48 {
49 	int ret;
50 
51 	if (fu->flags & USBG_BOT_CMD_PEND)
52 		return 0;
53 
54 	ret = usb_ep_queue(fu->ep_out, fu->cmd[0].req, GFP_ATOMIC);
55 	if (!ret)
56 		fu->flags |= USBG_BOT_CMD_PEND;
57 	return ret;
58 }
59 
60 static void bot_status_complete(struct usb_ep *ep, struct usb_request *req)
61 {
62 	struct usbg_cmd *cmd = req->context;
63 	struct f_uas *fu = cmd->fu;
64 
65 	transport_generic_free_cmd(&cmd->se_cmd, 0);
66 	if (req->status == -ESHUTDOWN)
67 		return;
68 
69 	if (req->status < 0)
70 		pr_err("ERR %s(%d)\n", __func__, __LINE__);
71 
72 	/* CSW completed, wait for next CBW */
73 	bot_enqueue_cmd_cbw(fu);
74 }
75 
76 static void bot_enqueue_sense_code(struct f_uas *fu, struct usbg_cmd *cmd)
77 {
78 	struct bulk_cs_wrap *csw = &fu->bot_status.csw;
79 	int ret;
80 	unsigned int csw_stat;
81 
82 	csw_stat = cmd->csw_code;
83 	csw->Tag = cmd->bot_tag;
84 	csw->Status = csw_stat;
85 	fu->bot_status.req->context = cmd;
86 	ret = usb_ep_queue(fu->ep_in, fu->bot_status.req, GFP_ATOMIC);
87 	if (ret)
88 		pr_err("%s(%d) ERR: %d\n", __func__, __LINE__, ret);
89 }
90 
91 static void bot_err_compl(struct usb_ep *ep, struct usb_request *req)
92 {
93 	struct usbg_cmd *cmd = req->context;
94 	struct f_uas *fu = cmd->fu;
95 
96 	if (req->status < 0)
97 		pr_err("ERR %s(%d)\n", __func__, __LINE__);
98 
99 	if (cmd->data_len) {
100 		if (cmd->data_len > ep->maxpacket) {
101 			req->length = ep->maxpacket;
102 			cmd->data_len -= ep->maxpacket;
103 		} else {
104 			req->length = cmd->data_len;
105 			cmd->data_len = 0;
106 		}
107 
108 		usb_ep_queue(ep, req, GFP_ATOMIC);
109 		return;
110 	}
111 	bot_enqueue_sense_code(fu, cmd);
112 }
113 
114 static void bot_send_bad_status(struct usbg_cmd *cmd)
115 {
116 	struct f_uas *fu = cmd->fu;
117 	struct bulk_cs_wrap *csw = &fu->bot_status.csw;
118 	struct usb_request *req;
119 	struct usb_ep *ep;
120 
121 	csw->Residue = cpu_to_le32(cmd->data_len);
122 
123 	if (cmd->data_len) {
124 		if (cmd->is_read) {
125 			ep = fu->ep_in;
126 			req = fu->bot_req_in;
127 		} else {
128 			ep = fu->ep_out;
129 			req = fu->bot_req_out;
130 		}
131 
132 		if (cmd->data_len > fu->ep_in->maxpacket) {
133 			req->length = ep->maxpacket;
134 			cmd->data_len -= ep->maxpacket;
135 		} else {
136 			req->length = cmd->data_len;
137 			cmd->data_len = 0;
138 		}
139 		req->complete = bot_err_compl;
140 		req->context = cmd;
141 		req->buf = fu->cmd[0].buf;
142 		usb_ep_queue(ep, req, GFP_KERNEL);
143 	} else {
144 		bot_enqueue_sense_code(fu, cmd);
145 	}
146 }
147 
148 static int bot_send_status(struct usbg_cmd *cmd, bool moved_data)
149 {
150 	struct f_uas *fu = cmd->fu;
151 	struct bulk_cs_wrap *csw = &fu->bot_status.csw;
152 	int ret;
153 
154 	if (cmd->se_cmd.scsi_status == SAM_STAT_GOOD) {
155 		if (!moved_data && cmd->data_len) {
156 			/*
157 			 * the host wants to move data, we don't. Fill / empty
158 			 * the pipe and then send the csw with reside set.
159 			 */
160 			cmd->csw_code = US_BULK_STAT_OK;
161 			bot_send_bad_status(cmd);
162 			return 0;
163 		}
164 
165 		csw->Tag = cmd->bot_tag;
166 		csw->Residue = cpu_to_le32(0);
167 		csw->Status = US_BULK_STAT_OK;
168 		fu->bot_status.req->context = cmd;
169 
170 		ret = usb_ep_queue(fu->ep_in, fu->bot_status.req, GFP_KERNEL);
171 		if (ret)
172 			pr_err("%s(%d) ERR: %d\n", __func__, __LINE__, ret);
173 	} else {
174 		cmd->csw_code = US_BULK_STAT_FAIL;
175 		bot_send_bad_status(cmd);
176 	}
177 	return 0;
178 }
179 
180 /*
181  * Called after command (no data transfer) or after the write (to device)
182  * operation is completed
183  */
184 static int bot_send_status_response(struct usbg_cmd *cmd)
185 {
186 	bool moved_data = false;
187 
188 	if (!cmd->is_read)
189 		moved_data = true;
190 	return bot_send_status(cmd, moved_data);
191 }
192 
193 /* Read request completed, now we have to send the CSW */
194 static void bot_read_compl(struct usb_ep *ep, struct usb_request *req)
195 {
196 	struct usbg_cmd *cmd = req->context;
197 
198 	if (req->status < 0)
199 		pr_err("ERR %s(%d)\n", __func__, __LINE__);
200 
201 	if (req->status == -ESHUTDOWN) {
202 		transport_generic_free_cmd(&cmd->se_cmd, 0);
203 		return;
204 	}
205 
206 	bot_send_status(cmd, true);
207 }
208 
209 static int bot_send_read_response(struct usbg_cmd *cmd)
210 {
211 	struct f_uas *fu = cmd->fu;
212 	struct se_cmd *se_cmd = &cmd->se_cmd;
213 	struct usb_gadget *gadget = fuas_to_gadget(fu);
214 	int ret;
215 
216 	if (!cmd->data_len) {
217 		cmd->csw_code = US_BULK_STAT_PHASE;
218 		bot_send_bad_status(cmd);
219 		return 0;
220 	}
221 
222 	if (!gadget->sg_supported) {
223 		cmd->data_buf = kmalloc(se_cmd->data_length, GFP_ATOMIC);
224 		if (!cmd->data_buf)
225 			return -ENOMEM;
226 
227 		sg_copy_to_buffer(se_cmd->t_data_sg,
228 				se_cmd->t_data_nents,
229 				cmd->data_buf,
230 				se_cmd->data_length);
231 
232 		fu->bot_req_in->buf = cmd->data_buf;
233 	} else {
234 		fu->bot_req_in->buf = NULL;
235 		fu->bot_req_in->num_sgs = se_cmd->t_data_nents;
236 		fu->bot_req_in->sg = se_cmd->t_data_sg;
237 	}
238 
239 	fu->bot_req_in->complete = bot_read_compl;
240 	fu->bot_req_in->length = se_cmd->data_length;
241 	fu->bot_req_in->context = cmd;
242 	ret = usb_ep_queue(fu->ep_in, fu->bot_req_in, GFP_ATOMIC);
243 	if (ret)
244 		pr_err("%s(%d)\n", __func__, __LINE__);
245 	return 0;
246 }
247 
248 static void usbg_data_write_cmpl(struct usb_ep *, struct usb_request *);
249 static int usbg_prepare_w_request(struct usbg_cmd *, struct usb_request *);
250 
251 static int bot_send_write_request(struct usbg_cmd *cmd)
252 {
253 	struct f_uas *fu = cmd->fu;
254 	int ret;
255 
256 	cmd->fu = fu;
257 
258 	if (!cmd->data_len) {
259 		cmd->csw_code = US_BULK_STAT_PHASE;
260 		return -EINVAL;
261 	}
262 
263 	ret = usbg_prepare_w_request(cmd, fu->bot_req_out);
264 	if (ret)
265 		goto cleanup;
266 	ret = usb_ep_queue(fu->ep_out, fu->bot_req_out, GFP_KERNEL);
267 	if (ret)
268 		pr_err("%s(%d)\n", __func__, __LINE__);
269 
270 cleanup:
271 	return ret;
272 }
273 
274 static int bot_submit_command(struct f_uas *, void *, unsigned int);
275 
276 static void bot_cmd_complete(struct usb_ep *ep, struct usb_request *req)
277 {
278 	struct f_uas *fu = req->context;
279 	int ret;
280 
281 	if (req->status == -ESHUTDOWN)
282 		return;
283 
284 	fu->flags &= ~USBG_BOT_CMD_PEND;
285 
286 	if (req->status < 0)
287 		return;
288 
289 	ret = bot_submit_command(fu, req->buf, req->actual);
290 	if (ret)
291 		pr_err("%s(%d): %d\n", __func__, __LINE__, ret);
292 }
293 
294 static int bot_prepare_reqs(struct f_uas *fu)
295 {
296 	int ret;
297 
298 	fu->bot_req_in = usb_ep_alloc_request(fu->ep_in, GFP_KERNEL);
299 	if (!fu->bot_req_in)
300 		goto err;
301 
302 	fu->bot_req_out = usb_ep_alloc_request(fu->ep_out, GFP_KERNEL);
303 	if (!fu->bot_req_out)
304 		goto err_out;
305 
306 	fu->cmd[0].req = usb_ep_alloc_request(fu->ep_out, GFP_KERNEL);
307 	if (!fu->cmd[0].req)
308 		goto err_cmd;
309 
310 	fu->bot_status.req = usb_ep_alloc_request(fu->ep_in, GFP_KERNEL);
311 	if (!fu->bot_status.req)
312 		goto err_sts;
313 
314 	fu->bot_status.req->buf = &fu->bot_status.csw;
315 	fu->bot_status.req->length = US_BULK_CS_WRAP_LEN;
316 	fu->bot_status.req->complete = bot_status_complete;
317 	fu->bot_status.csw.Signature = cpu_to_le32(US_BULK_CS_SIGN);
318 
319 	fu->cmd[0].buf = kmalloc(fu->ep_out->maxpacket, GFP_KERNEL);
320 	if (!fu->cmd[0].buf)
321 		goto err_buf;
322 
323 	fu->cmd[0].req->complete = bot_cmd_complete;
324 	fu->cmd[0].req->buf = fu->cmd[0].buf;
325 	fu->cmd[0].req->length = fu->ep_out->maxpacket;
326 	fu->cmd[0].req->context = fu;
327 
328 	ret = bot_enqueue_cmd_cbw(fu);
329 	if (ret)
330 		goto err_queue;
331 	return 0;
332 err_queue:
333 	kfree(fu->cmd[0].buf);
334 	fu->cmd[0].buf = NULL;
335 err_buf:
336 	usb_ep_free_request(fu->ep_in, fu->bot_status.req);
337 err_sts:
338 	usb_ep_free_request(fu->ep_out, fu->cmd[0].req);
339 	fu->cmd[0].req = NULL;
340 err_cmd:
341 	usb_ep_free_request(fu->ep_out, fu->bot_req_out);
342 	fu->bot_req_out = NULL;
343 err_out:
344 	usb_ep_free_request(fu->ep_in, fu->bot_req_in);
345 	fu->bot_req_in = NULL;
346 err:
347 	pr_err("BOT: endpoint setup failed\n");
348 	return -ENOMEM;
349 }
350 
351 static void bot_cleanup_old_alt(struct f_uas *fu)
352 {
353 	if (!(fu->flags & USBG_ENABLED))
354 		return;
355 
356 	usb_ep_disable(fu->ep_in);
357 	usb_ep_disable(fu->ep_out);
358 
359 	if (!fu->bot_req_in)
360 		return;
361 
362 	usb_ep_free_request(fu->ep_in, fu->bot_req_in);
363 	usb_ep_free_request(fu->ep_out, fu->bot_req_out);
364 	usb_ep_free_request(fu->ep_out, fu->cmd[0].req);
365 	usb_ep_free_request(fu->ep_in, fu->bot_status.req);
366 
367 	kfree(fu->cmd[0].buf);
368 
369 	fu->bot_req_in = NULL;
370 	fu->bot_req_out = NULL;
371 	fu->cmd[0].req = NULL;
372 	fu->bot_status.req = NULL;
373 	fu->cmd[0].buf = NULL;
374 }
375 
376 static void bot_set_alt(struct f_uas *fu)
377 {
378 	struct usb_function *f = &fu->function;
379 	struct usb_gadget *gadget = f->config->cdev->gadget;
380 	int ret;
381 
382 	fu->flags = USBG_IS_BOT;
383 
384 	config_ep_by_speed_and_alt(gadget, f, fu->ep_in, USB_G_ALT_INT_BBB);
385 	ret = usb_ep_enable(fu->ep_in);
386 	if (ret)
387 		goto err_b_in;
388 
389 	config_ep_by_speed_and_alt(gadget, f, fu->ep_out, USB_G_ALT_INT_BBB);
390 	ret = usb_ep_enable(fu->ep_out);
391 	if (ret)
392 		goto err_b_out;
393 
394 	ret = bot_prepare_reqs(fu);
395 	if (ret)
396 		goto err_wq;
397 	fu->flags |= USBG_ENABLED;
398 	pr_info("Using the BOT protocol\n");
399 	return;
400 err_wq:
401 	usb_ep_disable(fu->ep_out);
402 err_b_out:
403 	usb_ep_disable(fu->ep_in);
404 err_b_in:
405 	fu->flags = USBG_IS_BOT;
406 }
407 
408 static int usbg_bot_setup(struct usb_function *f,
409 		const struct usb_ctrlrequest *ctrl)
410 {
411 	struct f_uas *fu = to_f_uas(f);
412 	struct usb_composite_dev *cdev = f->config->cdev;
413 	u16 w_value = le16_to_cpu(ctrl->wValue);
414 	u16 w_length = le16_to_cpu(ctrl->wLength);
415 	int luns;
416 	u8 *ret_lun;
417 
418 	switch (ctrl->bRequest) {
419 	case US_BULK_GET_MAX_LUN:
420 		if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_CLASS |
421 					USB_RECIP_INTERFACE))
422 			return -ENOTSUPP;
423 
424 		if (w_length < 1)
425 			return -EINVAL;
426 		if (w_value != 0)
427 			return -EINVAL;
428 		luns = atomic_read(&fu->tpg->tpg_port_count);
429 		if (!luns) {
430 			pr_err("No LUNs configured?\n");
431 			return -EINVAL;
432 		}
433 		luns--;
434 		if (luns > US_BULK_MAX_LUN_LIMIT) {
435 			pr_info_once("Limiting the number of luns to 16\n");
436 			luns = US_BULK_MAX_LUN_LIMIT;
437 		}
438 		ret_lun = cdev->req->buf;
439 		*ret_lun = luns;
440 		cdev->req->length = 1;
441 		return usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
442 
443 	case US_BULK_RESET_REQUEST:
444 		/* XXX maybe we should remove previous requests for IN + OUT */
445 		bot_enqueue_cmd_cbw(fu);
446 		return 0;
447 	}
448 	return -ENOTSUPP;
449 }
450 
451 /* Start uas.c code */
452 
453 static int tcm_to_uasp_response(enum tcm_tmrsp_table code)
454 {
455 	switch (code) {
456 	case TMR_FUNCTION_FAILED:
457 		return RC_TMF_FAILED;
458 	case TMR_FUNCTION_COMPLETE:
459 	case TMR_TASK_DOES_NOT_EXIST:
460 		return RC_TMF_COMPLETE;
461 	case TMR_LUN_DOES_NOT_EXIST:
462 		return RC_INCORRECT_LUN;
463 	case TMR_FUNCTION_REJECTED:
464 	case TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED:
465 	default:
466 		return RC_TMF_NOT_SUPPORTED;
467 	}
468 }
469 
470 static unsigned char uasp_to_tcm_func(int code)
471 {
472 	switch (code) {
473 	case TMF_ABORT_TASK:
474 		return TMR_ABORT_TASK;
475 	case TMF_ABORT_TASK_SET:
476 		return TMR_ABORT_TASK_SET;
477 	case TMF_CLEAR_TASK_SET:
478 		return TMR_CLEAR_TASK_SET;
479 	case TMF_LOGICAL_UNIT_RESET:
480 		return TMR_LUN_RESET;
481 	case TMF_CLEAR_ACA:
482 		return TMR_CLEAR_ACA;
483 	case TMF_I_T_NEXUS_RESET:
484 	case TMF_QUERY_TASK:
485 	case TMF_QUERY_TASK_SET:
486 	case TMF_QUERY_ASYNC_EVENT:
487 	default:
488 		return TMR_UNKNOWN;
489 	}
490 }
491 
492 static void uasp_cleanup_one_stream(struct f_uas *fu, struct uas_stream *stream)
493 {
494 	/* We have either all three allocated or none */
495 	if (!stream->req_in)
496 		return;
497 
498 	usb_ep_free_request(fu->ep_in, stream->req_in);
499 	usb_ep_free_request(fu->ep_out, stream->req_out);
500 	usb_ep_free_request(fu->ep_status, stream->req_status);
501 
502 	stream->req_in = NULL;
503 	stream->req_out = NULL;
504 	stream->req_status = NULL;
505 }
506 
507 static void uasp_free_cmdreq(struct f_uas *fu)
508 {
509 	int i;
510 
511 	for (i = 0; i < USBG_NUM_CMDS; i++) {
512 		usb_ep_free_request(fu->ep_cmd, fu->cmd[i].req);
513 		kfree(fu->cmd[i].buf);
514 		fu->cmd[i].req = NULL;
515 		fu->cmd[i].buf = NULL;
516 	}
517 }
518 
519 static void uasp_cleanup_old_alt(struct f_uas *fu)
520 {
521 	int i;
522 
523 	if (!(fu->flags & USBG_ENABLED))
524 		return;
525 
526 	usb_ep_disable(fu->ep_in);
527 	usb_ep_disable(fu->ep_out);
528 	usb_ep_disable(fu->ep_status);
529 	usb_ep_disable(fu->ep_cmd);
530 
531 	for (i = 0; i < USBG_NUM_CMDS; i++)
532 		uasp_cleanup_one_stream(fu, &fu->stream[i]);
533 	uasp_free_cmdreq(fu);
534 }
535 
536 static void uasp_status_data_cmpl(struct usb_ep *ep, struct usb_request *req);
537 
538 static int uasp_prepare_r_request(struct usbg_cmd *cmd)
539 {
540 	struct se_cmd *se_cmd = &cmd->se_cmd;
541 	struct f_uas *fu = cmd->fu;
542 	struct usb_gadget *gadget = fuas_to_gadget(fu);
543 	struct uas_stream *stream = &fu->stream[se_cmd->map_tag];
544 
545 	if (!gadget->sg_supported) {
546 		cmd->data_buf = kmalloc(se_cmd->data_length, GFP_ATOMIC);
547 		if (!cmd->data_buf)
548 			return -ENOMEM;
549 
550 		sg_copy_to_buffer(se_cmd->t_data_sg,
551 				se_cmd->t_data_nents,
552 				cmd->data_buf,
553 				se_cmd->data_length);
554 
555 		stream->req_in->buf = cmd->data_buf;
556 	} else {
557 		stream->req_in->buf = NULL;
558 		stream->req_in->num_sgs = se_cmd->t_data_nents;
559 		stream->req_in->sg = se_cmd->t_data_sg;
560 	}
561 
562 	stream->req_in->is_last = 1;
563 	stream->req_in->stream_id = cmd->tag;
564 	stream->req_in->complete = uasp_status_data_cmpl;
565 	stream->req_in->length = se_cmd->data_length;
566 	stream->req_in->context = cmd;
567 
568 	cmd->state = UASP_SEND_STATUS;
569 	return 0;
570 }
571 
572 static void uasp_prepare_status(struct usbg_cmd *cmd)
573 {
574 	struct se_cmd *se_cmd = &cmd->se_cmd;
575 	struct sense_iu *iu = &cmd->sense_iu;
576 	struct uas_stream *stream = &cmd->fu->stream[se_cmd->map_tag];
577 
578 	cmd->state = UASP_QUEUE_COMMAND;
579 	iu->iu_id = IU_ID_STATUS;
580 	iu->tag = cpu_to_be16(cmd->tag);
581 
582 	/*
583 	 * iu->status_qual = cpu_to_be16(STATUS QUALIFIER SAM-4. Where R U?);
584 	 */
585 	iu->len = cpu_to_be16(se_cmd->scsi_sense_length);
586 	iu->status = se_cmd->scsi_status;
587 	stream->req_status->is_last = 1;
588 	stream->req_status->stream_id = cmd->tag;
589 	stream->req_status->context = cmd;
590 	stream->req_status->length = se_cmd->scsi_sense_length + 16;
591 	stream->req_status->buf = iu;
592 	stream->req_status->complete = uasp_status_data_cmpl;
593 }
594 
595 static void uasp_prepare_response(struct usbg_cmd *cmd)
596 {
597 	struct se_cmd *se_cmd = &cmd->se_cmd;
598 	struct response_iu *rsp_iu = &cmd->response_iu;
599 	struct uas_stream *stream = &cmd->fu->stream[se_cmd->map_tag];
600 
601 	cmd->state = UASP_QUEUE_COMMAND;
602 	rsp_iu->iu_id = IU_ID_RESPONSE;
603 	rsp_iu->tag = cpu_to_be16(cmd->tag);
604 
605 	if (cmd->tmr_rsp != RC_RESPONSE_UNKNOWN)
606 		rsp_iu->response_code = cmd->tmr_rsp;
607 	else
608 		rsp_iu->response_code =
609 			tcm_to_uasp_response(se_cmd->se_tmr_req->response);
610 
611 	/*
612 	 * The UASP driver must support all the task management functions listed
613 	 * in Table 20 of UAS-r04. To remain compliant while indicate that the
614 	 * TMR did not go through, report RC_TMF_FAILED instead of
615 	 * RC_TMF_NOT_SUPPORTED and print a warning to the user.
616 	 */
617 	switch (cmd->tmr_func) {
618 	case TMF_ABORT_TASK:
619 	case TMF_ABORT_TASK_SET:
620 	case TMF_CLEAR_TASK_SET:
621 	case TMF_LOGICAL_UNIT_RESET:
622 	case TMF_CLEAR_ACA:
623 	case TMF_I_T_NEXUS_RESET:
624 	case TMF_QUERY_TASK:
625 	case TMF_QUERY_TASK_SET:
626 	case TMF_QUERY_ASYNC_EVENT:
627 		if (rsp_iu->response_code == RC_TMF_NOT_SUPPORTED) {
628 			struct usb_gadget *gadget = fuas_to_gadget(cmd->fu);
629 
630 			dev_warn(&gadget->dev, "TMF function %d not supported\n",
631 				 cmd->tmr_func);
632 			rsp_iu->response_code = RC_TMF_FAILED;
633 		}
634 		break;
635 	default:
636 		break;
637 	}
638 
639 	stream->req_status->is_last = 1;
640 	stream->req_status->stream_id = cmd->tag;
641 	stream->req_status->context = cmd;
642 	stream->req_status->length = sizeof(struct response_iu);
643 	stream->req_status->buf = rsp_iu;
644 	stream->req_status->complete = uasp_status_data_cmpl;
645 }
646 
647 static void usbg_release_cmd(struct se_cmd *se_cmd);
648 static int uasp_send_tm_response(struct usbg_cmd *cmd);
649 
650 static void uasp_status_data_cmpl(struct usb_ep *ep, struct usb_request *req)
651 {
652 	struct usbg_cmd *cmd = req->context;
653 	struct f_uas *fu = cmd->fu;
654 	struct uas_stream *stream = &fu->stream[cmd->se_cmd.map_tag];
655 	int ret;
656 
657 	if (req->status == -ESHUTDOWN)
658 		goto cleanup;
659 
660 	switch (cmd->state) {
661 	case UASP_SEND_DATA:
662 		ret = uasp_prepare_r_request(cmd);
663 		if (ret)
664 			goto cleanup;
665 		ret = usb_ep_queue(fu->ep_in, stream->req_in, GFP_ATOMIC);
666 		if (ret)
667 			pr_err("%s(%d) => %d\n", __func__, __LINE__, ret);
668 		break;
669 
670 	case UASP_RECEIVE_DATA:
671 		ret = usbg_prepare_w_request(cmd, stream->req_out);
672 		if (ret)
673 			goto cleanup;
674 		ret = usb_ep_queue(fu->ep_out, stream->req_out, GFP_ATOMIC);
675 		if (ret)
676 			pr_err("%s(%d) => %d\n", __func__, __LINE__, ret);
677 		break;
678 
679 	case UASP_SEND_STATUS:
680 		uasp_prepare_status(cmd);
681 		ret = usb_ep_queue(fu->ep_status, stream->req_status,
682 				GFP_ATOMIC);
683 		if (ret)
684 			pr_err("%s(%d) => %d\n", __func__, __LINE__, ret);
685 		break;
686 
687 	case UASP_QUEUE_COMMAND:
688 		/*
689 		 * Overlapped command detected and cancelled.
690 		 * So send overlapped attempted status.
691 		 */
692 		if (cmd->tmr_rsp == RC_OVERLAPPED_TAG &&
693 		    req->status == -ECONNRESET) {
694 			uasp_send_tm_response(cmd);
695 			return;
696 		}
697 
698 		hash_del(&stream->node);
699 
700 		/*
701 		 * If no command submitted to target core here, just free the
702 		 * bitmap index. This is for the cases where f_tcm handles
703 		 * status response instead of the target core.
704 		 */
705 		if (cmd->tmr_rsp != RC_OVERLAPPED_TAG &&
706 		    cmd->tmr_rsp != RC_RESPONSE_UNKNOWN) {
707 			struct se_session *se_sess;
708 
709 			se_sess = fu->tpg->tpg_nexus->tvn_se_sess;
710 			sbitmap_queue_clear(&se_sess->sess_tag_pool,
711 					    cmd->se_cmd.map_tag,
712 					    cmd->se_cmd.map_cpu);
713 		} else {
714 			transport_generic_free_cmd(&cmd->se_cmd, 0);
715 		}
716 
717 		usb_ep_queue(fu->ep_cmd, cmd->req, GFP_ATOMIC);
718 		complete(&stream->cmd_completion);
719 		break;
720 
721 	default:
722 		BUG();
723 	}
724 	return;
725 
726 cleanup:
727 	hash_del(&stream->node);
728 	transport_generic_free_cmd(&cmd->se_cmd, 0);
729 }
730 
731 static int uasp_send_status_response(struct usbg_cmd *cmd)
732 {
733 	struct f_uas *fu = cmd->fu;
734 	struct uas_stream *stream = &fu->stream[cmd->se_cmd.map_tag];
735 	struct sense_iu *iu = &cmd->sense_iu;
736 
737 	iu->tag = cpu_to_be16(cmd->tag);
738 	cmd->fu = fu;
739 	uasp_prepare_status(cmd);
740 	return usb_ep_queue(fu->ep_status, stream->req_status, GFP_ATOMIC);
741 }
742 
743 static int uasp_send_tm_response(struct usbg_cmd *cmd)
744 {
745 	struct f_uas *fu = cmd->fu;
746 	struct uas_stream *stream = &fu->stream[cmd->se_cmd.map_tag];
747 	struct response_iu *iu = &cmd->response_iu;
748 
749 	iu->tag = cpu_to_be16(cmd->tag);
750 	cmd->fu = fu;
751 	uasp_prepare_response(cmd);
752 	return usb_ep_queue(fu->ep_status, stream->req_status, GFP_ATOMIC);
753 }
754 
755 static int uasp_send_read_response(struct usbg_cmd *cmd)
756 {
757 	struct f_uas *fu = cmd->fu;
758 	struct uas_stream *stream = &fu->stream[cmd->se_cmd.map_tag];
759 	struct sense_iu *iu = &cmd->sense_iu;
760 	int ret;
761 
762 	cmd->fu = fu;
763 
764 	iu->tag = cpu_to_be16(cmd->tag);
765 	if (fu->flags & USBG_USE_STREAMS) {
766 
767 		ret = uasp_prepare_r_request(cmd);
768 		if (ret)
769 			goto out;
770 		ret = usb_ep_queue(fu->ep_in, stream->req_in, GFP_ATOMIC);
771 		if (ret) {
772 			pr_err("%s(%d) => %d\n", __func__, __LINE__, ret);
773 			kfree(cmd->data_buf);
774 			cmd->data_buf = NULL;
775 		}
776 
777 	} else {
778 
779 		iu->iu_id = IU_ID_READ_READY;
780 		iu->tag = cpu_to_be16(cmd->tag);
781 
782 		stream->req_status->complete = uasp_status_data_cmpl;
783 		stream->req_status->context = cmd;
784 
785 		cmd->state = UASP_SEND_DATA;
786 		stream->req_status->buf = iu;
787 		stream->req_status->length = sizeof(struct iu);
788 
789 		ret = usb_ep_queue(fu->ep_status, stream->req_status,
790 				GFP_ATOMIC);
791 		if (ret)
792 			pr_err("%s(%d) => %d\n", __func__, __LINE__, ret);
793 	}
794 out:
795 	return ret;
796 }
797 
798 static int uasp_send_write_request(struct usbg_cmd *cmd)
799 {
800 	struct f_uas *fu = cmd->fu;
801 	struct se_cmd *se_cmd = &cmd->se_cmd;
802 	struct uas_stream *stream = &fu->stream[se_cmd->map_tag];
803 	struct sense_iu *iu = &cmd->sense_iu;
804 	int ret;
805 
806 	cmd->fu = fu;
807 
808 	iu->tag = cpu_to_be16(cmd->tag);
809 
810 	if (fu->flags & USBG_USE_STREAMS) {
811 
812 		ret = usbg_prepare_w_request(cmd, stream->req_out);
813 		if (ret)
814 			goto cleanup;
815 		ret = usb_ep_queue(fu->ep_out, stream->req_out, GFP_ATOMIC);
816 		if (ret)
817 			pr_err("%s(%d)\n", __func__, __LINE__);
818 
819 	} else {
820 
821 		iu->iu_id = IU_ID_WRITE_READY;
822 		iu->tag = cpu_to_be16(cmd->tag);
823 
824 		stream->req_status->complete = uasp_status_data_cmpl;
825 		stream->req_status->context = cmd;
826 
827 		cmd->state = UASP_RECEIVE_DATA;
828 		stream->req_status->buf = iu;
829 		stream->req_status->length = sizeof(struct iu);
830 
831 		ret = usb_ep_queue(fu->ep_status, stream->req_status,
832 				GFP_ATOMIC);
833 		if (ret)
834 			pr_err("%s(%d)\n", __func__, __LINE__);
835 	}
836 
837 cleanup:
838 	return ret;
839 }
840 
841 static int usbg_submit_command(struct f_uas *, struct usb_request *);
842 
843 static void uasp_cmd_complete(struct usb_ep *ep, struct usb_request *req)
844 {
845 	struct f_uas *fu = req->context;
846 
847 	if (req->status == -ESHUTDOWN)
848 		return;
849 
850 	if (req->status < 0) {
851 		usb_ep_queue(fu->ep_cmd, req, GFP_ATOMIC);
852 		return;
853 	}
854 
855 	usbg_submit_command(fu, req);
856 }
857 
858 static int uasp_alloc_stream_res(struct f_uas *fu, struct uas_stream *stream)
859 {
860 	init_completion(&stream->cmd_completion);
861 
862 	stream->req_in = usb_ep_alloc_request(fu->ep_in, GFP_KERNEL);
863 	if (!stream->req_in)
864 		goto out;
865 
866 	stream->req_out = usb_ep_alloc_request(fu->ep_out, GFP_KERNEL);
867 	if (!stream->req_out)
868 		goto err_out;
869 
870 	stream->req_status = usb_ep_alloc_request(fu->ep_status, GFP_KERNEL);
871 	if (!stream->req_status)
872 		goto err_sts;
873 
874 	return 0;
875 
876 err_sts:
877 	usb_ep_free_request(fu->ep_out, stream->req_out);
878 	stream->req_out = NULL;
879 err_out:
880 	usb_ep_free_request(fu->ep_in, stream->req_in);
881 	stream->req_in = NULL;
882 out:
883 	return -ENOMEM;
884 }
885 
886 static int uasp_alloc_cmd(struct f_uas *fu, int i)
887 {
888 	fu->cmd[i].req = usb_ep_alloc_request(fu->ep_cmd, GFP_KERNEL);
889 	if (!fu->cmd[i].req)
890 		goto err;
891 
892 	fu->cmd[i].buf = kmalloc(fu->ep_cmd->maxpacket, GFP_KERNEL);
893 	if (!fu->cmd[i].buf)
894 		goto err_buf;
895 
896 	fu->cmd[i].req->complete = uasp_cmd_complete;
897 	fu->cmd[i].req->buf = fu->cmd[i].buf;
898 	fu->cmd[i].req->length = fu->ep_cmd->maxpacket;
899 	fu->cmd[i].req->context = fu;
900 	return 0;
901 
902 err_buf:
903 	usb_ep_free_request(fu->ep_cmd, fu->cmd[i].req);
904 err:
905 	return -ENOMEM;
906 }
907 
908 static int uasp_prepare_reqs(struct f_uas *fu)
909 {
910 	int ret;
911 	int i;
912 
913 	for (i = 0; i < USBG_NUM_CMDS; i++) {
914 		ret = uasp_alloc_stream_res(fu, &fu->stream[i]);
915 		if (ret)
916 			goto err_cleanup;
917 	}
918 
919 	for (i = 0; i < USBG_NUM_CMDS; i++) {
920 		ret = uasp_alloc_cmd(fu, i);
921 		if (ret)
922 			goto err_free_stream;
923 
924 		ret = usb_ep_queue(fu->ep_cmd, fu->cmd[i].req, GFP_ATOMIC);
925 		if (ret)
926 			goto err_free_stream;
927 	}
928 
929 	return 0;
930 
931 err_free_stream:
932 	uasp_free_cmdreq(fu);
933 
934 err_cleanup:
935 	if (i) {
936 		do {
937 			uasp_cleanup_one_stream(fu, &fu->stream[i - 1]);
938 			i--;
939 		} while (i);
940 	}
941 	pr_err("UASP: endpoint setup failed\n");
942 	return ret;
943 }
944 
945 static void uasp_set_alt(struct f_uas *fu)
946 {
947 	struct usb_function *f = &fu->function;
948 	struct usb_gadget *gadget = f->config->cdev->gadget;
949 	int ret;
950 
951 	fu->flags = USBG_IS_UAS;
952 
953 	if (gadget->speed >= USB_SPEED_SUPER)
954 		fu->flags |= USBG_USE_STREAMS;
955 
956 	config_ep_by_speed_and_alt(gadget, f, fu->ep_in, USB_G_ALT_INT_UAS);
957 	ret = usb_ep_enable(fu->ep_in);
958 	if (ret)
959 		goto err_b_in;
960 
961 	config_ep_by_speed_and_alt(gadget, f, fu->ep_out, USB_G_ALT_INT_UAS);
962 	ret = usb_ep_enable(fu->ep_out);
963 	if (ret)
964 		goto err_b_out;
965 
966 	config_ep_by_speed_and_alt(gadget, f, fu->ep_cmd, USB_G_ALT_INT_UAS);
967 	ret = usb_ep_enable(fu->ep_cmd);
968 	if (ret)
969 		goto err_cmd;
970 	config_ep_by_speed_and_alt(gadget, f, fu->ep_status, USB_G_ALT_INT_UAS);
971 	ret = usb_ep_enable(fu->ep_status);
972 	if (ret)
973 		goto err_status;
974 
975 	ret = uasp_prepare_reqs(fu);
976 	if (ret)
977 		goto err_wq;
978 	fu->flags |= USBG_ENABLED;
979 
980 	pr_info("Using the UAS protocol\n");
981 	return;
982 err_wq:
983 	usb_ep_disable(fu->ep_status);
984 err_status:
985 	usb_ep_disable(fu->ep_cmd);
986 err_cmd:
987 	usb_ep_disable(fu->ep_out);
988 err_b_out:
989 	usb_ep_disable(fu->ep_in);
990 err_b_in:
991 	fu->flags = 0;
992 }
993 
994 static int get_cmd_dir(const unsigned char *cdb)
995 {
996 	int ret;
997 
998 	switch (cdb[0]) {
999 	case READ_6:
1000 	case READ_10:
1001 	case READ_12:
1002 	case READ_16:
1003 	case INQUIRY:
1004 	case MODE_SENSE:
1005 	case MODE_SENSE_10:
1006 	case SERVICE_ACTION_IN_16:
1007 	case MAINTENANCE_IN:
1008 	case PERSISTENT_RESERVE_IN:
1009 	case SECURITY_PROTOCOL_IN:
1010 	case ACCESS_CONTROL_IN:
1011 	case REPORT_LUNS:
1012 	case READ_BLOCK_LIMITS:
1013 	case READ_POSITION:
1014 	case READ_CAPACITY:
1015 	case READ_TOC:
1016 	case READ_FORMAT_CAPACITIES:
1017 	case REQUEST_SENSE:
1018 	case ATA_12:
1019 	case ATA_16:
1020 		ret = DMA_FROM_DEVICE;
1021 		break;
1022 
1023 	case WRITE_6:
1024 	case WRITE_10:
1025 	case WRITE_12:
1026 	case WRITE_16:
1027 	case MODE_SELECT:
1028 	case MODE_SELECT_10:
1029 	case WRITE_VERIFY:
1030 	case WRITE_VERIFY_12:
1031 	case PERSISTENT_RESERVE_OUT:
1032 	case MAINTENANCE_OUT:
1033 	case SECURITY_PROTOCOL_OUT:
1034 	case ACCESS_CONTROL_OUT:
1035 		ret = DMA_TO_DEVICE;
1036 		break;
1037 	case ALLOW_MEDIUM_REMOVAL:
1038 	case TEST_UNIT_READY:
1039 	case SYNCHRONIZE_CACHE:
1040 	case START_STOP:
1041 	case ERASE:
1042 	case REZERO_UNIT:
1043 	case SEEK_10:
1044 	case SPACE:
1045 	case VERIFY:
1046 	case WRITE_FILEMARKS:
1047 		ret = DMA_NONE;
1048 		break;
1049 	default:
1050 #define CMD_DIR_MSG "target: Unknown data direction for SCSI Opcode 0x%02x\n"
1051 		pr_warn(CMD_DIR_MSG, cdb[0]);
1052 #undef CMD_DIR_MSG
1053 		ret = -EINVAL;
1054 	}
1055 	return ret;
1056 }
1057 
1058 static void usbg_data_write_cmpl(struct usb_ep *ep, struct usb_request *req)
1059 {
1060 	struct usbg_cmd *cmd = req->context;
1061 	struct se_cmd *se_cmd = &cmd->se_cmd;
1062 
1063 	cmd->state = UASP_QUEUE_COMMAND;
1064 
1065 	if (req->status == -ESHUTDOWN) {
1066 		struct uas_stream *stream = &cmd->fu->stream[se_cmd->map_tag];
1067 
1068 		hash_del(&stream->node);
1069 		target_put_sess_cmd(se_cmd);
1070 		transport_generic_free_cmd(&cmd->se_cmd, 0);
1071 		return;
1072 	}
1073 
1074 	if (req->status) {
1075 		pr_err("%s() state %d transfer failed\n", __func__, cmd->state);
1076 		goto cleanup;
1077 	}
1078 
1079 	if (req->num_sgs == 0) {
1080 		sg_copy_from_buffer(se_cmd->t_data_sg,
1081 				se_cmd->t_data_nents,
1082 				cmd->data_buf,
1083 				se_cmd->data_length);
1084 	}
1085 
1086 	cmd->flags |= USBG_CMD_PENDING_DATA_WRITE;
1087 	queue_work(cmd->fu->tpg->workqueue, &cmd->work);
1088 	return;
1089 
1090 cleanup:
1091 	target_put_sess_cmd(se_cmd);
1092 
1093 	/* Command was aborted due to overlapped tag */
1094 	if (cmd->state == UASP_QUEUE_COMMAND &&
1095 	    cmd->tmr_rsp == RC_OVERLAPPED_TAG) {
1096 		uasp_send_tm_response(cmd);
1097 		return;
1098 	}
1099 
1100 	transport_send_check_condition_and_sense(se_cmd,
1101 			TCM_CHECK_CONDITION_ABORT_CMD, 0);
1102 }
1103 
1104 static int usbg_prepare_w_request(struct usbg_cmd *cmd, struct usb_request *req)
1105 {
1106 	struct se_cmd *se_cmd = &cmd->se_cmd;
1107 	struct f_uas *fu = cmd->fu;
1108 	struct usb_gadget *gadget = fuas_to_gadget(fu);
1109 
1110 	if (!gadget->sg_supported) {
1111 		cmd->data_buf = kmalloc(se_cmd->data_length, GFP_ATOMIC);
1112 		if (!cmd->data_buf)
1113 			return -ENOMEM;
1114 
1115 		req->buf = cmd->data_buf;
1116 	} else {
1117 		req->buf = NULL;
1118 		req->num_sgs = se_cmd->t_data_nents;
1119 		req->sg = se_cmd->t_data_sg;
1120 	}
1121 
1122 	req->is_last = 1;
1123 	req->stream_id = cmd->tag;
1124 	req->complete = usbg_data_write_cmpl;
1125 	req->length = se_cmd->data_length;
1126 	req->context = cmd;
1127 
1128 	cmd->state = UASP_SEND_STATUS;
1129 	return 0;
1130 }
1131 
1132 static int usbg_send_status_response(struct se_cmd *se_cmd)
1133 {
1134 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1135 			se_cmd);
1136 	struct f_uas *fu = cmd->fu;
1137 
1138 	if (fu->flags & USBG_IS_BOT)
1139 		return bot_send_status_response(cmd);
1140 	else
1141 		return uasp_send_status_response(cmd);
1142 }
1143 
1144 static int usbg_send_write_request(struct se_cmd *se_cmd)
1145 {
1146 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1147 			se_cmd);
1148 	struct f_uas *fu = cmd->fu;
1149 
1150 	if (fu->flags & USBG_IS_BOT)
1151 		return bot_send_write_request(cmd);
1152 	else
1153 		return uasp_send_write_request(cmd);
1154 }
1155 
1156 static int usbg_send_read_response(struct se_cmd *se_cmd)
1157 {
1158 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1159 			se_cmd);
1160 	struct f_uas *fu = cmd->fu;
1161 
1162 	if (fu->flags & USBG_IS_BOT)
1163 		return bot_send_read_response(cmd);
1164 	else
1165 		return uasp_send_read_response(cmd);
1166 }
1167 
1168 static void usbg_aborted_task(struct se_cmd *se_cmd);
1169 
1170 static void usbg_submit_tmr(struct usbg_cmd *cmd)
1171 {
1172 	struct se_session *se_sess;
1173 	struct se_cmd *se_cmd;
1174 	int flags = TARGET_SCF_ACK_KREF;
1175 
1176 	se_cmd = &cmd->se_cmd;
1177 	se_sess = cmd->fu->tpg->tpg_nexus->tvn_se_sess;
1178 
1179 	target_submit_tmr(se_cmd, se_sess,
1180 			  cmd->response_iu.add_response_info,
1181 			  cmd->unpacked_lun, NULL, uasp_to_tcm_func(cmd->tmr_func),
1182 			  GFP_ATOMIC, cmd->tag, flags);
1183 }
1184 
1185 static void usbg_submit_cmd(struct usbg_cmd *cmd)
1186 {
1187 	struct se_cmd *se_cmd;
1188 	struct tcm_usbg_nexus *tv_nexus;
1189 	struct usbg_tpg *tpg;
1190 	int dir, flags = (TARGET_SCF_UNKNOWN_SIZE | TARGET_SCF_ACK_KREF);
1191 
1192 	/*
1193 	 * Note: each command will spawn its own process, and each stage of the
1194 	 * command is processed sequentially. Should this no longer be the case,
1195 	 * locking is needed.
1196 	 */
1197 	if (cmd->flags & USBG_CMD_PENDING_DATA_WRITE) {
1198 		target_execute_cmd(&cmd->se_cmd);
1199 		cmd->flags &= ~USBG_CMD_PENDING_DATA_WRITE;
1200 		return;
1201 	}
1202 
1203 	se_cmd = &cmd->se_cmd;
1204 	tpg = cmd->fu->tpg;
1205 	tv_nexus = tpg->tpg_nexus;
1206 	dir = get_cmd_dir(cmd->cmd_buf);
1207 	if (dir < 0) {
1208 		__target_init_cmd(se_cmd,
1209 				  tv_nexus->tvn_se_sess->se_tpg->se_tpg_tfo,
1210 				  tv_nexus->tvn_se_sess, cmd->data_len, DMA_NONE,
1211 				  cmd->prio_attr, cmd->sense_iu.sense,
1212 				  cmd->unpacked_lun, NULL);
1213 		goto out;
1214 	}
1215 
1216 	target_submit_cmd(se_cmd, tv_nexus->tvn_se_sess, cmd->cmd_buf,
1217 			  cmd->sense_iu.sense, cmd->unpacked_lun, 0,
1218 			  cmd->prio_attr, dir, flags);
1219 
1220 	return;
1221 
1222 out:
1223 	transport_send_check_condition_and_sense(se_cmd,
1224 			TCM_UNSUPPORTED_SCSI_OPCODE, 0);
1225 }
1226 
1227 static void usbg_cmd_work(struct work_struct *work)
1228 {
1229 	struct usbg_cmd *cmd = container_of(work, struct usbg_cmd, work);
1230 
1231 	/*
1232 	 * Failure is detected by f_tcm here. Skip submitting the command to the
1233 	 * target core if we already know the failing response and send the usb
1234 	 * response to the host directly.
1235 	 */
1236 	if (cmd->tmr_rsp != RC_RESPONSE_UNKNOWN)
1237 		goto skip;
1238 
1239 	if (cmd->tmr_func)
1240 		usbg_submit_tmr(cmd);
1241 	else
1242 		usbg_submit_cmd(cmd);
1243 
1244 	return;
1245 
1246 skip:
1247 	if (cmd->tmr_rsp == RC_OVERLAPPED_TAG) {
1248 		struct f_uas *fu = cmd->fu;
1249 		struct se_session *se_sess;
1250 		struct uas_stream *stream = NULL;
1251 		struct hlist_node *tmp;
1252 		struct usbg_cmd *active_cmd = NULL;
1253 
1254 		se_sess = cmd->fu->tpg->tpg_nexus->tvn_se_sess;
1255 
1256 		hash_for_each_possible_safe(fu->stream_hash, stream, tmp, node, cmd->tag) {
1257 			int i = stream - &fu->stream[0];
1258 
1259 			active_cmd = &((struct usbg_cmd *)se_sess->sess_cmd_map)[i];
1260 			if (active_cmd->tag == cmd->tag)
1261 				break;
1262 		}
1263 
1264 		/* Sanity check */
1265 		if (!stream || (active_cmd && active_cmd->tag != cmd->tag)) {
1266 			usbg_submit_command(cmd->fu, cmd->req);
1267 			return;
1268 		}
1269 
1270 		reinit_completion(&stream->cmd_completion);
1271 
1272 		/*
1273 		 * A UASP command consists of the command, data, and status
1274 		 * stages, each operating sequentially from different endpoints.
1275 		 *
1276 		 * Each USB endpoint operates independently, and depending on
1277 		 * hardware implementation, a completion callback for a transfer
1278 		 * from one endpoint may not reflect the order of completion on
1279 		 * the wire. This is particularly true for devices with
1280 		 * endpoints that have independent interrupts and event buffers.
1281 		 *
1282 		 * The driver must still detect misbehaving hosts and respond
1283 		 * with an overlap status. To reduce false overlap failures,
1284 		 * allow the active and matching stream ID a brief 1ms to
1285 		 * complete before responding with an overlap command failure.
1286 		 * Overlap failure should be rare.
1287 		 */
1288 		wait_for_completion_timeout(&stream->cmd_completion, msecs_to_jiffies(1));
1289 
1290 		/* If the previous stream is completed, retry the command. */
1291 		if (!hash_hashed(&stream->node)) {
1292 			usbg_submit_command(cmd->fu, cmd->req);
1293 			return;
1294 		}
1295 
1296 		/*
1297 		 * The command isn't submitted to the target core, so we're safe
1298 		 * to remove the bitmap index from the session tag pool.
1299 		 */
1300 		sbitmap_queue_clear(&se_sess->sess_tag_pool,
1301 				    cmd->se_cmd.map_tag,
1302 				    cmd->se_cmd.map_cpu);
1303 
1304 		/*
1305 		 * Overlap command tag detected. Cancel any pending transfer of
1306 		 * the command submitted to target core.
1307 		 */
1308 		active_cmd->tmr_rsp = RC_OVERLAPPED_TAG;
1309 		usbg_aborted_task(&active_cmd->se_cmd);
1310 
1311 		/* Send the response after the transfer is aborted. */
1312 		return;
1313 	}
1314 
1315 	uasp_send_tm_response(cmd);
1316 }
1317 
1318 static struct usbg_cmd *usbg_get_cmd(struct f_uas *fu,
1319 		struct tcm_usbg_nexus *tv_nexus, u32 scsi_tag)
1320 {
1321 	struct se_session *se_sess = tv_nexus->tvn_se_sess;
1322 	struct usbg_cmd *cmd;
1323 	int tag, cpu;
1324 
1325 	tag = sbitmap_queue_get(&se_sess->sess_tag_pool, &cpu);
1326 	if (tag < 0)
1327 		return ERR_PTR(-ENOMEM);
1328 
1329 	cmd = &((struct usbg_cmd *)se_sess->sess_cmd_map)[tag];
1330 	memset(cmd, 0, sizeof(*cmd));
1331 	cmd->se_cmd.map_tag = tag;
1332 	cmd->se_cmd.map_cpu = cpu;
1333 	cmd->se_cmd.cpuid = cpu;
1334 	cmd->se_cmd.tag = cmd->tag = scsi_tag;
1335 	cmd->fu = fu;
1336 
1337 	return cmd;
1338 }
1339 
1340 static void usbg_release_cmd(struct se_cmd *);
1341 
1342 static int usbg_submit_command(struct f_uas *fu, struct usb_request *req)
1343 {
1344 	struct iu *iu = req->buf;
1345 	struct usbg_cmd *cmd;
1346 	struct usbg_tpg *tpg = fu->tpg;
1347 	struct tcm_usbg_nexus *tv_nexus;
1348 	struct uas_stream *stream;
1349 	struct hlist_node *tmp;
1350 	struct command_iu *cmd_iu;
1351 	u32 cmd_len;
1352 	u16 scsi_tag;
1353 
1354 	tv_nexus = tpg->tpg_nexus;
1355 	if (!tv_nexus) {
1356 		pr_err("Missing nexus, ignoring command\n");
1357 		return -EINVAL;
1358 	}
1359 
1360 	scsi_tag = be16_to_cpup(&iu->tag);
1361 	cmd = usbg_get_cmd(fu, tv_nexus, scsi_tag);
1362 	if (IS_ERR(cmd)) {
1363 		pr_err("usbg_get_cmd failed\n");
1364 		return -ENOMEM;
1365 	}
1366 
1367 	cmd->req = req;
1368 	cmd->fu = fu;
1369 	cmd->tag = scsi_tag;
1370 	cmd->se_cmd.tag = scsi_tag;
1371 	cmd->tmr_func = 0;
1372 	cmd->tmr_rsp = RC_RESPONSE_UNKNOWN;
1373 	cmd->flags = 0;
1374 
1375 	cmd_iu = (struct command_iu *)iu;
1376 
1377 	/* Command and Task Management IUs share the same LUN offset */
1378 	cmd->unpacked_lun = scsilun_to_int(&cmd_iu->lun);
1379 
1380 	if (iu->iu_id != IU_ID_COMMAND && iu->iu_id != IU_ID_TASK_MGMT) {
1381 		cmd->tmr_rsp = RC_INVALID_INFO_UNIT;
1382 		goto skip;
1383 	}
1384 
1385 	hash_for_each_possible_safe(fu->stream_hash, stream, tmp, node, scsi_tag) {
1386 		struct usbg_cmd *active_cmd;
1387 		struct se_session *se_sess;
1388 		int i = stream - &fu->stream[0];
1389 
1390 		se_sess = cmd->fu->tpg->tpg_nexus->tvn_se_sess;
1391 		active_cmd = &((struct usbg_cmd *)se_sess->sess_cmd_map)[i];
1392 
1393 		if (active_cmd->tag == scsi_tag) {
1394 			cmd->tmr_rsp = RC_OVERLAPPED_TAG;
1395 			goto skip;
1396 		}
1397 	}
1398 
1399 	stream = &fu->stream[cmd->se_cmd.map_tag];
1400 	hash_add(fu->stream_hash, &stream->node, scsi_tag);
1401 
1402 	if (iu->iu_id == IU_ID_TASK_MGMT) {
1403 		struct task_mgmt_iu *tm_iu;
1404 
1405 		tm_iu = (struct task_mgmt_iu *)iu;
1406 		cmd->tmr_func = tm_iu->function;
1407 		goto skip;
1408 	}
1409 
1410 	cmd_len = (cmd_iu->len & ~0x3) + 16;
1411 	if (cmd_len > USBG_MAX_CMD) {
1412 		target_free_tag(tv_nexus->tvn_se_sess, &cmd->se_cmd);
1413 		hash_del(&stream->node);
1414 		return -EINVAL;
1415 	}
1416 	memcpy(cmd->cmd_buf, cmd_iu->cdb, cmd_len);
1417 
1418 	switch (cmd_iu->prio_attr & 0x7) {
1419 	case UAS_HEAD_TAG:
1420 		cmd->prio_attr = TCM_HEAD_TAG;
1421 		break;
1422 	case UAS_ORDERED_TAG:
1423 		cmd->prio_attr = TCM_ORDERED_TAG;
1424 		break;
1425 	case UAS_ACA:
1426 		cmd->prio_attr = TCM_ACA_TAG;
1427 		break;
1428 	default:
1429 		pr_debug_once("Unsupported prio_attr: %02x.\n",
1430 				cmd_iu->prio_attr);
1431 		fallthrough;
1432 	case UAS_SIMPLE_TAG:
1433 		cmd->prio_attr = TCM_SIMPLE_TAG;
1434 		break;
1435 	}
1436 
1437 skip:
1438 	INIT_WORK(&cmd->work, usbg_cmd_work);
1439 	queue_work(tpg->workqueue, &cmd->work);
1440 
1441 	return 0;
1442 }
1443 
1444 static void bot_cmd_work(struct work_struct *work)
1445 {
1446 	struct usbg_cmd *cmd = container_of(work, struct usbg_cmd, work);
1447 	struct se_cmd *se_cmd;
1448 	struct tcm_usbg_nexus *tv_nexus;
1449 	struct usbg_tpg *tpg;
1450 	int dir;
1451 
1452 	/*
1453 	 * Note: each command will spawn its own process, and each stage of the
1454 	 * command is processed sequentially. Should this no longer be the case,
1455 	 * locking is needed.
1456 	 */
1457 	if (cmd->flags & USBG_CMD_PENDING_DATA_WRITE) {
1458 		target_execute_cmd(&cmd->se_cmd);
1459 		cmd->flags &= ~USBG_CMD_PENDING_DATA_WRITE;
1460 		return;
1461 	}
1462 
1463 	se_cmd = &cmd->se_cmd;
1464 	tpg = cmd->fu->tpg;
1465 	tv_nexus = tpg->tpg_nexus;
1466 	dir = get_cmd_dir(cmd->cmd_buf);
1467 	if (dir < 0) {
1468 		__target_init_cmd(se_cmd,
1469 				  tv_nexus->tvn_se_sess->se_tpg->se_tpg_tfo,
1470 				  tv_nexus->tvn_se_sess, cmd->data_len, DMA_NONE,
1471 				  cmd->prio_attr, cmd->sense_iu.sense,
1472 				  cmd->unpacked_lun, NULL);
1473 		goto out;
1474 	}
1475 
1476 	target_submit_cmd(se_cmd, tv_nexus->tvn_se_sess,
1477 			  cmd->cmd_buf, cmd->sense_iu.sense, cmd->unpacked_lun,
1478 			  cmd->data_len, cmd->prio_attr, dir, 0);
1479 	return;
1480 
1481 out:
1482 	transport_send_check_condition_and_sense(se_cmd,
1483 				TCM_UNSUPPORTED_SCSI_OPCODE, 0);
1484 }
1485 
1486 static int bot_submit_command(struct f_uas *fu,
1487 		void *cmdbuf, unsigned int len)
1488 {
1489 	struct bulk_cb_wrap *cbw = cmdbuf;
1490 	struct usbg_cmd *cmd;
1491 	struct usbg_tpg *tpg = fu->tpg;
1492 	struct tcm_usbg_nexus *tv_nexus;
1493 	u32 cmd_len;
1494 
1495 	if (cbw->Signature != cpu_to_le32(US_BULK_CB_SIGN)) {
1496 		pr_err("Wrong signature on CBW\n");
1497 		return -EINVAL;
1498 	}
1499 	if (len != 31) {
1500 		pr_err("Wrong length for CBW\n");
1501 		return -EINVAL;
1502 	}
1503 
1504 	cmd_len = cbw->Length;
1505 	if (cmd_len < 1 || cmd_len > 16)
1506 		return -EINVAL;
1507 
1508 	tv_nexus = tpg->tpg_nexus;
1509 	if (!tv_nexus) {
1510 		pr_err("Missing nexus, ignoring command\n");
1511 		return -ENODEV;
1512 	}
1513 
1514 	cmd = usbg_get_cmd(fu, tv_nexus, cbw->Tag);
1515 	if (IS_ERR(cmd)) {
1516 		pr_err("usbg_get_cmd failed\n");
1517 		return -ENOMEM;
1518 	}
1519 	memcpy(cmd->cmd_buf, cbw->CDB, cmd_len);
1520 
1521 	cmd->bot_tag = cbw->Tag;
1522 	cmd->prio_attr = TCM_SIMPLE_TAG;
1523 	cmd->unpacked_lun = cbw->Lun;
1524 	cmd->is_read = cbw->Flags & US_BULK_FLAG_IN ? 1 : 0;
1525 	cmd->data_len = le32_to_cpu(cbw->DataTransferLength);
1526 	cmd->se_cmd.tag = le32_to_cpu(cmd->bot_tag);
1527 	cmd->flags = 0;
1528 
1529 	INIT_WORK(&cmd->work, bot_cmd_work);
1530 	queue_work(tpg->workqueue, &cmd->work);
1531 
1532 	return 0;
1533 }
1534 
1535 /* Start fabric.c code */
1536 
1537 static int usbg_check_true(struct se_portal_group *se_tpg)
1538 {
1539 	return 1;
1540 }
1541 
1542 static char *usbg_get_fabric_wwn(struct se_portal_group *se_tpg)
1543 {
1544 	struct usbg_tpg *tpg = container_of(se_tpg,
1545 				struct usbg_tpg, se_tpg);
1546 	struct usbg_tport *tport = tpg->tport;
1547 
1548 	return &tport->tport_name[0];
1549 }
1550 
1551 static u16 usbg_get_tag(struct se_portal_group *se_tpg)
1552 {
1553 	struct usbg_tpg *tpg = container_of(se_tpg,
1554 				struct usbg_tpg, se_tpg);
1555 	return tpg->tport_tpgt;
1556 }
1557 
1558 static void usbg_release_cmd(struct se_cmd *se_cmd)
1559 {
1560 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1561 			se_cmd);
1562 	struct se_session *se_sess = se_cmd->se_sess;
1563 
1564 	cmd->tag = 0;
1565 	kfree(cmd->data_buf);
1566 	target_free_tag(se_sess, se_cmd);
1567 }
1568 
1569 static void usbg_queue_tm_rsp(struct se_cmd *se_cmd)
1570 {
1571 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd, se_cmd);
1572 
1573 	uasp_send_tm_response(cmd);
1574 }
1575 
1576 static void usbg_aborted_task(struct se_cmd *se_cmd)
1577 {
1578 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd, se_cmd);
1579 	struct f_uas *fu = cmd->fu;
1580 	struct usb_gadget *gadget = fuas_to_gadget(fu);
1581 	struct uas_stream *stream = &fu->stream[se_cmd->map_tag];
1582 	int ret = 0;
1583 
1584 	if (stream->req_out->status == -EINPROGRESS)
1585 		ret = usb_ep_dequeue(fu->ep_out, stream->req_out);
1586 	else if (stream->req_in->status == -EINPROGRESS)
1587 		ret = usb_ep_dequeue(fu->ep_in, stream->req_in);
1588 	else if (stream->req_status->status == -EINPROGRESS)
1589 		ret = usb_ep_dequeue(fu->ep_status, stream->req_status);
1590 
1591 	if (ret)
1592 		dev_err(&gadget->dev, "Failed to abort cmd tag %d, (%d)\n",
1593 			cmd->tag, ret);
1594 
1595 	cmd->state = UASP_QUEUE_COMMAND;
1596 }
1597 
1598 static const char *usbg_check_wwn(const char *name)
1599 {
1600 	const char *n;
1601 	unsigned int len;
1602 
1603 	n = strstr(name, "naa.");
1604 	if (!n)
1605 		return NULL;
1606 	n += 4;
1607 	len = strlen(n);
1608 	if (len == 0 || len > USBG_NAMELEN - 1)
1609 		return NULL;
1610 	return n;
1611 }
1612 
1613 static int usbg_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
1614 {
1615 	if (!usbg_check_wwn(name))
1616 		return -EINVAL;
1617 	return 0;
1618 }
1619 
1620 static struct se_portal_group *usbg_make_tpg(struct se_wwn *wwn,
1621 					     const char *name)
1622 {
1623 	struct usbg_tport *tport = container_of(wwn, struct usbg_tport,
1624 			tport_wwn);
1625 	struct usbg_tpg *tpg;
1626 	unsigned long tpgt;
1627 	int ret;
1628 	struct f_tcm_opts *opts;
1629 	unsigned i;
1630 
1631 	if (strstr(name, "tpgt_") != name)
1632 		return ERR_PTR(-EINVAL);
1633 	if (kstrtoul(name + 5, 0, &tpgt) || tpgt > UINT_MAX)
1634 		return ERR_PTR(-EINVAL);
1635 	ret = -ENODEV;
1636 	mutex_lock(&tpg_instances_lock);
1637 	for (i = 0; i < TPG_INSTANCES; ++i)
1638 		if (tpg_instances[i].func_inst && !tpg_instances[i].tpg)
1639 			break;
1640 	if (i == TPG_INSTANCES)
1641 		goto unlock_inst;
1642 
1643 	opts = container_of(tpg_instances[i].func_inst, struct f_tcm_opts,
1644 		func_inst);
1645 	mutex_lock(&opts->dep_lock);
1646 	if (!opts->ready)
1647 		goto unlock_dep;
1648 
1649 	if (opts->has_dep) {
1650 		if (!try_module_get(opts->dependent))
1651 			goto unlock_dep;
1652 	} else {
1653 		ret = configfs_depend_item_unlocked(
1654 			wwn->wwn_group.cg_subsys,
1655 			&opts->func_inst.group.cg_item);
1656 		if (ret)
1657 			goto unlock_dep;
1658 	}
1659 
1660 	tpg = kzalloc(sizeof(struct usbg_tpg), GFP_KERNEL);
1661 	ret = -ENOMEM;
1662 	if (!tpg)
1663 		goto unref_dep;
1664 	mutex_init(&tpg->tpg_mutex);
1665 	atomic_set(&tpg->tpg_port_count, 0);
1666 	tpg->workqueue = alloc_workqueue("tcm_usb_gadget",
1667 					 WQ_UNBOUND, WQ_UNBOUND_MAX_ACTIVE);
1668 	if (!tpg->workqueue)
1669 		goto free_tpg;
1670 
1671 	tpg->tport = tport;
1672 	tpg->tport_tpgt = tpgt;
1673 
1674 	/*
1675 	 * SPC doesn't assign a protocol identifier for USB-SCSI, so we
1676 	 * pretend to be SAS..
1677 	 */
1678 	ret = core_tpg_register(wwn, &tpg->se_tpg, SCSI_PROTOCOL_SAS);
1679 	if (ret < 0)
1680 		goto free_workqueue;
1681 
1682 	tpg_instances[i].tpg = tpg;
1683 	tpg->fi = tpg_instances[i].func_inst;
1684 	mutex_unlock(&opts->dep_lock);
1685 	mutex_unlock(&tpg_instances_lock);
1686 	return &tpg->se_tpg;
1687 
1688 free_workqueue:
1689 	destroy_workqueue(tpg->workqueue);
1690 free_tpg:
1691 	kfree(tpg);
1692 unref_dep:
1693 	if (opts->has_dep)
1694 		module_put(opts->dependent);
1695 	else
1696 		configfs_undepend_item_unlocked(&opts->func_inst.group.cg_item);
1697 unlock_dep:
1698 	mutex_unlock(&opts->dep_lock);
1699 unlock_inst:
1700 	mutex_unlock(&tpg_instances_lock);
1701 
1702 	return ERR_PTR(ret);
1703 }
1704 
1705 static int tcm_usbg_drop_nexus(struct usbg_tpg *);
1706 
1707 static void usbg_drop_tpg(struct se_portal_group *se_tpg)
1708 {
1709 	struct usbg_tpg *tpg = container_of(se_tpg,
1710 				struct usbg_tpg, se_tpg);
1711 	unsigned i;
1712 	struct f_tcm_opts *opts;
1713 
1714 	tcm_usbg_drop_nexus(tpg);
1715 	core_tpg_deregister(se_tpg);
1716 	destroy_workqueue(tpg->workqueue);
1717 
1718 	mutex_lock(&tpg_instances_lock);
1719 	for (i = 0; i < TPG_INSTANCES; ++i)
1720 		if (tpg_instances[i].tpg == tpg)
1721 			break;
1722 	if (i < TPG_INSTANCES) {
1723 		tpg_instances[i].tpg = NULL;
1724 		opts = container_of(tpg_instances[i].func_inst,
1725 			struct f_tcm_opts, func_inst);
1726 		mutex_lock(&opts->dep_lock);
1727 		if (opts->has_dep)
1728 			module_put(opts->dependent);
1729 		else
1730 			configfs_undepend_item_unlocked(
1731 				&opts->func_inst.group.cg_item);
1732 		mutex_unlock(&opts->dep_lock);
1733 	}
1734 	mutex_unlock(&tpg_instances_lock);
1735 
1736 	kfree(tpg);
1737 }
1738 
1739 static struct se_wwn *usbg_make_tport(
1740 	struct target_fabric_configfs *tf,
1741 	struct config_group *group,
1742 	const char *name)
1743 {
1744 	struct usbg_tport *tport;
1745 	const char *wnn_name;
1746 	u64 wwpn = 0;
1747 
1748 	wnn_name = usbg_check_wwn(name);
1749 	if (!wnn_name)
1750 		return ERR_PTR(-EINVAL);
1751 
1752 	tport = kzalloc(sizeof(struct usbg_tport), GFP_KERNEL);
1753 	if (!(tport))
1754 		return ERR_PTR(-ENOMEM);
1755 
1756 	tport->tport_wwpn = wwpn;
1757 	snprintf(tport->tport_name, sizeof(tport->tport_name), "%s", wnn_name);
1758 	return &tport->tport_wwn;
1759 }
1760 
1761 static void usbg_drop_tport(struct se_wwn *wwn)
1762 {
1763 	struct usbg_tport *tport = container_of(wwn,
1764 				struct usbg_tport, tport_wwn);
1765 	kfree(tport);
1766 }
1767 
1768 /*
1769  * If somebody feels like dropping the version property, go ahead.
1770  */
1771 static ssize_t usbg_wwn_version_show(struct config_item *item,  char *page)
1772 {
1773 	return sprintf(page, "usb-gadget fabric module\n");
1774 }
1775 
1776 CONFIGFS_ATTR_RO(usbg_wwn_, version);
1777 
1778 static struct configfs_attribute *usbg_wwn_attrs[] = {
1779 	&usbg_wwn_attr_version,
1780 	NULL,
1781 };
1782 
1783 static int usbg_attach(struct usbg_tpg *);
1784 static void usbg_detach(struct usbg_tpg *);
1785 
1786 static int usbg_enable_tpg(struct se_portal_group *se_tpg, bool enable)
1787 {
1788 	struct usbg_tpg  *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1789 	int ret = 0;
1790 
1791 	if (enable)
1792 		ret = usbg_attach(tpg);
1793 	else
1794 		usbg_detach(tpg);
1795 	if (ret)
1796 		return ret;
1797 
1798 	tpg->gadget_connect = enable;
1799 
1800 	return 0;
1801 }
1802 
1803 static ssize_t tcm_usbg_tpg_nexus_show(struct config_item *item, char *page)
1804 {
1805 	struct se_portal_group *se_tpg = to_tpg(item);
1806 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1807 	struct tcm_usbg_nexus *tv_nexus;
1808 	ssize_t ret;
1809 
1810 	mutex_lock(&tpg->tpg_mutex);
1811 	tv_nexus = tpg->tpg_nexus;
1812 	if (!tv_nexus) {
1813 		ret = -ENODEV;
1814 		goto out;
1815 	}
1816 	ret = sysfs_emit(page, "%s\n",
1817 			 tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1818 out:
1819 	mutex_unlock(&tpg->tpg_mutex);
1820 	return ret;
1821 }
1822 
1823 static int usbg_alloc_sess_cb(struct se_portal_group *se_tpg,
1824 			      struct se_session *se_sess, void *p)
1825 {
1826 	struct usbg_tpg *tpg = container_of(se_tpg,
1827 				struct usbg_tpg, se_tpg);
1828 
1829 	tpg->tpg_nexus = p;
1830 	return 0;
1831 }
1832 
1833 static int tcm_usbg_make_nexus(struct usbg_tpg *tpg, char *name)
1834 {
1835 	struct tcm_usbg_nexus *tv_nexus;
1836 	int ret = 0;
1837 
1838 	mutex_lock(&tpg->tpg_mutex);
1839 	if (tpg->tpg_nexus) {
1840 		ret = -EEXIST;
1841 		pr_debug("tpg->tpg_nexus already exists\n");
1842 		goto out_unlock;
1843 	}
1844 
1845 	tv_nexus = kzalloc(sizeof(*tv_nexus), GFP_KERNEL);
1846 	if (!tv_nexus) {
1847 		ret = -ENOMEM;
1848 		goto out_unlock;
1849 	}
1850 
1851 	tv_nexus->tvn_se_sess = target_setup_session(&tpg->se_tpg,
1852 						     USB_G_DEFAULT_SESSION_TAGS,
1853 						     sizeof(struct usbg_cmd),
1854 						     TARGET_PROT_NORMAL, name,
1855 						     tv_nexus, usbg_alloc_sess_cb);
1856 	if (IS_ERR(tv_nexus->tvn_se_sess)) {
1857 #define MAKE_NEXUS_MSG "core_tpg_check_initiator_node_acl() failed for %s\n"
1858 		pr_debug(MAKE_NEXUS_MSG, name);
1859 #undef MAKE_NEXUS_MSG
1860 		ret = PTR_ERR(tv_nexus->tvn_se_sess);
1861 		kfree(tv_nexus);
1862 	}
1863 
1864 out_unlock:
1865 	mutex_unlock(&tpg->tpg_mutex);
1866 	return ret;
1867 }
1868 
1869 static int tcm_usbg_drop_nexus(struct usbg_tpg *tpg)
1870 {
1871 	struct se_session *se_sess;
1872 	struct tcm_usbg_nexus *tv_nexus;
1873 	int ret = -ENODEV;
1874 
1875 	mutex_lock(&tpg->tpg_mutex);
1876 	tv_nexus = tpg->tpg_nexus;
1877 	if (!tv_nexus)
1878 		goto out;
1879 
1880 	se_sess = tv_nexus->tvn_se_sess;
1881 	if (!se_sess)
1882 		goto out;
1883 
1884 	if (atomic_read(&tpg->tpg_port_count)) {
1885 		ret = -EPERM;
1886 #define MSG "Unable to remove Host I_T Nexus with active TPG port count: %d\n"
1887 		pr_err(MSG, atomic_read(&tpg->tpg_port_count));
1888 #undef MSG
1889 		goto out;
1890 	}
1891 
1892 	pr_debug("Removing I_T Nexus to Initiator Port: %s\n",
1893 			tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1894 	/*
1895 	 * Release the SCSI I_T Nexus to the emulated vHost Target Port
1896 	 */
1897 	target_remove_session(se_sess);
1898 	tpg->tpg_nexus = NULL;
1899 
1900 	kfree(tv_nexus);
1901 	ret = 0;
1902 out:
1903 	mutex_unlock(&tpg->tpg_mutex);
1904 	return ret;
1905 }
1906 
1907 static ssize_t tcm_usbg_tpg_nexus_store(struct config_item *item,
1908 		const char *page, size_t count)
1909 {
1910 	struct se_portal_group *se_tpg = to_tpg(item);
1911 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1912 	unsigned char i_port[USBG_NAMELEN], *ptr;
1913 	int ret;
1914 
1915 	if (!strncmp(page, "NULL", 4)) {
1916 		ret = tcm_usbg_drop_nexus(tpg);
1917 		return (!ret) ? count : ret;
1918 	}
1919 	if (strlen(page) >= USBG_NAMELEN) {
1920 
1921 #define NEXUS_STORE_MSG "Emulated NAA Sas Address: %s, exceeds max: %d\n"
1922 		pr_err(NEXUS_STORE_MSG, page, USBG_NAMELEN);
1923 #undef NEXUS_STORE_MSG
1924 		return -EINVAL;
1925 	}
1926 	snprintf(i_port, USBG_NAMELEN, "%s", page);
1927 
1928 	ptr = strstr(i_port, "naa.");
1929 	if (!ptr) {
1930 		pr_err("Missing 'naa.' prefix\n");
1931 		return -EINVAL;
1932 	}
1933 
1934 	if (i_port[strlen(i_port) - 1] == '\n')
1935 		i_port[strlen(i_port) - 1] = '\0';
1936 
1937 	ret = tcm_usbg_make_nexus(tpg, &i_port[0]);
1938 	if (ret < 0)
1939 		return ret;
1940 	return count;
1941 }
1942 
1943 CONFIGFS_ATTR(tcm_usbg_tpg_, nexus);
1944 
1945 static struct configfs_attribute *usbg_base_attrs[] = {
1946 	&tcm_usbg_tpg_attr_nexus,
1947 	NULL,
1948 };
1949 
1950 static int usbg_port_link(struct se_portal_group *se_tpg, struct se_lun *lun)
1951 {
1952 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1953 
1954 	atomic_inc(&tpg->tpg_port_count);
1955 	smp_mb__after_atomic();
1956 	return 0;
1957 }
1958 
1959 static void usbg_port_unlink(struct se_portal_group *se_tpg,
1960 		struct se_lun *se_lun)
1961 {
1962 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1963 
1964 	atomic_dec(&tpg->tpg_port_count);
1965 	smp_mb__after_atomic();
1966 }
1967 
1968 static int usbg_check_stop_free(struct se_cmd *se_cmd)
1969 {
1970 	return target_put_sess_cmd(se_cmd);
1971 }
1972 
1973 static const struct target_core_fabric_ops usbg_ops = {
1974 	.module				= THIS_MODULE,
1975 	.fabric_name			= "usb_gadget",
1976 	.tpg_get_wwn			= usbg_get_fabric_wwn,
1977 	.tpg_get_tag			= usbg_get_tag,
1978 	.tpg_check_demo_mode		= usbg_check_true,
1979 	.release_cmd			= usbg_release_cmd,
1980 	.sess_get_initiator_sid		= NULL,
1981 	.write_pending			= usbg_send_write_request,
1982 	.queue_data_in			= usbg_send_read_response,
1983 	.queue_status			= usbg_send_status_response,
1984 	.queue_tm_rsp			= usbg_queue_tm_rsp,
1985 	.aborted_task			= usbg_aborted_task,
1986 	.check_stop_free		= usbg_check_stop_free,
1987 
1988 	.fabric_make_wwn		= usbg_make_tport,
1989 	.fabric_drop_wwn		= usbg_drop_tport,
1990 	.fabric_make_tpg		= usbg_make_tpg,
1991 	.fabric_enable_tpg		= usbg_enable_tpg,
1992 	.fabric_drop_tpg		= usbg_drop_tpg,
1993 	.fabric_post_link		= usbg_port_link,
1994 	.fabric_pre_unlink		= usbg_port_unlink,
1995 	.fabric_init_nodeacl		= usbg_init_nodeacl,
1996 
1997 	.tfc_wwn_attrs			= usbg_wwn_attrs,
1998 	.tfc_tpg_base_attrs		= usbg_base_attrs,
1999 
2000 	.default_submit_type		= TARGET_DIRECT_SUBMIT,
2001 	.direct_submit_supp		= 1,
2002 };
2003 
2004 /* Start gadget.c code */
2005 
2006 static struct usb_interface_descriptor bot_intf_desc = {
2007 	.bLength =              sizeof(bot_intf_desc),
2008 	.bDescriptorType =      USB_DT_INTERFACE,
2009 	.bNumEndpoints =        2,
2010 	.bAlternateSetting =	USB_G_ALT_INT_BBB,
2011 	.bInterfaceClass =      USB_CLASS_MASS_STORAGE,
2012 	.bInterfaceSubClass =   USB_SC_SCSI,
2013 	.bInterfaceProtocol =   USB_PR_BULK,
2014 };
2015 
2016 static struct usb_interface_descriptor uasp_intf_desc = {
2017 	.bLength =		sizeof(uasp_intf_desc),
2018 	.bDescriptorType =	USB_DT_INTERFACE,
2019 	.bNumEndpoints =	4,
2020 	.bAlternateSetting =	USB_G_ALT_INT_UAS,
2021 	.bInterfaceClass =	USB_CLASS_MASS_STORAGE,
2022 	.bInterfaceSubClass =	USB_SC_SCSI,
2023 	.bInterfaceProtocol =	USB_PR_UAS,
2024 };
2025 
2026 static struct usb_endpoint_descriptor uasp_bi_desc = {
2027 	.bLength =		USB_DT_ENDPOINT_SIZE,
2028 	.bDescriptorType =	USB_DT_ENDPOINT,
2029 	.bEndpointAddress =	USB_DIR_IN,
2030 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2031 	.wMaxPacketSize =	cpu_to_le16(512),
2032 };
2033 
2034 static struct usb_endpoint_descriptor uasp_fs_bi_desc = {
2035 	.bLength =		USB_DT_ENDPOINT_SIZE,
2036 	.bDescriptorType =	USB_DT_ENDPOINT,
2037 	.bEndpointAddress =	USB_DIR_IN,
2038 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2039 };
2040 
2041 static struct usb_pipe_usage_descriptor uasp_bi_pipe_desc = {
2042 	.bLength =		sizeof(uasp_bi_pipe_desc),
2043 	.bDescriptorType =	USB_DT_PIPE_USAGE,
2044 	.bPipeID =		DATA_IN_PIPE_ID,
2045 };
2046 
2047 static struct usb_endpoint_descriptor uasp_ss_bi_desc = {
2048 	.bLength =		USB_DT_ENDPOINT_SIZE,
2049 	.bDescriptorType =	USB_DT_ENDPOINT,
2050 	.bEndpointAddress =	USB_DIR_IN,
2051 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2052 	.wMaxPacketSize =	cpu_to_le16(1024),
2053 };
2054 
2055 static struct usb_ss_ep_comp_descriptor uasp_bi_ep_comp_desc = {
2056 	.bLength =		sizeof(uasp_bi_ep_comp_desc),
2057 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
2058 	.bMaxBurst =		15,
2059 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
2060 	.wBytesPerInterval =	0,
2061 };
2062 
2063 static struct usb_ss_ep_comp_descriptor bot_bi_ep_comp_desc = {
2064 	.bLength =		sizeof(bot_bi_ep_comp_desc),
2065 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
2066 	.bMaxBurst =		15,
2067 };
2068 
2069 static struct usb_endpoint_descriptor uasp_bo_desc = {
2070 	.bLength =		USB_DT_ENDPOINT_SIZE,
2071 	.bDescriptorType =	USB_DT_ENDPOINT,
2072 	.bEndpointAddress =	USB_DIR_OUT,
2073 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2074 	.wMaxPacketSize =	cpu_to_le16(512),
2075 };
2076 
2077 static struct usb_endpoint_descriptor uasp_fs_bo_desc = {
2078 	.bLength =		USB_DT_ENDPOINT_SIZE,
2079 	.bDescriptorType =	USB_DT_ENDPOINT,
2080 	.bEndpointAddress =	USB_DIR_OUT,
2081 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2082 };
2083 
2084 static struct usb_pipe_usage_descriptor uasp_bo_pipe_desc = {
2085 	.bLength =		sizeof(uasp_bo_pipe_desc),
2086 	.bDescriptorType =	USB_DT_PIPE_USAGE,
2087 	.bPipeID =		DATA_OUT_PIPE_ID,
2088 };
2089 
2090 static struct usb_endpoint_descriptor uasp_ss_bo_desc = {
2091 	.bLength =		USB_DT_ENDPOINT_SIZE,
2092 	.bDescriptorType =	USB_DT_ENDPOINT,
2093 	.bEndpointAddress =	USB_DIR_OUT,
2094 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2095 	.wMaxPacketSize =	cpu_to_le16(0x400),
2096 };
2097 
2098 static struct usb_ss_ep_comp_descriptor uasp_bo_ep_comp_desc = {
2099 	.bLength =		sizeof(uasp_bo_ep_comp_desc),
2100 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
2101 	.bMaxBurst =		15,
2102 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
2103 };
2104 
2105 static struct usb_ss_ep_comp_descriptor bot_bo_ep_comp_desc = {
2106 	.bLength =		sizeof(bot_bo_ep_comp_desc),
2107 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
2108 	.bMaxBurst =		15,
2109 };
2110 
2111 static struct usb_endpoint_descriptor uasp_status_desc = {
2112 	.bLength =		USB_DT_ENDPOINT_SIZE,
2113 	.bDescriptorType =	USB_DT_ENDPOINT,
2114 	.bEndpointAddress =	USB_DIR_IN,
2115 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2116 	.wMaxPacketSize =	cpu_to_le16(512),
2117 };
2118 
2119 static struct usb_endpoint_descriptor uasp_fs_status_desc = {
2120 	.bLength =		USB_DT_ENDPOINT_SIZE,
2121 	.bDescriptorType =	USB_DT_ENDPOINT,
2122 	.bEndpointAddress =	USB_DIR_IN,
2123 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2124 };
2125 
2126 static struct usb_pipe_usage_descriptor uasp_status_pipe_desc = {
2127 	.bLength =		sizeof(uasp_status_pipe_desc),
2128 	.bDescriptorType =	USB_DT_PIPE_USAGE,
2129 	.bPipeID =		STATUS_PIPE_ID,
2130 };
2131 
2132 static struct usb_endpoint_descriptor uasp_ss_status_desc = {
2133 	.bLength =		USB_DT_ENDPOINT_SIZE,
2134 	.bDescriptorType =	USB_DT_ENDPOINT,
2135 	.bEndpointAddress =	USB_DIR_IN,
2136 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2137 	.wMaxPacketSize =	cpu_to_le16(1024),
2138 };
2139 
2140 static struct usb_ss_ep_comp_descriptor uasp_status_in_ep_comp_desc = {
2141 	.bLength =		sizeof(uasp_status_in_ep_comp_desc),
2142 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
2143 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
2144 };
2145 
2146 static struct usb_endpoint_descriptor uasp_cmd_desc = {
2147 	.bLength =		USB_DT_ENDPOINT_SIZE,
2148 	.bDescriptorType =	USB_DT_ENDPOINT,
2149 	.bEndpointAddress =	USB_DIR_OUT,
2150 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2151 	.wMaxPacketSize =	cpu_to_le16(512),
2152 };
2153 
2154 static struct usb_endpoint_descriptor uasp_fs_cmd_desc = {
2155 	.bLength =		USB_DT_ENDPOINT_SIZE,
2156 	.bDescriptorType =	USB_DT_ENDPOINT,
2157 	.bEndpointAddress =	USB_DIR_OUT,
2158 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2159 };
2160 
2161 static struct usb_pipe_usage_descriptor uasp_cmd_pipe_desc = {
2162 	.bLength =		sizeof(uasp_cmd_pipe_desc),
2163 	.bDescriptorType =	USB_DT_PIPE_USAGE,
2164 	.bPipeID =		CMD_PIPE_ID,
2165 };
2166 
2167 static struct usb_endpoint_descriptor uasp_ss_cmd_desc = {
2168 	.bLength =		USB_DT_ENDPOINT_SIZE,
2169 	.bDescriptorType =	USB_DT_ENDPOINT,
2170 	.bEndpointAddress =	USB_DIR_OUT,
2171 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
2172 	.wMaxPacketSize =	cpu_to_le16(1024),
2173 };
2174 
2175 static struct usb_ss_ep_comp_descriptor uasp_cmd_comp_desc = {
2176 	.bLength =		sizeof(uasp_cmd_comp_desc),
2177 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
2178 };
2179 
2180 static struct usb_descriptor_header *uasp_fs_function_desc[] = {
2181 	(struct usb_descriptor_header *) &bot_intf_desc,
2182 	(struct usb_descriptor_header *) &uasp_fs_bi_desc,
2183 	(struct usb_descriptor_header *) &uasp_fs_bo_desc,
2184 
2185 	(struct usb_descriptor_header *) &uasp_intf_desc,
2186 	(struct usb_descriptor_header *) &uasp_fs_bi_desc,
2187 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
2188 	(struct usb_descriptor_header *) &uasp_fs_bo_desc,
2189 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
2190 	(struct usb_descriptor_header *) &uasp_fs_status_desc,
2191 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
2192 	(struct usb_descriptor_header *) &uasp_fs_cmd_desc,
2193 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
2194 	NULL,
2195 };
2196 
2197 static struct usb_descriptor_header *uasp_hs_function_desc[] = {
2198 	(struct usb_descriptor_header *) &bot_intf_desc,
2199 	(struct usb_descriptor_header *) &uasp_bi_desc,
2200 	(struct usb_descriptor_header *) &uasp_bo_desc,
2201 
2202 	(struct usb_descriptor_header *) &uasp_intf_desc,
2203 	(struct usb_descriptor_header *) &uasp_bi_desc,
2204 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
2205 	(struct usb_descriptor_header *) &uasp_bo_desc,
2206 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
2207 	(struct usb_descriptor_header *) &uasp_status_desc,
2208 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
2209 	(struct usb_descriptor_header *) &uasp_cmd_desc,
2210 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
2211 	NULL,
2212 };
2213 
2214 static struct usb_descriptor_header *uasp_ss_function_desc[] = {
2215 	(struct usb_descriptor_header *) &bot_intf_desc,
2216 	(struct usb_descriptor_header *) &uasp_ss_bi_desc,
2217 	(struct usb_descriptor_header *) &bot_bi_ep_comp_desc,
2218 	(struct usb_descriptor_header *) &uasp_ss_bo_desc,
2219 	(struct usb_descriptor_header *) &bot_bo_ep_comp_desc,
2220 
2221 	(struct usb_descriptor_header *) &uasp_intf_desc,
2222 	(struct usb_descriptor_header *) &uasp_ss_bi_desc,
2223 	(struct usb_descriptor_header *) &uasp_bi_ep_comp_desc,
2224 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
2225 	(struct usb_descriptor_header *) &uasp_ss_bo_desc,
2226 	(struct usb_descriptor_header *) &uasp_bo_ep_comp_desc,
2227 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
2228 	(struct usb_descriptor_header *) &uasp_ss_status_desc,
2229 	(struct usb_descriptor_header *) &uasp_status_in_ep_comp_desc,
2230 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
2231 	(struct usb_descriptor_header *) &uasp_ss_cmd_desc,
2232 	(struct usb_descriptor_header *) &uasp_cmd_comp_desc,
2233 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
2234 	NULL,
2235 };
2236 
2237 static struct usb_string	tcm_us_strings[] = {
2238 	[USB_G_STR_INT_UAS].s		= "USB Attached SCSI",
2239 	[USB_G_STR_INT_BBB].s		= "Bulk Only Transport",
2240 	{ },
2241 };
2242 
2243 static struct usb_gadget_strings tcm_stringtab = {
2244 	.language = 0x0409,
2245 	.strings = tcm_us_strings,
2246 };
2247 
2248 static struct usb_gadget_strings *tcm_strings[] = {
2249 	&tcm_stringtab,
2250 	NULL,
2251 };
2252 
2253 static int tcm_bind(struct usb_configuration *c, struct usb_function *f)
2254 {
2255 	struct f_uas		*fu = to_f_uas(f);
2256 	struct usb_string	*us;
2257 	struct usb_gadget	*gadget = c->cdev->gadget;
2258 	struct usb_ep		*ep;
2259 	struct f_tcm_opts	*opts;
2260 	int			iface;
2261 	int			ret;
2262 
2263 	opts = container_of(f->fi, struct f_tcm_opts, func_inst);
2264 
2265 	mutex_lock(&opts->dep_lock);
2266 	if (!opts->can_attach) {
2267 		mutex_unlock(&opts->dep_lock);
2268 		return -ENODEV;
2269 	}
2270 	mutex_unlock(&opts->dep_lock);
2271 	us = usb_gstrings_attach(c->cdev, tcm_strings,
2272 		ARRAY_SIZE(tcm_us_strings));
2273 	if (IS_ERR(us))
2274 		return PTR_ERR(us);
2275 	bot_intf_desc.iInterface = us[USB_G_STR_INT_BBB].id;
2276 	uasp_intf_desc.iInterface = us[USB_G_STR_INT_UAS].id;
2277 
2278 	iface = usb_interface_id(c, f);
2279 	if (iface < 0)
2280 		return iface;
2281 
2282 	bot_intf_desc.bInterfaceNumber = iface;
2283 	uasp_intf_desc.bInterfaceNumber = iface;
2284 	fu->iface = iface;
2285 	ep = usb_ep_autoconfig(gadget, &uasp_fs_bi_desc);
2286 	if (!ep)
2287 		goto ep_fail;
2288 
2289 	fu->ep_in = ep;
2290 
2291 	ep = usb_ep_autoconfig(gadget, &uasp_fs_bo_desc);
2292 	if (!ep)
2293 		goto ep_fail;
2294 	fu->ep_out = ep;
2295 
2296 	ep = usb_ep_autoconfig(gadget, &uasp_fs_status_desc);
2297 	if (!ep)
2298 		goto ep_fail;
2299 	fu->ep_status = ep;
2300 
2301 	ep = usb_ep_autoconfig(gadget, &uasp_fs_cmd_desc);
2302 	if (!ep)
2303 		goto ep_fail;
2304 	fu->ep_cmd = ep;
2305 
2306 	/* Assume endpoint addresses are the same for both speeds */
2307 	uasp_bi_desc.bEndpointAddress =	uasp_fs_bi_desc.bEndpointAddress;
2308 	uasp_bo_desc.bEndpointAddress = uasp_fs_bo_desc.bEndpointAddress;
2309 	uasp_status_desc.bEndpointAddress =
2310 		uasp_fs_status_desc.bEndpointAddress;
2311 	uasp_cmd_desc.bEndpointAddress = uasp_fs_cmd_desc.bEndpointAddress;
2312 
2313 	uasp_ss_bi_desc.bEndpointAddress = uasp_fs_bi_desc.bEndpointAddress;
2314 	uasp_ss_bo_desc.bEndpointAddress = uasp_fs_bo_desc.bEndpointAddress;
2315 	uasp_ss_status_desc.bEndpointAddress =
2316 		uasp_fs_status_desc.bEndpointAddress;
2317 	uasp_ss_cmd_desc.bEndpointAddress = uasp_fs_cmd_desc.bEndpointAddress;
2318 
2319 	ret = usb_assign_descriptors(f, uasp_fs_function_desc,
2320 			uasp_hs_function_desc, uasp_ss_function_desc,
2321 			uasp_ss_function_desc);
2322 	if (ret)
2323 		goto ep_fail;
2324 
2325 	return 0;
2326 ep_fail:
2327 	pr_err("Can't claim all required eps\n");
2328 
2329 	return -ENOTSUPP;
2330 }
2331 
2332 struct guas_setup_wq {
2333 	struct work_struct work;
2334 	struct f_uas *fu;
2335 	unsigned int alt;
2336 };
2337 
2338 static void tcm_delayed_set_alt(struct work_struct *wq)
2339 {
2340 	struct guas_setup_wq *work = container_of(wq, struct guas_setup_wq,
2341 			work);
2342 	struct f_uas *fu = work->fu;
2343 	int alt = work->alt;
2344 
2345 	kfree(work);
2346 
2347 	if (fu->flags & USBG_IS_BOT)
2348 		bot_cleanup_old_alt(fu);
2349 	if (fu->flags & USBG_IS_UAS)
2350 		uasp_cleanup_old_alt(fu);
2351 
2352 	if (alt == USB_G_ALT_INT_BBB)
2353 		bot_set_alt(fu);
2354 	else if (alt == USB_G_ALT_INT_UAS)
2355 		uasp_set_alt(fu);
2356 	usb_composite_setup_continue(fu->function.config->cdev);
2357 }
2358 
2359 static int tcm_get_alt(struct usb_function *f, unsigned intf)
2360 {
2361 	struct f_uas *fu = to_f_uas(f);
2362 
2363 	if (fu->iface != intf)
2364 		return -EOPNOTSUPP;
2365 
2366 	if (fu->flags & USBG_IS_BOT)
2367 		return USB_G_ALT_INT_BBB;
2368 	else if (fu->flags & USBG_IS_UAS)
2369 		return USB_G_ALT_INT_UAS;
2370 
2371 	return -EOPNOTSUPP;
2372 }
2373 
2374 static int tcm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2375 {
2376 	struct f_uas *fu = to_f_uas(f);
2377 
2378 	if (fu->iface != intf)
2379 		return -EOPNOTSUPP;
2380 
2381 	if ((alt == USB_G_ALT_INT_BBB) || (alt == USB_G_ALT_INT_UAS)) {
2382 		struct guas_setup_wq *work;
2383 
2384 		work = kmalloc(sizeof(*work), GFP_ATOMIC);
2385 		if (!work)
2386 			return -ENOMEM;
2387 		INIT_WORK(&work->work, tcm_delayed_set_alt);
2388 		work->fu = fu;
2389 		work->alt = alt;
2390 		schedule_work(&work->work);
2391 		return USB_GADGET_DELAYED_STATUS;
2392 	}
2393 	return -EOPNOTSUPP;
2394 }
2395 
2396 static void tcm_disable(struct usb_function *f)
2397 {
2398 	struct f_uas *fu = to_f_uas(f);
2399 
2400 	if (fu->flags & USBG_IS_UAS)
2401 		uasp_cleanup_old_alt(fu);
2402 	else if (fu->flags & USBG_IS_BOT)
2403 		bot_cleanup_old_alt(fu);
2404 	fu->flags = 0;
2405 }
2406 
2407 static int tcm_setup(struct usb_function *f,
2408 		const struct usb_ctrlrequest *ctrl)
2409 {
2410 	struct f_uas *fu = to_f_uas(f);
2411 
2412 	if (!(fu->flags & USBG_IS_BOT))
2413 		return -EOPNOTSUPP;
2414 
2415 	return usbg_bot_setup(f, ctrl);
2416 }
2417 
2418 static inline struct f_tcm_opts *to_f_tcm_opts(struct config_item *item)
2419 {
2420 	return container_of(to_config_group(item), struct f_tcm_opts,
2421 		func_inst.group);
2422 }
2423 
2424 static void tcm_attr_release(struct config_item *item)
2425 {
2426 	struct f_tcm_opts *opts = to_f_tcm_opts(item);
2427 
2428 	usb_put_function_instance(&opts->func_inst);
2429 }
2430 
2431 static struct configfs_item_operations tcm_item_ops = {
2432 	.release		= tcm_attr_release,
2433 };
2434 
2435 static const struct config_item_type tcm_func_type = {
2436 	.ct_item_ops	= &tcm_item_ops,
2437 	.ct_owner	= THIS_MODULE,
2438 };
2439 
2440 static void tcm_free_inst(struct usb_function_instance *f)
2441 {
2442 	struct f_tcm_opts *opts;
2443 	unsigned i;
2444 
2445 	opts = container_of(f, struct f_tcm_opts, func_inst);
2446 
2447 	mutex_lock(&tpg_instances_lock);
2448 	for (i = 0; i < TPG_INSTANCES; ++i)
2449 		if (tpg_instances[i].func_inst == f)
2450 			break;
2451 	if (i < TPG_INSTANCES)
2452 		tpg_instances[i].func_inst = NULL;
2453 	mutex_unlock(&tpg_instances_lock);
2454 
2455 	kfree(opts);
2456 }
2457 
2458 static int tcm_register_callback(struct usb_function_instance *f)
2459 {
2460 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2461 
2462 	mutex_lock(&opts->dep_lock);
2463 	opts->can_attach = true;
2464 	mutex_unlock(&opts->dep_lock);
2465 
2466 	return 0;
2467 }
2468 
2469 static void tcm_unregister_callback(struct usb_function_instance *f)
2470 {
2471 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2472 
2473 	mutex_lock(&opts->dep_lock);
2474 	unregister_gadget_item(opts->
2475 		func_inst.group.cg_item.ci_parent->ci_parent);
2476 	opts->can_attach = false;
2477 	mutex_unlock(&opts->dep_lock);
2478 }
2479 
2480 static int usbg_attach(struct usbg_tpg *tpg)
2481 {
2482 	struct usb_function_instance *f = tpg->fi;
2483 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2484 
2485 	if (opts->tcm_register_callback)
2486 		return opts->tcm_register_callback(f);
2487 
2488 	return 0;
2489 }
2490 
2491 static void usbg_detach(struct usbg_tpg *tpg)
2492 {
2493 	struct usb_function_instance *f = tpg->fi;
2494 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2495 
2496 	if (opts->tcm_unregister_callback)
2497 		opts->tcm_unregister_callback(f);
2498 }
2499 
2500 static int tcm_set_name(struct usb_function_instance *f, const char *name)
2501 {
2502 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2503 
2504 	pr_debug("tcm: Activating %s\n", name);
2505 
2506 	mutex_lock(&opts->dep_lock);
2507 	opts->ready = true;
2508 	mutex_unlock(&opts->dep_lock);
2509 
2510 	return 0;
2511 }
2512 
2513 static struct usb_function_instance *tcm_alloc_inst(void)
2514 {
2515 	struct f_tcm_opts *opts;
2516 	int i;
2517 
2518 
2519 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2520 	if (!opts)
2521 		return ERR_PTR(-ENOMEM);
2522 
2523 	mutex_lock(&tpg_instances_lock);
2524 	for (i = 0; i < TPG_INSTANCES; ++i)
2525 		if (!tpg_instances[i].func_inst)
2526 			break;
2527 
2528 	if (i == TPG_INSTANCES) {
2529 		mutex_unlock(&tpg_instances_lock);
2530 		kfree(opts);
2531 		return ERR_PTR(-EBUSY);
2532 	}
2533 	tpg_instances[i].func_inst = &opts->func_inst;
2534 	mutex_unlock(&tpg_instances_lock);
2535 
2536 	mutex_init(&opts->dep_lock);
2537 	opts->func_inst.set_inst_name = tcm_set_name;
2538 	opts->func_inst.free_func_inst = tcm_free_inst;
2539 	opts->tcm_register_callback = tcm_register_callback;
2540 	opts->tcm_unregister_callback = tcm_unregister_callback;
2541 
2542 	config_group_init_type_name(&opts->func_inst.group, "",
2543 			&tcm_func_type);
2544 
2545 	return &opts->func_inst;
2546 }
2547 
2548 static void tcm_free(struct usb_function *f)
2549 {
2550 	struct f_uas *tcm = to_f_uas(f);
2551 
2552 	kfree(tcm);
2553 }
2554 
2555 static void tcm_unbind(struct usb_configuration *c, struct usb_function *f)
2556 {
2557 	usb_free_all_descriptors(f);
2558 }
2559 
2560 static struct usb_function *tcm_alloc(struct usb_function_instance *fi)
2561 {
2562 	struct f_uas *fu;
2563 	unsigned i;
2564 
2565 	mutex_lock(&tpg_instances_lock);
2566 	for (i = 0; i < TPG_INSTANCES; ++i)
2567 		if (tpg_instances[i].func_inst == fi)
2568 			break;
2569 	if (i == TPG_INSTANCES) {
2570 		mutex_unlock(&tpg_instances_lock);
2571 		return ERR_PTR(-ENODEV);
2572 	}
2573 
2574 	fu = kzalloc(sizeof(*fu), GFP_KERNEL);
2575 	if (!fu) {
2576 		mutex_unlock(&tpg_instances_lock);
2577 		return ERR_PTR(-ENOMEM);
2578 	}
2579 
2580 	fu->function.name = "Target Function";
2581 	fu->function.bind = tcm_bind;
2582 	fu->function.unbind = tcm_unbind;
2583 	fu->function.set_alt = tcm_set_alt;
2584 	fu->function.get_alt = tcm_get_alt;
2585 	fu->function.setup = tcm_setup;
2586 	fu->function.disable = tcm_disable;
2587 	fu->function.free_func = tcm_free;
2588 	fu->tpg = tpg_instances[i].tpg;
2589 
2590 	hash_init(fu->stream_hash);
2591 	mutex_unlock(&tpg_instances_lock);
2592 
2593 	return &fu->function;
2594 }
2595 
2596 DECLARE_USB_FUNCTION(tcm, tcm_alloc_inst, tcm_alloc);
2597 
2598 static int __init tcm_init(void)
2599 {
2600 	int ret;
2601 
2602 	ret = usb_function_register(&tcmusb_func);
2603 	if (ret)
2604 		return ret;
2605 
2606 	ret = target_register_template(&usbg_ops);
2607 	if (ret)
2608 		usb_function_unregister(&tcmusb_func);
2609 
2610 	return ret;
2611 }
2612 module_init(tcm_init);
2613 
2614 static void __exit tcm_exit(void)
2615 {
2616 	target_unregister_template(&usbg_ops);
2617 	usb_function_unregister(&tcmusb_func);
2618 }
2619 module_exit(tcm_exit);
2620 
2621 MODULE_DESCRIPTION("Target based USB-Gadget");
2622 MODULE_LICENSE("GPL");
2623 MODULE_AUTHOR("Sebastian Andrzej Siewior");
2624