xref: /linux-6.15/drivers/usb/gadget/function/f_tcm.c (revision 3b2a52e8)
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 	target_put_sess_cmd(se_cmd);
973 	transport_generic_free_cmd(&cmd->se_cmd, 0);
974 }
975 
976 static int usbg_prepare_w_request(struct usbg_cmd *cmd, struct usb_request *req)
977 {
978 	struct se_cmd *se_cmd = &cmd->se_cmd;
979 	struct f_uas *fu = cmd->fu;
980 	struct usb_gadget *gadget = fuas_to_gadget(fu);
981 
982 	if (!gadget->sg_supported) {
983 		cmd->data_buf = kmalloc(se_cmd->data_length, GFP_ATOMIC);
984 		if (!cmd->data_buf)
985 			return -ENOMEM;
986 
987 		req->buf = cmd->data_buf;
988 	} else {
989 		req->buf = NULL;
990 		req->num_sgs = se_cmd->t_data_nents;
991 		req->sg = se_cmd->t_data_sg;
992 	}
993 
994 	req->is_last = 1;
995 	req->complete = usbg_data_write_cmpl;
996 	req->length = se_cmd->data_length;
997 	req->context = cmd;
998 	return 0;
999 }
1000 
1001 static int usbg_send_status_response(struct se_cmd *se_cmd)
1002 {
1003 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1004 			se_cmd);
1005 	struct f_uas *fu = cmd->fu;
1006 
1007 	if (fu->flags & USBG_IS_BOT)
1008 		return bot_send_status_response(cmd);
1009 	else
1010 		return uasp_send_status_response(cmd);
1011 }
1012 
1013 static int usbg_send_write_request(struct se_cmd *se_cmd)
1014 {
1015 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1016 			se_cmd);
1017 	struct f_uas *fu = cmd->fu;
1018 
1019 	if (fu->flags & USBG_IS_BOT)
1020 		return bot_send_write_request(cmd);
1021 	else
1022 		return uasp_send_write_request(cmd);
1023 }
1024 
1025 static int usbg_send_read_response(struct se_cmd *se_cmd)
1026 {
1027 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1028 			se_cmd);
1029 	struct f_uas *fu = cmd->fu;
1030 
1031 	if (fu->flags & USBG_IS_BOT)
1032 		return bot_send_read_response(cmd);
1033 	else
1034 		return uasp_send_read_response(cmd);
1035 }
1036 
1037 static void usbg_cmd_work(struct work_struct *work)
1038 {
1039 	struct usbg_cmd *cmd = container_of(work, struct usbg_cmd, work);
1040 	struct se_cmd *se_cmd;
1041 	struct tcm_usbg_nexus *tv_nexus;
1042 	struct usbg_tpg *tpg;
1043 	int dir, flags = (TARGET_SCF_UNKNOWN_SIZE | TARGET_SCF_ACK_KREF);
1044 
1045 	se_cmd = &cmd->se_cmd;
1046 	tpg = cmd->fu->tpg;
1047 	tv_nexus = tpg->tpg_nexus;
1048 	dir = get_cmd_dir(cmd->cmd_buf);
1049 	if (dir < 0) {
1050 		__target_init_cmd(se_cmd,
1051 				  tv_nexus->tvn_se_sess->se_tpg->se_tpg_tfo,
1052 				  tv_nexus->tvn_se_sess, cmd->data_len, DMA_NONE,
1053 				  cmd->prio_attr, cmd->sense_iu.sense,
1054 				  cmd->unpacked_lun, NULL);
1055 		goto out;
1056 	}
1057 
1058 	target_submit_cmd(se_cmd, tv_nexus->tvn_se_sess, cmd->cmd_buf,
1059 			  cmd->sense_iu.sense, cmd->unpacked_lun, 0,
1060 			  cmd->prio_attr, dir, flags);
1061 	return;
1062 
1063 out:
1064 	transport_send_check_condition_and_sense(se_cmd,
1065 			TCM_UNSUPPORTED_SCSI_OPCODE, 0);
1066 }
1067 
1068 static struct usbg_cmd *usbg_get_cmd(struct f_uas *fu,
1069 		struct tcm_usbg_nexus *tv_nexus, u32 scsi_tag)
1070 {
1071 	struct se_session *se_sess = tv_nexus->tvn_se_sess;
1072 	struct usbg_cmd *cmd;
1073 	int tag, cpu;
1074 
1075 	tag = sbitmap_queue_get(&se_sess->sess_tag_pool, &cpu);
1076 	if (tag < 0)
1077 		return ERR_PTR(-ENOMEM);
1078 
1079 	cmd = &((struct usbg_cmd *)se_sess->sess_cmd_map)[tag];
1080 	memset(cmd, 0, sizeof(*cmd));
1081 	cmd->se_cmd.map_tag = tag;
1082 	cmd->se_cmd.map_cpu = cpu;
1083 	cmd->se_cmd.tag = cmd->tag = scsi_tag;
1084 	cmd->fu = fu;
1085 
1086 	return cmd;
1087 }
1088 
1089 static void usbg_release_cmd(struct se_cmd *);
1090 
1091 static int usbg_submit_command(struct f_uas *fu,
1092 		void *cmdbuf, unsigned int len)
1093 {
1094 	struct command_iu *cmd_iu = cmdbuf;
1095 	struct usbg_cmd *cmd;
1096 	struct usbg_tpg *tpg = fu->tpg;
1097 	struct tcm_usbg_nexus *tv_nexus;
1098 	u32 cmd_len;
1099 	u16 scsi_tag;
1100 
1101 	if (cmd_iu->iu_id != IU_ID_COMMAND) {
1102 		pr_err("Unsupported type %d\n", cmd_iu->iu_id);
1103 		return -EINVAL;
1104 	}
1105 
1106 	tv_nexus = tpg->tpg_nexus;
1107 	if (!tv_nexus) {
1108 		pr_err("Missing nexus, ignoring command\n");
1109 		return -EINVAL;
1110 	}
1111 
1112 	cmd_len = (cmd_iu->len & ~0x3) + 16;
1113 	if (cmd_len > USBG_MAX_CMD)
1114 		return -EINVAL;
1115 
1116 	scsi_tag = be16_to_cpup(&cmd_iu->tag);
1117 	cmd = usbg_get_cmd(fu, tv_nexus, scsi_tag);
1118 	if (IS_ERR(cmd)) {
1119 		pr_err("usbg_get_cmd failed\n");
1120 		return -ENOMEM;
1121 	}
1122 	memcpy(cmd->cmd_buf, cmd_iu->cdb, cmd_len);
1123 
1124 	if (fu->flags & USBG_USE_STREAMS) {
1125 		if (cmd->tag > UASP_SS_EP_COMP_NUM_STREAMS)
1126 			goto err;
1127 		if (!cmd->tag)
1128 			cmd->stream = &fu->stream[0];
1129 		else
1130 			cmd->stream = &fu->stream[cmd->tag - 1];
1131 	} else {
1132 		cmd->stream = &fu->stream[0];
1133 	}
1134 
1135 	switch (cmd_iu->prio_attr & 0x7) {
1136 	case UAS_HEAD_TAG:
1137 		cmd->prio_attr = TCM_HEAD_TAG;
1138 		break;
1139 	case UAS_ORDERED_TAG:
1140 		cmd->prio_attr = TCM_ORDERED_TAG;
1141 		break;
1142 	case UAS_ACA:
1143 		cmd->prio_attr = TCM_ACA_TAG;
1144 		break;
1145 	default:
1146 		pr_debug_once("Unsupported prio_attr: %02x.\n",
1147 				cmd_iu->prio_attr);
1148 		fallthrough;
1149 	case UAS_SIMPLE_TAG:
1150 		cmd->prio_attr = TCM_SIMPLE_TAG;
1151 		break;
1152 	}
1153 
1154 	cmd->unpacked_lun = scsilun_to_int(&cmd_iu->lun);
1155 
1156 	INIT_WORK(&cmd->work, usbg_cmd_work);
1157 	queue_work(tpg->workqueue, &cmd->work);
1158 
1159 	return 0;
1160 err:
1161 	usbg_release_cmd(&cmd->se_cmd);
1162 	return -EINVAL;
1163 }
1164 
1165 static void bot_cmd_work(struct work_struct *work)
1166 {
1167 	struct usbg_cmd *cmd = container_of(work, struct usbg_cmd, work);
1168 	struct se_cmd *se_cmd;
1169 	struct tcm_usbg_nexus *tv_nexus;
1170 	struct usbg_tpg *tpg;
1171 	int dir;
1172 
1173 	se_cmd = &cmd->se_cmd;
1174 	tpg = cmd->fu->tpg;
1175 	tv_nexus = tpg->tpg_nexus;
1176 	dir = get_cmd_dir(cmd->cmd_buf);
1177 	if (dir < 0) {
1178 		__target_init_cmd(se_cmd,
1179 				  tv_nexus->tvn_se_sess->se_tpg->se_tpg_tfo,
1180 				  tv_nexus->tvn_se_sess, cmd->data_len, DMA_NONE,
1181 				  cmd->prio_attr, cmd->sense_iu.sense,
1182 				  cmd->unpacked_lun, NULL);
1183 		goto out;
1184 	}
1185 
1186 	target_submit_cmd(se_cmd, tv_nexus->tvn_se_sess,
1187 			  cmd->cmd_buf, cmd->sense_iu.sense, cmd->unpacked_lun,
1188 			  cmd->data_len, cmd->prio_attr, dir, 0);
1189 	return;
1190 
1191 out:
1192 	transport_send_check_condition_and_sense(se_cmd,
1193 				TCM_UNSUPPORTED_SCSI_OPCODE, 0);
1194 }
1195 
1196 static int bot_submit_command(struct f_uas *fu,
1197 		void *cmdbuf, unsigned int len)
1198 {
1199 	struct bulk_cb_wrap *cbw = cmdbuf;
1200 	struct usbg_cmd *cmd;
1201 	struct usbg_tpg *tpg = fu->tpg;
1202 	struct tcm_usbg_nexus *tv_nexus;
1203 	u32 cmd_len;
1204 
1205 	if (cbw->Signature != cpu_to_le32(US_BULK_CB_SIGN)) {
1206 		pr_err("Wrong signature on CBW\n");
1207 		return -EINVAL;
1208 	}
1209 	if (len != 31) {
1210 		pr_err("Wrong length for CBW\n");
1211 		return -EINVAL;
1212 	}
1213 
1214 	cmd_len = cbw->Length;
1215 	if (cmd_len < 1 || cmd_len > 16)
1216 		return -EINVAL;
1217 
1218 	tv_nexus = tpg->tpg_nexus;
1219 	if (!tv_nexus) {
1220 		pr_err("Missing nexus, ignoring command\n");
1221 		return -ENODEV;
1222 	}
1223 
1224 	cmd = usbg_get_cmd(fu, tv_nexus, cbw->Tag);
1225 	if (IS_ERR(cmd)) {
1226 		pr_err("usbg_get_cmd failed\n");
1227 		return -ENOMEM;
1228 	}
1229 	memcpy(cmd->cmd_buf, cbw->CDB, cmd_len);
1230 
1231 	cmd->bot_tag = cbw->Tag;
1232 	cmd->prio_attr = TCM_SIMPLE_TAG;
1233 	cmd->unpacked_lun = cbw->Lun;
1234 	cmd->is_read = cbw->Flags & US_BULK_FLAG_IN ? 1 : 0;
1235 	cmd->data_len = le32_to_cpu(cbw->DataTransferLength);
1236 	cmd->se_cmd.tag = le32_to_cpu(cmd->bot_tag);
1237 
1238 	INIT_WORK(&cmd->work, bot_cmd_work);
1239 	queue_work(tpg->workqueue, &cmd->work);
1240 
1241 	return 0;
1242 }
1243 
1244 /* Start fabric.c code */
1245 
1246 static int usbg_check_true(struct se_portal_group *se_tpg)
1247 {
1248 	return 1;
1249 }
1250 
1251 static char *usbg_get_fabric_wwn(struct se_portal_group *se_tpg)
1252 {
1253 	struct usbg_tpg *tpg = container_of(se_tpg,
1254 				struct usbg_tpg, se_tpg);
1255 	struct usbg_tport *tport = tpg->tport;
1256 
1257 	return &tport->tport_name[0];
1258 }
1259 
1260 static u16 usbg_get_tag(struct se_portal_group *se_tpg)
1261 {
1262 	struct usbg_tpg *tpg = container_of(se_tpg,
1263 				struct usbg_tpg, se_tpg);
1264 	return tpg->tport_tpgt;
1265 }
1266 
1267 static void usbg_release_cmd(struct se_cmd *se_cmd)
1268 {
1269 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1270 			se_cmd);
1271 	struct se_session *se_sess = se_cmd->se_sess;
1272 
1273 	kfree(cmd->data_buf);
1274 	target_free_tag(se_sess, se_cmd);
1275 }
1276 
1277 static void usbg_queue_tm_rsp(struct se_cmd *se_cmd)
1278 {
1279 }
1280 
1281 static void usbg_aborted_task(struct se_cmd *se_cmd)
1282 {
1283 }
1284 
1285 static const char *usbg_check_wwn(const char *name)
1286 {
1287 	const char *n;
1288 	unsigned int len;
1289 
1290 	n = strstr(name, "naa.");
1291 	if (!n)
1292 		return NULL;
1293 	n += 4;
1294 	len = strlen(n);
1295 	if (len == 0 || len > USBG_NAMELEN - 1)
1296 		return NULL;
1297 	return n;
1298 }
1299 
1300 static int usbg_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
1301 {
1302 	if (!usbg_check_wwn(name))
1303 		return -EINVAL;
1304 	return 0;
1305 }
1306 
1307 static struct se_portal_group *usbg_make_tpg(struct se_wwn *wwn,
1308 					     const char *name)
1309 {
1310 	struct usbg_tport *tport = container_of(wwn, struct usbg_tport,
1311 			tport_wwn);
1312 	struct usbg_tpg *tpg;
1313 	unsigned long tpgt;
1314 	int ret;
1315 	struct f_tcm_opts *opts;
1316 	unsigned i;
1317 
1318 	if (strstr(name, "tpgt_") != name)
1319 		return ERR_PTR(-EINVAL);
1320 	if (kstrtoul(name + 5, 0, &tpgt) || tpgt > UINT_MAX)
1321 		return ERR_PTR(-EINVAL);
1322 	ret = -ENODEV;
1323 	mutex_lock(&tpg_instances_lock);
1324 	for (i = 0; i < TPG_INSTANCES; ++i)
1325 		if (tpg_instances[i].func_inst && !tpg_instances[i].tpg)
1326 			break;
1327 	if (i == TPG_INSTANCES)
1328 		goto unlock_inst;
1329 
1330 	opts = container_of(tpg_instances[i].func_inst, struct f_tcm_opts,
1331 		func_inst);
1332 	mutex_lock(&opts->dep_lock);
1333 	if (!opts->ready)
1334 		goto unlock_dep;
1335 
1336 	if (opts->has_dep) {
1337 		if (!try_module_get(opts->dependent))
1338 			goto unlock_dep;
1339 	} else {
1340 		ret = configfs_depend_item_unlocked(
1341 			wwn->wwn_group.cg_subsys,
1342 			&opts->func_inst.group.cg_item);
1343 		if (ret)
1344 			goto unlock_dep;
1345 	}
1346 
1347 	tpg = kzalloc(sizeof(struct usbg_tpg), GFP_KERNEL);
1348 	ret = -ENOMEM;
1349 	if (!tpg)
1350 		goto unref_dep;
1351 	mutex_init(&tpg->tpg_mutex);
1352 	atomic_set(&tpg->tpg_port_count, 0);
1353 	tpg->workqueue = alloc_workqueue("tcm_usb_gadget", 0, 1);
1354 	if (!tpg->workqueue)
1355 		goto free_tpg;
1356 
1357 	tpg->tport = tport;
1358 	tpg->tport_tpgt = tpgt;
1359 
1360 	/*
1361 	 * SPC doesn't assign a protocol identifier for USB-SCSI, so we
1362 	 * pretend to be SAS..
1363 	 */
1364 	ret = core_tpg_register(wwn, &tpg->se_tpg, SCSI_PROTOCOL_SAS);
1365 	if (ret < 0)
1366 		goto free_workqueue;
1367 
1368 	tpg_instances[i].tpg = tpg;
1369 	tpg->fi = tpg_instances[i].func_inst;
1370 	mutex_unlock(&opts->dep_lock);
1371 	mutex_unlock(&tpg_instances_lock);
1372 	return &tpg->se_tpg;
1373 
1374 free_workqueue:
1375 	destroy_workqueue(tpg->workqueue);
1376 free_tpg:
1377 	kfree(tpg);
1378 unref_dep:
1379 	if (opts->has_dep)
1380 		module_put(opts->dependent);
1381 	else
1382 		configfs_undepend_item_unlocked(&opts->func_inst.group.cg_item);
1383 unlock_dep:
1384 	mutex_unlock(&opts->dep_lock);
1385 unlock_inst:
1386 	mutex_unlock(&tpg_instances_lock);
1387 
1388 	return ERR_PTR(ret);
1389 }
1390 
1391 static int tcm_usbg_drop_nexus(struct usbg_tpg *);
1392 
1393 static void usbg_drop_tpg(struct se_portal_group *se_tpg)
1394 {
1395 	struct usbg_tpg *tpg = container_of(se_tpg,
1396 				struct usbg_tpg, se_tpg);
1397 	unsigned i;
1398 	struct f_tcm_opts *opts;
1399 
1400 	tcm_usbg_drop_nexus(tpg);
1401 	core_tpg_deregister(se_tpg);
1402 	destroy_workqueue(tpg->workqueue);
1403 
1404 	mutex_lock(&tpg_instances_lock);
1405 	for (i = 0; i < TPG_INSTANCES; ++i)
1406 		if (tpg_instances[i].tpg == tpg)
1407 			break;
1408 	if (i < TPG_INSTANCES) {
1409 		tpg_instances[i].tpg = NULL;
1410 		opts = container_of(tpg_instances[i].func_inst,
1411 			struct f_tcm_opts, func_inst);
1412 		mutex_lock(&opts->dep_lock);
1413 		if (opts->has_dep)
1414 			module_put(opts->dependent);
1415 		else
1416 			configfs_undepend_item_unlocked(
1417 				&opts->func_inst.group.cg_item);
1418 		mutex_unlock(&opts->dep_lock);
1419 	}
1420 	mutex_unlock(&tpg_instances_lock);
1421 
1422 	kfree(tpg);
1423 }
1424 
1425 static struct se_wwn *usbg_make_tport(
1426 	struct target_fabric_configfs *tf,
1427 	struct config_group *group,
1428 	const char *name)
1429 {
1430 	struct usbg_tport *tport;
1431 	const char *wnn_name;
1432 	u64 wwpn = 0;
1433 
1434 	wnn_name = usbg_check_wwn(name);
1435 	if (!wnn_name)
1436 		return ERR_PTR(-EINVAL);
1437 
1438 	tport = kzalloc(sizeof(struct usbg_tport), GFP_KERNEL);
1439 	if (!(tport))
1440 		return ERR_PTR(-ENOMEM);
1441 
1442 	tport->tport_wwpn = wwpn;
1443 	snprintf(tport->tport_name, sizeof(tport->tport_name), "%s", wnn_name);
1444 	return &tport->tport_wwn;
1445 }
1446 
1447 static void usbg_drop_tport(struct se_wwn *wwn)
1448 {
1449 	struct usbg_tport *tport = container_of(wwn,
1450 				struct usbg_tport, tport_wwn);
1451 	kfree(tport);
1452 }
1453 
1454 /*
1455  * If somebody feels like dropping the version property, go ahead.
1456  */
1457 static ssize_t usbg_wwn_version_show(struct config_item *item,  char *page)
1458 {
1459 	return sprintf(page, "usb-gadget fabric module\n");
1460 }
1461 
1462 CONFIGFS_ATTR_RO(usbg_wwn_, version);
1463 
1464 static struct configfs_attribute *usbg_wwn_attrs[] = {
1465 	&usbg_wwn_attr_version,
1466 	NULL,
1467 };
1468 
1469 static int usbg_attach(struct usbg_tpg *);
1470 static void usbg_detach(struct usbg_tpg *);
1471 
1472 static int usbg_enable_tpg(struct se_portal_group *se_tpg, bool enable)
1473 {
1474 	struct usbg_tpg  *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1475 	int ret = 0;
1476 
1477 	if (enable)
1478 		ret = usbg_attach(tpg);
1479 	else
1480 		usbg_detach(tpg);
1481 	if (ret)
1482 		return ret;
1483 
1484 	tpg->gadget_connect = enable;
1485 
1486 	return 0;
1487 }
1488 
1489 static ssize_t tcm_usbg_tpg_nexus_show(struct config_item *item, char *page)
1490 {
1491 	struct se_portal_group *se_tpg = to_tpg(item);
1492 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1493 	struct tcm_usbg_nexus *tv_nexus;
1494 	ssize_t ret;
1495 
1496 	mutex_lock(&tpg->tpg_mutex);
1497 	tv_nexus = tpg->tpg_nexus;
1498 	if (!tv_nexus) {
1499 		ret = -ENODEV;
1500 		goto out;
1501 	}
1502 	ret = sysfs_emit(page, "%s\n",
1503 			 tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1504 out:
1505 	mutex_unlock(&tpg->tpg_mutex);
1506 	return ret;
1507 }
1508 
1509 static int usbg_alloc_sess_cb(struct se_portal_group *se_tpg,
1510 			      struct se_session *se_sess, void *p)
1511 {
1512 	struct usbg_tpg *tpg = container_of(se_tpg,
1513 				struct usbg_tpg, se_tpg);
1514 
1515 	tpg->tpg_nexus = p;
1516 	return 0;
1517 }
1518 
1519 static int tcm_usbg_make_nexus(struct usbg_tpg *tpg, char *name)
1520 {
1521 	struct tcm_usbg_nexus *tv_nexus;
1522 	int ret = 0;
1523 
1524 	mutex_lock(&tpg->tpg_mutex);
1525 	if (tpg->tpg_nexus) {
1526 		ret = -EEXIST;
1527 		pr_debug("tpg->tpg_nexus already exists\n");
1528 		goto out_unlock;
1529 	}
1530 
1531 	tv_nexus = kzalloc(sizeof(*tv_nexus), GFP_KERNEL);
1532 	if (!tv_nexus) {
1533 		ret = -ENOMEM;
1534 		goto out_unlock;
1535 	}
1536 
1537 	tv_nexus->tvn_se_sess = target_setup_session(&tpg->se_tpg,
1538 						     USB_G_DEFAULT_SESSION_TAGS,
1539 						     sizeof(struct usbg_cmd),
1540 						     TARGET_PROT_NORMAL, name,
1541 						     tv_nexus, usbg_alloc_sess_cb);
1542 	if (IS_ERR(tv_nexus->tvn_se_sess)) {
1543 #define MAKE_NEXUS_MSG "core_tpg_check_initiator_node_acl() failed for %s\n"
1544 		pr_debug(MAKE_NEXUS_MSG, name);
1545 #undef MAKE_NEXUS_MSG
1546 		ret = PTR_ERR(tv_nexus->tvn_se_sess);
1547 		kfree(tv_nexus);
1548 	}
1549 
1550 out_unlock:
1551 	mutex_unlock(&tpg->tpg_mutex);
1552 	return ret;
1553 }
1554 
1555 static int tcm_usbg_drop_nexus(struct usbg_tpg *tpg)
1556 {
1557 	struct se_session *se_sess;
1558 	struct tcm_usbg_nexus *tv_nexus;
1559 	int ret = -ENODEV;
1560 
1561 	mutex_lock(&tpg->tpg_mutex);
1562 	tv_nexus = tpg->tpg_nexus;
1563 	if (!tv_nexus)
1564 		goto out;
1565 
1566 	se_sess = tv_nexus->tvn_se_sess;
1567 	if (!se_sess)
1568 		goto out;
1569 
1570 	if (atomic_read(&tpg->tpg_port_count)) {
1571 		ret = -EPERM;
1572 #define MSG "Unable to remove Host I_T Nexus with active TPG port count: %d\n"
1573 		pr_err(MSG, atomic_read(&tpg->tpg_port_count));
1574 #undef MSG
1575 		goto out;
1576 	}
1577 
1578 	pr_debug("Removing I_T Nexus to Initiator Port: %s\n",
1579 			tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1580 	/*
1581 	 * Release the SCSI I_T Nexus to the emulated vHost Target Port
1582 	 */
1583 	target_remove_session(se_sess);
1584 	tpg->tpg_nexus = NULL;
1585 
1586 	kfree(tv_nexus);
1587 	ret = 0;
1588 out:
1589 	mutex_unlock(&tpg->tpg_mutex);
1590 	return ret;
1591 }
1592 
1593 static ssize_t tcm_usbg_tpg_nexus_store(struct config_item *item,
1594 		const char *page, size_t count)
1595 {
1596 	struct se_portal_group *se_tpg = to_tpg(item);
1597 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1598 	unsigned char i_port[USBG_NAMELEN], *ptr;
1599 	int ret;
1600 
1601 	if (!strncmp(page, "NULL", 4)) {
1602 		ret = tcm_usbg_drop_nexus(tpg);
1603 		return (!ret) ? count : ret;
1604 	}
1605 	if (strlen(page) >= USBG_NAMELEN) {
1606 
1607 #define NEXUS_STORE_MSG "Emulated NAA Sas Address: %s, exceeds max: %d\n"
1608 		pr_err(NEXUS_STORE_MSG, page, USBG_NAMELEN);
1609 #undef NEXUS_STORE_MSG
1610 		return -EINVAL;
1611 	}
1612 	snprintf(i_port, USBG_NAMELEN, "%s", page);
1613 
1614 	ptr = strstr(i_port, "naa.");
1615 	if (!ptr) {
1616 		pr_err("Missing 'naa.' prefix\n");
1617 		return -EINVAL;
1618 	}
1619 
1620 	if (i_port[strlen(i_port) - 1] == '\n')
1621 		i_port[strlen(i_port) - 1] = '\0';
1622 
1623 	ret = tcm_usbg_make_nexus(tpg, &i_port[0]);
1624 	if (ret < 0)
1625 		return ret;
1626 	return count;
1627 }
1628 
1629 CONFIGFS_ATTR(tcm_usbg_tpg_, nexus);
1630 
1631 static struct configfs_attribute *usbg_base_attrs[] = {
1632 	&tcm_usbg_tpg_attr_nexus,
1633 	NULL,
1634 };
1635 
1636 static int usbg_port_link(struct se_portal_group *se_tpg, struct se_lun *lun)
1637 {
1638 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1639 
1640 	atomic_inc(&tpg->tpg_port_count);
1641 	smp_mb__after_atomic();
1642 	return 0;
1643 }
1644 
1645 static void usbg_port_unlink(struct se_portal_group *se_tpg,
1646 		struct se_lun *se_lun)
1647 {
1648 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1649 
1650 	atomic_dec(&tpg->tpg_port_count);
1651 	smp_mb__after_atomic();
1652 }
1653 
1654 static int usbg_check_stop_free(struct se_cmd *se_cmd)
1655 {
1656 	return target_put_sess_cmd(se_cmd);
1657 }
1658 
1659 static const struct target_core_fabric_ops usbg_ops = {
1660 	.module				= THIS_MODULE,
1661 	.fabric_name			= "usb_gadget",
1662 	.tpg_get_wwn			= usbg_get_fabric_wwn,
1663 	.tpg_get_tag			= usbg_get_tag,
1664 	.tpg_check_demo_mode		= usbg_check_true,
1665 	.release_cmd			= usbg_release_cmd,
1666 	.sess_get_initiator_sid		= NULL,
1667 	.write_pending			= usbg_send_write_request,
1668 	.queue_data_in			= usbg_send_read_response,
1669 	.queue_status			= usbg_send_status_response,
1670 	.queue_tm_rsp			= usbg_queue_tm_rsp,
1671 	.aborted_task			= usbg_aborted_task,
1672 	.check_stop_free		= usbg_check_stop_free,
1673 
1674 	.fabric_make_wwn		= usbg_make_tport,
1675 	.fabric_drop_wwn		= usbg_drop_tport,
1676 	.fabric_make_tpg		= usbg_make_tpg,
1677 	.fabric_enable_tpg		= usbg_enable_tpg,
1678 	.fabric_drop_tpg		= usbg_drop_tpg,
1679 	.fabric_post_link		= usbg_port_link,
1680 	.fabric_pre_unlink		= usbg_port_unlink,
1681 	.fabric_init_nodeacl		= usbg_init_nodeacl,
1682 
1683 	.tfc_wwn_attrs			= usbg_wwn_attrs,
1684 	.tfc_tpg_base_attrs		= usbg_base_attrs,
1685 
1686 	.default_submit_type		= TARGET_DIRECT_SUBMIT,
1687 	.direct_submit_supp		= 1,
1688 };
1689 
1690 /* Start gadget.c code */
1691 
1692 static struct usb_interface_descriptor bot_intf_desc = {
1693 	.bLength =              sizeof(bot_intf_desc),
1694 	.bDescriptorType =      USB_DT_INTERFACE,
1695 	.bNumEndpoints =        2,
1696 	.bAlternateSetting =	USB_G_ALT_INT_BBB,
1697 	.bInterfaceClass =      USB_CLASS_MASS_STORAGE,
1698 	.bInterfaceSubClass =   USB_SC_SCSI,
1699 	.bInterfaceProtocol =   USB_PR_BULK,
1700 };
1701 
1702 static struct usb_interface_descriptor uasp_intf_desc = {
1703 	.bLength =		sizeof(uasp_intf_desc),
1704 	.bDescriptorType =	USB_DT_INTERFACE,
1705 	.bNumEndpoints =	4,
1706 	.bAlternateSetting =	USB_G_ALT_INT_UAS,
1707 	.bInterfaceClass =	USB_CLASS_MASS_STORAGE,
1708 	.bInterfaceSubClass =	USB_SC_SCSI,
1709 	.bInterfaceProtocol =	USB_PR_UAS,
1710 };
1711 
1712 static struct usb_endpoint_descriptor uasp_bi_desc = {
1713 	.bLength =		USB_DT_ENDPOINT_SIZE,
1714 	.bDescriptorType =	USB_DT_ENDPOINT,
1715 	.bEndpointAddress =	USB_DIR_IN,
1716 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1717 	.wMaxPacketSize =	cpu_to_le16(512),
1718 };
1719 
1720 static struct usb_endpoint_descriptor uasp_fs_bi_desc = {
1721 	.bLength =		USB_DT_ENDPOINT_SIZE,
1722 	.bDescriptorType =	USB_DT_ENDPOINT,
1723 	.bEndpointAddress =	USB_DIR_IN,
1724 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1725 };
1726 
1727 static struct usb_pipe_usage_descriptor uasp_bi_pipe_desc = {
1728 	.bLength =		sizeof(uasp_bi_pipe_desc),
1729 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1730 	.bPipeID =		DATA_IN_PIPE_ID,
1731 };
1732 
1733 static struct usb_endpoint_descriptor uasp_ss_bi_desc = {
1734 	.bLength =		USB_DT_ENDPOINT_SIZE,
1735 	.bDescriptorType =	USB_DT_ENDPOINT,
1736 	.bEndpointAddress =	USB_DIR_IN,
1737 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1738 	.wMaxPacketSize =	cpu_to_le16(1024),
1739 };
1740 
1741 static struct usb_ss_ep_comp_descriptor uasp_bi_ep_comp_desc = {
1742 	.bLength =		sizeof(uasp_bi_ep_comp_desc),
1743 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1744 	.bMaxBurst =		0,
1745 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1746 	.wBytesPerInterval =	0,
1747 };
1748 
1749 static struct usb_ss_ep_comp_descriptor bot_bi_ep_comp_desc = {
1750 	.bLength =		sizeof(bot_bi_ep_comp_desc),
1751 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1752 	.bMaxBurst =		0,
1753 };
1754 
1755 static struct usb_endpoint_descriptor uasp_bo_desc = {
1756 	.bLength =		USB_DT_ENDPOINT_SIZE,
1757 	.bDescriptorType =	USB_DT_ENDPOINT,
1758 	.bEndpointAddress =	USB_DIR_OUT,
1759 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1760 	.wMaxPacketSize =	cpu_to_le16(512),
1761 };
1762 
1763 static struct usb_endpoint_descriptor uasp_fs_bo_desc = {
1764 	.bLength =		USB_DT_ENDPOINT_SIZE,
1765 	.bDescriptorType =	USB_DT_ENDPOINT,
1766 	.bEndpointAddress =	USB_DIR_OUT,
1767 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1768 };
1769 
1770 static struct usb_pipe_usage_descriptor uasp_bo_pipe_desc = {
1771 	.bLength =		sizeof(uasp_bo_pipe_desc),
1772 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1773 	.bPipeID =		DATA_OUT_PIPE_ID,
1774 };
1775 
1776 static struct usb_endpoint_descriptor uasp_ss_bo_desc = {
1777 	.bLength =		USB_DT_ENDPOINT_SIZE,
1778 	.bDescriptorType =	USB_DT_ENDPOINT,
1779 	.bEndpointAddress =	USB_DIR_OUT,
1780 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1781 	.wMaxPacketSize =	cpu_to_le16(0x400),
1782 };
1783 
1784 static struct usb_ss_ep_comp_descriptor uasp_bo_ep_comp_desc = {
1785 	.bLength =		sizeof(uasp_bo_ep_comp_desc),
1786 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1787 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1788 };
1789 
1790 static struct usb_ss_ep_comp_descriptor bot_bo_ep_comp_desc = {
1791 	.bLength =		sizeof(bot_bo_ep_comp_desc),
1792 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1793 };
1794 
1795 static struct usb_endpoint_descriptor uasp_status_desc = {
1796 	.bLength =		USB_DT_ENDPOINT_SIZE,
1797 	.bDescriptorType =	USB_DT_ENDPOINT,
1798 	.bEndpointAddress =	USB_DIR_IN,
1799 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1800 	.wMaxPacketSize =	cpu_to_le16(512),
1801 };
1802 
1803 static struct usb_endpoint_descriptor uasp_fs_status_desc = {
1804 	.bLength =		USB_DT_ENDPOINT_SIZE,
1805 	.bDescriptorType =	USB_DT_ENDPOINT,
1806 	.bEndpointAddress =	USB_DIR_IN,
1807 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1808 };
1809 
1810 static struct usb_pipe_usage_descriptor uasp_status_pipe_desc = {
1811 	.bLength =		sizeof(uasp_status_pipe_desc),
1812 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1813 	.bPipeID =		STATUS_PIPE_ID,
1814 };
1815 
1816 static struct usb_endpoint_descriptor uasp_ss_status_desc = {
1817 	.bLength =		USB_DT_ENDPOINT_SIZE,
1818 	.bDescriptorType =	USB_DT_ENDPOINT,
1819 	.bEndpointAddress =	USB_DIR_IN,
1820 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1821 	.wMaxPacketSize =	cpu_to_le16(1024),
1822 };
1823 
1824 static struct usb_ss_ep_comp_descriptor uasp_status_in_ep_comp_desc = {
1825 	.bLength =		sizeof(uasp_status_in_ep_comp_desc),
1826 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1827 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1828 };
1829 
1830 static struct usb_endpoint_descriptor uasp_cmd_desc = {
1831 	.bLength =		USB_DT_ENDPOINT_SIZE,
1832 	.bDescriptorType =	USB_DT_ENDPOINT,
1833 	.bEndpointAddress =	USB_DIR_OUT,
1834 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1835 	.wMaxPacketSize =	cpu_to_le16(512),
1836 };
1837 
1838 static struct usb_endpoint_descriptor uasp_fs_cmd_desc = {
1839 	.bLength =		USB_DT_ENDPOINT_SIZE,
1840 	.bDescriptorType =	USB_DT_ENDPOINT,
1841 	.bEndpointAddress =	USB_DIR_OUT,
1842 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1843 };
1844 
1845 static struct usb_pipe_usage_descriptor uasp_cmd_pipe_desc = {
1846 	.bLength =		sizeof(uasp_cmd_pipe_desc),
1847 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1848 	.bPipeID =		CMD_PIPE_ID,
1849 };
1850 
1851 static struct usb_endpoint_descriptor uasp_ss_cmd_desc = {
1852 	.bLength =		USB_DT_ENDPOINT_SIZE,
1853 	.bDescriptorType =	USB_DT_ENDPOINT,
1854 	.bEndpointAddress =	USB_DIR_OUT,
1855 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1856 	.wMaxPacketSize =	cpu_to_le16(1024),
1857 };
1858 
1859 static struct usb_ss_ep_comp_descriptor uasp_cmd_comp_desc = {
1860 	.bLength =		sizeof(uasp_cmd_comp_desc),
1861 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1862 };
1863 
1864 static struct usb_descriptor_header *uasp_fs_function_desc[] = {
1865 	(struct usb_descriptor_header *) &bot_intf_desc,
1866 	(struct usb_descriptor_header *) &uasp_fs_bi_desc,
1867 	(struct usb_descriptor_header *) &uasp_fs_bo_desc,
1868 
1869 	(struct usb_descriptor_header *) &uasp_intf_desc,
1870 	(struct usb_descriptor_header *) &uasp_fs_bi_desc,
1871 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1872 	(struct usb_descriptor_header *) &uasp_fs_bo_desc,
1873 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1874 	(struct usb_descriptor_header *) &uasp_fs_status_desc,
1875 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1876 	(struct usb_descriptor_header *) &uasp_fs_cmd_desc,
1877 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1878 	NULL,
1879 };
1880 
1881 static struct usb_descriptor_header *uasp_hs_function_desc[] = {
1882 	(struct usb_descriptor_header *) &bot_intf_desc,
1883 	(struct usb_descriptor_header *) &uasp_bi_desc,
1884 	(struct usb_descriptor_header *) &uasp_bo_desc,
1885 
1886 	(struct usb_descriptor_header *) &uasp_intf_desc,
1887 	(struct usb_descriptor_header *) &uasp_bi_desc,
1888 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1889 	(struct usb_descriptor_header *) &uasp_bo_desc,
1890 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1891 	(struct usb_descriptor_header *) &uasp_status_desc,
1892 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1893 	(struct usb_descriptor_header *) &uasp_cmd_desc,
1894 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1895 	NULL,
1896 };
1897 
1898 static struct usb_descriptor_header *uasp_ss_function_desc[] = {
1899 	(struct usb_descriptor_header *) &bot_intf_desc,
1900 	(struct usb_descriptor_header *) &uasp_ss_bi_desc,
1901 	(struct usb_descriptor_header *) &bot_bi_ep_comp_desc,
1902 	(struct usb_descriptor_header *) &uasp_ss_bo_desc,
1903 	(struct usb_descriptor_header *) &bot_bo_ep_comp_desc,
1904 
1905 	(struct usb_descriptor_header *) &uasp_intf_desc,
1906 	(struct usb_descriptor_header *) &uasp_ss_bi_desc,
1907 	(struct usb_descriptor_header *) &uasp_bi_ep_comp_desc,
1908 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1909 	(struct usb_descriptor_header *) &uasp_ss_bo_desc,
1910 	(struct usb_descriptor_header *) &uasp_bo_ep_comp_desc,
1911 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1912 	(struct usb_descriptor_header *) &uasp_ss_status_desc,
1913 	(struct usb_descriptor_header *) &uasp_status_in_ep_comp_desc,
1914 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1915 	(struct usb_descriptor_header *) &uasp_ss_cmd_desc,
1916 	(struct usb_descriptor_header *) &uasp_cmd_comp_desc,
1917 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1918 	NULL,
1919 };
1920 
1921 static struct usb_string	tcm_us_strings[] = {
1922 	[USB_G_STR_INT_UAS].s		= "USB Attached SCSI",
1923 	[USB_G_STR_INT_BBB].s		= "Bulk Only Transport",
1924 	{ },
1925 };
1926 
1927 static struct usb_gadget_strings tcm_stringtab = {
1928 	.language = 0x0409,
1929 	.strings = tcm_us_strings,
1930 };
1931 
1932 static struct usb_gadget_strings *tcm_strings[] = {
1933 	&tcm_stringtab,
1934 	NULL,
1935 };
1936 
1937 static int tcm_bind(struct usb_configuration *c, struct usb_function *f)
1938 {
1939 	struct f_uas		*fu = to_f_uas(f);
1940 	struct usb_string	*us;
1941 	struct usb_gadget	*gadget = c->cdev->gadget;
1942 	struct usb_ep		*ep;
1943 	struct f_tcm_opts	*opts;
1944 	int			iface;
1945 	int			ret;
1946 
1947 	opts = container_of(f->fi, struct f_tcm_opts, func_inst);
1948 
1949 	mutex_lock(&opts->dep_lock);
1950 	if (!opts->can_attach) {
1951 		mutex_unlock(&opts->dep_lock);
1952 		return -ENODEV;
1953 	}
1954 	mutex_unlock(&opts->dep_lock);
1955 	us = usb_gstrings_attach(c->cdev, tcm_strings,
1956 		ARRAY_SIZE(tcm_us_strings));
1957 	if (IS_ERR(us))
1958 		return PTR_ERR(us);
1959 	bot_intf_desc.iInterface = us[USB_G_STR_INT_BBB].id;
1960 	uasp_intf_desc.iInterface = us[USB_G_STR_INT_UAS].id;
1961 
1962 	iface = usb_interface_id(c, f);
1963 	if (iface < 0)
1964 		return iface;
1965 
1966 	bot_intf_desc.bInterfaceNumber = iface;
1967 	uasp_intf_desc.bInterfaceNumber = iface;
1968 	fu->iface = iface;
1969 	ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_bi_desc,
1970 			&uasp_bi_ep_comp_desc);
1971 	if (!ep)
1972 		goto ep_fail;
1973 
1974 	fu->ep_in = ep;
1975 
1976 	ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_bo_desc,
1977 			&uasp_bo_ep_comp_desc);
1978 	if (!ep)
1979 		goto ep_fail;
1980 	fu->ep_out = ep;
1981 
1982 	ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_status_desc,
1983 			&uasp_status_in_ep_comp_desc);
1984 	if (!ep)
1985 		goto ep_fail;
1986 	fu->ep_status = ep;
1987 
1988 	ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_cmd_desc,
1989 			&uasp_cmd_comp_desc);
1990 	if (!ep)
1991 		goto ep_fail;
1992 	fu->ep_cmd = ep;
1993 
1994 	/* Assume endpoint addresses are the same for both speeds */
1995 	uasp_bi_desc.bEndpointAddress =	uasp_ss_bi_desc.bEndpointAddress;
1996 	uasp_bo_desc.bEndpointAddress = uasp_ss_bo_desc.bEndpointAddress;
1997 	uasp_status_desc.bEndpointAddress =
1998 		uasp_ss_status_desc.bEndpointAddress;
1999 	uasp_cmd_desc.bEndpointAddress = uasp_ss_cmd_desc.bEndpointAddress;
2000 
2001 	uasp_fs_bi_desc.bEndpointAddress = uasp_ss_bi_desc.bEndpointAddress;
2002 	uasp_fs_bo_desc.bEndpointAddress = uasp_ss_bo_desc.bEndpointAddress;
2003 	uasp_fs_status_desc.bEndpointAddress =
2004 		uasp_ss_status_desc.bEndpointAddress;
2005 	uasp_fs_cmd_desc.bEndpointAddress = uasp_ss_cmd_desc.bEndpointAddress;
2006 
2007 	ret = usb_assign_descriptors(f, uasp_fs_function_desc,
2008 			uasp_hs_function_desc, uasp_ss_function_desc,
2009 			uasp_ss_function_desc);
2010 	if (ret)
2011 		goto ep_fail;
2012 
2013 	return 0;
2014 ep_fail:
2015 	pr_err("Can't claim all required eps\n");
2016 
2017 	return -ENOTSUPP;
2018 }
2019 
2020 struct guas_setup_wq {
2021 	struct work_struct work;
2022 	struct f_uas *fu;
2023 	unsigned int alt;
2024 };
2025 
2026 static void tcm_delayed_set_alt(struct work_struct *wq)
2027 {
2028 	struct guas_setup_wq *work = container_of(wq, struct guas_setup_wq,
2029 			work);
2030 	struct f_uas *fu = work->fu;
2031 	int alt = work->alt;
2032 
2033 	kfree(work);
2034 
2035 	if (fu->flags & USBG_IS_BOT)
2036 		bot_cleanup_old_alt(fu);
2037 	if (fu->flags & USBG_IS_UAS)
2038 		uasp_cleanup_old_alt(fu);
2039 
2040 	if (alt == USB_G_ALT_INT_BBB)
2041 		bot_set_alt(fu);
2042 	else if (alt == USB_G_ALT_INT_UAS)
2043 		uasp_set_alt(fu);
2044 	usb_composite_setup_continue(fu->function.config->cdev);
2045 }
2046 
2047 static int tcm_get_alt(struct usb_function *f, unsigned intf)
2048 {
2049 	if (intf == bot_intf_desc.bInterfaceNumber)
2050 		return USB_G_ALT_INT_BBB;
2051 	if (intf == uasp_intf_desc.bInterfaceNumber)
2052 		return USB_G_ALT_INT_UAS;
2053 
2054 	return -EOPNOTSUPP;
2055 }
2056 
2057 static int tcm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2058 {
2059 	struct f_uas *fu = to_f_uas(f);
2060 
2061 	if ((alt == USB_G_ALT_INT_BBB) || (alt == USB_G_ALT_INT_UAS)) {
2062 		struct guas_setup_wq *work;
2063 
2064 		work = kmalloc(sizeof(*work), GFP_ATOMIC);
2065 		if (!work)
2066 			return -ENOMEM;
2067 		INIT_WORK(&work->work, tcm_delayed_set_alt);
2068 		work->fu = fu;
2069 		work->alt = alt;
2070 		schedule_work(&work->work);
2071 		return USB_GADGET_DELAYED_STATUS;
2072 	}
2073 	return -EOPNOTSUPP;
2074 }
2075 
2076 static void tcm_disable(struct usb_function *f)
2077 {
2078 	struct f_uas *fu = to_f_uas(f);
2079 
2080 	if (fu->flags & USBG_IS_UAS)
2081 		uasp_cleanup_old_alt(fu);
2082 	else if (fu->flags & USBG_IS_BOT)
2083 		bot_cleanup_old_alt(fu);
2084 	fu->flags = 0;
2085 }
2086 
2087 static int tcm_setup(struct usb_function *f,
2088 		const struct usb_ctrlrequest *ctrl)
2089 {
2090 	struct f_uas *fu = to_f_uas(f);
2091 
2092 	if (!(fu->flags & USBG_IS_BOT))
2093 		return -EOPNOTSUPP;
2094 
2095 	return usbg_bot_setup(f, ctrl);
2096 }
2097 
2098 static inline struct f_tcm_opts *to_f_tcm_opts(struct config_item *item)
2099 {
2100 	return container_of(to_config_group(item), struct f_tcm_opts,
2101 		func_inst.group);
2102 }
2103 
2104 static void tcm_attr_release(struct config_item *item)
2105 {
2106 	struct f_tcm_opts *opts = to_f_tcm_opts(item);
2107 
2108 	usb_put_function_instance(&opts->func_inst);
2109 }
2110 
2111 static struct configfs_item_operations tcm_item_ops = {
2112 	.release		= tcm_attr_release,
2113 };
2114 
2115 static const struct config_item_type tcm_func_type = {
2116 	.ct_item_ops	= &tcm_item_ops,
2117 	.ct_owner	= THIS_MODULE,
2118 };
2119 
2120 static void tcm_free_inst(struct usb_function_instance *f)
2121 {
2122 	struct f_tcm_opts *opts;
2123 	unsigned i;
2124 
2125 	opts = container_of(f, struct f_tcm_opts, func_inst);
2126 
2127 	mutex_lock(&tpg_instances_lock);
2128 	for (i = 0; i < TPG_INSTANCES; ++i)
2129 		if (tpg_instances[i].func_inst == f)
2130 			break;
2131 	if (i < TPG_INSTANCES)
2132 		tpg_instances[i].func_inst = NULL;
2133 	mutex_unlock(&tpg_instances_lock);
2134 
2135 	kfree(opts);
2136 }
2137 
2138 static int tcm_register_callback(struct usb_function_instance *f)
2139 {
2140 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2141 
2142 	mutex_lock(&opts->dep_lock);
2143 	opts->can_attach = true;
2144 	mutex_unlock(&opts->dep_lock);
2145 
2146 	return 0;
2147 }
2148 
2149 static void tcm_unregister_callback(struct usb_function_instance *f)
2150 {
2151 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2152 
2153 	mutex_lock(&opts->dep_lock);
2154 	unregister_gadget_item(opts->
2155 		func_inst.group.cg_item.ci_parent->ci_parent);
2156 	opts->can_attach = false;
2157 	mutex_unlock(&opts->dep_lock);
2158 }
2159 
2160 static int usbg_attach(struct usbg_tpg *tpg)
2161 {
2162 	struct usb_function_instance *f = tpg->fi;
2163 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2164 
2165 	if (opts->tcm_register_callback)
2166 		return opts->tcm_register_callback(f);
2167 
2168 	return 0;
2169 }
2170 
2171 static void usbg_detach(struct usbg_tpg *tpg)
2172 {
2173 	struct usb_function_instance *f = tpg->fi;
2174 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2175 
2176 	if (opts->tcm_unregister_callback)
2177 		opts->tcm_unregister_callback(f);
2178 }
2179 
2180 static int tcm_set_name(struct usb_function_instance *f, const char *name)
2181 {
2182 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2183 
2184 	pr_debug("tcm: Activating %s\n", name);
2185 
2186 	mutex_lock(&opts->dep_lock);
2187 	opts->ready = true;
2188 	mutex_unlock(&opts->dep_lock);
2189 
2190 	return 0;
2191 }
2192 
2193 static struct usb_function_instance *tcm_alloc_inst(void)
2194 {
2195 	struct f_tcm_opts *opts;
2196 	int i;
2197 
2198 
2199 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2200 	if (!opts)
2201 		return ERR_PTR(-ENOMEM);
2202 
2203 	mutex_lock(&tpg_instances_lock);
2204 	for (i = 0; i < TPG_INSTANCES; ++i)
2205 		if (!tpg_instances[i].func_inst)
2206 			break;
2207 
2208 	if (i == TPG_INSTANCES) {
2209 		mutex_unlock(&tpg_instances_lock);
2210 		kfree(opts);
2211 		return ERR_PTR(-EBUSY);
2212 	}
2213 	tpg_instances[i].func_inst = &opts->func_inst;
2214 	mutex_unlock(&tpg_instances_lock);
2215 
2216 	mutex_init(&opts->dep_lock);
2217 	opts->func_inst.set_inst_name = tcm_set_name;
2218 	opts->func_inst.free_func_inst = tcm_free_inst;
2219 	opts->tcm_register_callback = tcm_register_callback;
2220 	opts->tcm_unregister_callback = tcm_unregister_callback;
2221 
2222 	config_group_init_type_name(&opts->func_inst.group, "",
2223 			&tcm_func_type);
2224 
2225 	return &opts->func_inst;
2226 }
2227 
2228 static void tcm_free(struct usb_function *f)
2229 {
2230 	struct f_uas *tcm = to_f_uas(f);
2231 
2232 	kfree(tcm);
2233 }
2234 
2235 static void tcm_unbind(struct usb_configuration *c, struct usb_function *f)
2236 {
2237 	usb_free_all_descriptors(f);
2238 }
2239 
2240 static struct usb_function *tcm_alloc(struct usb_function_instance *fi)
2241 {
2242 	struct f_uas *fu;
2243 	unsigned i;
2244 
2245 	mutex_lock(&tpg_instances_lock);
2246 	for (i = 0; i < TPG_INSTANCES; ++i)
2247 		if (tpg_instances[i].func_inst == fi)
2248 			break;
2249 	if (i == TPG_INSTANCES) {
2250 		mutex_unlock(&tpg_instances_lock);
2251 		return ERR_PTR(-ENODEV);
2252 	}
2253 
2254 	fu = kzalloc(sizeof(*fu), GFP_KERNEL);
2255 	if (!fu) {
2256 		mutex_unlock(&tpg_instances_lock);
2257 		return ERR_PTR(-ENOMEM);
2258 	}
2259 
2260 	fu->function.name = "Target Function";
2261 	fu->function.bind = tcm_bind;
2262 	fu->function.unbind = tcm_unbind;
2263 	fu->function.set_alt = tcm_set_alt;
2264 	fu->function.get_alt = tcm_get_alt;
2265 	fu->function.setup = tcm_setup;
2266 	fu->function.disable = tcm_disable;
2267 	fu->function.free_func = tcm_free;
2268 	fu->tpg = tpg_instances[i].tpg;
2269 	mutex_unlock(&tpg_instances_lock);
2270 
2271 	return &fu->function;
2272 }
2273 
2274 DECLARE_USB_FUNCTION(tcm, tcm_alloc_inst, tcm_alloc);
2275 
2276 static int __init tcm_init(void)
2277 {
2278 	int ret;
2279 
2280 	ret = usb_function_register(&tcmusb_func);
2281 	if (ret)
2282 		return ret;
2283 
2284 	ret = target_register_template(&usbg_ops);
2285 	if (ret)
2286 		usb_function_unregister(&tcmusb_func);
2287 
2288 	return ret;
2289 }
2290 module_init(tcm_init);
2291 
2292 static void __exit tcm_exit(void)
2293 {
2294 	target_unregister_template(&usbg_ops);
2295 	usb_function_unregister(&tcmusb_func);
2296 }
2297 module_exit(tcm_exit);
2298 
2299 MODULE_DESCRIPTION("Target based USB-Gadget");
2300 MODULE_LICENSE("GPL");
2301 MODULE_AUTHOR("Sebastian Andrzej Siewior");
2302