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