xref: /linux/sound/usb/midi.c (revision c20313e98b04ce543936431b6122dd639d3a8346)
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 port0 = ep->current_port;
703 	int i;
704 
705 	for (i = 0; i < 0x10; ++i) {
706 		int portnum = (port0 + i) & 15;
707 		struct usbmidi_out_port *port = &ep->ports[portnum];
708 
709 		if (!port->active)
710 			continue;
711 		while (urb->transfer_buffer_length + 3 < ep->max_transfer) {
712 			uint8_t b;
713 
714 			if (snd_rawmidi_transmit(port->substream, &b, 1) != 1) {
715 				port->active = 0;
716 				break;
717 			}
718 			snd_usbmidi_transmit_byte(port, b, urb);
719 		}
720 	}
721 	ep->current_port = (port0 + 1) & 15;
722 }
723 
724 static const struct usb_protocol_ops snd_usbmidi_standard_ops = {
725 	.input = snd_usbmidi_standard_input,
726 	.output = snd_usbmidi_standard_output,
727 	.output_packet = snd_usbmidi_output_standard_packet,
728 };
729 
730 static const struct usb_protocol_ops snd_usbmidi_midiman_ops = {
731 	.input = snd_usbmidi_midiman_input,
732 	.output = snd_usbmidi_standard_output,
733 	.output_packet = snd_usbmidi_output_midiman_packet,
734 };
735 
736 static const
737 struct usb_protocol_ops snd_usbmidi_maudio_broken_running_status_ops = {
738 	.input = snd_usbmidi_maudio_broken_running_status_input,
739 	.output = snd_usbmidi_standard_output,
740 	.output_packet = snd_usbmidi_output_standard_packet,
741 };
742 
743 static const struct usb_protocol_ops snd_usbmidi_cme_ops = {
744 	.input = snd_usbmidi_cme_input,
745 	.output = snd_usbmidi_standard_output,
746 	.output_packet = snd_usbmidi_output_standard_packet,
747 };
748 
749 static const struct usb_protocol_ops snd_usbmidi_ch345_broken_sysex_ops = {
750 	.input = ch345_broken_sysex_input,
751 	.output = snd_usbmidi_standard_output,
752 	.output_packet = snd_usbmidi_output_standard_packet,
753 };
754 
755 /*
756  * AKAI MPD16 protocol:
757  *
758  * For control port (endpoint 1):
759  * ==============================
760  * One or more chunks consisting of first byte of (0x10 | msg_len) and then a
761  * SysEx message (msg_len=9 bytes long).
762  *
763  * For data port (endpoint 2):
764  * ===========================
765  * One or more chunks consisting of first byte of (0x20 | msg_len) and then a
766  * MIDI message (msg_len bytes long)
767  *
768  * Messages sent: Active Sense, Note On, Poly Pressure, Control Change.
769  */
770 static void snd_usbmidi_akai_input(struct snd_usb_midi_in_endpoint *ep,
771 				   uint8_t *buffer, int buffer_length)
772 {
773 	unsigned int pos = 0;
774 	unsigned int len = (unsigned int)buffer_length;
775 	while (pos < len) {
776 		unsigned int port = (buffer[pos] >> 4) - 1;
777 		unsigned int msg_len = buffer[pos] & 0x0f;
778 		pos++;
779 		if (pos + msg_len <= len && port < 2)
780 			snd_usbmidi_input_data(ep, 0, &buffer[pos], msg_len);
781 		pos += msg_len;
782 	}
783 }
784 
785 #define MAX_AKAI_SYSEX_LEN 9
786 
787 static void snd_usbmidi_akai_output(struct snd_usb_midi_out_endpoint *ep,
788 				    struct urb *urb)
789 {
790 	uint8_t *msg;
791 	int pos, end, count, buf_end;
792 	uint8_t tmp[MAX_AKAI_SYSEX_LEN];
793 	struct snd_rawmidi_substream *substream = ep->ports[0].substream;
794 
795 	if (!ep->ports[0].active)
796 		return;
797 
798 	msg = urb->transfer_buffer + urb->transfer_buffer_length;
799 	buf_end = ep->max_transfer - MAX_AKAI_SYSEX_LEN - 1;
800 	if (buf_end <= 0)
801 		return;
802 
803 	/* only try adding more data when there's space for at least 1 SysEx */
804 	while (urb->transfer_buffer_length < buf_end) {
805 		count = snd_rawmidi_transmit_peek(substream,
806 						  tmp, MAX_AKAI_SYSEX_LEN);
807 		if (!count) {
808 			ep->ports[0].active = 0;
809 			return;
810 		}
811 		/* try to skip non-SysEx data */
812 		for (pos = 0; pos < count && tmp[pos] != 0xF0; pos++)
813 			;
814 
815 		if (pos > 0) {
816 			snd_rawmidi_transmit_ack(substream, pos);
817 			continue;
818 		}
819 
820 		/* look for the start or end marker */
821 		for (end = 1; end < count && tmp[end] < 0xF0; end++)
822 			;
823 
824 		/* next SysEx started before the end of current one */
825 		if (end < count && tmp[end] == 0xF0) {
826 			/* it's incomplete - drop it */
827 			snd_rawmidi_transmit_ack(substream, end);
828 			continue;
829 		}
830 		/* SysEx complete */
831 		if (end < count && tmp[end] == 0xF7) {
832 			/* queue it, ack it, and get the next one */
833 			count = end + 1;
834 			msg[0] = 0x10 | count;
835 			memcpy(&msg[1], tmp, count);
836 			snd_rawmidi_transmit_ack(substream, count);
837 			urb->transfer_buffer_length += count + 1;
838 			msg += count + 1;
839 			continue;
840 		}
841 		/* less than 9 bytes and no end byte - wait for more */
842 		if (count < MAX_AKAI_SYSEX_LEN) {
843 			ep->ports[0].active = 0;
844 			return;
845 		}
846 		/* 9 bytes and no end marker in sight - malformed, skip it */
847 		snd_rawmidi_transmit_ack(substream, count);
848 	}
849 }
850 
851 static const struct usb_protocol_ops snd_usbmidi_akai_ops = {
852 	.input = snd_usbmidi_akai_input,
853 	.output = snd_usbmidi_akai_output,
854 };
855 
856 /*
857  * Novation USB MIDI protocol: number of data bytes is in the first byte
858  * (when receiving) (+1!) or in the second byte (when sending); data begins
859  * at the third byte.
860  */
861 
862 static void snd_usbmidi_novation_input(struct snd_usb_midi_in_endpoint *ep,
863 				       uint8_t *buffer, int buffer_length)
864 {
865 	if (buffer_length < 2 || !buffer[0] || buffer_length < buffer[0] + 1)
866 		return;
867 	snd_usbmidi_input_data(ep, 0, &buffer[2], buffer[0] - 1);
868 }
869 
870 static void snd_usbmidi_novation_output(struct snd_usb_midi_out_endpoint *ep,
871 					struct urb *urb)
872 {
873 	uint8_t *transfer_buffer;
874 	int count;
875 
876 	if (!ep->ports[0].active)
877 		return;
878 	if (ep->max_transfer < 3)
879 		return;
880 	transfer_buffer = urb->transfer_buffer;
881 	count = snd_rawmidi_transmit(ep->ports[0].substream,
882 				     &transfer_buffer[2],
883 				     ep->max_transfer - 2);
884 	if (count < 1) {
885 		ep->ports[0].active = 0;
886 		return;
887 	}
888 	transfer_buffer[0] = 0;
889 	transfer_buffer[1] = count;
890 	urb->transfer_buffer_length = 2 + count;
891 }
892 
893 static const struct usb_protocol_ops snd_usbmidi_novation_ops = {
894 	.input = snd_usbmidi_novation_input,
895 	.output = snd_usbmidi_novation_output,
896 };
897 
898 /*
899  * "raw" protocol: just move raw MIDI bytes from/to the endpoint
900  */
901 
902 static void snd_usbmidi_raw_input(struct snd_usb_midi_in_endpoint *ep,
903 				  uint8_t *buffer, int buffer_length)
904 {
905 	snd_usbmidi_input_data(ep, 0, buffer, buffer_length);
906 }
907 
908 static void snd_usbmidi_raw_output(struct snd_usb_midi_out_endpoint *ep,
909 				   struct urb *urb)
910 {
911 	int count;
912 
913 	if (!ep->ports[0].active)
914 		return;
915 	count = snd_rawmidi_transmit(ep->ports[0].substream,
916 				     urb->transfer_buffer,
917 				     ep->max_transfer);
918 	if (count < 1) {
919 		ep->ports[0].active = 0;
920 		return;
921 	}
922 	urb->transfer_buffer_length = count;
923 }
924 
925 static const struct usb_protocol_ops snd_usbmidi_raw_ops = {
926 	.input = snd_usbmidi_raw_input,
927 	.output = snd_usbmidi_raw_output,
928 };
929 
930 /*
931  * FTDI protocol: raw MIDI bytes, but input packets have two modem status bytes.
932  */
933 
934 static void snd_usbmidi_ftdi_input(struct snd_usb_midi_in_endpoint *ep,
935 				   uint8_t *buffer, int buffer_length)
936 {
937 	if (buffer_length > 2)
938 		snd_usbmidi_input_data(ep, 0, buffer + 2, buffer_length - 2);
939 }
940 
941 static const struct usb_protocol_ops snd_usbmidi_ftdi_ops = {
942 	.input = snd_usbmidi_ftdi_input,
943 	.output = snd_usbmidi_raw_output,
944 };
945 
946 static void snd_usbmidi_us122l_input(struct snd_usb_midi_in_endpoint *ep,
947 				     uint8_t *buffer, int buffer_length)
948 {
949 	if (buffer_length != 9)
950 		return;
951 	buffer_length = 8;
952 	while (buffer_length && buffer[buffer_length - 1] == 0xFD)
953 		buffer_length--;
954 	if (buffer_length)
955 		snd_usbmidi_input_data(ep, 0, buffer, buffer_length);
956 }
957 
958 static void snd_usbmidi_us122l_output(struct snd_usb_midi_out_endpoint *ep,
959 				      struct urb *urb)
960 {
961 	int count;
962 
963 	if (!ep->ports[0].active)
964 		return;
965 	switch (snd_usb_get_speed(ep->umidi->dev)) {
966 	case USB_SPEED_HIGH:
967 	case USB_SPEED_SUPER:
968 	case USB_SPEED_SUPER_PLUS:
969 		count = 1;
970 		break;
971 	default:
972 		count = 2;
973 	}
974 	count = snd_rawmidi_transmit(ep->ports[0].substream,
975 				     urb->transfer_buffer,
976 				     count);
977 	if (count < 1) {
978 		ep->ports[0].active = 0;
979 		return;
980 	}
981 
982 	memset(urb->transfer_buffer + count, 0xFD, ep->max_transfer - count);
983 	urb->transfer_buffer_length = ep->max_transfer;
984 }
985 
986 static const struct usb_protocol_ops snd_usbmidi_122l_ops = {
987 	.input = snd_usbmidi_us122l_input,
988 	.output = snd_usbmidi_us122l_output,
989 };
990 
991 /*
992  * Emagic USB MIDI protocol: raw MIDI with "F5 xx" port switching.
993  */
994 
995 static void snd_usbmidi_emagic_init_out(struct snd_usb_midi_out_endpoint *ep)
996 {
997 	static const u8 init_data[] = {
998 		/* initialization magic: "get version" */
999 		0xf0,
1000 		0x00, 0x20, 0x31,	/* Emagic */
1001 		0x64,			/* Unitor8 */
1002 		0x0b,			/* version number request */
1003 		0x00,			/* command version */
1004 		0x00,			/* EEPROM, box 0 */
1005 		0xf7
1006 	};
1007 	send_bulk_static_data(ep, init_data, sizeof(init_data));
1008 	/* while we're at it, pour on more magic */
1009 	send_bulk_static_data(ep, init_data, sizeof(init_data));
1010 }
1011 
1012 static void snd_usbmidi_emagic_finish_out(struct snd_usb_midi_out_endpoint *ep)
1013 {
1014 	static const u8 finish_data[] = {
1015 		/* switch to patch mode with last preset */
1016 		0xf0,
1017 		0x00, 0x20, 0x31,	/* Emagic */
1018 		0x64,			/* Unitor8 */
1019 		0x10,			/* patch switch command */
1020 		0x00,			/* command version */
1021 		0x7f,			/* to all boxes */
1022 		0x40,			/* last preset in EEPROM */
1023 		0xf7
1024 	};
1025 	send_bulk_static_data(ep, finish_data, sizeof(finish_data));
1026 }
1027 
1028 static void snd_usbmidi_emagic_input(struct snd_usb_midi_in_endpoint *ep,
1029 				     uint8_t *buffer, int buffer_length)
1030 {
1031 	int i;
1032 
1033 	/* FF indicates end of valid data */
1034 	for (i = 0; i < buffer_length; ++i)
1035 		if (buffer[i] == 0xff) {
1036 			buffer_length = i;
1037 			break;
1038 		}
1039 
1040 	/* handle F5 at end of last buffer */
1041 	if (ep->seen_f5)
1042 		goto switch_port;
1043 
1044 	while (buffer_length > 0) {
1045 		/* determine size of data until next F5 */
1046 		for (i = 0; i < buffer_length; ++i)
1047 			if (buffer[i] == 0xf5)
1048 				break;
1049 		snd_usbmidi_input_data(ep, ep->current_port, buffer, i);
1050 		buffer += i;
1051 		buffer_length -= i;
1052 
1053 		if (buffer_length <= 0)
1054 			break;
1055 		/* assert(buffer[0] == 0xf5); */
1056 		ep->seen_f5 = 1;
1057 		++buffer;
1058 		--buffer_length;
1059 
1060 	switch_port:
1061 		if (buffer_length <= 0)
1062 			break;
1063 		if (buffer[0] < 0x80) {
1064 			ep->current_port = (buffer[0] - 1) & 15;
1065 			++buffer;
1066 			--buffer_length;
1067 		}
1068 		ep->seen_f5 = 0;
1069 	}
1070 }
1071 
1072 static void snd_usbmidi_emagic_output(struct snd_usb_midi_out_endpoint *ep,
1073 				      struct urb *urb)
1074 {
1075 	int port0 = ep->current_port;
1076 	uint8_t *buf = urb->transfer_buffer;
1077 	int buf_free = ep->max_transfer;
1078 	int length, i;
1079 
1080 	for (i = 0; i < 0x10; ++i) {
1081 		/* round-robin, starting at the last current port */
1082 		int portnum = (port0 + i) & 15;
1083 		struct usbmidi_out_port *port = &ep->ports[portnum];
1084 
1085 		if (!port->active)
1086 			continue;
1087 		if (snd_rawmidi_transmit_peek(port->substream, buf, 1) != 1) {
1088 			port->active = 0;
1089 			continue;
1090 		}
1091 
1092 		if (portnum != ep->current_port) {
1093 			if (buf_free < 2)
1094 				break;
1095 			ep->current_port = portnum;
1096 			buf[0] = 0xf5;
1097 			buf[1] = (portnum + 1) & 15;
1098 			buf += 2;
1099 			buf_free -= 2;
1100 		}
1101 
1102 		if (buf_free < 1)
1103 			break;
1104 		length = snd_rawmidi_transmit(port->substream, buf, buf_free);
1105 		if (length > 0) {
1106 			buf += length;
1107 			buf_free -= length;
1108 			if (buf_free < 1)
1109 				break;
1110 		}
1111 	}
1112 	if (buf_free < ep->max_transfer && buf_free > 0) {
1113 		*buf = 0xff;
1114 		--buf_free;
1115 	}
1116 	urb->transfer_buffer_length = ep->max_transfer - buf_free;
1117 }
1118 
1119 static const struct usb_protocol_ops snd_usbmidi_emagic_ops = {
1120 	.input = snd_usbmidi_emagic_input,
1121 	.output = snd_usbmidi_emagic_output,
1122 	.init_out_endpoint = snd_usbmidi_emagic_init_out,
1123 	.finish_out_endpoint = snd_usbmidi_emagic_finish_out,
1124 };
1125 
1126 
1127 static void update_roland_altsetting(struct snd_usb_midi *umidi)
1128 {
1129 	struct usb_interface *intf;
1130 	struct usb_host_interface *hostif;
1131 	struct usb_interface_descriptor *intfd;
1132 	int is_light_load;
1133 
1134 	intf = umidi->iface;
1135 	is_light_load = intf->cur_altsetting != intf->altsetting;
1136 	if (umidi->roland_load_ctl->private_value == is_light_load)
1137 		return;
1138 	hostif = &intf->altsetting[umidi->roland_load_ctl->private_value];
1139 	intfd = get_iface_desc(hostif);
1140 	snd_usbmidi_input_stop(&umidi->list);
1141 	usb_set_interface(umidi->dev, intfd->bInterfaceNumber,
1142 			  intfd->bAlternateSetting);
1143 	snd_usbmidi_input_start(&umidi->list);
1144 }
1145 
1146 static int substream_open(struct snd_rawmidi_substream *substream, int dir,
1147 			  int open)
1148 {
1149 	struct snd_usb_midi *umidi = substream->rmidi->private_data;
1150 	struct snd_kcontrol *ctl;
1151 
1152 	guard(rwsem_read)(&umidi->disc_rwsem);
1153 	if (umidi->disconnected)
1154 		return open ? -ENODEV : 0;
1155 
1156 	guard(mutex)(&umidi->mutex);
1157 	if (open) {
1158 		if (!umidi->opened[0] && !umidi->opened[1]) {
1159 			if (umidi->roland_load_ctl) {
1160 				ctl = umidi->roland_load_ctl;
1161 				ctl->vd[0].access |=
1162 					SNDRV_CTL_ELEM_ACCESS_INACTIVE;
1163 				snd_ctl_notify(umidi->card,
1164 				       SNDRV_CTL_EVENT_MASK_INFO, &ctl->id);
1165 				update_roland_altsetting(umidi);
1166 			}
1167 		}
1168 		umidi->opened[dir]++;
1169 		if (umidi->opened[1])
1170 			snd_usbmidi_input_start(&umidi->list);
1171 	} else {
1172 		umidi->opened[dir]--;
1173 		if (!umidi->opened[1])
1174 			snd_usbmidi_input_stop(&umidi->list);
1175 		if (!umidi->opened[0] && !umidi->opened[1]) {
1176 			if (umidi->roland_load_ctl) {
1177 				ctl = umidi->roland_load_ctl;
1178 				ctl->vd[0].access &=
1179 					~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
1180 				snd_ctl_notify(umidi->card,
1181 				       SNDRV_CTL_EVENT_MASK_INFO, &ctl->id);
1182 			}
1183 		}
1184 	}
1185 	return 0;
1186 }
1187 
1188 static int snd_usbmidi_output_open(struct snd_rawmidi_substream *substream)
1189 {
1190 	struct snd_usb_midi *umidi = substream->rmidi->private_data;
1191 	struct usbmidi_out_port *port = NULL;
1192 	int i, j;
1193 
1194 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
1195 		if (umidi->endpoints[i].out)
1196 			for (j = 0; j < 0x10; ++j)
1197 				if (umidi->endpoints[i].out->ports[j].substream == substream) {
1198 					port = &umidi->endpoints[i].out->ports[j];
1199 					break;
1200 				}
1201 	if (!port)
1202 		return -ENXIO;
1203 
1204 	substream->runtime->private_data = port;
1205 	port->state = STATE_UNKNOWN;
1206 	return substream_open(substream, 0, 1);
1207 }
1208 
1209 static int snd_usbmidi_output_close(struct snd_rawmidi_substream *substream)
1210 {
1211 	struct usbmidi_out_port *port = substream->runtime->private_data;
1212 
1213 	flush_work(&port->ep->work);
1214 	return substream_open(substream, 0, 0);
1215 }
1216 
1217 static void snd_usbmidi_output_trigger(struct snd_rawmidi_substream *substream,
1218 				       int up)
1219 {
1220 	struct usbmidi_out_port *port =
1221 		(struct usbmidi_out_port *)substream->runtime->private_data;
1222 
1223 	port->active = up;
1224 	if (up) {
1225 		if (port->ep->umidi->disconnected) {
1226 			/* gobble up remaining bytes to prevent wait in
1227 			 * snd_rawmidi_drain_output */
1228 			snd_rawmidi_proceed(substream);
1229 			return;
1230 		}
1231 		queue_work(system_highpri_wq, &port->ep->work);
1232 	}
1233 }
1234 
1235 static void snd_usbmidi_output_drain(struct snd_rawmidi_substream *substream)
1236 {
1237 	struct usbmidi_out_port *port = substream->runtime->private_data;
1238 	struct snd_usb_midi_out_endpoint *ep = port->ep;
1239 	unsigned int drain_urbs;
1240 	DEFINE_WAIT(wait);
1241 	long timeout = msecs_to_jiffies(50);
1242 
1243 	if (ep->umidi->disconnected)
1244 		return;
1245 	/*
1246 	 * The substream buffer is empty, but some data might still be in the
1247 	 * currently active URBs, so we have to wait for those to complete.
1248 	 */
1249 	spin_lock_irq(&ep->buffer_lock);
1250 	drain_urbs = ep->active_urbs;
1251 	if (drain_urbs) {
1252 		ep->drain_urbs |= drain_urbs;
1253 		do {
1254 			prepare_to_wait(&ep->drain_wait, &wait,
1255 					TASK_UNINTERRUPTIBLE);
1256 			spin_unlock_irq(&ep->buffer_lock);
1257 			timeout = schedule_timeout(timeout);
1258 			spin_lock_irq(&ep->buffer_lock);
1259 			drain_urbs &= ep->drain_urbs;
1260 		} while (drain_urbs && timeout);
1261 		finish_wait(&ep->drain_wait, &wait);
1262 	}
1263 	port->active = 0;
1264 	spin_unlock_irq(&ep->buffer_lock);
1265 }
1266 
1267 static int snd_usbmidi_input_open(struct snd_rawmidi_substream *substream)
1268 {
1269 	return substream_open(substream, 1, 1);
1270 }
1271 
1272 static int snd_usbmidi_input_close(struct snd_rawmidi_substream *substream)
1273 {
1274 	return substream_open(substream, 1, 0);
1275 }
1276 
1277 static void snd_usbmidi_input_trigger(struct snd_rawmidi_substream *substream,
1278 				      int up)
1279 {
1280 	struct snd_usb_midi *umidi = substream->rmidi->private_data;
1281 
1282 	if (up)
1283 		set_bit(substream->number, &umidi->input_triggered);
1284 	else
1285 		clear_bit(substream->number, &umidi->input_triggered);
1286 }
1287 
1288 static const struct snd_rawmidi_ops snd_usbmidi_output_ops = {
1289 	.open = snd_usbmidi_output_open,
1290 	.close = snd_usbmidi_output_close,
1291 	.trigger = snd_usbmidi_output_trigger,
1292 	.drain = snd_usbmidi_output_drain,
1293 };
1294 
1295 static const struct snd_rawmidi_ops snd_usbmidi_input_ops = {
1296 	.open = snd_usbmidi_input_open,
1297 	.close = snd_usbmidi_input_close,
1298 	.trigger = snd_usbmidi_input_trigger
1299 };
1300 
1301 static void free_urb_and_buffer(struct snd_usb_midi *umidi, struct urb *urb,
1302 				unsigned int buffer_length)
1303 {
1304 	usb_free_coherent(umidi->dev, buffer_length,
1305 			  urb->transfer_buffer, urb->transfer_dma);
1306 	usb_free_urb(urb);
1307 }
1308 
1309 /*
1310  * Frees an input endpoint.
1311  * May be called when ep hasn't been initialized completely.
1312  */
1313 static void snd_usbmidi_in_endpoint_delete(struct snd_usb_midi_in_endpoint *ep)
1314 {
1315 	unsigned int i;
1316 
1317 	for (i = 0; i < INPUT_URBS; ++i)
1318 		if (ep->urbs[i])
1319 			free_urb_and_buffer(ep->umidi, ep->urbs[i],
1320 					    ep->urbs[i]->transfer_buffer_length);
1321 	kfree(ep);
1322 }
1323 
1324 /*
1325  * Creates an input endpoint.
1326  */
1327 static int snd_usbmidi_in_endpoint_create(struct snd_usb_midi *umidi,
1328 					  struct snd_usb_midi_endpoint_info *ep_info,
1329 					  struct snd_usb_midi_endpoint *rep)
1330 {
1331 	struct snd_usb_midi_in_endpoint *ep;
1332 	void *buffer;
1333 	unsigned int pipe;
1334 	int length;
1335 	unsigned int i;
1336 	int err;
1337 
1338 	rep->in = NULL;
1339 	ep = kzalloc_obj(*ep);
1340 	if (!ep)
1341 		return -ENOMEM;
1342 	ep->umidi = umidi;
1343 
1344 	for (i = 0; i < INPUT_URBS; ++i) {
1345 		ep->urbs[i] = usb_alloc_urb(0, GFP_KERNEL);
1346 		if (!ep->urbs[i]) {
1347 			err = -ENOMEM;
1348 			goto error;
1349 		}
1350 	}
1351 	if (ep_info->in_interval)
1352 		pipe = usb_rcvintpipe(umidi->dev, ep_info->in_ep);
1353 	else
1354 		pipe = usb_rcvbulkpipe(umidi->dev, ep_info->in_ep);
1355 	length = usb_maxpacket(umidi->dev, pipe);
1356 	for (i = 0; i < INPUT_URBS; ++i) {
1357 		buffer = usb_alloc_coherent(umidi->dev, length, GFP_KERNEL,
1358 					    &ep->urbs[i]->transfer_dma);
1359 		if (!buffer) {
1360 			err = -ENOMEM;
1361 			goto error;
1362 		}
1363 		if (ep_info->in_interval)
1364 			usb_fill_int_urb(ep->urbs[i], umidi->dev,
1365 					 pipe, buffer, length,
1366 					 snd_usbmidi_in_urb_complete,
1367 					 ep, ep_info->in_interval);
1368 		else
1369 			usb_fill_bulk_urb(ep->urbs[i], umidi->dev,
1370 					  pipe, buffer, length,
1371 					  snd_usbmidi_in_urb_complete, ep);
1372 		ep->urbs[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1373 		err = usb_urb_ep_type_check(ep->urbs[i]);
1374 		if (err < 0) {
1375 			dev_err(&umidi->dev->dev, "invalid MIDI in EP %x\n",
1376 				ep_info->in_ep);
1377 			goto error;
1378 		}
1379 	}
1380 
1381 	rep->in = ep;
1382 	return 0;
1383 
1384  error:
1385 	snd_usbmidi_in_endpoint_delete(ep);
1386 	return err;
1387 }
1388 
1389 /*
1390  * Frees an output endpoint.
1391  * May be called when ep hasn't been initialized completely.
1392  */
1393 static void snd_usbmidi_out_endpoint_clear(struct snd_usb_midi_out_endpoint *ep)
1394 {
1395 	unsigned int i;
1396 
1397 	for (i = 0; i < OUTPUT_URBS; ++i)
1398 		if (ep->urbs[i].urb) {
1399 			free_urb_and_buffer(ep->umidi, ep->urbs[i].urb,
1400 					    ep->max_transfer);
1401 			ep->urbs[i].urb = NULL;
1402 		}
1403 }
1404 
1405 static void snd_usbmidi_out_endpoint_delete(struct snd_usb_midi_out_endpoint *ep)
1406 {
1407 	snd_usbmidi_out_endpoint_clear(ep);
1408 	kfree(ep);
1409 }
1410 
1411 /*
1412  * Creates an output endpoint, and initializes output ports.
1413  */
1414 static int snd_usbmidi_out_endpoint_create(struct snd_usb_midi *umidi,
1415 					   struct snd_usb_midi_endpoint_info *ep_info,
1416 					   struct snd_usb_midi_endpoint *rep)
1417 {
1418 	struct snd_usb_midi_out_endpoint *ep;
1419 	unsigned int i;
1420 	unsigned int pipe;
1421 	void *buffer;
1422 	int err;
1423 
1424 	rep->out = NULL;
1425 	ep = kzalloc_obj(*ep);
1426 	if (!ep)
1427 		return -ENOMEM;
1428 	ep->umidi = umidi;
1429 
1430 	for (i = 0; i < OUTPUT_URBS; ++i) {
1431 		ep->urbs[i].urb = usb_alloc_urb(0, GFP_KERNEL);
1432 		if (!ep->urbs[i].urb) {
1433 			err = -ENOMEM;
1434 			goto error;
1435 		}
1436 		ep->urbs[i].ep = ep;
1437 	}
1438 	if (ep_info->out_interval)
1439 		pipe = usb_sndintpipe(umidi->dev, ep_info->out_ep);
1440 	else
1441 		pipe = usb_sndbulkpipe(umidi->dev, ep_info->out_ep);
1442 	switch (umidi->usb_id) {
1443 	default:
1444 		ep->max_transfer = usb_maxpacket(umidi->dev, pipe);
1445 		break;
1446 		/*
1447 		 * Various chips declare a packet size larger than 4 bytes, but
1448 		 * do not actually work with larger packets:
1449 		 */
1450 	case USB_ID(0x0a67, 0x5011): /* Medeli DD305 */
1451 	case USB_ID(0x0a92, 0x1020): /* ESI M4U */
1452 	case USB_ID(0x1430, 0x474b): /* RedOctane GH MIDI INTERFACE */
1453 	case USB_ID(0x15ca, 0x0101): /* Textech USB Midi Cable */
1454 	case USB_ID(0x15ca, 0x1806): /* Textech USB Midi Cable */
1455 	case USB_ID(0x1a86, 0x752d): /* QinHeng CH345 "USB2.0-MIDI" */
1456 	case USB_ID(0xfc08, 0x0101): /* Unknown vendor Cable */
1457 		ep->max_transfer = 4;
1458 		break;
1459 		/*
1460 		 * Some devices only work with 9 bytes packet size:
1461 		 */
1462 	case USB_ID(0x0644, 0x800e): /* Tascam US-122L */
1463 	case USB_ID(0x0644, 0x800f): /* Tascam US-144 */
1464 		ep->max_transfer = 9;
1465 		break;
1466 	}
1467 	for (i = 0; i < OUTPUT_URBS; ++i) {
1468 		buffer = usb_alloc_coherent(umidi->dev,
1469 					    ep->max_transfer, GFP_KERNEL,
1470 					    &ep->urbs[i].urb->transfer_dma);
1471 		if (!buffer) {
1472 			err = -ENOMEM;
1473 			goto error;
1474 		}
1475 		if (ep_info->out_interval)
1476 			usb_fill_int_urb(ep->urbs[i].urb, umidi->dev,
1477 					 pipe, buffer, ep->max_transfer,
1478 					 snd_usbmidi_out_urb_complete,
1479 					 &ep->urbs[i], ep_info->out_interval);
1480 		else
1481 			usb_fill_bulk_urb(ep->urbs[i].urb, umidi->dev,
1482 					  pipe, buffer, ep->max_transfer,
1483 					  snd_usbmidi_out_urb_complete,
1484 					  &ep->urbs[i]);
1485 		err = usb_urb_ep_type_check(ep->urbs[i].urb);
1486 		if (err < 0) {
1487 			dev_err(&umidi->dev->dev, "invalid MIDI out EP %x\n",
1488 				ep_info->out_ep);
1489 			goto error;
1490 		}
1491 		ep->urbs[i].urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1492 	}
1493 
1494 	spin_lock_init(&ep->buffer_lock);
1495 	INIT_WORK(&ep->work, snd_usbmidi_out_work);
1496 	init_waitqueue_head(&ep->drain_wait);
1497 
1498 	for (i = 0; i < 0x10; ++i)
1499 		if (ep_info->out_cables & (1 << i)) {
1500 			ep->ports[i].ep = ep;
1501 			ep->ports[i].cable = i << 4;
1502 		}
1503 
1504 	if (umidi->usb_protocol_ops->init_out_endpoint)
1505 		umidi->usb_protocol_ops->init_out_endpoint(ep);
1506 
1507 	rep->out = ep;
1508 	return 0;
1509 
1510  error:
1511 	snd_usbmidi_out_endpoint_delete(ep);
1512 	return err;
1513 }
1514 
1515 /*
1516  * Frees everything.
1517  */
1518 static void snd_usbmidi_free(struct snd_usb_midi *umidi)
1519 {
1520 	int i;
1521 
1522 	if (!umidi->disconnected)
1523 		snd_usbmidi_disconnect(&umidi->list);
1524 
1525 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1526 		struct snd_usb_midi_endpoint *ep = &umidi->endpoints[i];
1527 		kfree(ep->out);
1528 	}
1529 	mutex_destroy(&umidi->mutex);
1530 	kfree(umidi);
1531 }
1532 
1533 /*
1534  * Unlinks all URBs (must be done before the usb_device is deleted).
1535  */
1536 void snd_usbmidi_disconnect(struct list_head *p)
1537 {
1538 	struct snd_usb_midi *umidi;
1539 	unsigned int i, j;
1540 
1541 	umidi = list_entry(p, struct snd_usb_midi, list);
1542 	/*
1543 	 * an URB's completion handler may start the timer and
1544 	 * a timer may submit an URB. To reliably break the cycle
1545 	 * a flag under lock must be used
1546 	 */
1547 	scoped_guard(rwsem_write, &umidi->disc_rwsem) {
1548 		guard(spinlock_irq)(&umidi->disc_lock);
1549 		umidi->disconnected = 1;
1550 	}
1551 
1552 	timer_shutdown_sync(&umidi->error_timer);
1553 
1554 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1555 		struct snd_usb_midi_endpoint *ep = &umidi->endpoints[i];
1556 		if (ep->out)
1557 			cancel_work_sync(&ep->out->work);
1558 		if (ep->out) {
1559 			for (j = 0; j < OUTPUT_URBS; ++j)
1560 				usb_kill_urb(ep->out->urbs[j].urb);
1561 			if (umidi->usb_protocol_ops->finish_out_endpoint)
1562 				umidi->usb_protocol_ops->finish_out_endpoint(ep->out);
1563 			ep->out->active_urbs = 0;
1564 			if (ep->out->drain_urbs) {
1565 				ep->out->drain_urbs = 0;
1566 				wake_up(&ep->out->drain_wait);
1567 			}
1568 		}
1569 		if (ep->in)
1570 			for (j = 0; j < INPUT_URBS; ++j)
1571 				usb_kill_urb(ep->in->urbs[j]);
1572 		/* free endpoints here; later call can result in Oops */
1573 		if (ep->out)
1574 			snd_usbmidi_out_endpoint_clear(ep->out);
1575 		if (ep->in) {
1576 			snd_usbmidi_in_endpoint_delete(ep->in);
1577 			ep->in = NULL;
1578 		}
1579 	}
1580 }
1581 EXPORT_SYMBOL(snd_usbmidi_disconnect);
1582 
1583 static void snd_usbmidi_rawmidi_free(struct snd_rawmidi *rmidi)
1584 {
1585 	struct snd_usb_midi *umidi = rmidi->private_data;
1586 	snd_usbmidi_free(umidi);
1587 }
1588 
1589 static struct snd_rawmidi_substream *snd_usbmidi_find_substream(struct snd_usb_midi *umidi,
1590 								int stream,
1591 								int number)
1592 {
1593 	struct snd_rawmidi_substream *substream;
1594 
1595 	list_for_each_entry(substream, &umidi->rmidi->streams[stream].substreams,
1596 			    list) {
1597 		if (substream->number == number)
1598 			return substream;
1599 	}
1600 	return NULL;
1601 }
1602 
1603 /*
1604  * This list specifies names for ports that do not fit into the standard
1605  * "(product) MIDI (n)" schema because they aren't external MIDI ports,
1606  * such as internal control or synthesizer ports.
1607  */
1608 static struct port_info {
1609 	u32 id;
1610 	short int port;
1611 	short int voices;
1612 	const char *name;
1613 	unsigned int seq_flags;
1614 } snd_usbmidi_port_info[] = {
1615 #define PORT_INFO(vendor, product, num, name_, voices_, flags) \
1616 	{ .id = USB_ID(vendor, product), \
1617 	  .port = num, .voices = voices_, \
1618 	  .name = name_, .seq_flags = flags }
1619 #define EXTERNAL_PORT(vendor, product, num, name) \
1620 	PORT_INFO(vendor, product, num, name, 0, \
1621 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1622 		  SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1623 		  SNDRV_SEQ_PORT_TYPE_PORT)
1624 #define CONTROL_PORT(vendor, product, num, name) \
1625 	PORT_INFO(vendor, product, num, name, 0, \
1626 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1627 		  SNDRV_SEQ_PORT_TYPE_HARDWARE)
1628 #define GM_SYNTH_PORT(vendor, product, num, name, voices) \
1629 	PORT_INFO(vendor, product, num, name, voices, \
1630 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1631 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM | \
1632 		  SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1633 		  SNDRV_SEQ_PORT_TYPE_SYNTHESIZER)
1634 #define ROLAND_SYNTH_PORT(vendor, product, num, name, voices) \
1635 	PORT_INFO(vendor, product, num, name, voices, \
1636 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1637 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM | \
1638 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM2 | \
1639 		  SNDRV_SEQ_PORT_TYPE_MIDI_GS | \
1640 		  SNDRV_SEQ_PORT_TYPE_MIDI_XG | \
1641 		  SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1642 		  SNDRV_SEQ_PORT_TYPE_SYNTHESIZER)
1643 #define SOUNDCANVAS_PORT(vendor, product, num, name, voices) \
1644 	PORT_INFO(vendor, product, num, name, voices, \
1645 		  SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1646 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM | \
1647 		  SNDRV_SEQ_PORT_TYPE_MIDI_GM2 | \
1648 		  SNDRV_SEQ_PORT_TYPE_MIDI_GS | \
1649 		  SNDRV_SEQ_PORT_TYPE_MIDI_XG | \
1650 		  SNDRV_SEQ_PORT_TYPE_MIDI_MT32 | \
1651 		  SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1652 		  SNDRV_SEQ_PORT_TYPE_SYNTHESIZER)
1653 	/* Yamaha MOTIF XF */
1654 	GM_SYNTH_PORT(0x0499, 0x105c, 0, "%s Tone Generator", 128),
1655 	CONTROL_PORT(0x0499, 0x105c, 1, "%s Remote Control"),
1656 	EXTERNAL_PORT(0x0499, 0x105c, 2, "%s Thru"),
1657 	CONTROL_PORT(0x0499, 0x105c, 3, "%s Editor"),
1658 	/* Roland UA-100 */
1659 	CONTROL_PORT(0x0582, 0x0000, 2, "%s Control"),
1660 	/* Roland SC-8850 */
1661 	SOUNDCANVAS_PORT(0x0582, 0x0003, 0, "%s Part A", 128),
1662 	SOUNDCANVAS_PORT(0x0582, 0x0003, 1, "%s Part B", 128),
1663 	SOUNDCANVAS_PORT(0x0582, 0x0003, 2, "%s Part C", 128),
1664 	SOUNDCANVAS_PORT(0x0582, 0x0003, 3, "%s Part D", 128),
1665 	EXTERNAL_PORT(0x0582, 0x0003, 4, "%s MIDI 1"),
1666 	EXTERNAL_PORT(0x0582, 0x0003, 5, "%s MIDI 2"),
1667 	/* Roland U-8 */
1668 	EXTERNAL_PORT(0x0582, 0x0004, 0, "%s MIDI"),
1669 	CONTROL_PORT(0x0582, 0x0004, 1, "%s Control"),
1670 	/* Roland SC-8820 */
1671 	SOUNDCANVAS_PORT(0x0582, 0x0007, 0, "%s Part A", 64),
1672 	SOUNDCANVAS_PORT(0x0582, 0x0007, 1, "%s Part B", 64),
1673 	EXTERNAL_PORT(0x0582, 0x0007, 2, "%s MIDI"),
1674 	/* Roland SK-500 */
1675 	SOUNDCANVAS_PORT(0x0582, 0x000b, 0, "%s Part A", 64),
1676 	SOUNDCANVAS_PORT(0x0582, 0x000b, 1, "%s Part B", 64),
1677 	EXTERNAL_PORT(0x0582, 0x000b, 2, "%s MIDI"),
1678 	/* Roland SC-D70 */
1679 	SOUNDCANVAS_PORT(0x0582, 0x000c, 0, "%s Part A", 64),
1680 	SOUNDCANVAS_PORT(0x0582, 0x000c, 1, "%s Part B", 64),
1681 	EXTERNAL_PORT(0x0582, 0x000c, 2, "%s MIDI"),
1682 	/* Edirol UM-880 */
1683 	CONTROL_PORT(0x0582, 0x0014, 8, "%s Control"),
1684 	/* Edirol SD-90 */
1685 	ROLAND_SYNTH_PORT(0x0582, 0x0016, 0, "%s Part A", 128),
1686 	ROLAND_SYNTH_PORT(0x0582, 0x0016, 1, "%s Part B", 128),
1687 	EXTERNAL_PORT(0x0582, 0x0016, 2, "%s MIDI 1"),
1688 	EXTERNAL_PORT(0x0582, 0x0016, 3, "%s MIDI 2"),
1689 	/* Edirol UM-550 */
1690 	CONTROL_PORT(0x0582, 0x0023, 5, "%s Control"),
1691 	/* Edirol SD-20 */
1692 	ROLAND_SYNTH_PORT(0x0582, 0x0027, 0, "%s Part A", 64),
1693 	ROLAND_SYNTH_PORT(0x0582, 0x0027, 1, "%s Part B", 64),
1694 	EXTERNAL_PORT(0x0582, 0x0027, 2, "%s MIDI"),
1695 	/* Edirol SD-80 */
1696 	ROLAND_SYNTH_PORT(0x0582, 0x0029, 0, "%s Part A", 128),
1697 	ROLAND_SYNTH_PORT(0x0582, 0x0029, 1, "%s Part B", 128),
1698 	EXTERNAL_PORT(0x0582, 0x0029, 2, "%s MIDI 1"),
1699 	EXTERNAL_PORT(0x0582, 0x0029, 3, "%s MIDI 2"),
1700 	/* Edirol UA-700 */
1701 	EXTERNAL_PORT(0x0582, 0x002b, 0, "%s MIDI"),
1702 	CONTROL_PORT(0x0582, 0x002b, 1, "%s Control"),
1703 	/* Roland VariOS */
1704 	EXTERNAL_PORT(0x0582, 0x002f, 0, "%s MIDI"),
1705 	EXTERNAL_PORT(0x0582, 0x002f, 1, "%s External MIDI"),
1706 	EXTERNAL_PORT(0x0582, 0x002f, 2, "%s Sync"),
1707 	/* Edirol PCR */
1708 	EXTERNAL_PORT(0x0582, 0x0033, 0, "%s MIDI"),
1709 	EXTERNAL_PORT(0x0582, 0x0033, 1, "%s 1"),
1710 	EXTERNAL_PORT(0x0582, 0x0033, 2, "%s 2"),
1711 	/* BOSS GS-10 */
1712 	EXTERNAL_PORT(0x0582, 0x003b, 0, "%s MIDI"),
1713 	CONTROL_PORT(0x0582, 0x003b, 1, "%s Control"),
1714 	/* Edirol UA-1000 */
1715 	EXTERNAL_PORT(0x0582, 0x0044, 0, "%s MIDI"),
1716 	CONTROL_PORT(0x0582, 0x0044, 1, "%s Control"),
1717 	/* Edirol UR-80 */
1718 	EXTERNAL_PORT(0x0582, 0x0048, 0, "%s MIDI"),
1719 	EXTERNAL_PORT(0x0582, 0x0048, 1, "%s 1"),
1720 	EXTERNAL_PORT(0x0582, 0x0048, 2, "%s 2"),
1721 	/* Edirol PCR-A */
1722 	EXTERNAL_PORT(0x0582, 0x004d, 0, "%s MIDI"),
1723 	EXTERNAL_PORT(0x0582, 0x004d, 1, "%s 1"),
1724 	EXTERNAL_PORT(0x0582, 0x004d, 2, "%s 2"),
1725 	/* BOSS GT-PRO */
1726 	CONTROL_PORT(0x0582, 0x0089, 0, "%s Control"),
1727 	/* Edirol UM-3EX */
1728 	CONTROL_PORT(0x0582, 0x009a, 3, "%s Control"),
1729 	/* Roland VG-99 */
1730 	CONTROL_PORT(0x0582, 0x00b2, 0, "%s Control"),
1731 	EXTERNAL_PORT(0x0582, 0x00b2, 1, "%s MIDI"),
1732 	/* Cakewalk Sonar V-Studio 100 */
1733 	EXTERNAL_PORT(0x0582, 0x00eb, 0, "%s MIDI"),
1734 	CONTROL_PORT(0x0582, 0x00eb, 1, "%s Control"),
1735 	/* Roland VB-99 */
1736 	CONTROL_PORT(0x0582, 0x0102, 0, "%s Control"),
1737 	EXTERNAL_PORT(0x0582, 0x0102, 1, "%s MIDI"),
1738 	/* Roland A-PRO */
1739 	EXTERNAL_PORT(0x0582, 0x010f, 0, "%s MIDI"),
1740 	CONTROL_PORT(0x0582, 0x010f, 1, "%s 1"),
1741 	CONTROL_PORT(0x0582, 0x010f, 2, "%s 2"),
1742 	/* Roland SD-50 */
1743 	ROLAND_SYNTH_PORT(0x0582, 0x0114, 0, "%s Synth", 128),
1744 	EXTERNAL_PORT(0x0582, 0x0114, 1, "%s MIDI"),
1745 	CONTROL_PORT(0x0582, 0x0114, 2, "%s Control"),
1746 	/* Roland OCTA-CAPTURE */
1747 	EXTERNAL_PORT(0x0582, 0x0120, 0, "%s MIDI"),
1748 	CONTROL_PORT(0x0582, 0x0120, 1, "%s Control"),
1749 	EXTERNAL_PORT(0x0582, 0x0121, 0, "%s MIDI"),
1750 	CONTROL_PORT(0x0582, 0x0121, 1, "%s Control"),
1751 	/* Roland SPD-SX */
1752 	CONTROL_PORT(0x0582, 0x0145, 0, "%s Control"),
1753 	EXTERNAL_PORT(0x0582, 0x0145, 1, "%s MIDI"),
1754 	/* Roland A-Series */
1755 	CONTROL_PORT(0x0582, 0x0156, 0, "%s Keyboard"),
1756 	EXTERNAL_PORT(0x0582, 0x0156, 1, "%s MIDI"),
1757 	/* Roland INTEGRA-7 */
1758 	ROLAND_SYNTH_PORT(0x0582, 0x015b, 0, "%s Synth", 128),
1759 	CONTROL_PORT(0x0582, 0x015b, 1, "%s Control"),
1760 	/* M-Audio MidiSport 8x8 */
1761 	CONTROL_PORT(0x0763, 0x1031, 8, "%s Control"),
1762 	CONTROL_PORT(0x0763, 0x1033, 8, "%s Control"),
1763 	/* MOTU Fastlane */
1764 	EXTERNAL_PORT(0x07fd, 0x0001, 0, "%s MIDI A"),
1765 	EXTERNAL_PORT(0x07fd, 0x0001, 1, "%s MIDI B"),
1766 	/* Emagic Unitor8/AMT8/MT4 */
1767 	EXTERNAL_PORT(0x086a, 0x0001, 8, "%s Broadcast"),
1768 	EXTERNAL_PORT(0x086a, 0x0002, 8, "%s Broadcast"),
1769 	EXTERNAL_PORT(0x086a, 0x0003, 4, "%s Broadcast"),
1770 	/* Akai MPD16 */
1771 	CONTROL_PORT(0x09e8, 0x0062, 0, "%s Control"),
1772 	PORT_INFO(0x09e8, 0x0062, 1, "%s MIDI", 0,
1773 		SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC |
1774 		SNDRV_SEQ_PORT_TYPE_HARDWARE),
1775 	/* Access Music Virus TI */
1776 	EXTERNAL_PORT(0x133e, 0x0815, 0, "%s MIDI"),
1777 	PORT_INFO(0x133e, 0x0815, 1, "%s Synth", 0,
1778 		SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC |
1779 		SNDRV_SEQ_PORT_TYPE_HARDWARE |
1780 		SNDRV_SEQ_PORT_TYPE_SYNTHESIZER),
1781 };
1782 
1783 static struct port_info *find_port_info(struct snd_usb_midi *umidi, int number)
1784 {
1785 	int i;
1786 
1787 	for (i = 0; i < ARRAY_SIZE(snd_usbmidi_port_info); ++i) {
1788 		if (snd_usbmidi_port_info[i].id == umidi->usb_id &&
1789 		    snd_usbmidi_port_info[i].port == number)
1790 			return &snd_usbmidi_port_info[i];
1791 	}
1792 	return NULL;
1793 }
1794 
1795 static void snd_usbmidi_get_port_info(struct snd_rawmidi *rmidi, int number,
1796 				      struct snd_seq_port_info *seq_port_info)
1797 {
1798 	struct snd_usb_midi *umidi = rmidi->private_data;
1799 	struct port_info *port_info;
1800 
1801 	/* TODO: read port flags from descriptors */
1802 	port_info = find_port_info(umidi, number);
1803 	if (port_info) {
1804 		seq_port_info->type = port_info->seq_flags;
1805 		seq_port_info->midi_voices = port_info->voices;
1806 	}
1807 }
1808 
1809 /* return iJack for the corresponding jackID */
1810 static int find_usb_ijack(struct usb_host_interface *hostif, uint8_t jack_id)
1811 {
1812 	unsigned char *extra = hostif->extra;
1813 	int extralen = hostif->extralen;
1814 	struct usb_descriptor_header *h;
1815 	struct usb_midi_out_jack_descriptor *outjd;
1816 	struct usb_midi_in_jack_descriptor *injd;
1817 	size_t sz;
1818 
1819 	while (extralen > 4) {
1820 		h = (struct usb_descriptor_header *)extra;
1821 		if (h->bDescriptorType != USB_DT_CS_INTERFACE)
1822 			goto next;
1823 
1824 		outjd = (struct usb_midi_out_jack_descriptor *)h;
1825 		if (h->bLength >= sizeof(*outjd) &&
1826 		    outjd->bDescriptorSubtype == UAC_MIDI_OUT_JACK &&
1827 		    outjd->bJackID == jack_id) {
1828 			sz = USB_DT_MIDI_OUT_SIZE(outjd->bNrInputPins);
1829 			if (outjd->bLength < sz)
1830 				goto next;
1831 			return *(extra + sz - 1);
1832 		}
1833 
1834 		injd = (struct usb_midi_in_jack_descriptor *)h;
1835 		if (injd->bLength >= sizeof(*injd) &&
1836 		    injd->bDescriptorSubtype == UAC_MIDI_IN_JACK &&
1837 		    injd->bJackID == jack_id)
1838 			return injd->iJack;
1839 
1840 next:
1841 		if (!extra[0])
1842 			break;
1843 		extralen -= extra[0];
1844 		extra += extra[0];
1845 	}
1846 	return 0;
1847 }
1848 
1849 static void snd_usbmidi_init_substream(struct snd_usb_midi *umidi,
1850 				       int stream, int number, int jack_id,
1851 				       struct snd_rawmidi_substream **rsubstream)
1852 {
1853 	struct port_info *port_info;
1854 	const char *name_format;
1855 	struct usb_interface *intf;
1856 	struct usb_host_interface *hostif;
1857 	uint8_t jack_name_buf[32];
1858 	uint8_t *default_jack_name = "MIDI";
1859 	uint8_t *jack_name = default_jack_name;
1860 	uint8_t iJack;
1861 	int res;
1862 
1863 	struct snd_rawmidi_substream *substream =
1864 		snd_usbmidi_find_substream(umidi, stream, number);
1865 	if (!substream) {
1866 		dev_err(&umidi->dev->dev, "substream %d:%d not found\n", stream,
1867 			number);
1868 		return;
1869 	}
1870 
1871 	intf = umidi->iface;
1872 	if (intf && jack_id >= 0) {
1873 		hostif = intf->cur_altsetting;
1874 		iJack = find_usb_ijack(hostif, jack_id);
1875 		if (iJack != 0) {
1876 			res = usb_string(umidi->dev, iJack, jack_name_buf,
1877 			  ARRAY_SIZE(jack_name_buf));
1878 			if (res)
1879 				jack_name = jack_name_buf;
1880 		}
1881 	}
1882 
1883 	port_info = find_port_info(umidi, number);
1884 	if (port_info || jack_name == default_jack_name ||
1885 	    strncmp(umidi->card->shortname, jack_name, strlen(umidi->card->shortname)) != 0) {
1886 		name_format = port_info ? port_info->name :
1887 			(jack_name != default_jack_name  ? "%s %s" : "%s %s %d");
1888 		snprintf(substream->name, sizeof(substream->name),
1889 			 name_format, umidi->card->shortname, jack_name, number + 1);
1890 	} else {
1891 		/* The manufacturer included the iProduct name in the jack
1892 		 * name, do not use both
1893 		 */
1894 		strscpy(substream->name, jack_name);
1895 	}
1896 
1897 	*rsubstream = substream;
1898 }
1899 
1900 /*
1901  * Creates the endpoints and their ports.
1902  */
1903 static int snd_usbmidi_create_endpoints(struct snd_usb_midi *umidi,
1904 					struct snd_usb_midi_endpoint_info *endpoints)
1905 {
1906 	int i, j, err;
1907 	int out_ports = 0, in_ports = 0;
1908 
1909 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1910 		if (endpoints[i].out_cables) {
1911 			err = snd_usbmidi_out_endpoint_create(umidi,
1912 							      &endpoints[i],
1913 							      &umidi->endpoints[i]);
1914 			if (err < 0)
1915 				return err;
1916 		}
1917 		if (endpoints[i].in_cables) {
1918 			err = snd_usbmidi_in_endpoint_create(umidi,
1919 							     &endpoints[i],
1920 							     &umidi->endpoints[i]);
1921 			if (err < 0)
1922 				return err;
1923 		}
1924 
1925 		for (j = 0; j < 0x10; ++j) {
1926 			if (endpoints[i].out_cables & (1 << j)) {
1927 				snd_usbmidi_init_substream(umidi,
1928 							   SNDRV_RAWMIDI_STREAM_OUTPUT,
1929 							   out_ports,
1930 							   endpoints[i].assoc_out_jacks[j],
1931 							   &umidi->endpoints[i].out->ports[j].substream);
1932 				++out_ports;
1933 			}
1934 			if (endpoints[i].in_cables & (1 << j)) {
1935 				snd_usbmidi_init_substream(umidi,
1936 							   SNDRV_RAWMIDI_STREAM_INPUT,
1937 							   in_ports,
1938 							   endpoints[i].assoc_in_jacks[j],
1939 							   &umidi->endpoints[i].in->ports[j].substream);
1940 				++in_ports;
1941 			}
1942 		}
1943 	}
1944 	dev_dbg(&umidi->dev->dev, "created %d output and %d input ports\n",
1945 		    out_ports, in_ports);
1946 	return 0;
1947 }
1948 
1949 static struct usb_ms_endpoint_descriptor *find_usb_ms_endpoint_descriptor(
1950 					struct usb_host_endpoint *hostep)
1951 {
1952 	unsigned char *extra = hostep->extra;
1953 	int extralen = hostep->extralen;
1954 
1955 	while (extralen > 3) {
1956 		struct usb_ms_endpoint_descriptor *ms_ep =
1957 				(struct usb_ms_endpoint_descriptor *)extra;
1958 		int length = ms_ep->bLength;
1959 
1960 		if (!length || length > extralen)
1961 			break;
1962 
1963 		if (length > 3 &&
1964 		    ms_ep->bDescriptorType == USB_DT_CS_ENDPOINT &&
1965 		    ms_ep->bDescriptorSubtype == UAC_MS_GENERAL)
1966 			return ms_ep;
1967 		extralen -= length;
1968 		extra += length;
1969 	}
1970 	return NULL;
1971 }
1972 
1973 /*
1974  * Returns MIDIStreaming device capabilities.
1975  */
1976 static int snd_usbmidi_get_ms_info(struct snd_usb_midi *umidi,
1977 				   struct snd_usb_midi_endpoint_info *endpoints)
1978 {
1979 	struct usb_interface *intf;
1980 	struct usb_host_interface *hostif;
1981 	struct usb_interface_descriptor *intfd;
1982 	struct usb_ms_header_descriptor *ms_header;
1983 	struct usb_host_endpoint *hostep;
1984 	struct usb_endpoint_descriptor *ep;
1985 	struct usb_ms_endpoint_descriptor *ms_ep;
1986 	int i, j, epidx;
1987 
1988 	intf = umidi->iface;
1989 	if (!intf)
1990 		return -ENXIO;
1991 	hostif = &intf->altsetting[0];
1992 	intfd = get_iface_desc(hostif);
1993 	ms_header = (struct usb_ms_header_descriptor *)hostif->extra;
1994 	if (hostif->extralen >= 7 &&
1995 	    ms_header->bLength >= 7 &&
1996 	    ms_header->bDescriptorType == USB_DT_CS_INTERFACE &&
1997 	    ms_header->bDescriptorSubtype == UAC_HEADER)
1998 		dev_dbg(&umidi->dev->dev, "MIDIStreaming version %02x.%02x\n",
1999 			    ((uint8_t *)&ms_header->bcdMSC)[1], ((uint8_t *)&ms_header->bcdMSC)[0]);
2000 	else
2001 		dev_warn(&umidi->dev->dev,
2002 			 "MIDIStreaming interface descriptor not found\n");
2003 
2004 	epidx = 0;
2005 	for (i = 0; i < intfd->bNumEndpoints; ++i) {
2006 		hostep = &hostif->endpoint[i];
2007 		ep = get_ep_desc(hostep);
2008 		if (!usb_endpoint_xfer_bulk(ep) && !usb_endpoint_xfer_int(ep))
2009 			continue;
2010 		ms_ep = find_usb_ms_endpoint_descriptor(hostep);
2011 		if (!ms_ep)
2012 			continue;
2013 		if (ms_ep->bLength <= sizeof(*ms_ep))
2014 			continue;
2015 		if (ms_ep->bNumEmbMIDIJack > 0x10)
2016 			continue;
2017 		if (ms_ep->bLength < sizeof(*ms_ep) + ms_ep->bNumEmbMIDIJack)
2018 			continue;
2019 		if (usb_endpoint_dir_out(ep)) {
2020 			if (endpoints[epidx].out_ep) {
2021 				if (++epidx >= MIDI_MAX_ENDPOINTS) {
2022 					dev_warn(&umidi->dev->dev,
2023 						 "too many endpoints\n");
2024 					break;
2025 				}
2026 			}
2027 			endpoints[epidx].out_ep = usb_endpoint_num(ep);
2028 			if (usb_endpoint_xfer_int(ep))
2029 				endpoints[epidx].out_interval = ep->bInterval;
2030 			else if (snd_usb_get_speed(umidi->dev) == USB_SPEED_LOW)
2031 				/*
2032 				 * Low speed bulk transfers don't exist, so
2033 				 * force interrupt transfers for devices like
2034 				 * ESI MIDI Mate that try to use them anyway.
2035 				 */
2036 				endpoints[epidx].out_interval = 1;
2037 			endpoints[epidx].out_cables =
2038 				(1 << ms_ep->bNumEmbMIDIJack) - 1;
2039 			for (j = 0; j < ms_ep->bNumEmbMIDIJack; ++j)
2040 				endpoints[epidx].assoc_out_jacks[j] = ms_ep->baAssocJackID[j];
2041 			for (; j < ARRAY_SIZE(endpoints[epidx].assoc_out_jacks); ++j)
2042 				endpoints[epidx].assoc_out_jacks[j] = -1;
2043 			dev_dbg(&umidi->dev->dev, "EP %02X: %d jack(s)\n",
2044 				ep->bEndpointAddress, ms_ep->bNumEmbMIDIJack);
2045 		} else {
2046 			if (endpoints[epidx].in_ep) {
2047 				if (++epidx >= MIDI_MAX_ENDPOINTS) {
2048 					dev_warn(&umidi->dev->dev,
2049 						 "too many endpoints\n");
2050 					break;
2051 				}
2052 			}
2053 			endpoints[epidx].in_ep = usb_endpoint_num(ep);
2054 			if (usb_endpoint_xfer_int(ep))
2055 				endpoints[epidx].in_interval = ep->bInterval;
2056 			else if (snd_usb_get_speed(umidi->dev) == USB_SPEED_LOW)
2057 				endpoints[epidx].in_interval = 1;
2058 			endpoints[epidx].in_cables =
2059 				(1 << ms_ep->bNumEmbMIDIJack) - 1;
2060 			for (j = 0; j < ms_ep->bNumEmbMIDIJack; ++j)
2061 				endpoints[epidx].assoc_in_jacks[j] = ms_ep->baAssocJackID[j];
2062 			for (; j < ARRAY_SIZE(endpoints[epidx].assoc_in_jacks); ++j)
2063 				endpoints[epidx].assoc_in_jacks[j] = -1;
2064 			dev_dbg(&umidi->dev->dev, "EP %02X: %d jack(s)\n",
2065 				ep->bEndpointAddress, ms_ep->bNumEmbMIDIJack);
2066 		}
2067 	}
2068 	return 0;
2069 }
2070 
2071 static int roland_load_info(struct snd_kcontrol *kcontrol,
2072 			    struct snd_ctl_elem_info *info)
2073 {
2074 	static const char *const names[] = { "High Load", "Light Load" };
2075 
2076 	return snd_ctl_enum_info(info, 1, 2, names);
2077 }
2078 
2079 static int roland_load_get(struct snd_kcontrol *kcontrol,
2080 			   struct snd_ctl_elem_value *value)
2081 {
2082 	value->value.enumerated.item[0] = kcontrol->private_value;
2083 	return 0;
2084 }
2085 
2086 static int roland_load_put(struct snd_kcontrol *kcontrol,
2087 			   struct snd_ctl_elem_value *value)
2088 {
2089 	struct snd_usb_midi *umidi = snd_kcontrol_chip(kcontrol);
2090 	int changed;
2091 
2092 	if (value->value.enumerated.item[0] > 1)
2093 		return -EINVAL;
2094 	guard(mutex)(&umidi->mutex);
2095 	changed = value->value.enumerated.item[0] != kcontrol->private_value;
2096 	if (changed)
2097 		kcontrol->private_value = value->value.enumerated.item[0];
2098 	return changed;
2099 }
2100 
2101 static const struct snd_kcontrol_new roland_load_ctl = {
2102 	.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2103 	.name = "MIDI Input Mode",
2104 	.info = roland_load_info,
2105 	.get = roland_load_get,
2106 	.put = roland_load_put,
2107 	.private_value = 1,
2108 };
2109 
2110 /*
2111  * On Roland devices, use the second alternate setting to be able to use
2112  * the interrupt input endpoint.
2113  */
2114 static void snd_usbmidi_switch_roland_altsetting(struct snd_usb_midi *umidi)
2115 {
2116 	struct usb_interface *intf;
2117 	struct usb_host_interface *hostif;
2118 	struct usb_interface_descriptor *intfd;
2119 
2120 	intf = umidi->iface;
2121 	if (!intf || intf->num_altsetting != 2)
2122 		return;
2123 
2124 	hostif = &intf->altsetting[1];
2125 	intfd = get_iface_desc(hostif);
2126        /* If either or both of the endpoints support interrupt transfer,
2127         * then use the alternate setting
2128         */
2129 	if (intfd->bNumEndpoints != 2 ||
2130 	    !((get_endpoint(hostif, 0)->bmAttributes &
2131 	       USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT ||
2132 	      (get_endpoint(hostif, 1)->bmAttributes &
2133 	       USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT))
2134 		return;
2135 
2136 	dev_dbg(&umidi->dev->dev, "switching to altsetting %d with int ep\n",
2137 		    intfd->bAlternateSetting);
2138 	usb_set_interface(umidi->dev, intfd->bInterfaceNumber,
2139 			  intfd->bAlternateSetting);
2140 
2141 	umidi->roland_load_ctl = snd_ctl_new1(&roland_load_ctl, umidi);
2142 	if (snd_ctl_add(umidi->card, umidi->roland_load_ctl) < 0)
2143 		umidi->roland_load_ctl = NULL;
2144 }
2145 
2146 /*
2147  * Try to find any usable endpoints in the interface.
2148  */
2149 static int snd_usbmidi_detect_endpoints(struct snd_usb_midi *umidi,
2150 					struct snd_usb_midi_endpoint_info *endpoint,
2151 					int max_endpoints)
2152 {
2153 	struct usb_interface *intf;
2154 	struct usb_host_interface *hostif;
2155 	struct usb_interface_descriptor *intfd;
2156 	struct usb_endpoint_descriptor *epd;
2157 	int i, out_eps = 0, in_eps = 0;
2158 
2159 	if (USB_ID_VENDOR(umidi->usb_id) == 0x0582)
2160 		snd_usbmidi_switch_roland_altsetting(umidi);
2161 
2162 	if (endpoint[0].out_ep || endpoint[0].in_ep)
2163 		return 0;
2164 
2165 	intf = umidi->iface;
2166 	if (!intf || intf->num_altsetting < 1)
2167 		return -ENOENT;
2168 	hostif = intf->cur_altsetting;
2169 	intfd = get_iface_desc(hostif);
2170 
2171 	for (i = 0; i < intfd->bNumEndpoints; ++i) {
2172 		epd = get_endpoint(hostif, i);
2173 		if (!usb_endpoint_xfer_bulk(epd) &&
2174 		    !usb_endpoint_xfer_int(epd))
2175 			continue;
2176 		if (out_eps < max_endpoints &&
2177 		    usb_endpoint_dir_out(epd)) {
2178 			endpoint[out_eps].out_ep = usb_endpoint_num(epd);
2179 			if (usb_endpoint_xfer_int(epd))
2180 				endpoint[out_eps].out_interval = epd->bInterval;
2181 			++out_eps;
2182 		}
2183 		if (in_eps < max_endpoints &&
2184 		    usb_endpoint_dir_in(epd)) {
2185 			endpoint[in_eps].in_ep = usb_endpoint_num(epd);
2186 			if (usb_endpoint_xfer_int(epd))
2187 				endpoint[in_eps].in_interval = epd->bInterval;
2188 			++in_eps;
2189 		}
2190 	}
2191 	return (out_eps || in_eps) ? 0 : -ENOENT;
2192 }
2193 
2194 /*
2195  * Detects the endpoints for one-port-per-endpoint protocols.
2196  */
2197 static int snd_usbmidi_detect_per_port_endpoints(struct snd_usb_midi *umidi,
2198 						 struct snd_usb_midi_endpoint_info *endpoints)
2199 {
2200 	int err, i;
2201 
2202 	err = snd_usbmidi_detect_endpoints(umidi, endpoints, MIDI_MAX_ENDPOINTS);
2203 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
2204 		if (endpoints[i].out_ep)
2205 			endpoints[i].out_cables = 0x0001;
2206 		if (endpoints[i].in_ep)
2207 			endpoints[i].in_cables = 0x0001;
2208 	}
2209 	return err;
2210 }
2211 
2212 /*
2213  * Detects the endpoints and ports of Yamaha devices.
2214  */
2215 static int snd_usbmidi_detect_yamaha(struct snd_usb_midi *umidi,
2216 				     struct snd_usb_midi_endpoint_info *endpoint)
2217 {
2218 	struct usb_interface *intf;
2219 	struct usb_host_interface *hostif;
2220 	struct usb_interface_descriptor *intfd;
2221 	uint8_t *cs_desc;
2222 
2223 	intf = umidi->iface;
2224 	if (!intf)
2225 		return -ENOENT;
2226 	hostif = intf->altsetting;
2227 	intfd = get_iface_desc(hostif);
2228 	if (intfd->bNumEndpoints < 1)
2229 		return -ENOENT;
2230 
2231 	/*
2232 	 * For each port there is one MIDI_IN/OUT_JACK descriptor, not
2233 	 * necessarily with any useful contents.  So simply count 'em.
2234 	 */
2235 	for (cs_desc = hostif->extra;
2236 	     cs_desc < hostif->extra + hostif->extralen && cs_desc[0] >= 2;
2237 	     cs_desc += cs_desc[0]) {
2238 		if (cs_desc[1] == USB_DT_CS_INTERFACE) {
2239 			if (cs_desc[2] == UAC_MIDI_IN_JACK)
2240 				endpoint->in_cables =
2241 					(endpoint->in_cables << 1) | 1;
2242 			else if (cs_desc[2] == UAC_MIDI_OUT_JACK)
2243 				endpoint->out_cables =
2244 					(endpoint->out_cables << 1) | 1;
2245 		}
2246 	}
2247 	if (!endpoint->in_cables && !endpoint->out_cables)
2248 		return -ENOENT;
2249 
2250 	return snd_usbmidi_detect_endpoints(umidi, endpoint, 1);
2251 }
2252 
2253 /*
2254  * Detects the endpoints and ports of Roland devices.
2255  */
2256 static int snd_usbmidi_detect_roland(struct snd_usb_midi *umidi,
2257 				     struct snd_usb_midi_endpoint_info *endpoint)
2258 {
2259 	struct usb_interface *intf;
2260 	struct usb_host_interface *hostif;
2261 	u8 *cs_desc;
2262 
2263 	intf = umidi->iface;
2264 	if (!intf)
2265 		return -ENOENT;
2266 	hostif = intf->altsetting;
2267 	/*
2268 	 * Some devices have a descriptor <06 24 F1 02 <inputs> <outputs>>,
2269 	 * some have standard class descriptors, or both kinds, or neither.
2270 	 */
2271 	for (cs_desc = hostif->extra;
2272 	     cs_desc < hostif->extra + hostif->extralen && cs_desc[0] >= 2;
2273 	     cs_desc += cs_desc[0]) {
2274 		if (cs_desc[0] >= 6 &&
2275 		    cs_desc[1] == USB_DT_CS_INTERFACE &&
2276 		    cs_desc[2] == 0xf1 &&
2277 		    cs_desc[3] == 0x02) {
2278 			if (cs_desc[4] > 0x10 || cs_desc[5] > 0x10)
2279 				continue;
2280 			endpoint->in_cables  = (1 << cs_desc[4]) - 1;
2281 			endpoint->out_cables = (1 << cs_desc[5]) - 1;
2282 			return snd_usbmidi_detect_endpoints(umidi, endpoint, 1);
2283 		} else if (cs_desc[0] >= 7 &&
2284 			   cs_desc[1] == USB_DT_CS_INTERFACE &&
2285 			   cs_desc[2] == UAC_HEADER) {
2286 			return snd_usbmidi_get_ms_info(umidi, endpoint);
2287 		}
2288 	}
2289 
2290 	return -ENODEV;
2291 }
2292 
2293 /*
2294  * Creates the endpoints and their ports for Midiman devices.
2295  */
2296 static int snd_usbmidi_create_endpoints_midiman(struct snd_usb_midi *umidi,
2297 						struct snd_usb_midi_endpoint_info *endpoint)
2298 {
2299 	struct snd_usb_midi_endpoint_info ep_info;
2300 	struct usb_interface *intf;
2301 	struct usb_host_interface *hostif;
2302 	struct usb_interface_descriptor *intfd;
2303 	struct usb_endpoint_descriptor *epd;
2304 	int cable, err;
2305 
2306 	intf = umidi->iface;
2307 	if (!intf)
2308 		return -ENOENT;
2309 	hostif = intf->altsetting;
2310 	intfd = get_iface_desc(hostif);
2311 	/*
2312 	 * The various MidiSport devices have more or less random endpoint
2313 	 * numbers, so we have to identify the endpoints by their index in
2314 	 * the descriptor array, like the driver for that other OS does.
2315 	 *
2316 	 * There is one interrupt input endpoint for all input ports, one
2317 	 * bulk output endpoint for even-numbered ports, and one for odd-
2318 	 * numbered ports.  Both bulk output endpoints have corresponding
2319 	 * input bulk endpoints (at indices 1 and 3) which aren't used.
2320 	 */
2321 	if (intfd->bNumEndpoints < (endpoint->out_cables > 0x0001 ? 5 : 3)) {
2322 		dev_dbg(&umidi->dev->dev, "not enough endpoints\n");
2323 		return -ENOENT;
2324 	}
2325 
2326 	epd = get_endpoint(hostif, 0);
2327 	if (!usb_endpoint_dir_in(epd) || !usb_endpoint_xfer_int(epd)) {
2328 		dev_dbg(&umidi->dev->dev, "endpoint[0] isn't interrupt\n");
2329 		return -ENXIO;
2330 	}
2331 	epd = get_endpoint(hostif, 2);
2332 	if (!usb_endpoint_dir_out(epd) || !usb_endpoint_xfer_bulk(epd)) {
2333 		dev_dbg(&umidi->dev->dev, "endpoint[2] isn't bulk output\n");
2334 		return -ENXIO;
2335 	}
2336 	if (endpoint->out_cables > 0x0001) {
2337 		epd = get_endpoint(hostif, 4);
2338 		if (!usb_endpoint_dir_out(epd) ||
2339 		    !usb_endpoint_xfer_bulk(epd)) {
2340 			dev_dbg(&umidi->dev->dev,
2341 				"endpoint[4] isn't bulk output\n");
2342 			return -ENXIO;
2343 		}
2344 	}
2345 
2346 	ep_info.out_ep = get_endpoint(hostif, 2)->bEndpointAddress &
2347 		USB_ENDPOINT_NUMBER_MASK;
2348 	ep_info.out_interval = 0;
2349 	ep_info.out_cables = endpoint->out_cables & 0x5555;
2350 	err = snd_usbmidi_out_endpoint_create(umidi, &ep_info,
2351 					      &umidi->endpoints[0]);
2352 	if (err < 0)
2353 		return err;
2354 
2355 	ep_info.in_ep = get_endpoint(hostif, 0)->bEndpointAddress &
2356 		USB_ENDPOINT_NUMBER_MASK;
2357 	ep_info.in_interval = get_endpoint(hostif, 0)->bInterval;
2358 	ep_info.in_cables = endpoint->in_cables;
2359 	err = snd_usbmidi_in_endpoint_create(umidi, &ep_info,
2360 					     &umidi->endpoints[0]);
2361 	if (err < 0)
2362 		return err;
2363 
2364 	if (endpoint->out_cables > 0x0001) {
2365 		ep_info.out_ep = get_endpoint(hostif, 4)->bEndpointAddress &
2366 			USB_ENDPOINT_NUMBER_MASK;
2367 		ep_info.out_cables = endpoint->out_cables & 0xaaaa;
2368 		err = snd_usbmidi_out_endpoint_create(umidi, &ep_info,
2369 						      &umidi->endpoints[1]);
2370 		if (err < 0)
2371 			return err;
2372 	}
2373 
2374 	for (cable = 0; cable < 0x10; ++cable) {
2375 		if (endpoint->out_cables & (1 << cable))
2376 			snd_usbmidi_init_substream(umidi,
2377 						   SNDRV_RAWMIDI_STREAM_OUTPUT,
2378 						   cable,
2379 						   -1 /* prevent trying to find jack */,
2380 						   &umidi->endpoints[cable & 1].out->ports[cable].substream);
2381 		if (endpoint->in_cables & (1 << cable))
2382 			snd_usbmidi_init_substream(umidi,
2383 						   SNDRV_RAWMIDI_STREAM_INPUT,
2384 						   cable,
2385 						   -1 /* prevent trying to find jack */,
2386 						   &umidi->endpoints[0].in->ports[cable].substream);
2387 	}
2388 	return 0;
2389 }
2390 
2391 static const struct snd_rawmidi_global_ops snd_usbmidi_ops = {
2392 	.get_port_info = snd_usbmidi_get_port_info,
2393 };
2394 
2395 static int snd_usbmidi_create_rawmidi(struct snd_usb_midi *umidi,
2396 				      int out_ports, int in_ports)
2397 {
2398 	struct snd_rawmidi *rmidi;
2399 	int err;
2400 
2401 	err = snd_rawmidi_new(umidi->card, "USB MIDI",
2402 			      umidi->next_midi_device++,
2403 			      out_ports, in_ports, &rmidi);
2404 	if (err < 0)
2405 		return err;
2406 	strscpy(rmidi->name, umidi->card->shortname);
2407 	rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
2408 			    SNDRV_RAWMIDI_INFO_INPUT |
2409 			    SNDRV_RAWMIDI_INFO_DUPLEX;
2410 	rmidi->ops = &snd_usbmidi_ops;
2411 	rmidi->private_data = umidi;
2412 	rmidi->private_free = snd_usbmidi_rawmidi_free;
2413 	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT,
2414 			    &snd_usbmidi_output_ops);
2415 	snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT,
2416 			    &snd_usbmidi_input_ops);
2417 
2418 	umidi->rmidi = rmidi;
2419 	return 0;
2420 }
2421 
2422 /*
2423  * Temporarily stop input.
2424  */
2425 void snd_usbmidi_input_stop(struct list_head *p)
2426 {
2427 	struct snd_usb_midi *umidi;
2428 	unsigned int i, j;
2429 
2430 	umidi = list_entry(p, struct snd_usb_midi, list);
2431 	if (!umidi->input_running)
2432 		return;
2433 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
2434 		struct snd_usb_midi_endpoint *ep = &umidi->endpoints[i];
2435 		if (ep->in)
2436 			for (j = 0; j < INPUT_URBS; ++j)
2437 				usb_kill_urb(ep->in->urbs[j]);
2438 	}
2439 	umidi->input_running = 0;
2440 }
2441 EXPORT_SYMBOL(snd_usbmidi_input_stop);
2442 
2443 static void snd_usbmidi_input_start_ep(struct snd_usb_midi *umidi,
2444 				       struct snd_usb_midi_in_endpoint *ep)
2445 {
2446 	unsigned int i;
2447 
2448 	if (!ep)
2449 		return;
2450 	for (i = 0; i < INPUT_URBS; ++i) {
2451 		struct urb *urb = ep->urbs[i];
2452 		scoped_guard(spinlock_irqsave, &umidi->disc_lock) {
2453 			if (!atomic_read(&urb->use_count)) {
2454 				urb->dev = ep->umidi->dev;
2455 				snd_usbmidi_submit_urb(urb, GFP_ATOMIC);
2456 			}
2457 		}
2458 	}
2459 }
2460 
2461 /*
2462  * Resume input after a call to snd_usbmidi_input_stop().
2463  */
2464 void snd_usbmidi_input_start(struct list_head *p)
2465 {
2466 	struct snd_usb_midi *umidi;
2467 	int i;
2468 
2469 	umidi = list_entry(p, struct snd_usb_midi, list);
2470 	if (umidi->input_running || !umidi->opened[1])
2471 		return;
2472 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
2473 		snd_usbmidi_input_start_ep(umidi, umidi->endpoints[i].in);
2474 	umidi->input_running = 1;
2475 }
2476 EXPORT_SYMBOL(snd_usbmidi_input_start);
2477 
2478 /*
2479  * Prepare for suspend. Typically called from the USB suspend callback.
2480  */
2481 void snd_usbmidi_suspend(struct list_head *p)
2482 {
2483 	struct snd_usb_midi *umidi;
2484 
2485 	umidi = list_entry(p, struct snd_usb_midi, list);
2486 	guard(mutex)(&umidi->mutex);
2487 	snd_usbmidi_input_stop(p);
2488 }
2489 EXPORT_SYMBOL(snd_usbmidi_suspend);
2490 
2491 /*
2492  * Resume. Typically called from the USB resume callback.
2493  */
2494 void snd_usbmidi_resume(struct list_head *p)
2495 {
2496 	struct snd_usb_midi *umidi;
2497 
2498 	umidi = list_entry(p, struct snd_usb_midi, list);
2499 	guard(mutex)(&umidi->mutex);
2500 	snd_usbmidi_input_start(p);
2501 }
2502 EXPORT_SYMBOL(snd_usbmidi_resume);
2503 
2504 /*
2505  * Creates and registers everything needed for a MIDI streaming interface.
2506  */
2507 int __snd_usbmidi_create(struct snd_card *card,
2508 			 struct usb_interface *iface,
2509 			 struct list_head *midi_list,
2510 			 const struct snd_usb_audio_quirk *quirk,
2511 			 unsigned int usb_id,
2512 			 unsigned int *num_rawmidis)
2513 {
2514 	struct snd_usb_midi *umidi;
2515 	struct snd_usb_midi_endpoint_info endpoints[MIDI_MAX_ENDPOINTS];
2516 	int out_ports, in_ports;
2517 	int i, err;
2518 
2519 	umidi = kzalloc_obj(*umidi);
2520 	if (!umidi)
2521 		return -ENOMEM;
2522 	umidi->dev = interface_to_usbdev(iface);
2523 	umidi->card = card;
2524 	umidi->iface = iface;
2525 	umidi->quirk = quirk;
2526 	umidi->usb_protocol_ops = &snd_usbmidi_standard_ops;
2527 	if (num_rawmidis)
2528 		umidi->next_midi_device = *num_rawmidis;
2529 	spin_lock_init(&umidi->disc_lock);
2530 	init_rwsem(&umidi->disc_rwsem);
2531 	mutex_init(&umidi->mutex);
2532 	if (!usb_id)
2533 		usb_id = USB_ID(le16_to_cpu(umidi->dev->descriptor.idVendor),
2534 			       le16_to_cpu(umidi->dev->descriptor.idProduct));
2535 	umidi->usb_id = usb_id;
2536 	timer_setup(&umidi->error_timer, snd_usbmidi_error_timer, 0);
2537 
2538 	/* detect the endpoint(s) to use */
2539 	memset(endpoints, 0, sizeof(endpoints));
2540 	switch (quirk ? quirk->type : QUIRK_MIDI_STANDARD_INTERFACE) {
2541 	case QUIRK_MIDI_STANDARD_INTERFACE:
2542 		err = snd_usbmidi_get_ms_info(umidi, endpoints);
2543 		if (umidi->usb_id == USB_ID(0x0763, 0x0150)) /* M-Audio Uno */
2544 			umidi->usb_protocol_ops =
2545 				&snd_usbmidi_maudio_broken_running_status_ops;
2546 		break;
2547 	case QUIRK_MIDI_US122L:
2548 		umidi->usb_protocol_ops = &snd_usbmidi_122l_ops;
2549 		fallthrough;
2550 	case QUIRK_MIDI_FIXED_ENDPOINT:
2551 		memcpy(&endpoints[0], quirk->data,
2552 		       sizeof(struct snd_usb_midi_endpoint_info));
2553 		err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
2554 		break;
2555 	case QUIRK_MIDI_YAMAHA:
2556 		err = snd_usbmidi_detect_yamaha(umidi, &endpoints[0]);
2557 		break;
2558 	case QUIRK_MIDI_ROLAND:
2559 		err = snd_usbmidi_detect_roland(umidi, &endpoints[0]);
2560 		break;
2561 	case QUIRK_MIDI_MIDIMAN:
2562 		umidi->usb_protocol_ops = &snd_usbmidi_midiman_ops;
2563 		memcpy(&endpoints[0], quirk->data,
2564 		       sizeof(struct snd_usb_midi_endpoint_info));
2565 		err = 0;
2566 		break;
2567 	case QUIRK_MIDI_NOVATION:
2568 		umidi->usb_protocol_ops = &snd_usbmidi_novation_ops;
2569 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2570 		break;
2571 	case QUIRK_MIDI_RAW_BYTES:
2572 		umidi->usb_protocol_ops = &snd_usbmidi_raw_ops;
2573 		/*
2574 		 * Interface 1 contains isochronous endpoints, but with the same
2575 		 * numbers as in interface 0.  Since it is interface 1 that the
2576 		 * USB core has most recently seen, these descriptors are now
2577 		 * associated with the endpoint numbers.  This will foul up our
2578 		 * attempts to submit bulk/interrupt URBs to the endpoints in
2579 		 * interface 0, so we have to make sure that the USB core looks
2580 		 * again at interface 0 by calling usb_set_interface() on it.
2581 		 */
2582 		if (umidi->usb_id == USB_ID(0x07fd, 0x0001)) /* MOTU Fastlane */
2583 			usb_set_interface(umidi->dev, 0, 0);
2584 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2585 		break;
2586 	case QUIRK_MIDI_EMAGIC:
2587 		umidi->usb_protocol_ops = &snd_usbmidi_emagic_ops;
2588 		memcpy(&endpoints[0], quirk->data,
2589 		       sizeof(struct snd_usb_midi_endpoint_info));
2590 		err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
2591 		break;
2592 	case QUIRK_MIDI_CME:
2593 		umidi->usb_protocol_ops = &snd_usbmidi_cme_ops;
2594 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2595 		break;
2596 	case QUIRK_MIDI_AKAI:
2597 		umidi->usb_protocol_ops = &snd_usbmidi_akai_ops;
2598 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2599 		/* endpoint 1 is input-only */
2600 		endpoints[1].out_cables = 0;
2601 		break;
2602 	case QUIRK_MIDI_FTDI:
2603 		umidi->usb_protocol_ops = &snd_usbmidi_ftdi_ops;
2604 
2605 		/* set baud rate to 31250 (48 MHz / 16 / 96) */
2606 		err = usb_control_msg(umidi->dev, usb_sndctrlpipe(umidi->dev, 0),
2607 				      3, 0x40, 0x60, 0, NULL, 0, 1000);
2608 		if (err < 0)
2609 			break;
2610 
2611 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2612 		break;
2613 	case QUIRK_MIDI_CH345:
2614 		umidi->usb_protocol_ops = &snd_usbmidi_ch345_broken_sysex_ops;
2615 		err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2616 		break;
2617 	default:
2618 		dev_err(&umidi->dev->dev, "invalid quirk type %d\n",
2619 			quirk->type);
2620 		err = -ENXIO;
2621 		break;
2622 	}
2623 	if (err < 0)
2624 		goto free_midi;
2625 
2626 	/* create rawmidi device */
2627 	out_ports = 0;
2628 	in_ports = 0;
2629 	for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
2630 		out_ports += hweight16(endpoints[i].out_cables);
2631 		in_ports += hweight16(endpoints[i].in_cables);
2632 	}
2633 	err = snd_usbmidi_create_rawmidi(umidi, out_ports, in_ports);
2634 	if (err < 0)
2635 		goto free_midi;
2636 
2637 	/* create endpoint/port structures */
2638 	if (quirk && quirk->type == QUIRK_MIDI_MIDIMAN)
2639 		err = snd_usbmidi_create_endpoints_midiman(umidi, &endpoints[0]);
2640 	else
2641 		err = snd_usbmidi_create_endpoints(umidi, endpoints);
2642 	if (err < 0)
2643 		goto exit;
2644 
2645 	usb_autopm_get_interface_no_resume(umidi->iface);
2646 
2647 	list_add_tail(&umidi->list, midi_list);
2648 	if (num_rawmidis)
2649 		*num_rawmidis = umidi->next_midi_device;
2650 	return 0;
2651 
2652 free_midi:
2653 	kfree(umidi);
2654 exit:
2655 	return err;
2656 }
2657 EXPORT_SYMBOL(__snd_usbmidi_create);
2658