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