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 				cmd->unpacked_lun);
1057 		goto out;
1058 	}
1059 
1060 	if (target_submit_cmd(se_cmd, tv_nexus->tvn_se_sess, cmd->cmd_buf,
1061 			      cmd->sense_iu.sense, cmd->unpacked_lun, 0,
1062 			      cmd->prio_attr, dir, flags) < 0)
1063 		goto out;
1064 
1065 	return;
1066 
1067 out:
1068 	transport_send_check_condition_and_sense(se_cmd,
1069 			TCM_UNSUPPORTED_SCSI_OPCODE, 1);
1070 	transport_generic_free_cmd(&cmd->se_cmd, 0);
1071 }
1072 
1073 static struct usbg_cmd *usbg_get_cmd(struct f_uas *fu,
1074 		struct tcm_usbg_nexus *tv_nexus, u32 scsi_tag)
1075 {
1076 	struct se_session *se_sess = tv_nexus->tvn_se_sess;
1077 	struct usbg_cmd *cmd;
1078 	int tag, cpu;
1079 
1080 	tag = sbitmap_queue_get(&se_sess->sess_tag_pool, &cpu);
1081 	if (tag < 0)
1082 		return ERR_PTR(-ENOMEM);
1083 
1084 	cmd = &((struct usbg_cmd *)se_sess->sess_cmd_map)[tag];
1085 	memset(cmd, 0, sizeof(*cmd));
1086 	cmd->se_cmd.map_tag = tag;
1087 	cmd->se_cmd.map_cpu = cpu;
1088 	cmd->se_cmd.tag = cmd->tag = scsi_tag;
1089 	cmd->fu = fu;
1090 
1091 	return cmd;
1092 }
1093 
1094 static void usbg_release_cmd(struct se_cmd *);
1095 
1096 static int usbg_submit_command(struct f_uas *fu,
1097 		void *cmdbuf, unsigned int len)
1098 {
1099 	struct command_iu *cmd_iu = cmdbuf;
1100 	struct usbg_cmd *cmd;
1101 	struct usbg_tpg *tpg = fu->tpg;
1102 	struct tcm_usbg_nexus *tv_nexus;
1103 	u32 cmd_len;
1104 	u16 scsi_tag;
1105 
1106 	if (cmd_iu->iu_id != IU_ID_COMMAND) {
1107 		pr_err("Unsupported type %d\n", cmd_iu->iu_id);
1108 		return -EINVAL;
1109 	}
1110 
1111 	tv_nexus = tpg->tpg_nexus;
1112 	if (!tv_nexus) {
1113 		pr_err("Missing nexus, ignoring command\n");
1114 		return -EINVAL;
1115 	}
1116 
1117 	cmd_len = (cmd_iu->len & ~0x3) + 16;
1118 	if (cmd_len > USBG_MAX_CMD)
1119 		return -EINVAL;
1120 
1121 	scsi_tag = be16_to_cpup(&cmd_iu->tag);
1122 	cmd = usbg_get_cmd(fu, tv_nexus, scsi_tag);
1123 	if (IS_ERR(cmd)) {
1124 		pr_err("usbg_get_cmd failed\n");
1125 		return -ENOMEM;
1126 	}
1127 	memcpy(cmd->cmd_buf, cmd_iu->cdb, cmd_len);
1128 
1129 	if (fu->flags & USBG_USE_STREAMS) {
1130 		if (cmd->tag > UASP_SS_EP_COMP_NUM_STREAMS)
1131 			goto err;
1132 		if (!cmd->tag)
1133 			cmd->stream = &fu->stream[0];
1134 		else
1135 			cmd->stream = &fu->stream[cmd->tag - 1];
1136 	} else {
1137 		cmd->stream = &fu->stream[0];
1138 	}
1139 
1140 	switch (cmd_iu->prio_attr & 0x7) {
1141 	case UAS_HEAD_TAG:
1142 		cmd->prio_attr = TCM_HEAD_TAG;
1143 		break;
1144 	case UAS_ORDERED_TAG:
1145 		cmd->prio_attr = TCM_ORDERED_TAG;
1146 		break;
1147 	case UAS_ACA:
1148 		cmd->prio_attr = TCM_ACA_TAG;
1149 		break;
1150 	default:
1151 		pr_debug_once("Unsupported prio_attr: %02x.\n",
1152 				cmd_iu->prio_attr);
1153 		fallthrough;
1154 	case UAS_SIMPLE_TAG:
1155 		cmd->prio_attr = TCM_SIMPLE_TAG;
1156 		break;
1157 	}
1158 
1159 	cmd->unpacked_lun = scsilun_to_int(&cmd_iu->lun);
1160 
1161 	INIT_WORK(&cmd->work, usbg_cmd_work);
1162 	queue_work(tpg->workqueue, &cmd->work);
1163 
1164 	return 0;
1165 err:
1166 	usbg_release_cmd(&cmd->se_cmd);
1167 	return -EINVAL;
1168 }
1169 
1170 static void bot_cmd_work(struct work_struct *work)
1171 {
1172 	struct usbg_cmd *cmd = container_of(work, struct usbg_cmd, work);
1173 	struct se_cmd *se_cmd;
1174 	struct tcm_usbg_nexus *tv_nexus;
1175 	struct usbg_tpg *tpg;
1176 	int dir;
1177 
1178 	se_cmd = &cmd->se_cmd;
1179 	tpg = cmd->fu->tpg;
1180 	tv_nexus = tpg->tpg_nexus;
1181 	dir = get_cmd_dir(cmd->cmd_buf);
1182 	if (dir < 0) {
1183 		transport_init_se_cmd(se_cmd,
1184 				tv_nexus->tvn_se_sess->se_tpg->se_tpg_tfo,
1185 				tv_nexus->tvn_se_sess, cmd->data_len, DMA_NONE,
1186 				cmd->prio_attr, cmd->sense_iu.sense,
1187 				cmd->unpacked_lun);
1188 		goto out;
1189 	}
1190 
1191 	if (target_submit_cmd(se_cmd, tv_nexus->tvn_se_sess,
1192 			cmd->cmd_buf, cmd->sense_iu.sense, cmd->unpacked_lun,
1193 			cmd->data_len, cmd->prio_attr, dir, 0) < 0)
1194 		goto out;
1195 
1196 	return;
1197 
1198 out:
1199 	transport_send_check_condition_and_sense(se_cmd,
1200 				TCM_UNSUPPORTED_SCSI_OPCODE, 1);
1201 	transport_generic_free_cmd(&cmd->se_cmd, 0);
1202 }
1203 
1204 static int bot_submit_command(struct f_uas *fu,
1205 		void *cmdbuf, unsigned int len)
1206 {
1207 	struct bulk_cb_wrap *cbw = cmdbuf;
1208 	struct usbg_cmd *cmd;
1209 	struct usbg_tpg *tpg = fu->tpg;
1210 	struct tcm_usbg_nexus *tv_nexus;
1211 	u32 cmd_len;
1212 
1213 	if (cbw->Signature != cpu_to_le32(US_BULK_CB_SIGN)) {
1214 		pr_err("Wrong signature on CBW\n");
1215 		return -EINVAL;
1216 	}
1217 	if (len != 31) {
1218 		pr_err("Wrong length for CBW\n");
1219 		return -EINVAL;
1220 	}
1221 
1222 	cmd_len = cbw->Length;
1223 	if (cmd_len < 1 || cmd_len > 16)
1224 		return -EINVAL;
1225 
1226 	tv_nexus = tpg->tpg_nexus;
1227 	if (!tv_nexus) {
1228 		pr_err("Missing nexus, ignoring command\n");
1229 		return -ENODEV;
1230 	}
1231 
1232 	cmd = usbg_get_cmd(fu, tv_nexus, cbw->Tag);
1233 	if (IS_ERR(cmd)) {
1234 		pr_err("usbg_get_cmd failed\n");
1235 		return -ENOMEM;
1236 	}
1237 	memcpy(cmd->cmd_buf, cbw->CDB, cmd_len);
1238 
1239 	cmd->bot_tag = cbw->Tag;
1240 	cmd->prio_attr = TCM_SIMPLE_TAG;
1241 	cmd->unpacked_lun = cbw->Lun;
1242 	cmd->is_read = cbw->Flags & US_BULK_FLAG_IN ? 1 : 0;
1243 	cmd->data_len = le32_to_cpu(cbw->DataTransferLength);
1244 	cmd->se_cmd.tag = le32_to_cpu(cmd->bot_tag);
1245 
1246 	INIT_WORK(&cmd->work, bot_cmd_work);
1247 	queue_work(tpg->workqueue, &cmd->work);
1248 
1249 	return 0;
1250 }
1251 
1252 /* Start fabric.c code */
1253 
1254 static int usbg_check_true(struct se_portal_group *se_tpg)
1255 {
1256 	return 1;
1257 }
1258 
1259 static int usbg_check_false(struct se_portal_group *se_tpg)
1260 {
1261 	return 0;
1262 }
1263 
1264 static char *usbg_get_fabric_wwn(struct se_portal_group *se_tpg)
1265 {
1266 	struct usbg_tpg *tpg = container_of(se_tpg,
1267 				struct usbg_tpg, se_tpg);
1268 	struct usbg_tport *tport = tpg->tport;
1269 
1270 	return &tport->tport_name[0];
1271 }
1272 
1273 static u16 usbg_get_tag(struct se_portal_group *se_tpg)
1274 {
1275 	struct usbg_tpg *tpg = container_of(se_tpg,
1276 				struct usbg_tpg, se_tpg);
1277 	return tpg->tport_tpgt;
1278 }
1279 
1280 static u32 usbg_tpg_get_inst_index(struct se_portal_group *se_tpg)
1281 {
1282 	return 1;
1283 }
1284 
1285 static void usbg_release_cmd(struct se_cmd *se_cmd)
1286 {
1287 	struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1288 			se_cmd);
1289 	struct se_session *se_sess = se_cmd->se_sess;
1290 
1291 	kfree(cmd->data_buf);
1292 	target_free_tag(se_sess, se_cmd);
1293 }
1294 
1295 static u32 usbg_sess_get_index(struct se_session *se_sess)
1296 {
1297 	return 0;
1298 }
1299 
1300 static void usbg_set_default_node_attrs(struct se_node_acl *nacl)
1301 {
1302 }
1303 
1304 static int usbg_get_cmd_state(struct se_cmd *se_cmd)
1305 {
1306 	return 0;
1307 }
1308 
1309 static void usbg_queue_tm_rsp(struct se_cmd *se_cmd)
1310 {
1311 }
1312 
1313 static void usbg_aborted_task(struct se_cmd *se_cmd)
1314 {
1315 }
1316 
1317 static const char *usbg_check_wwn(const char *name)
1318 {
1319 	const char *n;
1320 	unsigned int len;
1321 
1322 	n = strstr(name, "naa.");
1323 	if (!n)
1324 		return NULL;
1325 	n += 4;
1326 	len = strlen(n);
1327 	if (len == 0 || len > USBG_NAMELEN - 1)
1328 		return NULL;
1329 	return n;
1330 }
1331 
1332 static int usbg_init_nodeacl(struct se_node_acl *se_nacl, const char *name)
1333 {
1334 	if (!usbg_check_wwn(name))
1335 		return -EINVAL;
1336 	return 0;
1337 }
1338 
1339 static struct se_portal_group *usbg_make_tpg(struct se_wwn *wwn,
1340 					     const char *name)
1341 {
1342 	struct usbg_tport *tport = container_of(wwn, struct usbg_tport,
1343 			tport_wwn);
1344 	struct usbg_tpg *tpg;
1345 	unsigned long tpgt;
1346 	int ret;
1347 	struct f_tcm_opts *opts;
1348 	unsigned i;
1349 
1350 	if (strstr(name, "tpgt_") != name)
1351 		return ERR_PTR(-EINVAL);
1352 	if (kstrtoul(name + 5, 0, &tpgt) || tpgt > UINT_MAX)
1353 		return ERR_PTR(-EINVAL);
1354 	ret = -ENODEV;
1355 	mutex_lock(&tpg_instances_lock);
1356 	for (i = 0; i < TPG_INSTANCES; ++i)
1357 		if (tpg_instances[i].func_inst && !tpg_instances[i].tpg)
1358 			break;
1359 	if (i == TPG_INSTANCES)
1360 		goto unlock_inst;
1361 
1362 	opts = container_of(tpg_instances[i].func_inst, struct f_tcm_opts,
1363 		func_inst);
1364 	mutex_lock(&opts->dep_lock);
1365 	if (!opts->ready)
1366 		goto unlock_dep;
1367 
1368 	if (opts->has_dep) {
1369 		if (!try_module_get(opts->dependent))
1370 			goto unlock_dep;
1371 	} else {
1372 		ret = configfs_depend_item_unlocked(
1373 			wwn->wwn_group.cg_subsys,
1374 			&opts->func_inst.group.cg_item);
1375 		if (ret)
1376 			goto unlock_dep;
1377 	}
1378 
1379 	tpg = kzalloc(sizeof(struct usbg_tpg), GFP_KERNEL);
1380 	ret = -ENOMEM;
1381 	if (!tpg)
1382 		goto unref_dep;
1383 	mutex_init(&tpg->tpg_mutex);
1384 	atomic_set(&tpg->tpg_port_count, 0);
1385 	tpg->workqueue = alloc_workqueue("tcm_usb_gadget", 0, 1);
1386 	if (!tpg->workqueue)
1387 		goto free_tpg;
1388 
1389 	tpg->tport = tport;
1390 	tpg->tport_tpgt = tpgt;
1391 
1392 	/*
1393 	 * SPC doesn't assign a protocol identifier for USB-SCSI, so we
1394 	 * pretend to be SAS..
1395 	 */
1396 	ret = core_tpg_register(wwn, &tpg->se_tpg, SCSI_PROTOCOL_SAS);
1397 	if (ret < 0)
1398 		goto free_workqueue;
1399 
1400 	tpg_instances[i].tpg = tpg;
1401 	tpg->fi = tpg_instances[i].func_inst;
1402 	mutex_unlock(&opts->dep_lock);
1403 	mutex_unlock(&tpg_instances_lock);
1404 	return &tpg->se_tpg;
1405 
1406 free_workqueue:
1407 	destroy_workqueue(tpg->workqueue);
1408 free_tpg:
1409 	kfree(tpg);
1410 unref_dep:
1411 	if (opts->has_dep)
1412 		module_put(opts->dependent);
1413 	else
1414 		configfs_undepend_item_unlocked(&opts->func_inst.group.cg_item);
1415 unlock_dep:
1416 	mutex_unlock(&opts->dep_lock);
1417 unlock_inst:
1418 	mutex_unlock(&tpg_instances_lock);
1419 
1420 	return ERR_PTR(ret);
1421 }
1422 
1423 static int tcm_usbg_drop_nexus(struct usbg_tpg *);
1424 
1425 static void usbg_drop_tpg(struct se_portal_group *se_tpg)
1426 {
1427 	struct usbg_tpg *tpg = container_of(se_tpg,
1428 				struct usbg_tpg, se_tpg);
1429 	unsigned i;
1430 	struct f_tcm_opts *opts;
1431 
1432 	tcm_usbg_drop_nexus(tpg);
1433 	core_tpg_deregister(se_tpg);
1434 	destroy_workqueue(tpg->workqueue);
1435 
1436 	mutex_lock(&tpg_instances_lock);
1437 	for (i = 0; i < TPG_INSTANCES; ++i)
1438 		if (tpg_instances[i].tpg == tpg)
1439 			break;
1440 	if (i < TPG_INSTANCES) {
1441 		tpg_instances[i].tpg = NULL;
1442 		opts = container_of(tpg_instances[i].func_inst,
1443 			struct f_tcm_opts, func_inst);
1444 		mutex_lock(&opts->dep_lock);
1445 		if (opts->has_dep)
1446 			module_put(opts->dependent);
1447 		else
1448 			configfs_undepend_item_unlocked(
1449 				&opts->func_inst.group.cg_item);
1450 		mutex_unlock(&opts->dep_lock);
1451 	}
1452 	mutex_unlock(&tpg_instances_lock);
1453 
1454 	kfree(tpg);
1455 }
1456 
1457 static struct se_wwn *usbg_make_tport(
1458 	struct target_fabric_configfs *tf,
1459 	struct config_group *group,
1460 	const char *name)
1461 {
1462 	struct usbg_tport *tport;
1463 	const char *wnn_name;
1464 	u64 wwpn = 0;
1465 
1466 	wnn_name = usbg_check_wwn(name);
1467 	if (!wnn_name)
1468 		return ERR_PTR(-EINVAL);
1469 
1470 	tport = kzalloc(sizeof(struct usbg_tport), GFP_KERNEL);
1471 	if (!(tport))
1472 		return ERR_PTR(-ENOMEM);
1473 
1474 	tport->tport_wwpn = wwpn;
1475 	snprintf(tport->tport_name, sizeof(tport->tport_name), "%s", wnn_name);
1476 	return &tport->tport_wwn;
1477 }
1478 
1479 static void usbg_drop_tport(struct se_wwn *wwn)
1480 {
1481 	struct usbg_tport *tport = container_of(wwn,
1482 				struct usbg_tport, tport_wwn);
1483 	kfree(tport);
1484 }
1485 
1486 /*
1487  * If somebody feels like dropping the version property, go ahead.
1488  */
1489 static ssize_t usbg_wwn_version_show(struct config_item *item,  char *page)
1490 {
1491 	return sprintf(page, "usb-gadget fabric module\n");
1492 }
1493 
1494 CONFIGFS_ATTR_RO(usbg_wwn_, version);
1495 
1496 static struct configfs_attribute *usbg_wwn_attrs[] = {
1497 	&usbg_wwn_attr_version,
1498 	NULL,
1499 };
1500 
1501 static ssize_t tcm_usbg_tpg_enable_show(struct config_item *item, char *page)
1502 {
1503 	struct se_portal_group *se_tpg = to_tpg(item);
1504 	struct usbg_tpg  *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1505 
1506 	return snprintf(page, PAGE_SIZE, "%u\n", tpg->gadget_connect);
1507 }
1508 
1509 static int usbg_attach(struct usbg_tpg *);
1510 static void usbg_detach(struct usbg_tpg *);
1511 
1512 static ssize_t tcm_usbg_tpg_enable_store(struct config_item *item,
1513 		const char *page, size_t count)
1514 {
1515 	struct se_portal_group *se_tpg = to_tpg(item);
1516 	struct usbg_tpg  *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1517 	bool op;
1518 	ssize_t ret;
1519 
1520 	ret = strtobool(page, &op);
1521 	if (ret)
1522 		return ret;
1523 
1524 	if ((op && tpg->gadget_connect) || (!op && !tpg->gadget_connect))
1525 		return -EINVAL;
1526 
1527 	if (op)
1528 		ret = usbg_attach(tpg);
1529 	else
1530 		usbg_detach(tpg);
1531 	if (ret)
1532 		return ret;
1533 
1534 	tpg->gadget_connect = op;
1535 
1536 	return count;
1537 }
1538 
1539 static ssize_t tcm_usbg_tpg_nexus_show(struct config_item *item, char *page)
1540 {
1541 	struct se_portal_group *se_tpg = to_tpg(item);
1542 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1543 	struct tcm_usbg_nexus *tv_nexus;
1544 	ssize_t ret;
1545 
1546 	mutex_lock(&tpg->tpg_mutex);
1547 	tv_nexus = tpg->tpg_nexus;
1548 	if (!tv_nexus) {
1549 		ret = -ENODEV;
1550 		goto out;
1551 	}
1552 	ret = snprintf(page, PAGE_SIZE, "%s\n",
1553 			tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1554 out:
1555 	mutex_unlock(&tpg->tpg_mutex);
1556 	return ret;
1557 }
1558 
1559 static int usbg_alloc_sess_cb(struct se_portal_group *se_tpg,
1560 			      struct se_session *se_sess, void *p)
1561 {
1562 	struct usbg_tpg *tpg = container_of(se_tpg,
1563 				struct usbg_tpg, se_tpg);
1564 
1565 	tpg->tpg_nexus = p;
1566 	return 0;
1567 }
1568 
1569 static int tcm_usbg_make_nexus(struct usbg_tpg *tpg, char *name)
1570 {
1571 	struct tcm_usbg_nexus *tv_nexus;
1572 	int ret = 0;
1573 
1574 	mutex_lock(&tpg->tpg_mutex);
1575 	if (tpg->tpg_nexus) {
1576 		ret = -EEXIST;
1577 		pr_debug("tpg->tpg_nexus already exists\n");
1578 		goto out_unlock;
1579 	}
1580 
1581 	tv_nexus = kzalloc(sizeof(*tv_nexus), GFP_KERNEL);
1582 	if (!tv_nexus) {
1583 		ret = -ENOMEM;
1584 		goto out_unlock;
1585 	}
1586 
1587 	tv_nexus->tvn_se_sess = target_setup_session(&tpg->se_tpg,
1588 						     USB_G_DEFAULT_SESSION_TAGS,
1589 						     sizeof(struct usbg_cmd),
1590 						     TARGET_PROT_NORMAL, name,
1591 						     tv_nexus, usbg_alloc_sess_cb);
1592 	if (IS_ERR(tv_nexus->tvn_se_sess)) {
1593 #define MAKE_NEXUS_MSG "core_tpg_check_initiator_node_acl() failed for %s\n"
1594 		pr_debug(MAKE_NEXUS_MSG, name);
1595 #undef MAKE_NEXUS_MSG
1596 		ret = PTR_ERR(tv_nexus->tvn_se_sess);
1597 		kfree(tv_nexus);
1598 	}
1599 
1600 out_unlock:
1601 	mutex_unlock(&tpg->tpg_mutex);
1602 	return ret;
1603 }
1604 
1605 static int tcm_usbg_drop_nexus(struct usbg_tpg *tpg)
1606 {
1607 	struct se_session *se_sess;
1608 	struct tcm_usbg_nexus *tv_nexus;
1609 	int ret = -ENODEV;
1610 
1611 	mutex_lock(&tpg->tpg_mutex);
1612 	tv_nexus = tpg->tpg_nexus;
1613 	if (!tv_nexus)
1614 		goto out;
1615 
1616 	se_sess = tv_nexus->tvn_se_sess;
1617 	if (!se_sess)
1618 		goto out;
1619 
1620 	if (atomic_read(&tpg->tpg_port_count)) {
1621 		ret = -EPERM;
1622 #define MSG "Unable to remove Host I_T Nexus with active TPG port count: %d\n"
1623 		pr_err(MSG, atomic_read(&tpg->tpg_port_count));
1624 #undef MSG
1625 		goto out;
1626 	}
1627 
1628 	pr_debug("Removing I_T Nexus to Initiator Port: %s\n",
1629 			tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1630 	/*
1631 	 * Release the SCSI I_T Nexus to the emulated vHost Target Port
1632 	 */
1633 	target_remove_session(se_sess);
1634 	tpg->tpg_nexus = NULL;
1635 
1636 	kfree(tv_nexus);
1637 	ret = 0;
1638 out:
1639 	mutex_unlock(&tpg->tpg_mutex);
1640 	return ret;
1641 }
1642 
1643 static ssize_t tcm_usbg_tpg_nexus_store(struct config_item *item,
1644 		const char *page, size_t count)
1645 {
1646 	struct se_portal_group *se_tpg = to_tpg(item);
1647 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1648 	unsigned char i_port[USBG_NAMELEN], *ptr;
1649 	int ret;
1650 
1651 	if (!strncmp(page, "NULL", 4)) {
1652 		ret = tcm_usbg_drop_nexus(tpg);
1653 		return (!ret) ? count : ret;
1654 	}
1655 	if (strlen(page) >= USBG_NAMELEN) {
1656 
1657 #define NEXUS_STORE_MSG "Emulated NAA Sas Address: %s, exceeds max: %d\n"
1658 		pr_err(NEXUS_STORE_MSG, page, USBG_NAMELEN);
1659 #undef NEXUS_STORE_MSG
1660 		return -EINVAL;
1661 	}
1662 	snprintf(i_port, USBG_NAMELEN, "%s", page);
1663 
1664 	ptr = strstr(i_port, "naa.");
1665 	if (!ptr) {
1666 		pr_err("Missing 'naa.' prefix\n");
1667 		return -EINVAL;
1668 	}
1669 
1670 	if (i_port[strlen(i_port) - 1] == '\n')
1671 		i_port[strlen(i_port) - 1] = '\0';
1672 
1673 	ret = tcm_usbg_make_nexus(tpg, &i_port[0]);
1674 	if (ret < 0)
1675 		return ret;
1676 	return count;
1677 }
1678 
1679 CONFIGFS_ATTR(tcm_usbg_tpg_, enable);
1680 CONFIGFS_ATTR(tcm_usbg_tpg_, nexus);
1681 
1682 static struct configfs_attribute *usbg_base_attrs[] = {
1683 	&tcm_usbg_tpg_attr_enable,
1684 	&tcm_usbg_tpg_attr_nexus,
1685 	NULL,
1686 };
1687 
1688 static int usbg_port_link(struct se_portal_group *se_tpg, struct se_lun *lun)
1689 {
1690 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1691 
1692 	atomic_inc(&tpg->tpg_port_count);
1693 	smp_mb__after_atomic();
1694 	return 0;
1695 }
1696 
1697 static void usbg_port_unlink(struct se_portal_group *se_tpg,
1698 		struct se_lun *se_lun)
1699 {
1700 	struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1701 
1702 	atomic_dec(&tpg->tpg_port_count);
1703 	smp_mb__after_atomic();
1704 }
1705 
1706 static int usbg_check_stop_free(struct se_cmd *se_cmd)
1707 {
1708 	return target_put_sess_cmd(se_cmd);
1709 }
1710 
1711 static const struct target_core_fabric_ops usbg_ops = {
1712 	.module				= THIS_MODULE,
1713 	.fabric_name			= "usb_gadget",
1714 	.tpg_get_wwn			= usbg_get_fabric_wwn,
1715 	.tpg_get_tag			= usbg_get_tag,
1716 	.tpg_check_demo_mode		= usbg_check_true,
1717 	.tpg_check_demo_mode_cache	= usbg_check_false,
1718 	.tpg_check_demo_mode_write_protect = usbg_check_false,
1719 	.tpg_check_prod_mode_write_protect = usbg_check_false,
1720 	.tpg_get_inst_index		= usbg_tpg_get_inst_index,
1721 	.release_cmd			= usbg_release_cmd,
1722 	.sess_get_index			= usbg_sess_get_index,
1723 	.sess_get_initiator_sid		= NULL,
1724 	.write_pending			= usbg_send_write_request,
1725 	.set_default_node_attributes	= usbg_set_default_node_attrs,
1726 	.get_cmd_state			= usbg_get_cmd_state,
1727 	.queue_data_in			= usbg_send_read_response,
1728 	.queue_status			= usbg_send_status_response,
1729 	.queue_tm_rsp			= usbg_queue_tm_rsp,
1730 	.aborted_task			= usbg_aborted_task,
1731 	.check_stop_free		= usbg_check_stop_free,
1732 
1733 	.fabric_make_wwn		= usbg_make_tport,
1734 	.fabric_drop_wwn		= usbg_drop_tport,
1735 	.fabric_make_tpg		= usbg_make_tpg,
1736 	.fabric_drop_tpg		= usbg_drop_tpg,
1737 	.fabric_post_link		= usbg_port_link,
1738 	.fabric_pre_unlink		= usbg_port_unlink,
1739 	.fabric_init_nodeacl		= usbg_init_nodeacl,
1740 
1741 	.tfc_wwn_attrs			= usbg_wwn_attrs,
1742 	.tfc_tpg_base_attrs		= usbg_base_attrs,
1743 };
1744 
1745 /* Start gadget.c code */
1746 
1747 static struct usb_interface_descriptor bot_intf_desc = {
1748 	.bLength =              sizeof(bot_intf_desc),
1749 	.bDescriptorType =      USB_DT_INTERFACE,
1750 	.bNumEndpoints =        2,
1751 	.bAlternateSetting =	USB_G_ALT_INT_BBB,
1752 	.bInterfaceClass =      USB_CLASS_MASS_STORAGE,
1753 	.bInterfaceSubClass =   USB_SC_SCSI,
1754 	.bInterfaceProtocol =   USB_PR_BULK,
1755 };
1756 
1757 static struct usb_interface_descriptor uasp_intf_desc = {
1758 	.bLength =		sizeof(uasp_intf_desc),
1759 	.bDescriptorType =	USB_DT_INTERFACE,
1760 	.bNumEndpoints =	4,
1761 	.bAlternateSetting =	USB_G_ALT_INT_UAS,
1762 	.bInterfaceClass =	USB_CLASS_MASS_STORAGE,
1763 	.bInterfaceSubClass =	USB_SC_SCSI,
1764 	.bInterfaceProtocol =	USB_PR_UAS,
1765 };
1766 
1767 static struct usb_endpoint_descriptor uasp_bi_desc = {
1768 	.bLength =		USB_DT_ENDPOINT_SIZE,
1769 	.bDescriptorType =	USB_DT_ENDPOINT,
1770 	.bEndpointAddress =	USB_DIR_IN,
1771 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1772 	.wMaxPacketSize =	cpu_to_le16(512),
1773 };
1774 
1775 static struct usb_endpoint_descriptor uasp_fs_bi_desc = {
1776 	.bLength =		USB_DT_ENDPOINT_SIZE,
1777 	.bDescriptorType =	USB_DT_ENDPOINT,
1778 	.bEndpointAddress =	USB_DIR_IN,
1779 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1780 };
1781 
1782 static struct usb_pipe_usage_descriptor uasp_bi_pipe_desc = {
1783 	.bLength =		sizeof(uasp_bi_pipe_desc),
1784 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1785 	.bPipeID =		DATA_IN_PIPE_ID,
1786 };
1787 
1788 static struct usb_endpoint_descriptor uasp_ss_bi_desc = {
1789 	.bLength =		USB_DT_ENDPOINT_SIZE,
1790 	.bDescriptorType =	USB_DT_ENDPOINT,
1791 	.bEndpointAddress =	USB_DIR_IN,
1792 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1793 	.wMaxPacketSize =	cpu_to_le16(1024),
1794 };
1795 
1796 static struct usb_ss_ep_comp_descriptor uasp_bi_ep_comp_desc = {
1797 	.bLength =		sizeof(uasp_bi_ep_comp_desc),
1798 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1799 	.bMaxBurst =		0,
1800 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1801 	.wBytesPerInterval =	0,
1802 };
1803 
1804 static struct usb_ss_ep_comp_descriptor bot_bi_ep_comp_desc = {
1805 	.bLength =		sizeof(bot_bi_ep_comp_desc),
1806 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1807 	.bMaxBurst =		0,
1808 };
1809 
1810 static struct usb_endpoint_descriptor uasp_bo_desc = {
1811 	.bLength =		USB_DT_ENDPOINT_SIZE,
1812 	.bDescriptorType =	USB_DT_ENDPOINT,
1813 	.bEndpointAddress =	USB_DIR_OUT,
1814 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1815 	.wMaxPacketSize =	cpu_to_le16(512),
1816 };
1817 
1818 static struct usb_endpoint_descriptor uasp_fs_bo_desc = {
1819 	.bLength =		USB_DT_ENDPOINT_SIZE,
1820 	.bDescriptorType =	USB_DT_ENDPOINT,
1821 	.bEndpointAddress =	USB_DIR_OUT,
1822 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1823 };
1824 
1825 static struct usb_pipe_usage_descriptor uasp_bo_pipe_desc = {
1826 	.bLength =		sizeof(uasp_bo_pipe_desc),
1827 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1828 	.bPipeID =		DATA_OUT_PIPE_ID,
1829 };
1830 
1831 static struct usb_endpoint_descriptor uasp_ss_bo_desc = {
1832 	.bLength =		USB_DT_ENDPOINT_SIZE,
1833 	.bDescriptorType =	USB_DT_ENDPOINT,
1834 	.bEndpointAddress =	USB_DIR_OUT,
1835 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1836 	.wMaxPacketSize =	cpu_to_le16(0x400),
1837 };
1838 
1839 static struct usb_ss_ep_comp_descriptor uasp_bo_ep_comp_desc = {
1840 	.bLength =		sizeof(uasp_bo_ep_comp_desc),
1841 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1842 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1843 };
1844 
1845 static struct usb_ss_ep_comp_descriptor bot_bo_ep_comp_desc = {
1846 	.bLength =		sizeof(bot_bo_ep_comp_desc),
1847 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1848 };
1849 
1850 static struct usb_endpoint_descriptor uasp_status_desc = {
1851 	.bLength =		USB_DT_ENDPOINT_SIZE,
1852 	.bDescriptorType =	USB_DT_ENDPOINT,
1853 	.bEndpointAddress =	USB_DIR_IN,
1854 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1855 	.wMaxPacketSize =	cpu_to_le16(512),
1856 };
1857 
1858 static struct usb_endpoint_descriptor uasp_fs_status_desc = {
1859 	.bLength =		USB_DT_ENDPOINT_SIZE,
1860 	.bDescriptorType =	USB_DT_ENDPOINT,
1861 	.bEndpointAddress =	USB_DIR_IN,
1862 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1863 };
1864 
1865 static struct usb_pipe_usage_descriptor uasp_status_pipe_desc = {
1866 	.bLength =		sizeof(uasp_status_pipe_desc),
1867 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1868 	.bPipeID =		STATUS_PIPE_ID,
1869 };
1870 
1871 static struct usb_endpoint_descriptor uasp_ss_status_desc = {
1872 	.bLength =		USB_DT_ENDPOINT_SIZE,
1873 	.bDescriptorType =	USB_DT_ENDPOINT,
1874 	.bEndpointAddress =	USB_DIR_IN,
1875 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1876 	.wMaxPacketSize =	cpu_to_le16(1024),
1877 };
1878 
1879 static struct usb_ss_ep_comp_descriptor uasp_status_in_ep_comp_desc = {
1880 	.bLength =		sizeof(uasp_status_in_ep_comp_desc),
1881 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1882 	.bmAttributes =		UASP_SS_EP_COMP_LOG_STREAMS,
1883 };
1884 
1885 static struct usb_endpoint_descriptor uasp_cmd_desc = {
1886 	.bLength =		USB_DT_ENDPOINT_SIZE,
1887 	.bDescriptorType =	USB_DT_ENDPOINT,
1888 	.bEndpointAddress =	USB_DIR_OUT,
1889 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1890 	.wMaxPacketSize =	cpu_to_le16(512),
1891 };
1892 
1893 static struct usb_endpoint_descriptor uasp_fs_cmd_desc = {
1894 	.bLength =		USB_DT_ENDPOINT_SIZE,
1895 	.bDescriptorType =	USB_DT_ENDPOINT,
1896 	.bEndpointAddress =	USB_DIR_OUT,
1897 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1898 };
1899 
1900 static struct usb_pipe_usage_descriptor uasp_cmd_pipe_desc = {
1901 	.bLength =		sizeof(uasp_cmd_pipe_desc),
1902 	.bDescriptorType =	USB_DT_PIPE_USAGE,
1903 	.bPipeID =		CMD_PIPE_ID,
1904 };
1905 
1906 static struct usb_endpoint_descriptor uasp_ss_cmd_desc = {
1907 	.bLength =		USB_DT_ENDPOINT_SIZE,
1908 	.bDescriptorType =	USB_DT_ENDPOINT,
1909 	.bEndpointAddress =	USB_DIR_OUT,
1910 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
1911 	.wMaxPacketSize =	cpu_to_le16(1024),
1912 };
1913 
1914 static struct usb_ss_ep_comp_descriptor uasp_cmd_comp_desc = {
1915 	.bLength =		sizeof(uasp_cmd_comp_desc),
1916 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
1917 };
1918 
1919 static struct usb_descriptor_header *uasp_fs_function_desc[] = {
1920 	(struct usb_descriptor_header *) &bot_intf_desc,
1921 	(struct usb_descriptor_header *) &uasp_fs_bi_desc,
1922 	(struct usb_descriptor_header *) &uasp_fs_bo_desc,
1923 
1924 	(struct usb_descriptor_header *) &uasp_intf_desc,
1925 	(struct usb_descriptor_header *) &uasp_fs_bi_desc,
1926 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1927 	(struct usb_descriptor_header *) &uasp_fs_bo_desc,
1928 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1929 	(struct usb_descriptor_header *) &uasp_fs_status_desc,
1930 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1931 	(struct usb_descriptor_header *) &uasp_fs_cmd_desc,
1932 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1933 	NULL,
1934 };
1935 
1936 static struct usb_descriptor_header *uasp_hs_function_desc[] = {
1937 	(struct usb_descriptor_header *) &bot_intf_desc,
1938 	(struct usb_descriptor_header *) &uasp_bi_desc,
1939 	(struct usb_descriptor_header *) &uasp_bo_desc,
1940 
1941 	(struct usb_descriptor_header *) &uasp_intf_desc,
1942 	(struct usb_descriptor_header *) &uasp_bi_desc,
1943 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1944 	(struct usb_descriptor_header *) &uasp_bo_desc,
1945 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1946 	(struct usb_descriptor_header *) &uasp_status_desc,
1947 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1948 	(struct usb_descriptor_header *) &uasp_cmd_desc,
1949 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1950 	NULL,
1951 };
1952 
1953 static struct usb_descriptor_header *uasp_ss_function_desc[] = {
1954 	(struct usb_descriptor_header *) &bot_intf_desc,
1955 	(struct usb_descriptor_header *) &uasp_ss_bi_desc,
1956 	(struct usb_descriptor_header *) &bot_bi_ep_comp_desc,
1957 	(struct usb_descriptor_header *) &uasp_ss_bo_desc,
1958 	(struct usb_descriptor_header *) &bot_bo_ep_comp_desc,
1959 
1960 	(struct usb_descriptor_header *) &uasp_intf_desc,
1961 	(struct usb_descriptor_header *) &uasp_ss_bi_desc,
1962 	(struct usb_descriptor_header *) &uasp_bi_ep_comp_desc,
1963 	(struct usb_descriptor_header *) &uasp_bi_pipe_desc,
1964 	(struct usb_descriptor_header *) &uasp_ss_bo_desc,
1965 	(struct usb_descriptor_header *) &uasp_bo_ep_comp_desc,
1966 	(struct usb_descriptor_header *) &uasp_bo_pipe_desc,
1967 	(struct usb_descriptor_header *) &uasp_ss_status_desc,
1968 	(struct usb_descriptor_header *) &uasp_status_in_ep_comp_desc,
1969 	(struct usb_descriptor_header *) &uasp_status_pipe_desc,
1970 	(struct usb_descriptor_header *) &uasp_ss_cmd_desc,
1971 	(struct usb_descriptor_header *) &uasp_cmd_comp_desc,
1972 	(struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
1973 	NULL,
1974 };
1975 
1976 static struct usb_string	tcm_us_strings[] = {
1977 	[USB_G_STR_INT_UAS].s		= "USB Attached SCSI",
1978 	[USB_G_STR_INT_BBB].s		= "Bulk Only Transport",
1979 	{ },
1980 };
1981 
1982 static struct usb_gadget_strings tcm_stringtab = {
1983 	.language = 0x0409,
1984 	.strings = tcm_us_strings,
1985 };
1986 
1987 static struct usb_gadget_strings *tcm_strings[] = {
1988 	&tcm_stringtab,
1989 	NULL,
1990 };
1991 
1992 static int tcm_bind(struct usb_configuration *c, struct usb_function *f)
1993 {
1994 	struct f_uas		*fu = to_f_uas(f);
1995 	struct usb_string	*us;
1996 	struct usb_gadget	*gadget = c->cdev->gadget;
1997 	struct usb_ep		*ep;
1998 	struct f_tcm_opts	*opts;
1999 	int			iface;
2000 	int			ret;
2001 
2002 	opts = container_of(f->fi, struct f_tcm_opts, func_inst);
2003 
2004 	mutex_lock(&opts->dep_lock);
2005 	if (!opts->can_attach) {
2006 		mutex_unlock(&opts->dep_lock);
2007 		return -ENODEV;
2008 	}
2009 	mutex_unlock(&opts->dep_lock);
2010 	us = usb_gstrings_attach(c->cdev, tcm_strings,
2011 		ARRAY_SIZE(tcm_us_strings));
2012 	if (IS_ERR(us))
2013 		return PTR_ERR(us);
2014 	bot_intf_desc.iInterface = us[USB_G_STR_INT_BBB].id;
2015 	uasp_intf_desc.iInterface = us[USB_G_STR_INT_UAS].id;
2016 
2017 	iface = usb_interface_id(c, f);
2018 	if (iface < 0)
2019 		return iface;
2020 
2021 	bot_intf_desc.bInterfaceNumber = iface;
2022 	uasp_intf_desc.bInterfaceNumber = iface;
2023 	fu->iface = iface;
2024 	ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_bi_desc,
2025 			&uasp_bi_ep_comp_desc);
2026 	if (!ep)
2027 		goto ep_fail;
2028 
2029 	fu->ep_in = ep;
2030 
2031 	ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_bo_desc,
2032 			&uasp_bo_ep_comp_desc);
2033 	if (!ep)
2034 		goto ep_fail;
2035 	fu->ep_out = ep;
2036 
2037 	ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_status_desc,
2038 			&uasp_status_in_ep_comp_desc);
2039 	if (!ep)
2040 		goto ep_fail;
2041 	fu->ep_status = ep;
2042 
2043 	ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_cmd_desc,
2044 			&uasp_cmd_comp_desc);
2045 	if (!ep)
2046 		goto ep_fail;
2047 	fu->ep_cmd = ep;
2048 
2049 	/* Assume endpoint addresses are the same for both speeds */
2050 	uasp_bi_desc.bEndpointAddress =	uasp_ss_bi_desc.bEndpointAddress;
2051 	uasp_bo_desc.bEndpointAddress = uasp_ss_bo_desc.bEndpointAddress;
2052 	uasp_status_desc.bEndpointAddress =
2053 		uasp_ss_status_desc.bEndpointAddress;
2054 	uasp_cmd_desc.bEndpointAddress = uasp_ss_cmd_desc.bEndpointAddress;
2055 
2056 	uasp_fs_bi_desc.bEndpointAddress = uasp_ss_bi_desc.bEndpointAddress;
2057 	uasp_fs_bo_desc.bEndpointAddress = uasp_ss_bo_desc.bEndpointAddress;
2058 	uasp_fs_status_desc.bEndpointAddress =
2059 		uasp_ss_status_desc.bEndpointAddress;
2060 	uasp_fs_cmd_desc.bEndpointAddress = uasp_ss_cmd_desc.bEndpointAddress;
2061 
2062 	ret = usb_assign_descriptors(f, uasp_fs_function_desc,
2063 			uasp_hs_function_desc, uasp_ss_function_desc, NULL);
2064 	if (ret)
2065 		goto ep_fail;
2066 
2067 	return 0;
2068 ep_fail:
2069 	pr_err("Can't claim all required eps\n");
2070 
2071 	return -ENOTSUPP;
2072 }
2073 
2074 struct guas_setup_wq {
2075 	struct work_struct work;
2076 	struct f_uas *fu;
2077 	unsigned int alt;
2078 };
2079 
2080 static void tcm_delayed_set_alt(struct work_struct *wq)
2081 {
2082 	struct guas_setup_wq *work = container_of(wq, struct guas_setup_wq,
2083 			work);
2084 	struct f_uas *fu = work->fu;
2085 	int alt = work->alt;
2086 
2087 	kfree(work);
2088 
2089 	if (fu->flags & USBG_IS_BOT)
2090 		bot_cleanup_old_alt(fu);
2091 	if (fu->flags & USBG_IS_UAS)
2092 		uasp_cleanup_old_alt(fu);
2093 
2094 	if (alt == USB_G_ALT_INT_BBB)
2095 		bot_set_alt(fu);
2096 	else if (alt == USB_G_ALT_INT_UAS)
2097 		uasp_set_alt(fu);
2098 	usb_composite_setup_continue(fu->function.config->cdev);
2099 }
2100 
2101 static int tcm_get_alt(struct usb_function *f, unsigned intf)
2102 {
2103 	if (intf == bot_intf_desc.bInterfaceNumber)
2104 		return USB_G_ALT_INT_BBB;
2105 	if (intf == uasp_intf_desc.bInterfaceNumber)
2106 		return USB_G_ALT_INT_UAS;
2107 
2108 	return -EOPNOTSUPP;
2109 }
2110 
2111 static int tcm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2112 {
2113 	struct f_uas *fu = to_f_uas(f);
2114 
2115 	if ((alt == USB_G_ALT_INT_BBB) || (alt == USB_G_ALT_INT_UAS)) {
2116 		struct guas_setup_wq *work;
2117 
2118 		work = kmalloc(sizeof(*work), GFP_ATOMIC);
2119 		if (!work)
2120 			return -ENOMEM;
2121 		INIT_WORK(&work->work, tcm_delayed_set_alt);
2122 		work->fu = fu;
2123 		work->alt = alt;
2124 		schedule_work(&work->work);
2125 		return USB_GADGET_DELAYED_STATUS;
2126 	}
2127 	return -EOPNOTSUPP;
2128 }
2129 
2130 static void tcm_disable(struct usb_function *f)
2131 {
2132 	struct f_uas *fu = to_f_uas(f);
2133 
2134 	if (fu->flags & USBG_IS_UAS)
2135 		uasp_cleanup_old_alt(fu);
2136 	else if (fu->flags & USBG_IS_BOT)
2137 		bot_cleanup_old_alt(fu);
2138 	fu->flags = 0;
2139 }
2140 
2141 static int tcm_setup(struct usb_function *f,
2142 		const struct usb_ctrlrequest *ctrl)
2143 {
2144 	struct f_uas *fu = to_f_uas(f);
2145 
2146 	if (!(fu->flags & USBG_IS_BOT))
2147 		return -EOPNOTSUPP;
2148 
2149 	return usbg_bot_setup(f, ctrl);
2150 }
2151 
2152 static inline struct f_tcm_opts *to_f_tcm_opts(struct config_item *item)
2153 {
2154 	return container_of(to_config_group(item), struct f_tcm_opts,
2155 		func_inst.group);
2156 }
2157 
2158 static void tcm_attr_release(struct config_item *item)
2159 {
2160 	struct f_tcm_opts *opts = to_f_tcm_opts(item);
2161 
2162 	usb_put_function_instance(&opts->func_inst);
2163 }
2164 
2165 static struct configfs_item_operations tcm_item_ops = {
2166 	.release		= tcm_attr_release,
2167 };
2168 
2169 static const struct config_item_type tcm_func_type = {
2170 	.ct_item_ops	= &tcm_item_ops,
2171 	.ct_owner	= THIS_MODULE,
2172 };
2173 
2174 static void tcm_free_inst(struct usb_function_instance *f)
2175 {
2176 	struct f_tcm_opts *opts;
2177 	unsigned i;
2178 
2179 	opts = container_of(f, struct f_tcm_opts, func_inst);
2180 
2181 	mutex_lock(&tpg_instances_lock);
2182 	for (i = 0; i < TPG_INSTANCES; ++i)
2183 		if (tpg_instances[i].func_inst == f)
2184 			break;
2185 	if (i < TPG_INSTANCES)
2186 		tpg_instances[i].func_inst = NULL;
2187 	mutex_unlock(&tpg_instances_lock);
2188 
2189 	kfree(opts);
2190 }
2191 
2192 static int tcm_register_callback(struct usb_function_instance *f)
2193 {
2194 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2195 
2196 	mutex_lock(&opts->dep_lock);
2197 	opts->can_attach = true;
2198 	mutex_unlock(&opts->dep_lock);
2199 
2200 	return 0;
2201 }
2202 
2203 static void tcm_unregister_callback(struct usb_function_instance *f)
2204 {
2205 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2206 
2207 	mutex_lock(&opts->dep_lock);
2208 	unregister_gadget_item(opts->
2209 		func_inst.group.cg_item.ci_parent->ci_parent);
2210 	opts->can_attach = false;
2211 	mutex_unlock(&opts->dep_lock);
2212 }
2213 
2214 static int usbg_attach(struct usbg_tpg *tpg)
2215 {
2216 	struct usb_function_instance *f = tpg->fi;
2217 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2218 
2219 	if (opts->tcm_register_callback)
2220 		return opts->tcm_register_callback(f);
2221 
2222 	return 0;
2223 }
2224 
2225 static void usbg_detach(struct usbg_tpg *tpg)
2226 {
2227 	struct usb_function_instance *f = tpg->fi;
2228 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2229 
2230 	if (opts->tcm_unregister_callback)
2231 		opts->tcm_unregister_callback(f);
2232 }
2233 
2234 static int tcm_set_name(struct usb_function_instance *f, const char *name)
2235 {
2236 	struct f_tcm_opts *opts = container_of(f, struct f_tcm_opts, func_inst);
2237 
2238 	pr_debug("tcm: Activating %s\n", name);
2239 
2240 	mutex_lock(&opts->dep_lock);
2241 	opts->ready = true;
2242 	mutex_unlock(&opts->dep_lock);
2243 
2244 	return 0;
2245 }
2246 
2247 static struct usb_function_instance *tcm_alloc_inst(void)
2248 {
2249 	struct f_tcm_opts *opts;
2250 	int i;
2251 
2252 
2253 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2254 	if (!opts)
2255 		return ERR_PTR(-ENOMEM);
2256 
2257 	mutex_lock(&tpg_instances_lock);
2258 	for (i = 0; i < TPG_INSTANCES; ++i)
2259 		if (!tpg_instances[i].func_inst)
2260 			break;
2261 
2262 	if (i == TPG_INSTANCES) {
2263 		mutex_unlock(&tpg_instances_lock);
2264 		kfree(opts);
2265 		return ERR_PTR(-EBUSY);
2266 	}
2267 	tpg_instances[i].func_inst = &opts->func_inst;
2268 	mutex_unlock(&tpg_instances_lock);
2269 
2270 	mutex_init(&opts->dep_lock);
2271 	opts->func_inst.set_inst_name = tcm_set_name;
2272 	opts->func_inst.free_func_inst = tcm_free_inst;
2273 	opts->tcm_register_callback = tcm_register_callback;
2274 	opts->tcm_unregister_callback = tcm_unregister_callback;
2275 
2276 	config_group_init_type_name(&opts->func_inst.group, "",
2277 			&tcm_func_type);
2278 
2279 	return &opts->func_inst;
2280 }
2281 
2282 static void tcm_free(struct usb_function *f)
2283 {
2284 	struct f_uas *tcm = to_f_uas(f);
2285 
2286 	kfree(tcm);
2287 }
2288 
2289 static void tcm_unbind(struct usb_configuration *c, struct usb_function *f)
2290 {
2291 	usb_free_all_descriptors(f);
2292 }
2293 
2294 static struct usb_function *tcm_alloc(struct usb_function_instance *fi)
2295 {
2296 	struct f_uas *fu;
2297 	unsigned i;
2298 
2299 	mutex_lock(&tpg_instances_lock);
2300 	for (i = 0; i < TPG_INSTANCES; ++i)
2301 		if (tpg_instances[i].func_inst == fi)
2302 			break;
2303 	if (i == TPG_INSTANCES) {
2304 		mutex_unlock(&tpg_instances_lock);
2305 		return ERR_PTR(-ENODEV);
2306 	}
2307 
2308 	fu = kzalloc(sizeof(*fu), GFP_KERNEL);
2309 	if (!fu) {
2310 		mutex_unlock(&tpg_instances_lock);
2311 		return ERR_PTR(-ENOMEM);
2312 	}
2313 
2314 	fu->function.name = "Target Function";
2315 	fu->function.bind = tcm_bind;
2316 	fu->function.unbind = tcm_unbind;
2317 	fu->function.set_alt = tcm_set_alt;
2318 	fu->function.get_alt = tcm_get_alt;
2319 	fu->function.setup = tcm_setup;
2320 	fu->function.disable = tcm_disable;
2321 	fu->function.free_func = tcm_free;
2322 	fu->tpg = tpg_instances[i].tpg;
2323 	mutex_unlock(&tpg_instances_lock);
2324 
2325 	return &fu->function;
2326 }
2327 
2328 DECLARE_USB_FUNCTION(tcm, tcm_alloc_inst, tcm_alloc);
2329 
2330 static int tcm_init(void)
2331 {
2332 	int ret;
2333 
2334 	ret = usb_function_register(&tcmusb_func);
2335 	if (ret)
2336 		return ret;
2337 
2338 	ret = target_register_template(&usbg_ops);
2339 	if (ret)
2340 		usb_function_unregister(&tcmusb_func);
2341 
2342 	return ret;
2343 }
2344 module_init(tcm_init);
2345 
2346 static void tcm_exit(void)
2347 {
2348 	target_unregister_template(&usbg_ops);
2349 	usb_function_unregister(&tcmusb_func);
2350 }
2351 module_exit(tcm_exit);
2352 
2353 MODULE_LICENSE("GPL");
2354 MODULE_AUTHOR("Sebastian Andrzej Siewior");
2355