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