1/*
2 * f_midi.c -- USB MIDI class function 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 * Rewritten for the composite framework
9 *   Copyright (C) 2011 Daniel Mack <zonque@gmail.com>
10 *
11 * Based on drivers/usb/gadget/f_audio.c,
12 *   Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
13 *   Copyright (C) 2008 Analog Devices, Inc
14 *
15 * and drivers/usb/gadget/midi.c,
16 *   Copyright (C) 2006 Thumtronics Pty Ltd.
17 *   Ben Williamson <ben.williamson@greyinnovation.com>
18 *
19 * Licensed under the GPL-2 or later.
20 */
21
22#include <linux/kernel.h>
23#include <linux/module.h>
24#include <linux/slab.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 "u_f.h"
37#include "u_midi.h"
38
39MODULE_AUTHOR("Ben Williamson");
40MODULE_LICENSE("GPL v2");
41
42static const char f_midi_shortname[] = "f_midi";
43static const char f_midi_longname[] = "MIDI Gadget";
44
45/*
46 * We can only handle 16 cables on one single endpoint, as cable numbers are
47 * stored in 4-bit fields. And as the interface currently only holds one
48 * single endpoint, this is the maximum number of ports we can allow.
49 */
50#define MAX_PORTS 16
51
52/*
53 * This is a gadget, and the IN/OUT naming is from the host's perspective.
54 * USB -> OUT endpoint -> rawmidi
55 * USB <- IN endpoint  <- rawmidi
56 */
57struct gmidi_in_port {
58	struct f_midi *midi;
59	int active;
60	uint8_t cable;
61	uint8_t state;
62#define STATE_UNKNOWN	0
63#define STATE_1PARAM	1
64#define STATE_2PARAM_1	2
65#define STATE_2PARAM_2	3
66#define STATE_SYSEX_0	4
67#define STATE_SYSEX_1	5
68#define STATE_SYSEX_2	6
69	uint8_t data[2];
70};
71
72struct f_midi {
73	struct usb_function	func;
74	struct usb_gadget	*gadget;
75	struct usb_ep		*in_ep, *out_ep;
76	struct snd_card		*card;
77	struct snd_rawmidi	*rmidi;
78
79	struct snd_rawmidi_substream *in_substream[MAX_PORTS];
80	struct snd_rawmidi_substream *out_substream[MAX_PORTS];
81	struct gmidi_in_port	*in_port[MAX_PORTS];
82
83	unsigned long		out_triggered;
84	struct tasklet_struct	tasklet;
85	unsigned int in_ports;
86	unsigned int out_ports;
87	int index;
88	char *id;
89	unsigned int buflen, qlen;
90};
91
92static inline struct f_midi *func_to_midi(struct usb_function *f)
93{
94	return container_of(f, struct f_midi, func);
95}
96
97static void f_midi_transmit(struct f_midi *midi, struct usb_request *req);
98
99DECLARE_UAC_AC_HEADER_DESCRIPTOR(1);
100DECLARE_USB_MIDI_OUT_JACK_DESCRIPTOR(1);
101DECLARE_USB_MS_ENDPOINT_DESCRIPTOR(16);
102
103/* B.3.1  Standard AC Interface Descriptor */
104static struct usb_interface_descriptor ac_interface_desc = {
105	.bLength =		USB_DT_INTERFACE_SIZE,
106	.bDescriptorType =	USB_DT_INTERFACE,
107	/* .bInterfaceNumber =	DYNAMIC */
108	/* .bNumEndpoints =	DYNAMIC */
109	.bInterfaceClass =	USB_CLASS_AUDIO,
110	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOCONTROL,
111	/* .iInterface =	DYNAMIC */
112};
113
114/* B.3.2  Class-Specific AC Interface Descriptor */
115static struct uac1_ac_header_descriptor_1 ac_header_desc = {
116	.bLength =		UAC_DT_AC_HEADER_SIZE(1),
117	.bDescriptorType =	USB_DT_CS_INTERFACE,
118	.bDescriptorSubtype =	USB_MS_HEADER,
119	.bcdADC =		cpu_to_le16(0x0100),
120	.wTotalLength =		cpu_to_le16(UAC_DT_AC_HEADER_SIZE(1)),
121	.bInCollection =	1,
122	/* .baInterfaceNr =	DYNAMIC */
123};
124
125/* B.4.1  Standard MS Interface Descriptor */
126static struct usb_interface_descriptor ms_interface_desc = {
127	.bLength =		USB_DT_INTERFACE_SIZE,
128	.bDescriptorType =	USB_DT_INTERFACE,
129	/* .bInterfaceNumber =	DYNAMIC */
130	.bNumEndpoints =	2,
131	.bInterfaceClass =	USB_CLASS_AUDIO,
132	.bInterfaceSubClass =	USB_SUBCLASS_MIDISTREAMING,
133	/* .iInterface =	DYNAMIC */
134};
135
136/* B.4.2  Class-Specific MS Interface Descriptor */
137static struct usb_ms_header_descriptor ms_header_desc = {
138	.bLength =		USB_DT_MS_HEADER_SIZE,
139	.bDescriptorType =	USB_DT_CS_INTERFACE,
140	.bDescriptorSubtype =	USB_MS_HEADER,
141	.bcdMSC =		cpu_to_le16(0x0100),
142	/* .wTotalLength =	DYNAMIC */
143};
144
145/* B.5.1  Standard Bulk OUT Endpoint Descriptor */
146static struct usb_endpoint_descriptor bulk_out_desc = {
147	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
148	.bDescriptorType =	USB_DT_ENDPOINT,
149	.bEndpointAddress =	USB_DIR_OUT,
150	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
151};
152
153/* B.5.2  Class-specific MS Bulk OUT Endpoint Descriptor */
154static struct usb_ms_endpoint_descriptor_16 ms_out_desc = {
155	/* .bLength =		DYNAMIC */
156	.bDescriptorType =	USB_DT_CS_ENDPOINT,
157	.bDescriptorSubtype =	USB_MS_GENERAL,
158	/* .bNumEmbMIDIJack =	DYNAMIC */
159	/* .baAssocJackID =	DYNAMIC */
160};
161
162/* B.6.1  Standard Bulk IN Endpoint Descriptor */
163static struct usb_endpoint_descriptor bulk_in_desc = {
164	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
165	.bDescriptorType =	USB_DT_ENDPOINT,
166	.bEndpointAddress =	USB_DIR_IN,
167	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
168};
169
170/* B.6.2  Class-specific MS Bulk IN Endpoint Descriptor */
171static struct usb_ms_endpoint_descriptor_16 ms_in_desc = {
172	/* .bLength =		DYNAMIC */
173	.bDescriptorType =	USB_DT_CS_ENDPOINT,
174	.bDescriptorSubtype =	USB_MS_GENERAL,
175	/* .bNumEmbMIDIJack =	DYNAMIC */
176	/* .baAssocJackID =	DYNAMIC */
177};
178
179/* string IDs are assigned dynamically */
180
181#define STRING_FUNC_IDX			0
182
183static struct usb_string midi_string_defs[] = {
184	[STRING_FUNC_IDX].s = "MIDI function",
185	{  } /* end of list */
186};
187
188static struct usb_gadget_strings midi_stringtab = {
189	.language	= 0x0409,	/* en-us */
190	.strings	= midi_string_defs,
191};
192
193static struct usb_gadget_strings *midi_strings[] = {
194	&midi_stringtab,
195	NULL,
196};
197
198static inline struct usb_request *midi_alloc_ep_req(struct usb_ep *ep,
199						    unsigned length)
200{
201	return alloc_ep_req(ep, length, length);
202}
203
204static void free_ep_req(struct usb_ep *ep, struct usb_request *req)
205{
206	kfree(req->buf);
207	usb_ep_free_request(ep, req);
208}
209
210static const uint8_t f_midi_cin_length[] = {
211	0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
212};
213
214/*
215 * Receives a chunk of MIDI data.
216 */
217static void f_midi_read_data(struct usb_ep *ep, int cable,
218			     uint8_t *data, int length)
219{
220	struct f_midi *midi = ep->driver_data;
221	struct snd_rawmidi_substream *substream = midi->out_substream[cable];
222
223	if (!substream)
224		/* Nobody is listening - throw it on the floor. */
225		return;
226
227	if (!test_bit(cable, &midi->out_triggered))
228		return;
229
230	snd_rawmidi_receive(substream, data, length);
231}
232
233static void f_midi_handle_out_data(struct usb_ep *ep, struct usb_request *req)
234{
235	unsigned int i;
236	u8 *buf = req->buf;
237
238	for (i = 0; i + 3 < req->actual; i += 4)
239		if (buf[i] != 0) {
240			int cable = buf[i] >> 4;
241			int length = f_midi_cin_length[buf[i] & 0x0f];
242			f_midi_read_data(ep, cable, &buf[i + 1], length);
243		}
244}
245
246static void
247f_midi_complete(struct usb_ep *ep, struct usb_request *req)
248{
249	struct f_midi *midi = ep->driver_data;
250	struct usb_composite_dev *cdev = midi->func.config->cdev;
251	int status = req->status;
252
253	switch (status) {
254	case 0:			 /* normal completion */
255		if (ep == midi->out_ep) {
256			/* We received stuff. req is queued again, below */
257			f_midi_handle_out_data(ep, req);
258		} else if (ep == midi->in_ep) {
259			/* Our transmit completed. See if there's more to go.
260			 * f_midi_transmit eats req, don't queue it again. */
261			f_midi_transmit(midi, req);
262			return;
263		}
264		break;
265
266	/* this endpoint is normally active while we're configured */
267	case -ECONNABORTED:	/* hardware forced ep reset */
268	case -ECONNRESET:	/* request dequeued */
269	case -ESHUTDOWN:	/* disconnect from host */
270		VDBG(cdev, "%s gone (%d), %d/%d\n", ep->name, status,
271				req->actual, req->length);
272		if (ep == midi->out_ep)
273			f_midi_handle_out_data(ep, req);
274
275		free_ep_req(ep, req);
276		return;
277
278	case -EOVERFLOW:	/* buffer overrun on read means that
279				 * we didn't provide a big enough buffer.
280				 */
281	default:
282		DBG(cdev, "%s complete --> %d, %d/%d\n", ep->name,
283				status, req->actual, req->length);
284		break;
285	case -EREMOTEIO:	/* short read */
286		break;
287	}
288
289	status = usb_ep_queue(ep, req, GFP_ATOMIC);
290	if (status) {
291		ERROR(cdev, "kill %s:  resubmit %d bytes --> %d\n",
292				ep->name, req->length, status);
293		usb_ep_set_halt(ep);
294		/* FIXME recover later ... somehow */
295	}
296}
297
298static int f_midi_start_ep(struct f_midi *midi,
299			   struct usb_function *f,
300			   struct usb_ep *ep)
301{
302	int err;
303	struct usb_composite_dev *cdev = f->config->cdev;
304
305	if (ep->driver_data)
306		usb_ep_disable(ep);
307
308	err = config_ep_by_speed(midi->gadget, f, ep);
309	if (err) {
310		ERROR(cdev, "can't configure %s: %d\n", ep->name, err);
311		return err;
312	}
313
314	err = usb_ep_enable(ep);
315	if (err) {
316		ERROR(cdev, "can't start %s: %d\n", ep->name, err);
317		return err;
318	}
319
320	ep->driver_data = midi;
321
322	return 0;
323}
324
325static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
326{
327	struct f_midi *midi = func_to_midi(f);
328	struct usb_composite_dev *cdev = f->config->cdev;
329	unsigned i;
330	int err;
331
332	/* For Control Device interface we do nothing */
333	if (intf == 0)
334		return 0;
335
336	err = f_midi_start_ep(midi, f, midi->in_ep);
337	if (err)
338		return err;
339
340	err = f_midi_start_ep(midi, f, midi->out_ep);
341	if (err)
342		return err;
343
344	if (midi->out_ep->driver_data)
345		usb_ep_disable(midi->out_ep);
346
347	err = config_ep_by_speed(midi->gadget, f, midi->out_ep);
348	if (err) {
349		ERROR(cdev, "can't configure %s: %d\n",
350		      midi->out_ep->name, err);
351		return err;
352	}
353
354	err = usb_ep_enable(midi->out_ep);
355	if (err) {
356		ERROR(cdev, "can't start %s: %d\n",
357		      midi->out_ep->name, err);
358		return err;
359	}
360
361	midi->out_ep->driver_data = midi;
362
363	/* allocate a bunch of read buffers and queue them all at once. */
364	for (i = 0; i < midi->qlen && err == 0; i++) {
365		struct usb_request *req =
366			midi_alloc_ep_req(midi->out_ep, midi->buflen);
367		if (req == NULL)
368			return -ENOMEM;
369
370		req->complete = f_midi_complete;
371		err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);
372		if (err) {
373			ERROR(midi, "%s queue req: %d\n",
374				    midi->out_ep->name, err);
375		}
376	}
377
378	return 0;
379}
380
381static void f_midi_disable(struct usb_function *f)
382{
383	struct f_midi *midi = func_to_midi(f);
384	struct usb_composite_dev *cdev = f->config->cdev;
385
386	DBG(cdev, "disable\n");
387
388	/*
389	 * just disable endpoints, forcing completion of pending i/o.
390	 * all our completion handlers free their requests in this case.
391	 */
392	usb_ep_disable(midi->in_ep);
393	usb_ep_disable(midi->out_ep);
394}
395
396static int f_midi_snd_free(struct snd_device *device)
397{
398	return 0;
399}
400
401static void f_midi_transmit_packet(struct usb_request *req, uint8_t p0,
402					uint8_t p1, uint8_t p2, uint8_t p3)
403{
404	unsigned length = req->length;
405	u8 *buf = (u8 *)req->buf + length;
406
407	buf[0] = p0;
408	buf[1] = p1;
409	buf[2] = p2;
410	buf[3] = p3;
411	req->length = length + 4;
412}
413
414/*
415 * Converts MIDI commands to USB MIDI packets.
416 */
417static void f_midi_transmit_byte(struct usb_request *req,
418				 struct gmidi_in_port *port, uint8_t b)
419{
420	uint8_t p0 = port->cable << 4;
421
422	if (b >= 0xf8) {
423		f_midi_transmit_packet(req, p0 | 0x0f, b, 0, 0);
424	} else if (b >= 0xf0) {
425		switch (b) {
426		case 0xf0:
427			port->data[0] = b;
428			port->state = STATE_SYSEX_1;
429			break;
430		case 0xf1:
431		case 0xf3:
432			port->data[0] = b;
433			port->state = STATE_1PARAM;
434			break;
435		case 0xf2:
436			port->data[0] = b;
437			port->state = STATE_2PARAM_1;
438			break;
439		case 0xf4:
440		case 0xf5:
441			port->state = STATE_UNKNOWN;
442			break;
443		case 0xf6:
444			f_midi_transmit_packet(req, p0 | 0x05, 0xf6, 0, 0);
445			port->state = STATE_UNKNOWN;
446			break;
447		case 0xf7:
448			switch (port->state) {
449			case STATE_SYSEX_0:
450				f_midi_transmit_packet(req,
451					p0 | 0x05, 0xf7, 0, 0);
452				break;
453			case STATE_SYSEX_1:
454				f_midi_transmit_packet(req,
455					p0 | 0x06, port->data[0], 0xf7, 0);
456				break;
457			case STATE_SYSEX_2:
458				f_midi_transmit_packet(req,
459					p0 | 0x07, port->data[0],
460					port->data[1], 0xf7);
461				break;
462			}
463			port->state = STATE_UNKNOWN;
464			break;
465		}
466	} else if (b >= 0x80) {
467		port->data[0] = b;
468		if (b >= 0xc0 && b <= 0xdf)
469			port->state = STATE_1PARAM;
470		else
471			port->state = STATE_2PARAM_1;
472	} else { /* b < 0x80 */
473		switch (port->state) {
474		case STATE_1PARAM:
475			if (port->data[0] < 0xf0) {
476				p0 |= port->data[0] >> 4;
477			} else {
478				p0 |= 0x02;
479				port->state = STATE_UNKNOWN;
480			}
481			f_midi_transmit_packet(req, p0, port->data[0], b, 0);
482			break;
483		case STATE_2PARAM_1:
484			port->data[1] = b;
485			port->state = STATE_2PARAM_2;
486			break;
487		case STATE_2PARAM_2:
488			if (port->data[0] < 0xf0) {
489				p0 |= port->data[0] >> 4;
490				port->state = STATE_2PARAM_1;
491			} else {
492				p0 |= 0x03;
493				port->state = STATE_UNKNOWN;
494			}
495			f_midi_transmit_packet(req,
496				p0, port->data[0], port->data[1], b);
497			break;
498		case STATE_SYSEX_0:
499			port->data[0] = b;
500			port->state = STATE_SYSEX_1;
501			break;
502		case STATE_SYSEX_1:
503			port->data[1] = b;
504			port->state = STATE_SYSEX_2;
505			break;
506		case STATE_SYSEX_2:
507			f_midi_transmit_packet(req,
508				p0 | 0x04, port->data[0], port->data[1], b);
509			port->state = STATE_SYSEX_0;
510			break;
511		}
512	}
513}
514
515static void f_midi_transmit(struct f_midi *midi, struct usb_request *req)
516{
517	struct usb_ep *ep = midi->in_ep;
518	int i;
519
520	if (!ep)
521		return;
522
523	if (!req)
524		req = midi_alloc_ep_req(ep, midi->buflen);
525
526	if (!req) {
527		ERROR(midi, "%s: alloc_ep_request failed\n", __func__);
528		return;
529	}
530	req->length = 0;
531	req->complete = f_midi_complete;
532
533	for (i = 0; i < MAX_PORTS; i++) {
534		struct gmidi_in_port *port = midi->in_port[i];
535		struct snd_rawmidi_substream *substream = midi->in_substream[i];
536
537		if (!port || !port->active || !substream)
538			continue;
539
540		while (req->length + 3 < midi->buflen) {
541			uint8_t b;
542			if (snd_rawmidi_transmit(substream, &b, 1) != 1) {
543				port->active = 0;
544				break;
545			}
546			f_midi_transmit_byte(req, port, b);
547		}
548	}
549
550	if (req->length > 0)
551		usb_ep_queue(ep, req, GFP_ATOMIC);
552	else
553		free_ep_req(ep, req);
554}
555
556static void f_midi_in_tasklet(unsigned long data)
557{
558	struct f_midi *midi = (struct f_midi *) data;
559	f_midi_transmit(midi, NULL);
560}
561
562static int f_midi_in_open(struct snd_rawmidi_substream *substream)
563{
564	struct f_midi *midi = substream->rmidi->private_data;
565
566	if (!midi->in_port[substream->number])
567		return -EINVAL;
568
569	VDBG(midi, "%s()\n", __func__);
570	midi->in_substream[substream->number] = substream;
571	midi->in_port[substream->number]->state = STATE_UNKNOWN;
572	return 0;
573}
574
575static int f_midi_in_close(struct snd_rawmidi_substream *substream)
576{
577	struct f_midi *midi = substream->rmidi->private_data;
578
579	VDBG(midi, "%s()\n", __func__);
580	return 0;
581}
582
583static void f_midi_in_trigger(struct snd_rawmidi_substream *substream, int up)
584{
585	struct f_midi *midi = substream->rmidi->private_data;
586
587	if (!midi->in_port[substream->number])
588		return;
589
590	VDBG(midi, "%s() %d\n", __func__, up);
591	midi->in_port[substream->number]->active = up;
592	if (up)
593		tasklet_hi_schedule(&midi->tasklet);
594}
595
596static int f_midi_out_open(struct snd_rawmidi_substream *substream)
597{
598	struct f_midi *midi = substream->rmidi->private_data;
599
600	if (substream->number >= MAX_PORTS)
601		return -EINVAL;
602
603	VDBG(midi, "%s()\n", __func__);
604	midi->out_substream[substream->number] = substream;
605	return 0;
606}
607
608static int f_midi_out_close(struct snd_rawmidi_substream *substream)
609{
610	struct f_midi *midi = substream->rmidi->private_data;
611
612	VDBG(midi, "%s()\n", __func__);
613	return 0;
614}
615
616static void f_midi_out_trigger(struct snd_rawmidi_substream *substream, int up)
617{
618	struct f_midi *midi = substream->rmidi->private_data;
619
620	VDBG(midi, "%s()\n", __func__);
621
622	if (up)
623		set_bit(substream->number, &midi->out_triggered);
624	else
625		clear_bit(substream->number, &midi->out_triggered);
626}
627
628static struct snd_rawmidi_ops gmidi_in_ops = {
629	.open = f_midi_in_open,
630	.close = f_midi_in_close,
631	.trigger = f_midi_in_trigger,
632};
633
634static struct snd_rawmidi_ops gmidi_out_ops = {
635	.open = f_midi_out_open,
636	.close = f_midi_out_close,
637	.trigger = f_midi_out_trigger
638};
639
640static inline void f_midi_unregister_card(struct f_midi *midi)
641{
642	if (midi->card) {
643		snd_card_free(midi->card);
644		midi->card = NULL;
645	}
646}
647
648/* register as a sound "card" */
649static int f_midi_register_card(struct f_midi *midi)
650{
651	struct snd_card *card;
652	struct snd_rawmidi *rmidi;
653	int err;
654	static struct snd_device_ops ops = {
655		.dev_free = f_midi_snd_free,
656	};
657
658	err = snd_card_new(&midi->gadget->dev, midi->index, midi->id,
659			   THIS_MODULE, 0, &card);
660	if (err < 0) {
661		ERROR(midi, "snd_card_new() failed\n");
662		goto fail;
663	}
664	midi->card = card;
665
666	err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, midi, &ops);
667	if (err < 0) {
668		ERROR(midi, "snd_device_new() failed: error %d\n", err);
669		goto fail;
670	}
671
672	strcpy(card->driver, f_midi_longname);
673	strcpy(card->longname, f_midi_longname);
674	strcpy(card->shortname, f_midi_shortname);
675
676	/* Set up rawmidi */
677	snd_component_add(card, "MIDI");
678	err = snd_rawmidi_new(card, card->longname, 0,
679			      midi->out_ports, midi->in_ports, &rmidi);
680	if (err < 0) {
681		ERROR(midi, "snd_rawmidi_new() failed: error %d\n", err);
682		goto fail;
683	}
684	midi->rmidi = rmidi;
685	strcpy(rmidi->name, card->shortname);
686	rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
687			    SNDRV_RAWMIDI_INFO_INPUT |
688			    SNDRV_RAWMIDI_INFO_DUPLEX;
689	rmidi->private_data = midi;
690
691	/*
692	 * Yes, rawmidi OUTPUT = USB IN, and rawmidi INPUT = USB OUT.
693	 * It's an upside-down world being a gadget.
694	 */
695	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &gmidi_in_ops);
696	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &gmidi_out_ops);
697
698	/* register it - we're ready to go */
699	err = snd_card_register(card);
700	if (err < 0) {
701		ERROR(midi, "snd_card_register() failed\n");
702		goto fail;
703	}
704
705	VDBG(midi, "%s() finished ok\n", __func__);
706	return 0;
707
708fail:
709	f_midi_unregister_card(midi);
710	return err;
711}
712
713/* MIDI function driver setup/binding */
714
715static int f_midi_bind(struct usb_configuration *c, struct usb_function *f)
716{
717	struct usb_descriptor_header **midi_function;
718	struct usb_midi_in_jack_descriptor jack_in_ext_desc[MAX_PORTS];
719	struct usb_midi_in_jack_descriptor jack_in_emb_desc[MAX_PORTS];
720	struct usb_midi_out_jack_descriptor_1 jack_out_ext_desc[MAX_PORTS];
721	struct usb_midi_out_jack_descriptor_1 jack_out_emb_desc[MAX_PORTS];
722	struct usb_composite_dev *cdev = c->cdev;
723	struct f_midi *midi = func_to_midi(f);
724	struct usb_string *us;
725	int status, n, jack = 1, i = 0;
726
727	midi->gadget = cdev->gadget;
728	tasklet_init(&midi->tasklet, f_midi_in_tasklet, (unsigned long) midi);
729	status = f_midi_register_card(midi);
730	if (status < 0)
731		goto fail_register;
732
733	/* maybe allocate device-global string ID */
734	us = usb_gstrings_attach(c->cdev, midi_strings,
735				 ARRAY_SIZE(midi_string_defs));
736	if (IS_ERR(us)) {
737		status = PTR_ERR(us);
738		goto fail;
739	}
740	ac_interface_desc.iInterface = us[STRING_FUNC_IDX].id;
741
742	/* We have two interfaces, AudioControl and MIDIStreaming */
743	status = usb_interface_id(c, f);
744	if (status < 0)
745		goto fail;
746	ac_interface_desc.bInterfaceNumber = status;
747
748	status = usb_interface_id(c, f);
749	if (status < 0)
750		goto fail;
751	ms_interface_desc.bInterfaceNumber = status;
752	ac_header_desc.baInterfaceNr[0] = status;
753
754	status = -ENODEV;
755
756	/* allocate instance-specific endpoints */
757	midi->in_ep = usb_ep_autoconfig(cdev->gadget, &bulk_in_desc);
758	if (!midi->in_ep)
759		goto fail;
760	midi->in_ep->driver_data = cdev;	/* claim */
761
762	midi->out_ep = usb_ep_autoconfig(cdev->gadget, &bulk_out_desc);
763	if (!midi->out_ep)
764		goto fail;
765	midi->out_ep->driver_data = cdev;	/* claim */
766
767	/* allocate temporary function list */
768	midi_function = kcalloc((MAX_PORTS * 4) + 9, sizeof(*midi_function),
769				GFP_KERNEL);
770	if (!midi_function) {
771		status = -ENOMEM;
772		goto fail;
773	}
774
775	/*
776	 * construct the function's descriptor set. As the number of
777	 * input and output MIDI ports is configurable, we have to do
778	 * it that way.
779	 */
780
781	/* add the headers - these are always the same */
782	midi_function[i++] = (struct usb_descriptor_header *) &ac_interface_desc;
783	midi_function[i++] = (struct usb_descriptor_header *) &ac_header_desc;
784	midi_function[i++] = (struct usb_descriptor_header *) &ms_interface_desc;
785
786	/* calculate the header's wTotalLength */
787	n = USB_DT_MS_HEADER_SIZE
788		+ (midi->in_ports + midi->out_ports) *
789			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
790	ms_header_desc.wTotalLength = cpu_to_le16(n);
791
792	midi_function[i++] = (struct usb_descriptor_header *) &ms_header_desc;
793
794	/* configure the external IN jacks, each linked to an embedded OUT jack */
795	for (n = 0; n < midi->in_ports; n++) {
796		struct usb_midi_in_jack_descriptor *in_ext = &jack_in_ext_desc[n];
797		struct usb_midi_out_jack_descriptor_1 *out_emb = &jack_out_emb_desc[n];
798
799		in_ext->bLength			= USB_DT_MIDI_IN_SIZE;
800		in_ext->bDescriptorType		= USB_DT_CS_INTERFACE;
801		in_ext->bDescriptorSubtype	= USB_MS_MIDI_IN_JACK;
802		in_ext->bJackType		= USB_MS_EXTERNAL;
803		in_ext->bJackID			= jack++;
804		in_ext->iJack			= 0;
805		midi_function[i++] = (struct usb_descriptor_header *) in_ext;
806
807		out_emb->bLength		= USB_DT_MIDI_OUT_SIZE(1);
808		out_emb->bDescriptorType	= USB_DT_CS_INTERFACE;
809		out_emb->bDescriptorSubtype	= USB_MS_MIDI_OUT_JACK;
810		out_emb->bJackType		= USB_MS_EMBEDDED;
811		out_emb->bJackID		= jack++;
812		out_emb->bNrInputPins		= 1;
813		out_emb->pins[0].baSourcePin	= 1;
814		out_emb->pins[0].baSourceID	= in_ext->bJackID;
815		out_emb->iJack			= 0;
816		midi_function[i++] = (struct usb_descriptor_header *) out_emb;
817
818		/* link it to the endpoint */
819		ms_in_desc.baAssocJackID[n] = out_emb->bJackID;
820	}
821
822	/* configure the external OUT jacks, each linked to an embedded IN jack */
823	for (n = 0; n < midi->out_ports; n++) {
824		struct usb_midi_in_jack_descriptor *in_emb = &jack_in_emb_desc[n];
825		struct usb_midi_out_jack_descriptor_1 *out_ext = &jack_out_ext_desc[n];
826
827		in_emb->bLength			= USB_DT_MIDI_IN_SIZE;
828		in_emb->bDescriptorType		= USB_DT_CS_INTERFACE;
829		in_emb->bDescriptorSubtype	= USB_MS_MIDI_IN_JACK;
830		in_emb->bJackType		= USB_MS_EMBEDDED;
831		in_emb->bJackID			= jack++;
832		in_emb->iJack			= 0;
833		midi_function[i++] = (struct usb_descriptor_header *) in_emb;
834
835		out_ext->bLength =		USB_DT_MIDI_OUT_SIZE(1);
836		out_ext->bDescriptorType =	USB_DT_CS_INTERFACE;
837		out_ext->bDescriptorSubtype =	USB_MS_MIDI_OUT_JACK;
838		out_ext->bJackType =		USB_MS_EXTERNAL;
839		out_ext->bJackID =		jack++;
840		out_ext->bNrInputPins =		1;
841		out_ext->iJack =		0;
842		out_ext->pins[0].baSourceID =	in_emb->bJackID;
843		out_ext->pins[0].baSourcePin =	1;
844		midi_function[i++] = (struct usb_descriptor_header *) out_ext;
845
846		/* link it to the endpoint */
847		ms_out_desc.baAssocJackID[n] = in_emb->bJackID;
848	}
849
850	/* configure the endpoint descriptors ... */
851	ms_out_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->in_ports);
852	ms_out_desc.bNumEmbMIDIJack = midi->in_ports;
853
854	ms_in_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->out_ports);
855	ms_in_desc.bNumEmbMIDIJack = midi->out_ports;
856
857	/* ... and add them to the list */
858	midi_function[i++] = (struct usb_descriptor_header *) &bulk_out_desc;
859	midi_function[i++] = (struct usb_descriptor_header *) &ms_out_desc;
860	midi_function[i++] = (struct usb_descriptor_header *) &bulk_in_desc;
861	midi_function[i++] = (struct usb_descriptor_header *) &ms_in_desc;
862	midi_function[i++] = NULL;
863
864	/*
865	 * support all relevant hardware speeds... we expect that when
866	 * hardware is dual speed, all bulk-capable endpoints work at
867	 * both speeds
868	 */
869	/* copy descriptors, and track endpoint copies */
870	f->fs_descriptors = usb_copy_descriptors(midi_function);
871	if (!f->fs_descriptors)
872		goto fail_f_midi;
873
874	if (gadget_is_dualspeed(c->cdev->gadget)) {
875		bulk_in_desc.wMaxPacketSize = cpu_to_le16(512);
876		bulk_out_desc.wMaxPacketSize = cpu_to_le16(512);
877		f->hs_descriptors = usb_copy_descriptors(midi_function);
878		if (!f->hs_descriptors)
879			goto fail_f_midi;
880	}
881
882	kfree(midi_function);
883
884	return 0;
885
886fail_f_midi:
887	kfree(midi_function);
888	usb_free_descriptors(f->hs_descriptors);
889fail:
890	f_midi_unregister_card(midi);
891fail_register:
892	/* we might as well release our claims on endpoints */
893	if (midi->out_ep)
894		midi->out_ep->driver_data = NULL;
895	if (midi->in_ep)
896		midi->in_ep->driver_data = NULL;
897
898	ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
899
900	return status;
901}
902
903static inline struct f_midi_opts *to_f_midi_opts(struct config_item *item)
904{
905	return container_of(to_config_group(item), struct f_midi_opts,
906			    func_inst.group);
907}
908
909CONFIGFS_ATTR_STRUCT(f_midi_opts);
910CONFIGFS_ATTR_OPS(f_midi_opts);
911
912static void midi_attr_release(struct config_item *item)
913{
914	struct f_midi_opts *opts = to_f_midi_opts(item);
915
916	usb_put_function_instance(&opts->func_inst);
917}
918
919static struct configfs_item_operations midi_item_ops = {
920	.release	= midi_attr_release,
921	.show_attribute	= f_midi_opts_attr_show,
922	.store_attribute = f_midi_opts_attr_store,
923};
924
925#define F_MIDI_OPT(name, test_limit, limit)				\
926static ssize_t f_midi_opts_##name##_show(struct f_midi_opts *opts, char *page) \
927{									\
928	int result;							\
929									\
930	mutex_lock(&opts->lock);					\
931	result = sprintf(page, "%d\n", opts->name);			\
932	mutex_unlock(&opts->lock);					\
933									\
934	return result;							\
935}									\
936									\
937static ssize_t f_midi_opts_##name##_store(struct f_midi_opts *opts,	\
938					 const char *page, size_t len)	\
939{									\
940	int ret;							\
941	u32 num;							\
942									\
943	mutex_lock(&opts->lock);					\
944	if (opts->refcnt) {						\
945		ret = -EBUSY;						\
946		goto end;						\
947	}								\
948									\
949	ret = kstrtou32(page, 0, &num);					\
950	if (ret)							\
951		goto end;						\
952									\
953	if (test_limit && num > limit) {				\
954		ret = -EINVAL;						\
955		goto end;						\
956	}								\
957	opts->name = num;						\
958	ret = len;							\
959									\
960end:									\
961	mutex_unlock(&opts->lock);					\
962	return ret;							\
963}									\
964									\
965static struct f_midi_opts_attribute f_midi_opts_##name =		\
966	__CONFIGFS_ATTR(name, S_IRUGO | S_IWUSR, f_midi_opts_##name##_show, \
967			f_midi_opts_##name##_store)
968
969F_MIDI_OPT(index, true, SNDRV_CARDS);
970F_MIDI_OPT(buflen, false, 0);
971F_MIDI_OPT(qlen, false, 0);
972F_MIDI_OPT(in_ports, true, MAX_PORTS);
973F_MIDI_OPT(out_ports, true, MAX_PORTS);
974
975static ssize_t f_midi_opts_id_show(struct f_midi_opts *opts, char *page)
976{
977	int result;
978
979	mutex_lock(&opts->lock);
980	if (opts->id) {
981		result = strlcpy(page, opts->id, PAGE_SIZE);
982	} else {
983		page[0] = 0;
984		result = 0;
985	}
986
987	mutex_unlock(&opts->lock);
988
989	return result;
990}
991
992static ssize_t f_midi_opts_id_store(struct f_midi_opts *opts,
993				    const char *page, size_t len)
994{
995	int ret;
996	char *c;
997
998	mutex_lock(&opts->lock);
999	if (opts->refcnt) {
1000		ret = -EBUSY;
1001		goto end;
1002	}
1003
1004	c = kstrndup(page, len, GFP_KERNEL);
1005	if (!c) {
1006		ret = -ENOMEM;
1007		goto end;
1008	}
1009	if (opts->id_allocated)
1010		kfree(opts->id);
1011	opts->id = c;
1012	opts->id_allocated = true;
1013	ret = len;
1014end:
1015	mutex_unlock(&opts->lock);
1016	return ret;
1017}
1018
1019static struct f_midi_opts_attribute f_midi_opts_id =
1020	__CONFIGFS_ATTR(id, S_IRUGO | S_IWUSR, f_midi_opts_id_show,
1021			f_midi_opts_id_store);
1022
1023static struct configfs_attribute *midi_attrs[] = {
1024	&f_midi_opts_index.attr,
1025	&f_midi_opts_buflen.attr,
1026	&f_midi_opts_qlen.attr,
1027	&f_midi_opts_in_ports.attr,
1028	&f_midi_opts_out_ports.attr,
1029	&f_midi_opts_id.attr,
1030	NULL,
1031};
1032
1033static struct config_item_type midi_func_type = {
1034	.ct_item_ops	= &midi_item_ops,
1035	.ct_attrs	= midi_attrs,
1036	.ct_owner	= THIS_MODULE,
1037};
1038
1039static void f_midi_free_inst(struct usb_function_instance *f)
1040{
1041	struct f_midi_opts *opts;
1042
1043	opts = container_of(f, struct f_midi_opts, func_inst);
1044
1045	if (opts->id_allocated)
1046		kfree(opts->id);
1047
1048	kfree(opts);
1049}
1050
1051#ifdef CONFIG_USB_CONFIGFS_UEVENT
1052extern struct device *create_function_device(char *name);
1053static ssize_t alsa_show(struct device *dev,
1054		struct device_attribute *attr, char *buf)
1055{
1056	struct usb_function_instance *fi_midi = dev_get_drvdata(dev);
1057	struct f_midi *midi;
1058
1059	if (!fi_midi->f)
1060		dev_warn(dev, "f_midi: function not set\n");
1061
1062	if (fi_midi && fi_midi->f) {
1063		midi = func_to_midi(fi_midi->f);
1064		if (midi->rmidi && midi->rmidi->card)
1065			return sprintf(buf, "%d %d\n",
1066			midi->rmidi->card->number, midi->rmidi->device);
1067	}
1068
1069	/* print PCM card and device numbers */
1070	return sprintf(buf, "%d %d\n", -1, -1);
1071}
1072
1073static DEVICE_ATTR(alsa, S_IRUGO, alsa_show, NULL);
1074
1075static struct device_attribute *alsa_function_attributes[] = {
1076	&dev_attr_alsa,
1077	NULL
1078};
1079
1080static int create_alsa_device(struct usb_function_instance *fi)
1081{
1082	struct device *dev;
1083	struct device_attribute **attrs;
1084	struct device_attribute *attr;
1085	int err = 0;
1086
1087	dev = create_function_device("f_midi");
1088	if (IS_ERR(dev))
1089		return PTR_ERR(dev);
1090
1091	attrs = alsa_function_attributes;
1092	if (attrs) {
1093		while ((attr = *attrs++) && !err)
1094			err = device_create_file(dev, attr);
1095		if (err) {
1096			device_destroy(dev->class, dev->devt);
1097			return -EINVAL;
1098		}
1099	}
1100	dev_set_drvdata(dev, fi);
1101	return 0;
1102}
1103#else
1104static int create_alsa_device(struct usb_function_instance *fi)
1105{
1106	return 0;
1107}
1108#endif
1109
1110static struct usb_function_instance *f_midi_alloc_inst(void)
1111{
1112	struct f_midi_opts *opts;
1113
1114	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1115	if (!opts)
1116		return ERR_PTR(-ENOMEM);
1117
1118	mutex_init(&opts->lock);
1119	opts->func_inst.free_func_inst = f_midi_free_inst;
1120	opts->index = SNDRV_DEFAULT_IDX1;
1121	opts->id = SNDRV_DEFAULT_STR1;
1122	opts->buflen = 256;
1123	opts->qlen = 32;
1124	opts->in_ports = 1;
1125	opts->out_ports = 1;
1126
1127	if (create_alsa_device(&opts->func_inst)) {
1128		kfree(opts);
1129		return ERR_PTR(-ENODEV);
1130	}
1131
1132	config_group_init_type_name(&opts->func_inst.group, "",
1133				    &midi_func_type);
1134
1135	return &opts->func_inst;
1136}
1137
1138static void f_midi_free(struct usb_function *f)
1139{
1140	struct f_midi *midi;
1141	struct f_midi_opts *opts;
1142	int i;
1143
1144	midi = func_to_midi(f);
1145	opts = container_of(f->fi, struct f_midi_opts, func_inst);
1146	kfree(midi->id);
1147	mutex_lock(&opts->lock);
1148	for (i = opts->in_ports - 1; i >= 0; --i)
1149		kfree(midi->in_port[i]);
1150	kfree(midi);
1151	--opts->refcnt;
1152	mutex_unlock(&opts->lock);
1153}
1154
1155static void f_midi_unbind(struct usb_configuration *c, struct usb_function *f)
1156{
1157	struct usb_composite_dev *cdev = f->config->cdev;
1158	struct f_midi *midi = func_to_midi(f);
1159	struct snd_card *card;
1160
1161	DBG(cdev, "unbind\n");
1162
1163	/* just to be sure */
1164	f_midi_disable(f);
1165
1166	card = midi->card;
1167	midi->card = NULL;
1168	if (card)
1169		snd_card_free(card);
1170
1171	usb_free_all_descriptors(f);
1172}
1173
1174static struct usb_function *f_midi_alloc(struct usb_function_instance *fi)
1175{
1176	struct f_midi *midi;
1177	struct f_midi_opts *opts;
1178	int status, i;
1179
1180	opts = container_of(fi, struct f_midi_opts, func_inst);
1181
1182	mutex_lock(&opts->lock);
1183	/* sanity check */
1184	if (opts->in_ports > MAX_PORTS || opts->out_ports > MAX_PORTS) {
1185		mutex_unlock(&opts->lock);
1186		return ERR_PTR(-EINVAL);
1187	}
1188
1189	/* allocate and initialize one new instance */
1190	midi = kzalloc(sizeof(*midi), GFP_KERNEL);
1191	if (!midi) {
1192		mutex_unlock(&opts->lock);
1193		return ERR_PTR(-ENOMEM);
1194	}
1195
1196	for (i = 0; i < opts->in_ports; i++) {
1197		struct gmidi_in_port *port = kzalloc(sizeof(*port), GFP_KERNEL);
1198
1199		if (!port) {
1200			status = -ENOMEM;
1201			mutex_unlock(&opts->lock);
1202			goto setup_fail;
1203		}
1204
1205		port->midi = midi;
1206		port->active = 0;
1207		port->cable = i;
1208		midi->in_port[i] = port;
1209	}
1210
1211	/* set up ALSA midi devices */
1212	midi->id = kstrdup(opts->id, GFP_KERNEL);
1213	if (opts->id && !midi->id) {
1214		status = -ENOMEM;
1215		mutex_unlock(&opts->lock);
1216		goto setup_fail;
1217	}
1218	midi->in_ports = opts->in_ports;
1219	midi->out_ports = opts->out_ports;
1220	midi->index = opts->index;
1221	midi->buflen = opts->buflen;
1222	midi->qlen = opts->qlen;
1223	++opts->refcnt;
1224	mutex_unlock(&opts->lock);
1225
1226	midi->func.name		= "gmidi function";
1227	midi->func.bind		= f_midi_bind;
1228	midi->func.unbind	= f_midi_unbind;
1229	midi->func.set_alt	= f_midi_set_alt;
1230	midi->func.disable	= f_midi_disable;
1231	midi->func.free_func	= f_midi_free;
1232
1233	fi->f = &midi->func;
1234	return &midi->func;
1235
1236setup_fail:
1237	for (--i; i >= 0; i--)
1238		kfree(midi->in_port[i]);
1239	kfree(midi);
1240	return ERR_PTR(status);
1241}
1242
1243DECLARE_USB_FUNCTION_INIT(midi, f_midi_alloc_inst, f_midi_alloc);
1244