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