]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/usb/gadget/gmidi.c
usb: gadget: add usb_endpoint_descriptor to struct usb_ep
[karo-tx-linux.git] / drivers / usb / gadget / gmidi.c
1 /*
2  * gmidi.c -- USB MIDI Gadget 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  * This software is distributed under the terms of the GNU General Public
9  * License ("GPL") version 2, as published by the Free Software Foundation.
10  *
11  * This code is based in part on:
12  *
13  * Gadget Zero driver, Copyright (C) 2003-2004 David Brownell.
14  * USB Audio driver, Copyright (C) 2002 by Takashi Iwai.
15  * USB MIDI driver, Copyright (C) 2002-2005 Clemens Ladisch.
16  *
17  * Refer to the USB Device Class Definition for MIDI Devices:
18  * http://www.usb.org/developers/devclass_docs/midi10.pdf
19  */
20
21 /* #define VERBOSE_DEBUG */
22
23 #include <linux/kernel.h>
24 #include <linux/slab.h>
25 #include <linux/utsname.h>
26 #include <linux/device.h>
27
28 #include <sound/core.h>
29 #include <sound/initval.h>
30 #include <sound/rawmidi.h>
31
32 #include <linux/usb/ch9.h>
33 #include <linux/usb/gadget.h>
34 #include <linux/usb/audio.h>
35 #include <linux/usb/midi.h>
36
37 #include "gadget_chips.h"
38
39
40 /*
41  * Kbuild is not very cooperative with respect to linking separately
42  * compiled library objects into one module.  So for now we won't use
43  * separate compilation ... ensuring init/exit sections work to shrink
44  * the runtime footprint, and giving us at least some parts of what
45  * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
46  */
47 #include "usbstring.c"
48 #include "config.c"
49 #include "epautoconf.c"
50
51 /*-------------------------------------------------------------------------*/
52
53
54 MODULE_AUTHOR("Ben Williamson");
55 MODULE_LICENSE("GPL v2");
56
57 #define DRIVER_VERSION "25 Jul 2006"
58
59 static const char shortname[] = "g_midi";
60 static const char longname[] = "MIDI Gadget";
61
62 static int index = SNDRV_DEFAULT_IDX1;
63 static char *id = SNDRV_DEFAULT_STR1;
64
65 module_param(index, int, 0444);
66 MODULE_PARM_DESC(index, "Index value for the USB MIDI Gadget adapter.");
67 module_param(id, charp, 0444);
68 MODULE_PARM_DESC(id, "ID string for the USB MIDI Gadget adapter.");
69
70 /* Some systems will want different product identifiers published in the
71  * device descriptor, either numbers or strings or both.  These string
72  * parameters are in UTF-8 (superset of ASCII's 7 bit characters).
73  */
74
75 static ushort idVendor;
76 module_param(idVendor, ushort, S_IRUGO);
77 MODULE_PARM_DESC(idVendor, "USB Vendor ID");
78
79 static ushort idProduct;
80 module_param(idProduct, ushort, S_IRUGO);
81 MODULE_PARM_DESC(idProduct, "USB Product ID");
82
83 static ushort bcdDevice;
84 module_param(bcdDevice, ushort, S_IRUGO);
85 MODULE_PARM_DESC(bcdDevice, "USB Device version (BCD)");
86
87 static char *iManufacturer;
88 module_param(iManufacturer, charp, S_IRUGO);
89 MODULE_PARM_DESC(iManufacturer, "USB Manufacturer string");
90
91 static char *iProduct;
92 module_param(iProduct, charp, S_IRUGO);
93 MODULE_PARM_DESC(iProduct, "USB Product string");
94
95 static char *iSerialNumber;
96 module_param(iSerialNumber, charp, S_IRUGO);
97 MODULE_PARM_DESC(iSerialNumber, "SerialNumber");
98
99 /*
100  * this version autoconfigures as much as possible,
101  * which is reasonable for most "bulk-only" drivers.
102  */
103 static const char *EP_IN_NAME;
104 static const char *EP_OUT_NAME;
105
106
107 /* big enough to hold our biggest descriptor */
108 #define USB_BUFSIZ 256
109
110
111 /* This is a gadget, and the IN/OUT naming is from the host's perspective.
112    USB -> OUT endpoint -> rawmidi
113    USB <- IN endpoint  <- rawmidi */
114 struct gmidi_in_port {
115         struct gmidi_device* dev;
116         int active;
117         uint8_t cable;          /* cable number << 4 */
118         uint8_t state;
119 #define STATE_UNKNOWN   0
120 #define STATE_1PARAM    1
121 #define STATE_2PARAM_1  2
122 #define STATE_2PARAM_2  3
123 #define STATE_SYSEX_0   4
124 #define STATE_SYSEX_1   5
125 #define STATE_SYSEX_2   6
126         uint8_t data[2];
127 };
128
129 struct gmidi_device {
130         spinlock_t              lock;
131         struct usb_gadget       *gadget;
132         struct usb_request      *req;           /* for control responses */
133         u8                      config;
134         struct usb_ep           *in_ep, *out_ep;
135         struct snd_card         *card;
136         struct snd_rawmidi      *rmidi;
137         struct snd_rawmidi_substream *in_substream;
138         struct snd_rawmidi_substream *out_substream;
139
140         /* For the moment we only support one port in
141            each direction, but in_port is kept as a
142            separate struct so we can have more later. */
143         struct gmidi_in_port    in_port;
144         unsigned long           out_triggered;
145         struct tasklet_struct   tasklet;
146 };
147
148 static void gmidi_transmit(struct gmidi_device* dev, struct usb_request* req);
149
150
151 #define DBG(d, fmt, args...) \
152         dev_dbg(&(d)->gadget->dev , fmt , ## args)
153 #define VDBG(d, fmt, args...) \
154         dev_vdbg(&(d)->gadget->dev , fmt , ## args)
155 #define ERROR(d, fmt, args...) \
156         dev_err(&(d)->gadget->dev , fmt , ## args)
157 #define INFO(d, fmt, args...) \
158         dev_info(&(d)->gadget->dev , fmt , ## args)
159
160
161 static unsigned buflen = 256;
162 static unsigned qlen = 32;
163
164 module_param(buflen, uint, S_IRUGO);
165 module_param(qlen, uint, S_IRUGO);
166
167
168 /* Thanks to Grey Innovation for donating this product ID.
169  *
170  * DO NOT REUSE THESE IDs with a protocol-incompatible driver!!  Ever!!
171  * Instead:  allocate your own, using normal USB-IF procedures.
172  */
173 #define DRIVER_VENDOR_NUM       0x17b3          /* Grey Innovation */
174 #define DRIVER_PRODUCT_NUM      0x0004          /* Linux-USB "MIDI Gadget" */
175
176
177 /*
178  * DESCRIPTORS ... most are static, but strings and (full)
179  * configuration descriptors are built on demand.
180  */
181
182 #define STRING_MANUFACTURER     25
183 #define STRING_PRODUCT          42
184 #define STRING_SERIAL           101
185 #define STRING_MIDI_GADGET      250
186
187 /* We only have the one configuration, it's number 1. */
188 #define GMIDI_CONFIG            1
189
190 /* We have two interfaces- AudioControl and MIDIStreaming */
191 #define GMIDI_AC_INTERFACE      0
192 #define GMIDI_MS_INTERFACE      1
193 #define GMIDI_NUM_INTERFACES    2
194
195 DECLARE_UAC_AC_HEADER_DESCRIPTOR(1);
196 DECLARE_USB_MIDI_OUT_JACK_DESCRIPTOR(1);
197 DECLARE_USB_MS_ENDPOINT_DESCRIPTOR(1);
198
199 /* B.1  Device Descriptor */
200 static struct usb_device_descriptor device_desc = {
201         .bLength =              USB_DT_DEVICE_SIZE,
202         .bDescriptorType =      USB_DT_DEVICE,
203         .bcdUSB =               cpu_to_le16(0x0200),
204         .bDeviceClass =         USB_CLASS_PER_INTERFACE,
205         .idVendor =             cpu_to_le16(DRIVER_VENDOR_NUM),
206         .idProduct =            cpu_to_le16(DRIVER_PRODUCT_NUM),
207         .iManufacturer =        STRING_MANUFACTURER,
208         .iProduct =             STRING_PRODUCT,
209         .bNumConfigurations =   1,
210 };
211
212 /* B.2  Configuration Descriptor */
213 static struct usb_config_descriptor config_desc = {
214         .bLength =              USB_DT_CONFIG_SIZE,
215         .bDescriptorType =      USB_DT_CONFIG,
216         /* compute wTotalLength on the fly */
217         .bNumInterfaces =       GMIDI_NUM_INTERFACES,
218         .bConfigurationValue =  GMIDI_CONFIG,
219         .iConfiguration =       STRING_MIDI_GADGET,
220         /*
221          * FIXME: When embedding this driver in a device,
222          * these need to be set to reflect the actual
223          * power properties of the device. Is it selfpowered?
224          */
225         .bmAttributes =         USB_CONFIG_ATT_ONE,
226         .bMaxPower =            CONFIG_USB_GADGET_VBUS_DRAW / 2,
227 };
228
229 /* B.3.1  Standard AC Interface Descriptor */
230 static const struct usb_interface_descriptor ac_interface_desc = {
231         .bLength =              USB_DT_INTERFACE_SIZE,
232         .bDescriptorType =      USB_DT_INTERFACE,
233         .bInterfaceNumber =     GMIDI_AC_INTERFACE,
234         .bNumEndpoints =        0,
235         .bInterfaceClass =      USB_CLASS_AUDIO,
236         .bInterfaceSubClass =   USB_SUBCLASS_AUDIOCONTROL,
237         .iInterface =           STRING_MIDI_GADGET,
238 };
239
240 /* B.3.2  Class-Specific AC Interface Descriptor */
241 static const struct uac1_ac_header_descriptor_1 ac_header_desc = {
242         .bLength =              UAC_DT_AC_HEADER_SIZE(1),
243         .bDescriptorType =      USB_DT_CS_INTERFACE,
244         .bDescriptorSubtype =   USB_MS_HEADER,
245         .bcdADC =               cpu_to_le16(0x0100),
246         .wTotalLength =         cpu_to_le16(UAC_DT_AC_HEADER_SIZE(1)),
247         .bInCollection =        1,
248         .baInterfaceNr = {
249                 [0] =           GMIDI_MS_INTERFACE,
250         }
251 };
252
253 /* B.4.1  Standard MS Interface Descriptor */
254 static const struct usb_interface_descriptor ms_interface_desc = {
255         .bLength =              USB_DT_INTERFACE_SIZE,
256         .bDescriptorType =      USB_DT_INTERFACE,
257         .bInterfaceNumber =     GMIDI_MS_INTERFACE,
258         .bNumEndpoints =        2,
259         .bInterfaceClass =      USB_CLASS_AUDIO,
260         .bInterfaceSubClass =   USB_SUBCLASS_MIDISTREAMING,
261         .iInterface =           STRING_MIDI_GADGET,
262 };
263
264 /* B.4.2  Class-Specific MS Interface Descriptor */
265 static const struct usb_ms_header_descriptor ms_header_desc = {
266         .bLength =              USB_DT_MS_HEADER_SIZE,
267         .bDescriptorType =      USB_DT_CS_INTERFACE,
268         .bDescriptorSubtype =   USB_MS_HEADER,
269         .bcdMSC =               cpu_to_le16(0x0100),
270         .wTotalLength =         cpu_to_le16(USB_DT_MS_HEADER_SIZE
271                                 + 2*USB_DT_MIDI_IN_SIZE
272                                 + 2*USB_DT_MIDI_OUT_SIZE(1)),
273 };
274
275 #define JACK_IN_EMB     1
276 #define JACK_IN_EXT     2
277 #define JACK_OUT_EMB    3
278 #define JACK_OUT_EXT    4
279
280 /* B.4.3  MIDI IN Jack Descriptors */
281 static const struct usb_midi_in_jack_descriptor jack_in_emb_desc = {
282         .bLength =              USB_DT_MIDI_IN_SIZE,
283         .bDescriptorType =      USB_DT_CS_INTERFACE,
284         .bDescriptorSubtype =   USB_MS_MIDI_IN_JACK,
285         .bJackType =            USB_MS_EMBEDDED,
286         .bJackID =              JACK_IN_EMB,
287 };
288
289 static const struct usb_midi_in_jack_descriptor jack_in_ext_desc = {
290         .bLength =              USB_DT_MIDI_IN_SIZE,
291         .bDescriptorType =      USB_DT_CS_INTERFACE,
292         .bDescriptorSubtype =   USB_MS_MIDI_IN_JACK,
293         .bJackType =            USB_MS_EXTERNAL,
294         .bJackID =              JACK_IN_EXT,
295 };
296
297 /* B.4.4  MIDI OUT Jack Descriptors */
298 static const struct usb_midi_out_jack_descriptor_1 jack_out_emb_desc = {
299         .bLength =              USB_DT_MIDI_OUT_SIZE(1),
300         .bDescriptorType =      USB_DT_CS_INTERFACE,
301         .bDescriptorSubtype =   USB_MS_MIDI_OUT_JACK,
302         .bJackType =            USB_MS_EMBEDDED,
303         .bJackID =              JACK_OUT_EMB,
304         .bNrInputPins =         1,
305         .pins = {
306                 [0] = {
307                         .baSourceID =   JACK_IN_EXT,
308                         .baSourcePin =  1,
309                 }
310         }
311 };
312
313 static const struct usb_midi_out_jack_descriptor_1 jack_out_ext_desc = {
314         .bLength =              USB_DT_MIDI_OUT_SIZE(1),
315         .bDescriptorType =      USB_DT_CS_INTERFACE,
316         .bDescriptorSubtype =   USB_MS_MIDI_OUT_JACK,
317         .bJackType =            USB_MS_EXTERNAL,
318         .bJackID =              JACK_OUT_EXT,
319         .bNrInputPins =         1,
320         .pins = {
321                 [0] = {
322                         .baSourceID =   JACK_IN_EMB,
323                         .baSourcePin =  1,
324                 }
325         }
326 };
327
328 /* B.5.1  Standard Bulk OUT Endpoint Descriptor */
329 static struct usb_endpoint_descriptor bulk_out_desc = {
330         .bLength =              USB_DT_ENDPOINT_AUDIO_SIZE,
331         .bDescriptorType =      USB_DT_ENDPOINT,
332         .bEndpointAddress =     USB_DIR_OUT,
333         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
334 };
335
336 /* B.5.2  Class-specific MS Bulk OUT Endpoint Descriptor */
337 static const struct usb_ms_endpoint_descriptor_1 ms_out_desc = {
338         .bLength =              USB_DT_MS_ENDPOINT_SIZE(1),
339         .bDescriptorType =      USB_DT_CS_ENDPOINT,
340         .bDescriptorSubtype =   USB_MS_GENERAL,
341         .bNumEmbMIDIJack =      1,
342         .baAssocJackID = {
343                 [0] =           JACK_IN_EMB,
344         }
345 };
346
347 /* B.6.1  Standard Bulk IN Endpoint Descriptor */
348 static struct usb_endpoint_descriptor bulk_in_desc = {
349         .bLength =              USB_DT_ENDPOINT_AUDIO_SIZE,
350         .bDescriptorType =      USB_DT_ENDPOINT,
351         .bEndpointAddress =     USB_DIR_IN,
352         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
353 };
354
355 /* B.6.2  Class-specific MS Bulk IN Endpoint Descriptor */
356 static const struct usb_ms_endpoint_descriptor_1 ms_in_desc = {
357         .bLength =              USB_DT_MS_ENDPOINT_SIZE(1),
358         .bDescriptorType =      USB_DT_CS_ENDPOINT,
359         .bDescriptorSubtype =   USB_MS_GENERAL,
360         .bNumEmbMIDIJack =      1,
361         .baAssocJackID = {
362                 [0] =           JACK_OUT_EMB,
363         }
364 };
365
366 static const struct usb_descriptor_header *gmidi_function [] = {
367         (struct usb_descriptor_header *)&ac_interface_desc,
368         (struct usb_descriptor_header *)&ac_header_desc,
369         (struct usb_descriptor_header *)&ms_interface_desc,
370
371         (struct usb_descriptor_header *)&ms_header_desc,
372         (struct usb_descriptor_header *)&jack_in_emb_desc,
373         (struct usb_descriptor_header *)&jack_in_ext_desc,
374         (struct usb_descriptor_header *)&jack_out_emb_desc,
375         (struct usb_descriptor_header *)&jack_out_ext_desc,
376         /* If you add more jacks, update ms_header_desc.wTotalLength */
377
378         (struct usb_descriptor_header *)&bulk_out_desc,
379         (struct usb_descriptor_header *)&ms_out_desc,
380         (struct usb_descriptor_header *)&bulk_in_desc,
381         (struct usb_descriptor_header *)&ms_in_desc,
382         NULL,
383 };
384
385 static char manufacturer[50];
386 static char product_desc[40] = "MIDI Gadget";
387 static char serial_number[20];
388
389 /* static strings, in UTF-8 */
390 static struct usb_string strings [] = {
391         { STRING_MANUFACTURER, manufacturer, },
392         { STRING_PRODUCT, product_desc, },
393         { STRING_SERIAL, serial_number, },
394         { STRING_MIDI_GADGET, longname, },
395         {  }                    /* end of list */
396 };
397
398 static struct usb_gadget_strings stringtab = {
399         .language       = 0x0409,       /* en-us */
400         .strings        = strings,
401 };
402
403 static int config_buf(struct usb_gadget *gadget,
404                 u8 *buf, u8 type, unsigned index)
405 {
406         int len;
407
408         /* only one configuration */
409         if (index != 0) {
410                 return -EINVAL;
411         }
412         len = usb_gadget_config_buf(&config_desc,
413                         buf, USB_BUFSIZ, gmidi_function);
414         if (len < 0) {
415                 return len;
416         }
417         ((struct usb_config_descriptor *)buf)->bDescriptorType = type;
418         return len;
419 }
420
421 static struct usb_request *alloc_ep_req(struct usb_ep *ep, unsigned length)
422 {
423         struct usb_request      *req;
424
425         req = usb_ep_alloc_request(ep, GFP_ATOMIC);
426         if (req) {
427                 req->length = length;
428                 req->buf = kmalloc(length, GFP_ATOMIC);
429                 if (!req->buf) {
430                         usb_ep_free_request(ep, req);
431                         req = NULL;
432                 }
433         }
434         return req;
435 }
436
437 static void free_ep_req(struct usb_ep *ep, struct usb_request *req)
438 {
439         kfree(req->buf);
440         usb_ep_free_request(ep, req);
441 }
442
443 static const uint8_t gmidi_cin_length[] = {
444         0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
445 };
446
447 /*
448  * Receives a chunk of MIDI data.
449  */
450 static void gmidi_read_data(struct usb_ep *ep, int cable,
451                                    uint8_t *data, int length)
452 {
453         struct gmidi_device *dev = ep->driver_data;
454         /* cable is ignored, because for now we only have one. */
455
456         if (!dev->out_substream) {
457                 /* Nobody is listening - throw it on the floor. */
458                 return;
459         }
460         if (!test_bit(dev->out_substream->number, &dev->out_triggered)) {
461                 return;
462         }
463         snd_rawmidi_receive(dev->out_substream, data, length);
464 }
465
466 static void gmidi_handle_out_data(struct usb_ep *ep, struct usb_request *req)
467 {
468         unsigned i;
469         u8 *buf = req->buf;
470
471         for (i = 0; i + 3 < req->actual; i += 4) {
472                 if (buf[i] != 0) {
473                         int cable = buf[i] >> 4;
474                         int length = gmidi_cin_length[buf[i] & 0x0f];
475                         gmidi_read_data(ep, cable, &buf[i + 1], length);
476                 }
477         }
478 }
479
480 static void gmidi_complete(struct usb_ep *ep, struct usb_request *req)
481 {
482         struct gmidi_device *dev = ep->driver_data;
483         int status = req->status;
484
485         switch (status) {
486         case 0:                         /* normal completion */
487                 if (ep == dev->out_ep) {
488                         /* we received stuff.
489                            req is queued again, below */
490                         gmidi_handle_out_data(ep, req);
491                 } else if (ep == dev->in_ep) {
492                         /* our transmit completed.
493                            see if there's more to go.
494                            gmidi_transmit eats req, don't queue it again. */
495                         gmidi_transmit(dev, req);
496                         return;
497                 }
498                 break;
499
500         /* this endpoint is normally active while we're configured */
501         case -ECONNABORTED:             /* hardware forced ep reset */
502         case -ECONNRESET:               /* request dequeued */
503         case -ESHUTDOWN:                /* disconnect from host */
504                 VDBG(dev, "%s gone (%d), %d/%d\n", ep->name, status,
505                                 req->actual, req->length);
506                 if (ep == dev->out_ep) {
507                         gmidi_handle_out_data(ep, req);
508                 }
509                 free_ep_req(ep, req);
510                 return;
511
512         case -EOVERFLOW:                /* buffer overrun on read means that
513                                          * we didn't provide a big enough
514                                          * buffer.
515                                          */
516         default:
517                 DBG(dev, "%s complete --> %d, %d/%d\n", ep->name,
518                                 status, req->actual, req->length);
519                 break;
520         case -EREMOTEIO:                /* short read */
521                 break;
522         }
523
524         status = usb_ep_queue(ep, req, GFP_ATOMIC);
525         if (status) {
526                 ERROR(dev, "kill %s:  resubmit %d bytes --> %d\n",
527                                 ep->name, req->length, status);
528                 usb_ep_set_halt(ep);
529                 /* FIXME recover later ... somehow */
530         }
531 }
532
533 static int set_gmidi_config(struct gmidi_device *dev, gfp_t gfp_flags)
534 {
535         int err = 0;
536         struct usb_request *req;
537         struct usb_ep *ep;
538         unsigned i;
539
540         dev->in_ep->desc = &bulk_in_desc;
541         err = usb_ep_enable(dev->in_ep);
542         if (err) {
543                 ERROR(dev, "can't start %s: %d\n", dev->in_ep->name, err);
544                 goto fail;
545         }
546         dev->in_ep->driver_data = dev;
547
548         dev->out_ep->desc = &bulk_out_desc;
549         err = usb_ep_enable(dev->out_ep);
550         if (err) {
551                 ERROR(dev, "can't start %s: %d\n", dev->out_ep->name, err);
552                 goto fail;
553         }
554         dev->out_ep->driver_data = dev;
555
556         /* allocate a bunch of read buffers and queue them all at once. */
557         ep = dev->out_ep;
558         for (i = 0; i < qlen && err == 0; i++) {
559                 req = alloc_ep_req(ep, buflen);
560                 if (req) {
561                         req->complete = gmidi_complete;
562                         err = usb_ep_queue(ep, req, GFP_ATOMIC);
563                         if (err) {
564                                 DBG(dev, "%s queue req: %d\n", ep->name, err);
565                         }
566                 } else {
567                         err = -ENOMEM;
568                 }
569         }
570 fail:
571         /* caller is responsible for cleanup on error */
572         return err;
573 }
574
575
576 static void gmidi_reset_config(struct gmidi_device *dev)
577 {
578         if (dev->config == 0) {
579                 return;
580         }
581
582         DBG(dev, "reset config\n");
583
584         /* just disable endpoints, forcing completion of pending i/o.
585          * all our completion handlers free their requests in this case.
586          */
587         usb_ep_disable(dev->in_ep);
588         usb_ep_disable(dev->out_ep);
589         dev->config = 0;
590 }
591
592 /* change our operational config.  this code must agree with the code
593  * that returns config descriptors, and altsetting code.
594  *
595  * it's also responsible for power management interactions. some
596  * configurations might not work with our current power sources.
597  *
598  * note that some device controller hardware will constrain what this
599  * code can do, perhaps by disallowing more than one configuration or
600  * by limiting configuration choices (like the pxa2xx).
601  */
602 static int
603 gmidi_set_config(struct gmidi_device *dev, unsigned number, gfp_t gfp_flags)
604 {
605         int result = 0;
606         struct usb_gadget *gadget = dev->gadget;
607
608 #if 0
609         /* FIXME */
610         /* Hacking this bit out fixes a bug where on receipt of two
611            USB_REQ_SET_CONFIGURATION messages, we end up with no
612            buffered OUT requests waiting for data. This is clearly
613            hiding a bug elsewhere, because if the config didn't
614            change then we really shouldn't do anything. */
615         /* Having said that, when we do "change" from config 1
616            to config 1, we at least gmidi_reset_config() which
617            clears out any requests on endpoints, so it's not like
618            we leak or anything. */
619         if (number == dev->config) {
620                 return 0;
621         }
622 #endif
623
624         gmidi_reset_config(dev);
625
626         switch (number) {
627         case GMIDI_CONFIG:
628                 result = set_gmidi_config(dev, gfp_flags);
629                 break;
630         default:
631                 result = -EINVAL;
632                 /* FALL THROUGH */
633         case 0:
634                 return result;
635         }
636
637         if (!result && (!dev->in_ep || !dev->out_ep)) {
638                 result = -ENODEV;
639         }
640         if (result) {
641                 gmidi_reset_config(dev);
642         } else {
643                 char *speed;
644
645                 switch (gadget->speed) {
646                 case USB_SPEED_LOW:     speed = "low"; break;
647                 case USB_SPEED_FULL:    speed = "full"; break;
648                 case USB_SPEED_HIGH:    speed = "high"; break;
649                 default:                speed = "?"; break;
650                 }
651
652                 dev->config = number;
653                 INFO(dev, "%s speed\n", speed);
654         }
655         return result;
656 }
657
658
659 static void gmidi_setup_complete(struct usb_ep *ep, struct usb_request *req)
660 {
661         if (req->status || req->actual != req->length) {
662                 DBG((struct gmidi_device *) ep->driver_data,
663                                 "setup complete --> %d, %d/%d\n",
664                                 req->status, req->actual, req->length);
665         }
666 }
667
668 /*
669  * The setup() callback implements all the ep0 functionality that's
670  * not handled lower down, in hardware or the hardware driver (like
671  * device and endpoint feature flags, and their status).  It's all
672  * housekeeping for the gadget function we're implementing.  Most of
673  * the work is in config-specific setup.
674  */
675 static int gmidi_setup(struct usb_gadget *gadget,
676                         const struct usb_ctrlrequest *ctrl)
677 {
678         struct gmidi_device *dev = get_gadget_data(gadget);
679         struct usb_request *req = dev->req;
680         int value = -EOPNOTSUPP;
681         u16 w_index = le16_to_cpu(ctrl->wIndex);
682         u16 w_value = le16_to_cpu(ctrl->wValue);
683         u16 w_length = le16_to_cpu(ctrl->wLength);
684
685         /* usually this stores reply data in the pre-allocated ep0 buffer,
686          * but config change events will reconfigure hardware.
687          */
688         req->zero = 0;
689         switch (ctrl->bRequest) {
690
691         case USB_REQ_GET_DESCRIPTOR:
692                 if (ctrl->bRequestType != USB_DIR_IN) {
693                         goto unknown;
694                 }
695                 switch (w_value >> 8) {
696
697                 case USB_DT_DEVICE:
698                         value = min(w_length, (u16) sizeof(device_desc));
699                         memcpy(req->buf, &device_desc, value);
700                         break;
701                 case USB_DT_CONFIG:
702                         value = config_buf(gadget, req->buf,
703                                         w_value >> 8,
704                                         w_value & 0xff);
705                         if (value >= 0) {
706                                 value = min(w_length, (u16)value);
707                         }
708                         break;
709
710                 case USB_DT_STRING:
711                         /* wIndex == language code.
712                          * this driver only handles one language, you can
713                          * add string tables for other languages, using
714                          * any UTF-8 characters
715                          */
716                         value = usb_gadget_get_string(&stringtab,
717                                         w_value & 0xff, req->buf);
718                         if (value >= 0) {
719                                 value = min(w_length, (u16)value);
720                         }
721                         break;
722                 }
723                 break;
724
725         /* currently two configs, two speeds */
726         case USB_REQ_SET_CONFIGURATION:
727                 if (ctrl->bRequestType != 0) {
728                         goto unknown;
729                 }
730                 if (gadget->a_hnp_support) {
731                         DBG(dev, "HNP available\n");
732                 } else if (gadget->a_alt_hnp_support) {
733                         DBG(dev, "HNP needs a different root port\n");
734                 } else {
735                         VDBG(dev, "HNP inactive\n");
736                 }
737                 spin_lock(&dev->lock);
738                 value = gmidi_set_config(dev, w_value, GFP_ATOMIC);
739                 spin_unlock(&dev->lock);
740                 break;
741         case USB_REQ_GET_CONFIGURATION:
742                 if (ctrl->bRequestType != USB_DIR_IN) {
743                         goto unknown;
744                 }
745                 *(u8 *)req->buf = dev->config;
746                 value = min(w_length, (u16)1);
747                 break;
748
749         /* until we add altsetting support, or other interfaces,
750          * only 0/0 are possible.  pxa2xx only supports 0/0 (poorly)
751          * and already killed pending endpoint I/O.
752          */
753         case USB_REQ_SET_INTERFACE:
754                 if (ctrl->bRequestType != USB_RECIP_INTERFACE) {
755                         goto unknown;
756                 }
757                 spin_lock(&dev->lock);
758                 if (dev->config && w_index < GMIDI_NUM_INTERFACES
759                         && w_value == 0)
760                 {
761                         u8 config = dev->config;
762
763                         /* resets interface configuration, forgets about
764                          * previous transaction state (queued bufs, etc)
765                          * and re-inits endpoint state (toggle etc)
766                          * no response queued, just zero status == success.
767                          * if we had more than one interface we couldn't
768                          * use this "reset the config" shortcut.
769                          */
770                         gmidi_reset_config(dev);
771                         gmidi_set_config(dev, config, GFP_ATOMIC);
772                         value = 0;
773                 }
774                 spin_unlock(&dev->lock);
775                 break;
776         case USB_REQ_GET_INTERFACE:
777                 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE)) {
778                         goto unknown;
779                 }
780                 if (!dev->config) {
781                         break;
782                 }
783                 if (w_index >= GMIDI_NUM_INTERFACES) {
784                         value = -EDOM;
785                         break;
786                 }
787                 *(u8 *)req->buf = 0;
788                 value = min(w_length, (u16)1);
789                 break;
790
791         default:
792 unknown:
793                 VDBG(dev, "unknown control req%02x.%02x v%04x i%04x l%d\n",
794                         ctrl->bRequestType, ctrl->bRequest,
795                         w_value, w_index, w_length);
796         }
797
798         /* respond with data transfer before status phase? */
799         if (value >= 0) {
800                 req->length = value;
801                 req->zero = value < w_length;
802                 value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
803                 if (value < 0) {
804                         DBG(dev, "ep_queue --> %d\n", value);
805                         req->status = 0;
806                         gmidi_setup_complete(gadget->ep0, req);
807                 }
808         }
809
810         /* device either stalls (value < 0) or reports success */
811         return value;
812 }
813
814 static void gmidi_disconnect(struct usb_gadget *gadget)
815 {
816         struct gmidi_device *dev = get_gadget_data(gadget);
817         unsigned long flags;
818
819         spin_lock_irqsave(&dev->lock, flags);
820         gmidi_reset_config(dev);
821
822         /* a more significant application might have some non-usb
823          * activities to quiesce here, saving resources like power
824          * or pushing the notification up a network stack.
825          */
826         spin_unlock_irqrestore(&dev->lock, flags);
827
828         /* next we may get setup() calls to enumerate new connections;
829          * or an unbind() during shutdown (including removing module).
830          */
831 }
832
833 static void /* __init_or_exit */ gmidi_unbind(struct usb_gadget *gadget)
834 {
835         struct gmidi_device *dev = get_gadget_data(gadget);
836         struct snd_card *card;
837
838         DBG(dev, "unbind\n");
839
840         card = dev->card;
841         dev->card = NULL;
842         if (card) {
843                 snd_card_free(card);
844         }
845
846         /* we've already been disconnected ... no i/o is active */
847         if (dev->req) {
848                 dev->req->length = USB_BUFSIZ;
849                 free_ep_req(gadget->ep0, dev->req);
850         }
851         kfree(dev);
852         set_gadget_data(gadget, NULL);
853 }
854
855 static int gmidi_snd_free(struct snd_device *device)
856 {
857         return 0;
858 }
859
860 static void gmidi_transmit_packet(struct usb_request *req, uint8_t p0,
861                                         uint8_t p1, uint8_t p2, uint8_t p3)
862 {
863         unsigned length = req->length;
864         u8 *buf = (u8 *)req->buf + length;
865
866         buf[0] = p0;
867         buf[1] = p1;
868         buf[2] = p2;
869         buf[3] = p3;
870         req->length = length + 4;
871 }
872
873 /*
874  * Converts MIDI commands to USB MIDI packets.
875  */
876 static void gmidi_transmit_byte(struct usb_request *req,
877                                 struct gmidi_in_port *port, uint8_t b)
878 {
879         uint8_t p0 = port->cable;
880
881         if (b >= 0xf8) {
882                 gmidi_transmit_packet(req, p0 | 0x0f, b, 0, 0);
883         } else if (b >= 0xf0) {
884                 switch (b) {
885                 case 0xf0:
886                         port->data[0] = b;
887                         port->state = STATE_SYSEX_1;
888                         break;
889                 case 0xf1:
890                 case 0xf3:
891                         port->data[0] = b;
892                         port->state = STATE_1PARAM;
893                         break;
894                 case 0xf2:
895                         port->data[0] = b;
896                         port->state = STATE_2PARAM_1;
897                         break;
898                 case 0xf4:
899                 case 0xf5:
900                         port->state = STATE_UNKNOWN;
901                         break;
902                 case 0xf6:
903                         gmidi_transmit_packet(req, p0 | 0x05, 0xf6, 0, 0);
904                         port->state = STATE_UNKNOWN;
905                         break;
906                 case 0xf7:
907                         switch (port->state) {
908                         case STATE_SYSEX_0:
909                                 gmidi_transmit_packet(req,
910                                         p0 | 0x05, 0xf7, 0, 0);
911                                 break;
912                         case STATE_SYSEX_1:
913                                 gmidi_transmit_packet(req,
914                                         p0 | 0x06, port->data[0], 0xf7, 0);
915                                 break;
916                         case STATE_SYSEX_2:
917                                 gmidi_transmit_packet(req,
918                                         p0 | 0x07, port->data[0],
919                                         port->data[1], 0xf7);
920                                 break;
921                         }
922                         port->state = STATE_UNKNOWN;
923                         break;
924                 }
925         } else if (b >= 0x80) {
926                 port->data[0] = b;
927                 if (b >= 0xc0 && b <= 0xdf)
928                         port->state = STATE_1PARAM;
929                 else
930                         port->state = STATE_2PARAM_1;
931         } else { /* b < 0x80 */
932                 switch (port->state) {
933                 case STATE_1PARAM:
934                         if (port->data[0] < 0xf0) {
935                                 p0 |= port->data[0] >> 4;
936                         } else {
937                                 p0 |= 0x02;
938                                 port->state = STATE_UNKNOWN;
939                         }
940                         gmidi_transmit_packet(req, p0, port->data[0], b, 0);
941                         break;
942                 case STATE_2PARAM_1:
943                         port->data[1] = b;
944                         port->state = STATE_2PARAM_2;
945                         break;
946                 case STATE_2PARAM_2:
947                         if (port->data[0] < 0xf0) {
948                                 p0 |= port->data[0] >> 4;
949                                 port->state = STATE_2PARAM_1;
950                         } else {
951                                 p0 |= 0x03;
952                                 port->state = STATE_UNKNOWN;
953                         }
954                         gmidi_transmit_packet(req,
955                                 p0, port->data[0], port->data[1], b);
956                         break;
957                 case STATE_SYSEX_0:
958                         port->data[0] = b;
959                         port->state = STATE_SYSEX_1;
960                         break;
961                 case STATE_SYSEX_1:
962                         port->data[1] = b;
963                         port->state = STATE_SYSEX_2;
964                         break;
965                 case STATE_SYSEX_2:
966                         gmidi_transmit_packet(req,
967                                 p0 | 0x04, port->data[0], port->data[1], b);
968                         port->state = STATE_SYSEX_0;
969                         break;
970                 }
971         }
972 }
973
974 static void gmidi_transmit(struct gmidi_device *dev, struct usb_request *req)
975 {
976         struct usb_ep *ep = dev->in_ep;
977         struct gmidi_in_port *port = &dev->in_port;
978
979         if (!ep) {
980                 return;
981         }
982         if (!req) {
983                 req = alloc_ep_req(ep, buflen);
984         }
985         if (!req) {
986                 ERROR(dev, "gmidi_transmit: alloc_ep_request failed\n");
987                 return;
988         }
989         req->length = 0;
990         req->complete = gmidi_complete;
991
992         if (port->active) {
993                 while (req->length + 3 < buflen) {
994                         uint8_t b;
995                         if (snd_rawmidi_transmit(dev->in_substream, &b, 1)
996                                 != 1)
997                         {
998                                 port->active = 0;
999                                 break;
1000                         }
1001                         gmidi_transmit_byte(req, port, b);
1002                 }
1003         }
1004         if (req->length > 0) {
1005                 usb_ep_queue(ep, req, GFP_ATOMIC);
1006         } else {
1007                 free_ep_req(ep, req);
1008         }
1009 }
1010
1011 static void gmidi_in_tasklet(unsigned long data)
1012 {
1013         struct gmidi_device *dev = (struct gmidi_device *)data;
1014
1015         gmidi_transmit(dev, NULL);
1016 }
1017
1018 static int gmidi_in_open(struct snd_rawmidi_substream *substream)
1019 {
1020         struct gmidi_device *dev = substream->rmidi->private_data;
1021
1022         VDBG(dev, "gmidi_in_open\n");
1023         dev->in_substream = substream;
1024         dev->in_port.state = STATE_UNKNOWN;
1025         return 0;
1026 }
1027
1028 static int gmidi_in_close(struct snd_rawmidi_substream *substream)
1029 {
1030         struct gmidi_device *dev = substream->rmidi->private_data;
1031
1032         VDBG(dev, "gmidi_in_close\n");
1033         return 0;
1034 }
1035
1036 static void gmidi_in_trigger(struct snd_rawmidi_substream *substream, int up)
1037 {
1038         struct gmidi_device *dev = substream->rmidi->private_data;
1039
1040         VDBG(dev, "gmidi_in_trigger %d\n", up);
1041         dev->in_port.active = up;
1042         if (up) {
1043                 tasklet_hi_schedule(&dev->tasklet);
1044         }
1045 }
1046
1047 static int gmidi_out_open(struct snd_rawmidi_substream *substream)
1048 {
1049         struct gmidi_device *dev = substream->rmidi->private_data;
1050
1051         VDBG(dev, "gmidi_out_open\n");
1052         dev->out_substream = substream;
1053         return 0;
1054 }
1055
1056 static int gmidi_out_close(struct snd_rawmidi_substream *substream)
1057 {
1058         struct gmidi_device *dev = substream->rmidi->private_data;
1059
1060         VDBG(dev, "gmidi_out_close\n");
1061         return 0;
1062 }
1063
1064 static void gmidi_out_trigger(struct snd_rawmidi_substream *substream, int up)
1065 {
1066         struct gmidi_device *dev = substream->rmidi->private_data;
1067
1068         VDBG(dev, "gmidi_out_trigger %d\n", up);
1069         if (up) {
1070                 set_bit(substream->number, &dev->out_triggered);
1071         } else {
1072                 clear_bit(substream->number, &dev->out_triggered);
1073         }
1074 }
1075
1076 static struct snd_rawmidi_ops gmidi_in_ops = {
1077         .open = gmidi_in_open,
1078         .close = gmidi_in_close,
1079         .trigger = gmidi_in_trigger,
1080 };
1081
1082 static struct snd_rawmidi_ops gmidi_out_ops = {
1083         .open = gmidi_out_open,
1084         .close = gmidi_out_close,
1085         .trigger = gmidi_out_trigger
1086 };
1087
1088 /* register as a sound "card" */
1089 static int gmidi_register_card(struct gmidi_device *dev)
1090 {
1091         struct snd_card *card;
1092         struct snd_rawmidi *rmidi;
1093         int err;
1094         int out_ports = 1;
1095         int in_ports = 1;
1096         static struct snd_device_ops ops = {
1097                 .dev_free = gmidi_snd_free,
1098         };
1099
1100         err = snd_card_create(index, id, THIS_MODULE, 0, &card);
1101         if (err < 0) {
1102                 ERROR(dev, "snd_card_create failed\n");
1103                 goto fail;
1104         }
1105         dev->card = card;
1106
1107         err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, dev, &ops);
1108         if (err < 0) {
1109                 ERROR(dev, "snd_device_new failed: error %d\n", err);
1110                 goto fail;
1111         }
1112
1113         strcpy(card->driver, longname);
1114         strcpy(card->longname, longname);
1115         strcpy(card->shortname, shortname);
1116
1117         /* Set up rawmidi */
1118         dev->in_port.dev = dev;
1119         dev->in_port.active = 0;
1120         snd_component_add(card, "MIDI");
1121         err = snd_rawmidi_new(card, "USB MIDI Gadget", 0,
1122                               out_ports, in_ports, &rmidi);
1123         if (err < 0) {
1124                 ERROR(dev, "snd_rawmidi_new failed: error %d\n", err);
1125                 goto fail;
1126         }
1127         dev->rmidi = rmidi;
1128         strcpy(rmidi->name, card->shortname);
1129         rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
1130                             SNDRV_RAWMIDI_INFO_INPUT |
1131                             SNDRV_RAWMIDI_INFO_DUPLEX;
1132         rmidi->private_data = dev;
1133
1134         /* Yes, rawmidi OUTPUT = USB IN, and rawmidi INPUT = USB OUT.
1135            It's an upside-down world being a gadget. */
1136         snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &gmidi_in_ops);
1137         snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &gmidi_out_ops);
1138
1139         snd_card_set_dev(card, &dev->gadget->dev);
1140
1141         /* register it - we're ready to go */
1142         err = snd_card_register(card);
1143         if (err < 0) {
1144                 ERROR(dev, "snd_card_register failed\n");
1145                 goto fail;
1146         }
1147
1148         VDBG(dev, "gmidi_register_card finished ok\n");
1149         return 0;
1150
1151 fail:
1152         if (dev->card) {
1153                 snd_card_free(dev->card);
1154                 dev->card = NULL;
1155         }
1156         return err;
1157 }
1158
1159 /*
1160  * Creates an output endpoint, and initializes output ports.
1161  */
1162 static int __init gmidi_bind(struct usb_gadget *gadget)
1163 {
1164         struct gmidi_device *dev;
1165         struct usb_ep *in_ep, *out_ep;
1166         int gcnum, err = 0;
1167
1168         /* support optional vendor/distro customization */
1169         if (idVendor) {
1170                 if (!idProduct) {
1171                         pr_err("idVendor needs idProduct!\n");
1172                         return -ENODEV;
1173                 }
1174                 device_desc.idVendor = cpu_to_le16(idVendor);
1175                 device_desc.idProduct = cpu_to_le16(idProduct);
1176                 if (bcdDevice) {
1177                         device_desc.bcdDevice = cpu_to_le16(bcdDevice);
1178                 }
1179         }
1180         if (iManufacturer) {
1181                 strlcpy(manufacturer, iManufacturer, sizeof(manufacturer));
1182         } else {
1183                 snprintf(manufacturer, sizeof(manufacturer), "%s %s with %s",
1184                         init_utsname()->sysname, init_utsname()->release,
1185                         gadget->name);
1186         }
1187         if (iProduct) {
1188                 strlcpy(product_desc, iProduct, sizeof(product_desc));
1189         }
1190         if (iSerialNumber) {
1191                 device_desc.iSerialNumber = STRING_SERIAL,
1192                 strlcpy(serial_number, iSerialNumber, sizeof(serial_number));
1193         }
1194
1195         /* Bulk-only drivers like this one SHOULD be able to
1196          * autoconfigure on any sane usb controller driver,
1197          * but there may also be important quirks to address.
1198          */
1199         usb_ep_autoconfig_reset(gadget);
1200         in_ep = usb_ep_autoconfig(gadget, &bulk_in_desc);
1201         if (!in_ep) {
1202 autoconf_fail:
1203                 pr_err("%s: can't autoconfigure on %s\n",
1204                         shortname, gadget->name);
1205                 return -ENODEV;
1206         }
1207         EP_IN_NAME = in_ep->name;
1208         in_ep->driver_data = in_ep;     /* claim */
1209
1210         out_ep = usb_ep_autoconfig(gadget, &bulk_out_desc);
1211         if (!out_ep) {
1212                 goto autoconf_fail;
1213         }
1214         EP_OUT_NAME = out_ep->name;
1215         out_ep->driver_data = out_ep;   /* claim */
1216
1217         gcnum = usb_gadget_controller_number(gadget);
1218         if (gcnum >= 0) {
1219                 device_desc.bcdDevice = cpu_to_le16(0x0200 + gcnum);
1220         } else {
1221                 /* gmidi is so simple (no altsettings) that
1222                  * it SHOULD NOT have problems with bulk-capable hardware.
1223                  * so warn about unrecognized controllers, don't panic.
1224                  */
1225                 pr_warning("%s: controller '%s' not recognized\n",
1226                         shortname, gadget->name);
1227                 device_desc.bcdDevice = cpu_to_le16(0x9999);
1228         }
1229
1230
1231         /* ok, we made sense of the hardware ... */
1232         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1233         if (!dev) {
1234                 return -ENOMEM;
1235         }
1236         spin_lock_init(&dev->lock);
1237         dev->gadget = gadget;
1238         dev->in_ep = in_ep;
1239         dev->out_ep = out_ep;
1240         set_gadget_data(gadget, dev);
1241         tasklet_init(&dev->tasklet, gmidi_in_tasklet, (unsigned long)dev);
1242
1243         /* preallocate control response and buffer */
1244         dev->req = alloc_ep_req(gadget->ep0, USB_BUFSIZ);
1245         if (!dev->req) {
1246                 err = -ENOMEM;
1247                 goto fail;
1248         }
1249
1250         dev->req->complete = gmidi_setup_complete;
1251
1252         device_desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1253
1254         gadget->ep0->driver_data = dev;
1255
1256         INFO(dev, "%s, version: " DRIVER_VERSION "\n", longname);
1257         INFO(dev, "using %s, OUT %s IN %s\n", gadget->name,
1258                 EP_OUT_NAME, EP_IN_NAME);
1259
1260         /* register as an ALSA sound card */
1261         err = gmidi_register_card(dev);
1262         if (err < 0) {
1263                 goto fail;
1264         }
1265
1266         VDBG(dev, "gmidi_bind finished ok\n");
1267         return 0;
1268
1269 fail:
1270         gmidi_unbind(gadget);
1271         return err;
1272 }
1273
1274
1275 static void gmidi_suspend(struct usb_gadget *gadget)
1276 {
1277         struct gmidi_device *dev = get_gadget_data(gadget);
1278
1279         if (gadget->speed == USB_SPEED_UNKNOWN) {
1280                 return;
1281         }
1282
1283         DBG(dev, "suspend\n");
1284 }
1285
1286 static void gmidi_resume(struct usb_gadget *gadget)
1287 {
1288         struct gmidi_device *dev = get_gadget_data(gadget);
1289
1290         DBG(dev, "resume\n");
1291 }
1292
1293
1294 static struct usb_gadget_driver gmidi_driver = {
1295         .speed          = USB_SPEED_FULL,
1296         .function       = (char *)longname,
1297         .unbind         = gmidi_unbind,
1298
1299         .setup          = gmidi_setup,
1300         .disconnect     = gmidi_disconnect,
1301
1302         .suspend        = gmidi_suspend,
1303         .resume         = gmidi_resume,
1304
1305         .driver         = {
1306                 .name           = (char *)shortname,
1307                 .owner          = THIS_MODULE,
1308         },
1309 };
1310
1311 static int __init gmidi_init(void)
1312 {
1313         return usb_gadget_probe_driver(&gmidi_driver, gmidi_bind);
1314 }
1315 module_init(gmidi_init);
1316
1317 static void __exit gmidi_cleanup(void)
1318 {
1319         usb_gadget_unregister_driver(&gmidi_driver);
1320 }
1321 module_exit(gmidi_cleanup);
1322