xref: /linux/sound/usb/midi2.c (revision c894ec016c9d0418dd832202225a8c64f450d71e)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * MIDI 2.0 support
4  */
5 
6 #include <linux/bitops.h>
7 #include <linux/string.h>
8 #include <linux/init.h>
9 #include <linux/slab.h>
10 #include <linux/usb.h>
11 #include <linux/wait.h>
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14 #include <linux/usb/audio.h>
15 #include <linux/usb/midi.h>
16 #include <linux/usb/midi-v2.h>
17 
18 #include <sound/core.h>
19 #include <sound/control.h>
20 #include <sound/ump.h>
21 #include "usbaudio.h"
22 #include "midi.h"
23 #include "midi2.h"
24 #include "helper.h"
25 
26 static bool midi2_enable = true;
27 module_param(midi2_enable, bool, 0444);
28 MODULE_PARM_DESC(midi2_enable, "Enable MIDI 2.0 support.");
29 
30 /* stream direction; just shorter names */
31 enum {
32 	STR_OUT = SNDRV_RAWMIDI_STREAM_OUTPUT,
33 	STR_IN = SNDRV_RAWMIDI_STREAM_INPUT
34 };
35 
36 #define NUM_URBS	8
37 
38 struct snd_usb_midi2_urb;
39 struct snd_usb_midi2_endpoint;
40 struct snd_usb_midi2_ump;
41 struct snd_usb_midi2_interface;
42 
43 /* URB context */
44 struct snd_usb_midi2_urb {
45 	struct urb *urb;
46 	struct snd_usb_midi2_endpoint *ep;
47 	unsigned int index;		/* array index */
48 };
49 
50 /* A USB MIDI input/output endpoint */
51 struct snd_usb_midi2_endpoint {
52 	struct usb_device *dev;
53 	const struct usb_ms20_endpoint_descriptor *ms_ep; /* reference to EP descriptor */
54 	struct snd_usb_midi2_endpoint *pair;	/* bidirectional pair EP */
55 	struct snd_usb_midi2_ump *rmidi;	/* assigned UMP EP pair */
56 	struct snd_ump_endpoint *ump;		/* assigned UMP EP */
57 	int direction;			/* direction (STR_IN/OUT) */
58 	unsigned int endpoint;		/* EP number */
59 	unsigned int pipe;		/* URB pipe */
60 	unsigned int packets;		/* packet buffer size in bytes */
61 	unsigned int interval;		/* interval for INT EP */
62 	wait_queue_head_t wait;		/* URB waiter */
63 	spinlock_t lock;		/* URB locking */
64 	struct snd_rawmidi_substream *substream; /* NULL when closed */
65 	unsigned int num_urbs;		/* number of allocated URBs */
66 	unsigned long urb_free;		/* bitmap for free URBs */
67 	unsigned long urb_free_mask;	/* bitmask for free URBs */
68 	atomic_t running;		/* running status */
69 	atomic_t suspended;		/* saved running status for suspend */
70 	bool disconnected;		/* shadow of umidi->disconnected */
71 	struct list_head list;		/* list to umidi->ep_list */
72 	struct snd_usb_midi2_urb urbs[NUM_URBS];
73 };
74 
75 /* A UMP endpoint - one or two USB MIDI endpoints are assigned */
76 struct snd_usb_midi2_ump {
77 	struct usb_device *dev;
78 	struct snd_usb_midi2_interface *umidi;	/* reference to MIDI iface */
79 	struct snd_ump_endpoint *ump;		/* assigned UMP EP object */
80 	struct snd_usb_midi2_endpoint *eps[2];	/* USB MIDI endpoints */
81 	int index;				/* rawmidi device index */
82 	unsigned char usb_block_id;		/* USB GTB id used for finding a pair */
83 	struct list_head list;		/* list to umidi->rawmidi_list */
84 };
85 
86 /* top-level instance per USB MIDI interface */
87 struct snd_usb_midi2_interface {
88 	struct snd_usb_audio *chip;	/* assigned USB-audio card */
89 	struct usb_interface *iface;	/* assigned USB interface */
90 	struct usb_host_interface *hostif;
91 	const char *blk_descs;		/* group terminal block descriptors */
92 	unsigned int blk_desc_size;	/* size of GTB descriptors */
93 	bool disconnected;
94 	struct list_head ep_list;	/* list of endpoints */
95 	struct list_head rawmidi_list;	/* list of UMP rawmidis */
96 	struct list_head list;		/* list to chip->midi_v2_list */
97 };
98 
99 /* submit URBs as much as possible; used for both input and output */
100 static void do_submit_urbs_locked(struct snd_usb_midi2_endpoint *ep,
101 				  int (*prepare)(struct snd_usb_midi2_endpoint *,
102 						 struct urb *))
103 {
104 	struct snd_usb_midi2_urb *ctx;
105 	int index, err = 0;
106 
107 	if (ep->disconnected)
108 		return;
109 
110 	while (ep->urb_free) {
111 		index = find_first_bit(&ep->urb_free, ep->num_urbs);
112 		if (index >= ep->num_urbs)
113 			return;
114 		ctx = &ep->urbs[index];
115 		err = prepare(ep, ctx->urb);
116 		if (err < 0)
117 			return;
118 		if (!ctx->urb->transfer_buffer_length)
119 			return;
120 		ctx->urb->dev = ep->dev;
121 		err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
122 		if (err < 0) {
123 			dev_dbg(&ep->dev->dev,
124 				"usb_submit_urb error %d\n", err);
125 			return;
126 		}
127 		clear_bit(index, &ep->urb_free);
128 	}
129 }
130 
131 /* prepare for output submission: copy from rawmidi buffer to urb packet */
132 static int prepare_output_urb(struct snd_usb_midi2_endpoint *ep,
133 			      struct urb *urb)
134 {
135 	int count;
136 
137 	count = snd_ump_transmit(ep->ump, urb->transfer_buffer,
138 				 ep->packets);
139 	if (count < 0) {
140 		dev_dbg(&ep->dev->dev, "rawmidi transmit error %d\n", count);
141 		return count;
142 	}
143 	cpu_to_le32_array((u32 *)urb->transfer_buffer, count >> 2);
144 	urb->transfer_buffer_length = count;
145 	return 0;
146 }
147 
148 static void submit_output_urbs_locked(struct snd_usb_midi2_endpoint *ep)
149 {
150 	do_submit_urbs_locked(ep, prepare_output_urb);
151 }
152 
153 /* URB completion for output; re-filling and re-submit */
154 static void output_urb_complete(struct urb *urb)
155 {
156 	struct snd_usb_midi2_urb *ctx = urb->context;
157 	struct snd_usb_midi2_endpoint *ep = ctx->ep;
158 	unsigned long flags;
159 
160 	spin_lock_irqsave(&ep->lock, flags);
161 	set_bit(ctx->index, &ep->urb_free);
162 	if (urb->status >= 0 && atomic_read(&ep->running))
163 		submit_output_urbs_locked(ep);
164 	if (ep->urb_free == ep->urb_free_mask)
165 		wake_up(&ep->wait);
166 	spin_unlock_irqrestore(&ep->lock, flags);
167 }
168 
169 /* prepare for input submission: just set the buffer length */
170 static int prepare_input_urb(struct snd_usb_midi2_endpoint *ep,
171 			     struct urb *urb)
172 {
173 	urb->transfer_buffer_length = ep->packets;
174 	return 0;
175 }
176 
177 static void submit_input_urbs_locked(struct snd_usb_midi2_endpoint *ep)
178 {
179 	do_submit_urbs_locked(ep, prepare_input_urb);
180 }
181 
182 /* URB completion for input; copy into rawmidi buffer and resubmit */
183 static void input_urb_complete(struct urb *urb)
184 {
185 	struct snd_usb_midi2_urb *ctx = urb->context;
186 	struct snd_usb_midi2_endpoint *ep = ctx->ep;
187 	unsigned long flags;
188 	int len;
189 
190 	spin_lock_irqsave(&ep->lock, flags);
191 	if (ep->disconnected || urb->status < 0)
192 		goto dequeue;
193 	len = urb->actual_length;
194 	len &= ~3; /* align UMP */
195 	if (len > ep->packets)
196 		len = ep->packets;
197 	if (len > 0) {
198 		le32_to_cpu_array((u32 *)urb->transfer_buffer, len >> 2);
199 		snd_ump_receive(ep->ump, (u32 *)urb->transfer_buffer, len);
200 	}
201  dequeue:
202 	set_bit(ctx->index, &ep->urb_free);
203 	submit_input_urbs_locked(ep);
204 	if (ep->urb_free == ep->urb_free_mask)
205 		wake_up(&ep->wait);
206 	spin_unlock_irqrestore(&ep->lock, flags);
207 }
208 
209 /* URB submission helper; for both direction */
210 static void submit_io_urbs(struct snd_usb_midi2_endpoint *ep)
211 {
212 	unsigned long flags;
213 
214 	if (!ep)
215 		return;
216 	spin_lock_irqsave(&ep->lock, flags);
217 	if (ep->direction == STR_IN)
218 		submit_input_urbs_locked(ep);
219 	else
220 		submit_output_urbs_locked(ep);
221 	spin_unlock_irqrestore(&ep->lock, flags);
222 }
223 
224 /* kill URBs for close, suspend and disconnect */
225 static void kill_midi_urbs(struct snd_usb_midi2_endpoint *ep, bool suspending)
226 {
227 	int i;
228 
229 	if (!ep)
230 		return;
231 	if (suspending)
232 		ep->suspended = ep->running;
233 	atomic_set(&ep->running, 0);
234 	for (i = 0; i < ep->num_urbs; i++) {
235 		if (!ep->urbs[i].urb)
236 			break;
237 		usb_kill_urb(ep->urbs[i].urb);
238 	}
239 }
240 
241 /* wait until all URBs get freed */
242 static void drain_urb_queue(struct snd_usb_midi2_endpoint *ep)
243 {
244 	if (!ep)
245 		return;
246 	spin_lock_irq(&ep->lock);
247 	atomic_set(&ep->running, 0);
248 	wait_event_lock_irq_timeout(ep->wait,
249 				    ep->disconnected ||
250 				    ep->urb_free == ep->urb_free_mask,
251 				    ep->lock, msecs_to_jiffies(500));
252 	spin_unlock_irq(&ep->lock);
253 }
254 
255 /* release URBs for an EP */
256 static void free_midi_urbs(struct snd_usb_midi2_endpoint *ep)
257 {
258 	struct snd_usb_midi2_urb *ctx;
259 	int i;
260 
261 	if (!ep)
262 		return;
263 	for (i = 0; i < ep->num_urbs; ++i) {
264 		ctx = &ep->urbs[i];
265 		if (!ctx->urb)
266 			break;
267 		usb_free_coherent(ep->dev, ep->packets,
268 				  ctx->urb->transfer_buffer,
269 				  ctx->urb->transfer_dma);
270 		usb_free_urb(ctx->urb);
271 		ctx->urb = NULL;
272 	}
273 	ep->num_urbs = 0;
274 }
275 
276 /* allocate URBs for an EP */
277 static int alloc_midi_urbs(struct snd_usb_midi2_endpoint *ep)
278 {
279 	struct snd_usb_midi2_urb *ctx;
280 	void (*comp)(struct urb *urb);
281 	void *buffer;
282 	int i, err;
283 	int endpoint, len;
284 
285 	endpoint = ep->endpoint;
286 	len = ep->packets;
287 	if (ep->direction == STR_IN)
288 		comp = input_urb_complete;
289 	else
290 		comp = output_urb_complete;
291 
292 	ep->num_urbs = 0;
293 	ep->urb_free = ep->urb_free_mask = 0;
294 	for (i = 0; i < NUM_URBS; i++) {
295 		ctx = &ep->urbs[i];
296 		ctx->index = i;
297 		ctx->urb = usb_alloc_urb(0, GFP_KERNEL);
298 		if (!ctx->urb) {
299 			dev_err(&ep->dev->dev, "URB alloc failed\n");
300 			return -ENOMEM;
301 		}
302 		ctx->ep = ep;
303 		buffer = usb_alloc_coherent(ep->dev, len, GFP_KERNEL,
304 					    &ctx->urb->transfer_dma);
305 		if (!buffer) {
306 			dev_err(&ep->dev->dev,
307 				"URB buffer alloc failed (size %d)\n", len);
308 			return -ENOMEM;
309 		}
310 		if (ep->interval)
311 			usb_fill_int_urb(ctx->urb, ep->dev, ep->pipe,
312 					 buffer, len, comp, ctx, ep->interval);
313 		else
314 			usb_fill_bulk_urb(ctx->urb, ep->dev, ep->pipe,
315 					  buffer, len, comp, ctx);
316 		err = usb_urb_ep_type_check(ctx->urb);
317 		if (err < 0) {
318 			dev_err(&ep->dev->dev, "invalid MIDI EP %x\n",
319 				endpoint);
320 			return err;
321 		}
322 		ctx->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
323 		ep->num_urbs++;
324 	}
325 	ep->urb_free = ep->urb_free_mask = GENMASK(ep->num_urbs - 1, 0);
326 	return 0;
327 }
328 
329 static struct snd_usb_midi2_endpoint *
330 ump_to_endpoint(struct snd_ump_endpoint *ump, int dir)
331 {
332 	struct snd_usb_midi2_ump *rmidi = ump->private_data;
333 
334 	return rmidi->eps[dir];
335 }
336 
337 /* ump open callback */
338 static int snd_usb_midi_v2_open(struct snd_ump_endpoint *ump, int dir)
339 {
340 	struct snd_usb_midi2_endpoint *ep = ump_to_endpoint(ump, dir);
341 	int err = 0;
342 
343 	if (!ep || !ep->endpoint)
344 		return -ENODEV;
345 	if (ep->disconnected)
346 		return -EIO;
347 	if (ep->direction == STR_OUT) {
348 		err = alloc_midi_urbs(ep);
349 		if (err)
350 			return err;
351 	}
352 	return 0;
353 }
354 
355 /* ump close callback */
356 static void snd_usb_midi_v2_close(struct snd_ump_endpoint *ump, int dir)
357 {
358 	struct snd_usb_midi2_endpoint *ep = ump_to_endpoint(ump, dir);
359 
360 	if (ep->direction == STR_OUT) {
361 		kill_midi_urbs(ep, false);
362 		drain_urb_queue(ep);
363 		free_midi_urbs(ep);
364 	}
365 }
366 
367 /* ump trigger callback */
368 static void snd_usb_midi_v2_trigger(struct snd_ump_endpoint *ump, int dir,
369 				    int up)
370 {
371 	struct snd_usb_midi2_endpoint *ep = ump_to_endpoint(ump, dir);
372 
373 	atomic_set(&ep->running, up);
374 	if (up && ep->direction == STR_OUT && !ep->disconnected)
375 		submit_io_urbs(ep);
376 }
377 
378 /* ump drain callback */
379 static void snd_usb_midi_v2_drain(struct snd_ump_endpoint *ump, int dir)
380 {
381 	struct snd_usb_midi2_endpoint *ep = ump_to_endpoint(ump, dir);
382 
383 	drain_urb_queue(ep);
384 }
385 
386 /* allocate and start all input streams */
387 static int start_input_streams(struct snd_usb_midi2_interface *umidi)
388 {
389 	struct snd_usb_midi2_endpoint *ep;
390 	int err;
391 
392 	list_for_each_entry(ep, &umidi->ep_list, list) {
393 		if (ep->direction == STR_IN) {
394 			err = alloc_midi_urbs(ep);
395 			if (err < 0)
396 				goto error;
397 		}
398 	}
399 
400 	list_for_each_entry(ep, &umidi->ep_list, list) {
401 		if (ep->direction == STR_IN)
402 			submit_io_urbs(ep);
403 	}
404 
405 	return 0;
406 
407  error:
408 	list_for_each_entry(ep, &umidi->ep_list, list) {
409 		if (ep->direction == STR_IN)
410 			free_midi_urbs(ep);
411 	}
412 
413 	return err;
414 }
415 
416 static const struct snd_ump_ops snd_usb_midi_v2_ump_ops = {
417 	.open = snd_usb_midi_v2_open,
418 	.close = snd_usb_midi_v2_close,
419 	.trigger = snd_usb_midi_v2_trigger,
420 	.drain = snd_usb_midi_v2_drain,
421 };
422 
423 /* create a USB MIDI 2.0 endpoint object */
424 static int create_midi2_endpoint(struct snd_usb_midi2_interface *umidi,
425 				 struct usb_host_endpoint *hostep,
426 				 const struct usb_ms20_endpoint_descriptor *ms_ep)
427 {
428 	struct snd_usb_midi2_endpoint *ep;
429 	int endpoint, dir;
430 
431 	usb_audio_dbg(umidi->chip, "Creating an EP 0x%02x, #GTB=%d\n",
432 		      hostep->desc.bEndpointAddress,
433 		      ms_ep->bNumGrpTrmBlock);
434 
435 	ep = kzalloc(sizeof(*ep), GFP_KERNEL);
436 	if (!ep)
437 		return -ENOMEM;
438 
439 	spin_lock_init(&ep->lock);
440 	init_waitqueue_head(&ep->wait);
441 	ep->dev = umidi->chip->dev;
442 	endpoint = hostep->desc.bEndpointAddress;
443 	dir = (endpoint & USB_DIR_IN) ? STR_IN : STR_OUT;
444 
445 	ep->endpoint = endpoint;
446 	ep->direction = dir;
447 	ep->ms_ep = ms_ep;
448 	if (usb_endpoint_xfer_int(&hostep->desc))
449 		ep->interval = hostep->desc.bInterval;
450 	else
451 		ep->interval = 0;
452 	if (dir == STR_IN) {
453 		if (ep->interval)
454 			ep->pipe = usb_rcvintpipe(ep->dev, endpoint);
455 		else
456 			ep->pipe = usb_rcvbulkpipe(ep->dev, endpoint);
457 	} else {
458 		if (ep->interval)
459 			ep->pipe = usb_sndintpipe(ep->dev, endpoint);
460 		else
461 			ep->pipe = usb_sndbulkpipe(ep->dev, endpoint);
462 	}
463 	ep->packets = usb_maxpacket(ep->dev, ep->pipe);
464 	list_add_tail(&ep->list, &umidi->ep_list);
465 
466 	return 0;
467 }
468 
469 /* destructor for endpoint; from snd_usb_midi_v2_free() */
470 static void free_midi2_endpoint(struct snd_usb_midi2_endpoint *ep)
471 {
472 	list_del(&ep->list);
473 	free_midi_urbs(ep);
474 	kfree(ep);
475 }
476 
477 /* call all endpoint destructors */
478 static void free_all_midi2_endpoints(struct snd_usb_midi2_interface *umidi)
479 {
480 	struct snd_usb_midi2_endpoint *ep;
481 
482 	while (!list_empty(&umidi->ep_list)) {
483 		ep = list_first_entry(&umidi->ep_list,
484 				      struct snd_usb_midi2_endpoint, list);
485 		free_midi2_endpoint(ep);
486 	}
487 }
488 
489 /* find a MIDI STREAMING descriptor with a given subtype */
490 static void *find_usb_ms_endpoint_descriptor(struct usb_host_endpoint *hostep,
491 					     unsigned char subtype)
492 {
493 	unsigned char *extra = hostep->extra;
494 	int extralen = hostep->extralen;
495 
496 	while (extralen > 3) {
497 		struct usb_ms_endpoint_descriptor *ms_ep =
498 			(struct usb_ms_endpoint_descriptor *)extra;
499 
500 		if (ms_ep->bLength > 3 &&
501 		    ms_ep->bDescriptorType == USB_DT_CS_ENDPOINT &&
502 		    ms_ep->bDescriptorSubtype == subtype)
503 			return ms_ep;
504 		if (!extra[0])
505 			break;
506 		extralen -= extra[0];
507 		extra += extra[0];
508 	}
509 	return NULL;
510 }
511 
512 /* get the full group terminal block descriptors and return the size */
513 static int get_group_terminal_block_descs(struct snd_usb_midi2_interface *umidi)
514 {
515 	struct usb_host_interface *hostif = umidi->hostif;
516 	struct usb_device *dev = umidi->chip->dev;
517 	struct usb_ms20_gr_trm_block_header_descriptor header = { 0 };
518 	unsigned char *data;
519 	int err, size;
520 
521 	err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0),
522 			      USB_REQ_GET_DESCRIPTOR,
523 			      USB_RECIP_INTERFACE | USB_TYPE_STANDARD | USB_DIR_IN,
524 			      USB_DT_CS_GR_TRM_BLOCK << 8 | hostif->desc.bAlternateSetting,
525 			      hostif->desc.bInterfaceNumber,
526 			      &header, sizeof(header));
527 	if (err < 0)
528 		return err;
529 	size = __le16_to_cpu(header.wTotalLength);
530 	if (!size) {
531 		dev_err(&dev->dev, "Failed to get GTB descriptors for %d:%d\n",
532 			hostif->desc.bInterfaceNumber, hostif->desc.bAlternateSetting);
533 		return -EINVAL;
534 	}
535 
536 	data = kzalloc(size, GFP_KERNEL);
537 	if (!data)
538 		return -ENOMEM;
539 
540 	err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0),
541 			      USB_REQ_GET_DESCRIPTOR,
542 			      USB_RECIP_INTERFACE | USB_TYPE_STANDARD | USB_DIR_IN,
543 			      USB_DT_CS_GR_TRM_BLOCK << 8 | hostif->desc.bAlternateSetting,
544 			      hostif->desc.bInterfaceNumber, data, size);
545 	if (err < 0) {
546 		kfree(data);
547 		return err;
548 	}
549 
550 	umidi->blk_descs = data;
551 	umidi->blk_desc_size = size;
552 	return 0;
553 }
554 
555 /* find the corresponding group terminal block descriptor */
556 static const struct usb_ms20_gr_trm_block_descriptor *
557 find_group_terminal_block(struct snd_usb_midi2_interface *umidi, int id)
558 {
559 	const unsigned char *data = umidi->blk_descs;
560 	int size = umidi->blk_desc_size;
561 	const struct usb_ms20_gr_trm_block_descriptor *desc;
562 
563 	size -= sizeof(struct usb_ms20_gr_trm_block_header_descriptor);
564 	data += sizeof(struct usb_ms20_gr_trm_block_header_descriptor);
565 	while (size > 0 && *data && *data <= size) {
566 		desc = (const struct usb_ms20_gr_trm_block_descriptor *)data;
567 		if (desc->bLength >= sizeof(*desc) &&
568 		    desc->bDescriptorType == USB_DT_CS_GR_TRM_BLOCK &&
569 		    desc->bDescriptorSubtype == USB_MS_GR_TRM_BLOCK &&
570 		    desc->bGrpTrmBlkID == id)
571 			return desc;
572 		size -= *data;
573 		data += *data;
574 	}
575 
576 	return NULL;
577 }
578 
579 /* fill up the information from GTB */
580 static int parse_group_terminal_block(struct snd_usb_midi2_ump *rmidi,
581 				      const struct usb_ms20_gr_trm_block_descriptor *desc)
582 {
583 	struct snd_ump_endpoint *ump = rmidi->ump;
584 	unsigned int protocol, protocol_caps;
585 
586 	/* set default protocol */
587 	switch (desc->bMIDIProtocol) {
588 	case USB_MS_MIDI_PROTO_1_0_64:
589 	case USB_MS_MIDI_PROTO_1_0_64_JRTS:
590 	case USB_MS_MIDI_PROTO_1_0_128:
591 	case USB_MS_MIDI_PROTO_1_0_128_JRTS:
592 		protocol = SNDRV_UMP_EP_INFO_PROTO_MIDI1;
593 		break;
594 	case USB_MS_MIDI_PROTO_2_0:
595 	case USB_MS_MIDI_PROTO_2_0_JRTS:
596 		protocol = SNDRV_UMP_EP_INFO_PROTO_MIDI2;
597 		break;
598 	default:
599 		return 0;
600 	}
601 
602 	if (ump->info.protocol && ump->info.protocol != protocol)
603 		usb_audio_info(rmidi->umidi->chip,
604 			       "Overriding preferred MIDI protocol in GTB %d: %x -> %x\n",
605 			       rmidi->usb_block_id, ump->info.protocol,
606 			       protocol);
607 	ump->info.protocol = protocol;
608 
609 	protocol_caps = protocol;
610 	switch (desc->bMIDIProtocol) {
611 	case USB_MS_MIDI_PROTO_1_0_64_JRTS:
612 	case USB_MS_MIDI_PROTO_1_0_128_JRTS:
613 	case USB_MS_MIDI_PROTO_2_0_JRTS:
614 		protocol_caps |= SNDRV_UMP_EP_INFO_PROTO_JRTS_TX |
615 			SNDRV_UMP_EP_INFO_PROTO_JRTS_RX;
616 		break;
617 	}
618 
619 	if (ump->info.protocol_caps && ump->info.protocol_caps != protocol_caps)
620 		usb_audio_info(rmidi->umidi->chip,
621 			       "Overriding MIDI protocol caps in GTB %d: %x -> %x\n",
622 			       rmidi->usb_block_id, ump->info.protocol_caps,
623 			       protocol_caps);
624 	ump->info.protocol_caps = protocol_caps;
625 
626 	return 0;
627 }
628 
629 /* allocate and parse for each assigned group terminal block */
630 static int parse_group_terminal_blocks(struct snd_usb_midi2_interface *umidi)
631 {
632 	struct snd_usb_midi2_ump *rmidi;
633 	const struct usb_ms20_gr_trm_block_descriptor *desc;
634 	int err;
635 
636 	err = get_group_terminal_block_descs(umidi);
637 	if (err < 0)
638 		return err;
639 	if (!umidi->blk_descs)
640 		return 0;
641 
642 	list_for_each_entry(rmidi, &umidi->rawmidi_list, list) {
643 		desc = find_group_terminal_block(umidi, rmidi->usb_block_id);
644 		if (!desc)
645 			continue;
646 		err = parse_group_terminal_block(rmidi, desc);
647 		if (err < 0)
648 			return err;
649 	}
650 
651 	return 0;
652 }
653 
654 /* parse endpoints included in the given interface and create objects */
655 static int parse_midi_2_0_endpoints(struct snd_usb_midi2_interface *umidi)
656 {
657 	struct usb_host_interface *hostif = umidi->hostif;
658 	struct usb_host_endpoint *hostep;
659 	struct usb_ms20_endpoint_descriptor *ms_ep;
660 	int i, err;
661 
662 	for (i = 0; i < hostif->desc.bNumEndpoints; i++) {
663 		hostep = &hostif->endpoint[i];
664 		if (!usb_endpoint_xfer_bulk(&hostep->desc) &&
665 		    !usb_endpoint_xfer_int(&hostep->desc))
666 			continue;
667 		ms_ep = find_usb_ms_endpoint_descriptor(hostep, USB_MS_GENERAL_2_0);
668 		if (!ms_ep)
669 			continue;
670 		if (ms_ep->bLength <= sizeof(*ms_ep))
671 			continue;
672 		if (!ms_ep->bNumGrpTrmBlock)
673 			continue;
674 		if (ms_ep->bLength < sizeof(*ms_ep) + ms_ep->bNumGrpTrmBlock)
675 			continue;
676 		err = create_midi2_endpoint(umidi, hostep, ms_ep);
677 		if (err < 0)
678 			return err;
679 	}
680 	return 0;
681 }
682 
683 static void free_all_midi2_umps(struct snd_usb_midi2_interface *umidi)
684 {
685 	struct snd_usb_midi2_ump *rmidi;
686 
687 	while (!list_empty(&umidi->rawmidi_list)) {
688 		rmidi = list_first_entry(&umidi->rawmidi_list,
689 					 struct snd_usb_midi2_ump, list);
690 		list_del(&rmidi->list);
691 		kfree(rmidi);
692 	}
693 }
694 
695 static int create_midi2_ump(struct snd_usb_midi2_interface *umidi,
696 			    struct snd_usb_midi2_endpoint *ep_in,
697 			    struct snd_usb_midi2_endpoint *ep_out,
698 			    int blk_id)
699 {
700 	struct snd_usb_midi2_ump *rmidi;
701 	struct snd_ump_endpoint *ump;
702 	int input, output;
703 	char idstr[16];
704 	int err;
705 
706 	rmidi = kzalloc(sizeof(*rmidi), GFP_KERNEL);
707 	if (!rmidi)
708 		return -ENOMEM;
709 	INIT_LIST_HEAD(&rmidi->list);
710 	rmidi->dev = umidi->chip->dev;
711 	rmidi->umidi = umidi;
712 	rmidi->usb_block_id = blk_id;
713 
714 	rmidi->index = umidi->chip->num_rawmidis;
715 	snprintf(idstr, sizeof(idstr), "UMP %d", rmidi->index);
716 	input = ep_in ? 1 : 0;
717 	output = ep_out ? 1 : 0;
718 	err = snd_ump_endpoint_new(umidi->chip->card, idstr, rmidi->index,
719 				   output, input, &ump);
720 	if (err < 0) {
721 		usb_audio_dbg(umidi->chip, "Failed to create a UMP object\n");
722 		kfree(rmidi);
723 		return err;
724 	}
725 
726 	rmidi->ump = ump;
727 	umidi->chip->num_rawmidis++;
728 
729 	ump->private_data = rmidi;
730 	ump->ops = &snd_usb_midi_v2_ump_ops;
731 
732 	rmidi->eps[STR_IN] = ep_in;
733 	rmidi->eps[STR_OUT] = ep_out;
734 	if (ep_in) {
735 		ep_in->pair = ep_out;
736 		ep_in->rmidi = rmidi;
737 		ep_in->ump = ump;
738 	}
739 	if (ep_out) {
740 		ep_out->pair = ep_in;
741 		ep_out->rmidi = rmidi;
742 		ep_out->ump = ump;
743 	}
744 
745 	list_add_tail(&rmidi->list, &umidi->rawmidi_list);
746 	return 0;
747 }
748 
749 /* find the UMP EP with the given USB block id */
750 static struct snd_usb_midi2_ump *
751 find_midi2_ump(struct snd_usb_midi2_interface *umidi, int blk_id)
752 {
753 	struct snd_usb_midi2_ump *rmidi;
754 
755 	list_for_each_entry(rmidi, &umidi->rawmidi_list, list) {
756 		if (rmidi->usb_block_id == blk_id)
757 			return rmidi;
758 	}
759 	return NULL;
760 }
761 
762 /* look for the matching output endpoint and create UMP object if found */
763 static int find_matching_ep_partner(struct snd_usb_midi2_interface *umidi,
764 				    struct snd_usb_midi2_endpoint *ep,
765 				    int blk_id)
766 {
767 	struct snd_usb_midi2_endpoint *pair_ep;
768 	int blk;
769 
770 	usb_audio_dbg(umidi->chip, "Looking for a pair for EP-in 0x%02x\n",
771 		      ep->endpoint);
772 	list_for_each_entry(pair_ep, &umidi->ep_list, list) {
773 		if (pair_ep->direction != STR_OUT)
774 			continue;
775 		if (pair_ep->pair)
776 			continue; /* already paired */
777 		for (blk = 0; blk < pair_ep->ms_ep->bNumGrpTrmBlock; blk++) {
778 			if (pair_ep->ms_ep->baAssoGrpTrmBlkID[blk] == blk_id) {
779 				usb_audio_dbg(umidi->chip,
780 					      "Found a match with EP-out 0x%02x blk %d\n",
781 					      pair_ep->endpoint, blk);
782 				return create_midi2_ump(umidi, ep, pair_ep, blk_id);
783 			}
784 		}
785 	}
786 	return 0;
787 }
788 
789 /* create a UMP block from a GTB entry */
790 static int create_gtb_block(struct snd_usb_midi2_ump *rmidi, int dir, int blk)
791 {
792 	struct snd_usb_midi2_interface *umidi = rmidi->umidi;
793 	const struct usb_ms20_gr_trm_block_descriptor *desc;
794 	struct snd_ump_block *fb;
795 	int type, err;
796 
797 	desc = find_group_terminal_block(umidi, blk);
798 	if (!desc)
799 		return 0;
800 
801 	usb_audio_dbg(umidi->chip,
802 		      "GTB %d: type=%d, group=%d/%d, protocol=%d, in bw=%d, out bw=%d\n",
803 		      blk, desc->bGrpTrmBlkType, desc->nGroupTrm,
804 		      desc->nNumGroupTrm, desc->bMIDIProtocol,
805 		      __le16_to_cpu(desc->wMaxInputBandwidth),
806 		      __le16_to_cpu(desc->wMaxOutputBandwidth));
807 
808 	/* assign the direction */
809 	switch (desc->bGrpTrmBlkType) {
810 	case USB_MS_GR_TRM_BLOCK_TYPE_BIDIRECTIONAL:
811 		type = SNDRV_UMP_DIR_BIDIRECTION;
812 		break;
813 	case USB_MS_GR_TRM_BLOCK_TYPE_INPUT_ONLY:
814 		type = SNDRV_UMP_DIR_INPUT;
815 		break;
816 	case USB_MS_GR_TRM_BLOCK_TYPE_OUTPUT_ONLY:
817 		type = SNDRV_UMP_DIR_OUTPUT;
818 		break;
819 	default:
820 		usb_audio_dbg(umidi->chip, "Unsupported GTB type %d\n",
821 			      desc->bGrpTrmBlkType);
822 		return 0; /* unsupported */
823 	}
824 
825 	/* guess work: set blk-1 as the (0-based) block ID */
826 	err = snd_ump_block_new(rmidi->ump, blk - 1, type,
827 				desc->nGroupTrm, desc->nNumGroupTrm,
828 				&fb);
829 	if (err == -EBUSY)
830 		return 0; /* already present */
831 	else if (err)
832 		return err;
833 
834 	if (desc->iBlockItem)
835 		usb_string(rmidi->dev, desc->iBlockItem,
836 			   fb->info.name, sizeof(fb->info.name));
837 
838 	if (__le16_to_cpu(desc->wMaxInputBandwidth) == 1 ||
839 	    __le16_to_cpu(desc->wMaxOutputBandwidth) == 1)
840 		fb->info.flags |= SNDRV_UMP_BLOCK_IS_MIDI1 |
841 			SNDRV_UMP_BLOCK_IS_LOWSPEED;
842 
843 	usb_audio_dbg(umidi->chip,
844 		      "Created a UMP block %d from GTB, name=%s\n",
845 		      blk, fb->info.name);
846 	return 0;
847 }
848 
849 /* Create UMP blocks for each UMP EP */
850 static int create_blocks_from_gtb(struct snd_usb_midi2_interface *umidi)
851 {
852 	struct snd_usb_midi2_ump *rmidi;
853 	int i, blk, err, dir;
854 
855 	list_for_each_entry(rmidi, &umidi->rawmidi_list, list) {
856 		if (!rmidi->ump)
857 			continue;
858 		/* Blocks have been already created? */
859 		if (rmidi->ump->info.num_blocks)
860 			continue;
861 		/* loop over GTBs */
862 		for (dir = 0; dir < 2; dir++) {
863 			if (!rmidi->eps[dir])
864 				continue;
865 			for (i = 0; i < rmidi->eps[dir]->ms_ep->bNumGrpTrmBlock; i++) {
866 				blk = rmidi->eps[dir]->ms_ep->baAssoGrpTrmBlkID[i];
867 				err = create_gtb_block(rmidi, dir, blk);
868 				if (err < 0)
869 					return err;
870 			}
871 		}
872 	}
873 
874 	return 0;
875 }
876 
877 /* attach legacy rawmidis */
878 static int attach_legacy_rawmidi(struct snd_usb_midi2_interface *umidi)
879 {
880 #if IS_ENABLED(CONFIG_SND_UMP_LEGACY_RAWMIDI)
881 	struct snd_usb_midi2_ump *rmidi;
882 	int err;
883 
884 	list_for_each_entry(rmidi, &umidi->rawmidi_list, list) {
885 		err = snd_ump_attach_legacy_rawmidi(rmidi->ump,
886 						    "Legacy MIDI",
887 						    umidi->chip->num_rawmidis);
888 		if (err < 0)
889 			return err;
890 		umidi->chip->num_rawmidis++;
891 	}
892 #endif
893 	return 0;
894 }
895 
896 static void snd_usb_midi_v2_free(struct snd_usb_midi2_interface *umidi)
897 {
898 	free_all_midi2_endpoints(umidi);
899 	free_all_midi2_umps(umidi);
900 	list_del(&umidi->list);
901 	kfree(umidi->blk_descs);
902 	kfree(umidi);
903 }
904 
905 /* parse the interface for MIDI 2.0 */
906 static int parse_midi_2_0(struct snd_usb_midi2_interface *umidi)
907 {
908 	struct snd_usb_midi2_endpoint *ep;
909 	int blk, id, err;
910 
911 	/* First, create an object for each USB MIDI Endpoint */
912 	err = parse_midi_2_0_endpoints(umidi);
913 	if (err < 0)
914 		return err;
915 	if (list_empty(&umidi->ep_list)) {
916 		usb_audio_warn(umidi->chip, "No MIDI endpoints found\n");
917 		return -ENODEV;
918 	}
919 
920 	/*
921 	 * Next, look for EP I/O pairs that are found in group terminal blocks
922 	 * A UMP object is created for each EP I/O pair as bidirecitonal
923 	 * UMP EP
924 	 */
925 	list_for_each_entry(ep, &umidi->ep_list, list) {
926 		/* only input in this loop; output is matched in find_midi_ump() */
927 		if (ep->direction != STR_IN)
928 			continue;
929 		for (blk = 0; blk < ep->ms_ep->bNumGrpTrmBlock; blk++) {
930 			id = ep->ms_ep->baAssoGrpTrmBlkID[blk];
931 			err = find_matching_ep_partner(umidi, ep, id);
932 			if (err < 0)
933 				return err;
934 		}
935 	}
936 
937 	/*
938 	 * For the remaining EPs, treat as singles, create a UMP object with
939 	 * unidirectional EP
940 	 */
941 	list_for_each_entry(ep, &umidi->ep_list, list) {
942 		if (ep->rmidi)
943 			continue; /* already paired */
944 		for (blk = 0; blk < ep->ms_ep->bNumGrpTrmBlock; blk++) {
945 			id = ep->ms_ep->baAssoGrpTrmBlkID[blk];
946 			if (find_midi2_ump(umidi, id))
947 				continue;
948 			usb_audio_dbg(umidi->chip,
949 				      "Creating a unidirection UMP for EP=0x%02x, blk=%d\n",
950 				      ep->endpoint, id);
951 			if (ep->direction == STR_IN)
952 				err = create_midi2_ump(umidi, ep, NULL, id);
953 			else
954 				err = create_midi2_ump(umidi, NULL, ep, id);
955 			if (err < 0)
956 				return err;
957 			break;
958 		}
959 	}
960 
961 	return attach_legacy_rawmidi(umidi);
962 }
963 
964 /* is the given interface for MIDI 2.0? */
965 static bool is_midi2_altset(struct usb_host_interface *hostif)
966 {
967 	struct usb_ms_header_descriptor *ms_header =
968 		(struct usb_ms_header_descriptor *)hostif->extra;
969 
970 	if (hostif->extralen < 7 ||
971 	    ms_header->bLength < 7 ||
972 	    ms_header->bDescriptorType != USB_DT_CS_INTERFACE ||
973 	    ms_header->bDescriptorSubtype != UAC_HEADER)
974 		return false;
975 
976 	return le16_to_cpu(ms_header->bcdMSC) == USB_MS_REV_MIDI_2_0;
977 }
978 
979 /* change the altsetting */
980 static int set_altset(struct snd_usb_midi2_interface *umidi)
981 {
982 	usb_audio_dbg(umidi->chip, "Setting host iface %d:%d\n",
983 		      umidi->hostif->desc.bInterfaceNumber,
984 		      umidi->hostif->desc.bAlternateSetting);
985 	return usb_set_interface(umidi->chip->dev,
986 				 umidi->hostif->desc.bInterfaceNumber,
987 				 umidi->hostif->desc.bAlternateSetting);
988 }
989 
990 /* fill UMP Endpoint name string from USB descriptor */
991 static void fill_ump_ep_name(struct snd_ump_endpoint *ump,
992 			     struct usb_device *dev, int id)
993 {
994 	int len;
995 
996 	usb_string(dev, id, ump->info.name, sizeof(ump->info.name));
997 
998 	/* trim superfluous "MIDI" suffix */
999 	len = strlen(ump->info.name);
1000 	if (len > 5 && !strcmp(ump->info.name + len - 5, " MIDI"))
1001 		ump->info.name[len - 5] = 0;
1002 }
1003 
1004 /* fill the fallback name string for each rawmidi instance */
1005 static void set_fallback_rawmidi_names(struct snd_usb_midi2_interface *umidi)
1006 {
1007 	struct usb_device *dev = umidi->chip->dev;
1008 	struct snd_usb_midi2_ump *rmidi;
1009 	struct snd_ump_endpoint *ump;
1010 
1011 	list_for_each_entry(rmidi, &umidi->rawmidi_list, list) {
1012 		ump = rmidi->ump;
1013 		/* fill UMP EP name from USB descriptors */
1014 		if (!*ump->info.name && umidi->hostif->desc.iInterface)
1015 			fill_ump_ep_name(ump, dev, umidi->hostif->desc.iInterface);
1016 		else if (!*ump->info.name && dev->descriptor.iProduct)
1017 			fill_ump_ep_name(ump, dev, dev->descriptor.iProduct);
1018 		/* fill fallback name */
1019 		if (!*ump->info.name)
1020 			sprintf(ump->info.name, "USB MIDI %d", rmidi->index);
1021 		/* copy as rawmidi name if not set */
1022 		if (!*ump->core.name)
1023 			strscpy(ump->core.name, ump->info.name,
1024 				sizeof(ump->core.name));
1025 		/* use serial number string as unique UMP product id */
1026 		if (!*ump->info.product_id && dev->descriptor.iSerialNumber)
1027 			usb_string(dev, dev->descriptor.iSerialNumber,
1028 				   ump->info.product_id,
1029 				   sizeof(ump->info.product_id));
1030 #if IS_ENABLED(CONFIG_SND_UMP_LEGACY_RAWMIDI)
1031 		if (ump->legacy_rmidi && !*ump->legacy_rmidi->name)
1032 			snprintf(ump->legacy_rmidi->name,
1033 				 sizeof(ump->legacy_rmidi->name),
1034 				 "%s (MIDI 1.0)", ump->info.name);
1035 #endif
1036 	}
1037 }
1038 
1039 /* create MIDI interface; fallback to MIDI 1.0 if needed */
1040 int snd_usb_midi_v2_create(struct snd_usb_audio *chip,
1041 			   struct usb_interface *iface,
1042 			   const struct snd_usb_audio_quirk *quirk,
1043 			   unsigned int usb_id)
1044 {
1045 	struct snd_usb_midi2_interface *umidi;
1046 	struct usb_host_interface *hostif;
1047 	int err;
1048 
1049 	usb_audio_dbg(chip, "Parsing interface %d...\n",
1050 		      iface->altsetting[0].desc.bInterfaceNumber);
1051 
1052 	/* fallback to MIDI 1.0? */
1053 	if (!midi2_enable) {
1054 		usb_audio_info(chip, "Falling back to MIDI 1.0 by module option\n");
1055 		goto fallback_to_midi1;
1056 	}
1057 	if ((quirk && quirk->type != QUIRK_MIDI_STANDARD_INTERFACE) ||
1058 	    iface->num_altsetting < 2) {
1059 		usb_audio_info(chip, "Quirk or no altest; falling back to MIDI 1.0\n");
1060 		goto fallback_to_midi1;
1061 	}
1062 	hostif = &iface->altsetting[1];
1063 	if (!is_midi2_altset(hostif)) {
1064 		usb_audio_info(chip, "No MIDI 2.0 at altset 1, falling back to MIDI 1.0\n");
1065 		goto fallback_to_midi1;
1066 	}
1067 	if (!hostif->desc.bNumEndpoints) {
1068 		usb_audio_info(chip, "No endpoint at altset 1, falling back to MIDI 1.0\n");
1069 		goto fallback_to_midi1;
1070 	}
1071 
1072 	usb_audio_dbg(chip, "Creating a MIDI 2.0 instance for %d:%d\n",
1073 		      hostif->desc.bInterfaceNumber,
1074 		      hostif->desc.bAlternateSetting);
1075 
1076 	umidi = kzalloc(sizeof(*umidi), GFP_KERNEL);
1077 	if (!umidi)
1078 		return -ENOMEM;
1079 	umidi->chip = chip;
1080 	umidi->iface = iface;
1081 	umidi->hostif = hostif;
1082 	INIT_LIST_HEAD(&umidi->rawmidi_list);
1083 	INIT_LIST_HEAD(&umidi->ep_list);
1084 
1085 	list_add_tail(&umidi->list, &chip->midi_v2_list);
1086 
1087 	err = set_altset(umidi);
1088 	if (err < 0) {
1089 		usb_audio_err(chip, "Failed to set altset\n");
1090 		goto error;
1091 	}
1092 
1093 	/* assume only altset 1 corresponding to MIDI 2.0 interface */
1094 	err = parse_midi_2_0(umidi);
1095 	if (err < 0) {
1096 		usb_audio_err(chip, "Failed to parse MIDI 2.0 interface\n");
1097 		goto error;
1098 	}
1099 
1100 	/* parse USB group terminal blocks */
1101 	err = parse_group_terminal_blocks(umidi);
1102 	if (err < 0) {
1103 		usb_audio_err(chip, "Failed to parse GTB\n");
1104 		goto error;
1105 	}
1106 
1107 	err = start_input_streams(umidi);
1108 	if (err < 0) {
1109 		usb_audio_err(chip, "Failed to start input streams\n");
1110 		goto error;
1111 	}
1112 
1113 	err = create_blocks_from_gtb(umidi);
1114 	if (err < 0) {
1115 		usb_audio_err(chip, "Failed to create GTB blocks\n");
1116 		goto error;
1117 	}
1118 
1119 	set_fallback_rawmidi_names(umidi);
1120 	return 0;
1121 
1122  error:
1123 	snd_usb_midi_v2_free(umidi);
1124 	return err;
1125 
1126  fallback_to_midi1:
1127 	return __snd_usbmidi_create(chip->card, iface, &chip->midi_list,
1128 				    quirk, usb_id, &chip->num_rawmidis);
1129 }
1130 
1131 static void suspend_midi2_endpoint(struct snd_usb_midi2_endpoint *ep)
1132 {
1133 	kill_midi_urbs(ep, true);
1134 	drain_urb_queue(ep);
1135 }
1136 
1137 void snd_usb_midi_v2_suspend_all(struct snd_usb_audio *chip)
1138 {
1139 	struct snd_usb_midi2_interface *umidi;
1140 	struct snd_usb_midi2_endpoint *ep;
1141 
1142 	list_for_each_entry(umidi, &chip->midi_v2_list, list) {
1143 		list_for_each_entry(ep, &umidi->ep_list, list)
1144 			suspend_midi2_endpoint(ep);
1145 	}
1146 }
1147 
1148 static void resume_midi2_endpoint(struct snd_usb_midi2_endpoint *ep)
1149 {
1150 	ep->running = ep->suspended;
1151 	if (ep->direction == STR_IN)
1152 		submit_io_urbs(ep);
1153 	/* FIXME: does it all? */
1154 }
1155 
1156 void snd_usb_midi_v2_resume_all(struct snd_usb_audio *chip)
1157 {
1158 	struct snd_usb_midi2_interface *umidi;
1159 	struct snd_usb_midi2_endpoint *ep;
1160 
1161 	list_for_each_entry(umidi, &chip->midi_v2_list, list) {
1162 		set_altset(umidi);
1163 		list_for_each_entry(ep, &umidi->ep_list, list)
1164 			resume_midi2_endpoint(ep);
1165 	}
1166 }
1167 
1168 void snd_usb_midi_v2_disconnect_all(struct snd_usb_audio *chip)
1169 {
1170 	struct snd_usb_midi2_interface *umidi;
1171 	struct snd_usb_midi2_endpoint *ep;
1172 
1173 	list_for_each_entry(umidi, &chip->midi_v2_list, list) {
1174 		umidi->disconnected = 1;
1175 		list_for_each_entry(ep, &umidi->ep_list, list) {
1176 			ep->disconnected = 1;
1177 			kill_midi_urbs(ep, false);
1178 			drain_urb_queue(ep);
1179 		}
1180 	}
1181 }
1182 
1183 /* release the MIDI instance */
1184 void snd_usb_midi_v2_free_all(struct snd_usb_audio *chip)
1185 {
1186 	struct snd_usb_midi2_interface *umidi, *next;
1187 
1188 	list_for_each_entry_safe(umidi, next, &chip->midi_v2_list, list)
1189 		snd_usb_midi_v2_free(umidi);
1190 }
1191