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