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