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