xref: /linux-6.15/drivers/usb/gadget/function/f_tcm.c (revision 76003eb6)
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 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd, se_cmd);
1261 	struct f_uas *fu = cmd->fu;
1262 	struct usb_gadget *gadget = fuas_to_gadget(fu);
1263 	struct uas_stream *stream = &fu->stream[se_cmd->map_tag];
1264 	int ret = 0;
1265 
1266 	if (stream->req_out->status == -EINPROGRESS)
1267 		ret = usb_ep_dequeue(fu->ep_out, stream->req_out);
1268 	else if (stream->req_in->status == -EINPROGRESS)
1269 		ret = usb_ep_dequeue(fu->ep_in, stream->req_in);
1270 	else if (stream->req_status->status == -EINPROGRESS)
1271 		ret = usb_ep_dequeue(fu->ep_status, stream->req_status);
1272 
1273 	if (ret)
1274 		dev_err(&gadget->dev, "Failed to abort cmd tag %d, (%d)\n",
1275 			cmd->tag, ret);
1276 
1277 	cmd->state = UASP_QUEUE_COMMAND;
1278 }
1279 
1280 static const char *usbg_check_wwn(const char *name)
1281 {
1282 	const char *n;
1283 	unsigned int len;
1284 
1285 	n = strstr(name, "naa.");
1286 	if (!n)
1287 		return NULL;
1288 	n += 4;
1289 	len = strlen(n);
1290 	if (len == 0 || len > USBG_NAMELEN - 1)
1291 		return NULL;
1292 	return n;
1293 }
1294 
1295 static int usbg_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
1296 {
1297 	if (!usbg_check_wwn(name))
1298 		return -EINVAL;
1299 	return 0;
1300 }
1301 
1302 static struct se_portal_group *usbg_make_tpg(struct se_wwn *wwn,
1303 					     const char *name)
1304 {
1305 	struct usbg_tport *tport = container_of(wwn, struct usbg_tport,
1306 			tport_wwn);
1307 	struct usbg_tpg *tpg;
1308 	unsigned long tpgt;
1309 	int ret;
1310 	struct f_tcm_opts *opts;
1311 	unsigned i;
1312 
1313 	if (strstr(name, "tpgt_") != name)
1314 		return ERR_PTR(-EINVAL);
1315 	if (kstrtoul(name + 5, 0, &tpgt) || tpgt > UINT_MAX)
1316 		return ERR_PTR(-EINVAL);
1317 	ret = -ENODEV;
1318 	mutex_lock(&tpg_instances_lock);
1319 	for (i = 0; i < TPG_INSTANCES; ++i)
1320 		if (tpg_instances[i].func_inst && !tpg_instances[i].tpg)
1321 			break;
1322 	if (i == TPG_INSTANCES)
1323 		goto unlock_inst;
1324 
1325 	opts = container_of(tpg_instances[i].func_inst, struct f_tcm_opts,
1326 		func_inst);
1327 	mutex_lock(&opts->dep_lock);
1328 	if (!opts->ready)
1329 		goto unlock_dep;
1330 
1331 	if (opts->has_dep) {
1332 		if (!try_module_get(opts->dependent))
1333 			goto unlock_dep;
1334 	} else {
1335 		ret = configfs_depend_item_unlocked(
1336 			wwn->wwn_group.cg_subsys,
1337 			&opts->func_inst.group.cg_item);
1338 		if (ret)
1339 			goto unlock_dep;
1340 	}
1341 
1342 	tpg = kzalloc(sizeof(struct usbg_tpg), GFP_KERNEL);
1343 	ret = -ENOMEM;
1344 	if (!tpg)
1345 		goto unref_dep;
1346 	mutex_init(&tpg->tpg_mutex);
1347 	atomic_set(&tpg->tpg_port_count, 0);
1348 	tpg->workqueue = alloc_workqueue("tcm_usb_gadget",
1349 					 WQ_UNBOUND, WQ_UNBOUND_MAX_ACTIVE);
1350 	if (!tpg->workqueue)
1351 		goto free_tpg;
1352 
1353 	tpg->tport = tport;
1354 	tpg->tport_tpgt = tpgt;
1355 
1356 	/*
1357 	 * SPC doesn't assign a protocol identifier for USB-SCSI, so we
1358 	 * pretend to be SAS..
1359 	 */
1360 	ret = core_tpg_register(wwn, &tpg->se_tpg, SCSI_PROTOCOL_SAS);
1361 	if (ret < 0)
1362 		goto free_workqueue;
1363 
1364 	tpg_instances[i].tpg = tpg;
1365 	tpg->fi = tpg_instances[i].func_inst;
1366 	mutex_unlock(&opts->dep_lock);
1367 	mutex_unlock(&tpg_instances_lock);
1368 	return &tpg->se_tpg;
1369 
1370 free_workqueue:
1371 	destroy_workqueue(tpg->workqueue);
1372 free_tpg:
1373 	kfree(tpg);
1374 unref_dep:
1375 	if (opts->has_dep)
1376 		module_put(opts->dependent);
1377 	else
1378 		configfs_undepend_item_unlocked(&opts->func_inst.group.cg_item);
1379 unlock_dep:
1380 	mutex_unlock(&opts->dep_lock);
1381 unlock_inst:
1382 	mutex_unlock(&tpg_instances_lock);
1383 
1384 	return ERR_PTR(ret);
1385 }
1386 
1387 static int tcm_usbg_drop_nexus(struct usbg_tpg *);
1388 
1389 static void usbg_drop_tpg(struct se_portal_group *se_tpg)
1390 {
1391 	struct usbg_tpg *tpg = container_of(se_tpg,
1392 				struct usbg_tpg, se_tpg);
1393 	unsigned i;
1394 	struct f_tcm_opts *opts;
1395 
1396 	tcm_usbg_drop_nexus(tpg);
1397 	core_tpg_deregister(se_tpg);
1398 	destroy_workqueue(tpg->workqueue);
1399 
1400 	mutex_lock(&tpg_instances_lock);
1401 	for (i = 0; i < TPG_INSTANCES; ++i)
1402 		if (tpg_instances[i].tpg == tpg)
1403 			break;
1404 	if (i < TPG_INSTANCES) {
1405 		tpg_instances[i].tpg = NULL;
1406 		opts = container_of(tpg_instances[i].func_inst,
1407 			struct f_tcm_opts, func_inst);
1408 		mutex_lock(&opts->dep_lock);
1409 		if (opts->has_dep)
1410 			module_put(opts->dependent);
1411 		else
1412 			configfs_undepend_item_unlocked(
1413 				&opts->func_inst.group.cg_item);
1414 		mutex_unlock(&opts->dep_lock);
1415 	}
1416 	mutex_unlock(&tpg_instances_lock);
1417 
1418 	kfree(tpg);
1419 }
1420 
1421 static struct se_wwn *usbg_make_tport(
1422 	struct target_fabric_configfs *tf,
1423 	struct config_group *group,
1424 	const char *name)
1425 {
1426 	struct usbg_tport *tport;
1427 	const char *wnn_name;
1428 	u64 wwpn = 0;
1429 
1430 	wnn_name = usbg_check_wwn(name);
1431 	if (!wnn_name)
1432 		return ERR_PTR(-EINVAL);
1433 
1434 	tport = kzalloc(sizeof(struct usbg_tport), GFP_KERNEL);
1435 	if (!(tport))
1436 		return ERR_PTR(-ENOMEM);
1437 
1438 	tport->tport_wwpn = wwpn;
1439 	snprintf(tport->tport_name, sizeof(tport->tport_name), "%s", wnn_name);
1440 	return &tport->tport_wwn;
1441 }
1442 
1443 static void usbg_drop_tport(struct se_wwn *wwn)
1444 {
1445 	struct usbg_tport *tport = container_of(wwn,
1446 				struct usbg_tport, tport_wwn);
1447 	kfree(tport);
1448 }
1449 
1450 /*
1451  * If somebody feels like dropping the version property, go ahead.
1452  */
1453 static ssize_t usbg_wwn_version_show(struct config_item *item,  char *page)
1454 {
1455 	return sprintf(page, "usb-gadget fabric module\n");
1456 }
1457 
1458 CONFIGFS_ATTR_RO(usbg_wwn_, version);
1459 
1460 static struct configfs_attribute *usbg_wwn_attrs[] = {
1461 	&usbg_wwn_attr_version,
1462 	NULL,
1463 };
1464 
1465 static int usbg_attach(struct usbg_tpg *);
1466 static void usbg_detach(struct usbg_tpg *);
1467 
1468 static int usbg_enable_tpg(struct se_portal_group *se_tpg, bool enable)
1469 {
1470 	struct usbg_tpg  *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1471 	int ret = 0;
1472 
1473 	if (enable)
1474 		ret = usbg_attach(tpg);
1475 	else
1476 		usbg_detach(tpg);
1477 	if (ret)
1478 		return ret;
1479 
1480 	tpg->gadget_connect = enable;
1481 
1482 	return 0;
1483 }
1484 
1485 static ssize_t tcm_usbg_tpg_nexus_show(struct config_item *item, char *page)
1486 {
1487 	struct se_portal_group *se_tpg = to_tpg(item);
1488 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1489 	struct tcm_usbg_nexus *tv_nexus;
1490 	ssize_t ret;
1491 
1492 	mutex_lock(&tpg->tpg_mutex);
1493 	tv_nexus = tpg->tpg_nexus;
1494 	if (!tv_nexus) {
1495 		ret = -ENODEV;
1496 		goto out;
1497 	}
1498 	ret = sysfs_emit(page, "%s\n",
1499 			 tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1500 out:
1501 	mutex_unlock(&tpg->tpg_mutex);
1502 	return ret;
1503 }
1504 
1505 static int usbg_alloc_sess_cb(struct se_portal_group *se_tpg,
1506 			      struct se_session *se_sess, void *p)
1507 {
1508 	struct usbg_tpg *tpg = container_of(se_tpg,
1509 				struct usbg_tpg, se_tpg);
1510 
1511 	tpg->tpg_nexus = p;
1512 	return 0;
1513 }
1514 
1515 static int tcm_usbg_make_nexus(struct usbg_tpg *tpg, char *name)
1516 {
1517 	struct tcm_usbg_nexus *tv_nexus;
1518 	int ret = 0;
1519 
1520 	mutex_lock(&tpg->tpg_mutex);
1521 	if (tpg->tpg_nexus) {
1522 		ret = -EEXIST;
1523 		pr_debug("tpg->tpg_nexus already exists\n");
1524 		goto out_unlock;
1525 	}
1526 
1527 	tv_nexus = kzalloc(sizeof(*tv_nexus), GFP_KERNEL);
1528 	if (!tv_nexus) {
1529 		ret = -ENOMEM;
1530 		goto out_unlock;
1531 	}
1532 
1533 	tv_nexus->tvn_se_sess = target_setup_session(&tpg->se_tpg,
1534 						     USB_G_DEFAULT_SESSION_TAGS,
1535 						     sizeof(struct usbg_cmd),
1536 						     TARGET_PROT_NORMAL, name,
1537 						     tv_nexus, usbg_alloc_sess_cb);
1538 	if (IS_ERR(tv_nexus->tvn_se_sess)) {
1539 #define MAKE_NEXUS_MSG "core_tpg_check_initiator_node_acl() failed for %s\n"
1540 		pr_debug(MAKE_NEXUS_MSG, name);
1541 #undef MAKE_NEXUS_MSG
1542 		ret = PTR_ERR(tv_nexus->tvn_se_sess);
1543 		kfree(tv_nexus);
1544 	}
1545 
1546 out_unlock:
1547 	mutex_unlock(&tpg->tpg_mutex);
1548 	return ret;
1549 }
1550 
1551 static int tcm_usbg_drop_nexus(struct usbg_tpg *tpg)
1552 {
1553 	struct se_session *se_sess;
1554 	struct tcm_usbg_nexus *tv_nexus;
1555 	int ret = -ENODEV;
1556 
1557 	mutex_lock(&tpg->tpg_mutex);
1558 	tv_nexus = tpg->tpg_nexus;
1559 	if (!tv_nexus)
1560 		goto out;
1561 
1562 	se_sess = tv_nexus->tvn_se_sess;
1563 	if (!se_sess)
1564 		goto out;
1565 
1566 	if (atomic_read(&tpg->tpg_port_count)) {
1567 		ret = -EPERM;
1568 #define MSG "Unable to remove Host I_T Nexus with active TPG port count: %d\n"
1569 		pr_err(MSG, atomic_read(&tpg->tpg_port_count));
1570 #undef MSG
1571 		goto out;
1572 	}
1573 
1574 	pr_debug("Removing I_T Nexus to Initiator Port: %s\n",
1575 			tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1576 	/*
1577 	 * Release the SCSI I_T Nexus to the emulated vHost Target Port
1578 	 */
1579 	target_remove_session(se_sess);
1580 	tpg->tpg_nexus = NULL;
1581 
1582 	kfree(tv_nexus);
1583 	ret = 0;
1584 out:
1585 	mutex_unlock(&tpg->tpg_mutex);
1586 	return ret;
1587 }
1588 
1589 static ssize_t tcm_usbg_tpg_nexus_store(struct config_item *item,
1590 		const char *page, size_t count)
1591 {
1592 	struct se_portal_group *se_tpg = to_tpg(item);
1593 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1594 	unsigned char i_port[USBG_NAMELEN], *ptr;
1595 	int ret;
1596 
1597 	if (!strncmp(page, "NULL", 4)) {
1598 		ret = tcm_usbg_drop_nexus(tpg);
1599 		return (!ret) ? count : ret;
1600 	}
1601 	if (strlen(page) >= USBG_NAMELEN) {
1602 
1603 #define NEXUS_STORE_MSG "Emulated NAA Sas Address: %s, exceeds max: %d\n"
1604 		pr_err(NEXUS_STORE_MSG, page, USBG_NAMELEN);
1605 #undef NEXUS_STORE_MSG
1606 		return -EINVAL;
1607 	}
1608 	snprintf(i_port, USBG_NAMELEN, "%s", page);
1609 
1610 	ptr = strstr(i_port, "naa.");
1611 	if (!ptr) {
1612 		pr_err("Missing 'naa.' prefix\n");
1613 		return -EINVAL;
1614 	}
1615 
1616 	if (i_port[strlen(i_port) - 1] == '\n')
1617 		i_port[strlen(i_port) - 1] = '\0';
1618 
1619 	ret = tcm_usbg_make_nexus(tpg, &i_port[0]);
1620 	if (ret < 0)
1621 		return ret;
1622 	return count;
1623 }
1624 
1625 CONFIGFS_ATTR(tcm_usbg_tpg_, nexus);
1626 
1627 static struct configfs_attribute *usbg_base_attrs[] = {
1628 	&tcm_usbg_tpg_attr_nexus,
1629 	NULL,
1630 };
1631 
1632 static int usbg_port_link(struct se_portal_group *se_tpg, struct se_lun *lun)
1633 {
1634 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1635 
1636 	atomic_inc(&tpg->tpg_port_count);
1637 	smp_mb__after_atomic();
1638 	return 0;
1639 }
1640 
1641 static void usbg_port_unlink(struct se_portal_group *se_tpg,
1642 		struct se_lun *se_lun)
1643 {
1644 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1645 
1646 	atomic_dec(&tpg->tpg_port_count);
1647 	smp_mb__after_atomic();
1648 }
1649 
1650 static int usbg_check_stop_free(struct se_cmd *se_cmd)
1651 {
1652 	return target_put_sess_cmd(se_cmd);
1653 }
1654 
1655 static const struct target_core_fabric_ops usbg_ops = {
1656 	.module				= THIS_MODULE,
1657 	.fabric_name			= "usb_gadget",
1658 	.tpg_get_wwn			= usbg_get_fabric_wwn,
1659 	.tpg_get_tag			= usbg_get_tag,
1660 	.tpg_check_demo_mode		= usbg_check_true,
1661 	.release_cmd			= usbg_release_cmd,
1662 	.sess_get_initiator_sid		= NULL,
1663 	.write_pending			= usbg_send_write_request,
1664 	.queue_data_in			= usbg_send_read_response,
1665 	.queue_status			= usbg_send_status_response,
1666 	.queue_tm_rsp			= usbg_queue_tm_rsp,
1667 	.aborted_task			= usbg_aborted_task,
1668 	.check_stop_free		= usbg_check_stop_free,
1669 
1670 	.fabric_make_wwn		= usbg_make_tport,
1671 	.fabric_drop_wwn		= usbg_drop_tport,
1672 	.fabric_make_tpg		= usbg_make_tpg,
1673 	.fabric_enable_tpg		= usbg_enable_tpg,
1674 	.fabric_drop_tpg		= usbg_drop_tpg,
1675 	.fabric_post_link		= usbg_port_link,
1676 	.fabric_pre_unlink		= usbg_port_unlink,
1677 	.fabric_init_nodeacl		= usbg_init_nodeacl,
1678 
1679 	.tfc_wwn_attrs			= usbg_wwn_attrs,
1680 	.tfc_tpg_base_attrs		= usbg_base_attrs,
1681 
1682 	.default_submit_type		= TARGET_DIRECT_SUBMIT,
1683 	.direct_submit_supp		= 1,
1684 };
1685 
1686 /* Start gadget.c code */
1687 
1688 static struct usb_interface_descriptor bot_intf_desc = {
1689 	.bLength =              sizeof(bot_intf_desc),
1690 	.bDescriptorType =      USB_DT_INTERFACE,
1691 	.bNumEndpoints =        2,
1692 	.bAlternateSetting =	USB_G_ALT_INT_BBB,
1693 	.bInterfaceClass =      USB_CLASS_MASS_STORAGE,
1694 	.bInterfaceSubClass =   USB_SC_SCSI,
1695 	.bInterfaceProtocol =   USB_PR_BULK,
1696 };
1697 
1698 static struct usb_interface_descriptor uasp_intf_desc = {
1699 	.bLength =		sizeof(uasp_intf_desc),
1700 	.bDescriptorType =	USB_DT_INTERFACE,
1701 	.bNumEndpoints =	4,
1702 	.bAlternateSetting =	USB_G_ALT_INT_UAS,
1703 	.bInterfaceClass =	USB_CLASS_MASS_STORAGE,
1704 	.bInterfaceSubClass =	USB_SC_SCSI,
1705 	.bInterfaceProtocol =	USB_PR_UAS,
1706 };
1707 
1708 static struct usb_endpoint_descriptor uasp_bi_desc = {
1709 	.bLength =		USB_DT_ENDPOINT_SIZE,
1710 	.bDescriptorType =	USB_DT_ENDPOINT,
1711 	.bEndpointAddress =	USB_DIR_IN,
1712 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1713 	.wMaxPacketSize =	cpu_to_le16(512),
1714 };
1715 
1716 static struct usb_endpoint_descriptor uasp_fs_bi_desc = {
1717 	.bLength =		USB_DT_ENDPOINT_SIZE,
1718 	.bDescriptorType =	USB_DT_ENDPOINT,
1719 	.bEndpointAddress =	USB_DIR_IN,
1720 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1721 };
1722 
1723 static struct usb_pipe_usage_descriptor uasp_bi_pipe_desc = {
1724 	.bLength =		sizeof(uasp_bi_pipe_desc),
1725 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1726 	.bPipeID =		DATA_IN_PIPE_ID,
1727 };
1728 
1729 static struct usb_endpoint_descriptor uasp_ss_bi_desc = {
1730 	.bLength =		USB_DT_ENDPOINT_SIZE,
1731 	.bDescriptorType =	USB_DT_ENDPOINT,
1732 	.bEndpointAddress =	USB_DIR_IN,
1733 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1734 	.wMaxPacketSize =	cpu_to_le16(1024),
1735 };
1736 
1737 static struct usb_ss_ep_comp_descriptor uasp_bi_ep_comp_desc = {
1738 	.bLength =		sizeof(uasp_bi_ep_comp_desc),
1739 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1740 	.bMaxBurst =		15,
1741 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1742 	.wBytesPerInterval =	0,
1743 };
1744 
1745 static struct usb_ss_ep_comp_descriptor bot_bi_ep_comp_desc = {
1746 	.bLength =		sizeof(bot_bi_ep_comp_desc),
1747 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1748 	.bMaxBurst =		15,
1749 };
1750 
1751 static struct usb_endpoint_descriptor uasp_bo_desc = {
1752 	.bLength =		USB_DT_ENDPOINT_SIZE,
1753 	.bDescriptorType =	USB_DT_ENDPOINT,
1754 	.bEndpointAddress =	USB_DIR_OUT,
1755 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1756 	.wMaxPacketSize =	cpu_to_le16(512),
1757 };
1758 
1759 static struct usb_endpoint_descriptor uasp_fs_bo_desc = {
1760 	.bLength =		USB_DT_ENDPOINT_SIZE,
1761 	.bDescriptorType =	USB_DT_ENDPOINT,
1762 	.bEndpointAddress =	USB_DIR_OUT,
1763 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1764 };
1765 
1766 static struct usb_pipe_usage_descriptor uasp_bo_pipe_desc = {
1767 	.bLength =		sizeof(uasp_bo_pipe_desc),
1768 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1769 	.bPipeID =		DATA_OUT_PIPE_ID,
1770 };
1771 
1772 static struct usb_endpoint_descriptor uasp_ss_bo_desc = {
1773 	.bLength =		USB_DT_ENDPOINT_SIZE,
1774 	.bDescriptorType =	USB_DT_ENDPOINT,
1775 	.bEndpointAddress =	USB_DIR_OUT,
1776 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1777 	.wMaxPacketSize =	cpu_to_le16(0x400),
1778 };
1779 
1780 static struct usb_ss_ep_comp_descriptor uasp_bo_ep_comp_desc = {
1781 	.bLength =		sizeof(uasp_bo_ep_comp_desc),
1782 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1783 	.bMaxBurst =		15,
1784 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1785 };
1786 
1787 static struct usb_ss_ep_comp_descriptor bot_bo_ep_comp_desc = {
1788 	.bLength =		sizeof(bot_bo_ep_comp_desc),
1789 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1790 	.bMaxBurst =		15,
1791 };
1792 
1793 static struct usb_endpoint_descriptor uasp_status_desc = {
1794 	.bLength =		USB_DT_ENDPOINT_SIZE,
1795 	.bDescriptorType =	USB_DT_ENDPOINT,
1796 	.bEndpointAddress =	USB_DIR_IN,
1797 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1798 	.wMaxPacketSize =	cpu_to_le16(512),
1799 };
1800 
1801 static struct usb_endpoint_descriptor uasp_fs_status_desc = {
1802 	.bLength =		USB_DT_ENDPOINT_SIZE,
1803 	.bDescriptorType =	USB_DT_ENDPOINT,
1804 	.bEndpointAddress =	USB_DIR_IN,
1805 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1806 };
1807 
1808 static struct usb_pipe_usage_descriptor uasp_status_pipe_desc = {
1809 	.bLength =		sizeof(uasp_status_pipe_desc),
1810 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1811 	.bPipeID =		STATUS_PIPE_ID,
1812 };
1813 
1814 static struct usb_endpoint_descriptor uasp_ss_status_desc = {
1815 	.bLength =		USB_DT_ENDPOINT_SIZE,
1816 	.bDescriptorType =	USB_DT_ENDPOINT,
1817 	.bEndpointAddress =	USB_DIR_IN,
1818 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1819 	.wMaxPacketSize =	cpu_to_le16(1024),
1820 };
1821 
1822 static struct usb_ss_ep_comp_descriptor uasp_status_in_ep_comp_desc = {
1823 	.bLength =		sizeof(uasp_status_in_ep_comp_desc),
1824 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1825 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1826 };
1827 
1828 static struct usb_endpoint_descriptor uasp_cmd_desc = {
1829 	.bLength =		USB_DT_ENDPOINT_SIZE,
1830 	.bDescriptorType =	USB_DT_ENDPOINT,
1831 	.bEndpointAddress =	USB_DIR_OUT,
1832 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1833 	.wMaxPacketSize =	cpu_to_le16(512),
1834 };
1835 
1836 static struct usb_endpoint_descriptor uasp_fs_cmd_desc = {
1837 	.bLength =		USB_DT_ENDPOINT_SIZE,
1838 	.bDescriptorType =	USB_DT_ENDPOINT,
1839 	.bEndpointAddress =	USB_DIR_OUT,
1840 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1841 };
1842 
1843 static struct usb_pipe_usage_descriptor uasp_cmd_pipe_desc = {
1844 	.bLength =		sizeof(uasp_cmd_pipe_desc),
1845 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1846 	.bPipeID =		CMD_PIPE_ID,
1847 };
1848 
1849 static struct usb_endpoint_descriptor uasp_ss_cmd_desc = {
1850 	.bLength =		USB_DT_ENDPOINT_SIZE,
1851 	.bDescriptorType =	USB_DT_ENDPOINT,
1852 	.bEndpointAddress =	USB_DIR_OUT,
1853 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1854 	.wMaxPacketSize =	cpu_to_le16(1024),
1855 };
1856 
1857 static struct usb_ss_ep_comp_descriptor uasp_cmd_comp_desc = {
1858 	.bLength =		sizeof(uasp_cmd_comp_desc),
1859 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1860 };
1861 
1862 static struct usb_descriptor_header *uasp_fs_function_desc[] = {
1863 	(struct usb_descriptor_header *) &bot_intf_desc,
1864 	(struct usb_descriptor_header *) &uasp_fs_bi_desc,
1865 	(struct usb_descriptor_header *) &uasp_fs_bo_desc,
1866 
1867 	(struct usb_descriptor_header *) &uasp_intf_desc,
1868 	(struct usb_descriptor_header *) &uasp_fs_bi_desc,
1869 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1870 	(struct usb_descriptor_header *) &uasp_fs_bo_desc,
1871 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1872 	(struct usb_descriptor_header *) &uasp_fs_status_desc,
1873 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1874 	(struct usb_descriptor_header *) &uasp_fs_cmd_desc,
1875 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1876 	NULL,
1877 };
1878 
1879 static struct usb_descriptor_header *uasp_hs_function_desc[] = {
1880 	(struct usb_descriptor_header *) &bot_intf_desc,
1881 	(struct usb_descriptor_header *) &uasp_bi_desc,
1882 	(struct usb_descriptor_header *) &uasp_bo_desc,
1883 
1884 	(struct usb_descriptor_header *) &uasp_intf_desc,
1885 	(struct usb_descriptor_header *) &uasp_bi_desc,
1886 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1887 	(struct usb_descriptor_header *) &uasp_bo_desc,
1888 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1889 	(struct usb_descriptor_header *) &uasp_status_desc,
1890 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1891 	(struct usb_descriptor_header *) &uasp_cmd_desc,
1892 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1893 	NULL,
1894 };
1895 
1896 static struct usb_descriptor_header *uasp_ss_function_desc[] = {
1897 	(struct usb_descriptor_header *) &bot_intf_desc,
1898 	(struct usb_descriptor_header *) &uasp_ss_bi_desc,
1899 	(struct usb_descriptor_header *) &bot_bi_ep_comp_desc,
1900 	(struct usb_descriptor_header *) &uasp_ss_bo_desc,
1901 	(struct usb_descriptor_header *) &bot_bo_ep_comp_desc,
1902 
1903 	(struct usb_descriptor_header *) &uasp_intf_desc,
1904 	(struct usb_descriptor_header *) &uasp_ss_bi_desc,
1905 	(struct usb_descriptor_header *) &uasp_bi_ep_comp_desc,
1906 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1907 	(struct usb_descriptor_header *) &uasp_ss_bo_desc,
1908 	(struct usb_descriptor_header *) &uasp_bo_ep_comp_desc,
1909 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1910 	(struct usb_descriptor_header *) &uasp_ss_status_desc,
1911 	(struct usb_descriptor_header *) &uasp_status_in_ep_comp_desc,
1912 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1913 	(struct usb_descriptor_header *) &uasp_ss_cmd_desc,
1914 	(struct usb_descriptor_header *) &uasp_cmd_comp_desc,
1915 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1916 	NULL,
1917 };
1918 
1919 static struct usb_string	tcm_us_strings[] = {
1920 	[USB_G_STR_INT_UAS].s		= "USB Attached SCSI",
1921 	[USB_G_STR_INT_BBB].s		= "Bulk Only Transport",
1922 	{ },
1923 };
1924 
1925 static struct usb_gadget_strings tcm_stringtab = {
1926 	.language = 0x0409,
1927 	.strings = tcm_us_strings,
1928 };
1929 
1930 static struct usb_gadget_strings *tcm_strings[] = {
1931 	&tcm_stringtab,
1932 	NULL,
1933 };
1934 
1935 static int tcm_bind(struct usb_configuration *c, struct usb_function *f)
1936 {
1937 	struct f_uas		*fu = to_f_uas(f);
1938 	struct usb_string	*us;
1939 	struct usb_gadget	*gadget = c->cdev->gadget;
1940 	struct usb_ep		*ep;
1941 	struct f_tcm_opts	*opts;
1942 	int			iface;
1943 	int			ret;
1944 
1945 	opts = container_of(f->fi, struct f_tcm_opts, func_inst);
1946 
1947 	mutex_lock(&opts->dep_lock);
1948 	if (!opts->can_attach) {
1949 		mutex_unlock(&opts->dep_lock);
1950 		return -ENODEV;
1951 	}
1952 	mutex_unlock(&opts->dep_lock);
1953 	us = usb_gstrings_attach(c->cdev, tcm_strings,
1954 		ARRAY_SIZE(tcm_us_strings));
1955 	if (IS_ERR(us))
1956 		return PTR_ERR(us);
1957 	bot_intf_desc.iInterface = us[USB_G_STR_INT_BBB].id;
1958 	uasp_intf_desc.iInterface = us[USB_G_STR_INT_UAS].id;
1959 
1960 	iface = usb_interface_id(c, f);
1961 	if (iface < 0)
1962 		return iface;
1963 
1964 	bot_intf_desc.bInterfaceNumber = iface;
1965 	uasp_intf_desc.bInterfaceNumber = iface;
1966 	fu->iface = iface;
1967 	ep = usb_ep_autoconfig(gadget, &uasp_fs_bi_desc);
1968 	if (!ep)
1969 		goto ep_fail;
1970 
1971 	fu->ep_in = ep;
1972 
1973 	ep = usb_ep_autoconfig(gadget, &uasp_fs_bo_desc);
1974 	if (!ep)
1975 		goto ep_fail;
1976 	fu->ep_out = ep;
1977 
1978 	ep = usb_ep_autoconfig(gadget, &uasp_fs_status_desc);
1979 	if (!ep)
1980 		goto ep_fail;
1981 	fu->ep_status = ep;
1982 
1983 	ep = usb_ep_autoconfig(gadget, &uasp_fs_cmd_desc);
1984 	if (!ep)
1985 		goto ep_fail;
1986 	fu->ep_cmd = ep;
1987 
1988 	/* Assume endpoint addresses are the same for both speeds */
1989 	uasp_bi_desc.bEndpointAddress =	uasp_fs_bi_desc.bEndpointAddress;
1990 	uasp_bo_desc.bEndpointAddress = uasp_fs_bo_desc.bEndpointAddress;
1991 	uasp_status_desc.bEndpointAddress =
1992 		uasp_fs_status_desc.bEndpointAddress;
1993 	uasp_cmd_desc.bEndpointAddress = uasp_fs_cmd_desc.bEndpointAddress;
1994 
1995 	uasp_ss_bi_desc.bEndpointAddress = uasp_fs_bi_desc.bEndpointAddress;
1996 	uasp_ss_bo_desc.bEndpointAddress = uasp_fs_bo_desc.bEndpointAddress;
1997 	uasp_ss_status_desc.bEndpointAddress =
1998 		uasp_fs_status_desc.bEndpointAddress;
1999 	uasp_ss_cmd_desc.bEndpointAddress = uasp_fs_cmd_desc.bEndpointAddress;
2000 
2001 	ret = usb_assign_descriptors(f, uasp_fs_function_desc,
2002 			uasp_hs_function_desc, uasp_ss_function_desc,
2003 			uasp_ss_function_desc);
2004 	if (ret)
2005 		goto ep_fail;
2006 
2007 	return 0;
2008 ep_fail:
2009 	pr_err("Can't claim all required eps\n");
2010 
2011 	return -ENOTSUPP;
2012 }
2013 
2014 struct guas_setup_wq {
2015 	struct work_struct work;
2016 	struct f_uas *fu;
2017 	unsigned int alt;
2018 };
2019 
2020 static void tcm_delayed_set_alt(struct work_struct *wq)
2021 {
2022 	struct guas_setup_wq *work = container_of(wq, struct guas_setup_wq,
2023 			work);
2024 	struct f_uas *fu = work->fu;
2025 	int alt = work->alt;
2026 
2027 	kfree(work);
2028 
2029 	if (fu->flags & USBG_IS_BOT)
2030 		bot_cleanup_old_alt(fu);
2031 	if (fu->flags & USBG_IS_UAS)
2032 		uasp_cleanup_old_alt(fu);
2033 
2034 	if (alt == USB_G_ALT_INT_BBB)
2035 		bot_set_alt(fu);
2036 	else if (alt == USB_G_ALT_INT_UAS)
2037 		uasp_set_alt(fu);
2038 	usb_composite_setup_continue(fu->function.config->cdev);
2039 }
2040 
2041 static int tcm_get_alt(struct usb_function *f, unsigned intf)
2042 {
2043 	struct f_uas *fu = to_f_uas(f);
2044 
2045 	if (fu->iface != intf)
2046 		return -EOPNOTSUPP;
2047 
2048 	if (fu->flags & USBG_IS_BOT)
2049 		return USB_G_ALT_INT_BBB;
2050 	else if (fu->flags & USBG_IS_UAS)
2051 		return USB_G_ALT_INT_UAS;
2052 
2053 	return -EOPNOTSUPP;
2054 }
2055 
2056 static int tcm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2057 {
2058 	struct f_uas *fu = to_f_uas(f);
2059 
2060 	if (fu->iface != intf)
2061 		return -EOPNOTSUPP;
2062 
2063 	if ((alt == USB_G_ALT_INT_BBB) || (alt == USB_G_ALT_INT_UAS)) {
2064 		struct guas_setup_wq *work;
2065 
2066 		work = kmalloc(sizeof(*work), GFP_ATOMIC);
2067 		if (!work)
2068 			return -ENOMEM;
2069 		INIT_WORK(&work->work, tcm_delayed_set_alt);
2070 		work->fu = fu;
2071 		work->alt = alt;
2072 		schedule_work(&work->work);
2073 		return USB_GADGET_DELAYED_STATUS;
2074 	}
2075 	return -EOPNOTSUPP;
2076 }
2077 
2078 static void tcm_disable(struct usb_function *f)
2079 {
2080 	struct f_uas *fu = to_f_uas(f);
2081 
2082 	if (fu->flags & USBG_IS_UAS)
2083 		uasp_cleanup_old_alt(fu);
2084 	else if (fu->flags & USBG_IS_BOT)
2085 		bot_cleanup_old_alt(fu);
2086 	fu->flags = 0;
2087 }
2088 
2089 static int tcm_setup(struct usb_function *f,
2090 		const struct usb_ctrlrequest *ctrl)
2091 {
2092 	struct f_uas *fu = to_f_uas(f);
2093 
2094 	if (!(fu->flags & USBG_IS_BOT))
2095 		return -EOPNOTSUPP;
2096 
2097 	return usbg_bot_setup(f, ctrl);
2098 }
2099 
2100 static inline struct f_tcm_opts *to_f_tcm_opts(struct config_item *item)
2101 {
2102 	return container_of(to_config_group(item), struct f_tcm_opts,
2103 		func_inst.group);
2104 }
2105 
2106 static void tcm_attr_release(struct config_item *item)
2107 {
2108 	struct f_tcm_opts *opts = to_f_tcm_opts(item);
2109 
2110 	usb_put_function_instance(&opts->func_inst);
2111 }
2112 
2113 static struct configfs_item_operations tcm_item_ops = {
2114 	.release		= tcm_attr_release,
2115 };
2116 
2117 static const struct config_item_type tcm_func_type = {
2118 	.ct_item_ops	= &tcm_item_ops,
2119 	.ct_owner	= THIS_MODULE,
2120 };
2121 
2122 static void tcm_free_inst(struct usb_function_instance *f)
2123 {
2124 	struct f_tcm_opts *opts;
2125 	unsigned i;
2126 
2127 	opts = container_of(f, struct f_tcm_opts, func_inst);
2128 
2129 	mutex_lock(&tpg_instances_lock);
2130 	for (i = 0; i < TPG_INSTANCES; ++i)
2131 		if (tpg_instances[i].func_inst == f)
2132 			break;
2133 	if (i < TPG_INSTANCES)
2134 		tpg_instances[i].func_inst = NULL;
2135 	mutex_unlock(&tpg_instances_lock);
2136 
2137 	kfree(opts);
2138 }
2139 
2140 static int tcm_register_callback(struct usb_function_instance *f)
2141 {
2142 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2143 
2144 	mutex_lock(&opts->dep_lock);
2145 	opts->can_attach = true;
2146 	mutex_unlock(&opts->dep_lock);
2147 
2148 	return 0;
2149 }
2150 
2151 static void tcm_unregister_callback(struct usb_function_instance *f)
2152 {
2153 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2154 
2155 	mutex_lock(&opts->dep_lock);
2156 	unregister_gadget_item(opts->
2157 		func_inst.group.cg_item.ci_parent->ci_parent);
2158 	opts->can_attach = false;
2159 	mutex_unlock(&opts->dep_lock);
2160 }
2161 
2162 static int usbg_attach(struct usbg_tpg *tpg)
2163 {
2164 	struct usb_function_instance *f = tpg->fi;
2165 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2166 
2167 	if (opts->tcm_register_callback)
2168 		return opts->tcm_register_callback(f);
2169 
2170 	return 0;
2171 }
2172 
2173 static void usbg_detach(struct usbg_tpg *tpg)
2174 {
2175 	struct usb_function_instance *f = tpg->fi;
2176 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2177 
2178 	if (opts->tcm_unregister_callback)
2179 		opts->tcm_unregister_callback(f);
2180 }
2181 
2182 static int tcm_set_name(struct usb_function_instance *f, const char *name)
2183 {
2184 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2185 
2186 	pr_debug("tcm: Activating %s\n", name);
2187 
2188 	mutex_lock(&opts->dep_lock);
2189 	opts->ready = true;
2190 	mutex_unlock(&opts->dep_lock);
2191 
2192 	return 0;
2193 }
2194 
2195 static struct usb_function_instance *tcm_alloc_inst(void)
2196 {
2197 	struct f_tcm_opts *opts;
2198 	int i;
2199 
2200 
2201 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2202 	if (!opts)
2203 		return ERR_PTR(-ENOMEM);
2204 
2205 	mutex_lock(&tpg_instances_lock);
2206 	for (i = 0; i < TPG_INSTANCES; ++i)
2207 		if (!tpg_instances[i].func_inst)
2208 			break;
2209 
2210 	if (i == TPG_INSTANCES) {
2211 		mutex_unlock(&tpg_instances_lock);
2212 		kfree(opts);
2213 		return ERR_PTR(-EBUSY);
2214 	}
2215 	tpg_instances[i].func_inst = &opts->func_inst;
2216 	mutex_unlock(&tpg_instances_lock);
2217 
2218 	mutex_init(&opts->dep_lock);
2219 	opts->func_inst.set_inst_name = tcm_set_name;
2220 	opts->func_inst.free_func_inst = tcm_free_inst;
2221 	opts->tcm_register_callback = tcm_register_callback;
2222 	opts->tcm_unregister_callback = tcm_unregister_callback;
2223 
2224 	config_group_init_type_name(&opts->func_inst.group, "",
2225 			&tcm_func_type);
2226 
2227 	return &opts->func_inst;
2228 }
2229 
2230 static void tcm_free(struct usb_function *f)
2231 {
2232 	struct f_uas *tcm = to_f_uas(f);
2233 
2234 	kfree(tcm);
2235 }
2236 
2237 static void tcm_unbind(struct usb_configuration *c, struct usb_function *f)
2238 {
2239 	usb_free_all_descriptors(f);
2240 }
2241 
2242 static struct usb_function *tcm_alloc(struct usb_function_instance *fi)
2243 {
2244 	struct f_uas *fu;
2245 	unsigned i;
2246 
2247 	mutex_lock(&tpg_instances_lock);
2248 	for (i = 0; i < TPG_INSTANCES; ++i)
2249 		if (tpg_instances[i].func_inst == fi)
2250 			break;
2251 	if (i == TPG_INSTANCES) {
2252 		mutex_unlock(&tpg_instances_lock);
2253 		return ERR_PTR(-ENODEV);
2254 	}
2255 
2256 	fu = kzalloc(sizeof(*fu), GFP_KERNEL);
2257 	if (!fu) {
2258 		mutex_unlock(&tpg_instances_lock);
2259 		return ERR_PTR(-ENOMEM);
2260 	}
2261 
2262 	fu->function.name = "Target Function";
2263 	fu->function.bind = tcm_bind;
2264 	fu->function.unbind = tcm_unbind;
2265 	fu->function.set_alt = tcm_set_alt;
2266 	fu->function.get_alt = tcm_get_alt;
2267 	fu->function.setup = tcm_setup;
2268 	fu->function.disable = tcm_disable;
2269 	fu->function.free_func = tcm_free;
2270 	fu->tpg = tpg_instances[i].tpg;
2271 	mutex_unlock(&tpg_instances_lock);
2272 
2273 	return &fu->function;
2274 }
2275 
2276 DECLARE_USB_FUNCTION(tcm, tcm_alloc_inst, tcm_alloc);
2277 
2278 static int __init tcm_init(void)
2279 {
2280 	int ret;
2281 
2282 	ret = usb_function_register(&tcmusb_func);
2283 	if (ret)
2284 		return ret;
2285 
2286 	ret = target_register_template(&usbg_ops);
2287 	if (ret)
2288 		usb_function_unregister(&tcmusb_func);
2289 
2290 	return ret;
2291 }
2292 module_init(tcm_init);
2293 
2294 static void __exit tcm_exit(void)
2295 {
2296 	target_unregister_template(&usbg_ops);
2297 	usb_function_unregister(&tcmusb_func);
2298 }
2299 module_exit(tcm_exit);
2300 
2301 MODULE_DESCRIPTION("Target based USB-Gadget");
2302 MODULE_LICENSE("GPL");
2303 MODULE_AUTHOR("Sebastian Andrzej Siewior");
2304