target: Remove unused target_core_fabric_ops.get_fabric_sense_len method
[profile/ivi/kernel-adaptation-intel-automotive.git] / drivers / usb / gadget / tcm_usb_gadget.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.h>
20 #include <scsi/scsi_tcq.h>
21 #include <target/target_core_base.h>
22 #include <target/target_core_fabric.h>
23 #include <target/target_core_fabric_configfs.h>
24 #include <target/target_core_configfs.h>
25 #include <target/configfs_macros.h>
26 #include <asm/unaligned.h>
27
28 #include "usbstring.c"
29 #include "epautoconf.c"
30 #include "config.c"
31 #include "composite.c"
32
33 #include "tcm_usb_gadget.h"
34
35 static struct target_fabric_configfs *usbg_fabric_configfs;
36
37 static inline struct f_uas *to_f_uas(struct usb_function *f)
38 {
39         return container_of(f, struct f_uas, function);
40 }
41
42 static void usbg_cmd_release(struct kref *);
43
44 static inline void usbg_cleanup_cmd(struct usbg_cmd *cmd)
45 {
46         kref_put(&cmd->ref, usbg_cmd_release);
47 }
48
49 /* Start bot.c code */
50
51 static int bot_enqueue_cmd_cbw(struct f_uas *fu)
52 {
53         int ret;
54
55         if (fu->flags & USBG_BOT_CMD_PEND)
56                 return 0;
57
58         ret = usb_ep_queue(fu->ep_out, fu->cmd.req, GFP_ATOMIC);
59         if (!ret)
60                 fu->flags |= USBG_BOT_CMD_PEND;
61         return ret;
62 }
63
64 static void bot_status_complete(struct usb_ep *ep, struct usb_request *req)
65 {
66         struct usbg_cmd *cmd = req->context;
67         struct f_uas *fu = cmd->fu;
68
69         usbg_cleanup_cmd(cmd);
70         if (req->status < 0) {
71                 pr_err("ERR %s(%d)\n", __func__, __LINE__);
72                 return;
73         }
74
75         /* CSW completed, wait for next CBW */
76         bot_enqueue_cmd_cbw(fu);
77 }
78
79 static void bot_enqueue_sense_code(struct f_uas *fu, struct usbg_cmd *cmd)
80 {
81         struct bulk_cs_wrap *csw = &fu->bot_status.csw;
82         int ret;
83         u8 *sense;
84         unsigned int csw_stat;
85
86         csw_stat = cmd->csw_code;
87
88         /*
89          * We can't send SENSE as a response. So we take ASC & ASCQ from our
90          * sense buffer and queue it and hope the host sends a REQUEST_SENSE
91          * command where it learns why we failed.
92          */
93         sense = cmd->sense_iu.sense;
94
95         csw->Tag = cmd->bot_tag;
96         csw->Status = csw_stat;
97         fu->bot_status.req->context = cmd;
98         ret = usb_ep_queue(fu->ep_in, fu->bot_status.req, GFP_ATOMIC);
99         if (ret)
100                 pr_err("%s(%d) ERR: %d\n", __func__, __LINE__, ret);
101 }
102
103 static void bot_err_compl(struct usb_ep *ep, struct usb_request *req)
104 {
105         struct usbg_cmd *cmd = req->context;
106         struct f_uas *fu = cmd->fu;
107
108         if (req->status < 0)
109                 pr_err("ERR %s(%d)\n", __func__, __LINE__);
110
111         if (cmd->data_len) {
112                 if (cmd->data_len > ep->maxpacket) {
113                         req->length = ep->maxpacket;
114                         cmd->data_len -= ep->maxpacket;
115                 } else {
116                         req->length = cmd->data_len;
117                         cmd->data_len = 0;
118                 }
119
120                 usb_ep_queue(ep, req, GFP_ATOMIC);
121                 return ;
122         }
123         bot_enqueue_sense_code(fu, cmd);
124 }
125
126 static void bot_send_bad_status(struct usbg_cmd *cmd)
127 {
128         struct f_uas *fu = cmd->fu;
129         struct bulk_cs_wrap *csw = &fu->bot_status.csw;
130         struct usb_request *req;
131         struct usb_ep *ep;
132
133         csw->Residue = cpu_to_le32(cmd->data_len);
134
135         if (cmd->data_len) {
136                 if (cmd->is_read) {
137                         ep = fu->ep_in;
138                         req = fu->bot_req_in;
139                 } else {
140                         ep = fu->ep_out;
141                         req = fu->bot_req_out;
142                 }
143
144                 if (cmd->data_len > fu->ep_in->maxpacket) {
145                         req->length = ep->maxpacket;
146                         cmd->data_len -= ep->maxpacket;
147                 } else {
148                         req->length = cmd->data_len;
149                         cmd->data_len = 0;
150                 }
151                 req->complete = bot_err_compl;
152                 req->context = cmd;
153                 req->buf = fu->cmd.buf;
154                 usb_ep_queue(ep, req, GFP_KERNEL);
155         } else {
156                 bot_enqueue_sense_code(fu, cmd);
157         }
158 }
159
160 static int bot_send_status(struct usbg_cmd *cmd, bool moved_data)
161 {
162         struct f_uas *fu = cmd->fu;
163         struct bulk_cs_wrap *csw = &fu->bot_status.csw;
164         int ret;
165
166         if (cmd->se_cmd.scsi_status == SAM_STAT_GOOD) {
167                 if (!moved_data && cmd->data_len) {
168                         /*
169                          * the host wants to move data, we don't. Fill / empty
170                          * the pipe and then send the csw with reside set.
171                          */
172                         cmd->csw_code = US_BULK_STAT_OK;
173                         bot_send_bad_status(cmd);
174                         return 0;
175                 }
176
177                 csw->Tag = cmd->bot_tag;
178                 csw->Residue = cpu_to_le32(0);
179                 csw->Status = US_BULK_STAT_OK;
180                 fu->bot_status.req->context = cmd;
181
182                 ret = usb_ep_queue(fu->ep_in, fu->bot_status.req, GFP_KERNEL);
183                 if (ret)
184                         pr_err("%s(%d) ERR: %d\n", __func__, __LINE__, ret);
185         } else {
186                 cmd->csw_code = US_BULK_STAT_FAIL;
187                 bot_send_bad_status(cmd);
188         }
189         return 0;
190 }
191
192 /*
193  * Called after command (no data transfer) or after the write (to device)
194  * operation is completed
195  */
196 static int bot_send_status_response(struct usbg_cmd *cmd)
197 {
198         bool moved_data = false;
199
200         if (!cmd->is_read)
201                 moved_data = true;
202         return bot_send_status(cmd, moved_data);
203 }
204
205 /* Read request completed, now we have to send the CSW */
206 static void bot_read_compl(struct usb_ep *ep, struct usb_request *req)
207 {
208         struct usbg_cmd *cmd = req->context;
209
210         if (req->status < 0)
211                 pr_err("ERR %s(%d)\n", __func__, __LINE__);
212
213         bot_send_status(cmd, true);
214 }
215
216 static int bot_send_read_response(struct usbg_cmd *cmd)
217 {
218         struct f_uas *fu = cmd->fu;
219         struct se_cmd *se_cmd = &cmd->se_cmd;
220         struct usb_gadget *gadget = fuas_to_gadget(fu);
221         int ret;
222
223         if (!cmd->data_len) {
224                 cmd->csw_code = US_BULK_STAT_PHASE;
225                 bot_send_bad_status(cmd);
226                 return 0;
227         }
228
229         if (!gadget->sg_supported) {
230                 cmd->data_buf = kmalloc(se_cmd->data_length, GFP_ATOMIC);
231                 if (!cmd->data_buf)
232                         return -ENOMEM;
233
234                 sg_copy_to_buffer(se_cmd->t_data_sg,
235                                 se_cmd->t_data_nents,
236                                 cmd->data_buf,
237                                 se_cmd->data_length);
238
239                 fu->bot_req_in->buf = cmd->data_buf;
240         } else {
241                 fu->bot_req_in->buf = NULL;
242                 fu->bot_req_in->num_sgs = se_cmd->t_data_nents;
243                 fu->bot_req_in->sg = se_cmd->t_data_sg;
244         }
245
246         fu->bot_req_in->complete = bot_read_compl;
247         fu->bot_req_in->length = se_cmd->data_length;
248         fu->bot_req_in->context = cmd;
249         ret = usb_ep_queue(fu->ep_in, fu->bot_req_in, GFP_ATOMIC);
250         if (ret)
251                 pr_err("%s(%d)\n", __func__, __LINE__);
252         return 0;
253 }
254
255 static void usbg_data_write_cmpl(struct usb_ep *, struct usb_request *);
256 static int usbg_prepare_w_request(struct usbg_cmd *, struct usb_request *);
257
258 static int bot_send_write_request(struct usbg_cmd *cmd)
259 {
260         struct f_uas *fu = cmd->fu;
261         struct se_cmd *se_cmd = &cmd->se_cmd;
262         struct usb_gadget *gadget = fuas_to_gadget(fu);
263         int ret;
264
265         init_completion(&cmd->write_complete);
266         cmd->fu = fu;
267
268         if (!cmd->data_len) {
269                 cmd->csw_code = US_BULK_STAT_PHASE;
270                 return -EINVAL;
271         }
272
273         if (!gadget->sg_supported) {
274                 cmd->data_buf = kmalloc(se_cmd->data_length, GFP_KERNEL);
275                 if (!cmd->data_buf)
276                         return -ENOMEM;
277
278                 fu->bot_req_out->buf = cmd->data_buf;
279         } else {
280                 fu->bot_req_out->buf = NULL;
281                 fu->bot_req_out->num_sgs = se_cmd->t_data_nents;
282                 fu->bot_req_out->sg = se_cmd->t_data_sg;
283         }
284
285         fu->bot_req_out->complete = usbg_data_write_cmpl;
286         fu->bot_req_out->length = se_cmd->data_length;
287         fu->bot_req_out->context = cmd;
288
289         ret = usbg_prepare_w_request(cmd, fu->bot_req_out);
290         if (ret)
291                 goto cleanup;
292         ret = usb_ep_queue(fu->ep_out, fu->bot_req_out, GFP_KERNEL);
293         if (ret)
294                 pr_err("%s(%d)\n", __func__, __LINE__);
295
296         wait_for_completion(&cmd->write_complete);
297         target_execute_cmd(se_cmd);
298 cleanup:
299         return ret;
300 }
301
302 static int bot_submit_command(struct f_uas *, void *, unsigned int);
303
304 static void bot_cmd_complete(struct usb_ep *ep, struct usb_request *req)
305 {
306         struct f_uas *fu = req->context;
307         int ret;
308
309         fu->flags &= ~USBG_BOT_CMD_PEND;
310
311         if (req->status < 0)
312                 return;
313
314         ret = bot_submit_command(fu, req->buf, req->actual);
315         if (ret)
316                 pr_err("%s(%d): %d\n", __func__, __LINE__, ret);
317 }
318
319 static int bot_prepare_reqs(struct f_uas *fu)
320 {
321         int ret;
322
323         fu->bot_req_in = usb_ep_alloc_request(fu->ep_in, GFP_KERNEL);
324         if (!fu->bot_req_in)
325                 goto err;
326
327         fu->bot_req_out = usb_ep_alloc_request(fu->ep_out, GFP_KERNEL);
328         if (!fu->bot_req_out)
329                 goto err_out;
330
331         fu->cmd.req = usb_ep_alloc_request(fu->ep_out, GFP_KERNEL);
332         if (!fu->cmd.req)
333                 goto err_cmd;
334
335         fu->bot_status.req = usb_ep_alloc_request(fu->ep_in, GFP_KERNEL);
336         if (!fu->bot_status.req)
337                 goto err_sts;
338
339         fu->bot_status.req->buf = &fu->bot_status.csw;
340         fu->bot_status.req->length = US_BULK_CS_WRAP_LEN;
341         fu->bot_status.req->complete = bot_status_complete;
342         fu->bot_status.csw.Signature = cpu_to_le32(US_BULK_CS_SIGN);
343
344         fu->cmd.buf = kmalloc(fu->ep_out->maxpacket, GFP_KERNEL);
345         if (!fu->cmd.buf)
346                 goto err_buf;
347
348         fu->cmd.req->complete = bot_cmd_complete;
349         fu->cmd.req->buf = fu->cmd.buf;
350         fu->cmd.req->length = fu->ep_out->maxpacket;
351         fu->cmd.req->context = fu;
352
353         ret = bot_enqueue_cmd_cbw(fu);
354         if (ret)
355                 goto err_queue;
356         return 0;
357 err_queue:
358         kfree(fu->cmd.buf);
359         fu->cmd.buf = NULL;
360 err_buf:
361         usb_ep_free_request(fu->ep_in, fu->bot_status.req);
362 err_sts:
363         usb_ep_free_request(fu->ep_out, fu->cmd.req);
364         fu->cmd.req = NULL;
365 err_cmd:
366         usb_ep_free_request(fu->ep_out, fu->bot_req_out);
367         fu->bot_req_out = NULL;
368 err_out:
369         usb_ep_free_request(fu->ep_in, fu->bot_req_in);
370         fu->bot_req_in = NULL;
371 err:
372         pr_err("BOT: endpoint setup failed\n");
373         return -ENOMEM;
374 }
375
376 void bot_cleanup_old_alt(struct f_uas *fu)
377 {
378         if (!(fu->flags & USBG_ENABLED))
379                 return;
380
381         usb_ep_disable(fu->ep_in);
382         usb_ep_disable(fu->ep_out);
383
384         if (!fu->bot_req_in)
385                 return;
386
387         usb_ep_free_request(fu->ep_in, fu->bot_req_in);
388         usb_ep_free_request(fu->ep_out, fu->bot_req_out);
389         usb_ep_free_request(fu->ep_out, fu->cmd.req);
390         usb_ep_free_request(fu->ep_out, fu->bot_status.req);
391
392         kfree(fu->cmd.buf);
393
394         fu->bot_req_in = NULL;
395         fu->bot_req_out = NULL;
396         fu->cmd.req = NULL;
397         fu->bot_status.req = NULL;
398         fu->cmd.buf = NULL;
399 }
400
401 static void bot_set_alt(struct f_uas *fu)
402 {
403         struct usb_function *f = &fu->function;
404         struct usb_gadget *gadget = f->config->cdev->gadget;
405         int ret;
406
407         fu->flags = USBG_IS_BOT;
408
409         config_ep_by_speed(gadget, f, fu->ep_in);
410         ret = usb_ep_enable(fu->ep_in);
411         if (ret)
412                 goto err_b_in;
413
414         config_ep_by_speed(gadget, f, fu->ep_out);
415         ret = usb_ep_enable(fu->ep_out);
416         if (ret)
417                 goto err_b_out;
418
419         ret = bot_prepare_reqs(fu);
420         if (ret)
421                 goto err_wq;
422         fu->flags |= USBG_ENABLED;
423         pr_info("Using the BOT protocol\n");
424         return;
425 err_wq:
426         usb_ep_disable(fu->ep_out);
427 err_b_out:
428         usb_ep_disable(fu->ep_in);
429 err_b_in:
430         fu->flags = USBG_IS_BOT;
431 }
432
433 static int usbg_bot_setup(struct usb_function *f,
434                 const struct usb_ctrlrequest *ctrl)
435 {
436         struct f_uas *fu = to_f_uas(f);
437         struct usb_composite_dev *cdev = f->config->cdev;
438         u16 w_value = le16_to_cpu(ctrl->wValue);
439         u16 w_length = le16_to_cpu(ctrl->wLength);
440         int luns;
441         u8 *ret_lun;
442
443         switch (ctrl->bRequest) {
444         case US_BULK_GET_MAX_LUN:
445                 if (ctrl->bRequestType != (USB_DIR_IN | USB_TYPE_CLASS |
446                                         USB_RECIP_INTERFACE))
447                         return -ENOTSUPP;
448
449                 if (w_length < 1)
450                         return -EINVAL;
451                 if (w_value != 0)
452                         return -EINVAL;
453                 luns = atomic_read(&fu->tpg->tpg_port_count);
454                 if (!luns) {
455                         pr_err("No LUNs configured?\n");
456                         return -EINVAL;
457                 }
458                 /*
459                  * If 4 LUNs are present we return 3 i.e. LUN 0..3 can be
460                  * accessed. The upper limit is 0xf
461                  */
462                 luns--;
463                 if (luns > 0xf) {
464                         pr_info_once("Limiting the number of luns to 16\n");
465                         luns = 0xf;
466                 }
467                 ret_lun = cdev->req->buf;
468                 *ret_lun = luns;
469                 cdev->req->length = 1;
470                 return usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
471                 break;
472
473         case US_BULK_RESET_REQUEST:
474                 /* XXX maybe we should remove previous requests for IN + OUT */
475                 bot_enqueue_cmd_cbw(fu);
476                 return 0;
477                 break;
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:
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                 pr_warn("target: Unknown data direction for SCSI Opcode "
961                                 "0x%02x\n", cdb[0]);
962                 ret = -EINVAL;
963         }
964         return ret;
965 }
966
967 static void usbg_data_write_cmpl(struct usb_ep *ep, struct usb_request *req)
968 {
969         struct usbg_cmd *cmd = req->context;
970         struct se_cmd *se_cmd = &cmd->se_cmd;
971
972         if (req->status < 0) {
973                 pr_err("%s() state %d transfer failed\n", __func__, cmd->state);
974                 goto cleanup;
975         }
976
977         if (req->num_sgs == 0) {
978                 sg_copy_from_buffer(se_cmd->t_data_sg,
979                                 se_cmd->t_data_nents,
980                                 cmd->data_buf,
981                                 se_cmd->data_length);
982         }
983
984         complete(&cmd->write_complete);
985         return;
986
987 cleanup:
988         usbg_cleanup_cmd(cmd);
989 }
990
991 static int usbg_prepare_w_request(struct usbg_cmd *cmd, struct usb_request *req)
992 {
993         struct se_cmd *se_cmd = &cmd->se_cmd;
994         struct f_uas *fu = cmd->fu;
995         struct usb_gadget *gadget = fuas_to_gadget(fu);
996
997         if (!gadget->sg_supported) {
998                 cmd->data_buf = kmalloc(se_cmd->data_length, GFP_ATOMIC);
999                 if (!cmd->data_buf)
1000                         return -ENOMEM;
1001
1002                 req->buf = cmd->data_buf;
1003         } else {
1004                 req->buf = NULL;
1005                 req->num_sgs = se_cmd->t_data_nents;
1006                 req->sg = se_cmd->t_data_sg;
1007         }
1008
1009         req->complete = usbg_data_write_cmpl;
1010         req->length = se_cmd->data_length;
1011         req->context = cmd;
1012         return 0;
1013 }
1014
1015 static int usbg_send_status_response(struct se_cmd *se_cmd)
1016 {
1017         struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1018                         se_cmd);
1019         struct f_uas *fu = cmd->fu;
1020
1021         if (fu->flags & USBG_IS_BOT)
1022                 return bot_send_status_response(cmd);
1023         else
1024                 return uasp_send_status_response(cmd);
1025 }
1026
1027 static int usbg_send_write_request(struct se_cmd *se_cmd)
1028 {
1029         struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1030                         se_cmd);
1031         struct f_uas *fu = cmd->fu;
1032
1033         if (fu->flags & USBG_IS_BOT)
1034                 return bot_send_write_request(cmd);
1035         else
1036                 return uasp_send_write_request(cmd);
1037 }
1038
1039 static int usbg_send_read_response(struct se_cmd *se_cmd)
1040 {
1041         struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1042                         se_cmd);
1043         struct f_uas *fu = cmd->fu;
1044
1045         if (fu->flags & USBG_IS_BOT)
1046                 return bot_send_read_response(cmd);
1047         else
1048                 return uasp_send_read_response(cmd);
1049 }
1050
1051 static void usbg_cmd_work(struct work_struct *work)
1052 {
1053         struct usbg_cmd *cmd = container_of(work, struct usbg_cmd, work);
1054         struct se_cmd *se_cmd;
1055         struct tcm_usbg_nexus *tv_nexus;
1056         struct usbg_tpg *tpg;
1057         int dir;
1058
1059         se_cmd = &cmd->se_cmd;
1060         tpg = cmd->fu->tpg;
1061         tv_nexus = tpg->tpg_nexus;
1062         dir = get_cmd_dir(cmd->cmd_buf);
1063         if (dir < 0) {
1064                 transport_init_se_cmd(se_cmd,
1065                                 tv_nexus->tvn_se_sess->se_tpg->se_tpg_tfo,
1066                                 tv_nexus->tvn_se_sess, cmd->data_len, DMA_NONE,
1067                                 cmd->prio_attr, cmd->sense_iu.sense);
1068                 goto out;
1069         }
1070
1071         if (target_submit_cmd(se_cmd, tv_nexus->tvn_se_sess,
1072                         cmd->cmd_buf, cmd->sense_iu.sense, cmd->unpacked_lun,
1073                         0, cmd->prio_attr, dir, TARGET_SCF_UNKNOWN_SIZE) < 0)
1074                 goto out;
1075
1076         return;
1077
1078 out:
1079         transport_send_check_condition_and_sense(se_cmd,
1080                         TCM_UNSUPPORTED_SCSI_OPCODE, 1);
1081         usbg_cleanup_cmd(cmd);
1082 }
1083
1084 static int usbg_submit_command(struct f_uas *fu,
1085                 void *cmdbuf, unsigned int len)
1086 {
1087         struct command_iu *cmd_iu = cmdbuf;
1088         struct usbg_cmd *cmd;
1089         struct usbg_tpg *tpg;
1090         struct se_cmd *se_cmd;
1091         struct tcm_usbg_nexus *tv_nexus;
1092         u32 cmd_len;
1093         int ret;
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         if (fu->flags & USBG_USE_STREAMS) {
1119                 if (cmd->tag > UASP_SS_EP_COMP_NUM_STREAMS)
1120                         goto err;
1121                 if (!cmd->tag)
1122                         cmd->stream = &fu->stream[0];
1123                 else
1124                         cmd->stream = &fu->stream[cmd->tag - 1];
1125         } else {
1126                 cmd->stream = &fu->stream[0];
1127         }
1128
1129         tv_nexus = tpg->tpg_nexus;
1130         if (!tv_nexus) {
1131                 pr_err("Missing nexus, ignoring command\n");
1132                 goto err;
1133         }
1134
1135         switch (cmd_iu->prio_attr & 0x7) {
1136         case UAS_HEAD_TAG:
1137                 cmd->prio_attr = MSG_HEAD_TAG;
1138                 break;
1139         case UAS_ORDERED_TAG:
1140                 cmd->prio_attr = MSG_ORDERED_TAG;
1141                 break;
1142         case UAS_ACA:
1143                 cmd->prio_attr = MSG_ACA_TAG;
1144                 break;
1145         default:
1146                 pr_debug_once("Unsupported prio_attr: %02x.\n",
1147                                 cmd_iu->prio_attr);
1148         case UAS_SIMPLE_TAG:
1149                 cmd->prio_attr = MSG_SIMPLE_TAG;
1150                 break;
1151         }
1152
1153         se_cmd = &cmd->se_cmd;
1154         cmd->unpacked_lun = scsilun_to_int(&cmd_iu->lun);
1155
1156         INIT_WORK(&cmd->work, usbg_cmd_work);
1157         ret = queue_work(tpg->workqueue, &cmd->work);
1158         if (ret < 0)
1159                 goto err;
1160
1161         return 0;
1162 err:
1163         kfree(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         usbg_cleanup_cmd(cmd);
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;
1206         struct se_cmd *se_cmd;
1207         struct tcm_usbg_nexus *tv_nexus;
1208         u32 cmd_len;
1209         int ret;
1210
1211         if (cbw->Signature != cpu_to_le32(US_BULK_CB_SIGN)) {
1212                 pr_err("Wrong signature on CBW\n");
1213                 return -EINVAL;
1214         }
1215         if (len != 31) {
1216                 pr_err("Wrong length for CBW\n");
1217                 return -EINVAL;
1218         }
1219
1220         cmd_len = cbw->Length;
1221         if (cmd_len < 1 || cmd_len > 16)
1222                 return -EINVAL;
1223
1224         cmd = kzalloc(sizeof *cmd, GFP_ATOMIC);
1225         if (!cmd)
1226                 return -ENOMEM;
1227
1228         cmd->fu = fu;
1229
1230         /* XXX until I figure out why I can't free in on complete */
1231         kref_init(&cmd->ref);
1232         kref_get(&cmd->ref);
1233
1234         tpg = fu->tpg;
1235
1236         memcpy(cmd->cmd_buf, cbw->CDB, cmd_len);
1237
1238         cmd->bot_tag = cbw->Tag;
1239
1240         tv_nexus = tpg->tpg_nexus;
1241         if (!tv_nexus) {
1242                 pr_err("Missing nexus, ignoring command\n");
1243                 goto err;
1244         }
1245
1246         cmd->prio_attr = MSG_SIMPLE_TAG;
1247         se_cmd = &cmd->se_cmd;
1248         cmd->unpacked_lun = cbw->Lun;
1249         cmd->is_read = cbw->Flags & US_BULK_FLAG_IN ? 1 : 0;
1250         cmd->data_len = le32_to_cpu(cbw->DataTransferLength);
1251
1252         INIT_WORK(&cmd->work, bot_cmd_work);
1253         ret = queue_work(tpg->workqueue, &cmd->work);
1254         if (ret < 0)
1255                 goto err;
1256
1257         return 0;
1258 err:
1259         kfree(cmd);
1260         return -EINVAL;
1261 }
1262
1263 /* Start fabric.c code */
1264
1265 static int usbg_check_true(struct se_portal_group *se_tpg)
1266 {
1267         return 1;
1268 }
1269
1270 static int usbg_check_false(struct se_portal_group *se_tpg)
1271 {
1272         return 0;
1273 }
1274
1275 static char *usbg_get_fabric_name(void)
1276 {
1277         return "usb_gadget";
1278 }
1279
1280 static u8 usbg_get_fabric_proto_ident(struct se_portal_group *se_tpg)
1281 {
1282         struct usbg_tpg *tpg = container_of(se_tpg,
1283                                 struct usbg_tpg, se_tpg);
1284         struct usbg_tport *tport = tpg->tport;
1285         u8 proto_id;
1286
1287         switch (tport->tport_proto_id) {
1288         case SCSI_PROTOCOL_SAS:
1289         default:
1290                 proto_id = sas_get_fabric_proto_ident(se_tpg);
1291                 break;
1292         }
1293
1294         return proto_id;
1295 }
1296
1297 static char *usbg_get_fabric_wwn(struct se_portal_group *se_tpg)
1298 {
1299         struct usbg_tpg *tpg = container_of(se_tpg,
1300                                 struct usbg_tpg, se_tpg);
1301         struct usbg_tport *tport = tpg->tport;
1302
1303         return &tport->tport_name[0];
1304 }
1305
1306 static u16 usbg_get_tag(struct se_portal_group *se_tpg)
1307 {
1308         struct usbg_tpg *tpg = container_of(se_tpg,
1309                                 struct usbg_tpg, se_tpg);
1310         return tpg->tport_tpgt;
1311 }
1312
1313 static u32 usbg_get_default_depth(struct se_portal_group *se_tpg)
1314 {
1315         return 1;
1316 }
1317
1318 static u32 usbg_get_pr_transport_id(
1319         struct se_portal_group *se_tpg,
1320         struct se_node_acl *se_nacl,
1321         struct t10_pr_registration *pr_reg,
1322         int *format_code,
1323         unsigned char *buf)
1324 {
1325         struct usbg_tpg *tpg = container_of(se_tpg,
1326                                 struct usbg_tpg, se_tpg);
1327         struct usbg_tport *tport = tpg->tport;
1328         int ret = 0;
1329
1330         switch (tport->tport_proto_id) {
1331         case SCSI_PROTOCOL_SAS:
1332         default:
1333                 ret = sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,
1334                                         format_code, buf);
1335                 break;
1336         }
1337
1338         return ret;
1339 }
1340
1341 static u32 usbg_get_pr_transport_id_len(
1342         struct se_portal_group *se_tpg,
1343         struct se_node_acl *se_nacl,
1344         struct t10_pr_registration *pr_reg,
1345         int *format_code)
1346 {
1347         struct usbg_tpg *tpg = container_of(se_tpg,
1348                                 struct usbg_tpg, se_tpg);
1349         struct usbg_tport *tport = tpg->tport;
1350         int ret = 0;
1351
1352         switch (tport->tport_proto_id) {
1353         case SCSI_PROTOCOL_SAS:
1354         default:
1355                 ret = sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,
1356                                         format_code);
1357                 break;
1358         }
1359
1360         return ret;
1361 }
1362
1363 static char *usbg_parse_pr_out_transport_id(
1364         struct se_portal_group *se_tpg,
1365         const char *buf,
1366         u32 *out_tid_len,
1367         char **port_nexus_ptr)
1368 {
1369         struct usbg_tpg *tpg = container_of(se_tpg,
1370                                 struct usbg_tpg, se_tpg);
1371         struct usbg_tport *tport = tpg->tport;
1372         char *tid = NULL;
1373
1374         switch (tport->tport_proto_id) {
1375         case SCSI_PROTOCOL_SAS:
1376         default:
1377                 tid = sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,
1378                                         port_nexus_ptr);
1379         }
1380
1381         return tid;
1382 }
1383
1384 static struct se_node_acl *usbg_alloc_fabric_acl(struct se_portal_group *se_tpg)
1385 {
1386         struct usbg_nacl *nacl;
1387
1388         nacl = kzalloc(sizeof(struct usbg_nacl), GFP_KERNEL);
1389         if (!nacl) {
1390                 printk(KERN_ERR "Unable to alocate struct usbg_nacl\n");
1391                 return NULL;
1392         }
1393
1394         return &nacl->se_node_acl;
1395 }
1396
1397 static void usbg_release_fabric_acl(
1398         struct se_portal_group *se_tpg,
1399         struct se_node_acl *se_nacl)
1400 {
1401         struct usbg_nacl *nacl = container_of(se_nacl,
1402                         struct usbg_nacl, se_node_acl);
1403         kfree(nacl);
1404 }
1405
1406 static u32 usbg_tpg_get_inst_index(struct se_portal_group *se_tpg)
1407 {
1408         return 1;
1409 }
1410
1411 static void usbg_cmd_release(struct kref *ref)
1412 {
1413         struct usbg_cmd *cmd = container_of(ref, struct usbg_cmd,
1414                         ref);
1415
1416         transport_generic_free_cmd(&cmd->se_cmd, 0);
1417 }
1418
1419 static void usbg_release_cmd(struct se_cmd *se_cmd)
1420 {
1421         struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1422                         se_cmd);
1423         kfree(cmd->data_buf);
1424         kfree(cmd);
1425         return;
1426 }
1427
1428 static int usbg_shutdown_session(struct se_session *se_sess)
1429 {
1430         return 0;
1431 }
1432
1433 static void usbg_close_session(struct se_session *se_sess)
1434 {
1435         return;
1436 }
1437
1438 static u32 usbg_sess_get_index(struct se_session *se_sess)
1439 {
1440         return 0;
1441 }
1442
1443 /*
1444  * XXX Error recovery: return != 0 if we expect writes. Dunno when that could be
1445  */
1446 static int usbg_write_pending_status(struct se_cmd *se_cmd)
1447 {
1448         return 0;
1449 }
1450
1451 static void usbg_set_default_node_attrs(struct se_node_acl *nacl)
1452 {
1453         return;
1454 }
1455
1456 static u32 usbg_get_task_tag(struct se_cmd *se_cmd)
1457 {
1458         struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1459                         se_cmd);
1460         struct f_uas *fu = cmd->fu;
1461
1462         if (fu->flags & USBG_IS_BOT)
1463                 return le32_to_cpu(cmd->bot_tag);
1464         else
1465                 return cmd->tag;
1466 }
1467
1468 static int usbg_get_cmd_state(struct se_cmd *se_cmd)
1469 {
1470         return 0;
1471 }
1472
1473 static int usbg_queue_tm_rsp(struct se_cmd *se_cmd)
1474 {
1475         return 0;
1476 }
1477
1478 static u16 usbg_set_fabric_sense_len(struct se_cmd *se_cmd, u32 sense_length)
1479 {
1480         return 0;
1481 }
1482
1483 static const char *usbg_check_wwn(const char *name)
1484 {
1485         const char *n;
1486         unsigned int len;
1487
1488         n = strstr(name, "naa.");
1489         if (!n)
1490                 return NULL;
1491         n += 4;
1492         len = strlen(n);
1493         if (len == 0 || len > USBG_NAMELEN - 1)
1494                 return NULL;
1495         return n;
1496 }
1497
1498 static struct se_node_acl *usbg_make_nodeacl(
1499         struct se_portal_group *se_tpg,
1500         struct config_group *group,
1501         const char *name)
1502 {
1503         struct se_node_acl *se_nacl, *se_nacl_new;
1504         struct usbg_nacl *nacl;
1505         u64 wwpn = 0;
1506         u32 nexus_depth;
1507         const char *wnn_name;
1508
1509         wnn_name = usbg_check_wwn(name);
1510         if (!wnn_name)
1511                 return ERR_PTR(-EINVAL);
1512         se_nacl_new = usbg_alloc_fabric_acl(se_tpg);
1513         if (!(se_nacl_new))
1514                 return ERR_PTR(-ENOMEM);
1515
1516         nexus_depth = 1;
1517         /*
1518          * se_nacl_new may be released by core_tpg_add_initiator_node_acl()
1519          * when converting a NodeACL from demo mode -> explict
1520          */
1521         se_nacl = core_tpg_add_initiator_node_acl(se_tpg, se_nacl_new,
1522                                 name, nexus_depth);
1523         if (IS_ERR(se_nacl)) {
1524                 usbg_release_fabric_acl(se_tpg, se_nacl_new);
1525                 return se_nacl;
1526         }
1527         /*
1528          * Locate our struct usbg_nacl and set the FC Nport WWPN
1529          */
1530         nacl = container_of(se_nacl, struct usbg_nacl, se_node_acl);
1531         nacl->iport_wwpn = wwpn;
1532         snprintf(nacl->iport_name, sizeof(nacl->iport_name), "%s", name);
1533         return se_nacl;
1534 }
1535
1536 static void usbg_drop_nodeacl(struct se_node_acl *se_acl)
1537 {
1538         struct usbg_nacl *nacl = container_of(se_acl,
1539                                 struct usbg_nacl, se_node_acl);
1540         core_tpg_del_initiator_node_acl(se_acl->se_tpg, se_acl, 1);
1541         kfree(nacl);
1542 }
1543
1544 struct usbg_tpg *the_only_tpg_I_currently_have;
1545
1546 static struct se_portal_group *usbg_make_tpg(
1547         struct se_wwn *wwn,
1548         struct config_group *group,
1549         const char *name)
1550 {
1551         struct usbg_tport *tport = container_of(wwn, struct usbg_tport,
1552                         tport_wwn);
1553         struct usbg_tpg *tpg;
1554         unsigned long tpgt;
1555         int ret;
1556
1557         if (strstr(name, "tpgt_") != name)
1558                 return ERR_PTR(-EINVAL);
1559         if (kstrtoul(name + 5, 0, &tpgt) || tpgt > UINT_MAX)
1560                 return ERR_PTR(-EINVAL);
1561         if (the_only_tpg_I_currently_have) {
1562                 pr_err("Until the gadget framework can't handle multiple\n");
1563                 pr_err("gadgets, you can't do this here.\n");
1564                 return ERR_PTR(-EBUSY);
1565         }
1566
1567         tpg = kzalloc(sizeof(struct usbg_tpg), GFP_KERNEL);
1568         if (!tpg) {
1569                 printk(KERN_ERR "Unable to allocate struct usbg_tpg");
1570                 return ERR_PTR(-ENOMEM);
1571         }
1572         mutex_init(&tpg->tpg_mutex);
1573         atomic_set(&tpg->tpg_port_count, 0);
1574         tpg->workqueue = alloc_workqueue("tcm_usb_gadget", 0, 1);
1575         if (!tpg->workqueue) {
1576                 kfree(tpg);
1577                 return NULL;
1578         }
1579
1580         tpg->tport = tport;
1581         tpg->tport_tpgt = tpgt;
1582
1583         ret = core_tpg_register(&usbg_fabric_configfs->tf_ops, wwn,
1584                                 &tpg->se_tpg, tpg,
1585                                 TRANSPORT_TPG_TYPE_NORMAL);
1586         if (ret < 0) {
1587                 destroy_workqueue(tpg->workqueue);
1588                 kfree(tpg);
1589                 return NULL;
1590         }
1591         the_only_tpg_I_currently_have = tpg;
1592         return &tpg->se_tpg;
1593 }
1594
1595 static void usbg_drop_tpg(struct se_portal_group *se_tpg)
1596 {
1597         struct usbg_tpg *tpg = container_of(se_tpg,
1598                                 struct usbg_tpg, se_tpg);
1599
1600         core_tpg_deregister(se_tpg);
1601         destroy_workqueue(tpg->workqueue);
1602         kfree(tpg);
1603         the_only_tpg_I_currently_have = NULL;
1604 }
1605
1606 static struct se_wwn *usbg_make_tport(
1607         struct target_fabric_configfs *tf,
1608         struct config_group *group,
1609         const char *name)
1610 {
1611         struct usbg_tport *tport;
1612         const char *wnn_name;
1613         u64 wwpn = 0;
1614
1615         wnn_name = usbg_check_wwn(name);
1616         if (!wnn_name)
1617                 return ERR_PTR(-EINVAL);
1618
1619         tport = kzalloc(sizeof(struct usbg_tport), GFP_KERNEL);
1620         if (!(tport)) {
1621                 printk(KERN_ERR "Unable to allocate struct usbg_tport");
1622                 return ERR_PTR(-ENOMEM);
1623         }
1624         tport->tport_wwpn = wwpn;
1625         snprintf(tport->tport_name, sizeof(tport->tport_name), wnn_name);
1626         return &tport->tport_wwn;
1627 }
1628
1629 static void usbg_drop_tport(struct se_wwn *wwn)
1630 {
1631         struct usbg_tport *tport = container_of(wwn,
1632                                 struct usbg_tport, tport_wwn);
1633         kfree(tport);
1634 }
1635
1636 /*
1637  * If somebody feels like dropping the version property, go ahead.
1638  */
1639 static ssize_t usbg_wwn_show_attr_version(
1640         struct target_fabric_configfs *tf,
1641         char *page)
1642 {
1643         return sprintf(page, "usb-gadget fabric module\n");
1644 }
1645 TF_WWN_ATTR_RO(usbg, version);
1646
1647 static struct configfs_attribute *usbg_wwn_attrs[] = {
1648         &usbg_wwn_version.attr,
1649         NULL,
1650 };
1651
1652 static ssize_t tcm_usbg_tpg_show_enable(
1653                 struct se_portal_group *se_tpg,
1654                 char *page)
1655 {
1656         struct usbg_tpg  *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1657
1658         return snprintf(page, PAGE_SIZE, "%u\n", tpg->gadget_connect);
1659 }
1660
1661 static int usbg_attach(struct usbg_tpg *);
1662 static void usbg_detach(struct usbg_tpg *);
1663
1664 static ssize_t tcm_usbg_tpg_store_enable(
1665                 struct se_portal_group *se_tpg,
1666                 const char *page,
1667                 size_t count)
1668 {
1669         struct usbg_tpg  *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1670         unsigned long op;
1671         ssize_t ret;
1672
1673         ret = kstrtoul(page, 0, &op);
1674         if (ret < 0)
1675                 return -EINVAL;
1676         if (op > 1)
1677                 return -EINVAL;
1678
1679         if (op && tpg->gadget_connect)
1680                 goto out;
1681         if (!op && !tpg->gadget_connect)
1682                 goto out;
1683
1684         if (op) {
1685                 ret = usbg_attach(tpg);
1686                 if (ret)
1687                         goto out;
1688         } else {
1689                 usbg_detach(tpg);
1690         }
1691         tpg->gadget_connect = op;
1692 out:
1693         return count;
1694 }
1695 TF_TPG_BASE_ATTR(tcm_usbg, enable, S_IRUGO | S_IWUSR);
1696
1697 static ssize_t tcm_usbg_tpg_show_nexus(
1698                 struct se_portal_group *se_tpg,
1699                 char *page)
1700 {
1701         struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1702         struct tcm_usbg_nexus *tv_nexus;
1703         ssize_t ret;
1704
1705         mutex_lock(&tpg->tpg_mutex);
1706         tv_nexus = tpg->tpg_nexus;
1707         if (!tv_nexus) {
1708                 ret = -ENODEV;
1709                 goto out;
1710         }
1711         ret = snprintf(page, PAGE_SIZE, "%s\n",
1712                         tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1713 out:
1714         mutex_unlock(&tpg->tpg_mutex);
1715         return ret;
1716 }
1717
1718 static int tcm_usbg_make_nexus(struct usbg_tpg *tpg, char *name)
1719 {
1720         struct se_portal_group *se_tpg;
1721         struct tcm_usbg_nexus *tv_nexus;
1722         int ret;
1723
1724         mutex_lock(&tpg->tpg_mutex);
1725         if (tpg->tpg_nexus) {
1726                 ret = -EEXIST;
1727                 pr_debug("tpg->tpg_nexus already exists\n");
1728                 goto err_unlock;
1729         }
1730         se_tpg = &tpg->se_tpg;
1731
1732         ret = -ENOMEM;
1733         tv_nexus = kzalloc(sizeof(*tv_nexus), GFP_KERNEL);
1734         if (!tv_nexus) {
1735                 pr_err("Unable to allocate struct tcm_vhost_nexus\n");
1736                 goto err_unlock;
1737         }
1738         tv_nexus->tvn_se_sess = transport_init_session();
1739         if (IS_ERR(tv_nexus->tvn_se_sess))
1740                 goto err_free;
1741
1742         /*
1743          * Since we are running in 'demo mode' this call with generate a
1744          * struct se_node_acl for the tcm_vhost struct se_portal_group with
1745          * the SCSI Initiator port name of the passed configfs group 'name'.
1746          */
1747         tv_nexus->tvn_se_sess->se_node_acl = core_tpg_check_initiator_node_acl(
1748                         se_tpg, name);
1749         if (!tv_nexus->tvn_se_sess->se_node_acl) {
1750                 pr_debug("core_tpg_check_initiator_node_acl() failed"
1751                                 " for %s\n", name);
1752                 goto err_session;
1753         }
1754         /*
1755          * Now register the TCM vHost virtual I_T Nexus as active with the
1756          * call to __transport_register_session()
1757          */
1758         __transport_register_session(se_tpg, tv_nexus->tvn_se_sess->se_node_acl,
1759                         tv_nexus->tvn_se_sess, tv_nexus);
1760         tpg->tpg_nexus = tv_nexus;
1761         mutex_unlock(&tpg->tpg_mutex);
1762         return 0;
1763
1764 err_session:
1765         transport_free_session(tv_nexus->tvn_se_sess);
1766 err_free:
1767         kfree(tv_nexus);
1768 err_unlock:
1769         mutex_unlock(&tpg->tpg_mutex);
1770         return ret;
1771 }
1772
1773 static int tcm_usbg_drop_nexus(struct usbg_tpg *tpg)
1774 {
1775         struct se_session *se_sess;
1776         struct tcm_usbg_nexus *tv_nexus;
1777         int ret = -ENODEV;
1778
1779         mutex_lock(&tpg->tpg_mutex);
1780         tv_nexus = tpg->tpg_nexus;
1781         if (!tv_nexus)
1782                 goto out;
1783
1784         se_sess = tv_nexus->tvn_se_sess;
1785         if (!se_sess)
1786                 goto out;
1787
1788         if (atomic_read(&tpg->tpg_port_count)) {
1789                 ret = -EPERM;
1790                 pr_err("Unable to remove Host I_T Nexus with"
1791                                 " active TPG port count: %d\n",
1792                                 atomic_read(&tpg->tpg_port_count));
1793                 goto out;
1794         }
1795
1796         pr_debug("Removing I_T Nexus to Initiator Port: %s\n",
1797                         tv_nexus->tvn_se_sess->se_node_acl->initiatorname);
1798         /*
1799          * Release the SCSI I_T Nexus to the emulated vHost Target Port
1800          */
1801         transport_deregister_session(tv_nexus->tvn_se_sess);
1802         tpg->tpg_nexus = NULL;
1803
1804         kfree(tv_nexus);
1805 out:
1806         mutex_unlock(&tpg->tpg_mutex);
1807         return 0;
1808 }
1809
1810 static ssize_t tcm_usbg_tpg_store_nexus(
1811                 struct se_portal_group *se_tpg,
1812                 const char *page,
1813                 size_t count)
1814 {
1815         struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1816         unsigned char i_port[USBG_NAMELEN], *ptr;
1817         int ret;
1818
1819         if (!strncmp(page, "NULL", 4)) {
1820                 ret = tcm_usbg_drop_nexus(tpg);
1821                 return (!ret) ? count : ret;
1822         }
1823         if (strlen(page) > USBG_NAMELEN) {
1824                 pr_err("Emulated NAA Sas Address: %s, exceeds"
1825                                 " max: %d\n", page, USBG_NAMELEN);
1826                 return -EINVAL;
1827         }
1828         snprintf(i_port, USBG_NAMELEN, "%s", page);
1829
1830         ptr = strstr(i_port, "naa.");
1831         if (!ptr) {
1832                 pr_err("Missing 'naa.' prefix\n");
1833                 return -EINVAL;
1834         }
1835
1836         if (i_port[strlen(i_port) - 1] == '\n')
1837                 i_port[strlen(i_port) - 1] = '\0';
1838
1839         ret = tcm_usbg_make_nexus(tpg, &i_port[4]);
1840         if (ret < 0)
1841                 return ret;
1842         return count;
1843 }
1844 TF_TPG_BASE_ATTR(tcm_usbg, nexus, S_IRUGO | S_IWUSR);
1845
1846 static struct configfs_attribute *usbg_base_attrs[] = {
1847         &tcm_usbg_tpg_enable.attr,
1848         &tcm_usbg_tpg_nexus.attr,
1849         NULL,
1850 };
1851
1852 static int usbg_port_link(struct se_portal_group *se_tpg, struct se_lun *lun)
1853 {
1854         struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1855
1856         atomic_inc(&tpg->tpg_port_count);
1857         smp_mb__after_atomic_inc();
1858         return 0;
1859 }
1860
1861 static void usbg_port_unlink(struct se_portal_group *se_tpg,
1862                 struct se_lun *se_lun)
1863 {
1864         struct usbg_tpg *tpg = container_of(se_tpg, struct usbg_tpg, se_tpg);
1865
1866         atomic_dec(&tpg->tpg_port_count);
1867         smp_mb__after_atomic_dec();
1868 }
1869
1870 static int usbg_check_stop_free(struct se_cmd *se_cmd)
1871 {
1872         struct usbg_cmd *cmd = container_of(se_cmd, struct usbg_cmd,
1873                         se_cmd);
1874
1875         kref_put(&cmd->ref, usbg_cmd_release);
1876         return 1;
1877 }
1878
1879 static struct target_core_fabric_ops usbg_ops = {
1880         .get_fabric_name                = usbg_get_fabric_name,
1881         .get_fabric_proto_ident         = usbg_get_fabric_proto_ident,
1882         .tpg_get_wwn                    = usbg_get_fabric_wwn,
1883         .tpg_get_tag                    = usbg_get_tag,
1884         .tpg_get_default_depth          = usbg_get_default_depth,
1885         .tpg_get_pr_transport_id        = usbg_get_pr_transport_id,
1886         .tpg_get_pr_transport_id_len    = usbg_get_pr_transport_id_len,
1887         .tpg_parse_pr_out_transport_id  = usbg_parse_pr_out_transport_id,
1888         .tpg_check_demo_mode            = usbg_check_true,
1889         .tpg_check_demo_mode_cache      = usbg_check_false,
1890         .tpg_check_demo_mode_write_protect = usbg_check_false,
1891         .tpg_check_prod_mode_write_protect = usbg_check_false,
1892         .tpg_alloc_fabric_acl           = usbg_alloc_fabric_acl,
1893         .tpg_release_fabric_acl         = usbg_release_fabric_acl,
1894         .tpg_get_inst_index             = usbg_tpg_get_inst_index,
1895         .release_cmd                    = usbg_release_cmd,
1896         .shutdown_session               = usbg_shutdown_session,
1897         .close_session                  = usbg_close_session,
1898         .sess_get_index                 = usbg_sess_get_index,
1899         .sess_get_initiator_sid         = NULL,
1900         .write_pending                  = usbg_send_write_request,
1901         .write_pending_status           = usbg_write_pending_status,
1902         .set_default_node_attributes    = usbg_set_default_node_attrs,
1903         .get_task_tag                   = usbg_get_task_tag,
1904         .get_cmd_state                  = usbg_get_cmd_state,
1905         .queue_data_in                  = usbg_send_read_response,
1906         .queue_status                   = usbg_send_status_response,
1907         .queue_tm_rsp                   = usbg_queue_tm_rsp,
1908         .set_fabric_sense_len           = usbg_set_fabric_sense_len,
1909         .check_stop_free                = usbg_check_stop_free,
1910
1911         .fabric_make_wwn                = usbg_make_tport,
1912         .fabric_drop_wwn                = usbg_drop_tport,
1913         .fabric_make_tpg                = usbg_make_tpg,
1914         .fabric_drop_tpg                = usbg_drop_tpg,
1915         .fabric_post_link               = usbg_port_link,
1916         .fabric_pre_unlink              = usbg_port_unlink,
1917         .fabric_make_np                 = NULL,
1918         .fabric_drop_np                 = NULL,
1919         .fabric_make_nodeacl            = usbg_make_nodeacl,
1920         .fabric_drop_nodeacl            = usbg_drop_nodeacl,
1921 };
1922
1923 static int usbg_register_configfs(void)
1924 {
1925         struct target_fabric_configfs *fabric;
1926         int ret;
1927
1928         fabric = target_fabric_configfs_init(THIS_MODULE, "usb_gadget");
1929         if (IS_ERR(fabric)) {
1930                 printk(KERN_ERR "target_fabric_configfs_init() failed\n");
1931                 return PTR_ERR(fabric);
1932         }
1933
1934         fabric->tf_ops = usbg_ops;
1935         TF_CIT_TMPL(fabric)->tfc_wwn_cit.ct_attrs = usbg_wwn_attrs;
1936         TF_CIT_TMPL(fabric)->tfc_tpg_base_cit.ct_attrs = usbg_base_attrs;
1937         TF_CIT_TMPL(fabric)->tfc_tpg_attrib_cit.ct_attrs = NULL;
1938         TF_CIT_TMPL(fabric)->tfc_tpg_param_cit.ct_attrs = NULL;
1939         TF_CIT_TMPL(fabric)->tfc_tpg_np_base_cit.ct_attrs = NULL;
1940         TF_CIT_TMPL(fabric)->tfc_tpg_nacl_base_cit.ct_attrs = NULL;
1941         TF_CIT_TMPL(fabric)->tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;
1942         TF_CIT_TMPL(fabric)->tfc_tpg_nacl_auth_cit.ct_attrs = NULL;
1943         TF_CIT_TMPL(fabric)->tfc_tpg_nacl_param_cit.ct_attrs = NULL;
1944         ret = target_fabric_configfs_register(fabric);
1945         if (ret < 0) {
1946                 printk(KERN_ERR "target_fabric_configfs_register() failed"
1947                                 " for usb-gadget\n");
1948                 return ret;
1949         }
1950         usbg_fabric_configfs = fabric;
1951         return 0;
1952 };
1953
1954 static void usbg_deregister_configfs(void)
1955 {
1956         if (!(usbg_fabric_configfs))
1957                 return;
1958
1959         target_fabric_configfs_deregister(usbg_fabric_configfs);
1960         usbg_fabric_configfs = NULL;
1961 };
1962
1963 /* Start gadget.c code */
1964
1965 static struct usb_interface_descriptor bot_intf_desc = {
1966         .bLength =              sizeof(bot_intf_desc),
1967         .bDescriptorType =      USB_DT_INTERFACE,
1968         .bAlternateSetting =    0,
1969         .bNumEndpoints =        2,
1970         .bAlternateSetting =    USB_G_ALT_INT_BBB,
1971         .bInterfaceClass =      USB_CLASS_MASS_STORAGE,
1972         .bInterfaceSubClass =   USB_SC_SCSI,
1973         .bInterfaceProtocol =   USB_PR_BULK,
1974         .iInterface =           USB_G_STR_INT_UAS,
1975 };
1976
1977 static struct usb_interface_descriptor uasp_intf_desc = {
1978         .bLength =              sizeof(uasp_intf_desc),
1979         .bDescriptorType =      USB_DT_INTERFACE,
1980         .bNumEndpoints =        4,
1981         .bAlternateSetting =    USB_G_ALT_INT_UAS,
1982         .bInterfaceClass =      USB_CLASS_MASS_STORAGE,
1983         .bInterfaceSubClass =   USB_SC_SCSI,
1984         .bInterfaceProtocol =   USB_PR_UAS,
1985         .iInterface =           USB_G_STR_INT_BBB,
1986 };
1987
1988 static struct usb_endpoint_descriptor uasp_bi_desc = {
1989         .bLength =              USB_DT_ENDPOINT_SIZE,
1990         .bDescriptorType =      USB_DT_ENDPOINT,
1991         .bEndpointAddress =     USB_DIR_IN,
1992         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
1993         .wMaxPacketSize =       cpu_to_le16(512),
1994 };
1995
1996 static struct usb_endpoint_descriptor uasp_fs_bi_desc = {
1997         .bLength =              USB_DT_ENDPOINT_SIZE,
1998         .bDescriptorType =      USB_DT_ENDPOINT,
1999         .bEndpointAddress =     USB_DIR_IN,
2000         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2001 };
2002
2003 static struct usb_pipe_usage_descriptor uasp_bi_pipe_desc = {
2004         .bLength =              sizeof(uasp_bi_pipe_desc),
2005         .bDescriptorType =      USB_DT_PIPE_USAGE,
2006         .bPipeID =              DATA_IN_PIPE_ID,
2007 };
2008
2009 static struct usb_endpoint_descriptor uasp_ss_bi_desc = {
2010         .bLength =              USB_DT_ENDPOINT_SIZE,
2011         .bDescriptorType =      USB_DT_ENDPOINT,
2012         .bEndpointAddress =     USB_DIR_IN,
2013         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2014         .wMaxPacketSize =       cpu_to_le16(1024),
2015 };
2016
2017 static struct usb_ss_ep_comp_descriptor uasp_bi_ep_comp_desc = {
2018         .bLength =              sizeof(uasp_bi_ep_comp_desc),
2019         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
2020         .bMaxBurst =            0,
2021         .bmAttributes =         UASP_SS_EP_COMP_LOG_STREAMS,
2022         .wBytesPerInterval =    0,
2023 };
2024
2025 static struct usb_ss_ep_comp_descriptor bot_bi_ep_comp_desc = {
2026         .bLength =              sizeof(bot_bi_ep_comp_desc),
2027         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
2028         .bMaxBurst =            0,
2029 };
2030
2031 static struct usb_endpoint_descriptor uasp_bo_desc = {
2032         .bLength =              USB_DT_ENDPOINT_SIZE,
2033         .bDescriptorType =      USB_DT_ENDPOINT,
2034         .bEndpointAddress =     USB_DIR_OUT,
2035         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2036         .wMaxPacketSize =       cpu_to_le16(512),
2037 };
2038
2039 static struct usb_endpoint_descriptor uasp_fs_bo_desc = {
2040         .bLength =              USB_DT_ENDPOINT_SIZE,
2041         .bDescriptorType =      USB_DT_ENDPOINT,
2042         .bEndpointAddress =     USB_DIR_OUT,
2043         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2044 };
2045
2046 static struct usb_pipe_usage_descriptor uasp_bo_pipe_desc = {
2047         .bLength =              sizeof(uasp_bo_pipe_desc),
2048         .bDescriptorType =      USB_DT_PIPE_USAGE,
2049         .bPipeID =              DATA_OUT_PIPE_ID,
2050 };
2051
2052 static struct usb_endpoint_descriptor uasp_ss_bo_desc = {
2053         .bLength =              USB_DT_ENDPOINT_SIZE,
2054         .bDescriptorType =      USB_DT_ENDPOINT,
2055         .bEndpointAddress =     USB_DIR_OUT,
2056         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2057         .wMaxPacketSize =       cpu_to_le16(0x400),
2058 };
2059
2060 static struct usb_ss_ep_comp_descriptor uasp_bo_ep_comp_desc = {
2061         .bLength =              sizeof(uasp_bo_ep_comp_desc),
2062         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
2063         .bmAttributes =         UASP_SS_EP_COMP_LOG_STREAMS,
2064 };
2065
2066 static struct usb_ss_ep_comp_descriptor bot_bo_ep_comp_desc = {
2067         .bLength =              sizeof(bot_bo_ep_comp_desc),
2068         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
2069 };
2070
2071 static struct usb_endpoint_descriptor uasp_status_desc = {
2072         .bLength =              USB_DT_ENDPOINT_SIZE,
2073         .bDescriptorType =      USB_DT_ENDPOINT,
2074         .bEndpointAddress =     USB_DIR_IN,
2075         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2076         .wMaxPacketSize =       cpu_to_le16(512),
2077 };
2078
2079 static struct usb_endpoint_descriptor uasp_fs_status_desc = {
2080         .bLength =              USB_DT_ENDPOINT_SIZE,
2081         .bDescriptorType =      USB_DT_ENDPOINT,
2082         .bEndpointAddress =     USB_DIR_IN,
2083         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2084 };
2085
2086 static struct usb_pipe_usage_descriptor uasp_status_pipe_desc = {
2087         .bLength =              sizeof(uasp_status_pipe_desc),
2088         .bDescriptorType =      USB_DT_PIPE_USAGE,
2089         .bPipeID =              STATUS_PIPE_ID,
2090 };
2091
2092 static struct usb_endpoint_descriptor uasp_ss_status_desc = {
2093         .bLength =              USB_DT_ENDPOINT_SIZE,
2094         .bDescriptorType =      USB_DT_ENDPOINT,
2095         .bEndpointAddress =     USB_DIR_IN,
2096         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2097         .wMaxPacketSize =       cpu_to_le16(1024),
2098 };
2099
2100 static struct usb_ss_ep_comp_descriptor uasp_status_in_ep_comp_desc = {
2101         .bLength =              sizeof(uasp_status_in_ep_comp_desc),
2102         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
2103         .bmAttributes =         UASP_SS_EP_COMP_LOG_STREAMS,
2104 };
2105
2106 static struct usb_endpoint_descriptor uasp_cmd_desc = {
2107         .bLength =              USB_DT_ENDPOINT_SIZE,
2108         .bDescriptorType =      USB_DT_ENDPOINT,
2109         .bEndpointAddress =     USB_DIR_OUT,
2110         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2111         .wMaxPacketSize =       cpu_to_le16(512),
2112 };
2113
2114 static struct usb_endpoint_descriptor uasp_fs_cmd_desc = {
2115         .bLength =              USB_DT_ENDPOINT_SIZE,
2116         .bDescriptorType =      USB_DT_ENDPOINT,
2117         .bEndpointAddress =     USB_DIR_OUT,
2118         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2119 };
2120
2121 static struct usb_pipe_usage_descriptor uasp_cmd_pipe_desc = {
2122         .bLength =              sizeof(uasp_cmd_pipe_desc),
2123         .bDescriptorType =      USB_DT_PIPE_USAGE,
2124         .bPipeID =              CMD_PIPE_ID,
2125 };
2126
2127 static struct usb_endpoint_descriptor uasp_ss_cmd_desc = {
2128         .bLength =              USB_DT_ENDPOINT_SIZE,
2129         .bDescriptorType =      USB_DT_ENDPOINT,
2130         .bEndpointAddress =     USB_DIR_OUT,
2131         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
2132         .wMaxPacketSize =       cpu_to_le16(1024),
2133 };
2134
2135 static struct usb_ss_ep_comp_descriptor uasp_cmd_comp_desc = {
2136         .bLength =              sizeof(uasp_cmd_comp_desc),
2137         .bDescriptorType =      USB_DT_SS_ENDPOINT_COMP,
2138 };
2139
2140 static struct usb_descriptor_header *uasp_fs_function_desc[] = {
2141         (struct usb_descriptor_header *) &bot_intf_desc,
2142         (struct usb_descriptor_header *) &uasp_fs_bi_desc,
2143         (struct usb_descriptor_header *) &uasp_fs_bo_desc,
2144
2145         (struct usb_descriptor_header *) &uasp_intf_desc,
2146         (struct usb_descriptor_header *) &uasp_fs_bi_desc,
2147         (struct usb_descriptor_header *) &uasp_bi_pipe_desc,
2148         (struct usb_descriptor_header *) &uasp_fs_bo_desc,
2149         (struct usb_descriptor_header *) &uasp_bo_pipe_desc,
2150         (struct usb_descriptor_header *) &uasp_fs_status_desc,
2151         (struct usb_descriptor_header *) &uasp_status_pipe_desc,
2152         (struct usb_descriptor_header *) &uasp_fs_cmd_desc,
2153         (struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
2154 };
2155
2156 static struct usb_descriptor_header *uasp_hs_function_desc[] = {
2157         (struct usb_descriptor_header *) &bot_intf_desc,
2158         (struct usb_descriptor_header *) &uasp_bi_desc,
2159         (struct usb_descriptor_header *) &uasp_bo_desc,
2160
2161         (struct usb_descriptor_header *) &uasp_intf_desc,
2162         (struct usb_descriptor_header *) &uasp_bi_desc,
2163         (struct usb_descriptor_header *) &uasp_bi_pipe_desc,
2164         (struct usb_descriptor_header *) &uasp_bo_desc,
2165         (struct usb_descriptor_header *) &uasp_bo_pipe_desc,
2166         (struct usb_descriptor_header *) &uasp_status_desc,
2167         (struct usb_descriptor_header *) &uasp_status_pipe_desc,
2168         (struct usb_descriptor_header *) &uasp_cmd_desc,
2169         (struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
2170         NULL,
2171 };
2172
2173 static struct usb_descriptor_header *uasp_ss_function_desc[] = {
2174         (struct usb_descriptor_header *) &bot_intf_desc,
2175         (struct usb_descriptor_header *) &uasp_ss_bi_desc,
2176         (struct usb_descriptor_header *) &bot_bi_ep_comp_desc,
2177         (struct usb_descriptor_header *) &uasp_ss_bo_desc,
2178         (struct usb_descriptor_header *) &bot_bo_ep_comp_desc,
2179
2180         (struct usb_descriptor_header *) &uasp_intf_desc,
2181         (struct usb_descriptor_header *) &uasp_ss_bi_desc,
2182         (struct usb_descriptor_header *) &uasp_bi_ep_comp_desc,
2183         (struct usb_descriptor_header *) &uasp_bi_pipe_desc,
2184         (struct usb_descriptor_header *) &uasp_ss_bo_desc,
2185         (struct usb_descriptor_header *) &uasp_bo_ep_comp_desc,
2186         (struct usb_descriptor_header *) &uasp_bo_pipe_desc,
2187         (struct usb_descriptor_header *) &uasp_ss_status_desc,
2188         (struct usb_descriptor_header *) &uasp_status_in_ep_comp_desc,
2189         (struct usb_descriptor_header *) &uasp_status_pipe_desc,
2190         (struct usb_descriptor_header *) &uasp_ss_cmd_desc,
2191         (struct usb_descriptor_header *) &uasp_cmd_comp_desc,
2192         (struct usb_descriptor_header *) &uasp_cmd_pipe_desc,
2193         NULL,
2194 };
2195
2196 #define UAS_VENDOR_ID   0x0525  /* NetChip */
2197 #define UAS_PRODUCT_ID  0xa4a5  /* Linux-USB File-backed Storage Gadget */
2198
2199 static struct usb_device_descriptor usbg_device_desc = {
2200         .bLength =              sizeof(usbg_device_desc),
2201         .bDescriptorType =      USB_DT_DEVICE,
2202         .bcdUSB =               cpu_to_le16(0x0200),
2203         .bDeviceClass =         USB_CLASS_PER_INTERFACE,
2204         .idVendor =             cpu_to_le16(UAS_VENDOR_ID),
2205         .idProduct =            cpu_to_le16(UAS_PRODUCT_ID),
2206         .iManufacturer =        USB_G_STR_MANUFACTOR,
2207         .iProduct =             USB_G_STR_PRODUCT,
2208         .iSerialNumber =        USB_G_STR_SERIAL,
2209
2210         .bNumConfigurations =   1,
2211 };
2212
2213 static struct usb_string        usbg_us_strings[] = {
2214         { USB_G_STR_MANUFACTOR, "Target Manufactor"},
2215         { USB_G_STR_PRODUCT,    "Target Product"},
2216         { USB_G_STR_SERIAL,     "000000000001"},
2217         { USB_G_STR_CONFIG,     "default config"},
2218         { USB_G_STR_INT_UAS,    "USB Attached SCSI"},
2219         { USB_G_STR_INT_BBB,    "Bulk Only Transport"},
2220         { },
2221 };
2222
2223 static struct usb_gadget_strings usbg_stringtab = {
2224         .language = 0x0409,
2225         .strings = usbg_us_strings,
2226 };
2227
2228 static struct usb_gadget_strings *usbg_strings[] = {
2229         &usbg_stringtab,
2230         NULL,
2231 };
2232
2233 static int guas_unbind(struct usb_composite_dev *cdev)
2234 {
2235         return 0;
2236 }
2237
2238 static struct usb_configuration usbg_config_driver = {
2239         .label                  = "Linux Target",
2240         .bConfigurationValue    = 1,
2241         .iConfiguration         = USB_G_STR_CONFIG,
2242         .bmAttributes           = USB_CONFIG_ATT_SELFPOWER,
2243 };
2244
2245 static void give_back_ep(struct usb_ep **pep)
2246 {
2247         struct usb_ep *ep = *pep;
2248         if (!ep)
2249                 return;
2250         ep->driver_data = NULL;
2251 }
2252
2253 static int usbg_bind(struct usb_configuration *c, struct usb_function *f)
2254 {
2255         struct f_uas            *fu = to_f_uas(f);
2256         struct usb_gadget       *gadget = c->cdev->gadget;
2257         struct usb_ep           *ep;
2258         int                     iface;
2259
2260         iface = usb_interface_id(c, f);
2261         if (iface < 0)
2262                 return iface;
2263
2264         bot_intf_desc.bInterfaceNumber = iface;
2265         uasp_intf_desc.bInterfaceNumber = iface;
2266         fu->iface = iface;
2267         ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_bi_desc,
2268                         &uasp_bi_ep_comp_desc);
2269         if (!ep)
2270                 goto ep_fail;
2271
2272         ep->driver_data = fu;
2273         fu->ep_in = ep;
2274
2275         ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_bo_desc,
2276                         &uasp_bo_ep_comp_desc);
2277         if (!ep)
2278                 goto ep_fail;
2279         ep->driver_data = fu;
2280         fu->ep_out = ep;
2281
2282         ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_status_desc,
2283                         &uasp_status_in_ep_comp_desc);
2284         if (!ep)
2285                 goto ep_fail;
2286         ep->driver_data = fu;
2287         fu->ep_status = ep;
2288
2289         ep = usb_ep_autoconfig_ss(gadget, &uasp_ss_cmd_desc,
2290                         &uasp_cmd_comp_desc);
2291         if (!ep)
2292                 goto ep_fail;
2293         ep->driver_data = fu;
2294         fu->ep_cmd = ep;
2295
2296         /* Assume endpoint addresses are the same for both speeds */
2297         uasp_bi_desc.bEndpointAddress = uasp_ss_bi_desc.bEndpointAddress;
2298         uasp_bo_desc.bEndpointAddress = uasp_ss_bo_desc.bEndpointAddress;
2299         uasp_status_desc.bEndpointAddress =
2300                 uasp_ss_status_desc.bEndpointAddress;
2301         uasp_cmd_desc.bEndpointAddress = uasp_ss_cmd_desc.bEndpointAddress;
2302
2303         uasp_fs_bi_desc.bEndpointAddress = uasp_ss_bi_desc.bEndpointAddress;
2304         uasp_fs_bo_desc.bEndpointAddress = uasp_ss_bo_desc.bEndpointAddress;
2305         uasp_fs_status_desc.bEndpointAddress =
2306                 uasp_ss_status_desc.bEndpointAddress;
2307         uasp_fs_cmd_desc.bEndpointAddress = uasp_ss_cmd_desc.bEndpointAddress;
2308
2309         return 0;
2310 ep_fail:
2311         pr_err("Can't claim all required eps\n");
2312
2313         give_back_ep(&fu->ep_in);
2314         give_back_ep(&fu->ep_out);
2315         give_back_ep(&fu->ep_status);
2316         give_back_ep(&fu->ep_cmd);
2317         return -ENOTSUPP;
2318 }
2319
2320 static void usbg_unbind(struct usb_configuration *c, struct usb_function *f)
2321 {
2322         struct f_uas *fu = to_f_uas(f);
2323
2324         kfree(fu);
2325 }
2326
2327 struct guas_setup_wq {
2328         struct work_struct work;
2329         struct f_uas *fu;
2330         unsigned int alt;
2331 };
2332
2333 static void usbg_delayed_set_alt(struct work_struct *wq)
2334 {
2335         struct guas_setup_wq *work = container_of(wq, struct guas_setup_wq,
2336                         work);
2337         struct f_uas *fu = work->fu;
2338         int alt = work->alt;
2339
2340         kfree(work);
2341
2342         if (fu->flags & USBG_IS_BOT)
2343                 bot_cleanup_old_alt(fu);
2344         if (fu->flags & USBG_IS_UAS)
2345                 uasp_cleanup_old_alt(fu);
2346
2347         if (alt == USB_G_ALT_INT_BBB)
2348                 bot_set_alt(fu);
2349         else if (alt == USB_G_ALT_INT_UAS)
2350                 uasp_set_alt(fu);
2351         usb_composite_setup_continue(fu->function.config->cdev);
2352 }
2353
2354 static int usbg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2355 {
2356         struct f_uas *fu = to_f_uas(f);
2357
2358         if ((alt == USB_G_ALT_INT_BBB) || (alt == USB_G_ALT_INT_UAS)) {
2359                 struct guas_setup_wq *work;
2360
2361                 work = kmalloc(sizeof(*work), GFP_ATOMIC);
2362                 if (!work)
2363                         return -ENOMEM;
2364                 INIT_WORK(&work->work, usbg_delayed_set_alt);
2365                 work->fu = fu;
2366                 work->alt = alt;
2367                 schedule_work(&work->work);
2368                 return USB_GADGET_DELAYED_STATUS;
2369         }
2370         return -EOPNOTSUPP;
2371 }
2372
2373 static void usbg_disable(struct usb_function *f)
2374 {
2375         struct f_uas *fu = to_f_uas(f);
2376
2377         if (fu->flags & USBG_IS_UAS)
2378                 uasp_cleanup_old_alt(fu);
2379         else if (fu->flags & USBG_IS_BOT)
2380                 bot_cleanup_old_alt(fu);
2381         fu->flags = 0;
2382 }
2383
2384 static int usbg_setup(struct usb_function *f,
2385                 const struct usb_ctrlrequest *ctrl)
2386 {
2387         struct f_uas *fu = to_f_uas(f);
2388
2389         if (!(fu->flags & USBG_IS_BOT))
2390                 return -EOPNOTSUPP;
2391
2392         return usbg_bot_setup(f, ctrl);
2393 }
2394
2395 static int usbg_cfg_bind(struct usb_configuration *c)
2396 {
2397         struct f_uas *fu;
2398         int ret;
2399
2400         fu = kzalloc(sizeof(*fu), GFP_KERNEL);
2401         if (!fu)
2402                 return -ENOMEM;
2403         fu->function.name = "Target Function";
2404         fu->function.descriptors = uasp_fs_function_desc;
2405         fu->function.hs_descriptors = uasp_hs_function_desc;
2406         fu->function.ss_descriptors = uasp_ss_function_desc;
2407         fu->function.bind = usbg_bind;
2408         fu->function.unbind = usbg_unbind;
2409         fu->function.set_alt = usbg_set_alt;
2410         fu->function.setup = usbg_setup;
2411         fu->function.disable = usbg_disable;
2412         fu->tpg = the_only_tpg_I_currently_have;
2413
2414         ret = usb_add_function(c, &fu->function);
2415         if (ret)
2416                 goto err;
2417
2418         return 0;
2419 err:
2420         kfree(fu);
2421         return ret;
2422 }
2423
2424 static int usb_target_bind(struct usb_composite_dev *cdev)
2425 {
2426         int ret;
2427
2428         ret = usb_add_config(cdev, &usbg_config_driver,
2429                         usbg_cfg_bind);
2430         return 0;
2431 }
2432
2433 static struct usb_composite_driver usbg_driver = {
2434         .name           = "g_target",
2435         .dev            = &usbg_device_desc,
2436         .strings        = usbg_strings,
2437         .max_speed      = USB_SPEED_SUPER,
2438         .unbind         = guas_unbind,
2439 };
2440
2441 static int usbg_attach(struct usbg_tpg *tpg)
2442 {
2443         return usb_composite_probe(&usbg_driver, usb_target_bind);
2444 }
2445
2446 static void usbg_detach(struct usbg_tpg *tpg)
2447 {
2448         usb_composite_unregister(&usbg_driver);
2449 }
2450
2451 static int __init usb_target_gadget_init(void)
2452 {
2453         int ret;
2454
2455         ret = usbg_register_configfs();
2456         return ret;
2457 }
2458 module_init(usb_target_gadget_init);
2459
2460 static void __exit usb_target_gadget_exit(void)
2461 {
2462         usbg_deregister_configfs();
2463 }
2464 module_exit(usb_target_gadget_exit);
2465
2466 MODULE_AUTHOR("Sebastian Andrzej Siewior <bigeasy@linutronix.de>");
2467 MODULE_DESCRIPTION("usb-gadget fabric");
2468 MODULE_LICENSE("GPL v2");