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