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