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