OSDN Git Service

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