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