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