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