GNU Linux-libre 4.9.292-gnu1
[releases.git] / drivers / usb / gadget / function / f_midi.c
1 /*
2  * f_midi.c -- USB MIDI class function driver
3  *
4  * Copyright (C) 2006 Thumtronics Pty Ltd.
5  * Developed for Thumtronics by Grey Innovation
6  * Ben Williamson <ben.williamson@greyinnovation.com>
7  *
8  * Rewritten for the composite framework
9  *   Copyright (C) 2011 Daniel Mack <zonque@gmail.com>
10  *
11  * Based on drivers/usb/gadget/f_audio.c,
12  *   Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
13  *   Copyright (C) 2008 Analog Devices, Inc
14  *
15  * and drivers/usb/gadget/midi.c,
16  *   Copyright (C) 2006 Thumtronics Pty Ltd.
17  *   Ben Williamson <ben.williamson@greyinnovation.com>
18  *
19  * Licensed under the GPL-2 or later.
20  */
21
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/slab.h>
25 #include <linux/device.h>
26 #include <linux/kfifo.h>
27 #include <linux/spinlock.h>
28
29 #include <sound/core.h>
30 #include <sound/initval.h>
31 #include <sound/rawmidi.h>
32
33 #include <linux/usb/ch9.h>
34 #include <linux/usb/gadget.h>
35 #include <linux/usb/audio.h>
36 #include <linux/usb/midi.h>
37
38 #include "u_f.h"
39 #include "u_midi.h"
40
41 MODULE_AUTHOR("Ben Williamson");
42 MODULE_LICENSE("GPL v2");
43
44 static const char f_midi_shortname[] = "f_midi";
45 static const char f_midi_longname[] = "MIDI Gadget";
46
47 /*
48  * We can only handle 16 cables on one single endpoint, as cable numbers are
49  * stored in 4-bit fields. And as the interface currently only holds one
50  * single endpoint, this is the maximum number of ports we can allow.
51  */
52 #define MAX_PORTS 16
53
54 /* MIDI message states */
55 enum {
56         STATE_INITIAL = 0,      /* pseudo state */
57         STATE_1PARAM,
58         STATE_2PARAM_1,
59         STATE_2PARAM_2,
60         STATE_SYSEX_0,
61         STATE_SYSEX_1,
62         STATE_SYSEX_2,
63         STATE_REAL_TIME,
64         STATE_FINISHED,         /* pseudo state */
65 };
66
67 /*
68  * This is a gadget, and the IN/OUT naming is from the host's perspective.
69  * USB -> OUT endpoint -> rawmidi
70  * USB <- IN endpoint  <- rawmidi
71  */
72 struct gmidi_in_port {
73         struct snd_rawmidi_substream *substream;
74         int active;
75         uint8_t cable;
76         uint8_t state;
77         uint8_t data[2];
78 };
79
80 struct f_midi {
81         struct usb_function     func;
82         struct usb_gadget       *gadget;
83         struct usb_ep           *in_ep, *out_ep;
84         struct snd_card         *card;
85         struct snd_rawmidi      *rmidi;
86         u8                      ms_id;
87
88         struct snd_rawmidi_substream *out_substream[MAX_PORTS];
89
90         unsigned long           out_triggered;
91         struct tasklet_struct   tasklet;
92         unsigned int in_ports;
93         unsigned int out_ports;
94         int index;
95         char *id;
96         unsigned int buflen, qlen;
97         /* This fifo is used as a buffer ring for pre-allocated IN usb_requests */
98         DECLARE_KFIFO_PTR(in_req_fifo, struct usb_request *);
99         spinlock_t transmit_lock;
100         unsigned int in_last_port;
101
102         struct gmidi_in_port    in_ports_array[/* in_ports */];
103 };
104
105 static inline struct f_midi *func_to_midi(struct usb_function *f)
106 {
107         return container_of(f, struct f_midi, func);
108 }
109
110 static void f_midi_transmit(struct f_midi *midi);
111
112 DECLARE_UAC_AC_HEADER_DESCRIPTOR(1);
113 DECLARE_USB_MIDI_OUT_JACK_DESCRIPTOR(1);
114 DECLARE_USB_MS_ENDPOINT_DESCRIPTOR(16);
115
116 /* B.3.1  Standard AC Interface Descriptor */
117 static struct usb_interface_descriptor ac_interface_desc = {
118         .bLength =              USB_DT_INTERFACE_SIZE,
119         .bDescriptorType =      USB_DT_INTERFACE,
120         /* .bInterfaceNumber =  DYNAMIC */
121         /* .bNumEndpoints =     DYNAMIC */
122         .bInterfaceClass =      USB_CLASS_AUDIO,
123         .bInterfaceSubClass =   USB_SUBCLASS_AUDIOCONTROL,
124         /* .iInterface =        DYNAMIC */
125 };
126
127 /* B.3.2  Class-Specific AC Interface Descriptor */
128 static struct uac1_ac_header_descriptor_1 ac_header_desc = {
129         .bLength =              UAC_DT_AC_HEADER_SIZE(1),
130         .bDescriptorType =      USB_DT_CS_INTERFACE,
131         .bDescriptorSubtype =   USB_MS_HEADER,
132         .bcdADC =               cpu_to_le16(0x0100),
133         .wTotalLength =         cpu_to_le16(UAC_DT_AC_HEADER_SIZE(1)),
134         .bInCollection =        1,
135         /* .baInterfaceNr =     DYNAMIC */
136 };
137
138 /* B.4.1  Standard MS Interface Descriptor */
139 static struct usb_interface_descriptor ms_interface_desc = {
140         .bLength =              USB_DT_INTERFACE_SIZE,
141         .bDescriptorType =      USB_DT_INTERFACE,
142         /* .bInterfaceNumber =  DYNAMIC */
143         .bNumEndpoints =        2,
144         .bInterfaceClass =      USB_CLASS_AUDIO,
145         .bInterfaceSubClass =   USB_SUBCLASS_MIDISTREAMING,
146         /* .iInterface =        DYNAMIC */
147 };
148
149 /* B.4.2  Class-Specific MS Interface Descriptor */
150 static struct usb_ms_header_descriptor ms_header_desc = {
151         .bLength =              USB_DT_MS_HEADER_SIZE,
152         .bDescriptorType =      USB_DT_CS_INTERFACE,
153         .bDescriptorSubtype =   USB_MS_HEADER,
154         .bcdMSC =               cpu_to_le16(0x0100),
155         /* .wTotalLength =      DYNAMIC */
156 };
157
158 /* B.5.1  Standard Bulk OUT Endpoint Descriptor */
159 static struct usb_endpoint_descriptor bulk_out_desc = {
160         .bLength =              USB_DT_ENDPOINT_AUDIO_SIZE,
161         .bDescriptorType =      USB_DT_ENDPOINT,
162         .bEndpointAddress =     USB_DIR_OUT,
163         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
164 };
165
166 /* B.5.2  Class-specific MS Bulk OUT Endpoint Descriptor */
167 static struct usb_ms_endpoint_descriptor_16 ms_out_desc = {
168         /* .bLength =           DYNAMIC */
169         .bDescriptorType =      USB_DT_CS_ENDPOINT,
170         .bDescriptorSubtype =   USB_MS_GENERAL,
171         /* .bNumEmbMIDIJack =   DYNAMIC */
172         /* .baAssocJackID =     DYNAMIC */
173 };
174
175 /* B.6.1  Standard Bulk IN Endpoint Descriptor */
176 static struct usb_endpoint_descriptor bulk_in_desc = {
177         .bLength =              USB_DT_ENDPOINT_AUDIO_SIZE,
178         .bDescriptorType =      USB_DT_ENDPOINT,
179         .bEndpointAddress =     USB_DIR_IN,
180         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
181 };
182
183 /* B.6.2  Class-specific MS Bulk IN Endpoint Descriptor */
184 static struct usb_ms_endpoint_descriptor_16 ms_in_desc = {
185         /* .bLength =           DYNAMIC */
186         .bDescriptorType =      USB_DT_CS_ENDPOINT,
187         .bDescriptorSubtype =   USB_MS_GENERAL,
188         /* .bNumEmbMIDIJack =   DYNAMIC */
189         /* .baAssocJackID =     DYNAMIC */
190 };
191
192 /* string IDs are assigned dynamically */
193
194 #define STRING_FUNC_IDX                 0
195
196 static struct usb_string midi_string_defs[] = {
197         [STRING_FUNC_IDX].s = "MIDI function",
198         {  } /* end of list */
199 };
200
201 static struct usb_gadget_strings midi_stringtab = {
202         .language       = 0x0409,       /* en-us */
203         .strings        = midi_string_defs,
204 };
205
206 static struct usb_gadget_strings *midi_strings[] = {
207         &midi_stringtab,
208         NULL,
209 };
210
211 static inline struct usb_request *midi_alloc_ep_req(struct usb_ep *ep,
212                                                     unsigned length)
213 {
214         return alloc_ep_req(ep, length);
215 }
216
217 static const uint8_t f_midi_cin_length[] = {
218         0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
219 };
220
221 /*
222  * Receives a chunk of MIDI data.
223  */
224 static void f_midi_read_data(struct usb_ep *ep, int cable,
225                              uint8_t *data, int length)
226 {
227         struct f_midi *midi = ep->driver_data;
228         struct snd_rawmidi_substream *substream = midi->out_substream[cable];
229
230         if (!substream)
231                 /* Nobody is listening - throw it on the floor. */
232                 return;
233
234         if (!test_bit(cable, &midi->out_triggered))
235                 return;
236
237         snd_rawmidi_receive(substream, data, length);
238 }
239
240 static void f_midi_handle_out_data(struct usb_ep *ep, struct usb_request *req)
241 {
242         unsigned int i;
243         u8 *buf = req->buf;
244
245         for (i = 0; i + 3 < req->actual; i += 4)
246                 if (buf[i] != 0) {
247                         int cable = buf[i] >> 4;
248                         int length = f_midi_cin_length[buf[i] & 0x0f];
249                         f_midi_read_data(ep, cable, &buf[i + 1], length);
250                 }
251 }
252
253 static void
254 f_midi_complete(struct usb_ep *ep, struct usb_request *req)
255 {
256         struct f_midi *midi = ep->driver_data;
257         struct usb_composite_dev *cdev = midi->func.config->cdev;
258         int status = req->status;
259
260         switch (status) {
261         case 0:                  /* normal completion */
262                 if (ep == midi->out_ep) {
263                         /* We received stuff. req is queued again, below */
264                         f_midi_handle_out_data(ep, req);
265                 } else if (ep == midi->in_ep) {
266                         /* Our transmit completed. See if there's more to go.
267                          * f_midi_transmit eats req, don't queue it again. */
268                         req->length = 0;
269                         f_midi_transmit(midi);
270                         return;
271                 }
272                 break;
273
274         /* this endpoint is normally active while we're configured */
275         case -ECONNABORTED:     /* hardware forced ep reset */
276         case -ECONNRESET:       /* request dequeued */
277         case -ESHUTDOWN:        /* disconnect from host */
278                 VDBG(cdev, "%s gone (%d), %d/%d\n", ep->name, status,
279                                 req->actual, req->length);
280                 if (ep == midi->out_ep) {
281                         f_midi_handle_out_data(ep, req);
282                         /* We don't need to free IN requests because it's handled
283                          * by the midi->in_req_fifo. */
284                         free_ep_req(ep, req);
285                 }
286                 return;
287
288         case -EOVERFLOW:        /* buffer overrun on read means that
289                                  * we didn't provide a big enough buffer.
290                                  */
291         default:
292                 DBG(cdev, "%s complete --> %d, %d/%d\n", ep->name,
293                                 status, req->actual, req->length);
294                 break;
295         case -EREMOTEIO:        /* short read */
296                 break;
297         }
298
299         status = usb_ep_queue(ep, req, GFP_ATOMIC);
300         if (status) {
301                 ERROR(cdev, "kill %s:  resubmit %d bytes --> %d\n",
302                                 ep->name, req->length, status);
303                 usb_ep_set_halt(ep);
304                 /* FIXME recover later ... somehow */
305         }
306 }
307
308 static void f_midi_drop_out_substreams(struct f_midi *midi)
309 {
310         unsigned int i;
311
312         for (i = 0; i < midi->in_ports; i++) {
313                 struct gmidi_in_port *port = midi->in_ports_array + i;
314                 struct snd_rawmidi_substream *substream = port->substream;
315
316                 if (port->active && substream)
317                         snd_rawmidi_drop_output(substream);
318         }
319 }
320
321 static int f_midi_start_ep(struct f_midi *midi,
322                            struct usb_function *f,
323                            struct usb_ep *ep)
324 {
325         int err;
326         struct usb_composite_dev *cdev = f->config->cdev;
327
328         usb_ep_disable(ep);
329
330         err = config_ep_by_speed(midi->gadget, f, ep);
331         if (err) {
332                 ERROR(cdev, "can't configure %s: %d\n", ep->name, err);
333                 return err;
334         }
335
336         err = usb_ep_enable(ep);
337         if (err) {
338                 ERROR(cdev, "can't start %s: %d\n", ep->name, err);
339                 return err;
340         }
341
342         ep->driver_data = midi;
343
344         return 0;
345 }
346
347 static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
348 {
349         struct f_midi *midi = func_to_midi(f);
350         unsigned i;
351         int err;
352
353         /* we only set alt for MIDIStreaming interface */
354         if (intf != midi->ms_id)
355                 return 0;
356
357         err = f_midi_start_ep(midi, f, midi->in_ep);
358         if (err)
359                 return err;
360
361         err = f_midi_start_ep(midi, f, midi->out_ep);
362         if (err)
363                 return err;
364
365         /* pre-allocate write usb requests to use on f_midi_transmit. */
366         while (kfifo_avail(&midi->in_req_fifo)) {
367                 struct usb_request *req =
368                         midi_alloc_ep_req(midi->in_ep, midi->buflen);
369
370                 if (req == NULL)
371                         return -ENOMEM;
372
373                 req->length = 0;
374                 req->complete = f_midi_complete;
375
376                 kfifo_put(&midi->in_req_fifo, req);
377         }
378
379         /* allocate a bunch of read buffers and queue them all at once. */
380         for (i = 0; i < midi->qlen && err == 0; i++) {
381                 struct usb_request *req =
382                         midi_alloc_ep_req(midi->out_ep, midi->buflen);
383
384                 if (req == NULL)
385                         return -ENOMEM;
386
387                 req->complete = f_midi_complete;
388                 err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);
389                 if (err) {
390                         ERROR(midi, "%s: couldn't enqueue request: %d\n",
391                                     midi->out_ep->name, err);
392                         if (req->buf != NULL)
393                                 free_ep_req(midi->out_ep, req);
394                         return err;
395                 }
396         }
397
398         return 0;
399 }
400
401 static void f_midi_disable(struct usb_function *f)
402 {
403         struct f_midi *midi = func_to_midi(f);
404         struct usb_composite_dev *cdev = f->config->cdev;
405         struct usb_request *req = NULL;
406
407         DBG(cdev, "disable\n");
408
409         /*
410          * just disable endpoints, forcing completion of pending i/o.
411          * all our completion handlers free their requests in this case.
412          */
413         usb_ep_disable(midi->in_ep);
414         usb_ep_disable(midi->out_ep);
415
416         /* release IN requests */
417         while (kfifo_get(&midi->in_req_fifo, &req))
418                 free_ep_req(midi->in_ep, req);
419
420         f_midi_drop_out_substreams(midi);
421 }
422
423 static int f_midi_snd_free(struct snd_device *device)
424 {
425         return 0;
426 }
427
428 /*
429  * Converts MIDI commands to USB MIDI packets.
430  */
431 static void f_midi_transmit_byte(struct usb_request *req,
432                                  struct gmidi_in_port *port, uint8_t b)
433 {
434         uint8_t p[4] = { port->cable << 4, 0, 0, 0 };
435         uint8_t next_state = STATE_INITIAL;
436
437         switch (b) {
438         case 0xf8 ... 0xff:
439                 /* System Real-Time Messages */
440                 p[0] |= 0x0f;
441                 p[1] = b;
442                 next_state = port->state;
443                 port->state = STATE_REAL_TIME;
444                 break;
445
446         case 0xf7:
447                 /* End of SysEx */
448                 switch (port->state) {
449                 case STATE_SYSEX_0:
450                         p[0] |= 0x05;
451                         p[1] = 0xf7;
452                         next_state = STATE_FINISHED;
453                         break;
454                 case STATE_SYSEX_1:
455                         p[0] |= 0x06;
456                         p[1] = port->data[0];
457                         p[2] = 0xf7;
458                         next_state = STATE_FINISHED;
459                         break;
460                 case STATE_SYSEX_2:
461                         p[0] |= 0x07;
462                         p[1] = port->data[0];
463                         p[2] = port->data[1];
464                         p[3] = 0xf7;
465                         next_state = STATE_FINISHED;
466                         break;
467                 default:
468                         /* Ignore byte */
469                         next_state = port->state;
470                         port->state = STATE_INITIAL;
471                 }
472                 break;
473
474         case 0xf0 ... 0xf6:
475                 /* System Common Messages */
476                 port->data[0] = port->data[1] = 0;
477                 port->state = STATE_INITIAL;
478                 switch (b) {
479                 case 0xf0:
480                         port->data[0] = b;
481                         port->data[1] = 0;
482                         next_state = STATE_SYSEX_1;
483                         break;
484                 case 0xf1:
485                 case 0xf3:
486                         port->data[0] = b;
487                         next_state = STATE_1PARAM;
488                         break;
489                 case 0xf2:
490                         port->data[0] = b;
491                         next_state = STATE_2PARAM_1;
492                         break;
493                 case 0xf4:
494                 case 0xf5:
495                         next_state = STATE_INITIAL;
496                         break;
497                 case 0xf6:
498                         p[0] |= 0x05;
499                         p[1] = 0xf6;
500                         next_state = STATE_FINISHED;
501                         break;
502                 }
503                 break;
504
505         case 0x80 ... 0xef:
506                 /*
507                  * Channel Voice Messages, Channel Mode Messages
508                  * and Control Change Messages.
509                  */
510                 port->data[0] = b;
511                 port->data[1] = 0;
512                 port->state = STATE_INITIAL;
513                 if (b >= 0xc0 && b <= 0xdf)
514                         next_state = STATE_1PARAM;
515                 else
516                         next_state = STATE_2PARAM_1;
517                 break;
518
519         case 0x00 ... 0x7f:
520                 /* Message parameters */
521                 switch (port->state) {
522                 case STATE_1PARAM:
523                         if (port->data[0] < 0xf0)
524                                 p[0] |= port->data[0] >> 4;
525                         else
526                                 p[0] |= 0x02;
527
528                         p[1] = port->data[0];
529                         p[2] = b;
530                         /* This is to allow Running State Messages */
531                         next_state = STATE_1PARAM;
532                         break;
533                 case STATE_2PARAM_1:
534                         port->data[1] = b;
535                         next_state = STATE_2PARAM_2;
536                         break;
537                 case STATE_2PARAM_2:
538                         if (port->data[0] < 0xf0)
539                                 p[0] |= port->data[0] >> 4;
540                         else
541                                 p[0] |= 0x03;
542
543                         p[1] = port->data[0];
544                         p[2] = port->data[1];
545                         p[3] = b;
546                         /* This is to allow Running State Messages */
547                         next_state = STATE_2PARAM_1;
548                         break;
549                 case STATE_SYSEX_0:
550                         port->data[0] = b;
551                         next_state = STATE_SYSEX_1;
552                         break;
553                 case STATE_SYSEX_1:
554                         port->data[1] = b;
555                         next_state = STATE_SYSEX_2;
556                         break;
557                 case STATE_SYSEX_2:
558                         p[0] |= 0x04;
559                         p[1] = port->data[0];
560                         p[2] = port->data[1];
561                         p[3] = b;
562                         next_state = STATE_SYSEX_0;
563                         break;
564                 }
565                 break;
566         }
567
568         /* States where we have to write into the USB request */
569         if (next_state == STATE_FINISHED ||
570             port->state == STATE_SYSEX_2 ||
571             port->state == STATE_1PARAM ||
572             port->state == STATE_2PARAM_2 ||
573             port->state == STATE_REAL_TIME) {
574
575                 unsigned int length = req->length;
576                 u8 *buf = (u8 *)req->buf + length;
577
578                 memcpy(buf, p, sizeof(p));
579                 req->length = length + sizeof(p);
580
581                 if (next_state == STATE_FINISHED) {
582                         next_state = STATE_INITIAL;
583                         port->data[0] = port->data[1] = 0;
584                 }
585         }
586
587         port->state = next_state;
588 }
589
590 static int f_midi_do_transmit(struct f_midi *midi, struct usb_ep *ep)
591 {
592         struct usb_request *req = NULL;
593         unsigned int len, i;
594         bool active = false;
595         int err;
596
597         /*
598          * We peek the request in order to reuse it if it fails to enqueue on
599          * its endpoint
600          */
601         len = kfifo_peek(&midi->in_req_fifo, &req);
602         if (len != 1) {
603                 ERROR(midi, "%s: Couldn't get usb request\n", __func__);
604                 return -1;
605         }
606
607         /*
608          * If buffer overrun, then we ignore this transmission.
609          * IMPORTANT: This will cause the user-space rawmidi device to block
610          * until a) usb requests have been completed or b) snd_rawmidi_write()
611          * times out.
612          */
613         if (req->length > 0)
614                 return 0;
615
616         for (i = midi->in_last_port; i < midi->in_ports; ++i) {
617                 struct gmidi_in_port *port = midi->in_ports_array + i;
618                 struct snd_rawmidi_substream *substream = port->substream;
619
620                 if (!port->active || !substream)
621                         continue;
622
623                 while (req->length + 3 < midi->buflen) {
624                         uint8_t b;
625
626                         if (snd_rawmidi_transmit(substream, &b, 1) != 1) {
627                                 port->active = 0;
628                                 break;
629                         }
630                         f_midi_transmit_byte(req, port, b);
631                 }
632
633                 active = !!port->active;
634                 if (active)
635                         break;
636         }
637         midi->in_last_port = active ? i : 0;
638
639         if (req->length <= 0)
640                 goto done;
641
642         err = usb_ep_queue(ep, req, GFP_ATOMIC);
643         if (err < 0) {
644                 ERROR(midi, "%s failed to queue req: %d\n",
645                       midi->in_ep->name, err);
646                 req->length = 0; /* Re-use request next time. */
647         } else {
648                 /* Upon success, put request at the back of the queue. */
649                 kfifo_skip(&midi->in_req_fifo);
650                 kfifo_put(&midi->in_req_fifo, req);
651         }
652
653 done:
654         return active;
655 }
656
657 static void f_midi_transmit(struct f_midi *midi)
658 {
659         struct usb_ep *ep = midi->in_ep;
660         int ret;
661         unsigned long flags;
662
663         /* We only care about USB requests if IN endpoint is enabled */
664         if (!ep || !ep->enabled)
665                 goto drop_out;
666
667         spin_lock_irqsave(&midi->transmit_lock, flags);
668
669         do {
670                 ret = f_midi_do_transmit(midi, ep);
671                 if (ret < 0) {
672                         spin_unlock_irqrestore(&midi->transmit_lock, flags);
673                         goto drop_out;
674                 }
675         } while (ret);
676
677         spin_unlock_irqrestore(&midi->transmit_lock, flags);
678
679         return;
680
681 drop_out:
682         f_midi_drop_out_substreams(midi);
683 }
684
685 static void f_midi_in_tasklet(unsigned long data)
686 {
687         struct f_midi *midi = (struct f_midi *) data;
688         f_midi_transmit(midi);
689 }
690
691 static int f_midi_in_open(struct snd_rawmidi_substream *substream)
692 {
693         struct f_midi *midi = substream->rmidi->private_data;
694         struct gmidi_in_port *port;
695
696         if (substream->number >= midi->in_ports)
697                 return -EINVAL;
698
699         VDBG(midi, "%s()\n", __func__);
700         port = midi->in_ports_array + substream->number;
701         port->substream = substream;
702         port->state = STATE_INITIAL;
703         return 0;
704 }
705
706 static int f_midi_in_close(struct snd_rawmidi_substream *substream)
707 {
708         struct f_midi *midi = substream->rmidi->private_data;
709
710         VDBG(midi, "%s()\n", __func__);
711         return 0;
712 }
713
714 static void f_midi_in_trigger(struct snd_rawmidi_substream *substream, int up)
715 {
716         struct f_midi *midi = substream->rmidi->private_data;
717
718         if (substream->number >= midi->in_ports)
719                 return;
720
721         VDBG(midi, "%s() %d\n", __func__, up);
722         midi->in_ports_array[substream->number].active = up;
723         if (up)
724                 tasklet_hi_schedule(&midi->tasklet);
725 }
726
727 static int f_midi_out_open(struct snd_rawmidi_substream *substream)
728 {
729         struct f_midi *midi = substream->rmidi->private_data;
730
731         if (substream->number >= MAX_PORTS)
732                 return -EINVAL;
733
734         VDBG(midi, "%s()\n", __func__);
735         midi->out_substream[substream->number] = substream;
736         return 0;
737 }
738
739 static int f_midi_out_close(struct snd_rawmidi_substream *substream)
740 {
741         struct f_midi *midi = substream->rmidi->private_data;
742
743         VDBG(midi, "%s()\n", __func__);
744         return 0;
745 }
746
747 static void f_midi_out_trigger(struct snd_rawmidi_substream *substream, int up)
748 {
749         struct f_midi *midi = substream->rmidi->private_data;
750
751         VDBG(midi, "%s()\n", __func__);
752
753         if (up)
754                 set_bit(substream->number, &midi->out_triggered);
755         else
756                 clear_bit(substream->number, &midi->out_triggered);
757 }
758
759 static struct snd_rawmidi_ops gmidi_in_ops = {
760         .open = f_midi_in_open,
761         .close = f_midi_in_close,
762         .trigger = f_midi_in_trigger,
763 };
764
765 static struct snd_rawmidi_ops gmidi_out_ops = {
766         .open = f_midi_out_open,
767         .close = f_midi_out_close,
768         .trigger = f_midi_out_trigger
769 };
770
771 static inline void f_midi_unregister_card(struct f_midi *midi)
772 {
773         if (midi->card) {
774                 snd_card_free(midi->card);
775                 midi->card = NULL;
776         }
777 }
778
779 /* register as a sound "card" */
780 static int f_midi_register_card(struct f_midi *midi)
781 {
782         struct snd_card *card;
783         struct snd_rawmidi *rmidi;
784         int err;
785         static struct snd_device_ops ops = {
786                 .dev_free = f_midi_snd_free,
787         };
788
789         err = snd_card_new(&midi->gadget->dev, midi->index, midi->id,
790                            THIS_MODULE, 0, &card);
791         if (err < 0) {
792                 ERROR(midi, "snd_card_new() failed\n");
793                 goto fail;
794         }
795         midi->card = card;
796
797         err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, midi, &ops);
798         if (err < 0) {
799                 ERROR(midi, "snd_device_new() failed: error %d\n", err);
800                 goto fail;
801         }
802
803         strcpy(card->driver, f_midi_longname);
804         strcpy(card->longname, f_midi_longname);
805         strcpy(card->shortname, f_midi_shortname);
806
807         /* Set up rawmidi */
808         snd_component_add(card, "MIDI");
809         err = snd_rawmidi_new(card, card->longname, 0,
810                               midi->out_ports, midi->in_ports, &rmidi);
811         if (err < 0) {
812                 ERROR(midi, "snd_rawmidi_new() failed: error %d\n", err);
813                 goto fail;
814         }
815         midi->rmidi = rmidi;
816         midi->in_last_port = 0;
817         strcpy(rmidi->name, card->shortname);
818         rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
819                             SNDRV_RAWMIDI_INFO_INPUT |
820                             SNDRV_RAWMIDI_INFO_DUPLEX;
821         rmidi->private_data = midi;
822
823         /*
824          * Yes, rawmidi OUTPUT = USB IN, and rawmidi INPUT = USB OUT.
825          * It's an upside-down world being a gadget.
826          */
827         snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &gmidi_in_ops);
828         snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &gmidi_out_ops);
829
830         /* register it - we're ready to go */
831         err = snd_card_register(card);
832         if (err < 0) {
833                 ERROR(midi, "snd_card_register() failed\n");
834                 goto fail;
835         }
836
837         VDBG(midi, "%s() finished ok\n", __func__);
838         return 0;
839
840 fail:
841         f_midi_unregister_card(midi);
842         return err;
843 }
844
845 /* MIDI function driver setup/binding */
846
847 static int f_midi_bind(struct usb_configuration *c, struct usb_function *f)
848 {
849         struct usb_descriptor_header **midi_function;
850         struct usb_midi_in_jack_descriptor jack_in_ext_desc[MAX_PORTS];
851         struct usb_midi_in_jack_descriptor jack_in_emb_desc[MAX_PORTS];
852         struct usb_midi_out_jack_descriptor_1 jack_out_ext_desc[MAX_PORTS];
853         struct usb_midi_out_jack_descriptor_1 jack_out_emb_desc[MAX_PORTS];
854         struct usb_composite_dev *cdev = c->cdev;
855         struct f_midi *midi = func_to_midi(f);
856         struct usb_string *us;
857         int status, n, jack = 1, i = 0;
858
859         midi->gadget = cdev->gadget;
860         tasklet_init(&midi->tasklet, f_midi_in_tasklet, (unsigned long) midi);
861         status = f_midi_register_card(midi);
862         if (status < 0)
863                 goto fail_register;
864
865         /* maybe allocate device-global string ID */
866         us = usb_gstrings_attach(c->cdev, midi_strings,
867                                  ARRAY_SIZE(midi_string_defs));
868         if (IS_ERR(us)) {
869                 status = PTR_ERR(us);
870                 goto fail;
871         }
872         ac_interface_desc.iInterface = us[STRING_FUNC_IDX].id;
873
874         /* We have two interfaces, AudioControl and MIDIStreaming */
875         status = usb_interface_id(c, f);
876         if (status < 0)
877                 goto fail;
878         ac_interface_desc.bInterfaceNumber = status;
879
880         status = usb_interface_id(c, f);
881         if (status < 0)
882                 goto fail;
883         ms_interface_desc.bInterfaceNumber = status;
884         ac_header_desc.baInterfaceNr[0] = status;
885         midi->ms_id = status;
886
887         status = -ENODEV;
888
889         /* allocate instance-specific endpoints */
890         midi->in_ep = usb_ep_autoconfig(cdev->gadget, &bulk_in_desc);
891         if (!midi->in_ep)
892                 goto fail;
893
894         midi->out_ep = usb_ep_autoconfig(cdev->gadget, &bulk_out_desc);
895         if (!midi->out_ep)
896                 goto fail;
897
898         /* allocate temporary function list */
899         midi_function = kcalloc((MAX_PORTS * 4) + 9, sizeof(*midi_function),
900                                 GFP_KERNEL);
901         if (!midi_function) {
902                 status = -ENOMEM;
903                 goto fail;
904         }
905
906         /*
907          * construct the function's descriptor set. As the number of
908          * input and output MIDI ports is configurable, we have to do
909          * it that way.
910          */
911
912         /* add the headers - these are always the same */
913         midi_function[i++] = (struct usb_descriptor_header *) &ac_interface_desc;
914         midi_function[i++] = (struct usb_descriptor_header *) &ac_header_desc;
915         midi_function[i++] = (struct usb_descriptor_header *) &ms_interface_desc;
916
917         /* calculate the header's wTotalLength */
918         n = USB_DT_MS_HEADER_SIZE
919                 + (midi->in_ports + midi->out_ports) *
920                         (USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
921         ms_header_desc.wTotalLength = cpu_to_le16(n);
922
923         midi_function[i++] = (struct usb_descriptor_header *) &ms_header_desc;
924
925         /* configure the external IN jacks, each linked to an embedded OUT jack */
926         for (n = 0; n < midi->in_ports; n++) {
927                 struct usb_midi_in_jack_descriptor *in_ext = &jack_in_ext_desc[n];
928                 struct usb_midi_out_jack_descriptor_1 *out_emb = &jack_out_emb_desc[n];
929
930                 in_ext->bLength                 = USB_DT_MIDI_IN_SIZE;
931                 in_ext->bDescriptorType         = USB_DT_CS_INTERFACE;
932                 in_ext->bDescriptorSubtype      = USB_MS_MIDI_IN_JACK;
933                 in_ext->bJackType               = USB_MS_EXTERNAL;
934                 in_ext->bJackID                 = jack++;
935                 in_ext->iJack                   = 0;
936                 midi_function[i++] = (struct usb_descriptor_header *) in_ext;
937
938                 out_emb->bLength                = USB_DT_MIDI_OUT_SIZE(1);
939                 out_emb->bDescriptorType        = USB_DT_CS_INTERFACE;
940                 out_emb->bDescriptorSubtype     = USB_MS_MIDI_OUT_JACK;
941                 out_emb->bJackType              = USB_MS_EMBEDDED;
942                 out_emb->bJackID                = jack++;
943                 out_emb->bNrInputPins           = 1;
944                 out_emb->pins[0].baSourcePin    = 1;
945                 out_emb->pins[0].baSourceID     = in_ext->bJackID;
946                 out_emb->iJack                  = 0;
947                 midi_function[i++] = (struct usb_descriptor_header *) out_emb;
948
949                 /* link it to the endpoint */
950                 ms_in_desc.baAssocJackID[n] = out_emb->bJackID;
951         }
952
953         /* configure the external OUT jacks, each linked to an embedded IN jack */
954         for (n = 0; n < midi->out_ports; n++) {
955                 struct usb_midi_in_jack_descriptor *in_emb = &jack_in_emb_desc[n];
956                 struct usb_midi_out_jack_descriptor_1 *out_ext = &jack_out_ext_desc[n];
957
958                 in_emb->bLength                 = USB_DT_MIDI_IN_SIZE;
959                 in_emb->bDescriptorType         = USB_DT_CS_INTERFACE;
960                 in_emb->bDescriptorSubtype      = USB_MS_MIDI_IN_JACK;
961                 in_emb->bJackType               = USB_MS_EMBEDDED;
962                 in_emb->bJackID                 = jack++;
963                 in_emb->iJack                   = 0;
964                 midi_function[i++] = (struct usb_descriptor_header *) in_emb;
965
966                 out_ext->bLength =              USB_DT_MIDI_OUT_SIZE(1);
967                 out_ext->bDescriptorType =      USB_DT_CS_INTERFACE;
968                 out_ext->bDescriptorSubtype =   USB_MS_MIDI_OUT_JACK;
969                 out_ext->bJackType =            USB_MS_EXTERNAL;
970                 out_ext->bJackID =              jack++;
971                 out_ext->bNrInputPins =         1;
972                 out_ext->iJack =                0;
973                 out_ext->pins[0].baSourceID =   in_emb->bJackID;
974                 out_ext->pins[0].baSourcePin =  1;
975                 midi_function[i++] = (struct usb_descriptor_header *) out_ext;
976
977                 /* link it to the endpoint */
978                 ms_out_desc.baAssocJackID[n] = in_emb->bJackID;
979         }
980
981         /* configure the endpoint descriptors ... */
982         ms_out_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->in_ports);
983         ms_out_desc.bNumEmbMIDIJack = midi->in_ports;
984
985         ms_in_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->out_ports);
986         ms_in_desc.bNumEmbMIDIJack = midi->out_ports;
987
988         /* ... and add them to the list */
989         midi_function[i++] = (struct usb_descriptor_header *) &bulk_out_desc;
990         midi_function[i++] = (struct usb_descriptor_header *) &ms_out_desc;
991         midi_function[i++] = (struct usb_descriptor_header *) &bulk_in_desc;
992         midi_function[i++] = (struct usb_descriptor_header *) &ms_in_desc;
993         midi_function[i++] = NULL;
994
995         /*
996          * support all relevant hardware speeds... we expect that when
997          * hardware is dual speed, all bulk-capable endpoints work at
998          * both speeds
999          */
1000         /* copy descriptors, and track endpoint copies */
1001         f->fs_descriptors = usb_copy_descriptors(midi_function);
1002         if (!f->fs_descriptors)
1003                 goto fail_f_midi;
1004
1005         if (gadget_is_dualspeed(c->cdev->gadget)) {
1006                 bulk_in_desc.wMaxPacketSize = cpu_to_le16(512);
1007                 bulk_out_desc.wMaxPacketSize = cpu_to_le16(512);
1008                 f->hs_descriptors = usb_copy_descriptors(midi_function);
1009                 if (!f->hs_descriptors)
1010                         goto fail_f_midi;
1011
1012                 if (gadget_is_superspeed_plus(c->cdev->gadget)) {
1013                         f->ssp_descriptors = usb_copy_descriptors(midi_function);
1014                         if (!f->ssp_descriptors)
1015                                 goto fail_f_midi;
1016                 }
1017         }
1018
1019         kfree(midi_function);
1020
1021         return 0;
1022
1023 fail_f_midi:
1024         kfree(midi_function);
1025         usb_free_descriptors(f->hs_descriptors);
1026 fail:
1027         f_midi_unregister_card(midi);
1028 fail_register:
1029         ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
1030
1031         return status;
1032 }
1033
1034 static inline struct f_midi_opts *to_f_midi_opts(struct config_item *item)
1035 {
1036         return container_of(to_config_group(item), struct f_midi_opts,
1037                             func_inst.group);
1038 }
1039
1040 static void midi_attr_release(struct config_item *item)
1041 {
1042         struct f_midi_opts *opts = to_f_midi_opts(item);
1043
1044         usb_put_function_instance(&opts->func_inst);
1045 }
1046
1047 static struct configfs_item_operations midi_item_ops = {
1048         .release        = midi_attr_release,
1049 };
1050
1051 #define F_MIDI_OPT(name, test_limit, limit)                             \
1052 static ssize_t f_midi_opts_##name##_show(struct config_item *item, char *page) \
1053 {                                                                       \
1054         struct f_midi_opts *opts = to_f_midi_opts(item);                \
1055         int result;                                                     \
1056                                                                         \
1057         mutex_lock(&opts->lock);                                        \
1058         result = sprintf(page, "%d\n", opts->name);                     \
1059         mutex_unlock(&opts->lock);                                      \
1060                                                                         \
1061         return result;                                                  \
1062 }                                                                       \
1063                                                                         \
1064 static ssize_t f_midi_opts_##name##_store(struct config_item *item,     \
1065                                          const char *page, size_t len)  \
1066 {                                                                       \
1067         struct f_midi_opts *opts = to_f_midi_opts(item);                \
1068         int ret;                                                        \
1069         u32 num;                                                        \
1070                                                                         \
1071         mutex_lock(&opts->lock);                                        \
1072         if (opts->refcnt) {                                             \
1073                 ret = -EBUSY;                                           \
1074                 goto end;                                               \
1075         }                                                               \
1076                                                                         \
1077         ret = kstrtou32(page, 0, &num);                                 \
1078         if (ret)                                                        \
1079                 goto end;                                               \
1080                                                                         \
1081         if (test_limit && num > limit) {                                \
1082                 ret = -EINVAL;                                          \
1083                 goto end;                                               \
1084         }                                                               \
1085         opts->name = num;                                               \
1086         ret = len;                                                      \
1087                                                                         \
1088 end:                                                                    \
1089         mutex_unlock(&opts->lock);                                      \
1090         return ret;                                                     \
1091 }                                                                       \
1092                                                                         \
1093 CONFIGFS_ATTR(f_midi_opts_, name);
1094
1095 F_MIDI_OPT(index, true, SNDRV_CARDS);
1096 F_MIDI_OPT(buflen, false, 0);
1097 F_MIDI_OPT(qlen, false, 0);
1098 F_MIDI_OPT(in_ports, true, MAX_PORTS);
1099 F_MIDI_OPT(out_ports, true, MAX_PORTS);
1100
1101 static ssize_t f_midi_opts_id_show(struct config_item *item, char *page)
1102 {
1103         struct f_midi_opts *opts = to_f_midi_opts(item);
1104         int result;
1105
1106         mutex_lock(&opts->lock);
1107         if (opts->id) {
1108                 result = strlcpy(page, opts->id, PAGE_SIZE);
1109         } else {
1110                 page[0] = 0;
1111                 result = 0;
1112         }
1113
1114         mutex_unlock(&opts->lock);
1115
1116         return result;
1117 }
1118
1119 static ssize_t f_midi_opts_id_store(struct config_item *item,
1120                                     const char *page, size_t len)
1121 {
1122         struct f_midi_opts *opts = to_f_midi_opts(item);
1123         int ret;
1124         char *c;
1125
1126         mutex_lock(&opts->lock);
1127         if (opts->refcnt) {
1128                 ret = -EBUSY;
1129                 goto end;
1130         }
1131
1132         c = kstrndup(page, len, GFP_KERNEL);
1133         if (!c) {
1134                 ret = -ENOMEM;
1135                 goto end;
1136         }
1137         if (opts->id_allocated)
1138                 kfree(opts->id);
1139         opts->id = c;
1140         opts->id_allocated = true;
1141         ret = len;
1142 end:
1143         mutex_unlock(&opts->lock);
1144         return ret;
1145 }
1146
1147 CONFIGFS_ATTR(f_midi_opts_, id);
1148
1149 static struct configfs_attribute *midi_attrs[] = {
1150         &f_midi_opts_attr_index,
1151         &f_midi_opts_attr_buflen,
1152         &f_midi_opts_attr_qlen,
1153         &f_midi_opts_attr_in_ports,
1154         &f_midi_opts_attr_out_ports,
1155         &f_midi_opts_attr_id,
1156         NULL,
1157 };
1158
1159 static struct config_item_type midi_func_type = {
1160         .ct_item_ops    = &midi_item_ops,
1161         .ct_attrs       = midi_attrs,
1162         .ct_owner       = THIS_MODULE,
1163 };
1164
1165 static void f_midi_free_inst(struct usb_function_instance *f)
1166 {
1167         struct f_midi_opts *opts;
1168
1169         opts = container_of(f, struct f_midi_opts, func_inst);
1170
1171         if (opts->id_allocated)
1172                 kfree(opts->id);
1173
1174         kfree(opts);
1175 }
1176
1177 static struct usb_function_instance *f_midi_alloc_inst(void)
1178 {
1179         struct f_midi_opts *opts;
1180
1181         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1182         if (!opts)
1183                 return ERR_PTR(-ENOMEM);
1184
1185         mutex_init(&opts->lock);
1186         opts->func_inst.free_func_inst = f_midi_free_inst;
1187         opts->index = SNDRV_DEFAULT_IDX1;
1188         opts->id = SNDRV_DEFAULT_STR1;
1189         opts->buflen = 512;
1190         opts->qlen = 32;
1191         opts->in_ports = 1;
1192         opts->out_ports = 1;
1193
1194         config_group_init_type_name(&opts->func_inst.group, "",
1195                                     &midi_func_type);
1196
1197         return &opts->func_inst;
1198 }
1199
1200 static void f_midi_free(struct usb_function *f)
1201 {
1202         struct f_midi *midi;
1203         struct f_midi_opts *opts;
1204
1205         midi = func_to_midi(f);
1206         opts = container_of(f->fi, struct f_midi_opts, func_inst);
1207         kfree(midi->id);
1208         mutex_lock(&opts->lock);
1209         kfifo_free(&midi->in_req_fifo);
1210         kfree(midi);
1211         --opts->refcnt;
1212         mutex_unlock(&opts->lock);
1213 }
1214
1215 static void f_midi_unbind(struct usb_configuration *c, struct usb_function *f)
1216 {
1217         struct usb_composite_dev *cdev = f->config->cdev;
1218         struct f_midi *midi = func_to_midi(f);
1219         struct snd_card *card;
1220
1221         DBG(cdev, "unbind\n");
1222
1223         /* just to be sure */
1224         f_midi_disable(f);
1225
1226         card = midi->card;
1227         midi->card = NULL;
1228         if (card)
1229                 snd_card_free(card);
1230
1231         usb_free_all_descriptors(f);
1232 }
1233
1234 static struct usb_function *f_midi_alloc(struct usb_function_instance *fi)
1235 {
1236         struct f_midi *midi = NULL;
1237         struct f_midi_opts *opts;
1238         int status, i;
1239
1240         opts = container_of(fi, struct f_midi_opts, func_inst);
1241
1242         mutex_lock(&opts->lock);
1243         /* sanity check */
1244         if (opts->in_ports > MAX_PORTS || opts->out_ports > MAX_PORTS) {
1245                 status = -EINVAL;
1246                 goto setup_fail;
1247         }
1248
1249         /* allocate and initialize one new instance */
1250         midi = kzalloc(
1251                 sizeof(*midi) + opts->in_ports * sizeof(*midi->in_ports_array),
1252                 GFP_KERNEL);
1253         if (!midi) {
1254                 status = -ENOMEM;
1255                 goto setup_fail;
1256         }
1257
1258         for (i = 0; i < opts->in_ports; i++)
1259                 midi->in_ports_array[i].cable = i;
1260
1261         /* set up ALSA midi devices */
1262         midi->id = kstrdup(opts->id, GFP_KERNEL);
1263         if (opts->id && !midi->id) {
1264                 status = -ENOMEM;
1265                 goto midi_free;
1266         }
1267         midi->in_ports = opts->in_ports;
1268         midi->out_ports = opts->out_ports;
1269         midi->index = opts->index;
1270         midi->buflen = opts->buflen;
1271         midi->qlen = opts->qlen;
1272         midi->in_last_port = 0;
1273
1274         status = kfifo_alloc(&midi->in_req_fifo, midi->qlen, GFP_KERNEL);
1275         if (status)
1276                 goto midi_free;
1277
1278         spin_lock_init(&midi->transmit_lock);
1279
1280         ++opts->refcnt;
1281         mutex_unlock(&opts->lock);
1282
1283         midi->func.name         = "gmidi function";
1284         midi->func.bind         = f_midi_bind;
1285         midi->func.unbind       = f_midi_unbind;
1286         midi->func.set_alt      = f_midi_set_alt;
1287         midi->func.disable      = f_midi_disable;
1288         midi->func.free_func    = f_midi_free;
1289
1290         return &midi->func;
1291
1292 midi_free:
1293         if (midi)
1294                 kfree(midi->id);
1295         kfree(midi);
1296 setup_fail:
1297         mutex_unlock(&opts->lock);
1298
1299         return ERR_PTR(status);
1300 }
1301
1302 DECLARE_USB_FUNCTION_INIT(midi, f_midi_alloc_inst, f_midi_alloc);