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