xref: /linux/sound/usb/midi.c (revision 089843177f35de2d020be6aa35c00a843873a538)
1 /*
2  * usbmidi.c - ALSA USB MIDI driver
3  *
4  * Copyright (c) 2002-2009 Clemens Ladisch
5  * All rights reserved.
6  *
7  * Based on the OSS usb-midi driver by NAGANO Daisuke,
8  *          NetBSD's umidi driver by Takuya SHIOZAKI,
9  *          the "USB Device Class Definition for MIDI Devices" by Roland
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions, and the following disclaimer,
16  *    without modification.
17  * 2. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * Alternatively, this software may be distributed and/or modified under the
21  * terms of the GNU General Public License as published by the Free Software
22  * Foundation; either version 2 of the License, or (at your option) any later
23  * version.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
29  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #include <linux/kernel.h>
39 #include <linux/types.h>
40 #include <linux/bitops.h>
41 #include <linux/interrupt.h>
42 #include <linux/spinlock.h>
43 #include <linux/string.h>
44 #include <linux/init.h>
45 #include <linux/slab.h>
46 #include <linux/timer.h>
47 #include <linux/usb.h>
48 #include <linux/wait.h>
49 #include <linux/usb/audio.h>
50 #include <linux/usb/midi.h>
51 #include <linux/module.h>
52 
53 #include <sound/core.h>
54 #include <sound/control.h>
55 #include <sound/rawmidi.h>
56 #include <sound/asequencer.h>
57 #include "usbaudio.h"
58 #include "midi.h"
59 #include "power.h"
60 #include "helper.h"
61 
62 /*
63  * define this to log all USB packets
64  */
65 /* #define DUMP_PACKETS */
66 
67 /*
68  * how long to wait after some USB errors, so that hub_wq can disconnect() us
69  * without too many spurious errors
70  */
71 #define ERROR_DELAY_JIFFIES (HZ / 10)
72 
73 #define OUTPUT_URBS 7
74 #define INPUT_URBS 7
75 
76 
77 MODULE_AUTHOR("Clemens Ladisch <clemens@ladisch.de>");
78 MODULE_DESCRIPTION("USB Audio/MIDI helper module");
79 MODULE_LICENSE("Dual BSD/GPL");
80 
81 struct snd_usb_midi_in_endpoint;
82 struct snd_usb_midi_out_endpoint;
83 struct snd_usb_midi_endpoint;
84 
85 struct usb_protocol_ops {
86 	void (*input)(struct snd_usb_midi_in_endpoint*, uint8_t*, int);
87 	void (*output)(struct snd_usb_midi_out_endpoint *ep, struct urb *urb);
88 	void (*output_packet)(struct urb*, uint8_t, uint8_t, uint8_t, uint8_t);
89 	void (*init_out_endpoint)(struct snd_usb_midi_out_endpoint *);
90 	void (*finish_out_endpoint)(struct snd_usb_midi_out_endpoint *);
91 };
92 
93 struct snd_usb_midi {
94 	struct usb_device *dev;
95 	struct snd_card *card;
96 	struct usb_interface *iface;
97 	const struct snd_usb_audio_quirk *quirk;
98 	struct snd_rawmidi *rmidi;
99 	const struct usb_protocol_ops *usb_protocol_ops;
100 	struct list_head list;
101 	struct timer_list error_timer;
102 	spinlock_t disc_lock;
103 	struct rw_semaphore disc_rwsem;
104 	struct mutex mutex;
105 	u32 usb_id;
106 	int next_midi_device;
107 
108 	struct snd_usb_midi_endpoint {
109 		struct snd_usb_midi_out_endpoint *out;
110 		struct snd_usb_midi_in_endpoint *in;
111 	} endpoints[MIDI_MAX_ENDPOINTS];
112 	unsigned long input_triggered;
113 	unsigned int opened[2];
114 	unsigned char disconnected;
115 	unsigned char input_running;
116 
117 	struct snd_kcontrol *roland_load_ctl;
118 };
119 
120 struct snd_usb_midi_out_endpoint {
121 	struct snd_usb_midi *umidi;
122 	struct out_urb_context {
123 		struct urb *urb;
124 		struct snd_usb_midi_out_endpoint *ep;
125 	} urbs[OUTPUT_URBS];
126 	unsigned int active_urbs;
127 	unsigned int drain_urbs;
128 	int max_transfer;		/* size of urb buffer */
129 	struct work_struct work;
130 	unsigned int next_urb;
131 	spinlock_t buffer_lock;
132 
133 	struct usbmidi_out_port {
134 		struct snd_usb_midi_out_endpoint *ep;
135 		struct snd_rawmidi_substream *substream;
136 		int active;
137 		uint8_t cable;		/* cable number << 4 */
138 		uint8_t state;
139 #define STATE_UNKNOWN	0
140 #define STATE_1PARAM	1
141 #define STATE_2PARAM_1	2
142 #define STATE_2PARAM_2	3
143 #define STATE_SYSEX_0	4
144 #define STATE_SYSEX_1	5
145 #define STATE_SYSEX_2	6
146 		uint8_t data[2];
147 	} ports[0x10];
148 	int current_port;
149 
150 	wait_queue_head_t drain_wait;
151 };
152 
153 struct snd_usb_midi_in_endpoint {
154 	struct snd_usb_midi *umidi;
155 	struct urb *urbs[INPUT_URBS];
156 	struct usbmidi_in_port {
157 		struct snd_rawmidi_substream *substream;
158 		u8 running_status_length;
159 	} ports[0x10];
160 	u8 seen_f5;
161 	bool in_sysex;
162 	u8 last_cin;
163 	u8 error_resubmit;
164 	int current_port;
165 };
166 
167 static void snd_usbmidi_do_output(struct snd_usb_midi_out_endpoint *ep);
168 
169 static const uint8_t snd_usbmidi_cin_length[] = {
170 	0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
171 };
172 
173 /*
174  * Submits the URB, with error handling.
175  */
176 static int snd_usbmidi_submit_urb(struct urb *urb, gfp_t flags)
177 {
178 	int err = usb_submit_urb(urb, flags);
179 	if (err < 0 && err != -ENODEV)
180 		dev_err(&urb->dev->dev, "usb_submit_urb: %d\n", err);
181 	return err;
182 }
183 
184 /*
185  * Error handling for URB completion functions.
186  */
187 static int snd_usbmidi_urb_error(const struct urb *urb)
188 {
189 	switch (urb->status) {
190 	/* manually unlinked, or device gone */
191 	case -ENOENT:
192 	case -ECONNRESET:
193 	case -ESHUTDOWN:
194 	case -ENODEV:
195 		return -ENODEV;
196 	/* errors that might occur during unplugging */
197 	case -EPROTO:
198 	case -ETIME:
199 	case -EILSEQ:
200 		return -EIO;
201 	default:
202 		dev_err(&urb->dev->dev, "urb status %d\n", urb->status);
203 		return 0; /* continue */
204 	}
205 }
206 
207 /*
208  * Receives a chunk of MIDI data.
209  */
210 static void snd_usbmidi_input_data(struct snd_usb_midi_in_endpoint *ep,
211 				   int portidx, uint8_t *data, int length)
212 {
213 	struct usbmidi_in_port *port = &ep->ports[portidx];
214 
215 	if (!port->substream) {
216 		dev_dbg(&ep->umidi->dev->dev, "unexpected port %d!\n", portidx);
217 		return;
218 	}
219 	if (!test_bit(port->substream->number, &ep->umidi->input_triggered))
220 		return;
221 	snd_rawmidi_receive(port->substream, data, length);
222 }
223 
224 #ifdef DUMP_PACKETS
225 static void dump_urb(const char *type, const u8 *data, int length)
226 {
227 	pr_debug("%s packet: [", type);
228 	for (; length > 0; ++data, --length)
229 		pr_cont(" %02x", *data);
230 	pr_cont(" ]\n");
231 }
232 #else
233 #define dump_urb(type, data, length) /* nothing */
234 #endif
235 
236 /*
237  * Processes the data read from the device.
238  */
239 static void snd_usbmidi_in_urb_complete(struct urb *urb)
240 {
241 	struct snd_usb_midi_in_endpoint *ep = urb->context;
242 
243 	if (urb->status == 0) {
244 		dump_urb("received", urb->transfer_buffer, urb->actual_length);
245 		ep->umidi->usb_protocol_ops->input(ep, urb->transfer_buffer,
246 						   urb->actual_length);
247 	} else {
248 		int err = snd_usbmidi_urb_error(urb);
249 		if (err < 0) {
250 			if (err != -ENODEV) {
251 				ep->error_resubmit = 1;
252 				mod_timer(&ep->umidi->error_timer,
253 					  jiffies + ERROR_DELAY_JIFFIES);
254 			}
255 			return;
256 		}
257 	}
258 
259 	urb->dev = ep->umidi->dev;
260 	snd_usbmidi_submit_urb(urb, GFP_ATOMIC);
261 }
262 
263 static void snd_usbmidi_out_urb_complete(struct urb *urb)
264 {
265 	struct out_urb_context *context = urb->context;
266 	struct snd_usb_midi_out_endpoint *ep = context->ep;
267 	unsigned int urb_index;
268 
269 	scoped_guard(spinlock_irqsave, &ep->buffer_lock) {
270 		urb_index = context - ep->urbs;
271 		ep->active_urbs &= ~(1 << urb_index);
272 		if (unlikely(ep->drain_urbs)) {
273 			ep->drain_urbs &= ~(1 << urb_index);
274 			wake_up(&ep->drain_wait);
275 		}
276 	}
277 	if (urb->status < 0) {
278 		int err = snd_usbmidi_urb_error(urb);
279 		if (err < 0) {
280 			if (err != -ENODEV)
281 				mod_timer(&ep->umidi->error_timer,
282 					  jiffies + ERROR_DELAY_JIFFIES);
283 			return;
284 		}
285 	}
286 	snd_usbmidi_do_output(ep);
287 }
288 
289 /*
290  * This is called when some data should be transferred to the device
291  * (from one or more substreams).
292  */
293 static void snd_usbmidi_do_output(struct snd_usb_midi_out_endpoint *ep)
294 {
295 	unsigned int urb_index;
296 	struct urb *urb;
297 
298 	guard(spinlock_irqsave)(&ep->buffer_lock);
299 	if (ep->umidi->disconnected)
300 		return;
301 
302 	urb_index = ep->next_urb;
303 	for (;;) {
304 		if (!(ep->active_urbs & (1 << urb_index))) {
305 			urb = ep->urbs[urb_index].urb;
306 			urb->transfer_buffer_length = 0;
307 			ep->umidi->usb_protocol_ops->output(ep, urb);
308 			if (urb->transfer_buffer_length == 0)
309 				break;
310 
311 			dump_urb("sending", urb->transfer_buffer,
312 				 urb->transfer_buffer_length);
313 			urb->dev = ep->umidi->dev;
314 			if (snd_usbmidi_submit_urb(urb, GFP_ATOMIC) < 0)
315 				break;
316 			ep->active_urbs |= 1 << urb_index;
317 		}
318 		if (++urb_index >= OUTPUT_URBS)
319 			urb_index = 0;
320 		if (urb_index == ep->next_urb)
321 			break;
322 	}
323 	ep->next_urb = urb_index;
324 }
325 
326 static void snd_usbmidi_out_work(struct work_struct *work)
327 {
328 	struct snd_usb_midi_out_endpoint *ep =
329 		container_of(work, struct snd_usb_midi_out_endpoint, work);
330 
331 	snd_usbmidi_do_output(ep);
332 }
333 
334 /* called after transfers had been interrupted due to some USB error */
335 static void snd_usbmidi_error_timer(struct timer_list *t)
336 {
337 	struct snd_usb_midi *umidi = timer_container_of(umidi, t, error_timer);
338 	unsigned int i, j;
339 
340 	guard(spinlock)(&umidi->disc_lock);
341 	if (umidi->disconnected) {
342 		return;
343 	}
344 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
345 		struct snd_usb_midi_in_endpoint *in = umidi->endpoints[i].in;
346 		if (in && in->error_resubmit) {
347 			in->error_resubmit = 0;
348 			for (j = 0; j < INPUT_URBS; ++j) {
349 				if (atomic_read(&in->urbs[j]->use_count))
350 					continue;
351 				in->urbs[j]->dev = umidi->dev;
352 				snd_usbmidi_submit_urb(in->urbs[j], GFP_ATOMIC);
353 			}
354 		}
355 		if (umidi->endpoints[i].out)
356 			snd_usbmidi_do_output(umidi->endpoints[i].out);
357 	}
358 }
359 
360 /* helper function to send static data that may not DMA-able */
361 static int send_bulk_static_data(struct snd_usb_midi_out_endpoint *ep,
362 				 const void *data, int len)
363 {
364 	int err = 0;
365 	void *buf = kmemdup(data, len, GFP_KERNEL);
366 	if (!buf)
367 		return -ENOMEM;
368 	dump_urb("sending", buf, len);
369 	if (ep->urbs[0].urb)
370 		err = usb_bulk_msg(ep->umidi->dev, ep->urbs[0].urb->pipe,
371 				   buf, len, NULL, 250);
372 	kfree(buf);
373 	return err;
374 }
375 
376 /*
377  * Standard USB MIDI protocol: see the spec.
378  * Midiman protocol: like the standard protocol, but the control byte is the
379  * fourth byte in each packet, and uses length instead of CIN.
380  */
381 
382 static void snd_usbmidi_standard_input(struct snd_usb_midi_in_endpoint *ep,
383 				       uint8_t *buffer, int buffer_length)
384 {
385 	int i;
386 
387 	for (i = 0; i + 3 < buffer_length; i += 4)
388 		if (buffer[i] != 0) {
389 			int cable = buffer[i] >> 4;
390 			int length = snd_usbmidi_cin_length[buffer[i] & 0x0f];
391 			snd_usbmidi_input_data(ep, cable, &buffer[i + 1],
392 					       length);
393 		}
394 }
395 
396 static void snd_usbmidi_midiman_input(struct snd_usb_midi_in_endpoint *ep,
397 				      uint8_t *buffer, int buffer_length)
398 {
399 	int i;
400 
401 	for (i = 0; i + 3 < buffer_length; i += 4)
402 		if (buffer[i + 3] != 0) {
403 			int port = buffer[i + 3] >> 4;
404 			int length = buffer[i + 3] & 3;
405 			snd_usbmidi_input_data(ep, port, &buffer[i], length);
406 		}
407 }
408 
409 /*
410  * Buggy M-Audio device: running status on input results in a packet that has
411  * the data bytes but not the status byte and that is marked with CIN 4.
412  */
413 static void snd_usbmidi_maudio_broken_running_status_input(
414 					struct snd_usb_midi_in_endpoint *ep,
415 					uint8_t *buffer, int buffer_length)
416 {
417 	int i;
418 
419 	for (i = 0; i + 3 < buffer_length; i += 4)
420 		if (buffer[i] != 0) {
421 			int cable = buffer[i] >> 4;
422 			u8 cin = buffer[i] & 0x0f;
423 			struct usbmidi_in_port *port = &ep->ports[cable];
424 			int length;
425 
426 			length = snd_usbmidi_cin_length[cin];
427 			if (cin == 0xf && buffer[i + 1] >= 0xf8)
428 				; /* realtime msg: no running status change */
429 			else if (cin >= 0x8 && cin <= 0xe)
430 				/* channel msg */
431 				port->running_status_length = length - 1;
432 			else if (cin == 0x4 &&
433 				 port->running_status_length != 0 &&
434 				 buffer[i + 1] < 0x80)
435 				/* CIN 4 that is not a SysEx */
436 				length = port->running_status_length;
437 			else
438 				/*
439 				 * All other msgs cannot begin running status.
440 				 * (A channel msg sent as two or three CIN 0xF
441 				 * packets could in theory, but this device
442 				 * doesn't use this format.)
443 				 */
444 				port->running_status_length = 0;
445 			snd_usbmidi_input_data(ep, cable, &buffer[i + 1],
446 					       length);
447 		}
448 }
449 
450 /*
451  * QinHeng CH345 is buggy: every second packet inside a SysEx has not CIN 4
452  * but the previously seen CIN, but still with three data bytes.
453  */
454 static void ch345_broken_sysex_input(struct snd_usb_midi_in_endpoint *ep,
455 				     uint8_t *buffer, int buffer_length)
456 {
457 	unsigned int i, cin, length;
458 
459 	for (i = 0; i + 3 < buffer_length; i += 4) {
460 		if (buffer[i] == 0 && i > 0)
461 			break;
462 		cin = buffer[i] & 0x0f;
463 		if (ep->in_sysex &&
464 		    cin == ep->last_cin &&
465 		    (buffer[i + 1 + (cin == 0x6)] & 0x80) == 0)
466 			cin = 0x4;
467 #if 0
468 		if (buffer[i + 1] == 0x90) {
469 			/*
470 			 * Either a corrupted running status or a real note-on
471 			 * message; impossible to detect reliably.
472 			 */
473 		}
474 #endif
475 		length = snd_usbmidi_cin_length[cin];
476 		snd_usbmidi_input_data(ep, 0, &buffer[i + 1], length);
477 		ep->in_sysex = cin == 0x4;
478 		if (!ep->in_sysex)
479 			ep->last_cin = cin;
480 	}
481 }
482 
483 /*
484  * CME protocol: like the standard protocol, but SysEx commands are sent as a
485  * single USB packet preceded by a 0x0F byte, as are system realtime
486  * messages and MIDI Active Sensing.
487  * Also, multiple messages can be sent in the same packet.
488  */
489 static void snd_usbmidi_cme_input(struct snd_usb_midi_in_endpoint *ep,
490 				  uint8_t *buffer, int buffer_length)
491 {
492 	int remaining = buffer_length;
493 
494 	/*
495 	 * CME send sysex, song position pointer, system realtime
496 	 * and active sensing using CIN 0x0f, which in the standard
497 	 * is only intended for single byte unparsed data.
498 	 * So we need to interpret these here before sending them on.
499 	 * By default, we assume single byte data, which is true
500 	 * for system realtime (midi clock, start, stop and continue)
501 	 * and active sensing, and handle the other (known) cases
502 	 * separately.
503 	 * In contrast to the standard, CME does not split sysex
504 	 * into multiple 4-byte packets, but lumps everything together
505 	 * into one. In addition, CME can string multiple messages
506 	 * together in the same packet; pressing the Record button
507 	 * on an UF6 sends a sysex message directly followed
508 	 * by a song position pointer in the same packet.
509 	 * For it to have any reasonable meaning, a sysex message
510 	 * needs to be at least 3 bytes in length (0xf0, id, 0xf7),
511 	 * corresponding to a packet size of 4 bytes, and the ones sent
512 	 * by CME devices are 6 or 7 bytes, making the packet fragments
513 	 * 7 or 8 bytes long (six or seven bytes plus preceding CN+CIN byte).
514 	 * For the other types, the packet size is always 4 bytes,
515 	 * as per the standard, with the data size being 3 for SPP
516 	 * and 1 for the others.
517 	 * Thus all packet fragments are at least 4 bytes long, so we can
518 	 * skip anything that is shorter; this also conveniantly skips
519 	 * packets with size 0, which CME devices continuously send when
520 	 * they have nothing better to do.
521 	 * Another quirk is that sometimes multiple messages are sent
522 	 * in the same packet. This has been observed for midi clock
523 	 * and active sensing i.e. 0x0f 0xf8 0x00 0x00 0x0f 0xfe 0x00 0x00,
524 	 * but also multiple note ons/offs, and control change together
525 	 * with MIDI clock. Similarly, some sysex messages are followed by
526 	 * the song position pointer in the same packet, and occasionally
527 	 * additionally by a midi clock or active sensing.
528 	 * We handle this by looping over all data and parsing it along the way.
529 	 */
530 	while (remaining >= 4) {
531 		int source_length = 4; /* default */
532 
533 		if ((buffer[0] & 0x0f) == 0x0f) {
534 			int data_length = 1; /* default */
535 
536 			if (buffer[1] == 0xf0) {
537 				/* Sysex: Find EOX and send on whole message. */
538 				/* To kick off the search, skip the first
539 				 * two bytes (CN+CIN and SYSEX (0xf0).
540 				 */
541 				uint8_t *tmp_buf = buffer + 2;
542 				int tmp_length = remaining - 2;
543 
544 				while (tmp_length > 1 && *tmp_buf != 0xf7) {
545 					tmp_buf++;
546 					tmp_length--;
547 				}
548 				data_length = tmp_buf - buffer;
549 				source_length = data_length + 1;
550 			} else if (buffer[1] == 0xf2) {
551 				/* Three byte song position pointer */
552 				data_length = 3;
553 			}
554 			snd_usbmidi_input_data(ep, buffer[0] >> 4,
555 					       &buffer[1], data_length);
556 		} else {
557 			/* normal channel events */
558 			snd_usbmidi_standard_input(ep, buffer, source_length);
559 		}
560 		buffer += source_length;
561 		remaining -= source_length;
562 	}
563 }
564 
565 /*
566  * Adds one USB MIDI packet to the output buffer.
567  */
568 static void snd_usbmidi_output_standard_packet(struct urb *urb, uint8_t p0,
569 					       uint8_t p1, uint8_t p2,
570 					       uint8_t p3)
571 {
572 
573 	uint8_t *buf =
574 		(uint8_t *)urb->transfer_buffer + urb->transfer_buffer_length;
575 	buf[0] = p0;
576 	buf[1] = p1;
577 	buf[2] = p2;
578 	buf[3] = p3;
579 	urb->transfer_buffer_length += 4;
580 }
581 
582 /*
583  * Adds one Midiman packet to the output buffer.
584  */
585 static void snd_usbmidi_output_midiman_packet(struct urb *urb, uint8_t p0,
586 					      uint8_t p1, uint8_t p2,
587 					      uint8_t p3)
588 {
589 
590 	uint8_t *buf =
591 		(uint8_t *)urb->transfer_buffer + urb->transfer_buffer_length;
592 	buf[0] = p1;
593 	buf[1] = p2;
594 	buf[2] = p3;
595 	buf[3] = (p0 & 0xf0) | snd_usbmidi_cin_length[p0 & 0x0f];
596 	urb->transfer_buffer_length += 4;
597 }
598 
599 /*
600  * Converts MIDI commands to USB MIDI packets.
601  */
602 static void snd_usbmidi_transmit_byte(struct usbmidi_out_port *port,
603 				      uint8_t b, struct urb *urb)
604 {
605 	uint8_t p0 = port->cable;
606 	void (*output_packet)(struct urb*, uint8_t, uint8_t, uint8_t, uint8_t) =
607 		port->ep->umidi->usb_protocol_ops->output_packet;
608 
609 	if (b >= 0xf8) {
610 		output_packet(urb, p0 | 0x0f, b, 0, 0);
611 	} else if (b >= 0xf0) {
612 		switch (b) {
613 		case 0xf0:
614 			port->data[0] = b;
615 			port->state = STATE_SYSEX_1;
616 			break;
617 		case 0xf1:
618 		case 0xf3:
619 			port->data[0] = b;
620 			port->state = STATE_1PARAM;
621 			break;
622 		case 0xf2:
623 			port->data[0] = b;
624 			port->state = STATE_2PARAM_1;
625 			break;
626 		case 0xf4:
627 		case 0xf5:
628 			port->state = STATE_UNKNOWN;
629 			break;
630 		case 0xf6:
631 			output_packet(urb, p0 | 0x05, 0xf6, 0, 0);
632 			port->state = STATE_UNKNOWN;
633 			break;
634 		case 0xf7:
635 			switch (port->state) {
636 			case STATE_SYSEX_0:
637 				output_packet(urb, p0 | 0x05, 0xf7, 0, 0);
638 				break;
639 			case STATE_SYSEX_1:
640 				output_packet(urb, p0 | 0x06, port->data[0],
641 					      0xf7, 0);
642 				break;
643 			case STATE_SYSEX_2:
644 				output_packet(urb, p0 | 0x07, port->data[0],
645 					      port->data[1], 0xf7);
646 				break;
647 			}
648 			port->state = STATE_UNKNOWN;
649 			break;
650 		}
651 	} else if (b >= 0x80) {
652 		port->data[0] = b;
653 		if (b >= 0xc0 && b <= 0xdf)
654 			port->state = STATE_1PARAM;
655 		else
656 			port->state = STATE_2PARAM_1;
657 	} else { /* b < 0x80 */
658 		switch (port->state) {
659 		case STATE_1PARAM:
660 			if (port->data[0] < 0xf0) {
661 				p0 |= port->data[0] >> 4;
662 			} else {
663 				p0 |= 0x02;
664 				port->state = STATE_UNKNOWN;
665 			}
666 			output_packet(urb, p0, port->data[0], b, 0);
667 			break;
668 		case STATE_2PARAM_1:
669 			port->data[1] = b;
670 			port->state = STATE_2PARAM_2;
671 			break;
672 		case STATE_2PARAM_2:
673 			if (port->data[0] < 0xf0) {
674 				p0 |= port->data[0] >> 4;
675 				port->state = STATE_2PARAM_1;
676 			} else {
677 				p0 |= 0x03;
678 				port->state = STATE_UNKNOWN;
679 			}
680 			output_packet(urb, p0, port->data[0], port->data[1], b);
681 			break;
682 		case STATE_SYSEX_0:
683 			port->data[0] = b;
684 			port->state = STATE_SYSEX_1;
685 			break;
686 		case STATE_SYSEX_1:
687 			port->data[1] = b;
688 			port->state = STATE_SYSEX_2;
689 			break;
690 		case STATE_SYSEX_2:
691 			output_packet(urb, p0 | 0x04, port->data[0],
692 				      port->data[1], b);
693 			port->state = STATE_SYSEX_0;
694 			break;
695 		}
696 	}
697 }
698 
699 static void snd_usbmidi_standard_output(struct snd_usb_midi_out_endpoint *ep,
700 					struct urb *urb)
701 {
702 	int p;
703 
704 	/* FIXME: lower-numbered ports can starve higher-numbered ports */
705 	for (p = 0; p < 0x10; ++p) {
706 		struct usbmidi_out_port *port = &ep->ports[p];
707 		if (!port->active)
708 			continue;
709 		while (urb->transfer_buffer_length + 3 < ep->max_transfer) {
710 			uint8_t b;
711 			if (snd_rawmidi_transmit(port->substream, &b, 1) != 1) {
712 				port->active = 0;
713 				break;
714 			}
715 			snd_usbmidi_transmit_byte(port, b, urb);
716 		}
717 	}
718 }
719 
720 static const struct usb_protocol_ops snd_usbmidi_standard_ops = {
721 	.input = snd_usbmidi_standard_input,
722 	.output = snd_usbmidi_standard_output,
723 	.output_packet = snd_usbmidi_output_standard_packet,
724 };
725 
726 static const struct usb_protocol_ops snd_usbmidi_midiman_ops = {
727 	.input = snd_usbmidi_midiman_input,
728 	.output = snd_usbmidi_standard_output,
729 	.output_packet = snd_usbmidi_output_midiman_packet,
730 };
731 
732 static const
733 struct usb_protocol_ops snd_usbmidi_maudio_broken_running_status_ops = {
734 	.input = snd_usbmidi_maudio_broken_running_status_input,
735 	.output = snd_usbmidi_standard_output,
736 	.output_packet = snd_usbmidi_output_standard_packet,
737 };
738 
739 static const struct usb_protocol_ops snd_usbmidi_cme_ops = {
740 	.input = snd_usbmidi_cme_input,
741 	.output = snd_usbmidi_standard_output,
742 	.output_packet = snd_usbmidi_output_standard_packet,
743 };
744 
745 static const struct usb_protocol_ops snd_usbmidi_ch345_broken_sysex_ops = {
746 	.input = ch345_broken_sysex_input,
747 	.output = snd_usbmidi_standard_output,
748 	.output_packet = snd_usbmidi_output_standard_packet,
749 };
750 
751 /*
752  * AKAI MPD16 protocol:
753  *
754  * For control port (endpoint 1):
755  * ==============================
756  * One or more chunks consisting of first byte of (0x10 | msg_len) and then a
757  * SysEx message (msg_len=9 bytes long).
758  *
759  * For data port (endpoint 2):
760  * ===========================
761  * One or more chunks consisting of first byte of (0x20 | msg_len) and then a
762  * MIDI message (msg_len bytes long)
763  *
764  * Messages sent: Active Sense, Note On, Poly Pressure, Control Change.
765  */
766 static void snd_usbmidi_akai_input(struct snd_usb_midi_in_endpoint *ep,
767 				   uint8_t *buffer, int buffer_length)
768 {
769 	unsigned int pos = 0;
770 	unsigned int len = (unsigned int)buffer_length;
771 	while (pos < len) {
772 		unsigned int port = (buffer[pos] >> 4) - 1;
773 		unsigned int msg_len = buffer[pos] & 0x0f;
774 		pos++;
775 		if (pos + msg_len <= len && port < 2)
776 			snd_usbmidi_input_data(ep, 0, &buffer[pos], msg_len);
777 		pos += msg_len;
778 	}
779 }
780 
781 #define MAX_AKAI_SYSEX_LEN 9
782 
783 static void snd_usbmidi_akai_output(struct snd_usb_midi_out_endpoint *ep,
784 				    struct urb *urb)
785 {
786 	uint8_t *msg;
787 	int pos, end, count, buf_end;
788 	uint8_t tmp[MAX_AKAI_SYSEX_LEN];
789 	struct snd_rawmidi_substream *substream = ep->ports[0].substream;
790 
791 	if (!ep->ports[0].active)
792 		return;
793 
794 	msg = urb->transfer_buffer + urb->transfer_buffer_length;
795 	buf_end = ep->max_transfer - MAX_AKAI_SYSEX_LEN - 1;
796 
797 	/* only try adding more data when there's space for at least 1 SysEx */
798 	while (urb->transfer_buffer_length < buf_end) {
799 		count = snd_rawmidi_transmit_peek(substream,
800 						  tmp, MAX_AKAI_SYSEX_LEN);
801 		if (!count) {
802 			ep->ports[0].active = 0;
803 			return;
804 		}
805 		/* try to skip non-SysEx data */
806 		for (pos = 0; pos < count && tmp[pos] != 0xF0; pos++)
807 			;
808 
809 		if (pos > 0) {
810 			snd_rawmidi_transmit_ack(substream, pos);
811 			continue;
812 		}
813 
814 		/* look for the start or end marker */
815 		for (end = 1; end < count && tmp[end] < 0xF0; end++)
816 			;
817 
818 		/* next SysEx started before the end of current one */
819 		if (end < count && tmp[end] == 0xF0) {
820 			/* it's incomplete - drop it */
821 			snd_rawmidi_transmit_ack(substream, end);
822 			continue;
823 		}
824 		/* SysEx complete */
825 		if (end < count && tmp[end] == 0xF7) {
826 			/* queue it, ack it, and get the next one */
827 			count = end + 1;
828 			msg[0] = 0x10 | count;
829 			memcpy(&msg[1], tmp, count);
830 			snd_rawmidi_transmit_ack(substream, count);
831 			urb->transfer_buffer_length += count + 1;
832 			msg += count + 1;
833 			continue;
834 		}
835 		/* less than 9 bytes and no end byte - wait for more */
836 		if (count < MAX_AKAI_SYSEX_LEN) {
837 			ep->ports[0].active = 0;
838 			return;
839 		}
840 		/* 9 bytes and no end marker in sight - malformed, skip it */
841 		snd_rawmidi_transmit_ack(substream, count);
842 	}
843 }
844 
845 static const struct usb_protocol_ops snd_usbmidi_akai_ops = {
846 	.input = snd_usbmidi_akai_input,
847 	.output = snd_usbmidi_akai_output,
848 };
849 
850 /*
851  * Novation USB MIDI protocol: number of data bytes is in the first byte
852  * (when receiving) (+1!) or in the second byte (when sending); data begins
853  * at the third byte.
854  */
855 
856 static void snd_usbmidi_novation_input(struct snd_usb_midi_in_endpoint *ep,
857 				       uint8_t *buffer, int buffer_length)
858 {
859 	if (buffer_length < 2 || !buffer[0] || buffer_length < buffer[0] + 1)
860 		return;
861 	snd_usbmidi_input_data(ep, 0, &buffer[2], buffer[0] - 1);
862 }
863 
864 static void snd_usbmidi_novation_output(struct snd_usb_midi_out_endpoint *ep,
865 					struct urb *urb)
866 {
867 	uint8_t *transfer_buffer;
868 	int count;
869 
870 	if (!ep->ports[0].active)
871 		return;
872 	transfer_buffer = urb->transfer_buffer;
873 	count = snd_rawmidi_transmit(ep->ports[0].substream,
874 				     &transfer_buffer[2],
875 				     ep->max_transfer - 2);
876 	if (count < 1) {
877 		ep->ports[0].active = 0;
878 		return;
879 	}
880 	transfer_buffer[0] = 0;
881 	transfer_buffer[1] = count;
882 	urb->transfer_buffer_length = 2 + count;
883 }
884 
885 static const struct usb_protocol_ops snd_usbmidi_novation_ops = {
886 	.input = snd_usbmidi_novation_input,
887 	.output = snd_usbmidi_novation_output,
888 };
889 
890 /*
891  * "raw" protocol: just move raw MIDI bytes from/to the endpoint
892  */
893 
894 static void snd_usbmidi_raw_input(struct snd_usb_midi_in_endpoint *ep,
895 				  uint8_t *buffer, int buffer_length)
896 {
897 	snd_usbmidi_input_data(ep, 0, buffer, buffer_length);
898 }
899 
900 static void snd_usbmidi_raw_output(struct snd_usb_midi_out_endpoint *ep,
901 				   struct urb *urb)
902 {
903 	int count;
904 
905 	if (!ep->ports[0].active)
906 		return;
907 	count = snd_rawmidi_transmit(ep->ports[0].substream,
908 				     urb->transfer_buffer,
909 				     ep->max_transfer);
910 	if (count < 1) {
911 		ep->ports[0].active = 0;
912 		return;
913 	}
914 	urb->transfer_buffer_length = count;
915 }
916 
917 static const struct usb_protocol_ops snd_usbmidi_raw_ops = {
918 	.input = snd_usbmidi_raw_input,
919 	.output = snd_usbmidi_raw_output,
920 };
921 
922 /*
923  * FTDI protocol: raw MIDI bytes, but input packets have two modem status bytes.
924  */
925 
926 static void snd_usbmidi_ftdi_input(struct snd_usb_midi_in_endpoint *ep,
927 				   uint8_t *buffer, int buffer_length)
928 {
929 	if (buffer_length > 2)
930 		snd_usbmidi_input_data(ep, 0, buffer + 2, buffer_length - 2);
931 }
932 
933 static const struct usb_protocol_ops snd_usbmidi_ftdi_ops = {
934 	.input = snd_usbmidi_ftdi_input,
935 	.output = snd_usbmidi_raw_output,
936 };
937 
938 static void snd_usbmidi_us122l_input(struct snd_usb_midi_in_endpoint *ep,
939 				     uint8_t *buffer, int buffer_length)
940 {
941 	if (buffer_length != 9)
942 		return;
943 	buffer_length = 8;
944 	while (buffer_length && buffer[buffer_length - 1] == 0xFD)
945 		buffer_length--;
946 	if (buffer_length)
947 		snd_usbmidi_input_data(ep, 0, buffer, buffer_length);
948 }
949 
950 static void snd_usbmidi_us122l_output(struct snd_usb_midi_out_endpoint *ep,
951 				      struct urb *urb)
952 {
953 	int count;
954 
955 	if (!ep->ports[0].active)
956 		return;
957 	switch (snd_usb_get_speed(ep->umidi->dev)) {
958 	case USB_SPEED_HIGH:
959 	case USB_SPEED_SUPER:
960 	case USB_SPEED_SUPER_PLUS:
961 		count = 1;
962 		break;
963 	default:
964 		count = 2;
965 	}
966 	count = snd_rawmidi_transmit(ep->ports[0].substream,
967 				     urb->transfer_buffer,
968 				     count);
969 	if (count < 1) {
970 		ep->ports[0].active = 0;
971 		return;
972 	}
973 
974 	memset(urb->transfer_buffer + count, 0xFD, ep->max_transfer - count);
975 	urb->transfer_buffer_length = ep->max_transfer;
976 }
977 
978 static const struct usb_protocol_ops snd_usbmidi_122l_ops = {
979 	.input = snd_usbmidi_us122l_input,
980 	.output = snd_usbmidi_us122l_output,
981 };
982 
983 /*
984  * Emagic USB MIDI protocol: raw MIDI with "F5 xx" port switching.
985  */
986 
987 static void snd_usbmidi_emagic_init_out(struct snd_usb_midi_out_endpoint *ep)
988 {
989 	static const u8 init_data[] = {
990 		/* initialization magic: "get version" */
991 		0xf0,
992 		0x00, 0x20, 0x31,	/* Emagic */
993 		0x64,			/* Unitor8 */
994 		0x0b,			/* version number request */
995 		0x00,			/* command version */
996 		0x00,			/* EEPROM, box 0 */
997 		0xf7
998 	};
999 	send_bulk_static_data(ep, init_data, sizeof(init_data));
1000 	/* while we're at it, pour on more magic */
1001 	send_bulk_static_data(ep, init_data, sizeof(init_data));
1002 }
1003 
1004 static void snd_usbmidi_emagic_finish_out(struct snd_usb_midi_out_endpoint *ep)
1005 {
1006 	static const u8 finish_data[] = {
1007 		/* switch to patch mode with last preset */
1008 		0xf0,
1009 		0x00, 0x20, 0x31,	/* Emagic */
1010 		0x64,			/* Unitor8 */
1011 		0x10,			/* patch switch command */
1012 		0x00,			/* command version */
1013 		0x7f,			/* to all boxes */
1014 		0x40,			/* last preset in EEPROM */
1015 		0xf7
1016 	};
1017 	send_bulk_static_data(ep, finish_data, sizeof(finish_data));
1018 }
1019 
1020 static void snd_usbmidi_emagic_input(struct snd_usb_midi_in_endpoint *ep,
1021 				     uint8_t *buffer, int buffer_length)
1022 {
1023 	int i;
1024 
1025 	/* FF indicates end of valid data */
1026 	for (i = 0; i < buffer_length; ++i)
1027 		if (buffer[i] == 0xff) {
1028 			buffer_length = i;
1029 			break;
1030 		}
1031 
1032 	/* handle F5 at end of last buffer */
1033 	if (ep->seen_f5)
1034 		goto switch_port;
1035 
1036 	while (buffer_length > 0) {
1037 		/* determine size of data until next F5 */
1038 		for (i = 0; i < buffer_length; ++i)
1039 			if (buffer[i] == 0xf5)
1040 				break;
1041 		snd_usbmidi_input_data(ep, ep->current_port, buffer, i);
1042 		buffer += i;
1043 		buffer_length -= i;
1044 
1045 		if (buffer_length <= 0)
1046 			break;
1047 		/* assert(buffer[0] == 0xf5); */
1048 		ep->seen_f5 = 1;
1049 		++buffer;
1050 		--buffer_length;
1051 
1052 	switch_port:
1053 		if (buffer_length <= 0)
1054 			break;
1055 		if (buffer[0] < 0x80) {
1056 			ep->current_port = (buffer[0] - 1) & 15;
1057 			++buffer;
1058 			--buffer_length;
1059 		}
1060 		ep->seen_f5 = 0;
1061 	}
1062 }
1063 
1064 static void snd_usbmidi_emagic_output(struct snd_usb_midi_out_endpoint *ep,
1065 				      struct urb *urb)
1066 {
1067 	int port0 = ep->current_port;
1068 	uint8_t *buf = urb->transfer_buffer;
1069 	int buf_free = ep->max_transfer;
1070 	int length, i;
1071 
1072 	for (i = 0; i < 0x10; ++i) {
1073 		/* round-robin, starting at the last current port */
1074 		int portnum = (port0 + i) & 15;
1075 		struct usbmidi_out_port *port = &ep->ports[portnum];
1076 
1077 		if (!port->active)
1078 			continue;
1079 		if (snd_rawmidi_transmit_peek(port->substream, buf, 1) != 1) {
1080 			port->active = 0;
1081 			continue;
1082 		}
1083 
1084 		if (portnum != ep->current_port) {
1085 			if (buf_free < 2)
1086 				break;
1087 			ep->current_port = portnum;
1088 			buf[0] = 0xf5;
1089 			buf[1] = (portnum + 1) & 15;
1090 			buf += 2;
1091 			buf_free -= 2;
1092 		}
1093 
1094 		if (buf_free < 1)
1095 			break;
1096 		length = snd_rawmidi_transmit(port->substream, buf, buf_free);
1097 		if (length > 0) {
1098 			buf += length;
1099 			buf_free -= length;
1100 			if (buf_free < 1)
1101 				break;
1102 		}
1103 	}
1104 	if (buf_free < ep->max_transfer && buf_free > 0) {
1105 		*buf = 0xff;
1106 		--buf_free;
1107 	}
1108 	urb->transfer_buffer_length = ep->max_transfer - buf_free;
1109 }
1110 
1111 static const struct usb_protocol_ops snd_usbmidi_emagic_ops = {
1112 	.input = snd_usbmidi_emagic_input,
1113 	.output = snd_usbmidi_emagic_output,
1114 	.init_out_endpoint = snd_usbmidi_emagic_init_out,
1115 	.finish_out_endpoint = snd_usbmidi_emagic_finish_out,
1116 };
1117 
1118 
1119 static void update_roland_altsetting(struct snd_usb_midi *umidi)
1120 {
1121 	struct usb_interface *intf;
1122 	struct usb_host_interface *hostif;
1123 	struct usb_interface_descriptor *intfd;
1124 	int is_light_load;
1125 
1126 	intf = umidi->iface;
1127 	is_light_load = intf->cur_altsetting != intf->altsetting;
1128 	if (umidi->roland_load_ctl->private_value == is_light_load)
1129 		return;
1130 	hostif = &intf->altsetting[umidi->roland_load_ctl->private_value];
1131 	intfd = get_iface_desc(hostif);
1132 	snd_usbmidi_input_stop(&umidi->list);
1133 	usb_set_interface(umidi->dev, intfd->bInterfaceNumber,
1134 			  intfd->bAlternateSetting);
1135 	snd_usbmidi_input_start(&umidi->list);
1136 }
1137 
1138 static int substream_open(struct snd_rawmidi_substream *substream, int dir,
1139 			  int open)
1140 {
1141 	struct snd_usb_midi *umidi = substream->rmidi->private_data;
1142 	struct snd_kcontrol *ctl;
1143 
1144 	guard(rwsem_read)(&umidi->disc_rwsem);
1145 	if (umidi->disconnected)
1146 		return open ? -ENODEV : 0;
1147 
1148 	guard(mutex)(&umidi->mutex);
1149 	if (open) {
1150 		if (!umidi->opened[0] && !umidi->opened[1]) {
1151 			if (umidi->roland_load_ctl) {
1152 				ctl = umidi->roland_load_ctl;
1153 				ctl->vd[0].access |=
1154 					SNDRV_CTL_ELEM_ACCESS_INACTIVE;
1155 				snd_ctl_notify(umidi->card,
1156 				       SNDRV_CTL_EVENT_MASK_INFO, &ctl->id);
1157 				update_roland_altsetting(umidi);
1158 			}
1159 		}
1160 		umidi->opened[dir]++;
1161 		if (umidi->opened[1])
1162 			snd_usbmidi_input_start(&umidi->list);
1163 	} else {
1164 		umidi->opened[dir]--;
1165 		if (!umidi->opened[1])
1166 			snd_usbmidi_input_stop(&umidi->list);
1167 		if (!umidi->opened[0] && !umidi->opened[1]) {
1168 			if (umidi->roland_load_ctl) {
1169 				ctl = umidi->roland_load_ctl;
1170 				ctl->vd[0].access &=
1171 					~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
1172 				snd_ctl_notify(umidi->card,
1173 				       SNDRV_CTL_EVENT_MASK_INFO, &ctl->id);
1174 			}
1175 		}
1176 	}
1177 	return 0;
1178 }
1179 
1180 static int snd_usbmidi_output_open(struct snd_rawmidi_substream *substream)
1181 {
1182 	struct snd_usb_midi *umidi = substream->rmidi->private_data;
1183 	struct usbmidi_out_port *port = NULL;
1184 	int i, j;
1185 
1186 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
1187 		if (umidi->endpoints[i].out)
1188 			for (j = 0; j < 0x10; ++j)
1189 				if (umidi->endpoints[i].out->ports[j].substream == substream) {
1190 					port = &umidi->endpoints[i].out->ports[j];
1191 					break;
1192 				}
1193 	if (!port)
1194 		return -ENXIO;
1195 
1196 	substream->runtime->private_data = port;
1197 	port->state = STATE_UNKNOWN;
1198 	return substream_open(substream, 0, 1);
1199 }
1200 
1201 static int snd_usbmidi_output_close(struct snd_rawmidi_substream *substream)
1202 {
1203 	struct usbmidi_out_port *port = substream->runtime->private_data;
1204 
1205 	flush_work(&port->ep->work);
1206 	return substream_open(substream, 0, 0);
1207 }
1208 
1209 static void snd_usbmidi_output_trigger(struct snd_rawmidi_substream *substream,
1210 				       int up)
1211 {
1212 	struct usbmidi_out_port *port =
1213 		(struct usbmidi_out_port *)substream->runtime->private_data;
1214 
1215 	port->active = up;
1216 	if (up) {
1217 		if (port->ep->umidi->disconnected) {
1218 			/* gobble up remaining bytes to prevent wait in
1219 			 * snd_rawmidi_drain_output */
1220 			snd_rawmidi_proceed(substream);
1221 			return;
1222 		}
1223 		queue_work(system_highpri_wq, &port->ep->work);
1224 	}
1225 }
1226 
1227 static void snd_usbmidi_output_drain(struct snd_rawmidi_substream *substream)
1228 {
1229 	struct usbmidi_out_port *port = substream->runtime->private_data;
1230 	struct snd_usb_midi_out_endpoint *ep = port->ep;
1231 	unsigned int drain_urbs;
1232 	DEFINE_WAIT(wait);
1233 	long timeout = msecs_to_jiffies(50);
1234 
1235 	if (ep->umidi->disconnected)
1236 		return;
1237 	/*
1238 	 * The substream buffer is empty, but some data might still be in the
1239 	 * currently active URBs, so we have to wait for those to complete.
1240 	 */
1241 	spin_lock_irq(&ep->buffer_lock);
1242 	drain_urbs = ep->active_urbs;
1243 	if (drain_urbs) {
1244 		ep->drain_urbs |= drain_urbs;
1245 		do {
1246 			prepare_to_wait(&ep->drain_wait, &wait,
1247 					TASK_UNINTERRUPTIBLE);
1248 			spin_unlock_irq(&ep->buffer_lock);
1249 			timeout = schedule_timeout(timeout);
1250 			spin_lock_irq(&ep->buffer_lock);
1251 			drain_urbs &= ep->drain_urbs;
1252 		} while (drain_urbs && timeout);
1253 		finish_wait(&ep->drain_wait, &wait);
1254 	}
1255 	port->active = 0;
1256 	spin_unlock_irq(&ep->buffer_lock);
1257 }
1258 
1259 static int snd_usbmidi_input_open(struct snd_rawmidi_substream *substream)
1260 {
1261 	return substream_open(substream, 1, 1);
1262 }
1263 
1264 static int snd_usbmidi_input_close(struct snd_rawmidi_substream *substream)
1265 {
1266 	return substream_open(substream, 1, 0);
1267 }
1268 
1269 static void snd_usbmidi_input_trigger(struct snd_rawmidi_substream *substream,
1270 				      int up)
1271 {
1272 	struct snd_usb_midi *umidi = substream->rmidi->private_data;
1273 
1274 	if (up)
1275 		set_bit(substream->number, &umidi->input_triggered);
1276 	else
1277 		clear_bit(substream->number, &umidi->input_triggered);
1278 }
1279 
1280 static const struct snd_rawmidi_ops snd_usbmidi_output_ops = {
1281 	.open = snd_usbmidi_output_open,
1282 	.close = snd_usbmidi_output_close,
1283 	.trigger = snd_usbmidi_output_trigger,
1284 	.drain = snd_usbmidi_output_drain,
1285 };
1286 
1287 static const struct snd_rawmidi_ops snd_usbmidi_input_ops = {
1288 	.open = snd_usbmidi_input_open,
1289 	.close = snd_usbmidi_input_close,
1290 	.trigger = snd_usbmidi_input_trigger
1291 };
1292 
1293 static void free_urb_and_buffer(struct snd_usb_midi *umidi, struct urb *urb,
1294 				unsigned int buffer_length)
1295 {
1296 	usb_free_coherent(umidi->dev, buffer_length,
1297 			  urb->transfer_buffer, urb->transfer_dma);
1298 	usb_free_urb(urb);
1299 }
1300 
1301 /*
1302  * Frees an input endpoint.
1303  * May be called when ep hasn't been initialized completely.
1304  */
1305 static void snd_usbmidi_in_endpoint_delete(struct snd_usb_midi_in_endpoint *ep)
1306 {
1307 	unsigned int i;
1308 
1309 	for (i = 0; i < INPUT_URBS; ++i)
1310 		if (ep->urbs[i])
1311 			free_urb_and_buffer(ep->umidi, ep->urbs[i],
1312 					    ep->urbs[i]->transfer_buffer_length);
1313 	kfree(ep);
1314 }
1315 
1316 /*
1317  * Creates an input endpoint.
1318  */
1319 static int snd_usbmidi_in_endpoint_create(struct snd_usb_midi *umidi,
1320 					  struct snd_usb_midi_endpoint_info *ep_info,
1321 					  struct snd_usb_midi_endpoint *rep)
1322 {
1323 	struct snd_usb_midi_in_endpoint *ep;
1324 	void *buffer;
1325 	unsigned int pipe;
1326 	int length;
1327 	unsigned int i;
1328 	int err;
1329 
1330 	rep->in = NULL;
1331 	ep = kzalloc(sizeof(*ep), GFP_KERNEL);
1332 	if (!ep)
1333 		return -ENOMEM;
1334 	ep->umidi = umidi;
1335 
1336 	for (i = 0; i < INPUT_URBS; ++i) {
1337 		ep->urbs[i] = usb_alloc_urb(0, GFP_KERNEL);
1338 		if (!ep->urbs[i]) {
1339 			err = -ENOMEM;
1340 			goto error;
1341 		}
1342 	}
1343 	if (ep_info->in_interval)
1344 		pipe = usb_rcvintpipe(umidi->dev, ep_info->in_ep);
1345 	else
1346 		pipe = usb_rcvbulkpipe(umidi->dev, ep_info->in_ep);
1347 	length = usb_maxpacket(umidi->dev, pipe);
1348 	for (i = 0; i < INPUT_URBS; ++i) {
1349 		buffer = usb_alloc_coherent(umidi->dev, length, GFP_KERNEL,
1350 					    &ep->urbs[i]->transfer_dma);
1351 		if (!buffer) {
1352 			err = -ENOMEM;
1353 			goto error;
1354 		}
1355 		if (ep_info->in_interval)
1356 			usb_fill_int_urb(ep->urbs[i], umidi->dev,
1357 					 pipe, buffer, length,
1358 					 snd_usbmidi_in_urb_complete,
1359 					 ep, ep_info->in_interval);
1360 		else
1361 			usb_fill_bulk_urb(ep->urbs[i], umidi->dev,
1362 					  pipe, buffer, length,
1363 					  snd_usbmidi_in_urb_complete, ep);
1364 		ep->urbs[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1365 		err = usb_urb_ep_type_check(ep->urbs[i]);
1366 		if (err < 0) {
1367 			dev_err(&umidi->dev->dev, "invalid MIDI in EP %x\n",
1368 				ep_info->in_ep);
1369 			goto error;
1370 		}
1371 	}
1372 
1373 	rep->in = ep;
1374 	return 0;
1375 
1376  error:
1377 	snd_usbmidi_in_endpoint_delete(ep);
1378 	return err;
1379 }
1380 
1381 /*
1382  * Frees an output endpoint.
1383  * May be called when ep hasn't been initialized completely.
1384  */
1385 static void snd_usbmidi_out_endpoint_clear(struct snd_usb_midi_out_endpoint *ep)
1386 {
1387 	unsigned int i;
1388 
1389 	for (i = 0; i < OUTPUT_URBS; ++i)
1390 		if (ep->urbs[i].urb) {
1391 			free_urb_and_buffer(ep->umidi, ep->urbs[i].urb,
1392 					    ep->max_transfer);
1393 			ep->urbs[i].urb = NULL;
1394 		}
1395 }
1396 
1397 static void snd_usbmidi_out_endpoint_delete(struct snd_usb_midi_out_endpoint *ep)
1398 {
1399 	snd_usbmidi_out_endpoint_clear(ep);
1400 	kfree(ep);
1401 }
1402 
1403 /*
1404  * Creates an output endpoint, and initializes output ports.
1405  */
1406 static int snd_usbmidi_out_endpoint_create(struct snd_usb_midi *umidi,
1407 					   struct snd_usb_midi_endpoint_info *ep_info,
1408 					   struct snd_usb_midi_endpoint *rep)
1409 {
1410 	struct snd_usb_midi_out_endpoint *ep;
1411 	unsigned int i;
1412 	unsigned int pipe;
1413 	void *buffer;
1414 	int err;
1415 
1416 	rep->out = NULL;
1417 	ep = kzalloc(sizeof(*ep), GFP_KERNEL);
1418 	if (!ep)
1419 		return -ENOMEM;
1420 	ep->umidi = umidi;
1421 
1422 	for (i = 0; i < OUTPUT_URBS; ++i) {
1423 		ep->urbs[i].urb = usb_alloc_urb(0, GFP_KERNEL);
1424 		if (!ep->urbs[i].urb) {
1425 			err = -ENOMEM;
1426 			goto error;
1427 		}
1428 		ep->urbs[i].ep = ep;
1429 	}
1430 	if (ep_info->out_interval)
1431 		pipe = usb_sndintpipe(umidi->dev, ep_info->out_ep);
1432 	else
1433 		pipe = usb_sndbulkpipe(umidi->dev, ep_info->out_ep);
1434 	switch (umidi->usb_id) {
1435 	default:
1436 		ep->max_transfer = usb_maxpacket(umidi->dev, pipe);
1437 		break;
1438 		/*
1439 		 * Various chips declare a packet size larger than 4 bytes, but
1440 		 * do not actually work with larger packets:
1441 		 */
1442 	case USB_ID(0x0a67, 0x5011): /* Medeli DD305 */
1443 	case USB_ID(0x0a92, 0x1020): /* ESI M4U */
1444 	case USB_ID(0x1430, 0x474b): /* RedOctane GH MIDI INTERFACE */
1445 	case USB_ID(0x15ca, 0x0101): /* Textech USB Midi Cable */
1446 	case USB_ID(0x15ca, 0x1806): /* Textech USB Midi Cable */
1447 	case USB_ID(0x1a86, 0x752d): /* QinHeng CH345 "USB2.0-MIDI" */
1448 	case USB_ID(0xfc08, 0x0101): /* Unknown vendor Cable */
1449 		ep->max_transfer = 4;
1450 		break;
1451 		/*
1452 		 * Some devices only work with 9 bytes packet size:
1453 		 */
1454 	case USB_ID(0x0644, 0x800e): /* Tascam US-122L */
1455 	case USB_ID(0x0644, 0x800f): /* Tascam US-144 */
1456 		ep->max_transfer = 9;
1457 		break;
1458 	}
1459 	for (i = 0; i < OUTPUT_URBS; ++i) {
1460 		buffer = usb_alloc_coherent(umidi->dev,
1461 					    ep->max_transfer, GFP_KERNEL,
1462 					    &ep->urbs[i].urb->transfer_dma);
1463 		if (!buffer) {
1464 			err = -ENOMEM;
1465 			goto error;
1466 		}
1467 		if (ep_info->out_interval)
1468 			usb_fill_int_urb(ep->urbs[i].urb, umidi->dev,
1469 					 pipe, buffer, ep->max_transfer,
1470 					 snd_usbmidi_out_urb_complete,
1471 					 &ep->urbs[i], ep_info->out_interval);
1472 		else
1473 			usb_fill_bulk_urb(ep->urbs[i].urb, umidi->dev,
1474 					  pipe, buffer, ep->max_transfer,
1475 					  snd_usbmidi_out_urb_complete,
1476 					  &ep->urbs[i]);
1477 		err = usb_urb_ep_type_check(ep->urbs[i].urb);
1478 		if (err < 0) {
1479 			dev_err(&umidi->dev->dev, "invalid MIDI out EP %x\n",
1480 				ep_info->out_ep);
1481 			goto error;
1482 		}
1483 		ep->urbs[i].urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1484 	}
1485 
1486 	spin_lock_init(&ep->buffer_lock);
1487 	INIT_WORK(&ep->work, snd_usbmidi_out_work);
1488 	init_waitqueue_head(&ep->drain_wait);
1489 
1490 	for (i = 0; i < 0x10; ++i)
1491 		if (ep_info->out_cables & (1 << i)) {
1492 			ep->ports[i].ep = ep;
1493 			ep->ports[i].cable = i << 4;
1494 		}
1495 
1496 	if (umidi->usb_protocol_ops->init_out_endpoint)
1497 		umidi->usb_protocol_ops->init_out_endpoint(ep);
1498 
1499 	rep->out = ep;
1500 	return 0;
1501 
1502  error:
1503 	snd_usbmidi_out_endpoint_delete(ep);
1504 	return err;
1505 }
1506 
1507 /*
1508  * Frees everything.
1509  */
1510 static void snd_usbmidi_free(struct snd_usb_midi *umidi)
1511 {
1512 	int i;
1513 
1514 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1515 		struct snd_usb_midi_endpoint *ep = &umidi->endpoints[i];
1516 		if (ep->out)
1517 			snd_usbmidi_out_endpoint_delete(ep->out);
1518 		if (ep->in)
1519 			snd_usbmidi_in_endpoint_delete(ep->in);
1520 	}
1521 	mutex_destroy(&umidi->mutex);
1522 	timer_shutdown_sync(&umidi->error_timer);
1523 	kfree(umidi);
1524 }
1525 
1526 /*
1527  * Unlinks all URBs (must be done before the usb_device is deleted).
1528  */
1529 void snd_usbmidi_disconnect(struct list_head *p)
1530 {
1531 	struct snd_usb_midi *umidi;
1532 	unsigned int i, j;
1533 
1534 	umidi = list_entry(p, struct snd_usb_midi, list);
1535 	/*
1536 	 * an URB's completion handler may start the timer and
1537 	 * a timer may submit an URB. To reliably break the cycle
1538 	 * a flag under lock must be used
1539 	 */
1540 	scoped_guard(rwsem_write, &umidi->disc_rwsem) {
1541 		guard(spinlock_irq)(&umidi->disc_lock);
1542 		umidi->disconnected = 1;
1543 	}
1544 
1545 	timer_shutdown_sync(&umidi->error_timer);
1546 
1547 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1548 		struct snd_usb_midi_endpoint *ep = &umidi->endpoints[i];
1549 		if (ep->out)
1550 			cancel_work_sync(&ep->out->work);
1551 		if (ep->out) {
1552 			for (j = 0; j < OUTPUT_URBS; ++j)
1553 				usb_kill_urb(ep->out->urbs[j].urb);
1554 			if (umidi->usb_protocol_ops->finish_out_endpoint)
1555 				umidi->usb_protocol_ops->finish_out_endpoint(ep->out);
1556 			ep->out->active_urbs = 0;
1557 			if (ep->out->drain_urbs) {
1558 				ep->out->drain_urbs = 0;
1559 				wake_up(&ep->out->drain_wait);
1560 			}
1561 		}
1562 		if (ep->in)
1563 			for (j = 0; j < INPUT_URBS; ++j)
1564 				usb_kill_urb(ep->in->urbs[j]);
1565 		/* free endpoints here; later call can result in Oops */
1566 		if (ep->out)
1567 			snd_usbmidi_out_endpoint_clear(ep->out);
1568 		if (ep->in) {
1569 			snd_usbmidi_in_endpoint_delete(ep->in);
1570 			ep->in = NULL;
1571 		}
1572 	}
1573 }
1574 EXPORT_SYMBOL(snd_usbmidi_disconnect);
1575 
1576 static void snd_usbmidi_rawmidi_free(struct snd_rawmidi *rmidi)
1577 {
1578 	struct snd_usb_midi *umidi = rmidi->private_data;
1579 	snd_usbmidi_free(umidi);
1580 }
1581 
1582 static struct snd_rawmidi_substream *snd_usbmidi_find_substream(struct snd_usb_midi *umidi,
1583 								int stream,
1584 								int number)
1585 {
1586 	struct snd_rawmidi_substream *substream;
1587 
1588 	list_for_each_entry(substream, &umidi->rmidi->streams[stream].substreams,
1589 			    list) {
1590 		if (substream->number == number)
1591 			return substream;
1592 	}
1593 	return NULL;
1594 }
1595 
1596 /*
1597  * This list specifies names for ports that do not fit into the standard
1598  * "(product) MIDI (n)" schema because they aren't external MIDI ports,
1599  * such as internal control or synthesizer ports.
1600  */
1601 static struct port_info {
1602 	u32 id;
1603 	short int port;
1604 	short int voices;
1605 	const char *name;
1606 	unsigned int seq_flags;
1607 } snd_usbmidi_port_info[] = {
1608 #define PORT_INFO(vendor, product, num, name_, voices_, flags) \
1609 	{ .id = USB_ID(vendor, product), \
1610 	  .port = num, .voices = voices_, \
1611 	  .name = name_, .seq_flags = flags }
1612 #define EXTERNAL_PORT(vendor, product, num, name) \
1613 	PORT_INFO(vendor, product, num, name, 0, \
1614 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1615 		  SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1616 		  SNDRV_SEQ_PORT_TYPE_PORT)
1617 #define CONTROL_PORT(vendor, product, num, name) \
1618 	PORT_INFO(vendor, product, num, name, 0, \
1619 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1620 		  SNDRV_SEQ_PORT_TYPE_HARDWARE)
1621 #define GM_SYNTH_PORT(vendor, product, num, name, voices) \
1622 	PORT_INFO(vendor, product, num, name, voices, \
1623 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1624 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM | \
1625 		  SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1626 		  SNDRV_SEQ_PORT_TYPE_SYNTHESIZER)
1627 #define ROLAND_SYNTH_PORT(vendor, product, num, name, voices) \
1628 	PORT_INFO(vendor, product, num, name, voices, \
1629 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1630 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM | \
1631 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM2 | \
1632 		  SNDRV_SEQ_PORT_TYPE_MIDI_GS | \
1633 		  SNDRV_SEQ_PORT_TYPE_MIDI_XG | \
1634 		  SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1635 		  SNDRV_SEQ_PORT_TYPE_SYNTHESIZER)
1636 #define SOUNDCANVAS_PORT(vendor, product, num, name, voices) \
1637 	PORT_INFO(vendor, product, num, name, voices, \
1638 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1639 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM | \
1640 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM2 | \
1641 		  SNDRV_SEQ_PORT_TYPE_MIDI_GS | \
1642 		  SNDRV_SEQ_PORT_TYPE_MIDI_XG | \
1643 		  SNDRV_SEQ_PORT_TYPE_MIDI_MT32 | \
1644 		  SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1645 		  SNDRV_SEQ_PORT_TYPE_SYNTHESIZER)
1646 	/* Yamaha MOTIF XF */
1647 	GM_SYNTH_PORT(0x0499, 0x105c, 0, "%s Tone Generator", 128),
1648 	CONTROL_PORT(0x0499, 0x105c, 1, "%s Remote Control"),
1649 	EXTERNAL_PORT(0x0499, 0x105c, 2, "%s Thru"),
1650 	CONTROL_PORT(0x0499, 0x105c, 3, "%s Editor"),
1651 	/* Roland UA-100 */
1652 	CONTROL_PORT(0x0582, 0x0000, 2, "%s Control"),
1653 	/* Roland SC-8850 */
1654 	SOUNDCANVAS_PORT(0x0582, 0x0003, 0, "%s Part A", 128),
1655 	SOUNDCANVAS_PORT(0x0582, 0x0003, 1, "%s Part B", 128),
1656 	SOUNDCANVAS_PORT(0x0582, 0x0003, 2, "%s Part C", 128),
1657 	SOUNDCANVAS_PORT(0x0582, 0x0003, 3, "%s Part D", 128),
1658 	EXTERNAL_PORT(0x0582, 0x0003, 4, "%s MIDI 1"),
1659 	EXTERNAL_PORT(0x0582, 0x0003, 5, "%s MIDI 2"),
1660 	/* Roland U-8 */
1661 	EXTERNAL_PORT(0x0582, 0x0004, 0, "%s MIDI"),
1662 	CONTROL_PORT(0x0582, 0x0004, 1, "%s Control"),
1663 	/* Roland SC-8820 */
1664 	SOUNDCANVAS_PORT(0x0582, 0x0007, 0, "%s Part A", 64),
1665 	SOUNDCANVAS_PORT(0x0582, 0x0007, 1, "%s Part B", 64),
1666 	EXTERNAL_PORT(0x0582, 0x0007, 2, "%s MIDI"),
1667 	/* Roland SK-500 */
1668 	SOUNDCANVAS_PORT(0x0582, 0x000b, 0, "%s Part A", 64),
1669 	SOUNDCANVAS_PORT(0x0582, 0x000b, 1, "%s Part B", 64),
1670 	EXTERNAL_PORT(0x0582, 0x000b, 2, "%s MIDI"),
1671 	/* Roland SC-D70 */
1672 	SOUNDCANVAS_PORT(0x0582, 0x000c, 0, "%s Part A", 64),
1673 	SOUNDCANVAS_PORT(0x0582, 0x000c, 1, "%s Part B", 64),
1674 	EXTERNAL_PORT(0x0582, 0x000c, 2, "%s MIDI"),
1675 	/* Edirol UM-880 */
1676 	CONTROL_PORT(0x0582, 0x0014, 8, "%s Control"),
1677 	/* Edirol SD-90 */
1678 	ROLAND_SYNTH_PORT(0x0582, 0x0016, 0, "%s Part A", 128),
1679 	ROLAND_SYNTH_PORT(0x0582, 0x0016, 1, "%s Part B", 128),
1680 	EXTERNAL_PORT(0x0582, 0x0016, 2, "%s MIDI 1"),
1681 	EXTERNAL_PORT(0x0582, 0x0016, 3, "%s MIDI 2"),
1682 	/* Edirol UM-550 */
1683 	CONTROL_PORT(0x0582, 0x0023, 5, "%s Control"),
1684 	/* Edirol SD-20 */
1685 	ROLAND_SYNTH_PORT(0x0582, 0x0027, 0, "%s Part A", 64),
1686 	ROLAND_SYNTH_PORT(0x0582, 0x0027, 1, "%s Part B", 64),
1687 	EXTERNAL_PORT(0x0582, 0x0027, 2, "%s MIDI"),
1688 	/* Edirol SD-80 */
1689 	ROLAND_SYNTH_PORT(0x0582, 0x0029, 0, "%s Part A", 128),
1690 	ROLAND_SYNTH_PORT(0x0582, 0x0029, 1, "%s Part B", 128),
1691 	EXTERNAL_PORT(0x0582, 0x0029, 2, "%s MIDI 1"),
1692 	EXTERNAL_PORT(0x0582, 0x0029, 3, "%s MIDI 2"),
1693 	/* Edirol UA-700 */
1694 	EXTERNAL_PORT(0x0582, 0x002b, 0, "%s MIDI"),
1695 	CONTROL_PORT(0x0582, 0x002b, 1, "%s Control"),
1696 	/* Roland VariOS */
1697 	EXTERNAL_PORT(0x0582, 0x002f, 0, "%s MIDI"),
1698 	EXTERNAL_PORT(0x0582, 0x002f, 1, "%s External MIDI"),
1699 	EXTERNAL_PORT(0x0582, 0x002f, 2, "%s Sync"),
1700 	/* Edirol PCR */
1701 	EXTERNAL_PORT(0x0582, 0x0033, 0, "%s MIDI"),
1702 	EXTERNAL_PORT(0x0582, 0x0033, 1, "%s 1"),
1703 	EXTERNAL_PORT(0x0582, 0x0033, 2, "%s 2"),
1704 	/* BOSS GS-10 */
1705 	EXTERNAL_PORT(0x0582, 0x003b, 0, "%s MIDI"),
1706 	CONTROL_PORT(0x0582, 0x003b, 1, "%s Control"),
1707 	/* Edirol UA-1000 */
1708 	EXTERNAL_PORT(0x0582, 0x0044, 0, "%s MIDI"),
1709 	CONTROL_PORT(0x0582, 0x0044, 1, "%s Control"),
1710 	/* Edirol UR-80 */
1711 	EXTERNAL_PORT(0x0582, 0x0048, 0, "%s MIDI"),
1712 	EXTERNAL_PORT(0x0582, 0x0048, 1, "%s 1"),
1713 	EXTERNAL_PORT(0x0582, 0x0048, 2, "%s 2"),
1714 	/* Edirol PCR-A */
1715 	EXTERNAL_PORT(0x0582, 0x004d, 0, "%s MIDI"),
1716 	EXTERNAL_PORT(0x0582, 0x004d, 1, "%s 1"),
1717 	EXTERNAL_PORT(0x0582, 0x004d, 2, "%s 2"),
1718 	/* BOSS GT-PRO */
1719 	CONTROL_PORT(0x0582, 0x0089, 0, "%s Control"),
1720 	/* Edirol UM-3EX */
1721 	CONTROL_PORT(0x0582, 0x009a, 3, "%s Control"),
1722 	/* Roland VG-99 */
1723 	CONTROL_PORT(0x0582, 0x00b2, 0, "%s Control"),
1724 	EXTERNAL_PORT(0x0582, 0x00b2, 1, "%s MIDI"),
1725 	/* Cakewalk Sonar V-Studio 100 */
1726 	EXTERNAL_PORT(0x0582, 0x00eb, 0, "%s MIDI"),
1727 	CONTROL_PORT(0x0582, 0x00eb, 1, "%s Control"),
1728 	/* Roland VB-99 */
1729 	CONTROL_PORT(0x0582, 0x0102, 0, "%s Control"),
1730 	EXTERNAL_PORT(0x0582, 0x0102, 1, "%s MIDI"),
1731 	/* Roland A-PRO */
1732 	EXTERNAL_PORT(0x0582, 0x010f, 0, "%s MIDI"),
1733 	CONTROL_PORT(0x0582, 0x010f, 1, "%s 1"),
1734 	CONTROL_PORT(0x0582, 0x010f, 2, "%s 2"),
1735 	/* Roland SD-50 */
1736 	ROLAND_SYNTH_PORT(0x0582, 0x0114, 0, "%s Synth", 128),
1737 	EXTERNAL_PORT(0x0582, 0x0114, 1, "%s MIDI"),
1738 	CONTROL_PORT(0x0582, 0x0114, 2, "%s Control"),
1739 	/* Roland OCTA-CAPTURE */
1740 	EXTERNAL_PORT(0x0582, 0x0120, 0, "%s MIDI"),
1741 	CONTROL_PORT(0x0582, 0x0120, 1, "%s Control"),
1742 	EXTERNAL_PORT(0x0582, 0x0121, 0, "%s MIDI"),
1743 	CONTROL_PORT(0x0582, 0x0121, 1, "%s Control"),
1744 	/* Roland SPD-SX */
1745 	CONTROL_PORT(0x0582, 0x0145, 0, "%s Control"),
1746 	EXTERNAL_PORT(0x0582, 0x0145, 1, "%s MIDI"),
1747 	/* Roland A-Series */
1748 	CONTROL_PORT(0x0582, 0x0156, 0, "%s Keyboard"),
1749 	EXTERNAL_PORT(0x0582, 0x0156, 1, "%s MIDI"),
1750 	/* Roland INTEGRA-7 */
1751 	ROLAND_SYNTH_PORT(0x0582, 0x015b, 0, "%s Synth", 128),
1752 	CONTROL_PORT(0x0582, 0x015b, 1, "%s Control"),
1753 	/* M-Audio MidiSport 8x8 */
1754 	CONTROL_PORT(0x0763, 0x1031, 8, "%s Control"),
1755 	CONTROL_PORT(0x0763, 0x1033, 8, "%s Control"),
1756 	/* MOTU Fastlane */
1757 	EXTERNAL_PORT(0x07fd, 0x0001, 0, "%s MIDI A"),
1758 	EXTERNAL_PORT(0x07fd, 0x0001, 1, "%s MIDI B"),
1759 	/* Emagic Unitor8/AMT8/MT4 */
1760 	EXTERNAL_PORT(0x086a, 0x0001, 8, "%s Broadcast"),
1761 	EXTERNAL_PORT(0x086a, 0x0002, 8, "%s Broadcast"),
1762 	EXTERNAL_PORT(0x086a, 0x0003, 4, "%s Broadcast"),
1763 	/* Akai MPD16 */
1764 	CONTROL_PORT(0x09e8, 0x0062, 0, "%s Control"),
1765 	PORT_INFO(0x09e8, 0x0062, 1, "%s MIDI", 0,
1766 		SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC |
1767 		SNDRV_SEQ_PORT_TYPE_HARDWARE),
1768 	/* Access Music Virus TI */
1769 	EXTERNAL_PORT(0x133e, 0x0815, 0, "%s MIDI"),
1770 	PORT_INFO(0x133e, 0x0815, 1, "%s Synth", 0,
1771 		SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC |
1772 		SNDRV_SEQ_PORT_TYPE_HARDWARE |
1773 		SNDRV_SEQ_PORT_TYPE_SYNTHESIZER),
1774 };
1775 
1776 static struct port_info *find_port_info(struct snd_usb_midi *umidi, int number)
1777 {
1778 	int i;
1779 
1780 	for (i = 0; i < ARRAY_SIZE(snd_usbmidi_port_info); ++i) {
1781 		if (snd_usbmidi_port_info[i].id == umidi->usb_id &&
1782 		    snd_usbmidi_port_info[i].port == number)
1783 			return &snd_usbmidi_port_info[i];
1784 	}
1785 	return NULL;
1786 }
1787 
1788 static void snd_usbmidi_get_port_info(struct snd_rawmidi *rmidi, int number,
1789 				      struct snd_seq_port_info *seq_port_info)
1790 {
1791 	struct snd_usb_midi *umidi = rmidi->private_data;
1792 	struct port_info *port_info;
1793 
1794 	/* TODO: read port flags from descriptors */
1795 	port_info = find_port_info(umidi, number);
1796 	if (port_info) {
1797 		seq_port_info->type = port_info->seq_flags;
1798 		seq_port_info->midi_voices = port_info->voices;
1799 	}
1800 }
1801 
1802 /* return iJack for the corresponding jackID */
1803 static int find_usb_ijack(struct usb_host_interface *hostif, uint8_t jack_id)
1804 {
1805 	unsigned char *extra = hostif->extra;
1806 	int extralen = hostif->extralen;
1807 	struct usb_descriptor_header *h;
1808 	struct usb_midi_out_jack_descriptor *outjd;
1809 	struct usb_midi_in_jack_descriptor *injd;
1810 	size_t sz;
1811 
1812 	while (extralen > 4) {
1813 		h = (struct usb_descriptor_header *)extra;
1814 		if (h->bDescriptorType != USB_DT_CS_INTERFACE)
1815 			goto next;
1816 
1817 		outjd = (struct usb_midi_out_jack_descriptor *)h;
1818 		if (h->bLength >= sizeof(*outjd) &&
1819 		    outjd->bDescriptorSubtype == UAC_MIDI_OUT_JACK &&
1820 		    outjd->bJackID == jack_id) {
1821 			sz = USB_DT_MIDI_OUT_SIZE(outjd->bNrInputPins);
1822 			if (outjd->bLength < sz)
1823 				goto next;
1824 			return *(extra + sz - 1);
1825 		}
1826 
1827 		injd = (struct usb_midi_in_jack_descriptor *)h;
1828 		if (injd->bLength >= sizeof(*injd) &&
1829 		    injd->bDescriptorSubtype == UAC_MIDI_IN_JACK &&
1830 		    injd->bJackID == jack_id)
1831 			return injd->iJack;
1832 
1833 next:
1834 		if (!extra[0])
1835 			break;
1836 		extralen -= extra[0];
1837 		extra += extra[0];
1838 	}
1839 	return 0;
1840 }
1841 
1842 static void snd_usbmidi_init_substream(struct snd_usb_midi *umidi,
1843 				       int stream, int number, int jack_id,
1844 				       struct snd_rawmidi_substream **rsubstream)
1845 {
1846 	struct port_info *port_info;
1847 	const char *name_format;
1848 	struct usb_interface *intf;
1849 	struct usb_host_interface *hostif;
1850 	uint8_t jack_name_buf[32];
1851 	uint8_t *default_jack_name = "MIDI";
1852 	uint8_t *jack_name = default_jack_name;
1853 	uint8_t iJack;
1854 	int res;
1855 
1856 	struct snd_rawmidi_substream *substream =
1857 		snd_usbmidi_find_substream(umidi, stream, number);
1858 	if (!substream) {
1859 		dev_err(&umidi->dev->dev, "substream %d:%d not found\n", stream,
1860 			number);
1861 		return;
1862 	}
1863 
1864 	intf = umidi->iface;
1865 	if (intf && jack_id >= 0) {
1866 		hostif = intf->cur_altsetting;
1867 		iJack = find_usb_ijack(hostif, jack_id);
1868 		if (iJack != 0) {
1869 			res = usb_string(umidi->dev, iJack, jack_name_buf,
1870 			  ARRAY_SIZE(jack_name_buf));
1871 			if (res)
1872 				jack_name = jack_name_buf;
1873 		}
1874 	}
1875 
1876 	port_info = find_port_info(umidi, number);
1877 	if (port_info || jack_name == default_jack_name ||
1878 	    strncmp(umidi->card->shortname, jack_name, strlen(umidi->card->shortname)) != 0) {
1879 		name_format = port_info ? port_info->name :
1880 			(jack_name != default_jack_name  ? "%s %s" : "%s %s %d");
1881 		snprintf(substream->name, sizeof(substream->name),
1882 			 name_format, umidi->card->shortname, jack_name, number + 1);
1883 	} else {
1884 		/* The manufacturer included the iProduct name in the jack
1885 		 * name, do not use both
1886 		 */
1887 		strscpy(substream->name, jack_name);
1888 	}
1889 
1890 	*rsubstream = substream;
1891 }
1892 
1893 /*
1894  * Creates the endpoints and their ports.
1895  */
1896 static int snd_usbmidi_create_endpoints(struct snd_usb_midi *umidi,
1897 					struct snd_usb_midi_endpoint_info *endpoints)
1898 {
1899 	int i, j, err;
1900 	int out_ports = 0, in_ports = 0;
1901 
1902 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1903 		if (endpoints[i].out_cables) {
1904 			err = snd_usbmidi_out_endpoint_create(umidi,
1905 							      &endpoints[i],
1906 							      &umidi->endpoints[i]);
1907 			if (err < 0)
1908 				return err;
1909 		}
1910 		if (endpoints[i].in_cables) {
1911 			err = snd_usbmidi_in_endpoint_create(umidi,
1912 							     &endpoints[i],
1913 							     &umidi->endpoints[i]);
1914 			if (err < 0)
1915 				return err;
1916 		}
1917 
1918 		for (j = 0; j < 0x10; ++j) {
1919 			if (endpoints[i].out_cables & (1 << j)) {
1920 				snd_usbmidi_init_substream(umidi,
1921 							   SNDRV_RAWMIDI_STREAM_OUTPUT,
1922 							   out_ports,
1923 							   endpoints[i].assoc_out_jacks[j],
1924 							   &umidi->endpoints[i].out->ports[j].substream);
1925 				++out_ports;
1926 			}
1927 			if (endpoints[i].in_cables & (1 << j)) {
1928 				snd_usbmidi_init_substream(umidi,
1929 							   SNDRV_RAWMIDI_STREAM_INPUT,
1930 							   in_ports,
1931 							   endpoints[i].assoc_in_jacks[j],
1932 							   &umidi->endpoints[i].in->ports[j].substream);
1933 				++in_ports;
1934 			}
1935 		}
1936 	}
1937 	dev_dbg(&umidi->dev->dev, "created %d output and %d input ports\n",
1938 		    out_ports, in_ports);
1939 	return 0;
1940 }
1941 
1942 static struct usb_ms_endpoint_descriptor *find_usb_ms_endpoint_descriptor(
1943 					struct usb_host_endpoint *hostep)
1944 {
1945 	unsigned char *extra = hostep->extra;
1946 	int extralen = hostep->extralen;
1947 
1948 	while (extralen > 3) {
1949 		struct usb_ms_endpoint_descriptor *ms_ep =
1950 				(struct usb_ms_endpoint_descriptor *)extra;
1951 
1952 		if (ms_ep->bLength > 3 &&
1953 		    ms_ep->bDescriptorType == USB_DT_CS_ENDPOINT &&
1954 		    ms_ep->bDescriptorSubtype == UAC_MS_GENERAL)
1955 			return ms_ep;
1956 		if (!extra[0])
1957 			break;
1958 		extralen -= extra[0];
1959 		extra += extra[0];
1960 	}
1961 	return NULL;
1962 }
1963 
1964 /*
1965  * Returns MIDIStreaming device capabilities.
1966  */
1967 static int snd_usbmidi_get_ms_info(struct snd_usb_midi *umidi,
1968 				   struct snd_usb_midi_endpoint_info *endpoints)
1969 {
1970 	struct usb_interface *intf;
1971 	struct usb_host_interface *hostif;
1972 	struct usb_interface_descriptor *intfd;
1973 	struct usb_ms_header_descriptor *ms_header;
1974 	struct usb_host_endpoint *hostep;
1975 	struct usb_endpoint_descriptor *ep;
1976 	struct usb_ms_endpoint_descriptor *ms_ep;
1977 	int i, j, epidx;
1978 
1979 	intf = umidi->iface;
1980 	if (!intf)
1981 		return -ENXIO;
1982 	hostif = &intf->altsetting[0];
1983 	intfd = get_iface_desc(hostif);
1984 	ms_header = (struct usb_ms_header_descriptor *)hostif->extra;
1985 	if (hostif->extralen >= 7 &&
1986 	    ms_header->bLength >= 7 &&
1987 	    ms_header->bDescriptorType == USB_DT_CS_INTERFACE &&
1988 	    ms_header->bDescriptorSubtype == UAC_HEADER)
1989 		dev_dbg(&umidi->dev->dev, "MIDIStreaming version %02x.%02x\n",
1990 			    ((uint8_t *)&ms_header->bcdMSC)[1], ((uint8_t *)&ms_header->bcdMSC)[0]);
1991 	else
1992 		dev_warn(&umidi->dev->dev,
1993 			 "MIDIStreaming interface descriptor not found\n");
1994 
1995 	epidx = 0;
1996 	for (i = 0; i < intfd->bNumEndpoints; ++i) {
1997 		hostep = &hostif->endpoint[i];
1998 		ep = get_ep_desc(hostep);
1999 		if (!usb_endpoint_xfer_bulk(ep) && !usb_endpoint_xfer_int(ep))
2000 			continue;
2001 		ms_ep = find_usb_ms_endpoint_descriptor(hostep);
2002 		if (!ms_ep)
2003 			continue;
2004 		if (ms_ep->bLength <= sizeof(*ms_ep))
2005 			continue;
2006 		if (ms_ep->bNumEmbMIDIJack > 0x10)
2007 			continue;
2008 		if (ms_ep->bLength < sizeof(*ms_ep) + ms_ep->bNumEmbMIDIJack)
2009 			continue;
2010 		if (usb_endpoint_dir_out(ep)) {
2011 			if (endpoints[epidx].out_ep) {
2012 				if (++epidx >= MIDI_MAX_ENDPOINTS) {
2013 					dev_warn(&umidi->dev->dev,
2014 						 "too many endpoints\n");
2015 					break;
2016 				}
2017 			}
2018 			endpoints[epidx].out_ep = usb_endpoint_num(ep);
2019 			if (usb_endpoint_xfer_int(ep))
2020 				endpoints[epidx].out_interval = ep->bInterval;
2021 			else if (snd_usb_get_speed(umidi->dev) == USB_SPEED_LOW)
2022 				/*
2023 				 * Low speed bulk transfers don't exist, so
2024 				 * force interrupt transfers for devices like
2025 				 * ESI MIDI Mate that try to use them anyway.
2026 				 */
2027 				endpoints[epidx].out_interval = 1;
2028 			endpoints[epidx].out_cables =
2029 				(1 << ms_ep->bNumEmbMIDIJack) - 1;
2030 			for (j = 0; j < ms_ep->bNumEmbMIDIJack; ++j)
2031 				endpoints[epidx].assoc_out_jacks[j] = ms_ep->baAssocJackID[j];
2032 			for (; j < ARRAY_SIZE(endpoints[epidx].assoc_out_jacks); ++j)
2033 				endpoints[epidx].assoc_out_jacks[j] = -1;
2034 			dev_dbg(&umidi->dev->dev, "EP %02X: %d jack(s)\n",
2035 				ep->bEndpointAddress, ms_ep->bNumEmbMIDIJack);
2036 		} else {
2037 			if (endpoints[epidx].in_ep) {
2038 				if (++epidx >= MIDI_MAX_ENDPOINTS) {
2039 					dev_warn(&umidi->dev->dev,
2040 						 "too many endpoints\n");
2041 					break;
2042 				}
2043 			}
2044 			endpoints[epidx].in_ep = usb_endpoint_num(ep);
2045 			if (usb_endpoint_xfer_int(ep))
2046 				endpoints[epidx].in_interval = ep->bInterval;
2047 			else if (snd_usb_get_speed(umidi->dev) == USB_SPEED_LOW)
2048 				endpoints[epidx].in_interval = 1;
2049 			endpoints[epidx].in_cables =
2050 				(1 << ms_ep->bNumEmbMIDIJack) - 1;
2051 			for (j = 0; j < ms_ep->bNumEmbMIDIJack; ++j)
2052 				endpoints[epidx].assoc_in_jacks[j] = ms_ep->baAssocJackID[j];
2053 			for (; j < ARRAY_SIZE(endpoints[epidx].assoc_in_jacks); ++j)
2054 				endpoints[epidx].assoc_in_jacks[j] = -1;
2055 			dev_dbg(&umidi->dev->dev, "EP %02X: %d jack(s)\n",
2056 				ep->bEndpointAddress, ms_ep->bNumEmbMIDIJack);
2057 		}
2058 	}
2059 	return 0;
2060 }
2061 
2062 static int roland_load_info(struct snd_kcontrol *kcontrol,
2063 			    struct snd_ctl_elem_info *info)
2064 {
2065 	static const char *const names[] = { "High Load", "Light Load" };
2066 
2067 	return snd_ctl_enum_info(info, 1, 2, names);
2068 }
2069 
2070 static int roland_load_get(struct snd_kcontrol *kcontrol,
2071 			   struct snd_ctl_elem_value *value)
2072 {
2073 	value->value.enumerated.item[0] = kcontrol->private_value;
2074 	return 0;
2075 }
2076 
2077 static int roland_load_put(struct snd_kcontrol *kcontrol,
2078 			   struct snd_ctl_elem_value *value)
2079 {
2080 	struct snd_usb_midi *umidi = snd_kcontrol_chip(kcontrol);
2081 	int changed;
2082 
2083 	if (value->value.enumerated.item[0] > 1)
2084 		return -EINVAL;
2085 	guard(mutex)(&umidi->mutex);
2086 	changed = value->value.enumerated.item[0] != kcontrol->private_value;
2087 	if (changed)
2088 		kcontrol->private_value = value->value.enumerated.item[0];
2089 	return changed;
2090 }
2091 
2092 static const struct snd_kcontrol_new roland_load_ctl = {
2093 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2094 	.name = "MIDI Input Mode",
2095 	.info = roland_load_info,
2096 	.get = roland_load_get,
2097 	.put = roland_load_put,
2098 	.private_value = 1,
2099 };
2100 
2101 /*
2102  * On Roland devices, use the second alternate setting to be able to use
2103  * the interrupt input endpoint.
2104  */
2105 static void snd_usbmidi_switch_roland_altsetting(struct snd_usb_midi *umidi)
2106 {
2107 	struct usb_interface *intf;
2108 	struct usb_host_interface *hostif;
2109 	struct usb_interface_descriptor *intfd;
2110 
2111 	intf = umidi->iface;
2112 	if (!intf || intf->num_altsetting != 2)
2113 		return;
2114 
2115 	hostif = &intf->altsetting[1];
2116 	intfd = get_iface_desc(hostif);
2117        /* If either or both of the endpoints support interrupt transfer,
2118         * then use the alternate setting
2119         */
2120 	if (intfd->bNumEndpoints != 2 ||
2121 	    !((get_endpoint(hostif, 0)->bmAttributes &
2122 	       USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT ||
2123 	      (get_endpoint(hostif, 1)->bmAttributes &
2124 	       USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT))
2125 		return;
2126 
2127 	dev_dbg(&umidi->dev->dev, "switching to altsetting %d with int ep\n",
2128 		    intfd->bAlternateSetting);
2129 	usb_set_interface(umidi->dev, intfd->bInterfaceNumber,
2130 			  intfd->bAlternateSetting);
2131 
2132 	umidi->roland_load_ctl = snd_ctl_new1(&roland_load_ctl, umidi);
2133 	if (snd_ctl_add(umidi->card, umidi->roland_load_ctl) < 0)
2134 		umidi->roland_load_ctl = NULL;
2135 }
2136 
2137 /*
2138  * Try to find any usable endpoints in the interface.
2139  */
2140 static int snd_usbmidi_detect_endpoints(struct snd_usb_midi *umidi,
2141 					struct snd_usb_midi_endpoint_info *endpoint,
2142 					int max_endpoints)
2143 {
2144 	struct usb_interface *intf;
2145 	struct usb_host_interface *hostif;
2146 	struct usb_interface_descriptor *intfd;
2147 	struct usb_endpoint_descriptor *epd;
2148 	int i, out_eps = 0, in_eps = 0;
2149 
2150 	if (USB_ID_VENDOR(umidi->usb_id) == 0x0582)
2151 		snd_usbmidi_switch_roland_altsetting(umidi);
2152 
2153 	if (endpoint[0].out_ep || endpoint[0].in_ep)
2154 		return 0;
2155 
2156 	intf = umidi->iface;
2157 	if (!intf || intf->num_altsetting < 1)
2158 		return -ENOENT;
2159 	hostif = intf->cur_altsetting;
2160 	intfd = get_iface_desc(hostif);
2161 
2162 	for (i = 0; i < intfd->bNumEndpoints; ++i) {
2163 		epd = get_endpoint(hostif, i);
2164 		if (!usb_endpoint_xfer_bulk(epd) &&
2165 		    !usb_endpoint_xfer_int(epd))
2166 			continue;
2167 		if (out_eps < max_endpoints &&
2168 		    usb_endpoint_dir_out(epd)) {
2169 			endpoint[out_eps].out_ep = usb_endpoint_num(epd);
2170 			if (usb_endpoint_xfer_int(epd))
2171 				endpoint[out_eps].out_interval = epd->bInterval;
2172 			++out_eps;
2173 		}
2174 		if (in_eps < max_endpoints &&
2175 		    usb_endpoint_dir_in(epd)) {
2176 			endpoint[in_eps].in_ep = usb_endpoint_num(epd);
2177 			if (usb_endpoint_xfer_int(epd))
2178 				endpoint[in_eps].in_interval = epd->bInterval;
2179 			++in_eps;
2180 		}
2181 	}
2182 	return (out_eps || in_eps) ? 0 : -ENOENT;
2183 }
2184 
2185 /*
2186  * Detects the endpoints for one-port-per-endpoint protocols.
2187  */
2188 static int snd_usbmidi_detect_per_port_endpoints(struct snd_usb_midi *umidi,
2189 						 struct snd_usb_midi_endpoint_info *endpoints)
2190 {
2191 	int err, i;
2192 
2193 	err = snd_usbmidi_detect_endpoints(umidi, endpoints, MIDI_MAX_ENDPOINTS);
2194 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
2195 		if (endpoints[i].out_ep)
2196 			endpoints[i].out_cables = 0x0001;
2197 		if (endpoints[i].in_ep)
2198 			endpoints[i].in_cables = 0x0001;
2199 	}
2200 	return err;
2201 }
2202 
2203 /*
2204  * Detects the endpoints and ports of Yamaha devices.
2205  */
2206 static int snd_usbmidi_detect_yamaha(struct snd_usb_midi *umidi,
2207 				     struct snd_usb_midi_endpoint_info *endpoint)
2208 {
2209 	struct usb_interface *intf;
2210 	struct usb_host_interface *hostif;
2211 	struct usb_interface_descriptor *intfd;
2212 	uint8_t *cs_desc;
2213 
2214 	intf = umidi->iface;
2215 	if (!intf)
2216 		return -ENOENT;
2217 	hostif = intf->altsetting;
2218 	intfd = get_iface_desc(hostif);
2219 	if (intfd->bNumEndpoints < 1)
2220 		return -ENOENT;
2221 
2222 	/*
2223 	 * For each port there is one MIDI_IN/OUT_JACK descriptor, not
2224 	 * necessarily with any useful contents.  So simply count 'em.
2225 	 */
2226 	for (cs_desc = hostif->extra;
2227 	     cs_desc < hostif->extra + hostif->extralen && cs_desc[0] >= 2;
2228 	     cs_desc += cs_desc[0]) {
2229 		if (cs_desc[1] == USB_DT_CS_INTERFACE) {
2230 			if (cs_desc[2] == UAC_MIDI_IN_JACK)
2231 				endpoint->in_cables =
2232 					(endpoint->in_cables << 1) | 1;
2233 			else if (cs_desc[2] == UAC_MIDI_OUT_JACK)
2234 				endpoint->out_cables =
2235 					(endpoint->out_cables << 1) | 1;
2236 		}
2237 	}
2238 	if (!endpoint->in_cables && !endpoint->out_cables)
2239 		return -ENOENT;
2240 
2241 	return snd_usbmidi_detect_endpoints(umidi, endpoint, 1);
2242 }
2243 
2244 /*
2245  * Detects the endpoints and ports of Roland devices.
2246  */
2247 static int snd_usbmidi_detect_roland(struct snd_usb_midi *umidi,
2248 				     struct snd_usb_midi_endpoint_info *endpoint)
2249 {
2250 	struct usb_interface *intf;
2251 	struct usb_host_interface *hostif;
2252 	u8 *cs_desc;
2253 
2254 	intf = umidi->iface;
2255 	if (!intf)
2256 		return -ENOENT;
2257 	hostif = intf->altsetting;
2258 	/*
2259 	 * Some devices have a descriptor <06 24 F1 02 <inputs> <outputs>>,
2260 	 * some have standard class descriptors, or both kinds, or neither.
2261 	 */
2262 	for (cs_desc = hostif->extra;
2263 	     cs_desc < hostif->extra + hostif->extralen && cs_desc[0] >= 2;
2264 	     cs_desc += cs_desc[0]) {
2265 		if (cs_desc[0] >= 6 &&
2266 		    cs_desc[1] == USB_DT_CS_INTERFACE &&
2267 		    cs_desc[2] == 0xf1 &&
2268 		    cs_desc[3] == 0x02) {
2269 			if (cs_desc[4] > 0x10 || cs_desc[5] > 0x10)
2270 				continue;
2271 			endpoint->in_cables  = (1 << cs_desc[4]) - 1;
2272 			endpoint->out_cables = (1 << cs_desc[5]) - 1;
2273 			return snd_usbmidi_detect_endpoints(umidi, endpoint, 1);
2274 		} else if (cs_desc[0] >= 7 &&
2275 			   cs_desc[1] == USB_DT_CS_INTERFACE &&
2276 			   cs_desc[2] == UAC_HEADER) {
2277 			return snd_usbmidi_get_ms_info(umidi, endpoint);
2278 		}
2279 	}
2280 
2281 	return -ENODEV;
2282 }
2283 
2284 /*
2285  * Creates the endpoints and their ports for Midiman devices.
2286  */
2287 static int snd_usbmidi_create_endpoints_midiman(struct snd_usb_midi *umidi,
2288 						struct snd_usb_midi_endpoint_info *endpoint)
2289 {
2290 	struct snd_usb_midi_endpoint_info ep_info;
2291 	struct usb_interface *intf;
2292 	struct usb_host_interface *hostif;
2293 	struct usb_interface_descriptor *intfd;
2294 	struct usb_endpoint_descriptor *epd;
2295 	int cable, err;
2296 
2297 	intf = umidi->iface;
2298 	if (!intf)
2299 		return -ENOENT;
2300 	hostif = intf->altsetting;
2301 	intfd = get_iface_desc(hostif);
2302 	/*
2303 	 * The various MidiSport devices have more or less random endpoint
2304 	 * numbers, so we have to identify the endpoints by their index in
2305 	 * the descriptor array, like the driver for that other OS does.
2306 	 *
2307 	 * There is one interrupt input endpoint for all input ports, one
2308 	 * bulk output endpoint for even-numbered ports, and one for odd-
2309 	 * numbered ports.  Both bulk output endpoints have corresponding
2310 	 * input bulk endpoints (at indices 1 and 3) which aren't used.
2311 	 */
2312 	if (intfd->bNumEndpoints < (endpoint->out_cables > 0x0001 ? 5 : 3)) {
2313 		dev_dbg(&umidi->dev->dev, "not enough endpoints\n");
2314 		return -ENOENT;
2315 	}
2316 
2317 	epd = get_endpoint(hostif, 0);
2318 	if (!usb_endpoint_dir_in(epd) || !usb_endpoint_xfer_int(epd)) {
2319 		dev_dbg(&umidi->dev->dev, "endpoint[0] isn't interrupt\n");
2320 		return -ENXIO;
2321 	}
2322 	epd = get_endpoint(hostif, 2);
2323 	if (!usb_endpoint_dir_out(epd) || !usb_endpoint_xfer_bulk(epd)) {
2324 		dev_dbg(&umidi->dev->dev, "endpoint[2] isn't bulk output\n");
2325 		return -ENXIO;
2326 	}
2327 	if (endpoint->out_cables > 0x0001) {
2328 		epd = get_endpoint(hostif, 4);
2329 		if (!usb_endpoint_dir_out(epd) ||
2330 		    !usb_endpoint_xfer_bulk(epd)) {
2331 			dev_dbg(&umidi->dev->dev,
2332 				"endpoint[4] isn't bulk output\n");
2333 			return -ENXIO;
2334 		}
2335 	}
2336 
2337 	ep_info.out_ep = get_endpoint(hostif, 2)->bEndpointAddress &
2338 		USB_ENDPOINT_NUMBER_MASK;
2339 	ep_info.out_interval = 0;
2340 	ep_info.out_cables = endpoint->out_cables & 0x5555;
2341 	err = snd_usbmidi_out_endpoint_create(umidi, &ep_info,
2342 					      &umidi->endpoints[0]);
2343 	if (err < 0)
2344 		return err;
2345 
2346 	ep_info.in_ep = get_endpoint(hostif, 0)->bEndpointAddress &
2347 		USB_ENDPOINT_NUMBER_MASK;
2348 	ep_info.in_interval = get_endpoint(hostif, 0)->bInterval;
2349 	ep_info.in_cables = endpoint->in_cables;
2350 	err = snd_usbmidi_in_endpoint_create(umidi, &ep_info,
2351 					     &umidi->endpoints[0]);
2352 	if (err < 0)
2353 		return err;
2354 
2355 	if (endpoint->out_cables > 0x0001) {
2356 		ep_info.out_ep = get_endpoint(hostif, 4)->bEndpointAddress &
2357 			USB_ENDPOINT_NUMBER_MASK;
2358 		ep_info.out_cables = endpoint->out_cables & 0xaaaa;
2359 		err = snd_usbmidi_out_endpoint_create(umidi, &ep_info,
2360 						      &umidi->endpoints[1]);
2361 		if (err < 0)
2362 			return err;
2363 	}
2364 
2365 	for (cable = 0; cable < 0x10; ++cable) {
2366 		if (endpoint->out_cables & (1 << cable))
2367 			snd_usbmidi_init_substream(umidi,
2368 						   SNDRV_RAWMIDI_STREAM_OUTPUT,
2369 						   cable,
2370 						   -1 /* prevent trying to find jack */,
2371 						   &umidi->endpoints[cable & 1].out->ports[cable].substream);
2372 		if (endpoint->in_cables & (1 << cable))
2373 			snd_usbmidi_init_substream(umidi,
2374 						   SNDRV_RAWMIDI_STREAM_INPUT,
2375 						   cable,
2376 						   -1 /* prevent trying to find jack */,
2377 						   &umidi->endpoints[0].in->ports[cable].substream);
2378 	}
2379 	return 0;
2380 }
2381 
2382 static const struct snd_rawmidi_global_ops snd_usbmidi_ops = {
2383 	.get_port_info = snd_usbmidi_get_port_info,
2384 };
2385 
2386 static int snd_usbmidi_create_rawmidi(struct snd_usb_midi *umidi,
2387 				      int out_ports, int in_ports)
2388 {
2389 	struct snd_rawmidi *rmidi;
2390 	int err;
2391 
2392 	err = snd_rawmidi_new(umidi->card, "USB MIDI",
2393 			      umidi->next_midi_device++,
2394 			      out_ports, in_ports, &rmidi);
2395 	if (err < 0)
2396 		return err;
2397 	strscpy(rmidi->name, umidi->card->shortname);
2398 	rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
2399 			    SNDRV_RAWMIDI_INFO_INPUT |
2400 			    SNDRV_RAWMIDI_INFO_DUPLEX;
2401 	rmidi->ops = &snd_usbmidi_ops;
2402 	rmidi->private_data = umidi;
2403 	rmidi->private_free = snd_usbmidi_rawmidi_free;
2404 	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT,
2405 			    &snd_usbmidi_output_ops);
2406 	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT,
2407 			    &snd_usbmidi_input_ops);
2408 
2409 	umidi->rmidi = rmidi;
2410 	return 0;
2411 }
2412 
2413 /*
2414  * Temporarily stop input.
2415  */
2416 void snd_usbmidi_input_stop(struct list_head *p)
2417 {
2418 	struct snd_usb_midi *umidi;
2419 	unsigned int i, j;
2420 
2421 	umidi = list_entry(p, struct snd_usb_midi, list);
2422 	if (!umidi->input_running)
2423 		return;
2424 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
2425 		struct snd_usb_midi_endpoint *ep = &umidi->endpoints[i];
2426 		if (ep->in)
2427 			for (j = 0; j < INPUT_URBS; ++j)
2428 				usb_kill_urb(ep->in->urbs[j]);
2429 	}
2430 	umidi->input_running = 0;
2431 }
2432 EXPORT_SYMBOL(snd_usbmidi_input_stop);
2433 
2434 static void snd_usbmidi_input_start_ep(struct snd_usb_midi *umidi,
2435 				       struct snd_usb_midi_in_endpoint *ep)
2436 {
2437 	unsigned int i;
2438 
2439 	if (!ep)
2440 		return;
2441 	for (i = 0; i < INPUT_URBS; ++i) {
2442 		struct urb *urb = ep->urbs[i];
2443 		scoped_guard(spinlock_irqsave, &umidi->disc_lock) {
2444 			if (!atomic_read(&urb->use_count)) {
2445 				urb->dev = ep->umidi->dev;
2446 				snd_usbmidi_submit_urb(urb, GFP_ATOMIC);
2447 			}
2448 		}
2449 	}
2450 }
2451 
2452 /*
2453  * Resume input after a call to snd_usbmidi_input_stop().
2454  */
2455 void snd_usbmidi_input_start(struct list_head *p)
2456 {
2457 	struct snd_usb_midi *umidi;
2458 	int i;
2459 
2460 	umidi = list_entry(p, struct snd_usb_midi, list);
2461 	if (umidi->input_running || !umidi->opened[1])
2462 		return;
2463 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
2464 		snd_usbmidi_input_start_ep(umidi, umidi->endpoints[i].in);
2465 	umidi->input_running = 1;
2466 }
2467 EXPORT_SYMBOL(snd_usbmidi_input_start);
2468 
2469 /*
2470  * Prepare for suspend. Typically called from the USB suspend callback.
2471  */
2472 void snd_usbmidi_suspend(struct list_head *p)
2473 {
2474 	struct snd_usb_midi *umidi;
2475 
2476 	umidi = list_entry(p, struct snd_usb_midi, list);
2477 	guard(mutex)(&umidi->mutex);
2478 	snd_usbmidi_input_stop(p);
2479 }
2480 EXPORT_SYMBOL(snd_usbmidi_suspend);
2481 
2482 /*
2483  * Resume. Typically called from the USB resume callback.
2484  */
2485 void snd_usbmidi_resume(struct list_head *p)
2486 {
2487 	struct snd_usb_midi *umidi;
2488 
2489 	umidi = list_entry(p, struct snd_usb_midi, list);
2490 	guard(mutex)(&umidi->mutex);
2491 	snd_usbmidi_input_start(p);
2492 }
2493 EXPORT_SYMBOL(snd_usbmidi_resume);
2494 
2495 /*
2496  * Creates and registers everything needed for a MIDI streaming interface.
2497  */
2498 int __snd_usbmidi_create(struct snd_card *card,
2499 			 struct usb_interface *iface,
2500 			 struct list_head *midi_list,
2501 			 const struct snd_usb_audio_quirk *quirk,
2502 			 unsigned int usb_id,
2503 			 unsigned int *num_rawmidis)
2504 {
2505 	struct snd_usb_midi *umidi;
2506 	struct snd_usb_midi_endpoint_info endpoints[MIDI_MAX_ENDPOINTS];
2507 	int out_ports, in_ports;
2508 	int i, err;
2509 
2510 	umidi = kzalloc(sizeof(*umidi), GFP_KERNEL);
2511 	if (!umidi)
2512 		return -ENOMEM;
2513 	umidi->dev = interface_to_usbdev(iface);
2514 	umidi->card = card;
2515 	umidi->iface = iface;
2516 	umidi->quirk = quirk;
2517 	umidi->usb_protocol_ops = &snd_usbmidi_standard_ops;
2518 	if (num_rawmidis)
2519 		umidi->next_midi_device = *num_rawmidis;
2520 	spin_lock_init(&umidi->disc_lock);
2521 	init_rwsem(&umidi->disc_rwsem);
2522 	mutex_init(&umidi->mutex);
2523 	if (!usb_id)
2524 		usb_id = USB_ID(le16_to_cpu(umidi->dev->descriptor.idVendor),
2525 			       le16_to_cpu(umidi->dev->descriptor.idProduct));
2526 	umidi->usb_id = usb_id;
2527 	timer_setup(&umidi->error_timer, snd_usbmidi_error_timer, 0);
2528 
2529 	/* detect the endpoint(s) to use */
2530 	memset(endpoints, 0, sizeof(endpoints));
2531 	switch (quirk ? quirk->type : QUIRK_MIDI_STANDARD_INTERFACE) {
2532 	case QUIRK_MIDI_STANDARD_INTERFACE:
2533 		err = snd_usbmidi_get_ms_info(umidi, endpoints);
2534 		if (umidi->usb_id == USB_ID(0x0763, 0x0150)) /* M-Audio Uno */
2535 			umidi->usb_protocol_ops =
2536 				&snd_usbmidi_maudio_broken_running_status_ops;
2537 		break;
2538 	case QUIRK_MIDI_US122L:
2539 		umidi->usb_protocol_ops = &snd_usbmidi_122l_ops;
2540 		fallthrough;
2541 	case QUIRK_MIDI_FIXED_ENDPOINT:
2542 		memcpy(&endpoints[0], quirk->data,
2543 		       sizeof(struct snd_usb_midi_endpoint_info));
2544 		err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
2545 		break;
2546 	case QUIRK_MIDI_YAMAHA:
2547 		err = snd_usbmidi_detect_yamaha(umidi, &endpoints[0]);
2548 		break;
2549 	case QUIRK_MIDI_ROLAND:
2550 		err = snd_usbmidi_detect_roland(umidi, &endpoints[0]);
2551 		break;
2552 	case QUIRK_MIDI_MIDIMAN:
2553 		umidi->usb_protocol_ops = &snd_usbmidi_midiman_ops;
2554 		memcpy(&endpoints[0], quirk->data,
2555 		       sizeof(struct snd_usb_midi_endpoint_info));
2556 		err = 0;
2557 		break;
2558 	case QUIRK_MIDI_NOVATION:
2559 		umidi->usb_protocol_ops = &snd_usbmidi_novation_ops;
2560 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2561 		break;
2562 	case QUIRK_MIDI_RAW_BYTES:
2563 		umidi->usb_protocol_ops = &snd_usbmidi_raw_ops;
2564 		/*
2565 		 * Interface 1 contains isochronous endpoints, but with the same
2566 		 * numbers as in interface 0.  Since it is interface 1 that the
2567 		 * USB core has most recently seen, these descriptors are now
2568 		 * associated with the endpoint numbers.  This will foul up our
2569 		 * attempts to submit bulk/interrupt URBs to the endpoints in
2570 		 * interface 0, so we have to make sure that the USB core looks
2571 		 * again at interface 0 by calling usb_set_interface() on it.
2572 		 */
2573 		if (umidi->usb_id == USB_ID(0x07fd, 0x0001)) /* MOTU Fastlane */
2574 			usb_set_interface(umidi->dev, 0, 0);
2575 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2576 		break;
2577 	case QUIRK_MIDI_EMAGIC:
2578 		umidi->usb_protocol_ops = &snd_usbmidi_emagic_ops;
2579 		memcpy(&endpoints[0], quirk->data,
2580 		       sizeof(struct snd_usb_midi_endpoint_info));
2581 		err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
2582 		break;
2583 	case QUIRK_MIDI_CME:
2584 		umidi->usb_protocol_ops = &snd_usbmidi_cme_ops;
2585 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2586 		break;
2587 	case QUIRK_MIDI_AKAI:
2588 		umidi->usb_protocol_ops = &snd_usbmidi_akai_ops;
2589 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2590 		/* endpoint 1 is input-only */
2591 		endpoints[1].out_cables = 0;
2592 		break;
2593 	case QUIRK_MIDI_FTDI:
2594 		umidi->usb_protocol_ops = &snd_usbmidi_ftdi_ops;
2595 
2596 		/* set baud rate to 31250 (48 MHz / 16 / 96) */
2597 		err = usb_control_msg(umidi->dev, usb_sndctrlpipe(umidi->dev, 0),
2598 				      3, 0x40, 0x60, 0, NULL, 0, 1000);
2599 		if (err < 0)
2600 			break;
2601 
2602 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2603 		break;
2604 	case QUIRK_MIDI_CH345:
2605 		umidi->usb_protocol_ops = &snd_usbmidi_ch345_broken_sysex_ops;
2606 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2607 		break;
2608 	default:
2609 		dev_err(&umidi->dev->dev, "invalid quirk type %d\n",
2610 			quirk->type);
2611 		err = -ENXIO;
2612 		break;
2613 	}
2614 	if (err < 0)
2615 		goto free_midi;
2616 
2617 	/* create rawmidi device */
2618 	out_ports = 0;
2619 	in_ports = 0;
2620 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
2621 		out_ports += hweight16(endpoints[i].out_cables);
2622 		in_ports += hweight16(endpoints[i].in_cables);
2623 	}
2624 	err = snd_usbmidi_create_rawmidi(umidi, out_ports, in_ports);
2625 	if (err < 0)
2626 		goto free_midi;
2627 
2628 	/* create endpoint/port structures */
2629 	if (quirk && quirk->type == QUIRK_MIDI_MIDIMAN)
2630 		err = snd_usbmidi_create_endpoints_midiman(umidi, &endpoints[0]);
2631 	else
2632 		err = snd_usbmidi_create_endpoints(umidi, endpoints);
2633 	if (err < 0)
2634 		goto exit;
2635 
2636 	usb_autopm_get_interface_no_resume(umidi->iface);
2637 
2638 	list_add_tail(&umidi->list, midi_list);
2639 	if (num_rawmidis)
2640 		*num_rawmidis = umidi->next_midi_device;
2641 	return 0;
2642 
2643 free_midi:
2644 	kfree(umidi);
2645 exit:
2646 	return err;
2647 }
2648 EXPORT_SYMBOL(__snd_usbmidi_create);
2649