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