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