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