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