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