0ee3d39627ae10a496c437bac19959b5cb7cb730
[firefly-linux-kernel-4.4.55.git] / sound / usb / midi.c
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
51 #include <sound/core.h>
52 #include <sound/control.h>
53 #include <sound/rawmidi.h>
54 #include <sound/asequencer.h>
55 #include "usbaudio.h"
56 #include "midi.h"
57 #include "power.h"
58 #include "helper.h"
59
60 /*
61  * define this to log all USB packets
62  */
63 /* #define DUMP_PACKETS */
64
65 /*
66  * how long to wait after some USB errors, so that khubd can disconnect() us
67  * without too many spurious errors
68  */
69 #define ERROR_DELAY_JIFFIES (HZ / 10)
70
71 #define OUTPUT_URBS 7
72 #define INPUT_URBS 7
73
74
75 MODULE_AUTHOR("Clemens Ladisch <clemens@ladisch.de>");
76 MODULE_DESCRIPTION("USB Audio/MIDI helper module");
77 MODULE_LICENSE("Dual BSD/GPL");
78
79
80 struct usb_ms_header_descriptor {
81         __u8  bLength;
82         __u8  bDescriptorType;
83         __u8  bDescriptorSubtype;
84         __u8  bcdMSC[2];
85         __le16 wTotalLength;
86 } __attribute__ ((packed));
87
88 struct usb_ms_endpoint_descriptor {
89         __u8  bLength;
90         __u8  bDescriptorType;
91         __u8  bDescriptorSubtype;
92         __u8  bNumEmbMIDIJack;
93         __u8  baAssocJackID[0];
94 } __attribute__ ((packed));
95
96 struct snd_usb_midi_in_endpoint;
97 struct snd_usb_midi_out_endpoint;
98 struct snd_usb_midi_endpoint;
99
100 struct usb_protocol_ops {
101         void (*input)(struct snd_usb_midi_in_endpoint*, uint8_t*, int);
102         void (*output)(struct snd_usb_midi_out_endpoint *ep, struct urb *urb);
103         void (*output_packet)(struct urb*, uint8_t, uint8_t, uint8_t, uint8_t);
104         void (*init_out_endpoint)(struct snd_usb_midi_out_endpoint*);
105         void (*finish_out_endpoint)(struct snd_usb_midi_out_endpoint*);
106 };
107
108 struct snd_usb_midi {
109         struct usb_device *dev;
110         struct snd_card *card;
111         struct usb_interface *iface;
112         const struct snd_usb_audio_quirk *quirk;
113         struct snd_rawmidi *rmidi;
114         struct usb_protocol_ops* usb_protocol_ops;
115         struct list_head list;
116         struct timer_list error_timer;
117         spinlock_t disc_lock;
118         struct rw_semaphore disc_rwsem;
119         struct mutex mutex;
120         u32 usb_id;
121         int next_midi_device;
122
123         struct snd_usb_midi_endpoint {
124                 struct snd_usb_midi_out_endpoint *out;
125                 struct snd_usb_midi_in_endpoint *in;
126         } endpoints[MIDI_MAX_ENDPOINTS];
127         unsigned long input_triggered;
128         unsigned int opened;
129         unsigned char disconnected;
130
131         struct snd_kcontrol *roland_load_ctl;
132 };
133
134 struct snd_usb_midi_out_endpoint {
135         struct snd_usb_midi* umidi;
136         struct out_urb_context {
137                 struct urb *urb;
138                 struct snd_usb_midi_out_endpoint *ep;
139         } urbs[OUTPUT_URBS];
140         unsigned int active_urbs;
141         unsigned int drain_urbs;
142         int max_transfer;               /* size of urb buffer */
143         struct tasklet_struct tasklet;
144         unsigned int next_urb;
145         spinlock_t buffer_lock;
146
147         struct usbmidi_out_port {
148                 struct snd_usb_midi_out_endpoint* ep;
149                 struct snd_rawmidi_substream *substream;
150                 int active;
151                 bool autopm_reference;
152                 uint8_t cable;          /* cable number << 4 */
153                 uint8_t state;
154 #define STATE_UNKNOWN   0
155 #define STATE_1PARAM    1
156 #define STATE_2PARAM_1  2
157 #define STATE_2PARAM_2  3
158 #define STATE_SYSEX_0   4
159 #define STATE_SYSEX_1   5
160 #define STATE_SYSEX_2   6
161                 uint8_t data[2];
162         } ports[0x10];
163         int current_port;
164
165         wait_queue_head_t drain_wait;
166 };
167
168 struct snd_usb_midi_in_endpoint {
169         struct snd_usb_midi* umidi;
170         struct urb* urbs[INPUT_URBS];
171         struct usbmidi_in_port {
172                 struct snd_rawmidi_substream *substream;
173                 u8 running_status_length;
174         } ports[0x10];
175         u8 seen_f5;
176         u8 error_resubmit;
177         int current_port;
178 };
179
180 static void snd_usbmidi_do_output(struct snd_usb_midi_out_endpoint* ep);
181
182 static const uint8_t snd_usbmidi_cin_length[] = {
183         0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
184 };
185
186 /*
187  * Submits the URB, with error handling.
188  */
189 static int snd_usbmidi_submit_urb(struct urb* urb, gfp_t flags)
190 {
191         int err = usb_submit_urb(urb, flags);
192         if (err < 0 && err != -ENODEV)
193                 snd_printk(KERN_ERR "usb_submit_urb: %d\n", err);
194         return err;
195 }
196
197 /*
198  * Error handling for URB completion functions.
199  */
200 static int snd_usbmidi_urb_error(int status)
201 {
202         switch (status) {
203         /* manually unlinked, or device gone */
204         case -ENOENT:
205         case -ECONNRESET:
206         case -ESHUTDOWN:
207         case -ENODEV:
208                 return -ENODEV;
209         /* errors that might occur during unplugging */
210         case -EPROTO:
211         case -ETIME:
212         case -EILSEQ:
213                 return -EIO;
214         default:
215                 snd_printk(KERN_ERR "urb status %d\n", status);
216                 return 0; /* continue */
217         }
218 }
219
220 /*
221  * Receives a chunk of MIDI data.
222  */
223 static void snd_usbmidi_input_data(struct snd_usb_midi_in_endpoint* ep, int portidx,
224                                    uint8_t* data, int length)
225 {
226         struct usbmidi_in_port* port = &ep->ports[portidx];
227
228         if (!port->substream) {
229                 snd_printd("unexpected port %d!\n", portidx);
230                 return;
231         }
232         if (!test_bit(port->substream->number, &ep->umidi->input_triggered))
233                 return;
234         snd_rawmidi_receive(port->substream, data, length);
235 }
236
237 #ifdef DUMP_PACKETS
238 static void dump_urb(const char *type, const u8 *data, int length)
239 {
240         snd_printk(KERN_DEBUG "%s packet: [", type);
241         for (; length > 0; ++data, --length)
242                 printk(" %02x", *data);
243         printk(" ]\n");
244 }
245 #else
246 #define dump_urb(type, data, length) /* nothing */
247 #endif
248
249 /*
250  * Processes the data read from the device.
251  */
252 static void snd_usbmidi_in_urb_complete(struct urb* urb)
253 {
254         struct snd_usb_midi_in_endpoint* ep = urb->context;
255
256         if (urb->status == 0) {
257                 dump_urb("received", urb->transfer_buffer, urb->actual_length);
258                 ep->umidi->usb_protocol_ops->input(ep, urb->transfer_buffer,
259                                                    urb->actual_length);
260         } else {
261                 int err = snd_usbmidi_urb_error(urb->status);
262                 if (err < 0) {
263                         if (err != -ENODEV) {
264                                 ep->error_resubmit = 1;
265                                 mod_timer(&ep->umidi->error_timer,
266                                           jiffies + ERROR_DELAY_JIFFIES);
267                         }
268                         return;
269                 }
270         }
271
272         urb->dev = ep->umidi->dev;
273         snd_usbmidi_submit_urb(urb, GFP_ATOMIC);
274 }
275
276 static void snd_usbmidi_out_urb_complete(struct urb* urb)
277 {
278         struct out_urb_context *context = urb->context;
279         struct snd_usb_midi_out_endpoint* ep = context->ep;
280         unsigned int urb_index;
281
282         spin_lock(&ep->buffer_lock);
283         urb_index = context - ep->urbs;
284         ep->active_urbs &= ~(1 << urb_index);
285         if (unlikely(ep->drain_urbs)) {
286                 ep->drain_urbs &= ~(1 << urb_index);
287                 wake_up(&ep->drain_wait);
288         }
289         spin_unlock(&ep->buffer_lock);
290         if (urb->status < 0) {
291                 int err = snd_usbmidi_urb_error(urb->status);
292                 if (err < 0) {
293                         if (err != -ENODEV)
294                                 mod_timer(&ep->umidi->error_timer,
295                                           jiffies + ERROR_DELAY_JIFFIES);
296                         return;
297                 }
298         }
299         snd_usbmidi_do_output(ep);
300 }
301
302 /*
303  * This is called when some data should be transferred to the device
304  * (from one or more substreams).
305  */
306 static void snd_usbmidi_do_output(struct snd_usb_midi_out_endpoint* ep)
307 {
308         unsigned int urb_index;
309         struct urb* urb;
310         unsigned long flags;
311
312         spin_lock_irqsave(&ep->buffer_lock, flags);
313         if (ep->umidi->disconnected) {
314                 spin_unlock_irqrestore(&ep->buffer_lock, flags);
315                 return;
316         }
317
318         urb_index = ep->next_urb;
319         for (;;) {
320                 if (!(ep->active_urbs & (1 << urb_index))) {
321                         urb = ep->urbs[urb_index].urb;
322                         urb->transfer_buffer_length = 0;
323                         ep->umidi->usb_protocol_ops->output(ep, urb);
324                         if (urb->transfer_buffer_length == 0)
325                                 break;
326
327                         dump_urb("sending", urb->transfer_buffer,
328                                  urb->transfer_buffer_length);
329                         urb->dev = ep->umidi->dev;
330                         if (snd_usbmidi_submit_urb(urb, GFP_ATOMIC) < 0)
331                                 break;
332                         ep->active_urbs |= 1 << urb_index;
333                 }
334                 if (++urb_index >= OUTPUT_URBS)
335                         urb_index = 0;
336                 if (urb_index == ep->next_urb)
337                         break;
338         }
339         ep->next_urb = urb_index;
340         spin_unlock_irqrestore(&ep->buffer_lock, flags);
341 }
342
343 static void snd_usbmidi_out_tasklet(unsigned long data)
344 {
345         struct snd_usb_midi_out_endpoint* ep = (struct snd_usb_midi_out_endpoint *) data;
346
347         snd_usbmidi_do_output(ep);
348 }
349
350 /* called after transfers had been interrupted due to some USB error */
351 static void snd_usbmidi_error_timer(unsigned long data)
352 {
353         struct snd_usb_midi *umidi = (struct snd_usb_midi *)data;
354         unsigned int i, j;
355
356         spin_lock(&umidi->disc_lock);
357         if (umidi->disconnected) {
358                 spin_unlock(&umidi->disc_lock);
359                 return;
360         }
361         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
362                 struct snd_usb_midi_in_endpoint *in = umidi->endpoints[i].in;
363                 if (in && in->error_resubmit) {
364                         in->error_resubmit = 0;
365                         for (j = 0; j < INPUT_URBS; ++j) {
366                                 in->urbs[j]->dev = umidi->dev;
367                                 snd_usbmidi_submit_urb(in->urbs[j], GFP_ATOMIC);
368                         }
369                 }
370                 if (umidi->endpoints[i].out)
371                         snd_usbmidi_do_output(umidi->endpoints[i].out);
372         }
373         spin_unlock(&umidi->disc_lock);
374 }
375
376 /* helper function to send static data that may not DMA-able */
377 static int send_bulk_static_data(struct snd_usb_midi_out_endpoint* ep,
378                                  const void *data, int len)
379 {
380         int err = 0;
381         void *buf = kmemdup(data, len, GFP_KERNEL);
382         if (!buf)
383                 return -ENOMEM;
384         dump_urb("sending", buf, len);
385         if (ep->urbs[0].urb)
386                 err = usb_bulk_msg(ep->umidi->dev, ep->urbs[0].urb->pipe,
387                                    buf, len, NULL, 250);
388         kfree(buf);
389         return err;
390 }
391
392 /*
393  * Standard USB MIDI protocol: see the spec.
394  * Midiman protocol: like the standard protocol, but the control byte is the
395  * fourth byte in each packet, and uses length instead of CIN.
396  */
397
398 static void snd_usbmidi_standard_input(struct snd_usb_midi_in_endpoint* ep,
399                                        uint8_t* buffer, int buffer_length)
400 {
401         int i;
402
403         for (i = 0; i + 3 < buffer_length; i += 4)
404                 if (buffer[i] != 0) {
405                         int cable = buffer[i] >> 4;
406                         int length = snd_usbmidi_cin_length[buffer[i] & 0x0f];
407                         snd_usbmidi_input_data(ep, cable, &buffer[i + 1], length);
408                 }
409 }
410
411 static void snd_usbmidi_midiman_input(struct snd_usb_midi_in_endpoint* ep,
412                                       uint8_t* buffer, int buffer_length)
413 {
414         int i;
415
416         for (i = 0; i + 3 < buffer_length; i += 4)
417                 if (buffer[i + 3] != 0) {
418                         int port = buffer[i + 3] >> 4;
419                         int length = buffer[i + 3] & 3;
420                         snd_usbmidi_input_data(ep, port, &buffer[i], length);
421                 }
422 }
423
424 /*
425  * Buggy M-Audio device: running status on input results in a packet that has
426  * the data bytes but not the status byte and that is marked with CIN 4.
427  */
428 static void snd_usbmidi_maudio_broken_running_status_input(
429                                         struct snd_usb_midi_in_endpoint* ep,
430                                         uint8_t* buffer, int buffer_length)
431 {
432         int i;
433
434         for (i = 0; i + 3 < buffer_length; i += 4)
435                 if (buffer[i] != 0) {
436                         int cable = buffer[i] >> 4;
437                         u8 cin = buffer[i] & 0x0f;
438                         struct usbmidi_in_port *port = &ep->ports[cable];
439                         int length;
440
441                         length = snd_usbmidi_cin_length[cin];
442                         if (cin == 0xf && buffer[i + 1] >= 0xf8)
443                                 ; /* realtime msg: no running status change */
444                         else if (cin >= 0x8 && cin <= 0xe)
445                                 /* channel msg */
446                                 port->running_status_length = length - 1;
447                         else if (cin == 0x4 &&
448                                  port->running_status_length != 0 &&
449                                  buffer[i + 1] < 0x80)
450                                 /* CIN 4 that is not a SysEx */
451                                 length = port->running_status_length;
452                         else
453                                 /*
454                                  * All other msgs cannot begin running status.
455                                  * (A channel msg sent as two or three CIN 0xF
456                                  * packets could in theory, but this device
457                                  * doesn't use this format.)
458                                  */
459                                 port->running_status_length = 0;
460                         snd_usbmidi_input_data(ep, cable, &buffer[i + 1], length);
461                 }
462 }
463
464 /*
465  * CME protocol: like the standard protocol, but SysEx commands are sent as a
466  * single USB packet preceded by a 0x0F byte.
467  */
468 static void snd_usbmidi_cme_input(struct snd_usb_midi_in_endpoint *ep,
469                                   uint8_t *buffer, int buffer_length)
470 {
471         if (buffer_length < 2 || (buffer[0] & 0x0f) != 0x0f)
472                 snd_usbmidi_standard_input(ep, buffer, buffer_length);
473         else
474                 snd_usbmidi_input_data(ep, buffer[0] >> 4,
475                                        &buffer[1], buffer_length - 1);
476 }
477
478 /*
479  * Adds one USB MIDI packet to the output buffer.
480  */
481 static void snd_usbmidi_output_standard_packet(struct urb* urb, uint8_t p0,
482                                                uint8_t p1, uint8_t p2, uint8_t p3)
483 {
484
485         uint8_t* buf = (uint8_t*)urb->transfer_buffer + urb->transfer_buffer_length;
486         buf[0] = p0;
487         buf[1] = p1;
488         buf[2] = p2;
489         buf[3] = p3;
490         urb->transfer_buffer_length += 4;
491 }
492
493 /*
494  * Adds one Midiman packet to the output buffer.
495  */
496 static void snd_usbmidi_output_midiman_packet(struct urb* urb, uint8_t p0,
497                                               uint8_t p1, uint8_t p2, uint8_t p3)
498 {
499
500         uint8_t* buf = (uint8_t*)urb->transfer_buffer + urb->transfer_buffer_length;
501         buf[0] = p1;
502         buf[1] = p2;
503         buf[2] = p3;
504         buf[3] = (p0 & 0xf0) | snd_usbmidi_cin_length[p0 & 0x0f];
505         urb->transfer_buffer_length += 4;
506 }
507
508 /*
509  * Converts MIDI commands to USB MIDI packets.
510  */
511 static void snd_usbmidi_transmit_byte(struct usbmidi_out_port* port,
512                                       uint8_t b, struct urb* urb)
513 {
514         uint8_t p0 = port->cable;
515         void (*output_packet)(struct urb*, uint8_t, uint8_t, uint8_t, uint8_t) =
516                 port->ep->umidi->usb_protocol_ops->output_packet;
517
518         if (b >= 0xf8) {
519                 output_packet(urb, p0 | 0x0f, b, 0, 0);
520         } else if (b >= 0xf0) {
521                 switch (b) {
522                 case 0xf0:
523                         port->data[0] = b;
524                         port->state = STATE_SYSEX_1;
525                         break;
526                 case 0xf1:
527                 case 0xf3:
528                         port->data[0] = b;
529                         port->state = STATE_1PARAM;
530                         break;
531                 case 0xf2:
532                         port->data[0] = b;
533                         port->state = STATE_2PARAM_1;
534                         break;
535                 case 0xf4:
536                 case 0xf5:
537                         port->state = STATE_UNKNOWN;
538                         break;
539                 case 0xf6:
540                         output_packet(urb, p0 | 0x05, 0xf6, 0, 0);
541                         port->state = STATE_UNKNOWN;
542                         break;
543                 case 0xf7:
544                         switch (port->state) {
545                         case STATE_SYSEX_0:
546                                 output_packet(urb, p0 | 0x05, 0xf7, 0, 0);
547                                 break;
548                         case STATE_SYSEX_1:
549                                 output_packet(urb, p0 | 0x06, port->data[0], 0xf7, 0);
550                                 break;
551                         case STATE_SYSEX_2:
552                                 output_packet(urb, p0 | 0x07, port->data[0], port->data[1], 0xf7);
553                                 break;
554                         }
555                         port->state = STATE_UNKNOWN;
556                         break;
557                 }
558         } else if (b >= 0x80) {
559                 port->data[0] = b;
560                 if (b >= 0xc0 && b <= 0xdf)
561                         port->state = STATE_1PARAM;
562                 else
563                         port->state = STATE_2PARAM_1;
564         } else { /* b < 0x80 */
565                 switch (port->state) {
566                 case STATE_1PARAM:
567                         if (port->data[0] < 0xf0) {
568                                 p0 |= port->data[0] >> 4;
569                         } else {
570                                 p0 |= 0x02;
571                                 port->state = STATE_UNKNOWN;
572                         }
573                         output_packet(urb, p0, port->data[0], b, 0);
574                         break;
575                 case STATE_2PARAM_1:
576                         port->data[1] = b;
577                         port->state = STATE_2PARAM_2;
578                         break;
579                 case STATE_2PARAM_2:
580                         if (port->data[0] < 0xf0) {
581                                 p0 |= port->data[0] >> 4;
582                                 port->state = STATE_2PARAM_1;
583                         } else {
584                                 p0 |= 0x03;
585                                 port->state = STATE_UNKNOWN;
586                         }
587                         output_packet(urb, p0, port->data[0], port->data[1], b);
588                         break;
589                 case STATE_SYSEX_0:
590                         port->data[0] = b;
591                         port->state = STATE_SYSEX_1;
592                         break;
593                 case STATE_SYSEX_1:
594                         port->data[1] = b;
595                         port->state = STATE_SYSEX_2;
596                         break;
597                 case STATE_SYSEX_2:
598                         output_packet(urb, p0 | 0x04, port->data[0], port->data[1], b);
599                         port->state = STATE_SYSEX_0;
600                         break;
601                 }
602         }
603 }
604
605 static void snd_usbmidi_standard_output(struct snd_usb_midi_out_endpoint* ep,
606                                         struct urb *urb)
607 {
608         int p;
609
610         /* FIXME: lower-numbered ports can starve higher-numbered ports */
611         for (p = 0; p < 0x10; ++p) {
612                 struct usbmidi_out_port* port = &ep->ports[p];
613                 if (!port->active)
614                         continue;
615                 while (urb->transfer_buffer_length + 3 < ep->max_transfer) {
616                         uint8_t b;
617                         if (snd_rawmidi_transmit(port->substream, &b, 1) != 1) {
618                                 port->active = 0;
619                                 break;
620                         }
621                         snd_usbmidi_transmit_byte(port, b, urb);
622                 }
623         }
624 }
625
626 static struct usb_protocol_ops snd_usbmidi_standard_ops = {
627         .input = snd_usbmidi_standard_input,
628         .output = snd_usbmidi_standard_output,
629         .output_packet = snd_usbmidi_output_standard_packet,
630 };
631
632 static struct usb_protocol_ops snd_usbmidi_midiman_ops = {
633         .input = snd_usbmidi_midiman_input,
634         .output = snd_usbmidi_standard_output,
635         .output_packet = snd_usbmidi_output_midiman_packet,
636 };
637
638 static struct usb_protocol_ops snd_usbmidi_maudio_broken_running_status_ops = {
639         .input = snd_usbmidi_maudio_broken_running_status_input,
640         .output = snd_usbmidi_standard_output,
641         .output_packet = snd_usbmidi_output_standard_packet,
642 };
643
644 static struct usb_protocol_ops snd_usbmidi_cme_ops = {
645         .input = snd_usbmidi_cme_input,
646         .output = snd_usbmidi_standard_output,
647         .output_packet = snd_usbmidi_output_standard_packet,
648 };
649
650 /*
651  * AKAI MPD16 protocol:
652  *
653  * For control port (endpoint 1):
654  * ==============================
655  * One or more chunks consisting of first byte of (0x10 | msg_len) and then a
656  * SysEx message (msg_len=9 bytes long).
657  *
658  * For data port (endpoint 2):
659  * ===========================
660  * One or more chunks consisting of first byte of (0x20 | msg_len) and then a
661  * MIDI message (msg_len bytes long)
662  *
663  * Messages sent: Active Sense, Note On, Poly Pressure, Control Change.
664  */
665 static void snd_usbmidi_akai_input(struct snd_usb_midi_in_endpoint *ep,
666                                    uint8_t *buffer, int buffer_length)
667 {
668         unsigned int pos = 0;
669         unsigned int len = (unsigned int)buffer_length;
670         while (pos < len) {
671                 unsigned int port = (buffer[pos] >> 4) - 1;
672                 unsigned int msg_len = buffer[pos] & 0x0f;
673                 pos++;
674                 if (pos + msg_len <= len && port < 2)
675                         snd_usbmidi_input_data(ep, 0, &buffer[pos], msg_len);
676                 pos += msg_len;
677         }
678 }
679
680 #define MAX_AKAI_SYSEX_LEN 9
681
682 static void snd_usbmidi_akai_output(struct snd_usb_midi_out_endpoint *ep,
683                                     struct urb *urb)
684 {
685         uint8_t *msg;
686         int pos, end, count, buf_end;
687         uint8_t tmp[MAX_AKAI_SYSEX_LEN];
688         struct snd_rawmidi_substream *substream = ep->ports[0].substream;
689
690         if (!ep->ports[0].active)
691                 return;
692
693         msg = urb->transfer_buffer + urb->transfer_buffer_length;
694         buf_end = ep->max_transfer - MAX_AKAI_SYSEX_LEN - 1;
695
696         /* only try adding more data when there's space for at least 1 SysEx */
697         while (urb->transfer_buffer_length < buf_end) {
698                 count = snd_rawmidi_transmit_peek(substream,
699                                                   tmp, MAX_AKAI_SYSEX_LEN);
700                 if (!count) {
701                         ep->ports[0].active = 0;
702                         return;
703                 }
704                 /* try to skip non-SysEx data */
705                 for (pos = 0; pos < count && tmp[pos] != 0xF0; pos++)
706                         ;
707
708                 if (pos > 0) {
709                         snd_rawmidi_transmit_ack(substream, pos);
710                         continue;
711                 }
712
713                 /* look for the start or end marker */
714                 for (end = 1; end < count && tmp[end] < 0xF0; end++)
715                         ;
716
717                 /* next SysEx started before the end of current one */
718                 if (end < count && tmp[end] == 0xF0) {
719                         /* it's incomplete - drop it */
720                         snd_rawmidi_transmit_ack(substream, end);
721                         continue;
722                 }
723                 /* SysEx complete */
724                 if (end < count && tmp[end] == 0xF7) {
725                         /* queue it, ack it, and get the next one */
726                         count = end + 1;
727                         msg[0] = 0x10 | count;
728                         memcpy(&msg[1], tmp, count);
729                         snd_rawmidi_transmit_ack(substream, count);
730                         urb->transfer_buffer_length += count + 1;
731                         msg += count + 1;
732                         continue;
733                 }
734                 /* less than 9 bytes and no end byte - wait for more */
735                 if (count < MAX_AKAI_SYSEX_LEN) {
736                         ep->ports[0].active = 0;
737                         return;
738                 }
739                 /* 9 bytes and no end marker in sight - malformed, skip it */
740                 snd_rawmidi_transmit_ack(substream, count);
741         }
742 }
743
744 static struct usb_protocol_ops snd_usbmidi_akai_ops = {
745         .input = snd_usbmidi_akai_input,
746         .output = snd_usbmidi_akai_output,
747 };
748
749 /*
750  * Novation USB MIDI protocol: number of data bytes is in the first byte
751  * (when receiving) (+1!) or in the second byte (when sending); data begins
752  * at the third byte.
753  */
754
755 static void snd_usbmidi_novation_input(struct snd_usb_midi_in_endpoint* ep,
756                                        uint8_t* buffer, int buffer_length)
757 {
758         if (buffer_length < 2 || !buffer[0] || buffer_length < buffer[0] + 1)
759                 return;
760         snd_usbmidi_input_data(ep, 0, &buffer[2], buffer[0] - 1);
761 }
762
763 static void snd_usbmidi_novation_output(struct snd_usb_midi_out_endpoint* ep,
764                                         struct urb *urb)
765 {
766         uint8_t* transfer_buffer;
767         int count;
768
769         if (!ep->ports[0].active)
770                 return;
771         transfer_buffer = urb->transfer_buffer;
772         count = snd_rawmidi_transmit(ep->ports[0].substream,
773                                      &transfer_buffer[2],
774                                      ep->max_transfer - 2);
775         if (count < 1) {
776                 ep->ports[0].active = 0;
777                 return;
778         }
779         transfer_buffer[0] = 0;
780         transfer_buffer[1] = count;
781         urb->transfer_buffer_length = 2 + count;
782 }
783
784 static struct usb_protocol_ops snd_usbmidi_novation_ops = {
785         .input = snd_usbmidi_novation_input,
786         .output = snd_usbmidi_novation_output,
787 };
788
789 /*
790  * "raw" protocol: just move raw MIDI bytes from/to the endpoint
791  */
792
793 static void snd_usbmidi_raw_input(struct snd_usb_midi_in_endpoint* ep,
794                                   uint8_t* buffer, int buffer_length)
795 {
796         snd_usbmidi_input_data(ep, 0, buffer, buffer_length);
797 }
798
799 static void snd_usbmidi_raw_output(struct snd_usb_midi_out_endpoint* ep,
800                                    struct urb *urb)
801 {
802         int count;
803
804         if (!ep->ports[0].active)
805                 return;
806         count = snd_rawmidi_transmit(ep->ports[0].substream,
807                                      urb->transfer_buffer,
808                                      ep->max_transfer);
809         if (count < 1) {
810                 ep->ports[0].active = 0;
811                 return;
812         }
813         urb->transfer_buffer_length = count;
814 }
815
816 static struct usb_protocol_ops snd_usbmidi_raw_ops = {
817         .input = snd_usbmidi_raw_input,
818         .output = snd_usbmidi_raw_output,
819 };
820
821 static void snd_usbmidi_us122l_input(struct snd_usb_midi_in_endpoint *ep,
822                                      uint8_t *buffer, int buffer_length)
823 {
824         if (buffer_length != 9)
825                 return;
826         buffer_length = 8;
827         while (buffer_length && buffer[buffer_length - 1] == 0xFD)
828                 buffer_length--;
829         if (buffer_length)
830                 snd_usbmidi_input_data(ep, 0, buffer, buffer_length);
831 }
832
833 static void snd_usbmidi_us122l_output(struct snd_usb_midi_out_endpoint *ep,
834                                       struct urb *urb)
835 {
836         int count;
837
838         if (!ep->ports[0].active)
839                 return;
840         switch (snd_usb_get_speed(ep->umidi->dev)) {
841         case USB_SPEED_HIGH:
842         case USB_SPEED_SUPER:
843                 count = 1;
844                 break;
845         default:
846                 count = 2;
847         }
848         count = snd_rawmidi_transmit(ep->ports[0].substream,
849                                      urb->transfer_buffer,
850                                      count);
851         if (count < 1) {
852                 ep->ports[0].active = 0;
853                 return;
854         }
855
856         memset(urb->transfer_buffer + count, 0xFD, ep->max_transfer - count);
857         urb->transfer_buffer_length = ep->max_transfer;
858 }
859
860 static struct usb_protocol_ops snd_usbmidi_122l_ops = {
861         .input = snd_usbmidi_us122l_input,
862         .output = snd_usbmidi_us122l_output,
863 };
864
865 /*
866  * Emagic USB MIDI protocol: raw MIDI with "F5 xx" port switching.
867  */
868
869 static void snd_usbmidi_emagic_init_out(struct snd_usb_midi_out_endpoint* ep)
870 {
871         static const u8 init_data[] = {
872                 /* initialization magic: "get version" */
873                 0xf0,
874                 0x00, 0x20, 0x31,       /* Emagic */
875                 0x64,                   /* Unitor8 */
876                 0x0b,                   /* version number request */
877                 0x00,                   /* command version */
878                 0x00,                   /* EEPROM, box 0 */
879                 0xf7
880         };
881         send_bulk_static_data(ep, init_data, sizeof(init_data));
882         /* while we're at it, pour on more magic */
883         send_bulk_static_data(ep, init_data, sizeof(init_data));
884 }
885
886 static void snd_usbmidi_emagic_finish_out(struct snd_usb_midi_out_endpoint* ep)
887 {
888         static const u8 finish_data[] = {
889                 /* switch to patch mode with last preset */
890                 0xf0,
891                 0x00, 0x20, 0x31,       /* Emagic */
892                 0x64,                   /* Unitor8 */
893                 0x10,                   /* patch switch command */
894                 0x00,                   /* command version */
895                 0x7f,                   /* to all boxes */
896                 0x40,                   /* last preset in EEPROM */
897                 0xf7
898         };
899         send_bulk_static_data(ep, finish_data, sizeof(finish_data));
900 }
901
902 static void snd_usbmidi_emagic_input(struct snd_usb_midi_in_endpoint* ep,
903                                      uint8_t* buffer, int buffer_length)
904 {
905         int i;
906
907         /* FF indicates end of valid data */
908         for (i = 0; i < buffer_length; ++i)
909                 if (buffer[i] == 0xff) {
910                         buffer_length = i;
911                         break;
912                 }
913
914         /* handle F5 at end of last buffer */
915         if (ep->seen_f5)
916                 goto switch_port;
917
918         while (buffer_length > 0) {
919                 /* determine size of data until next F5 */
920                 for (i = 0; i < buffer_length; ++i)
921                         if (buffer[i] == 0xf5)
922                                 break;
923                 snd_usbmidi_input_data(ep, ep->current_port, buffer, i);
924                 buffer += i;
925                 buffer_length -= i;
926
927                 if (buffer_length <= 0)
928                         break;
929                 /* assert(buffer[0] == 0xf5); */
930                 ep->seen_f5 = 1;
931                 ++buffer;
932                 --buffer_length;
933
934         switch_port:
935                 if (buffer_length <= 0)
936                         break;
937                 if (buffer[0] < 0x80) {
938                         ep->current_port = (buffer[0] - 1) & 15;
939                         ++buffer;
940                         --buffer_length;
941                 }
942                 ep->seen_f5 = 0;
943         }
944 }
945
946 static void snd_usbmidi_emagic_output(struct snd_usb_midi_out_endpoint* ep,
947                                       struct urb *urb)
948 {
949         int port0 = ep->current_port;
950         uint8_t* buf = urb->transfer_buffer;
951         int buf_free = ep->max_transfer;
952         int length, i;
953
954         for (i = 0; i < 0x10; ++i) {
955                 /* round-robin, starting at the last current port */
956                 int portnum = (port0 + i) & 15;
957                 struct usbmidi_out_port* port = &ep->ports[portnum];
958
959                 if (!port->active)
960                         continue;
961                 if (snd_rawmidi_transmit_peek(port->substream, buf, 1) != 1) {
962                         port->active = 0;
963                         continue;
964                 }
965
966                 if (portnum != ep->current_port) {
967                         if (buf_free < 2)
968                                 break;
969                         ep->current_port = portnum;
970                         buf[0] = 0xf5;
971                         buf[1] = (portnum + 1) & 15;
972                         buf += 2;
973                         buf_free -= 2;
974                 }
975
976                 if (buf_free < 1)
977                         break;
978                 length = snd_rawmidi_transmit(port->substream, buf, buf_free);
979                 if (length > 0) {
980                         buf += length;
981                         buf_free -= length;
982                         if (buf_free < 1)
983                                 break;
984                 }
985         }
986         if (buf_free < ep->max_transfer && buf_free > 0) {
987                 *buf = 0xff;
988                 --buf_free;
989         }
990         urb->transfer_buffer_length = ep->max_transfer - buf_free;
991 }
992
993 static struct usb_protocol_ops snd_usbmidi_emagic_ops = {
994         .input = snd_usbmidi_emagic_input,
995         .output = snd_usbmidi_emagic_output,
996         .init_out_endpoint = snd_usbmidi_emagic_init_out,
997         .finish_out_endpoint = snd_usbmidi_emagic_finish_out,
998 };
999
1000
1001 static void update_roland_altsetting(struct snd_usb_midi* umidi)
1002 {
1003         struct usb_interface *intf;
1004         struct usb_host_interface *hostif;
1005         struct usb_interface_descriptor *intfd;
1006         int is_light_load;
1007
1008         intf = umidi->iface;
1009         is_light_load = intf->cur_altsetting != intf->altsetting;
1010         if (umidi->roland_load_ctl->private_value == is_light_load)
1011                 return;
1012         hostif = &intf->altsetting[umidi->roland_load_ctl->private_value];
1013         intfd = get_iface_desc(hostif);
1014         snd_usbmidi_input_stop(&umidi->list);
1015         usb_set_interface(umidi->dev, intfd->bInterfaceNumber,
1016                           intfd->bAlternateSetting);
1017         snd_usbmidi_input_start(&umidi->list);
1018 }
1019
1020 static void substream_open(struct snd_rawmidi_substream *substream, int open)
1021 {
1022         struct snd_usb_midi* umidi = substream->rmidi->private_data;
1023         struct snd_kcontrol *ctl;
1024
1025         down_read(&umidi->disc_rwsem);
1026         if (umidi->disconnected) {
1027                 up_read(&umidi->disc_rwsem);
1028                 return;
1029         }
1030
1031         mutex_lock(&umidi->mutex);
1032         if (open) {
1033                 if (umidi->opened++ == 0 && umidi->roland_load_ctl) {
1034                         ctl = umidi->roland_load_ctl;
1035                         ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
1036                         snd_ctl_notify(umidi->card,
1037                                        SNDRV_CTL_EVENT_MASK_INFO, &ctl->id);
1038                         update_roland_altsetting(umidi);
1039                 }
1040         } else {
1041                 if (--umidi->opened == 0 && umidi->roland_load_ctl) {
1042                         ctl = umidi->roland_load_ctl;
1043                         ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
1044                         snd_ctl_notify(umidi->card,
1045                                        SNDRV_CTL_EVENT_MASK_INFO, &ctl->id);
1046                 }
1047         }
1048         mutex_unlock(&umidi->mutex);
1049         up_read(&umidi->disc_rwsem);
1050 }
1051
1052 static int snd_usbmidi_output_open(struct snd_rawmidi_substream *substream)
1053 {
1054         struct snd_usb_midi* umidi = substream->rmidi->private_data;
1055         struct usbmidi_out_port* port = NULL;
1056         int i, j;
1057         int err;
1058
1059         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
1060                 if (umidi->endpoints[i].out)
1061                         for (j = 0; j < 0x10; ++j)
1062                                 if (umidi->endpoints[i].out->ports[j].substream == substream) {
1063                                         port = &umidi->endpoints[i].out->ports[j];
1064                                         break;
1065                                 }
1066         if (!port) {
1067                 snd_BUG();
1068                 return -ENXIO;
1069         }
1070
1071         down_read(&umidi->disc_rwsem);
1072         if (umidi->disconnected) {
1073                 up_read(&umidi->disc_rwsem);
1074                 return -ENODEV;
1075         }
1076         err = usb_autopm_get_interface(umidi->iface);
1077         port->autopm_reference = err >= 0;
1078         up_read(&umidi->disc_rwsem);
1079         if (err < 0 && err != -EACCES)
1080                 return -EIO;
1081         substream->runtime->private_data = port;
1082         port->state = STATE_UNKNOWN;
1083         substream_open(substream, 1);
1084         return 0;
1085 }
1086
1087 static int snd_usbmidi_output_close(struct snd_rawmidi_substream *substream)
1088 {
1089         struct snd_usb_midi* umidi = substream->rmidi->private_data;
1090         struct usbmidi_out_port *port = substream->runtime->private_data;
1091
1092         substream_open(substream, 0);
1093         down_read(&umidi->disc_rwsem);
1094         if (!umidi->disconnected && port->autopm_reference)
1095                 usb_autopm_put_interface(umidi->iface);
1096         up_read(&umidi->disc_rwsem);
1097         return 0;
1098 }
1099
1100 static void snd_usbmidi_output_trigger(struct snd_rawmidi_substream *substream, int up)
1101 {
1102         struct usbmidi_out_port* port = (struct usbmidi_out_port*)substream->runtime->private_data;
1103
1104         port->active = up;
1105         if (up) {
1106                 if (port->ep->umidi->disconnected) {
1107                         /* gobble up remaining bytes to prevent wait in
1108                          * snd_rawmidi_drain_output */
1109                         while (!snd_rawmidi_transmit_empty(substream))
1110                                 snd_rawmidi_transmit_ack(substream, 1);
1111                         return;
1112                 }
1113                 tasklet_schedule(&port->ep->tasklet);
1114         }
1115 }
1116
1117 static void snd_usbmidi_output_drain(struct snd_rawmidi_substream *substream)
1118 {
1119         struct usbmidi_out_port* port = substream->runtime->private_data;
1120         struct snd_usb_midi_out_endpoint *ep = port->ep;
1121         unsigned int drain_urbs;
1122         DEFINE_WAIT(wait);
1123         long timeout = msecs_to_jiffies(50);
1124
1125         if (ep->umidi->disconnected)
1126                 return;
1127         /*
1128          * The substream buffer is empty, but some data might still be in the
1129          * currently active URBs, so we have to wait for those to complete.
1130          */
1131         spin_lock_irq(&ep->buffer_lock);
1132         drain_urbs = ep->active_urbs;
1133         if (drain_urbs) {
1134                 ep->drain_urbs |= drain_urbs;
1135                 do {
1136                         prepare_to_wait(&ep->drain_wait, &wait,
1137                                         TASK_UNINTERRUPTIBLE);
1138                         spin_unlock_irq(&ep->buffer_lock);
1139                         timeout = schedule_timeout(timeout);
1140                         spin_lock_irq(&ep->buffer_lock);
1141                         drain_urbs &= ep->drain_urbs;
1142                 } while (drain_urbs && timeout);
1143                 finish_wait(&ep->drain_wait, &wait);
1144         }
1145         spin_unlock_irq(&ep->buffer_lock);
1146 }
1147
1148 static int snd_usbmidi_input_open(struct snd_rawmidi_substream *substream)
1149 {
1150         substream_open(substream, 1);
1151         return 0;
1152 }
1153
1154 static int snd_usbmidi_input_close(struct snd_rawmidi_substream *substream)
1155 {
1156         substream_open(substream, 0);
1157         return 0;
1158 }
1159
1160 static void snd_usbmidi_input_trigger(struct snd_rawmidi_substream *substream, int up)
1161 {
1162         struct snd_usb_midi* umidi = substream->rmidi->private_data;
1163
1164         if (up)
1165                 set_bit(substream->number, &umidi->input_triggered);
1166         else
1167                 clear_bit(substream->number, &umidi->input_triggered);
1168 }
1169
1170 static struct snd_rawmidi_ops snd_usbmidi_output_ops = {
1171         .open = snd_usbmidi_output_open,
1172         .close = snd_usbmidi_output_close,
1173         .trigger = snd_usbmidi_output_trigger,
1174         .drain = snd_usbmidi_output_drain,
1175 };
1176
1177 static struct snd_rawmidi_ops snd_usbmidi_input_ops = {
1178         .open = snd_usbmidi_input_open,
1179         .close = snd_usbmidi_input_close,
1180         .trigger = snd_usbmidi_input_trigger
1181 };
1182
1183 static void free_urb_and_buffer(struct snd_usb_midi *umidi, struct urb *urb,
1184                                 unsigned int buffer_length)
1185 {
1186         usb_free_coherent(umidi->dev, buffer_length,
1187                           urb->transfer_buffer, urb->transfer_dma);
1188         usb_free_urb(urb);
1189 }
1190
1191 /*
1192  * Frees an input endpoint.
1193  * May be called when ep hasn't been initialized completely.
1194  */
1195 static void snd_usbmidi_in_endpoint_delete(struct snd_usb_midi_in_endpoint* ep)
1196 {
1197         unsigned int i;
1198
1199         for (i = 0; i < INPUT_URBS; ++i)
1200                 if (ep->urbs[i])
1201                         free_urb_and_buffer(ep->umidi, ep->urbs[i],
1202                                             ep->urbs[i]->transfer_buffer_length);
1203         kfree(ep);
1204 }
1205
1206 /*
1207  * Creates an input endpoint.
1208  */
1209 static int snd_usbmidi_in_endpoint_create(struct snd_usb_midi* umidi,
1210                                           struct snd_usb_midi_endpoint_info* ep_info,
1211                                           struct snd_usb_midi_endpoint* rep)
1212 {
1213         struct snd_usb_midi_in_endpoint* ep;
1214         void* buffer;
1215         unsigned int pipe;
1216         int length;
1217         unsigned int i;
1218
1219         rep->in = NULL;
1220         ep = kzalloc(sizeof(*ep), GFP_KERNEL);
1221         if (!ep)
1222                 return -ENOMEM;
1223         ep->umidi = umidi;
1224
1225         for (i = 0; i < INPUT_URBS; ++i) {
1226                 ep->urbs[i] = usb_alloc_urb(0, GFP_KERNEL);
1227                 if (!ep->urbs[i]) {
1228                         snd_usbmidi_in_endpoint_delete(ep);
1229                         return -ENOMEM;
1230                 }
1231         }
1232         if (ep_info->in_interval)
1233                 pipe = usb_rcvintpipe(umidi->dev, ep_info->in_ep);
1234         else
1235                 pipe = usb_rcvbulkpipe(umidi->dev, ep_info->in_ep);
1236         length = usb_maxpacket(umidi->dev, pipe, 0);
1237         for (i = 0; i < INPUT_URBS; ++i) {
1238                 buffer = usb_alloc_coherent(umidi->dev, length, GFP_KERNEL,
1239                                             &ep->urbs[i]->transfer_dma);
1240                 if (!buffer) {
1241                         snd_usbmidi_in_endpoint_delete(ep);
1242                         return -ENOMEM;
1243                 }
1244                 if (ep_info->in_interval)
1245                         usb_fill_int_urb(ep->urbs[i], umidi->dev,
1246                                          pipe, buffer, length,
1247                                          snd_usbmidi_in_urb_complete,
1248                                          ep, ep_info->in_interval);
1249                 else
1250                         usb_fill_bulk_urb(ep->urbs[i], umidi->dev,
1251                                           pipe, buffer, length,
1252                                           snd_usbmidi_in_urb_complete, ep);
1253                 ep->urbs[i]->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1254         }
1255
1256         rep->in = ep;
1257         return 0;
1258 }
1259
1260 /*
1261  * Frees an output endpoint.
1262  * May be called when ep hasn't been initialized completely.
1263  */
1264 static void snd_usbmidi_out_endpoint_clear(struct snd_usb_midi_out_endpoint *ep)
1265 {
1266         unsigned int i;
1267
1268         for (i = 0; i < OUTPUT_URBS; ++i)
1269                 if (ep->urbs[i].urb) {
1270                         free_urb_and_buffer(ep->umidi, ep->urbs[i].urb,
1271                                             ep->max_transfer);
1272                         ep->urbs[i].urb = NULL;
1273                 }
1274 }
1275
1276 static void snd_usbmidi_out_endpoint_delete(struct snd_usb_midi_out_endpoint *ep)
1277 {
1278         snd_usbmidi_out_endpoint_clear(ep);
1279         kfree(ep);
1280 }
1281
1282 /*
1283  * Creates an output endpoint, and initializes output ports.
1284  */
1285 static int snd_usbmidi_out_endpoint_create(struct snd_usb_midi* umidi,
1286                                            struct snd_usb_midi_endpoint_info* ep_info,
1287                                            struct snd_usb_midi_endpoint* rep)
1288 {
1289         struct snd_usb_midi_out_endpoint* ep;
1290         unsigned int i;
1291         unsigned int pipe;
1292         void* buffer;
1293
1294         rep->out = NULL;
1295         ep = kzalloc(sizeof(*ep), GFP_KERNEL);
1296         if (!ep)
1297                 return -ENOMEM;
1298         ep->umidi = umidi;
1299
1300         for (i = 0; i < OUTPUT_URBS; ++i) {
1301                 ep->urbs[i].urb = usb_alloc_urb(0, GFP_KERNEL);
1302                 if (!ep->urbs[i].urb) {
1303                         snd_usbmidi_out_endpoint_delete(ep);
1304                         return -ENOMEM;
1305                 }
1306                 ep->urbs[i].ep = ep;
1307         }
1308         if (ep_info->out_interval)
1309                 pipe = usb_sndintpipe(umidi->dev, ep_info->out_ep);
1310         else
1311                 pipe = usb_sndbulkpipe(umidi->dev, ep_info->out_ep);
1312         switch (umidi->usb_id) {
1313         default:
1314                 ep->max_transfer = usb_maxpacket(umidi->dev, pipe, 1);
1315                 break;
1316                 /*
1317                  * Various chips declare a packet size larger than 4 bytes, but
1318                  * do not actually work with larger packets:
1319                  */
1320         case USB_ID(0x0a92, 0x1020): /* ESI M4U */
1321         case USB_ID(0x1430, 0x474b): /* RedOctane GH MIDI INTERFACE */
1322         case USB_ID(0x15ca, 0x0101): /* Textech USB Midi Cable */
1323         case USB_ID(0x15ca, 0x1806): /* Textech USB Midi Cable */
1324         case USB_ID(0x1a86, 0x752d): /* QinHeng CH345 "USB2.0-MIDI" */
1325         case USB_ID(0xfc08, 0x0101): /* Unknown vendor Cable */
1326                 ep->max_transfer = 4;
1327                 break;
1328                 /*
1329                  * Some devices only work with 9 bytes packet size:
1330                  */
1331         case USB_ID(0x0644, 0x800E): /* Tascam US-122L */
1332         case USB_ID(0x0644, 0x800F): /* Tascam US-144 */
1333                 ep->max_transfer = 9;
1334                 break;
1335         }
1336         for (i = 0; i < OUTPUT_URBS; ++i) {
1337                 buffer = usb_alloc_coherent(umidi->dev,
1338                                             ep->max_transfer, GFP_KERNEL,
1339                                             &ep->urbs[i].urb->transfer_dma);
1340                 if (!buffer) {
1341                         snd_usbmidi_out_endpoint_delete(ep);
1342                         return -ENOMEM;
1343                 }
1344                 if (ep_info->out_interval)
1345                         usb_fill_int_urb(ep->urbs[i].urb, umidi->dev,
1346                                          pipe, buffer, ep->max_transfer,
1347                                          snd_usbmidi_out_urb_complete,
1348                                          &ep->urbs[i], ep_info->out_interval);
1349                 else
1350                         usb_fill_bulk_urb(ep->urbs[i].urb, umidi->dev,
1351                                           pipe, buffer, ep->max_transfer,
1352                                           snd_usbmidi_out_urb_complete,
1353                                           &ep->urbs[i]);
1354                 ep->urbs[i].urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
1355         }
1356
1357         spin_lock_init(&ep->buffer_lock);
1358         tasklet_init(&ep->tasklet, snd_usbmidi_out_tasklet, (unsigned long)ep);
1359         init_waitqueue_head(&ep->drain_wait);
1360
1361         for (i = 0; i < 0x10; ++i)
1362                 if (ep_info->out_cables & (1 << i)) {
1363                         ep->ports[i].ep = ep;
1364                         ep->ports[i].cable = i << 4;
1365                 }
1366
1367         if (umidi->usb_protocol_ops->init_out_endpoint)
1368                 umidi->usb_protocol_ops->init_out_endpoint(ep);
1369
1370         rep->out = ep;
1371         return 0;
1372 }
1373
1374 /*
1375  * Frees everything.
1376  */
1377 static void snd_usbmidi_free(struct snd_usb_midi* umidi)
1378 {
1379         int i;
1380
1381         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1382                 struct snd_usb_midi_endpoint* ep = &umidi->endpoints[i];
1383                 if (ep->out)
1384                         snd_usbmidi_out_endpoint_delete(ep->out);
1385                 if (ep->in)
1386                         snd_usbmidi_in_endpoint_delete(ep->in);
1387         }
1388         mutex_destroy(&umidi->mutex);
1389         kfree(umidi);
1390 }
1391
1392 /*
1393  * Unlinks all URBs (must be done before the usb_device is deleted).
1394  */
1395 void snd_usbmidi_disconnect(struct list_head* p)
1396 {
1397         struct snd_usb_midi* umidi;
1398         unsigned int i, j;
1399
1400         umidi = list_entry(p, struct snd_usb_midi, list);
1401         /*
1402          * an URB's completion handler may start the timer and
1403          * a timer may submit an URB. To reliably break the cycle
1404          * a flag under lock must be used
1405          */
1406         down_write(&umidi->disc_rwsem);
1407         spin_lock_irq(&umidi->disc_lock);
1408         umidi->disconnected = 1;
1409         spin_unlock_irq(&umidi->disc_lock);
1410         up_write(&umidi->disc_rwsem);
1411
1412         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1413                 struct snd_usb_midi_endpoint* ep = &umidi->endpoints[i];
1414                 if (ep->out)
1415                         tasklet_kill(&ep->out->tasklet);
1416                 if (ep->out) {
1417                         for (j = 0; j < OUTPUT_URBS; ++j)
1418                                 usb_kill_urb(ep->out->urbs[j].urb);
1419                         if (umidi->usb_protocol_ops->finish_out_endpoint)
1420                                 umidi->usb_protocol_ops->finish_out_endpoint(ep->out);
1421                         ep->out->active_urbs = 0;
1422                         if (ep->out->drain_urbs) {
1423                                 ep->out->drain_urbs = 0;
1424                                 wake_up(&ep->out->drain_wait);
1425                         }
1426                 }
1427                 if (ep->in)
1428                         for (j = 0; j < INPUT_URBS; ++j)
1429                                 usb_kill_urb(ep->in->urbs[j]);
1430                 /* free endpoints here; later call can result in Oops */
1431                 if (ep->out)
1432                         snd_usbmidi_out_endpoint_clear(ep->out);
1433                 if (ep->in) {
1434                         snd_usbmidi_in_endpoint_delete(ep->in);
1435                         ep->in = NULL;
1436                 }
1437         }
1438         del_timer_sync(&umidi->error_timer);
1439 }
1440
1441 static void snd_usbmidi_rawmidi_free(struct snd_rawmidi *rmidi)
1442 {
1443         struct snd_usb_midi* umidi = rmidi->private_data;
1444         snd_usbmidi_free(umidi);
1445 }
1446
1447 static struct snd_rawmidi_substream *snd_usbmidi_find_substream(struct snd_usb_midi* umidi,
1448                                                                 int stream, int number)
1449 {
1450         struct list_head* list;
1451
1452         list_for_each(list, &umidi->rmidi->streams[stream].substreams) {
1453                 struct snd_rawmidi_substream *substream = list_entry(list, struct snd_rawmidi_substream, list);
1454                 if (substream->number == number)
1455                         return substream;
1456         }
1457         return NULL;
1458 }
1459
1460 /*
1461  * This list specifies names for ports that do not fit into the standard
1462  * "(product) MIDI (n)" schema because they aren't external MIDI ports,
1463  * such as internal control or synthesizer ports.
1464  */
1465 static struct port_info {
1466         u32 id;
1467         short int port;
1468         short int voices;
1469         const char *name;
1470         unsigned int seq_flags;
1471 } snd_usbmidi_port_info[] = {
1472 #define PORT_INFO(vendor, product, num, name_, voices_, flags) \
1473         { .id = USB_ID(vendor, product), \
1474           .port = num, .voices = voices_, \
1475           .name = name_, .seq_flags = flags }
1476 #define EXTERNAL_PORT(vendor, product, num, name) \
1477         PORT_INFO(vendor, product, num, name, 0, \
1478                   SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1479                   SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1480                   SNDRV_SEQ_PORT_TYPE_PORT)
1481 #define CONTROL_PORT(vendor, product, num, name) \
1482         PORT_INFO(vendor, product, num, name, 0, \
1483                   SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1484                   SNDRV_SEQ_PORT_TYPE_HARDWARE)
1485 #define ROLAND_SYNTH_PORT(vendor, product, num, name, voices) \
1486         PORT_INFO(vendor, product, num, name, voices, \
1487                   SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1488                   SNDRV_SEQ_PORT_TYPE_MIDI_GM | \
1489                   SNDRV_SEQ_PORT_TYPE_MIDI_GM2 | \
1490                   SNDRV_SEQ_PORT_TYPE_MIDI_GS | \
1491                   SNDRV_SEQ_PORT_TYPE_MIDI_XG | \
1492                   SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1493                   SNDRV_SEQ_PORT_TYPE_SYNTHESIZER)
1494 #define SOUNDCANVAS_PORT(vendor, product, num, name, voices) \
1495         PORT_INFO(vendor, product, num, name, voices, \
1496                   SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | \
1497                   SNDRV_SEQ_PORT_TYPE_MIDI_GM | \
1498                   SNDRV_SEQ_PORT_TYPE_MIDI_GM2 | \
1499                   SNDRV_SEQ_PORT_TYPE_MIDI_GS | \
1500                   SNDRV_SEQ_PORT_TYPE_MIDI_XG | \
1501                   SNDRV_SEQ_PORT_TYPE_MIDI_MT32 | \
1502                   SNDRV_SEQ_PORT_TYPE_HARDWARE | \
1503                   SNDRV_SEQ_PORT_TYPE_SYNTHESIZER)
1504         /* Roland UA-100 */
1505         CONTROL_PORT(0x0582, 0x0000, 2, "%s Control"),
1506         /* Roland SC-8850 */
1507         SOUNDCANVAS_PORT(0x0582, 0x0003, 0, "%s Part A", 128),
1508         SOUNDCANVAS_PORT(0x0582, 0x0003, 1, "%s Part B", 128),
1509         SOUNDCANVAS_PORT(0x0582, 0x0003, 2, "%s Part C", 128),
1510         SOUNDCANVAS_PORT(0x0582, 0x0003, 3, "%s Part D", 128),
1511         EXTERNAL_PORT(0x0582, 0x0003, 4, "%s MIDI 1"),
1512         EXTERNAL_PORT(0x0582, 0x0003, 5, "%s MIDI 2"),
1513         /* Roland U-8 */
1514         EXTERNAL_PORT(0x0582, 0x0004, 0, "%s MIDI"),
1515         CONTROL_PORT(0x0582, 0x0004, 1, "%s Control"),
1516         /* Roland SC-8820 */
1517         SOUNDCANVAS_PORT(0x0582, 0x0007, 0, "%s Part A", 64),
1518         SOUNDCANVAS_PORT(0x0582, 0x0007, 1, "%s Part B", 64),
1519         EXTERNAL_PORT(0x0582, 0x0007, 2, "%s MIDI"),
1520         /* Roland SK-500 */
1521         SOUNDCANVAS_PORT(0x0582, 0x000b, 0, "%s Part A", 64),
1522         SOUNDCANVAS_PORT(0x0582, 0x000b, 1, "%s Part B", 64),
1523         EXTERNAL_PORT(0x0582, 0x000b, 2, "%s MIDI"),
1524         /* Roland SC-D70 */
1525         SOUNDCANVAS_PORT(0x0582, 0x000c, 0, "%s Part A", 64),
1526         SOUNDCANVAS_PORT(0x0582, 0x000c, 1, "%s Part B", 64),
1527         EXTERNAL_PORT(0x0582, 0x000c, 2, "%s MIDI"),
1528         /* Edirol UM-880 */
1529         CONTROL_PORT(0x0582, 0x0014, 8, "%s Control"),
1530         /* Edirol SD-90 */
1531         ROLAND_SYNTH_PORT(0x0582, 0x0016, 0, "%s Part A", 128),
1532         ROLAND_SYNTH_PORT(0x0582, 0x0016, 1, "%s Part B", 128),
1533         EXTERNAL_PORT(0x0582, 0x0016, 2, "%s MIDI 1"),
1534         EXTERNAL_PORT(0x0582, 0x0016, 3, "%s MIDI 2"),
1535         /* Edirol UM-550 */
1536         CONTROL_PORT(0x0582, 0x0023, 5, "%s Control"),
1537         /* Edirol SD-20 */
1538         ROLAND_SYNTH_PORT(0x0582, 0x0027, 0, "%s Part A", 64),
1539         ROLAND_SYNTH_PORT(0x0582, 0x0027, 1, "%s Part B", 64),
1540         EXTERNAL_PORT(0x0582, 0x0027, 2, "%s MIDI"),
1541         /* Edirol SD-80 */
1542         ROLAND_SYNTH_PORT(0x0582, 0x0029, 0, "%s Part A", 128),
1543         ROLAND_SYNTH_PORT(0x0582, 0x0029, 1, "%s Part B", 128),
1544         EXTERNAL_PORT(0x0582, 0x0029, 2, "%s MIDI 1"),
1545         EXTERNAL_PORT(0x0582, 0x0029, 3, "%s MIDI 2"),
1546         /* Edirol UA-700 */
1547         EXTERNAL_PORT(0x0582, 0x002b, 0, "%s MIDI"),
1548         CONTROL_PORT(0x0582, 0x002b, 1, "%s Control"),
1549         /* Roland VariOS */
1550         EXTERNAL_PORT(0x0582, 0x002f, 0, "%s MIDI"),
1551         EXTERNAL_PORT(0x0582, 0x002f, 1, "%s External MIDI"),
1552         EXTERNAL_PORT(0x0582, 0x002f, 2, "%s Sync"),
1553         /* Edirol PCR */
1554         EXTERNAL_PORT(0x0582, 0x0033, 0, "%s MIDI"),
1555         EXTERNAL_PORT(0x0582, 0x0033, 1, "%s 1"),
1556         EXTERNAL_PORT(0x0582, 0x0033, 2, "%s 2"),
1557         /* BOSS GS-10 */
1558         EXTERNAL_PORT(0x0582, 0x003b, 0, "%s MIDI"),
1559         CONTROL_PORT(0x0582, 0x003b, 1, "%s Control"),
1560         /* Edirol UA-1000 */
1561         EXTERNAL_PORT(0x0582, 0x0044, 0, "%s MIDI"),
1562         CONTROL_PORT(0x0582, 0x0044, 1, "%s Control"),
1563         /* Edirol UR-80 */
1564         EXTERNAL_PORT(0x0582, 0x0048, 0, "%s MIDI"),
1565         EXTERNAL_PORT(0x0582, 0x0048, 1, "%s 1"),
1566         EXTERNAL_PORT(0x0582, 0x0048, 2, "%s 2"),
1567         /* Edirol PCR-A */
1568         EXTERNAL_PORT(0x0582, 0x004d, 0, "%s MIDI"),
1569         EXTERNAL_PORT(0x0582, 0x004d, 1, "%s 1"),
1570         EXTERNAL_PORT(0x0582, 0x004d, 2, "%s 2"),
1571         /* Edirol UM-3EX */
1572         CONTROL_PORT(0x0582, 0x009a, 3, "%s Control"),
1573         /* M-Audio MidiSport 8x8 */
1574         CONTROL_PORT(0x0763, 0x1031, 8, "%s Control"),
1575         CONTROL_PORT(0x0763, 0x1033, 8, "%s Control"),
1576         /* MOTU Fastlane */
1577         EXTERNAL_PORT(0x07fd, 0x0001, 0, "%s MIDI A"),
1578         EXTERNAL_PORT(0x07fd, 0x0001, 1, "%s MIDI B"),
1579         /* Emagic Unitor8/AMT8/MT4 */
1580         EXTERNAL_PORT(0x086a, 0x0001, 8, "%s Broadcast"),
1581         EXTERNAL_PORT(0x086a, 0x0002, 8, "%s Broadcast"),
1582         EXTERNAL_PORT(0x086a, 0x0003, 4, "%s Broadcast"),
1583         /* Akai MPD16 */
1584         CONTROL_PORT(0x09e8, 0x0062, 0, "%s Control"),
1585         PORT_INFO(0x09e8, 0x0062, 1, "%s MIDI", 0,
1586                 SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC |
1587                 SNDRV_SEQ_PORT_TYPE_HARDWARE),
1588         /* Access Music Virus TI */
1589         EXTERNAL_PORT(0x133e, 0x0815, 0, "%s MIDI"),
1590         PORT_INFO(0x133e, 0x0815, 1, "%s Synth", 0,
1591                 SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC |
1592                 SNDRV_SEQ_PORT_TYPE_HARDWARE |
1593                 SNDRV_SEQ_PORT_TYPE_SYNTHESIZER),
1594 };
1595
1596 static struct port_info *find_port_info(struct snd_usb_midi* umidi, int number)
1597 {
1598         int i;
1599
1600         for (i = 0; i < ARRAY_SIZE(snd_usbmidi_port_info); ++i) {
1601                 if (snd_usbmidi_port_info[i].id == umidi->usb_id &&
1602                     snd_usbmidi_port_info[i].port == number)
1603                         return &snd_usbmidi_port_info[i];
1604         }
1605         return NULL;
1606 }
1607
1608 static void snd_usbmidi_get_port_info(struct snd_rawmidi *rmidi, int number,
1609                                       struct snd_seq_port_info *seq_port_info)
1610 {
1611         struct snd_usb_midi *umidi = rmidi->private_data;
1612         struct port_info *port_info;
1613
1614         /* TODO: read port flags from descriptors */
1615         port_info = find_port_info(umidi, number);
1616         if (port_info) {
1617                 seq_port_info->type = port_info->seq_flags;
1618                 seq_port_info->midi_voices = port_info->voices;
1619         }
1620 }
1621
1622 static void snd_usbmidi_init_substream(struct snd_usb_midi* umidi,
1623                                        int stream, int number,
1624                                        struct snd_rawmidi_substream ** rsubstream)
1625 {
1626         struct port_info *port_info;
1627         const char *name_format;
1628
1629         struct snd_rawmidi_substream *substream = snd_usbmidi_find_substream(umidi, stream, number);
1630         if (!substream) {
1631                 snd_printd(KERN_ERR "substream %d:%d not found\n", stream, number);
1632                 return;
1633         }
1634
1635         /* TODO: read port name from jack descriptor */
1636         port_info = find_port_info(umidi, number);
1637         name_format = port_info ? port_info->name : "%s MIDI %d";
1638         snprintf(substream->name, sizeof(substream->name),
1639                  name_format, umidi->card->shortname, number + 1);
1640
1641         *rsubstream = substream;
1642 }
1643
1644 /*
1645  * Creates the endpoints and their ports.
1646  */
1647 static int snd_usbmidi_create_endpoints(struct snd_usb_midi* umidi,
1648                                         struct snd_usb_midi_endpoint_info* endpoints)
1649 {
1650         int i, j, err;
1651         int out_ports = 0, in_ports = 0;
1652
1653         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1654                 if (endpoints[i].out_cables) {
1655                         err = snd_usbmidi_out_endpoint_create(umidi, &endpoints[i],
1656                                                               &umidi->endpoints[i]);
1657                         if (err < 0)
1658                                 return err;
1659                 }
1660                 if (endpoints[i].in_cables) {
1661                         err = snd_usbmidi_in_endpoint_create(umidi, &endpoints[i],
1662                                                              &umidi->endpoints[i]);
1663                         if (err < 0)
1664                                 return err;
1665                 }
1666
1667                 for (j = 0; j < 0x10; ++j) {
1668                         if (endpoints[i].out_cables & (1 << j)) {
1669                                 snd_usbmidi_init_substream(umidi, SNDRV_RAWMIDI_STREAM_OUTPUT, out_ports,
1670                                                            &umidi->endpoints[i].out->ports[j].substream);
1671                                 ++out_ports;
1672                         }
1673                         if (endpoints[i].in_cables & (1 << j)) {
1674                                 snd_usbmidi_init_substream(umidi, SNDRV_RAWMIDI_STREAM_INPUT, in_ports,
1675                                                            &umidi->endpoints[i].in->ports[j].substream);
1676                                 ++in_ports;
1677                         }
1678                 }
1679         }
1680         snd_printdd(KERN_INFO "created %d output and %d input ports\n",
1681                     out_ports, in_ports);
1682         return 0;
1683 }
1684
1685 /*
1686  * Returns MIDIStreaming device capabilities.
1687  */
1688 static int snd_usbmidi_get_ms_info(struct snd_usb_midi* umidi,
1689                                    struct snd_usb_midi_endpoint_info* endpoints)
1690 {
1691         struct usb_interface* intf;
1692         struct usb_host_interface *hostif;
1693         struct usb_interface_descriptor* intfd;
1694         struct usb_ms_header_descriptor* ms_header;
1695         struct usb_host_endpoint *hostep;
1696         struct usb_endpoint_descriptor* ep;
1697         struct usb_ms_endpoint_descriptor* ms_ep;
1698         int i, epidx;
1699
1700         intf = umidi->iface;
1701         if (!intf)
1702                 return -ENXIO;
1703         hostif = &intf->altsetting[0];
1704         intfd = get_iface_desc(hostif);
1705         ms_header = (struct usb_ms_header_descriptor*)hostif->extra;
1706         if (hostif->extralen >= 7 &&
1707             ms_header->bLength >= 7 &&
1708             ms_header->bDescriptorType == USB_DT_CS_INTERFACE &&
1709             ms_header->bDescriptorSubtype == UAC_HEADER)
1710                 snd_printdd(KERN_INFO "MIDIStreaming version %02x.%02x\n",
1711                             ms_header->bcdMSC[1], ms_header->bcdMSC[0]);
1712         else
1713                 snd_printk(KERN_WARNING "MIDIStreaming interface descriptor not found\n");
1714
1715         epidx = 0;
1716         for (i = 0; i < intfd->bNumEndpoints; ++i) {
1717                 hostep = &hostif->endpoint[i];
1718                 ep = get_ep_desc(hostep);
1719                 if (!usb_endpoint_xfer_bulk(ep) && !usb_endpoint_xfer_int(ep))
1720                         continue;
1721                 ms_ep = (struct usb_ms_endpoint_descriptor*)hostep->extra;
1722                 if (hostep->extralen < 4 ||
1723                     ms_ep->bLength < 4 ||
1724                     ms_ep->bDescriptorType != USB_DT_CS_ENDPOINT ||
1725                     ms_ep->bDescriptorSubtype != UAC_MS_GENERAL)
1726                         continue;
1727                 if (usb_endpoint_dir_out(ep)) {
1728                         if (endpoints[epidx].out_ep) {
1729                                 if (++epidx >= MIDI_MAX_ENDPOINTS) {
1730                                         snd_printk(KERN_WARNING "too many endpoints\n");
1731                                         break;
1732                                 }
1733                         }
1734                         endpoints[epidx].out_ep = usb_endpoint_num(ep);
1735                         if (usb_endpoint_xfer_int(ep))
1736                                 endpoints[epidx].out_interval = ep->bInterval;
1737                         else if (snd_usb_get_speed(umidi->dev) == USB_SPEED_LOW)
1738                                 /*
1739                                  * Low speed bulk transfers don't exist, so
1740                                  * force interrupt transfers for devices like
1741                                  * ESI MIDI Mate that try to use them anyway.
1742                                  */
1743                                 endpoints[epidx].out_interval = 1;
1744                         endpoints[epidx].out_cables = (1 << ms_ep->bNumEmbMIDIJack) - 1;
1745                         snd_printdd(KERN_INFO "EP %02X: %d jack(s)\n",
1746                                     ep->bEndpointAddress, ms_ep->bNumEmbMIDIJack);
1747                 } else {
1748                         if (endpoints[epidx].in_ep) {
1749                                 if (++epidx >= MIDI_MAX_ENDPOINTS) {
1750                                         snd_printk(KERN_WARNING "too many endpoints\n");
1751                                         break;
1752                                 }
1753                         }
1754                         endpoints[epidx].in_ep = usb_endpoint_num(ep);
1755                         if (usb_endpoint_xfer_int(ep))
1756                                 endpoints[epidx].in_interval = ep->bInterval;
1757                         else if (snd_usb_get_speed(umidi->dev) == USB_SPEED_LOW)
1758                                 endpoints[epidx].in_interval = 1;
1759                         endpoints[epidx].in_cables = (1 << ms_ep->bNumEmbMIDIJack) - 1;
1760                         snd_printdd(KERN_INFO "EP %02X: %d jack(s)\n",
1761                                     ep->bEndpointAddress, ms_ep->bNumEmbMIDIJack);
1762                 }
1763         }
1764         return 0;
1765 }
1766
1767 static int roland_load_info(struct snd_kcontrol *kcontrol,
1768                             struct snd_ctl_elem_info *info)
1769 {
1770         static const char *const names[] = { "High Load", "Light Load" };
1771
1772         return snd_ctl_enum_info(info, 1, 2, names);
1773 }
1774
1775 static int roland_load_get(struct snd_kcontrol *kcontrol,
1776                            struct snd_ctl_elem_value *value)
1777 {
1778         value->value.enumerated.item[0] = kcontrol->private_value;
1779         return 0;
1780 }
1781
1782 static int roland_load_put(struct snd_kcontrol *kcontrol,
1783                            struct snd_ctl_elem_value *value)
1784 {
1785         struct snd_usb_midi* umidi = kcontrol->private_data;
1786         int changed;
1787
1788         if (value->value.enumerated.item[0] > 1)
1789                 return -EINVAL;
1790         mutex_lock(&umidi->mutex);
1791         changed = value->value.enumerated.item[0] != kcontrol->private_value;
1792         if (changed)
1793                 kcontrol->private_value = value->value.enumerated.item[0];
1794         mutex_unlock(&umidi->mutex);
1795         return changed;
1796 }
1797
1798 static struct snd_kcontrol_new roland_load_ctl = {
1799         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
1800         .name = "MIDI Input Mode",
1801         .info = roland_load_info,
1802         .get = roland_load_get,
1803         .put = roland_load_put,
1804         .private_value = 1,
1805 };
1806
1807 /*
1808  * On Roland devices, use the second alternate setting to be able to use
1809  * the interrupt input endpoint.
1810  */
1811 static void snd_usbmidi_switch_roland_altsetting(struct snd_usb_midi* umidi)
1812 {
1813         struct usb_interface* intf;
1814         struct usb_host_interface *hostif;
1815         struct usb_interface_descriptor* intfd;
1816
1817         intf = umidi->iface;
1818         if (!intf || intf->num_altsetting != 2)
1819                 return;
1820
1821         hostif = &intf->altsetting[1];
1822         intfd = get_iface_desc(hostif);
1823         if (intfd->bNumEndpoints != 2 ||
1824             (get_endpoint(hostif, 0)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK ||
1825             (get_endpoint(hostif, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_INT)
1826                 return;
1827
1828         snd_printdd(KERN_INFO "switching to altsetting %d with int ep\n",
1829                     intfd->bAlternateSetting);
1830         usb_set_interface(umidi->dev, intfd->bInterfaceNumber,
1831                           intfd->bAlternateSetting);
1832
1833         umidi->roland_load_ctl = snd_ctl_new1(&roland_load_ctl, umidi);
1834         if (snd_ctl_add(umidi->card, umidi->roland_load_ctl) < 0)
1835                 umidi->roland_load_ctl = NULL;
1836 }
1837
1838 /*
1839  * Try to find any usable endpoints in the interface.
1840  */
1841 static int snd_usbmidi_detect_endpoints(struct snd_usb_midi* umidi,
1842                                         struct snd_usb_midi_endpoint_info* endpoint,
1843                                         int max_endpoints)
1844 {
1845         struct usb_interface* intf;
1846         struct usb_host_interface *hostif;
1847         struct usb_interface_descriptor* intfd;
1848         struct usb_endpoint_descriptor* epd;
1849         int i, out_eps = 0, in_eps = 0;
1850
1851         if (USB_ID_VENDOR(umidi->usb_id) == 0x0582)
1852                 snd_usbmidi_switch_roland_altsetting(umidi);
1853
1854         if (endpoint[0].out_ep || endpoint[0].in_ep)
1855                 return 0;
1856
1857         intf = umidi->iface;
1858         if (!intf || intf->num_altsetting < 1)
1859                 return -ENOENT;
1860         hostif = intf->cur_altsetting;
1861         intfd = get_iface_desc(hostif);
1862
1863         for (i = 0; i < intfd->bNumEndpoints; ++i) {
1864                 epd = get_endpoint(hostif, i);
1865                 if (!usb_endpoint_xfer_bulk(epd) &&
1866                     !usb_endpoint_xfer_int(epd))
1867                         continue;
1868                 if (out_eps < max_endpoints &&
1869                     usb_endpoint_dir_out(epd)) {
1870                         endpoint[out_eps].out_ep = usb_endpoint_num(epd);
1871                         if (usb_endpoint_xfer_int(epd))
1872                                 endpoint[out_eps].out_interval = epd->bInterval;
1873                         ++out_eps;
1874                 }
1875                 if (in_eps < max_endpoints &&
1876                     usb_endpoint_dir_in(epd)) {
1877                         endpoint[in_eps].in_ep = usb_endpoint_num(epd);
1878                         if (usb_endpoint_xfer_int(epd))
1879                                 endpoint[in_eps].in_interval = epd->bInterval;
1880                         ++in_eps;
1881                 }
1882         }
1883         return (out_eps || in_eps) ? 0 : -ENOENT;
1884 }
1885
1886 /*
1887  * Detects the endpoints for one-port-per-endpoint protocols.
1888  */
1889 static int snd_usbmidi_detect_per_port_endpoints(struct snd_usb_midi* umidi,
1890                                                  struct snd_usb_midi_endpoint_info* endpoints)
1891 {
1892         int err, i;
1893
1894         err = snd_usbmidi_detect_endpoints(umidi, endpoints, MIDI_MAX_ENDPOINTS);
1895         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1896                 if (endpoints[i].out_ep)
1897                         endpoints[i].out_cables = 0x0001;
1898                 if (endpoints[i].in_ep)
1899                         endpoints[i].in_cables = 0x0001;
1900         }
1901         return err;
1902 }
1903
1904 /*
1905  * Detects the endpoints and ports of Yamaha devices.
1906  */
1907 static int snd_usbmidi_detect_yamaha(struct snd_usb_midi* umidi,
1908                                      struct snd_usb_midi_endpoint_info* endpoint)
1909 {
1910         struct usb_interface* intf;
1911         struct usb_host_interface *hostif;
1912         struct usb_interface_descriptor* intfd;
1913         uint8_t* cs_desc;
1914
1915         intf = umidi->iface;
1916         if (!intf)
1917                 return -ENOENT;
1918         hostif = intf->altsetting;
1919         intfd = get_iface_desc(hostif);
1920         if (intfd->bNumEndpoints < 1)
1921                 return -ENOENT;
1922
1923         /*
1924          * For each port there is one MIDI_IN/OUT_JACK descriptor, not
1925          * necessarily with any useful contents.  So simply count 'em.
1926          */
1927         for (cs_desc = hostif->extra;
1928              cs_desc < hostif->extra + hostif->extralen && cs_desc[0] >= 2;
1929              cs_desc += cs_desc[0]) {
1930                 if (cs_desc[1] == USB_DT_CS_INTERFACE) {
1931                         if (cs_desc[2] == UAC_MIDI_IN_JACK)
1932                                 endpoint->in_cables = (endpoint->in_cables << 1) | 1;
1933                         else if (cs_desc[2] == UAC_MIDI_OUT_JACK)
1934                                 endpoint->out_cables = (endpoint->out_cables << 1) | 1;
1935                 }
1936         }
1937         if (!endpoint->in_cables && !endpoint->out_cables)
1938                 return -ENOENT;
1939
1940         return snd_usbmidi_detect_endpoints(umidi, endpoint, 1);
1941 }
1942
1943 /*
1944  * Creates the endpoints and their ports for Midiman devices.
1945  */
1946 static int snd_usbmidi_create_endpoints_midiman(struct snd_usb_midi* umidi,
1947                                                 struct snd_usb_midi_endpoint_info* endpoint)
1948 {
1949         struct snd_usb_midi_endpoint_info ep_info;
1950         struct usb_interface* intf;
1951         struct usb_host_interface *hostif;
1952         struct usb_interface_descriptor* intfd;
1953         struct usb_endpoint_descriptor* epd;
1954         int cable, err;
1955
1956         intf = umidi->iface;
1957         if (!intf)
1958                 return -ENOENT;
1959         hostif = intf->altsetting;
1960         intfd = get_iface_desc(hostif);
1961         /*
1962          * The various MidiSport devices have more or less random endpoint
1963          * numbers, so we have to identify the endpoints by their index in
1964          * the descriptor array, like the driver for that other OS does.
1965          *
1966          * There is one interrupt input endpoint for all input ports, one
1967          * bulk output endpoint for even-numbered ports, and one for odd-
1968          * numbered ports.  Both bulk output endpoints have corresponding
1969          * input bulk endpoints (at indices 1 and 3) which aren't used.
1970          */
1971         if (intfd->bNumEndpoints < (endpoint->out_cables > 0x0001 ? 5 : 3)) {
1972                 snd_printdd(KERN_ERR "not enough endpoints\n");
1973                 return -ENOENT;
1974         }
1975
1976         epd = get_endpoint(hostif, 0);
1977         if (!usb_endpoint_dir_in(epd) || !usb_endpoint_xfer_int(epd)) {
1978                 snd_printdd(KERN_ERR "endpoint[0] isn't interrupt\n");
1979                 return -ENXIO;
1980         }
1981         epd = get_endpoint(hostif, 2);
1982         if (!usb_endpoint_dir_out(epd) || !usb_endpoint_xfer_bulk(epd)) {
1983                 snd_printdd(KERN_ERR "endpoint[2] isn't bulk output\n");
1984                 return -ENXIO;
1985         }
1986         if (endpoint->out_cables > 0x0001) {
1987                 epd = get_endpoint(hostif, 4);
1988                 if (!usb_endpoint_dir_out(epd) ||
1989                     !usb_endpoint_xfer_bulk(epd)) {
1990                         snd_printdd(KERN_ERR "endpoint[4] isn't bulk output\n");
1991                         return -ENXIO;
1992                 }
1993         }
1994
1995         ep_info.out_ep = get_endpoint(hostif, 2)->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1996         ep_info.out_interval = 0;
1997         ep_info.out_cables = endpoint->out_cables & 0x5555;
1998         err = snd_usbmidi_out_endpoint_create(umidi, &ep_info, &umidi->endpoints[0]);
1999         if (err < 0)
2000                 return err;
2001
2002         ep_info.in_ep = get_endpoint(hostif, 0)->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
2003         ep_info.in_interval = get_endpoint(hostif, 0)->bInterval;
2004         ep_info.in_cables = endpoint->in_cables;
2005         err = snd_usbmidi_in_endpoint_create(umidi, &ep_info, &umidi->endpoints[0]);
2006         if (err < 0)
2007                 return err;
2008
2009         if (endpoint->out_cables > 0x0001) {
2010                 ep_info.out_ep = get_endpoint(hostif, 4)->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
2011                 ep_info.out_cables = endpoint->out_cables & 0xaaaa;
2012                 err = snd_usbmidi_out_endpoint_create(umidi, &ep_info, &umidi->endpoints[1]);
2013                 if (err < 0)
2014                         return err;
2015         }
2016
2017         for (cable = 0; cable < 0x10; ++cable) {
2018                 if (endpoint->out_cables & (1 << cable))
2019                         snd_usbmidi_init_substream(umidi, SNDRV_RAWMIDI_STREAM_OUTPUT, cable,
2020                                                    &umidi->endpoints[cable & 1].out->ports[cable].substream);
2021                 if (endpoint->in_cables & (1 << cable))
2022                         snd_usbmidi_init_substream(umidi, SNDRV_RAWMIDI_STREAM_INPUT, cable,
2023                                                    &umidi->endpoints[0].in->ports[cable].substream);
2024         }
2025         return 0;
2026 }
2027
2028 static struct snd_rawmidi_global_ops snd_usbmidi_ops = {
2029         .get_port_info = snd_usbmidi_get_port_info,
2030 };
2031
2032 static int snd_usbmidi_create_rawmidi(struct snd_usb_midi* umidi,
2033                                       int out_ports, int in_ports)
2034 {
2035         struct snd_rawmidi *rmidi;
2036         int err;
2037
2038         err = snd_rawmidi_new(umidi->card, "USB MIDI",
2039                               umidi->next_midi_device++,
2040                               out_ports, in_ports, &rmidi);
2041         if (err < 0)
2042                 return err;
2043         strcpy(rmidi->name, umidi->card->shortname);
2044         rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
2045                             SNDRV_RAWMIDI_INFO_INPUT |
2046                             SNDRV_RAWMIDI_INFO_DUPLEX;
2047         rmidi->ops = &snd_usbmidi_ops;
2048         rmidi->private_data = umidi;
2049         rmidi->private_free = snd_usbmidi_rawmidi_free;
2050         snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_usbmidi_output_ops);
2051         snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_usbmidi_input_ops);
2052
2053         umidi->rmidi = rmidi;
2054         return 0;
2055 }
2056
2057 /*
2058  * Temporarily stop input.
2059  */
2060 void snd_usbmidi_input_stop(struct list_head* p)
2061 {
2062         struct snd_usb_midi* umidi;
2063         unsigned int i, j;
2064
2065         umidi = list_entry(p, struct snd_usb_midi, list);
2066         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
2067                 struct snd_usb_midi_endpoint* ep = &umidi->endpoints[i];
2068                 if (ep->in)
2069                         for (j = 0; j < INPUT_URBS; ++j)
2070                                 usb_kill_urb(ep->in->urbs[j]);
2071         }
2072 }
2073
2074 static void snd_usbmidi_input_start_ep(struct snd_usb_midi_in_endpoint* ep)
2075 {
2076         unsigned int i;
2077
2078         if (!ep)
2079                 return;
2080         for (i = 0; i < INPUT_URBS; ++i) {
2081                 struct urb* urb = ep->urbs[i];
2082                 urb->dev = ep->umidi->dev;
2083                 snd_usbmidi_submit_urb(urb, GFP_KERNEL);
2084         }
2085 }
2086
2087 /*
2088  * Resume input after a call to snd_usbmidi_input_stop().
2089  */
2090 void snd_usbmidi_input_start(struct list_head* p)
2091 {
2092         struct snd_usb_midi* umidi;
2093         int i;
2094
2095         umidi = list_entry(p, struct snd_usb_midi, list);
2096         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
2097                 snd_usbmidi_input_start_ep(umidi->endpoints[i].in);
2098 }
2099
2100 /*
2101  * Creates and registers everything needed for a MIDI streaming interface.
2102  */
2103 int snd_usbmidi_create(struct snd_card *card,
2104                        struct usb_interface* iface,
2105                        struct list_head *midi_list,
2106                        const struct snd_usb_audio_quirk* quirk)
2107 {
2108         struct snd_usb_midi* umidi;
2109         struct snd_usb_midi_endpoint_info endpoints[MIDI_MAX_ENDPOINTS];
2110         int out_ports, in_ports;
2111         int i, err;
2112
2113         umidi = kzalloc(sizeof(*umidi), GFP_KERNEL);
2114         if (!umidi)
2115                 return -ENOMEM;
2116         umidi->dev = interface_to_usbdev(iface);
2117         umidi->card = card;
2118         umidi->iface = iface;
2119         umidi->quirk = quirk;
2120         umidi->usb_protocol_ops = &snd_usbmidi_standard_ops;
2121         init_timer(&umidi->error_timer);
2122         spin_lock_init(&umidi->disc_lock);
2123         init_rwsem(&umidi->disc_rwsem);
2124         mutex_init(&umidi->mutex);
2125         umidi->usb_id = USB_ID(le16_to_cpu(umidi->dev->descriptor.idVendor),
2126                                le16_to_cpu(umidi->dev->descriptor.idProduct));
2127         umidi->error_timer.function = snd_usbmidi_error_timer;
2128         umidi->error_timer.data = (unsigned long)umidi;
2129
2130         /* detect the endpoint(s) to use */
2131         memset(endpoints, 0, sizeof(endpoints));
2132         switch (quirk ? quirk->type : QUIRK_MIDI_STANDARD_INTERFACE) {
2133         case QUIRK_MIDI_STANDARD_INTERFACE:
2134                 err = snd_usbmidi_get_ms_info(umidi, endpoints);
2135                 if (umidi->usb_id == USB_ID(0x0763, 0x0150)) /* M-Audio Uno */
2136                         umidi->usb_protocol_ops =
2137                                 &snd_usbmidi_maudio_broken_running_status_ops;
2138                 break;
2139         case QUIRK_MIDI_US122L:
2140                 umidi->usb_protocol_ops = &snd_usbmidi_122l_ops;
2141                 /* fall through */
2142         case QUIRK_MIDI_FIXED_ENDPOINT:
2143                 memcpy(&endpoints[0], quirk->data,
2144                        sizeof(struct snd_usb_midi_endpoint_info));
2145                 err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
2146                 break;
2147         case QUIRK_MIDI_YAMAHA:
2148                 err = snd_usbmidi_detect_yamaha(umidi, &endpoints[0]);
2149                 break;
2150         case QUIRK_MIDI_MIDIMAN:
2151                 umidi->usb_protocol_ops = &snd_usbmidi_midiman_ops;
2152                 memcpy(&endpoints[0], quirk->data,
2153                        sizeof(struct snd_usb_midi_endpoint_info));
2154                 err = 0;
2155                 break;
2156         case QUIRK_MIDI_NOVATION:
2157                 umidi->usb_protocol_ops = &snd_usbmidi_novation_ops;
2158                 err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2159                 break;
2160         case QUIRK_MIDI_RAW_BYTES:
2161                 umidi->usb_protocol_ops = &snd_usbmidi_raw_ops;
2162                 /*
2163                  * Interface 1 contains isochronous endpoints, but with the same
2164                  * numbers as in interface 0.  Since it is interface 1 that the
2165                  * USB core has most recently seen, these descriptors are now
2166                  * associated with the endpoint numbers.  This will foul up our
2167                  * attempts to submit bulk/interrupt URBs to the endpoints in
2168                  * interface 0, so we have to make sure that the USB core looks
2169                  * again at interface 0 by calling usb_set_interface() on it.
2170                  */
2171                 if (umidi->usb_id == USB_ID(0x07fd, 0x0001)) /* MOTU Fastlane */
2172                         usb_set_interface(umidi->dev, 0, 0);
2173                 err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2174                 break;
2175         case QUIRK_MIDI_EMAGIC:
2176                 umidi->usb_protocol_ops = &snd_usbmidi_emagic_ops;
2177                 memcpy(&endpoints[0], quirk->data,
2178                        sizeof(struct snd_usb_midi_endpoint_info));
2179                 err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
2180                 break;
2181         case QUIRK_MIDI_CME:
2182                 umidi->usb_protocol_ops = &snd_usbmidi_cme_ops;
2183                 err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2184                 break;
2185         case QUIRK_MIDI_AKAI:
2186                 umidi->usb_protocol_ops = &snd_usbmidi_akai_ops;
2187                 err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
2188                 /* endpoint 1 is input-only */
2189                 endpoints[1].out_cables = 0;
2190                 break;
2191         default:
2192                 snd_printd(KERN_ERR "invalid quirk type %d\n", quirk->type);
2193                 err = -ENXIO;
2194                 break;
2195         }
2196         if (err < 0) {
2197                 kfree(umidi);
2198                 return err;
2199         }
2200
2201         /* create rawmidi device */
2202         out_ports = 0;
2203         in_ports = 0;
2204         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
2205                 out_ports += hweight16(endpoints[i].out_cables);
2206                 in_ports += hweight16(endpoints[i].in_cables);
2207         }
2208         err = snd_usbmidi_create_rawmidi(umidi, out_ports, in_ports);
2209         if (err < 0) {
2210                 kfree(umidi);
2211                 return err;
2212         }
2213
2214         /* create endpoint/port structures */
2215         if (quirk && quirk->type == QUIRK_MIDI_MIDIMAN)
2216                 err = snd_usbmidi_create_endpoints_midiman(umidi, &endpoints[0]);
2217         else
2218                 err = snd_usbmidi_create_endpoints(umidi, endpoints);
2219         if (err < 0) {
2220                 snd_usbmidi_free(umidi);
2221                 return err;
2222         }
2223
2224         list_add_tail(&umidi->list, midi_list);
2225
2226         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
2227                 snd_usbmidi_input_start_ep(umidi->endpoints[i].in);
2228         return 0;
2229 }
2230
2231 EXPORT_SYMBOL(snd_usbmidi_create);
2232 EXPORT_SYMBOL(snd_usbmidi_input_stop);
2233 EXPORT_SYMBOL(snd_usbmidi_input_start);
2234 EXPORT_SYMBOL(snd_usbmidi_disconnect);