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/slab.h>
24 #include <linux/device.h>
25 
26 #include <sound/core.h>
27 #include <sound/initval.h>
28 #include <sound/rawmidi.h>
29 
30 #include <linux/usb/ch9.h>
31 #include <linux/usb/gadget.h>
32 #include <linux/usb/audio.h>
33 #include <linux/usb/midi.h>
34 
35 #include "u_f.h"
36 
37 MODULE_AUTHOR("Ben Williamson");
38 MODULE_LICENSE("GPL v2");
39 
40 static const char f_midi_shortname[] = "f_midi";
41 static const char f_midi_longname[] = "MIDI Gadget";
42 
43 /*
44  * We can only handle 16 cables on one single endpoint, as cable numbers are
45  * stored in 4-bit fields. And as the interface currently only holds one
46  * single endpoint, this is the maximum number of ports we can allow.
47  */
48 #define MAX_PORTS 16
49 
50 /*
51  * This is a gadget, and the IN/OUT naming is from the host's perspective.
52  * USB -> OUT endpoint -> rawmidi
53  * USB <- IN endpoint  <- rawmidi
54  */
55 struct gmidi_in_port {
56 	struct f_midi *midi;
57 	int active;
58 	uint8_t cable;
59 	uint8_t state;
60 #define STATE_UNKNOWN	0
61 #define STATE_1PARAM	1
62 #define STATE_2PARAM_1	2
63 #define STATE_2PARAM_2	3
64 #define STATE_SYSEX_0	4
65 #define STATE_SYSEX_1	5
66 #define STATE_SYSEX_2	6
67 	uint8_t data[2];
68 };
69 
70 struct f_midi {
71 	struct usb_function	func;
72 	struct usb_gadget	*gadget;
73 	struct usb_ep		*in_ep, *out_ep;
74 	struct snd_card		*card;
75 	struct snd_rawmidi	*rmidi;
76 
77 	struct snd_rawmidi_substream *in_substream[MAX_PORTS];
78 	struct snd_rawmidi_substream *out_substream[MAX_PORTS];
79 	struct gmidi_in_port	*in_port[MAX_PORTS];
80 
81 	unsigned long		out_triggered;
82 	struct tasklet_struct	tasklet;
83 	unsigned int in_ports;
84 	unsigned int out_ports;
85 	int index;
86 	char *id;
87 	unsigned int buflen, qlen;
88 };
89 
90 static inline struct f_midi *func_to_midi(struct usb_function *f)
91 {
92 	return container_of(f, struct f_midi, func);
93 }
94 
95 static void f_midi_transmit(struct f_midi *midi, struct usb_request *req);
96 
97 DECLARE_UAC_AC_HEADER_DESCRIPTOR(1);
98 DECLARE_USB_MIDI_OUT_JACK_DESCRIPTOR(1);
99 DECLARE_USB_MS_ENDPOINT_DESCRIPTOR(16);
100 
101 /* B.3.1  Standard AC Interface Descriptor */
102 static struct usb_interface_descriptor ac_interface_desc __initdata = {
103 	.bLength =		USB_DT_INTERFACE_SIZE,
104 	.bDescriptorType =	USB_DT_INTERFACE,
105 	/* .bInterfaceNumber =	DYNAMIC */
106 	/* .bNumEndpoints =	DYNAMIC */
107 	.bInterfaceClass =	USB_CLASS_AUDIO,
108 	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOCONTROL,
109 	/* .iInterface =	DYNAMIC */
110 };
111 
112 /* B.3.2  Class-Specific AC Interface Descriptor */
113 static struct uac1_ac_header_descriptor_1 ac_header_desc __initdata = {
114 	.bLength =		UAC_DT_AC_HEADER_SIZE(1),
115 	.bDescriptorType =	USB_DT_CS_INTERFACE,
116 	.bDescriptorSubtype =	USB_MS_HEADER,
117 	.bcdADC =		cpu_to_le16(0x0100),
118 	.wTotalLength =		cpu_to_le16(UAC_DT_AC_HEADER_SIZE(1)),
119 	.bInCollection =	1,
120 	/* .baInterfaceNr =	DYNAMIC */
121 };
122 
123 /* B.4.1  Standard MS Interface Descriptor */
124 static struct usb_interface_descriptor ms_interface_desc __initdata = {
125 	.bLength =		USB_DT_INTERFACE_SIZE,
126 	.bDescriptorType =	USB_DT_INTERFACE,
127 	/* .bInterfaceNumber =	DYNAMIC */
128 	.bNumEndpoints =	2,
129 	.bInterfaceClass =	USB_CLASS_AUDIO,
130 	.bInterfaceSubClass =	USB_SUBCLASS_MIDISTREAMING,
131 	/* .iInterface =	DYNAMIC */
132 };
133 
134 /* B.4.2  Class-Specific MS Interface Descriptor */
135 static struct usb_ms_header_descriptor ms_header_desc __initdata = {
136 	.bLength =		USB_DT_MS_HEADER_SIZE,
137 	.bDescriptorType =	USB_DT_CS_INTERFACE,
138 	.bDescriptorSubtype =	USB_MS_HEADER,
139 	.bcdMSC =		cpu_to_le16(0x0100),
140 	/* .wTotalLength =	DYNAMIC */
141 };
142 
143 /* B.5.1  Standard Bulk OUT Endpoint Descriptor */
144 static struct usb_endpoint_descriptor bulk_out_desc = {
145 	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
146 	.bDescriptorType =	USB_DT_ENDPOINT,
147 	.bEndpointAddress =	USB_DIR_OUT,
148 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
149 };
150 
151 /* B.5.2  Class-specific MS Bulk OUT Endpoint Descriptor */
152 static struct usb_ms_endpoint_descriptor_16 ms_out_desc = {
153 	/* .bLength =		DYNAMIC */
154 	.bDescriptorType =	USB_DT_CS_ENDPOINT,
155 	.bDescriptorSubtype =	USB_MS_GENERAL,
156 	/* .bNumEmbMIDIJack =	DYNAMIC */
157 	/* .baAssocJackID =	DYNAMIC */
158 };
159 
160 /* B.6.1  Standard Bulk IN Endpoint Descriptor */
161 static struct usb_endpoint_descriptor bulk_in_desc = {
162 	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
163 	.bDescriptorType =	USB_DT_ENDPOINT,
164 	.bEndpointAddress =	USB_DIR_IN,
165 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
166 };
167 
168 /* B.6.2  Class-specific MS Bulk IN Endpoint Descriptor */
169 static struct usb_ms_endpoint_descriptor_16 ms_in_desc = {
170 	/* .bLength =		DYNAMIC */
171 	.bDescriptorType =	USB_DT_CS_ENDPOINT,
172 	.bDescriptorSubtype =	USB_MS_GENERAL,
173 	/* .bNumEmbMIDIJack =	DYNAMIC */
174 	/* .baAssocJackID =	DYNAMIC */
175 };
176 
177 /* string IDs are assigned dynamically */
178 
179 #define STRING_FUNC_IDX			0
180 
181 static struct usb_string midi_string_defs[] = {
182 	[STRING_FUNC_IDX].s = "MIDI function",
183 	{  } /* end of list */
184 };
185 
186 static struct usb_gadget_strings midi_stringtab = {
187 	.language	= 0x0409,	/* en-us */
188 	.strings	= midi_string_defs,
189 };
190 
191 static struct usb_gadget_strings *midi_strings[] = {
192 	&midi_stringtab,
193 	NULL,
194 };
195 
196 static inline struct usb_request *midi_alloc_ep_req(struct usb_ep *ep,
197 						    unsigned length)
198 {
199 	return alloc_ep_req(ep, length, length);
200 }
201 
202 static void free_ep_req(struct usb_ep *ep, struct usb_request *req)
203 {
204 	kfree(req->buf);
205 	usb_ep_free_request(ep, req);
206 }
207 
208 static const uint8_t f_midi_cin_length[] = {
209 	0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
210 };
211 
212 /*
213  * Receives a chunk of MIDI data.
214  */
215 static void f_midi_read_data(struct usb_ep *ep, int cable,
216 			     uint8_t *data, int length)
217 {
218 	struct f_midi *midi = ep->driver_data;
219 	struct snd_rawmidi_substream *substream = midi->out_substream[cable];
220 
221 	if (!substream)
222 		/* Nobody is listening - throw it on the floor. */
223 		return;
224 
225 	if (!test_bit(cable, &midi->out_triggered))
226 		return;
227 
228 	snd_rawmidi_receive(substream, data, length);
229 }
230 
231 static void f_midi_handle_out_data(struct usb_ep *ep, struct usb_request *req)
232 {
233 	unsigned int i;
234 	u8 *buf = req->buf;
235 
236 	for (i = 0; i + 3 < req->actual; i += 4)
237 		if (buf[i] != 0) {
238 			int cable = buf[i] >> 4;
239 			int length = f_midi_cin_length[buf[i] & 0x0f];
240 			f_midi_read_data(ep, cable, &buf[i + 1], length);
241 		}
242 }
243 
244 static void
245 f_midi_complete(struct usb_ep *ep, struct usb_request *req)
246 {
247 	struct f_midi *midi = ep->driver_data;
248 	struct usb_composite_dev *cdev = midi->func.config->cdev;
249 	int status = req->status;
250 
251 	switch (status) {
252 	case 0:			 /* normal completion */
253 		if (ep == midi->out_ep) {
254 			/* We received stuff. req is queued again, below */
255 			f_midi_handle_out_data(ep, req);
256 		} else if (ep == midi->in_ep) {
257 			/* Our transmit completed. See if there's more to go.
258 			 * f_midi_transmit eats req, don't queue it again. */
259 			f_midi_transmit(midi, req);
260 			return;
261 		}
262 		break;
263 
264 	/* this endpoint is normally active while we're configured */
265 	case -ECONNABORTED:	/* hardware forced ep reset */
266 	case -ECONNRESET:	/* request dequeued */
267 	case -ESHUTDOWN:	/* disconnect from host */
268 		VDBG(cdev, "%s gone (%d), %d/%d\n", ep->name, status,
269 				req->actual, req->length);
270 		if (ep == midi->out_ep)
271 			f_midi_handle_out_data(ep, req);
272 
273 		free_ep_req(ep, req);
274 		return;
275 
276 	case -EOVERFLOW:	/* buffer overrun on read means that
277 				 * we didn't provide a big enough buffer.
278 				 */
279 	default:
280 		DBG(cdev, "%s complete --> %d, %d/%d\n", ep->name,
281 				status, req->actual, req->length);
282 		break;
283 	case -EREMOTEIO:	/* short read */
284 		break;
285 	}
286 
287 	status = usb_ep_queue(ep, req, GFP_ATOMIC);
288 	if (status) {
289 		ERROR(cdev, "kill %s:  resubmit %d bytes --> %d\n",
290 				ep->name, req->length, status);
291 		usb_ep_set_halt(ep);
292 		/* FIXME recover later ... somehow */
293 	}
294 }
295 
296 static int f_midi_start_ep(struct f_midi *midi,
297 			   struct usb_function *f,
298 			   struct usb_ep *ep)
299 {
300 	int err;
301 	struct usb_composite_dev *cdev = f->config->cdev;
302 
303 	if (ep->driver_data)
304 		usb_ep_disable(ep);
305 
306 	err = config_ep_by_speed(midi->gadget, f, ep);
307 	if (err) {
308 		ERROR(cdev, "can't configure %s: %d\n", ep->name, err);
309 		return err;
310 	}
311 
312 	err = usb_ep_enable(ep);
313 	if (err) {
314 		ERROR(cdev, "can't start %s: %d\n", ep->name, err);
315 		return err;
316 	}
317 
318 	ep->driver_data = midi;
319 
320 	return 0;
321 }
322 
323 static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
324 {
325 	struct f_midi *midi = func_to_midi(f);
326 	struct usb_composite_dev *cdev = f->config->cdev;
327 	unsigned i;
328 	int err;
329 
330 	err = f_midi_start_ep(midi, f, midi->in_ep);
331 	if (err)
332 		return err;
333 
334 	err = f_midi_start_ep(midi, f, midi->out_ep);
335 	if (err)
336 		return err;
337 
338 	if (midi->out_ep->driver_data)
339 		usb_ep_disable(midi->out_ep);
340 
341 	err = config_ep_by_speed(midi->gadget, f, midi->out_ep);
342 	if (err) {
343 		ERROR(cdev, "can't configure %s: %d\n",
344 		      midi->out_ep->name, err);
345 		return err;
346 	}
347 
348 	err = usb_ep_enable(midi->out_ep);
349 	if (err) {
350 		ERROR(cdev, "can't start %s: %d\n",
351 		      midi->out_ep->name, err);
352 		return err;
353 	}
354 
355 	midi->out_ep->driver_data = midi;
356 
357 	/* allocate a bunch of read buffers and queue them all at once. */
358 	for (i = 0; i < midi->qlen && err == 0; i++) {
359 		struct usb_request *req =
360 			midi_alloc_ep_req(midi->out_ep, midi->buflen);
361 		if (req == NULL)
362 			return -ENOMEM;
363 
364 		req->complete = f_midi_complete;
365 		err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);
366 		if (err) {
367 			ERROR(midi, "%s queue req: %d\n",
368 				    midi->out_ep->name, err);
369 		}
370 	}
371 
372 	return 0;
373 }
374 
375 static void f_midi_disable(struct usb_function *f)
376 {
377 	struct f_midi *midi = func_to_midi(f);
378 	struct usb_composite_dev *cdev = f->config->cdev;
379 
380 	DBG(cdev, "disable\n");
381 
382 	/*
383 	 * just disable endpoints, forcing completion of pending i/o.
384 	 * all our completion handlers free their requests in this case.
385 	 */
386 	usb_ep_disable(midi->in_ep);
387 	usb_ep_disable(midi->out_ep);
388 }
389 
390 static void f_midi_unbind(struct usb_configuration *c, struct usb_function *f)
391 {
392 	struct usb_composite_dev *cdev = f->config->cdev;
393 	struct f_midi *midi = func_to_midi(f);
394 	struct snd_card *card;
395 
396 	DBG(cdev, "unbind\n");
397 
398 	/* just to be sure */
399 	f_midi_disable(f);
400 
401 	card = midi->card;
402 	midi->card = NULL;
403 	if (card)
404 		snd_card_free(card);
405 
406 	kfree(midi->id);
407 	midi->id = NULL;
408 
409 	usb_free_all_descriptors(f);
410 	kfree(midi);
411 }
412 
413 static int f_midi_snd_free(struct snd_device *device)
414 {
415 	return 0;
416 }
417 
418 static void f_midi_transmit_packet(struct usb_request *req, uint8_t p0,
419 					uint8_t p1, uint8_t p2, uint8_t p3)
420 {
421 	unsigned length = req->length;
422 	u8 *buf = (u8 *)req->buf + length;
423 
424 	buf[0] = p0;
425 	buf[1] = p1;
426 	buf[2] = p2;
427 	buf[3] = p3;
428 	req->length = length + 4;
429 }
430 
431 /*
432  * Converts MIDI commands to USB MIDI packets.
433  */
434 static void f_midi_transmit_byte(struct usb_request *req,
435 				 struct gmidi_in_port *port, uint8_t b)
436 {
437 	uint8_t p0 = port->cable << 4;
438 
439 	if (b >= 0xf8) {
440 		f_midi_transmit_packet(req, p0 | 0x0f, b, 0, 0);
441 	} else if (b >= 0xf0) {
442 		switch (b) {
443 		case 0xf0:
444 			port->data[0] = b;
445 			port->state = STATE_SYSEX_1;
446 			break;
447 		case 0xf1:
448 		case 0xf3:
449 			port->data[0] = b;
450 			port->state = STATE_1PARAM;
451 			break;
452 		case 0xf2:
453 			port->data[0] = b;
454 			port->state = STATE_2PARAM_1;
455 			break;
456 		case 0xf4:
457 		case 0xf5:
458 			port->state = STATE_UNKNOWN;
459 			break;
460 		case 0xf6:
461 			f_midi_transmit_packet(req, p0 | 0x05, 0xf6, 0, 0);
462 			port->state = STATE_UNKNOWN;
463 			break;
464 		case 0xf7:
465 			switch (port->state) {
466 			case STATE_SYSEX_0:
467 				f_midi_transmit_packet(req,
468 					p0 | 0x05, 0xf7, 0, 0);
469 				break;
470 			case STATE_SYSEX_1:
471 				f_midi_transmit_packet(req,
472 					p0 | 0x06, port->data[0], 0xf7, 0);
473 				break;
474 			case STATE_SYSEX_2:
475 				f_midi_transmit_packet(req,
476 					p0 | 0x07, port->data[0],
477 					port->data[1], 0xf7);
478 				break;
479 			}
480 			port->state = STATE_UNKNOWN;
481 			break;
482 		}
483 	} else if (b >= 0x80) {
484 		port->data[0] = b;
485 		if (b >= 0xc0 && b <= 0xdf)
486 			port->state = STATE_1PARAM;
487 		else
488 			port->state = STATE_2PARAM_1;
489 	} else { /* b < 0x80 */
490 		switch (port->state) {
491 		case STATE_1PARAM:
492 			if (port->data[0] < 0xf0) {
493 				p0 |= port->data[0] >> 4;
494 			} else {
495 				p0 |= 0x02;
496 				port->state = STATE_UNKNOWN;
497 			}
498 			f_midi_transmit_packet(req, p0, port->data[0], b, 0);
499 			break;
500 		case STATE_2PARAM_1:
501 			port->data[1] = b;
502 			port->state = STATE_2PARAM_2;
503 			break;
504 		case STATE_2PARAM_2:
505 			if (port->data[0] < 0xf0) {
506 				p0 |= port->data[0] >> 4;
507 				port->state = STATE_2PARAM_1;
508 			} else {
509 				p0 |= 0x03;
510 				port->state = STATE_UNKNOWN;
511 			}
512 			f_midi_transmit_packet(req,
513 				p0, port->data[0], port->data[1], b);
514 			break;
515 		case STATE_SYSEX_0:
516 			port->data[0] = b;
517 			port->state = STATE_SYSEX_1;
518 			break;
519 		case STATE_SYSEX_1:
520 			port->data[1] = b;
521 			port->state = STATE_SYSEX_2;
522 			break;
523 		case STATE_SYSEX_2:
524 			f_midi_transmit_packet(req,
525 				p0 | 0x04, port->data[0], port->data[1], b);
526 			port->state = STATE_SYSEX_0;
527 			break;
528 		}
529 	}
530 }
531 
532 static void f_midi_transmit(struct f_midi *midi, struct usb_request *req)
533 {
534 	struct usb_ep *ep = midi->in_ep;
535 	int i;
536 
537 	if (!ep)
538 		return;
539 
540 	if (!req)
541 		req = midi_alloc_ep_req(ep, midi->buflen);
542 
543 	if (!req) {
544 		ERROR(midi, "gmidi_transmit: alloc_ep_request failed\n");
545 		return;
546 	}
547 	req->length = 0;
548 	req->complete = f_midi_complete;
549 
550 	for (i = 0; i < MAX_PORTS; i++) {
551 		struct gmidi_in_port *port = midi->in_port[i];
552 		struct snd_rawmidi_substream *substream = midi->in_substream[i];
553 
554 		if (!port || !port->active || !substream)
555 			continue;
556 
557 		while (req->length + 3 < midi->buflen) {
558 			uint8_t b;
559 			if (snd_rawmidi_transmit(substream, &b, 1) != 1) {
560 				port->active = 0;
561 				break;
562 			}
563 			f_midi_transmit_byte(req, port, b);
564 		}
565 	}
566 
567 	if (req->length > 0)
568 		usb_ep_queue(ep, req, GFP_ATOMIC);
569 	else
570 		free_ep_req(ep, req);
571 }
572 
573 static void f_midi_in_tasklet(unsigned long data)
574 {
575 	struct f_midi *midi = (struct f_midi *) data;
576 	f_midi_transmit(midi, NULL);
577 }
578 
579 static int f_midi_in_open(struct snd_rawmidi_substream *substream)
580 {
581 	struct f_midi *midi = substream->rmidi->private_data;
582 
583 	if (!midi->in_port[substream->number])
584 		return -EINVAL;
585 
586 	VDBG(midi, "%s()\n", __func__);
587 	midi->in_substream[substream->number] = substream;
588 	midi->in_port[substream->number]->state = STATE_UNKNOWN;
589 	return 0;
590 }
591 
592 static int f_midi_in_close(struct snd_rawmidi_substream *substream)
593 {
594 	struct f_midi *midi = substream->rmidi->private_data;
595 
596 	VDBG(midi, "%s()\n", __func__);
597 	return 0;
598 }
599 
600 static void f_midi_in_trigger(struct snd_rawmidi_substream *substream, int up)
601 {
602 	struct f_midi *midi = substream->rmidi->private_data;
603 
604 	if (!midi->in_port[substream->number])
605 		return;
606 
607 	VDBG(midi, "%s() %d\n", __func__, up);
608 	midi->in_port[substream->number]->active = up;
609 	if (up)
610 		tasklet_hi_schedule(&midi->tasklet);
611 }
612 
613 static int f_midi_out_open(struct snd_rawmidi_substream *substream)
614 {
615 	struct f_midi *midi = substream->rmidi->private_data;
616 
617 	if (substream->number >= MAX_PORTS)
618 		return -EINVAL;
619 
620 	VDBG(midi, "%s()\n", __func__);
621 	midi->out_substream[substream->number] = substream;
622 	return 0;
623 }
624 
625 static int f_midi_out_close(struct snd_rawmidi_substream *substream)
626 {
627 	struct f_midi *midi = substream->rmidi->private_data;
628 
629 	VDBG(midi, "%s()\n", __func__);
630 	return 0;
631 }
632 
633 static void f_midi_out_trigger(struct snd_rawmidi_substream *substream, int up)
634 {
635 	struct f_midi *midi = substream->rmidi->private_data;
636 
637 	VDBG(midi, "%s()\n", __func__);
638 
639 	if (up)
640 		set_bit(substream->number, &midi->out_triggered);
641 	else
642 		clear_bit(substream->number, &midi->out_triggered);
643 }
644 
645 static struct snd_rawmidi_ops gmidi_in_ops = {
646 	.open = f_midi_in_open,
647 	.close = f_midi_in_close,
648 	.trigger = f_midi_in_trigger,
649 };
650 
651 static struct snd_rawmidi_ops gmidi_out_ops = {
652 	.open = f_midi_out_open,
653 	.close = f_midi_out_close,
654 	.trigger = f_midi_out_trigger
655 };
656 
657 /* register as a sound "card" */
658 static int f_midi_register_card(struct f_midi *midi)
659 {
660 	struct snd_card *card;
661 	struct snd_rawmidi *rmidi;
662 	int err;
663 	static struct snd_device_ops ops = {
664 		.dev_free = f_midi_snd_free,
665 	};
666 
667 	err = snd_card_new(&midi->gadget->dev, midi->index, midi->id,
668 			   THIS_MODULE, 0, &card);
669 	if (err < 0) {
670 		ERROR(midi, "snd_card_new() failed\n");
671 		goto fail;
672 	}
673 	midi->card = card;
674 
675 	err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, midi, &ops);
676 	if (err < 0) {
677 		ERROR(midi, "snd_device_new() failed: error %d\n", err);
678 		goto fail;
679 	}
680 
681 	strcpy(card->driver, f_midi_longname);
682 	strcpy(card->longname, f_midi_longname);
683 	strcpy(card->shortname, f_midi_shortname);
684 
685 	/* Set up rawmidi */
686 	snd_component_add(card, "MIDI");
687 	err = snd_rawmidi_new(card, card->longname, 0,
688 			      midi->out_ports, midi->in_ports, &rmidi);
689 	if (err < 0) {
690 		ERROR(midi, "snd_rawmidi_new() failed: error %d\n", err);
691 		goto fail;
692 	}
693 	midi->rmidi = rmidi;
694 	strcpy(rmidi->name, card->shortname);
695 	rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
696 			    SNDRV_RAWMIDI_INFO_INPUT |
697 			    SNDRV_RAWMIDI_INFO_DUPLEX;
698 	rmidi->private_data = midi;
699 
700 	/*
701 	 * Yes, rawmidi OUTPUT = USB IN, and rawmidi INPUT = USB OUT.
702 	 * It's an upside-down world being a gadget.
703 	 */
704 	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &gmidi_in_ops);
705 	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &gmidi_out_ops);
706 
707 	/* register it - we're ready to go */
708 	err = snd_card_register(card);
709 	if (err < 0) {
710 		ERROR(midi, "snd_card_register() failed\n");
711 		goto fail;
712 	}
713 
714 	VDBG(midi, "%s() finished ok\n", __func__);
715 	return 0;
716 
717 fail:
718 	if (midi->card) {
719 		snd_card_free(midi->card);
720 		midi->card = NULL;
721 	}
722 	return err;
723 }
724 
725 /* MIDI function driver setup/binding */
726 
727 static int __init
728 f_midi_bind(struct usb_configuration *c, struct usb_function *f)
729 {
730 	struct usb_descriptor_header **midi_function;
731 	struct usb_midi_in_jack_descriptor jack_in_ext_desc[MAX_PORTS];
732 	struct usb_midi_in_jack_descriptor jack_in_emb_desc[MAX_PORTS];
733 	struct usb_midi_out_jack_descriptor_1 jack_out_ext_desc[MAX_PORTS];
734 	struct usb_midi_out_jack_descriptor_1 jack_out_emb_desc[MAX_PORTS];
735 	struct usb_composite_dev *cdev = c->cdev;
736 	struct f_midi *midi = func_to_midi(f);
737 	int status, n, jack = 1, i = 0;
738 
739 	/* maybe allocate device-global string ID */
740 	if (midi_string_defs[0].id == 0) {
741 		status = usb_string_id(c->cdev);
742 		if (status < 0)
743 			goto fail;
744 		midi_string_defs[0].id = status;
745 	}
746 
747 	/* We have two interfaces, AudioControl and MIDIStreaming */
748 	status = usb_interface_id(c, f);
749 	if (status < 0)
750 		goto fail;
751 	ac_interface_desc.bInterfaceNumber = status;
752 
753 	status = usb_interface_id(c, f);
754 	if (status < 0)
755 		goto fail;
756 	ms_interface_desc.bInterfaceNumber = status;
757 	ac_header_desc.baInterfaceNr[0] = status;
758 
759 	status = -ENODEV;
760 
761 	/* allocate instance-specific endpoints */
762 	midi->in_ep = usb_ep_autoconfig(cdev->gadget, &bulk_in_desc);
763 	if (!midi->in_ep)
764 		goto fail;
765 	midi->in_ep->driver_data = cdev;	/* claim */
766 
767 	midi->out_ep = usb_ep_autoconfig(cdev->gadget, &bulk_out_desc);
768 	if (!midi->out_ep)
769 		goto fail;
770 	midi->out_ep->driver_data = cdev;	/* claim */
771 
772 	/* allocate temporary function list */
773 	midi_function = kcalloc((MAX_PORTS * 4) + 9, sizeof(*midi_function),
774 				GFP_KERNEL);
775 	if (!midi_function) {
776 		status = -ENOMEM;
777 		goto fail;
778 	}
779 
780 	/*
781 	 * construct the function's descriptor set. As the number of
782 	 * input and output MIDI ports is configurable, we have to do
783 	 * it that way.
784 	 */
785 
786 	/* add the headers - these are always the same */
787 	midi_function[i++] = (struct usb_descriptor_header *) &ac_interface_desc;
788 	midi_function[i++] = (struct usb_descriptor_header *) &ac_header_desc;
789 	midi_function[i++] = (struct usb_descriptor_header *) &ms_interface_desc;
790 
791 	/* calculate the header's wTotalLength */
792 	n = USB_DT_MS_HEADER_SIZE
793 		+ (midi->in_ports + midi->out_ports) *
794 			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
795 	ms_header_desc.wTotalLength = cpu_to_le16(n);
796 
797 	midi_function[i++] = (struct usb_descriptor_header *) &ms_header_desc;
798 
799 	/* configure the external IN jacks, each linked to an embedded OUT jack */
800 	for (n = 0; n < midi->in_ports; n++) {
801 		struct usb_midi_in_jack_descriptor *in_ext = &jack_in_ext_desc[n];
802 		struct usb_midi_out_jack_descriptor_1 *out_emb = &jack_out_emb_desc[n];
803 
804 		in_ext->bLength			= USB_DT_MIDI_IN_SIZE;
805 		in_ext->bDescriptorType		= USB_DT_CS_INTERFACE;
806 		in_ext->bDescriptorSubtype	= USB_MS_MIDI_IN_JACK;
807 		in_ext->bJackType		= USB_MS_EXTERNAL;
808 		in_ext->bJackID			= jack++;
809 		in_ext->iJack			= 0;
810 		midi_function[i++] = (struct usb_descriptor_header *) in_ext;
811 
812 		out_emb->bLength		= USB_DT_MIDI_OUT_SIZE(1);
813 		out_emb->bDescriptorType	= USB_DT_CS_INTERFACE;
814 		out_emb->bDescriptorSubtype	= USB_MS_MIDI_OUT_JACK;
815 		out_emb->bJackType		= USB_MS_EMBEDDED;
816 		out_emb->bJackID		= jack++;
817 		out_emb->bNrInputPins		= 1;
818 		out_emb->pins[0].baSourcePin	= 1;
819 		out_emb->pins[0].baSourceID	= in_ext->bJackID;
820 		out_emb->iJack			= 0;
821 		midi_function[i++] = (struct usb_descriptor_header *) out_emb;
822 
823 		/* link it to the endpoint */
824 		ms_in_desc.baAssocJackID[n] = out_emb->bJackID;
825 	}
826 
827 	/* configure the external OUT jacks, each linked to an embedded IN jack */
828 	for (n = 0; n < midi->out_ports; n++) {
829 		struct usb_midi_in_jack_descriptor *in_emb = &jack_in_emb_desc[n];
830 		struct usb_midi_out_jack_descriptor_1 *out_ext = &jack_out_ext_desc[n];
831 
832 		in_emb->bLength			= USB_DT_MIDI_IN_SIZE;
833 		in_emb->bDescriptorType		= USB_DT_CS_INTERFACE;
834 		in_emb->bDescriptorSubtype	= USB_MS_MIDI_IN_JACK;
835 		in_emb->bJackType		= USB_MS_EMBEDDED;
836 		in_emb->bJackID			= jack++;
837 		in_emb->iJack			= 0;
838 		midi_function[i++] = (struct usb_descriptor_header *) in_emb;
839 
840 		out_ext->bLength =		USB_DT_MIDI_OUT_SIZE(1);
841 		out_ext->bDescriptorType =	USB_DT_CS_INTERFACE;
842 		out_ext->bDescriptorSubtype =	USB_MS_MIDI_OUT_JACK;
843 		out_ext->bJackType =		USB_MS_EXTERNAL;
844 		out_ext->bJackID =		jack++;
845 		out_ext->bNrInputPins =		1;
846 		out_ext->iJack =		0;
847 		out_ext->pins[0].baSourceID =	in_emb->bJackID;
848 		out_ext->pins[0].baSourcePin =	1;
849 		midi_function[i++] = (struct usb_descriptor_header *) out_ext;
850 
851 		/* link it to the endpoint */
852 		ms_out_desc.baAssocJackID[n] = in_emb->bJackID;
853 	}
854 
855 	/* configure the endpoint descriptors ... */
856 	ms_out_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->in_ports);
857 	ms_out_desc.bNumEmbMIDIJack = midi->in_ports;
858 
859 	ms_in_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->out_ports);
860 	ms_in_desc.bNumEmbMIDIJack = midi->out_ports;
861 
862 	/* ... and add them to the list */
863 	midi_function[i++] = (struct usb_descriptor_header *) &bulk_out_desc;
864 	midi_function[i++] = (struct usb_descriptor_header *) &ms_out_desc;
865 	midi_function[i++] = (struct usb_descriptor_header *) &bulk_in_desc;
866 	midi_function[i++] = (struct usb_descriptor_header *) &ms_in_desc;
867 	midi_function[i++] = NULL;
868 
869 	/*
870 	 * support all relevant hardware speeds... we expect that when
871 	 * hardware is dual speed, all bulk-capable endpoints work at
872 	 * both speeds
873 	 */
874 	/* copy descriptors, and track endpoint copies */
875 	f->fs_descriptors = usb_copy_descriptors(midi_function);
876 	if (!f->fs_descriptors)
877 		goto fail_f_midi;
878 
879 	if (gadget_is_dualspeed(c->cdev->gadget)) {
880 		bulk_in_desc.wMaxPacketSize = cpu_to_le16(512);
881 		bulk_out_desc.wMaxPacketSize = cpu_to_le16(512);
882 		f->hs_descriptors = usb_copy_descriptors(midi_function);
883 		if (!f->hs_descriptors)
884 			goto fail_f_midi;
885 	}
886 
887 	kfree(midi_function);
888 
889 	return 0;
890 
891 fail_f_midi:
892 	kfree(midi_function);
893 	usb_free_descriptors(f->hs_descriptors);
894 fail:
895 	/* we might as well release our claims on endpoints */
896 	if (midi->out_ep)
897 		midi->out_ep->driver_data = NULL;
898 	if (midi->in_ep)
899 		midi->in_ep->driver_data = NULL;
900 
901 	ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
902 
903 	return status;
904 }
905 
906 /**
907  * f_midi_bind_config - add USB MIDI function to a configuration
908  * @c: the configuration to supcard the USB audio function
909  * @index: the soundcard index to use for the ALSA device creation
910  * @id: the soundcard id to use for the ALSA device creation
911  * @buflen: the buffer length to use
912  * @qlen the number of read requests to pre-allocate
913  * Context: single threaded during gadget setup
914  *
915  * Returns zero on success, else negative errno.
916  */
917 int __init f_midi_bind_config(struct usb_configuration *c,
918 			      int index, char *id,
919 			      unsigned int in_ports,
920 			      unsigned int out_ports,
921 			      unsigned int buflen,
922 			      unsigned int qlen)
923 {
924 	struct f_midi *midi;
925 	int status, i;
926 
927 	/* sanity check */
928 	if (in_ports > MAX_PORTS || out_ports > MAX_PORTS)
929 		return -EINVAL;
930 
931 	/* allocate and initialize one new instance */
932 	midi = kzalloc(sizeof *midi, GFP_KERNEL);
933 	if (!midi) {
934 		status = -ENOMEM;
935 		goto fail;
936 	}
937 
938 	for (i = 0; i < in_ports; i++) {
939 		struct gmidi_in_port *port = kzalloc(sizeof(*port), GFP_KERNEL);
940 		if (!port) {
941 			status = -ENOMEM;
942 			goto setup_fail;
943 		}
944 
945 		port->midi = midi;
946 		port->active = 0;
947 		port->cable = i;
948 		midi->in_port[i] = port;
949 	}
950 
951 	midi->gadget = c->cdev->gadget;
952 	tasklet_init(&midi->tasklet, f_midi_in_tasklet, (unsigned long) midi);
953 
954 	/* set up ALSA midi devices */
955 	midi->in_ports = in_ports;
956 	midi->out_ports = out_ports;
957 	status = f_midi_register_card(midi);
958 	if (status < 0)
959 		goto setup_fail;
960 
961 	midi->func.name        = "gmidi function";
962 	midi->func.strings     = midi_strings;
963 	midi->func.bind        = f_midi_bind;
964 	midi->func.unbind      = f_midi_unbind;
965 	midi->func.set_alt     = f_midi_set_alt;
966 	midi->func.disable     = f_midi_disable;
967 
968 	midi->id = kstrdup(id, GFP_KERNEL);
969 	midi->index = index;
970 	midi->buflen = buflen;
971 	midi->qlen = qlen;
972 
973 	status = usb_add_function(c, &midi->func);
974 	if (status)
975 		goto setup_fail;
976 
977 	return 0;
978 
979 setup_fail:
980 	for (--i; i >= 0; i--)
981 		kfree(midi->in_port[i]);
982 	kfree(midi);
983 fail:
984 	return status;
985 }
986 
987