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