xref: /linux/drivers/usb/gadget/function/f_midi.c (revision 78a8d6537f1de34770e460edee360b556ef40427)
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 			queue_work(system_highpri_wq, &midi->work);
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 	unsigned long flags;
424 
425 	DBG(cdev, "disable\n");
426 
427 	/*
428 	 * just disable endpoints, forcing completion of pending i/o.
429 	 * all our completion handlers free their requests in this case.
430 	 */
431 	usb_ep_disable(midi->in_ep);
432 	usb_ep_disable(midi->out_ep);
433 
434 	/* release IN requests */
435 	spin_lock_irqsave(&midi->transmit_lock, flags);
436 	while (kfifo_get(&midi->in_req_fifo, &req))
437 		free_ep_req(midi->in_ep, req);
438 	spin_unlock_irqrestore(&midi->transmit_lock, flags);
439 
440 	f_midi_drop_out_substreams(midi);
441 }
442 
443 static int f_midi_snd_free(struct snd_device *device)
444 {
445 	return 0;
446 }
447 
448 /*
449  * Converts MIDI commands to USB MIDI packets.
450  */
451 static void f_midi_transmit_byte(struct usb_request *req,
452 				 struct gmidi_in_port *port, uint8_t b)
453 {
454 	uint8_t p[4] = { port->cable << 4, 0, 0, 0 };
455 	uint8_t next_state = STATE_INITIAL;
456 
457 	switch (b) {
458 	case 0xf8 ... 0xff:
459 		/* System Real-Time Messages */
460 		p[0] |= 0x0f;
461 		p[1] = b;
462 		next_state = port->state;
463 		port->state = STATE_REAL_TIME;
464 		break;
465 
466 	case 0xf7:
467 		/* End of SysEx */
468 		switch (port->state) {
469 		case STATE_SYSEX_0:
470 			p[0] |= 0x05;
471 			p[1] = 0xf7;
472 			next_state = STATE_FINISHED;
473 			break;
474 		case STATE_SYSEX_1:
475 			p[0] |= 0x06;
476 			p[1] = port->data[0];
477 			p[2] = 0xf7;
478 			next_state = STATE_FINISHED;
479 			break;
480 		case STATE_SYSEX_2:
481 			p[0] |= 0x07;
482 			p[1] = port->data[0];
483 			p[2] = port->data[1];
484 			p[3] = 0xf7;
485 			next_state = STATE_FINISHED;
486 			break;
487 		default:
488 			/* Ignore byte */
489 			next_state = port->state;
490 			port->state = STATE_INITIAL;
491 		}
492 		break;
493 
494 	case 0xf0 ... 0xf6:
495 		/* System Common Messages */
496 		port->data[0] = port->data[1] = 0;
497 		port->state = STATE_INITIAL;
498 		switch (b) {
499 		case 0xf0:
500 			port->data[0] = b;
501 			port->data[1] = 0;
502 			next_state = STATE_SYSEX_1;
503 			break;
504 		case 0xf1:
505 		case 0xf3:
506 			port->data[0] = b;
507 			next_state = STATE_1PARAM;
508 			break;
509 		case 0xf2:
510 			port->data[0] = b;
511 			next_state = STATE_2PARAM_1;
512 			break;
513 		case 0xf4:
514 		case 0xf5:
515 			next_state = STATE_INITIAL;
516 			break;
517 		case 0xf6:
518 			p[0] |= 0x05;
519 			p[1] = 0xf6;
520 			next_state = STATE_FINISHED;
521 			break;
522 		}
523 		break;
524 
525 	case 0x80 ... 0xef:
526 		/*
527 		 * Channel Voice Messages, Channel Mode Messages
528 		 * and Control Change Messages.
529 		 */
530 		port->data[0] = b;
531 		port->data[1] = 0;
532 		port->state = STATE_INITIAL;
533 		if (b >= 0xc0 && b <= 0xdf)
534 			next_state = STATE_1PARAM;
535 		else
536 			next_state = STATE_2PARAM_1;
537 		break;
538 
539 	case 0x00 ... 0x7f:
540 		/* Message parameters */
541 		switch (port->state) {
542 		case STATE_1PARAM:
543 			if (port->data[0] < 0xf0)
544 				p[0] |= port->data[0] >> 4;
545 			else
546 				p[0] |= 0x02;
547 
548 			p[1] = port->data[0];
549 			p[2] = b;
550 			/* This is to allow Running State Messages */
551 			next_state = STATE_1PARAM;
552 			break;
553 		case STATE_2PARAM_1:
554 			port->data[1] = b;
555 			next_state = STATE_2PARAM_2;
556 			break;
557 		case STATE_2PARAM_2:
558 			if (port->data[0] < 0xf0)
559 				p[0] |= port->data[0] >> 4;
560 			else
561 				p[0] |= 0x03;
562 
563 			p[1] = port->data[0];
564 			p[2] = port->data[1];
565 			p[3] = b;
566 			/* This is to allow Running State Messages */
567 			next_state = STATE_2PARAM_1;
568 			break;
569 		case STATE_SYSEX_0:
570 			port->data[0] = b;
571 			next_state = STATE_SYSEX_1;
572 			break;
573 		case STATE_SYSEX_1:
574 			port->data[1] = b;
575 			next_state = STATE_SYSEX_2;
576 			break;
577 		case STATE_SYSEX_2:
578 			p[0] |= 0x04;
579 			p[1] = port->data[0];
580 			p[2] = port->data[1];
581 			p[3] = b;
582 			next_state = STATE_SYSEX_0;
583 			break;
584 		}
585 		break;
586 	}
587 
588 	/* States where we have to write into the USB request */
589 	if (next_state == STATE_FINISHED ||
590 	    port->state == STATE_SYSEX_2 ||
591 	    port->state == STATE_1PARAM ||
592 	    port->state == STATE_2PARAM_2 ||
593 	    port->state == STATE_REAL_TIME) {
594 
595 		unsigned int length = req->length;
596 		u8 *buf = (u8 *)req->buf + length;
597 
598 		memcpy(buf, p, sizeof(p));
599 		req->length = length + sizeof(p);
600 
601 		if (next_state == STATE_FINISHED) {
602 			next_state = STATE_INITIAL;
603 			port->data[0] = port->data[1] = 0;
604 		}
605 	}
606 
607 	port->state = next_state;
608 }
609 
610 static int f_midi_do_transmit(struct f_midi *midi, struct usb_ep *ep)
611 {
612 	struct usb_request *req = NULL;
613 	unsigned int len, i;
614 	bool active = false;
615 	int err;
616 
617 	/*
618 	 * We peek the request in order to reuse it if it fails to enqueue on
619 	 * its endpoint
620 	 */
621 	len = kfifo_peek(&midi->in_req_fifo, &req);
622 	if (len != 1) {
623 		ERROR(midi, "%s: Couldn't get usb request\n", __func__);
624 		return -1;
625 	}
626 
627 	/*
628 	 * If buffer overrun, then we ignore this transmission.
629 	 * IMPORTANT: This will cause the user-space rawmidi device to block
630 	 * until a) usb requests have been completed or b) snd_rawmidi_write()
631 	 * times out.
632 	 */
633 	if (req->length > 0)
634 		return 0;
635 
636 	for (i = midi->in_last_port; i < midi->in_ports; ++i) {
637 		struct gmidi_in_port *port = midi->in_ports_array + i;
638 		struct snd_rawmidi_substream *substream = port->substream;
639 
640 		if (!port->active || !substream)
641 			continue;
642 
643 		while (req->length + 3 < midi->buflen) {
644 			uint8_t b;
645 
646 			if (snd_rawmidi_transmit(substream, &b, 1) != 1) {
647 				port->active = 0;
648 				break;
649 			}
650 			f_midi_transmit_byte(req, port, b);
651 		}
652 
653 		active = !!port->active;
654 		if (active)
655 			break;
656 	}
657 	midi->in_last_port = active ? i : 0;
658 
659 	if (req->length <= 0)
660 		goto done;
661 
662 	err = usb_ep_queue(ep, req, GFP_ATOMIC);
663 	if (err < 0) {
664 		ERROR(midi, "%s failed to queue req: %d\n",
665 		      midi->in_ep->name, err);
666 		req->length = 0; /* Re-use request next time. */
667 		return err;
668 	} else {
669 		/* Upon success, put request at the back of the queue. */
670 		kfifo_skip(&midi->in_req_fifo);
671 		kfifo_put(&midi->in_req_fifo, req);
672 	}
673 
674 done:
675 	return active;
676 }
677 
678 static void f_midi_transmit(struct f_midi *midi)
679 {
680 	struct usb_ep *ep = midi->in_ep;
681 	int ret;
682 	unsigned long flags;
683 
684 	/* We only care about USB requests if IN endpoint is enabled */
685 	if (!ep || !ep->enabled)
686 		goto drop_out;
687 
688 	spin_lock_irqsave(&midi->transmit_lock, flags);
689 
690 	do {
691 		ret = f_midi_do_transmit(midi, ep);
692 		if (ret < 0) {
693 			spin_unlock_irqrestore(&midi->transmit_lock, flags);
694 			goto drop_out;
695 		}
696 	} while (ret);
697 
698 	spin_unlock_irqrestore(&midi->transmit_lock, flags);
699 
700 	return;
701 
702 drop_out:
703 	f_midi_drop_out_substreams(midi);
704 }
705 
706 static void f_midi_in_work(struct work_struct *work)
707 {
708 	struct f_midi *midi;
709 
710 	midi = container_of(work, struct f_midi, work);
711 	f_midi_transmit(midi);
712 }
713 
714 static int f_midi_in_open(struct snd_rawmidi_substream *substream)
715 {
716 	struct f_midi *midi = substream->rmidi->private_data;
717 	struct gmidi_in_port *port;
718 
719 	if (substream->number >= midi->in_ports)
720 		return -EINVAL;
721 
722 	VDBG(midi, "%s()\n", __func__);
723 	port = midi->in_ports_array + substream->number;
724 	port->substream = substream;
725 	port->state = STATE_INITIAL;
726 	return 0;
727 }
728 
729 static int f_midi_in_close(struct snd_rawmidi_substream *substream)
730 {
731 	struct f_midi *midi = substream->rmidi->private_data;
732 
733 	VDBG(midi, "%s()\n", __func__);
734 	return 0;
735 }
736 
737 static void f_midi_in_trigger(struct snd_rawmidi_substream *substream, int up)
738 {
739 	struct f_midi *midi = substream->rmidi->private_data;
740 
741 	if (substream->number >= midi->in_ports)
742 		return;
743 
744 	VDBG(midi, "%s() %d\n", __func__, up);
745 	midi->in_ports_array[substream->number].active = up;
746 	if (up)
747 		queue_work(system_highpri_wq, &midi->work);
748 }
749 
750 static int f_midi_out_open(struct snd_rawmidi_substream *substream)
751 {
752 	struct f_midi *midi = substream->rmidi->private_data;
753 
754 	if (substream->number >= MAX_PORTS)
755 		return -EINVAL;
756 
757 	VDBG(midi, "%s()\n", __func__);
758 	midi->out_substream[substream->number] = substream;
759 	return 0;
760 }
761 
762 static int f_midi_out_close(struct snd_rawmidi_substream *substream)
763 {
764 	struct f_midi *midi = substream->rmidi->private_data;
765 
766 	VDBG(midi, "%s()\n", __func__);
767 	return 0;
768 }
769 
770 static void f_midi_out_trigger(struct snd_rawmidi_substream *substream, int up)
771 {
772 	struct f_midi *midi = substream->rmidi->private_data;
773 
774 	VDBG(midi, "%s()\n", __func__);
775 
776 	if (up)
777 		set_bit(substream->number, &midi->out_triggered);
778 	else
779 		clear_bit(substream->number, &midi->out_triggered);
780 }
781 
782 static const struct snd_rawmidi_ops gmidi_in_ops = {
783 	.open = f_midi_in_open,
784 	.close = f_midi_in_close,
785 	.trigger = f_midi_in_trigger,
786 };
787 
788 static const struct snd_rawmidi_ops gmidi_out_ops = {
789 	.open = f_midi_out_open,
790 	.close = f_midi_out_close,
791 	.trigger = f_midi_out_trigger
792 };
793 
794 static inline void f_midi_unregister_card(struct f_midi *midi)
795 {
796 	if (midi->card) {
797 		snd_card_free(midi->card);
798 		midi->card = NULL;
799 	}
800 }
801 
802 /* register as a sound "card" */
803 static int f_midi_register_card(struct f_midi *midi)
804 {
805 	struct snd_card *card;
806 	struct snd_rawmidi *rmidi;
807 	int err;
808 	static struct snd_device_ops ops = {
809 		.dev_free = f_midi_snd_free,
810 	};
811 
812 	err = snd_card_new(&midi->gadget->dev, midi->index, midi->id,
813 			   THIS_MODULE, 0, &card);
814 	if (err < 0) {
815 		ERROR(midi, "snd_card_new() failed\n");
816 		goto fail;
817 	}
818 	midi->card = card;
819 
820 	err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, midi, &ops);
821 	if (err < 0) {
822 		ERROR(midi, "snd_device_new() failed: error %d\n", err);
823 		goto fail;
824 	}
825 
826 	strscpy(card->driver, f_midi_longname);
827 	strscpy(card->longname, f_midi_longname);
828 	strscpy(card->shortname, f_midi_shortname);
829 
830 	/* Set up rawmidi */
831 	snd_component_add(card, "MIDI");
832 	err = snd_rawmidi_new(card, card->longname, 0,
833 			      midi->out_ports, midi->in_ports, &rmidi);
834 	if (err < 0) {
835 		ERROR(midi, "snd_rawmidi_new() failed: error %d\n", err);
836 		goto fail;
837 	}
838 	midi->rmidi = rmidi;
839 	midi->in_last_port = 0;
840 	strscpy(rmidi->name, card->shortname);
841 	rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
842 			    SNDRV_RAWMIDI_INFO_INPUT |
843 			    SNDRV_RAWMIDI_INFO_DUPLEX;
844 	rmidi->private_data = midi;
845 	rmidi->private_free = f_midi_rmidi_free;
846 	midi->free_ref++;
847 
848 	/*
849 	 * Yes, rawmidi OUTPUT = USB IN, and rawmidi INPUT = USB OUT.
850 	 * It's an upside-down world being a gadget.
851 	 */
852 	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &gmidi_in_ops);
853 	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &gmidi_out_ops);
854 
855 	/* register it - we're ready to go */
856 	err = snd_card_register(card);
857 	if (err < 0) {
858 		ERROR(midi, "snd_card_register() failed\n");
859 		goto fail;
860 	}
861 
862 	VDBG(midi, "%s() finished ok\n", __func__);
863 	return 0;
864 
865 fail:
866 	f_midi_unregister_card(midi);
867 	return err;
868 }
869 
870 /* MIDI function driver setup/binding */
871 
872 static int f_midi_bind(struct usb_configuration *c, struct usb_function *f)
873 {
874 	struct usb_descriptor_header **midi_function;
875 	struct usb_midi_in_jack_descriptor jack_in_ext_desc[MAX_PORTS];
876 	struct usb_midi_in_jack_descriptor jack_in_emb_desc[MAX_PORTS];
877 	struct usb_midi_out_jack_descriptor_1 jack_out_ext_desc[MAX_PORTS];
878 	struct usb_midi_out_jack_descriptor_1 jack_out_emb_desc[MAX_PORTS];
879 	struct usb_composite_dev *cdev = c->cdev;
880 	struct f_midi *midi = func_to_midi(f);
881 	struct usb_string *us;
882 	struct f_midi_opts *opts;
883 	int status, n, jack = 1, i = 0, endpoint_descriptor_index = 0;
884 
885 	midi->gadget = cdev->gadget;
886 	status = f_midi_register_card(midi);
887 	if (status < 0)
888 		goto fail_register;
889 
890 	opts = container_of(f->fi, struct f_midi_opts, func_inst);
891 	if (opts->interface_string)
892 		midi_string_defs[STRING_FUNC_IDX].s = opts->interface_string;
893 
894 	/* maybe allocate device-global string ID */
895 	us = usb_gstrings_attach(c->cdev, midi_strings,
896 				 ARRAY_SIZE(midi_string_defs));
897 	if (IS_ERR(us)) {
898 		status = PTR_ERR(us);
899 		goto fail;
900 	}
901 	ac_interface_desc.iInterface = us[STRING_FUNC_IDX].id;
902 
903 	/* We have two interfaces, AudioControl and MIDIStreaming */
904 	status = usb_interface_id(c, f);
905 	if (status < 0)
906 		goto fail;
907 	ac_interface_desc.bInterfaceNumber = status;
908 
909 	status = usb_interface_id(c, f);
910 	if (status < 0)
911 		goto fail;
912 	ms_interface_desc.bInterfaceNumber = status;
913 	ac_header_desc.baInterfaceNr[0] = status;
914 	midi->ms_id = status;
915 
916 	status = -ENODEV;
917 
918 	/*
919 	 * Reset wMaxPacketSize with maximum packet size of FS bulk transfer before
920 	 * endpoint claim. This ensures that the wMaxPacketSize does not exceed the
921 	 * limit during bind retries where configured dwc3 TX/RX FIFO's maxpacket
922 	 * size of 512 bytes for IN/OUT endpoints in support HS speed only.
923 	 */
924 	bulk_in_desc.wMaxPacketSize = cpu_to_le16(64);
925 	bulk_out_desc.wMaxPacketSize = cpu_to_le16(64);
926 
927 	/* allocate instance-specific endpoints */
928 	midi->in_ep = usb_ep_autoconfig(cdev->gadget, &bulk_in_desc);
929 	if (!midi->in_ep)
930 		goto fail;
931 
932 	midi->out_ep = usb_ep_autoconfig(cdev->gadget, &bulk_out_desc);
933 	if (!midi->out_ep)
934 		goto fail;
935 
936 	/* allocate temporary function list */
937 	midi_function = kzalloc_objs(*midi_function, (MAX_PORTS * 4) + 11);
938 	if (!midi_function) {
939 		status = -ENOMEM;
940 		goto fail;
941 	}
942 
943 	/*
944 	 * construct the function's descriptor set. As the number of
945 	 * input and output MIDI ports is configurable, we have to do
946 	 * it that way.
947 	 */
948 
949 	/* add the headers - these are always the same */
950 	midi_function[i++] = (struct usb_descriptor_header *) &ac_interface_desc;
951 	midi_function[i++] = (struct usb_descriptor_header *) &ac_header_desc;
952 	midi_function[i++] = (struct usb_descriptor_header *) &ms_interface_desc;
953 
954 	/* calculate the header's wTotalLength */
955 	n = USB_DT_MS_HEADER_SIZE
956 		+ (midi->in_ports + midi->out_ports) *
957 			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
958 	ms_header_desc.wTotalLength = cpu_to_le16(n);
959 
960 	midi_function[i++] = (struct usb_descriptor_header *) &ms_header_desc;
961 
962 	/* configure the external IN jacks, each linked to an embedded OUT jack */
963 	for (n = 0; n < midi->in_ports; n++) {
964 		struct usb_midi_in_jack_descriptor *in_ext = &jack_in_ext_desc[n];
965 		struct usb_midi_out_jack_descriptor_1 *out_emb = &jack_out_emb_desc[n];
966 
967 		in_ext->bLength			= USB_DT_MIDI_IN_SIZE;
968 		in_ext->bDescriptorType		= USB_DT_CS_INTERFACE;
969 		in_ext->bDescriptorSubtype	= USB_MS_MIDI_IN_JACK;
970 		in_ext->bJackType		= USB_MS_EXTERNAL;
971 		in_ext->bJackID			= jack++;
972 		in_ext->iJack			= 0;
973 		midi_function[i++] = (struct usb_descriptor_header *) in_ext;
974 
975 		out_emb->bLength		= USB_DT_MIDI_OUT_SIZE(1);
976 		out_emb->bDescriptorType	= USB_DT_CS_INTERFACE;
977 		out_emb->bDescriptorSubtype	= USB_MS_MIDI_OUT_JACK;
978 		out_emb->bJackType		= USB_MS_EMBEDDED;
979 		out_emb->bJackID		= jack++;
980 		out_emb->bNrInputPins		= 1;
981 		out_emb->pins[0].baSourcePin	= 1;
982 		out_emb->pins[0].baSourceID	= in_ext->bJackID;
983 		out_emb->iJack			= 0;
984 		midi_function[i++] = (struct usb_descriptor_header *) out_emb;
985 
986 		/* link it to the endpoint */
987 		ms_in_desc.baAssocJackID[n] = out_emb->bJackID;
988 	}
989 
990 	/* configure the external OUT jacks, each linked to an embedded IN jack */
991 	for (n = 0; n < midi->out_ports; n++) {
992 		struct usb_midi_in_jack_descriptor *in_emb = &jack_in_emb_desc[n];
993 		struct usb_midi_out_jack_descriptor_1 *out_ext = &jack_out_ext_desc[n];
994 
995 		in_emb->bLength			= USB_DT_MIDI_IN_SIZE;
996 		in_emb->bDescriptorType		= USB_DT_CS_INTERFACE;
997 		in_emb->bDescriptorSubtype	= USB_MS_MIDI_IN_JACK;
998 		in_emb->bJackType		= USB_MS_EMBEDDED;
999 		in_emb->bJackID			= jack++;
1000 		in_emb->iJack			= 0;
1001 		midi_function[i++] = (struct usb_descriptor_header *) in_emb;
1002 
1003 		out_ext->bLength =		USB_DT_MIDI_OUT_SIZE(1);
1004 		out_ext->bDescriptorType =	USB_DT_CS_INTERFACE;
1005 		out_ext->bDescriptorSubtype =	USB_MS_MIDI_OUT_JACK;
1006 		out_ext->bJackType =		USB_MS_EXTERNAL;
1007 		out_ext->bJackID =		jack++;
1008 		out_ext->bNrInputPins =		1;
1009 		out_ext->iJack =		0;
1010 		out_ext->pins[0].baSourceID =	in_emb->bJackID;
1011 		out_ext->pins[0].baSourcePin =	1;
1012 		midi_function[i++] = (struct usb_descriptor_header *) out_ext;
1013 
1014 		/* link it to the endpoint */
1015 		ms_out_desc.baAssocJackID[n] = in_emb->bJackID;
1016 	}
1017 
1018 	/* configure the endpoint descriptors ... */
1019 	ms_out_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->out_ports);
1020 	ms_out_desc.bNumEmbMIDIJack = midi->out_ports;
1021 
1022 	ms_in_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->in_ports);
1023 	ms_in_desc.bNumEmbMIDIJack = midi->in_ports;
1024 
1025 	/* ... and add them to the list */
1026 	endpoint_descriptor_index = i;
1027 	midi_function[i++] = (struct usb_descriptor_header *) &bulk_out_desc;
1028 	midi_function[i++] = (struct usb_descriptor_header *) &ms_out_desc;
1029 	midi_function[i++] = (struct usb_descriptor_header *) &bulk_in_desc;
1030 	midi_function[i++] = (struct usb_descriptor_header *) &ms_in_desc;
1031 	midi_function[i++] = NULL;
1032 
1033 	/*
1034 	 * support all relevant hardware speeds... we expect that when
1035 	 * hardware is dual speed, all bulk-capable endpoints work at
1036 	 * both speeds
1037 	 */
1038 	/* copy descriptors, and track endpoint copies */
1039 	f->fs_descriptors = usb_copy_descriptors(midi_function);
1040 	if (!f->fs_descriptors)
1041 		goto fail_f_midi;
1042 
1043 	bulk_in_desc.wMaxPacketSize = cpu_to_le16(512);
1044 	bulk_out_desc.wMaxPacketSize = cpu_to_le16(512);
1045 	f->hs_descriptors = usb_copy_descriptors(midi_function);
1046 	if (!f->hs_descriptors)
1047 		goto fail_f_midi;
1048 
1049 	bulk_in_desc.wMaxPacketSize = cpu_to_le16(1024);
1050 	bulk_out_desc.wMaxPacketSize = cpu_to_le16(1024);
1051 	i = endpoint_descriptor_index;
1052 	midi_function[i++] = (struct usb_descriptor_header *)
1053 			     &bulk_out_desc;
1054 	midi_function[i++] = (struct usb_descriptor_header *)
1055 			     &bulk_out_ss_comp_desc;
1056 	midi_function[i++] = (struct usb_descriptor_header *)
1057 			     &ms_out_desc;
1058 	midi_function[i++] = (struct usb_descriptor_header *)
1059 			     &bulk_in_desc;
1060 	midi_function[i++] = (struct usb_descriptor_header *)
1061 			     &bulk_in_ss_comp_desc;
1062 	midi_function[i++] = (struct usb_descriptor_header *)
1063 			     &ms_in_desc;
1064 	f->ss_descriptors = usb_copy_descriptors(midi_function);
1065 	if (!f->ss_descriptors)
1066 		goto fail_f_midi;
1067 
1068 	kfree(midi_function);
1069 
1070 	return 0;
1071 
1072 fail_f_midi:
1073 	kfree(midi_function);
1074 	usb_free_all_descriptors(f);
1075 fail:
1076 	f_midi_unregister_card(midi);
1077 fail_register:
1078 	ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
1079 
1080 	return status;
1081 }
1082 
1083 static inline struct f_midi_opts *to_f_midi_opts(struct config_item *item)
1084 {
1085 	return container_of(to_config_group(item), struct f_midi_opts,
1086 			    func_inst.group);
1087 }
1088 
1089 static void midi_attr_release(struct config_item *item)
1090 {
1091 	struct f_midi_opts *opts = to_f_midi_opts(item);
1092 
1093 	usb_put_function_instance(&opts->func_inst);
1094 }
1095 
1096 static const struct configfs_item_operations midi_item_ops = {
1097 	.release	= midi_attr_release,
1098 };
1099 
1100 #define F_MIDI_OPT(name, test_limit, limit)				\
1101 static ssize_t f_midi_opts_##name##_show(struct config_item *item, char *page) \
1102 {									\
1103 	struct f_midi_opts *opts = to_f_midi_opts(item);		\
1104 	int result;							\
1105 									\
1106 	mutex_lock(&opts->lock);					\
1107 	result = sprintf(page, "%u\n", opts->name);			\
1108 	mutex_unlock(&opts->lock);					\
1109 									\
1110 	return result;							\
1111 }									\
1112 									\
1113 static ssize_t f_midi_opts_##name##_store(struct config_item *item,	\
1114 					 const char *page, size_t len)	\
1115 {									\
1116 	struct f_midi_opts *opts = to_f_midi_opts(item);		\
1117 	int ret;							\
1118 	u32 num;							\
1119 									\
1120 	mutex_lock(&opts->lock);					\
1121 	if (opts->refcnt > 1) {						\
1122 		ret = -EBUSY;						\
1123 		goto end;						\
1124 	}								\
1125 									\
1126 	ret = kstrtou32(page, 0, &num);					\
1127 	if (ret)							\
1128 		goto end;						\
1129 									\
1130 	if (test_limit && num > limit) {				\
1131 		ret = -EINVAL;						\
1132 		goto end;						\
1133 	}								\
1134 	opts->name = num;						\
1135 	ret = len;							\
1136 									\
1137 end:									\
1138 	mutex_unlock(&opts->lock);					\
1139 	return ret;							\
1140 }									\
1141 									\
1142 CONFIGFS_ATTR(f_midi_opts_, name);
1143 
1144 #define F_MIDI_OPT_SIGNED(name, test_limit, limit)				\
1145 static ssize_t f_midi_opts_##name##_show(struct config_item *item, char *page) \
1146 {									\
1147 	struct f_midi_opts *opts = to_f_midi_opts(item);		\
1148 	int result;							\
1149 									\
1150 	mutex_lock(&opts->lock);					\
1151 	result = sprintf(page, "%d\n", opts->name);			\
1152 	mutex_unlock(&opts->lock);					\
1153 									\
1154 	return result;							\
1155 }									\
1156 									\
1157 static ssize_t f_midi_opts_##name##_store(struct config_item *item,	\
1158 					 const char *page, size_t len)	\
1159 {									\
1160 	struct f_midi_opts *opts = to_f_midi_opts(item);		\
1161 	int ret;							\
1162 	s32 num;							\
1163 									\
1164 	mutex_lock(&opts->lock);					\
1165 	if (opts->refcnt > 1) {						\
1166 		ret = -EBUSY;						\
1167 		goto end;						\
1168 	}								\
1169 									\
1170 	ret = kstrtos32(page, 0, &num);					\
1171 	if (ret)							\
1172 		goto end;						\
1173 									\
1174 	if (test_limit && num > limit) {				\
1175 		ret = -EINVAL;						\
1176 		goto end;						\
1177 	}								\
1178 	opts->name = num;						\
1179 	ret = len;							\
1180 									\
1181 end:									\
1182 	mutex_unlock(&opts->lock);					\
1183 	return ret;							\
1184 }									\
1185 									\
1186 CONFIGFS_ATTR(f_midi_opts_, name);
1187 
1188 #define F_MIDI_OPT_STRING(name)						\
1189 static ssize_t f_midi_opts_##name##_show(struct config_item *item, char *page) \
1190 {									\
1191 	struct f_midi_opts *opts = to_f_midi_opts(item);		\
1192 	ssize_t result;							\
1193 									\
1194 	mutex_lock(&opts->lock);					\
1195 	if (opts->name) {						\
1196 		result = strscpy(page, opts->name, PAGE_SIZE);		\
1197 	} else {							\
1198 		page[0] = 0;						\
1199 		result = 0;						\
1200 	}								\
1201 									\
1202 	mutex_unlock(&opts->lock);					\
1203 									\
1204 	return result;							\
1205 }									\
1206 									\
1207 static ssize_t f_midi_opts_##name##_store(struct config_item *item,	\
1208 					 const char *page, size_t len)	\
1209 {									\
1210 	struct f_midi_opts *opts = to_f_midi_opts(item);		\
1211 	int ret;							\
1212 	char *c;							\
1213 									\
1214 	mutex_lock(&opts->lock);					\
1215 	if (opts->refcnt > 1) {						\
1216 		ret = -EBUSY;						\
1217 		goto end;						\
1218 	}								\
1219 									\
1220 	c = kstrndup(page, len, GFP_KERNEL);				\
1221 	if (!c) {							\
1222 		ret = -ENOMEM;						\
1223 		goto end;						\
1224 	}								\
1225 	kfree(opts->name);						\
1226 	opts->name = c;							\
1227 	ret = len;							\
1228 end:									\
1229 	mutex_unlock(&opts->lock);					\
1230 	return ret;							\
1231 }									\
1232 									\
1233 CONFIGFS_ATTR(f_midi_opts_, name)
1234 
1235 F_MIDI_OPT_SIGNED(index, true, SNDRV_CARDS);
1236 F_MIDI_OPT(buflen, false, 0);
1237 F_MIDI_OPT(qlen, false, 0);
1238 F_MIDI_OPT(in_ports, true, MAX_PORTS);
1239 F_MIDI_OPT(out_ports, true, MAX_PORTS);
1240 F_MIDI_OPT_STRING(id);
1241 F_MIDI_OPT_STRING(interface_string);
1242 
1243 static struct configfs_attribute *midi_attrs[] = {
1244 	&f_midi_opts_attr_index,
1245 	&f_midi_opts_attr_buflen,
1246 	&f_midi_opts_attr_qlen,
1247 	&f_midi_opts_attr_in_ports,
1248 	&f_midi_opts_attr_out_ports,
1249 	&f_midi_opts_attr_id,
1250 	&f_midi_opts_attr_interface_string,
1251 	NULL,
1252 };
1253 
1254 static const struct config_item_type midi_func_type = {
1255 	.ct_item_ops	= &midi_item_ops,
1256 	.ct_attrs	= midi_attrs,
1257 	.ct_owner	= THIS_MODULE,
1258 };
1259 
1260 static void f_midi_free_inst(struct usb_function_instance *f)
1261 {
1262 	struct f_midi_opts *opts;
1263 	bool free = false;
1264 
1265 	opts = container_of(f, struct f_midi_opts, func_inst);
1266 
1267 	mutex_lock(&opts->lock);
1268 	if (!--opts->refcnt) {
1269 		free = true;
1270 	}
1271 	mutex_unlock(&opts->lock);
1272 
1273 	if (free) {
1274 		kfree(opts->id);
1275 		kfree(opts->interface_string);
1276 		kfree(opts);
1277 	}
1278 }
1279 
1280 static struct usb_function_instance *f_midi_alloc_inst(void)
1281 {
1282 	struct f_midi_opts *opts;
1283 
1284 	opts = kzalloc_obj(*opts);
1285 	if (!opts)
1286 		return ERR_PTR(-ENOMEM);
1287 
1288 	mutex_init(&opts->lock);
1289 	opts->func_inst.free_func_inst = f_midi_free_inst;
1290 	opts->index = SNDRV_DEFAULT_IDX1;
1291 	opts->id = NULL;
1292 	opts->interface_string = NULL;
1293 	opts->buflen = 512;
1294 	opts->qlen = 32;
1295 	opts->in_ports = 1;
1296 	opts->out_ports = 1;
1297 	opts->refcnt = 1;
1298 
1299 	config_group_init_type_name(&opts->func_inst.group, "",
1300 				    &midi_func_type);
1301 
1302 	return &opts->func_inst;
1303 }
1304 
1305 static void f_midi_free(struct usb_function *f)
1306 {
1307 	struct f_midi *midi;
1308 	struct f_midi_opts *opts;
1309 	bool free = false;
1310 
1311 	midi = func_to_midi(f);
1312 	opts = container_of(f->fi, struct f_midi_opts, func_inst);
1313 	mutex_lock(&opts->lock);
1314 	if (!--midi->free_ref) {
1315 		cancel_work_sync(&midi->work);
1316 		kfree(midi->id);
1317 		kfifo_free(&midi->in_req_fifo);
1318 		kfree(midi);
1319 		free = true;
1320 	}
1321 	mutex_unlock(&opts->lock);
1322 
1323 	if (free)
1324 		f_midi_free_inst(&opts->func_inst);
1325 }
1326 
1327 static void f_midi_rmidi_free(struct snd_rawmidi *rmidi)
1328 {
1329 	f_midi_free(rmidi->private_data);
1330 }
1331 
1332 static void f_midi_unbind(struct usb_configuration *c, struct usb_function *f)
1333 {
1334 	struct usb_composite_dev *cdev = f->config->cdev;
1335 	struct f_midi *midi = func_to_midi(f);
1336 	struct snd_card *card;
1337 
1338 	DBG(cdev, "unbind\n");
1339 
1340 	/* just to be sure */
1341 	f_midi_disable(f);
1342 
1343 	card = midi->card;
1344 	midi->card = NULL;
1345 	if (card)
1346 		snd_card_free_when_closed(card);
1347 
1348 	usb_free_all_descriptors(f);
1349 }
1350 
1351 static struct usb_function *f_midi_alloc(struct usb_function_instance *fi)
1352 {
1353 	struct f_midi *midi = NULL;
1354 	struct f_midi_opts *opts;
1355 	int status, i;
1356 
1357 	opts = container_of(fi, struct f_midi_opts, func_inst);
1358 
1359 	mutex_lock(&opts->lock);
1360 	/* sanity check */
1361 	if (opts->in_ports > MAX_PORTS || opts->out_ports > MAX_PORTS) {
1362 		status = -EINVAL;
1363 		goto setup_fail;
1364 	}
1365 
1366 	/* allocate and initialize one new instance */
1367 	midi = kzalloc_flex(*midi, in_ports_array, opts->in_ports);
1368 	if (!midi) {
1369 		status = -ENOMEM;
1370 		goto setup_fail;
1371 	}
1372 	midi->in_ports = opts->in_ports;
1373 
1374 	for (i = 0; i < opts->in_ports; i++)
1375 		midi->in_ports_array[i].cable = i;
1376 
1377 	/* set up ALSA midi devices */
1378 	midi->id = kstrdup(opts->id, GFP_KERNEL);
1379 	if (opts->id && !midi->id) {
1380 		status = -ENOMEM;
1381 		goto midi_free;
1382 	}
1383 	INIT_WORK(&midi->work, f_midi_in_work);
1384 	midi->out_ports = opts->out_ports;
1385 	midi->index = opts->index;
1386 	midi->buflen = opts->buflen;
1387 	midi->qlen = opts->qlen;
1388 	midi->in_last_port = 0;
1389 	midi->free_ref = 1;
1390 
1391 	status = kfifo_alloc(&midi->in_req_fifo, midi->qlen, GFP_KERNEL);
1392 	if (status)
1393 		goto midi_free;
1394 
1395 	spin_lock_init(&midi->transmit_lock);
1396 
1397 	++opts->refcnt;
1398 	mutex_unlock(&opts->lock);
1399 
1400 	midi->func.name		= "gmidi function";
1401 	midi->func.bind		= f_midi_bind;
1402 	midi->func.unbind	= f_midi_unbind;
1403 	midi->func.set_alt	= f_midi_set_alt;
1404 	midi->func.disable	= f_midi_disable;
1405 	midi->func.free_func	= f_midi_free;
1406 
1407 	return &midi->func;
1408 
1409 midi_free:
1410 	if (midi)
1411 		kfree(midi->id);
1412 	kfree(midi);
1413 setup_fail:
1414 	mutex_unlock(&opts->lock);
1415 
1416 	return ERR_PTR(status);
1417 }
1418 
1419 DECLARE_USB_FUNCTION_INIT(midi, f_midi_alloc_inst, f_midi_alloc);
1420