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