Merge refs/heads/upstream from master.kernel.org:/pub/scm/linux/kernel/git/jgarzik...
[pandora-kernel.git] / sound / usb / usbmidi.c
1 /*
2  * usbmidi.c - ALSA USB MIDI driver
3  *
4  * Copyright (c) 2002-2005 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 <sound/driver.h>
39 #include <linux/kernel.h>
40 #include <linux/types.h>
41 #include <linux/bitops.h>
42 #include <linux/interrupt.h>
43 #include <linux/spinlock.h>
44 #include <linux/string.h>
45 #include <linux/init.h>
46 #include <linux/slab.h>
47 #include <linux/timer.h>
48 #include <linux/usb.h>
49 #include <sound/core.h>
50 #include <sound/minors.h>
51 #include <sound/rawmidi.h>
52 #include "usbaudio.h"
53
54
55 /*
56  * define this to log all USB packets
57  */
58 /* #define DUMP_PACKETS */
59
60 /*
61  * how long to wait after some USB errors, so that khubd can disconnect() us
62  * without too many spurious errors
63  */
64 #define ERROR_DELAY_JIFFIES (HZ / 10)
65
66
67 MODULE_AUTHOR("Clemens Ladisch <clemens@ladisch.de>");
68 MODULE_DESCRIPTION("USB Audio/MIDI helper module");
69 MODULE_LICENSE("Dual BSD/GPL");
70
71
72 struct usb_ms_header_descriptor {
73         __u8  bLength;
74         __u8  bDescriptorType;
75         __u8  bDescriptorSubtype;
76         __u8  bcdMSC[2];
77         __le16 wTotalLength;
78 } __attribute__ ((packed));
79
80 struct usb_ms_endpoint_descriptor {
81         __u8  bLength;
82         __u8  bDescriptorType;
83         __u8  bDescriptorSubtype;
84         __u8  bNumEmbMIDIJack;
85         __u8  baAssocJackID[0];
86 } __attribute__ ((packed));
87
88 typedef struct snd_usb_midi snd_usb_midi_t;
89 typedef struct snd_usb_midi_endpoint snd_usb_midi_endpoint_t;
90 typedef struct snd_usb_midi_out_endpoint snd_usb_midi_out_endpoint_t;
91 typedef struct snd_usb_midi_in_endpoint snd_usb_midi_in_endpoint_t;
92 typedef struct usbmidi_out_port usbmidi_out_port_t;
93 typedef struct usbmidi_in_port usbmidi_in_port_t;
94
95 struct usb_protocol_ops {
96         void (*input)(snd_usb_midi_in_endpoint_t*, uint8_t*, int);
97         void (*output)(snd_usb_midi_out_endpoint_t*);
98         void (*output_packet)(struct urb*, uint8_t, uint8_t, uint8_t, uint8_t);
99         void (*init_out_endpoint)(snd_usb_midi_out_endpoint_t*);
100         void (*finish_out_endpoint)(snd_usb_midi_out_endpoint_t*);
101 };
102
103 struct snd_usb_midi {
104         snd_usb_audio_t *chip;
105         struct usb_interface *iface;
106         const snd_usb_audio_quirk_t *quirk;
107         snd_rawmidi_t* rmidi;
108         struct usb_protocol_ops* usb_protocol_ops;
109         struct list_head list;
110         struct timer_list error_timer;
111
112         struct snd_usb_midi_endpoint {
113                 snd_usb_midi_out_endpoint_t *out;
114                 snd_usb_midi_in_endpoint_t *in;
115         } endpoints[MIDI_MAX_ENDPOINTS];
116         unsigned long input_triggered;
117 };
118
119 struct snd_usb_midi_out_endpoint {
120         snd_usb_midi_t* umidi;
121         struct urb* urb;
122         int urb_active;
123         int max_transfer;               /* size of urb buffer */
124         struct tasklet_struct tasklet;
125
126         spinlock_t buffer_lock;
127
128         struct usbmidi_out_port {
129                 snd_usb_midi_out_endpoint_t* ep;
130                 snd_rawmidi_substream_t* substream;
131                 int active;
132                 uint8_t cable;          /* cable number << 4 */
133                 uint8_t state;
134 #define STATE_UNKNOWN   0
135 #define STATE_1PARAM    1
136 #define STATE_2PARAM_1  2
137 #define STATE_2PARAM_2  3
138 #define STATE_SYSEX_0   4
139 #define STATE_SYSEX_1   5
140 #define STATE_SYSEX_2   6
141                 uint8_t data[2];
142         } ports[0x10];
143         int current_port;
144 };
145
146 struct snd_usb_midi_in_endpoint {
147         snd_usb_midi_t* umidi;
148         struct urb* urb;
149         struct usbmidi_in_port {
150                 snd_rawmidi_substream_t* substream;
151         } ports[0x10];
152         u8 seen_f5;
153         u8 error_resubmit;
154         int current_port;
155 };
156
157 static void snd_usbmidi_do_output(snd_usb_midi_out_endpoint_t* ep);
158
159 static const uint8_t snd_usbmidi_cin_length[] = {
160         0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
161 };
162
163 /*
164  * Submits the URB, with error handling.
165  */
166 static int snd_usbmidi_submit_urb(struct urb* urb, int flags)
167 {
168         int err = usb_submit_urb(urb, flags);
169         if (err < 0 && err != -ENODEV)
170                 snd_printk(KERN_ERR "usb_submit_urb: %d\n", err);
171         return err;
172 }
173
174 /*
175  * Error handling for URB completion functions.
176  */
177 static int snd_usbmidi_urb_error(int status)
178 {
179         switch (status) {
180         /* manually unlinked, or device gone */
181         case -ENOENT:
182         case -ECONNRESET:
183         case -ESHUTDOWN:
184         case -ENODEV:
185                 return -ENODEV;
186         /* errors that might occur during unplugging */
187         case -EPROTO:    /* EHCI */
188         case -ETIMEDOUT: /* OHCI */
189         case -EILSEQ:    /* UHCI */
190                 return -EIO;
191         default:
192                 snd_printk(KERN_ERR "urb status %d\n", status);
193                 return 0; /* continue */
194         }
195 }
196
197 /*
198  * Receives a chunk of MIDI data.
199  */
200 static void snd_usbmidi_input_data(snd_usb_midi_in_endpoint_t* ep, int portidx,
201                                    uint8_t* data, int length)
202 {
203         usbmidi_in_port_t* port = &ep->ports[portidx];
204
205         if (!port->substream) {
206                 snd_printd("unexpected port %d!\n", portidx);
207                 return;
208         }
209         if (!test_bit(port->substream->number, &ep->umidi->input_triggered))
210                 return;
211         snd_rawmidi_receive(port->substream, data, length);
212 }
213
214 #ifdef DUMP_PACKETS
215 static void dump_urb(const char *type, const u8 *data, int length)
216 {
217         snd_printk(KERN_DEBUG "%s packet: [", type);
218         for (; length > 0; ++data, --length)
219                 printk(" %02x", *data);
220         printk(" ]\n");
221 }
222 #else
223 #define dump_urb(type, data, length) /* nothing */
224 #endif
225
226 /*
227  * Processes the data read from the device.
228  */
229 static void snd_usbmidi_in_urb_complete(struct urb* urb, struct pt_regs *regs)
230 {
231         snd_usb_midi_in_endpoint_t* ep = urb->context;
232
233         if (urb->status == 0) {
234                 dump_urb("received", urb->transfer_buffer, urb->actual_length);
235                 ep->umidi->usb_protocol_ops->input(ep, urb->transfer_buffer,
236                                                    urb->actual_length);
237         } else {
238                 int err = snd_usbmidi_urb_error(urb->status);
239                 if (err < 0) {
240                         if (err != -ENODEV) {
241                                 ep->error_resubmit = 1;
242                                 mod_timer(&ep->umidi->error_timer,
243                                           jiffies + ERROR_DELAY_JIFFIES);
244                         }
245                         return;
246                 }
247         }
248
249         if (usb_pipe_needs_resubmit(urb->pipe)) {
250                 urb->dev = ep->umidi->chip->dev;
251                 snd_usbmidi_submit_urb(urb, GFP_ATOMIC);
252         }
253 }
254
255 static void snd_usbmidi_out_urb_complete(struct urb* urb, struct pt_regs *regs)
256 {
257         snd_usb_midi_out_endpoint_t* ep = urb->context;
258
259         spin_lock(&ep->buffer_lock);
260         ep->urb_active = 0;
261         spin_unlock(&ep->buffer_lock);
262         if (urb->status < 0) {
263                 int err = snd_usbmidi_urb_error(urb->status);
264                 if (err < 0) {
265                         if (err != -ENODEV)
266                                 mod_timer(&ep->umidi->error_timer,
267                                           jiffies + ERROR_DELAY_JIFFIES);
268                         return;
269                 }
270         }
271         snd_usbmidi_do_output(ep);
272 }
273
274 /*
275  * This is called when some data should be transferred to the device
276  * (from one or more substreams).
277  */
278 static void snd_usbmidi_do_output(snd_usb_midi_out_endpoint_t* ep)
279 {
280         struct urb* urb = ep->urb;
281         unsigned long flags;
282
283         spin_lock_irqsave(&ep->buffer_lock, flags);
284         if (ep->urb_active || ep->umidi->chip->shutdown) {
285                 spin_unlock_irqrestore(&ep->buffer_lock, flags);
286                 return;
287         }
288
289         urb->transfer_buffer_length = 0;
290         ep->umidi->usb_protocol_ops->output(ep);
291
292         if (urb->transfer_buffer_length > 0) {
293                 dump_urb("sending", urb->transfer_buffer,
294                          urb->transfer_buffer_length);
295                 urb->dev = ep->umidi->chip->dev;
296                 ep->urb_active = snd_usbmidi_submit_urb(urb, GFP_ATOMIC) >= 0;
297         }
298         spin_unlock_irqrestore(&ep->buffer_lock, flags);
299 }
300
301 static void snd_usbmidi_out_tasklet(unsigned long data)
302 {
303         snd_usb_midi_out_endpoint_t* ep = (snd_usb_midi_out_endpoint_t *) data;
304
305         snd_usbmidi_do_output(ep);
306 }
307
308 /* called after transfers had been interrupted due to some USB error */
309 static void snd_usbmidi_error_timer(unsigned long data)
310 {
311         snd_usb_midi_t *umidi = (snd_usb_midi_t *)data;
312         int i;
313
314         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
315                 snd_usb_midi_in_endpoint_t *in = umidi->endpoints[i].in;
316                 if (in && in->error_resubmit) {
317                         in->error_resubmit = 0;
318                         in->urb->dev = umidi->chip->dev;
319                         snd_usbmidi_submit_urb(in->urb, GFP_ATOMIC);
320                 }
321                 if (umidi->endpoints[i].out)
322                         snd_usbmidi_do_output(umidi->endpoints[i].out);
323         }
324 }
325
326 /* helper function to send static data that may not DMA-able */
327 static int send_bulk_static_data(snd_usb_midi_out_endpoint_t* ep,
328                                  const void *data, int len)
329 {
330         int err;
331         void *buf = kmalloc(len, GFP_KERNEL);
332         if (!buf)
333                 return -ENOMEM;
334         memcpy(buf, data, len);
335         dump_urb("sending", buf, len);
336         err = usb_bulk_msg(ep->umidi->chip->dev, ep->urb->pipe, buf, len,
337                            NULL, 250);
338         kfree(buf);
339         return err;
340 }
341
342 /*
343  * Standard USB MIDI protocol: see the spec.
344  * Midiman protocol: like the standard protocol, but the control byte is the
345  * fourth byte in each packet, and uses length instead of CIN.
346  */
347
348 static void snd_usbmidi_standard_input(snd_usb_midi_in_endpoint_t* ep,
349                                        uint8_t* buffer, int buffer_length)
350 {
351         int i;
352
353         for (i = 0; i + 3 < buffer_length; i += 4)
354                 if (buffer[i] != 0) {
355                         int cable = buffer[i] >> 4;
356                         int length = snd_usbmidi_cin_length[buffer[i] & 0x0f];
357                         snd_usbmidi_input_data(ep, cable, &buffer[i + 1], length);
358                 }
359 }
360
361 static void snd_usbmidi_midiman_input(snd_usb_midi_in_endpoint_t* ep,
362                                       uint8_t* buffer, int buffer_length)
363 {
364         int i;
365
366         for (i = 0; i + 3 < buffer_length; i += 4)
367                 if (buffer[i + 3] != 0) {
368                         int port = buffer[i + 3] >> 4;
369                         int length = buffer[i + 3] & 3;
370                         snd_usbmidi_input_data(ep, port, &buffer[i], length);
371                 }
372 }
373
374 /*
375  * Adds one USB MIDI packet to the output buffer.
376  */
377 static void snd_usbmidi_output_standard_packet(struct urb* urb, uint8_t p0,
378                                                uint8_t p1, uint8_t p2, uint8_t p3)
379 {
380
381         uint8_t* buf = (uint8_t*)urb->transfer_buffer + urb->transfer_buffer_length;
382         buf[0] = p0;
383         buf[1] = p1;
384         buf[2] = p2;
385         buf[3] = p3;
386         urb->transfer_buffer_length += 4;
387 }
388
389 /*
390  * Adds one Midiman packet to the output buffer.
391  */
392 static void snd_usbmidi_output_midiman_packet(struct urb* urb, uint8_t p0,
393                                               uint8_t p1, uint8_t p2, uint8_t p3)
394 {
395
396         uint8_t* buf = (uint8_t*)urb->transfer_buffer + urb->transfer_buffer_length;
397         buf[0] = p1;
398         buf[1] = p2;
399         buf[2] = p3;
400         buf[3] = (p0 & 0xf0) | snd_usbmidi_cin_length[p0 & 0x0f];
401         urb->transfer_buffer_length += 4;
402 }
403
404 /*
405  * Converts MIDI commands to USB MIDI packets.
406  */
407 static void snd_usbmidi_transmit_byte(usbmidi_out_port_t* port,
408                                       uint8_t b, struct urb* urb)
409 {
410         uint8_t p0 = port->cable;
411         void (*output_packet)(struct urb*, uint8_t, uint8_t, uint8_t, uint8_t) =
412                 port->ep->umidi->usb_protocol_ops->output_packet;
413
414         if (b >= 0xf8) {
415                 output_packet(urb, p0 | 0x0f, b, 0, 0);
416         } else if (b >= 0xf0) {
417                 switch (b) {
418                 case 0xf0:
419                         port->data[0] = b;
420                         port->state = STATE_SYSEX_1;
421                         break;
422                 case 0xf1:
423                 case 0xf3:
424                         port->data[0] = b;
425                         port->state = STATE_1PARAM;
426                         break;
427                 case 0xf2:
428                         port->data[0] = b;
429                         port->state = STATE_2PARAM_1;
430                         break;
431                 case 0xf4:
432                 case 0xf5:
433                         port->state = STATE_UNKNOWN;
434                         break;
435                 case 0xf6:
436                         output_packet(urb, p0 | 0x05, 0xf6, 0, 0);
437                         port->state = STATE_UNKNOWN;
438                         break;
439                 case 0xf7:
440                         switch (port->state) {
441                         case STATE_SYSEX_0:
442                                 output_packet(urb, p0 | 0x05, 0xf7, 0, 0);
443                                 break;
444                         case STATE_SYSEX_1:
445                                 output_packet(urb, p0 | 0x06, port->data[0], 0xf7, 0);
446                                 break;
447                         case STATE_SYSEX_2:
448                                 output_packet(urb, p0 | 0x07, port->data[0], port->data[1], 0xf7);
449                                 break;
450                         }
451                         port->state = STATE_UNKNOWN;
452                         break;
453                 }
454         } else if (b >= 0x80) {
455                 port->data[0] = b;
456                 if (b >= 0xc0 && b <= 0xdf)
457                         port->state = STATE_1PARAM;
458                 else
459                         port->state = STATE_2PARAM_1;
460         } else { /* b < 0x80 */
461                 switch (port->state) {
462                 case STATE_1PARAM:
463                         if (port->data[0] < 0xf0) {
464                                 p0 |= port->data[0] >> 4;
465                         } else {
466                                 p0 |= 0x02;
467                                 port->state = STATE_UNKNOWN;
468                         }
469                         output_packet(urb, p0, port->data[0], b, 0);
470                         break;
471                 case STATE_2PARAM_1:
472                         port->data[1] = b;
473                         port->state = STATE_2PARAM_2;
474                         break;
475                 case STATE_2PARAM_2:
476                         if (port->data[0] < 0xf0) {
477                                 p0 |= port->data[0] >> 4;
478                                 port->state = STATE_2PARAM_1;
479                         } else {
480                                 p0 |= 0x03;
481                                 port->state = STATE_UNKNOWN;
482                         }
483                         output_packet(urb, p0, port->data[0], port->data[1], b);
484                         break;
485                 case STATE_SYSEX_0:
486                         port->data[0] = b;
487                         port->state = STATE_SYSEX_1;
488                         break;
489                 case STATE_SYSEX_1:
490                         port->data[1] = b;
491                         port->state = STATE_SYSEX_2;
492                         break;
493                 case STATE_SYSEX_2:
494                         output_packet(urb, p0 | 0x04, port->data[0], port->data[1], b);
495                         port->state = STATE_SYSEX_0;
496                         break;
497                 }
498         }
499 }
500
501 static void snd_usbmidi_standard_output(snd_usb_midi_out_endpoint_t* ep)
502 {
503         struct urb* urb = ep->urb;
504         int p;
505
506         /* FIXME: lower-numbered ports can starve higher-numbered ports */
507         for (p = 0; p < 0x10; ++p) {
508                 usbmidi_out_port_t* port = &ep->ports[p];
509                 if (!port->active)
510                         continue;
511                 while (urb->transfer_buffer_length + 3 < ep->max_transfer) {
512                         uint8_t b;
513                         if (snd_rawmidi_transmit(port->substream, &b, 1) != 1) {
514                                 port->active = 0;
515                                 break;
516                         }
517                         snd_usbmidi_transmit_byte(port, b, urb);
518                 }
519         }
520 }
521
522 static struct usb_protocol_ops snd_usbmidi_standard_ops = {
523         .input = snd_usbmidi_standard_input,
524         .output = snd_usbmidi_standard_output,
525         .output_packet = snd_usbmidi_output_standard_packet,
526 };
527
528 static struct usb_protocol_ops snd_usbmidi_midiman_ops = {
529         .input = snd_usbmidi_midiman_input,
530         .output = snd_usbmidi_standard_output, 
531         .output_packet = snd_usbmidi_output_midiman_packet,
532 };
533
534 /*
535  * Novation USB MIDI protocol: number of data bytes is in the first byte
536  * (when receiving) (+1!) or in the second byte (when sending); data begins
537  * at the third byte.
538  */
539
540 static void snd_usbmidi_novation_input(snd_usb_midi_in_endpoint_t* ep,
541                                        uint8_t* buffer, int buffer_length)
542 {
543         if (buffer_length < 2 || !buffer[0] || buffer_length < buffer[0] + 1)
544                 return;
545         snd_usbmidi_input_data(ep, 0, &buffer[2], buffer[0] - 1);
546 }
547
548 static void snd_usbmidi_novation_output(snd_usb_midi_out_endpoint_t* ep)
549 {
550         uint8_t* transfer_buffer;
551         int count;
552
553         if (!ep->ports[0].active)
554                 return;
555         transfer_buffer = ep->urb->transfer_buffer;
556         count = snd_rawmidi_transmit(ep->ports[0].substream,
557                                      &transfer_buffer[2],
558                                      ep->max_transfer - 2);
559         if (count < 1) {
560                 ep->ports[0].active = 0;
561                 return;
562         }
563         transfer_buffer[0] = 0;
564         transfer_buffer[1] = count;
565         ep->urb->transfer_buffer_length = 2 + count;
566 }
567
568 static struct usb_protocol_ops snd_usbmidi_novation_ops = {
569         .input = snd_usbmidi_novation_input,
570         .output = snd_usbmidi_novation_output,
571 };
572
573 /*
574  * "raw" protocol: used by the MOTU FastLane.
575  */
576
577 static void snd_usbmidi_raw_input(snd_usb_midi_in_endpoint_t* ep,
578                                   uint8_t* buffer, int buffer_length)
579 {
580         snd_usbmidi_input_data(ep, 0, buffer, buffer_length);
581 }
582
583 static void snd_usbmidi_raw_output(snd_usb_midi_out_endpoint_t* ep)
584 {
585         int count;
586
587         if (!ep->ports[0].active)
588                 return;
589         count = snd_rawmidi_transmit(ep->ports[0].substream,
590                                      ep->urb->transfer_buffer,
591                                      ep->max_transfer);
592         if (count < 1) {
593                 ep->ports[0].active = 0;
594                 return;
595         }
596         ep->urb->transfer_buffer_length = count;
597 }
598
599 static struct usb_protocol_ops snd_usbmidi_raw_ops = {
600         .input = snd_usbmidi_raw_input,
601         .output = snd_usbmidi_raw_output,
602 };
603
604 /*
605  * Emagic USB MIDI protocol: raw MIDI with "F5 xx" port switching.
606  */
607
608 static void snd_usbmidi_emagic_init_out(snd_usb_midi_out_endpoint_t* ep)
609 {
610         static const u8 init_data[] = {
611                 /* initialization magic: "get version" */
612                 0xf0,
613                 0x00, 0x20, 0x31,       /* Emagic */
614                 0x64,                   /* Unitor8 */
615                 0x0b,                   /* version number request */
616                 0x00,                   /* command version */
617                 0x00,                   /* EEPROM, box 0 */
618                 0xf7
619         };
620         send_bulk_static_data(ep, init_data, sizeof(init_data));
621         /* while we're at it, pour on more magic */
622         send_bulk_static_data(ep, init_data, sizeof(init_data));
623 }
624
625 static void snd_usbmidi_emagic_finish_out(snd_usb_midi_out_endpoint_t* ep)
626 {
627         static const u8 finish_data[] = {
628                 /* switch to patch mode with last preset */
629                 0xf0,
630                 0x00, 0x20, 0x31,       /* Emagic */
631                 0x64,                   /* Unitor8 */
632                 0x10,                   /* patch switch command */
633                 0x00,                   /* command version */
634                 0x7f,                   /* to all boxes */
635                 0x40,                   /* last preset in EEPROM */
636                 0xf7
637         };
638         send_bulk_static_data(ep, finish_data, sizeof(finish_data));
639 }
640
641 static void snd_usbmidi_emagic_input(snd_usb_midi_in_endpoint_t* ep,
642                                      uint8_t* buffer, int buffer_length)
643 {
644         int i;
645
646         /* FF indicates end of valid data */
647         for (i = 0; i < buffer_length; ++i)
648                 if (buffer[i] == 0xff) {
649                         buffer_length = i;
650                         break;
651                 }
652
653         /* handle F5 at end of last buffer */
654         if (ep->seen_f5)
655                 goto switch_port;
656
657         while (buffer_length > 0) {
658                 /* determine size of data until next F5 */
659                 for (i = 0; i < buffer_length; ++i)
660                         if (buffer[i] == 0xf5)
661                                 break;
662                 snd_usbmidi_input_data(ep, ep->current_port, buffer, i);
663                 buffer += i;
664                 buffer_length -= i;
665
666                 if (buffer_length <= 0)
667                         break;
668                 /* assert(buffer[0] == 0xf5); */
669                 ep->seen_f5 = 1;
670                 ++buffer;
671                 --buffer_length;
672
673         switch_port:
674                 if (buffer_length <= 0)
675                         break;
676                 if (buffer[0] < 0x80) {
677                         ep->current_port = (buffer[0] - 1) & 15;
678                         ++buffer;
679                         --buffer_length;
680                 }
681                 ep->seen_f5 = 0;
682         }
683 }
684
685 static void snd_usbmidi_emagic_output(snd_usb_midi_out_endpoint_t* ep)
686 {
687         int port0 = ep->current_port;
688         uint8_t* buf = ep->urb->transfer_buffer;
689         int buf_free = ep->max_transfer;
690         int length, i;
691
692         for (i = 0; i < 0x10; ++i) {
693                 /* round-robin, starting at the last current port */
694                 int portnum = (port0 + i) & 15;
695                 usbmidi_out_port_t* port = &ep->ports[portnum];
696
697                 if (!port->active)
698                         continue;
699                 if (snd_rawmidi_transmit_peek(port->substream, buf, 1) != 1) {
700                         port->active = 0;
701                         continue;
702                 }
703
704                 if (portnum != ep->current_port) {
705                         if (buf_free < 2)
706                                 break;
707                         ep->current_port = portnum;
708                         buf[0] = 0xf5;
709                         buf[1] = (portnum + 1) & 15;
710                         buf += 2;
711                         buf_free -= 2;
712                 }
713
714                 if (buf_free < 1)
715                         break;
716                 length = snd_rawmidi_transmit(port->substream, buf, buf_free);
717                 if (length > 0) {
718                         buf += length;
719                         buf_free -= length;
720                         if (buf_free < 1)
721                                 break;
722                 }
723         }
724         if (buf_free < ep->max_transfer && buf_free > 0) {
725                 *buf = 0xff;
726                 --buf_free;
727         }
728         ep->urb->transfer_buffer_length = ep->max_transfer - buf_free;
729 }
730
731 static struct usb_protocol_ops snd_usbmidi_emagic_ops = {
732         .input = snd_usbmidi_emagic_input,
733         .output = snd_usbmidi_emagic_output,
734         .init_out_endpoint = snd_usbmidi_emagic_init_out,
735         .finish_out_endpoint = snd_usbmidi_emagic_finish_out,
736 };
737
738
739 static int snd_usbmidi_output_open(snd_rawmidi_substream_t* substream)
740 {
741         snd_usb_midi_t* umidi = substream->rmidi->private_data;
742         usbmidi_out_port_t* port = NULL;
743         int i, j;
744
745         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
746                 if (umidi->endpoints[i].out)
747                         for (j = 0; j < 0x10; ++j)
748                                 if (umidi->endpoints[i].out->ports[j].substream == substream) {
749                                         port = &umidi->endpoints[i].out->ports[j];
750                                         break;
751                                 }
752         if (!port) {
753                 snd_BUG();
754                 return -ENXIO;
755         }
756         substream->runtime->private_data = port;
757         port->state = STATE_UNKNOWN;
758         return 0;
759 }
760
761 static int snd_usbmidi_output_close(snd_rawmidi_substream_t* substream)
762 {
763         return 0;
764 }
765
766 static void snd_usbmidi_output_trigger(snd_rawmidi_substream_t* substream, int up)
767 {
768         usbmidi_out_port_t* port = (usbmidi_out_port_t*)substream->runtime->private_data;
769
770         port->active = up;
771         if (up) {
772                 if (port->ep->umidi->chip->shutdown) {
773                         /* gobble up remaining bytes to prevent wait in
774                          * snd_rawmidi_drain_output */
775                         while (!snd_rawmidi_transmit_empty(substream))
776                                 snd_rawmidi_transmit_ack(substream, 1);
777                         return;
778                 }
779                 tasklet_hi_schedule(&port->ep->tasklet);
780         }
781 }
782
783 static int snd_usbmidi_input_open(snd_rawmidi_substream_t* substream)
784 {
785         return 0;
786 }
787
788 static int snd_usbmidi_input_close(snd_rawmidi_substream_t* substream)
789 {
790         return 0;
791 }
792
793 static void snd_usbmidi_input_trigger(snd_rawmidi_substream_t* substream, int up)
794 {
795         snd_usb_midi_t* umidi = substream->rmidi->private_data;
796
797         if (up)
798                 set_bit(substream->number, &umidi->input_triggered);
799         else
800                 clear_bit(substream->number, &umidi->input_triggered);
801 }
802
803 static snd_rawmidi_ops_t snd_usbmidi_output_ops = {
804         .open = snd_usbmidi_output_open,
805         .close = snd_usbmidi_output_close,
806         .trigger = snd_usbmidi_output_trigger,
807 };
808
809 static snd_rawmidi_ops_t snd_usbmidi_input_ops = {
810         .open = snd_usbmidi_input_open,
811         .close = snd_usbmidi_input_close,
812         .trigger = snd_usbmidi_input_trigger
813 };
814
815 /*
816  * Frees an input endpoint.
817  * May be called when ep hasn't been initialized completely.
818  */
819 static void snd_usbmidi_in_endpoint_delete(snd_usb_midi_in_endpoint_t* ep)
820 {
821         if (ep->urb) {
822                 usb_buffer_free(ep->umidi->chip->dev,
823                                 ep->urb->transfer_buffer_length,
824                                 ep->urb->transfer_buffer,
825                                 ep->urb->transfer_dma);
826                 usb_free_urb(ep->urb);
827         }
828         kfree(ep);
829 }
830
831 /*
832  * Creates an input endpoint.
833  */
834 static int snd_usbmidi_in_endpoint_create(snd_usb_midi_t* umidi,
835                                           snd_usb_midi_endpoint_info_t* ep_info,
836                                           snd_usb_midi_endpoint_t* rep)
837 {
838         snd_usb_midi_in_endpoint_t* ep;
839         void* buffer;
840         unsigned int pipe;
841         int length;
842
843         rep->in = NULL;
844         ep = kcalloc(1, sizeof(*ep), GFP_KERNEL);
845         if (!ep)
846                 return -ENOMEM;
847         ep->umidi = umidi;
848
849         ep->urb = usb_alloc_urb(0, GFP_KERNEL);
850         if (!ep->urb) {
851                 snd_usbmidi_in_endpoint_delete(ep);
852                 return -ENOMEM;
853         }
854         if (ep_info->in_interval)
855                 pipe = usb_rcvintpipe(umidi->chip->dev, ep_info->in_ep);
856         else
857                 pipe = usb_rcvbulkpipe(umidi->chip->dev, ep_info->in_ep);
858         length = usb_maxpacket(umidi->chip->dev, pipe, 0);
859         buffer = usb_buffer_alloc(umidi->chip->dev, length, GFP_KERNEL,
860                                   &ep->urb->transfer_dma);
861         if (!buffer) {
862                 snd_usbmidi_in_endpoint_delete(ep);
863                 return -ENOMEM;
864         }
865         if (ep_info->in_interval)
866                 usb_fill_int_urb(ep->urb, umidi->chip->dev, pipe, buffer, length,
867                                  snd_usb_complete_callback(snd_usbmidi_in_urb_complete),
868                                  ep, ep_info->in_interval);
869         else
870                 usb_fill_bulk_urb(ep->urb, umidi->chip->dev, pipe, buffer, length,
871                                   snd_usb_complete_callback(snd_usbmidi_in_urb_complete),
872                                   ep);
873         ep->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
874
875         rep->in = ep;
876         return 0;
877 }
878
879 static unsigned int snd_usbmidi_count_bits(unsigned int x)
880 {
881         unsigned int bits = 0;
882
883         for (; x; x >>= 1)
884                 bits += x & 1;
885         return bits;
886 }
887
888 /*
889  * Frees an output endpoint.
890  * May be called when ep hasn't been initialized completely.
891  */
892 static void snd_usbmidi_out_endpoint_delete(snd_usb_midi_out_endpoint_t* ep)
893 {
894         if (ep->urb) {
895                 usb_buffer_free(ep->umidi->chip->dev, ep->max_transfer,
896                                 ep->urb->transfer_buffer,
897                                 ep->urb->transfer_dma);
898                 usb_free_urb(ep->urb);
899         }
900         kfree(ep);
901 }
902
903 /*
904  * Creates an output endpoint, and initializes output ports.
905  */
906 static int snd_usbmidi_out_endpoint_create(snd_usb_midi_t* umidi,
907                                            snd_usb_midi_endpoint_info_t* ep_info,
908                                            snd_usb_midi_endpoint_t* rep)
909 {
910         snd_usb_midi_out_endpoint_t* ep;
911         int i;
912         unsigned int pipe;
913         void* buffer;
914
915         rep->out = NULL;
916         ep = kcalloc(1, sizeof(*ep), GFP_KERNEL);
917         if (!ep)
918                 return -ENOMEM;
919         ep->umidi = umidi;
920
921         ep->urb = usb_alloc_urb(0, GFP_KERNEL);
922         if (!ep->urb) {
923                 snd_usbmidi_out_endpoint_delete(ep);
924                 return -ENOMEM;
925         }
926         /* we never use interrupt output pipes */
927         pipe = usb_sndbulkpipe(umidi->chip->dev, ep_info->out_ep);
928         ep->max_transfer = usb_maxpacket(umidi->chip->dev, pipe, 1);
929         buffer = usb_buffer_alloc(umidi->chip->dev, ep->max_transfer,
930                                   GFP_KERNEL, &ep->urb->transfer_dma);
931         if (!buffer) {
932                 snd_usbmidi_out_endpoint_delete(ep);
933                 return -ENOMEM;
934         }
935         usb_fill_bulk_urb(ep->urb, umidi->chip->dev, pipe, buffer,
936                           ep->max_transfer,
937                           snd_usb_complete_callback(snd_usbmidi_out_urb_complete), ep);
938         ep->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
939
940         spin_lock_init(&ep->buffer_lock);
941         tasklet_init(&ep->tasklet, snd_usbmidi_out_tasklet, (unsigned long)ep);
942
943         for (i = 0; i < 0x10; ++i)
944                 if (ep_info->out_cables & (1 << i)) {
945                         ep->ports[i].ep = ep;
946                         ep->ports[i].cable = i << 4;
947                 }
948
949         if (umidi->usb_protocol_ops->init_out_endpoint)
950                 umidi->usb_protocol_ops->init_out_endpoint(ep);
951
952         rep->out = ep;
953         return 0;
954 }
955
956 /*
957  * Frees everything.
958  */
959 static void snd_usbmidi_free(snd_usb_midi_t* umidi)
960 {
961         int i;
962
963         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
964                 snd_usb_midi_endpoint_t* ep = &umidi->endpoints[i];
965                 if (ep->out)
966                         snd_usbmidi_out_endpoint_delete(ep->out);
967                 if (ep->in)
968                         snd_usbmidi_in_endpoint_delete(ep->in);
969         }
970         kfree(umidi);
971 }
972
973 /*
974  * Unlinks all URBs (must be done before the usb_device is deleted).
975  */
976 void snd_usbmidi_disconnect(struct list_head* p)
977 {
978         snd_usb_midi_t* umidi;
979         int i;
980
981         umidi = list_entry(p, snd_usb_midi_t, list);
982         del_timer_sync(&umidi->error_timer);
983         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
984                 snd_usb_midi_endpoint_t* ep = &umidi->endpoints[i];
985                 if (ep->out)
986                         tasklet_kill(&ep->out->tasklet);
987                 if (ep->out && ep->out->urb) {
988                         usb_kill_urb(ep->out->urb);
989                         if (umidi->usb_protocol_ops->finish_out_endpoint)
990                                 umidi->usb_protocol_ops->finish_out_endpoint(ep->out);
991                 }
992                 if (ep->in && ep->in->urb)
993                         usb_kill_urb(ep->in->urb);
994         }
995 }
996
997 static void snd_usbmidi_rawmidi_free(snd_rawmidi_t* rmidi)
998 {
999         snd_usb_midi_t* umidi = rmidi->private_data;
1000         snd_usbmidi_free(umidi);
1001 }
1002
1003 static snd_rawmidi_substream_t* snd_usbmidi_find_substream(snd_usb_midi_t* umidi,
1004                                                            int stream, int number)
1005 {
1006         struct list_head* list;
1007
1008         list_for_each(list, &umidi->rmidi->streams[stream].substreams) {
1009                 snd_rawmidi_substream_t* substream = list_entry(list, snd_rawmidi_substream_t, list);
1010                 if (substream->number == number)
1011                         return substream;
1012         }
1013         return NULL;
1014 }
1015
1016 /*
1017  * This list specifies names for ports that do not fit into the standard
1018  * "(product) MIDI (n)" schema because they aren't external MIDI ports,
1019  * such as internal control or synthesizer ports.
1020  */
1021 static struct {
1022         u32 id;
1023         int port;
1024         const char *name_format;
1025 } snd_usbmidi_port_names[] = {
1026         /* Roland UA-100 */
1027         { USB_ID(0x0582, 0x0000), 2, "%s Control" },
1028         /* Roland SC-8850 */
1029         { USB_ID(0x0582, 0x0003), 0, "%s Part A" },
1030         { USB_ID(0x0582, 0x0003), 1, "%s Part B" },
1031         { USB_ID(0x0582, 0x0003), 2, "%s Part C" },
1032         { USB_ID(0x0582, 0x0003), 3, "%s Part D" },
1033         { USB_ID(0x0582, 0x0003), 4, "%s MIDI 1" },
1034         { USB_ID(0x0582, 0x0003), 5, "%s MIDI 2" },
1035         /* Roland U-8 */
1036         { USB_ID(0x0582, 0x0004), 0, "%s MIDI" },
1037         { USB_ID(0x0582, 0x0004), 1, "%s Control" },
1038         /* Roland SC-8820 */
1039         { USB_ID(0x0582, 0x0007), 0, "%s Part A" },
1040         { USB_ID(0x0582, 0x0007), 1, "%s Part B" },
1041         { USB_ID(0x0582, 0x0007), 2, "%s MIDI" },
1042         /* Roland SK-500 */
1043         { USB_ID(0x0582, 0x000b), 0, "%s Part A" },
1044         { USB_ID(0x0582, 0x000b), 1, "%s Part B" },
1045         { USB_ID(0x0582, 0x000b), 2, "%s MIDI" },
1046         /* Roland SC-D70 */
1047         { USB_ID(0x0582, 0x000c), 0, "%s Part A" },
1048         { USB_ID(0x0582, 0x000c), 1, "%s Part B" },
1049         { USB_ID(0x0582, 0x000c), 2, "%s MIDI" },
1050         /* Edirol UM-880 */
1051         { USB_ID(0x0582, 0x0014), 8, "%s Control" },
1052         /* Edirol SD-90 */
1053         { USB_ID(0x0582, 0x0016), 0, "%s Part A" },
1054         { USB_ID(0x0582, 0x0016), 1, "%s Part B" },
1055         { USB_ID(0x0582, 0x0016), 2, "%s MIDI 1" },
1056         { USB_ID(0x0582, 0x0016), 3, "%s MIDI 2" },
1057         /* Edirol UM-550 */
1058         { USB_ID(0x0582, 0x0023), 5, "%s Control" },
1059         /* Edirol SD-20 */
1060         { USB_ID(0x0582, 0x0027), 0, "%s Part A" },
1061         { USB_ID(0x0582, 0x0027), 1, "%s Part B" },
1062         { USB_ID(0x0582, 0x0027), 2, "%s MIDI" },
1063         /* Edirol SD-80 */
1064         { USB_ID(0x0582, 0x0029), 0, "%s Part A" },
1065         { USB_ID(0x0582, 0x0029), 1, "%s Part B" },
1066         { USB_ID(0x0582, 0x0029), 2, "%s MIDI 1" },
1067         { USB_ID(0x0582, 0x0029), 3, "%s MIDI 2" },
1068         /* Edirol UA-700 */
1069         { USB_ID(0x0582, 0x002b), 0, "%s MIDI" },
1070         { USB_ID(0x0582, 0x002b), 1, "%s Control" },
1071         /* Roland VariOS */
1072         { USB_ID(0x0582, 0x002f), 0, "%s MIDI" },
1073         { USB_ID(0x0582, 0x002f), 1, "%s External MIDI" },
1074         { USB_ID(0x0582, 0x002f), 2, "%s Sync" },
1075         /* Edirol PCR */
1076         { USB_ID(0x0582, 0x0033), 0, "%s MIDI" },
1077         { USB_ID(0x0582, 0x0033), 1, "%s 1" },
1078         { USB_ID(0x0582, 0x0033), 2, "%s 2" },
1079         /* BOSS GS-10 */
1080         { USB_ID(0x0582, 0x003b), 0, "%s MIDI" },
1081         { USB_ID(0x0582, 0x003b), 1, "%s Control" },
1082         /* Edirol UA-1000 */
1083         { USB_ID(0x0582, 0x0044), 0, "%s MIDI" },
1084         { USB_ID(0x0582, 0x0044), 1, "%s Control" },
1085         /* Edirol UR-80 */
1086         { USB_ID(0x0582, 0x0048), 0, "%s MIDI" },
1087         { USB_ID(0x0582, 0x0048), 1, "%s 1" },
1088         { USB_ID(0x0582, 0x0048), 2, "%s 2" },
1089         /* Edirol PCR-A */
1090         { USB_ID(0x0582, 0x004d), 0, "%s MIDI" },
1091         { USB_ID(0x0582, 0x004d), 1, "%s 1" },
1092         { USB_ID(0x0582, 0x004d), 2, "%s 2" },
1093         /* M-Audio MidiSport 8x8 */
1094         { USB_ID(0x0763, 0x1031), 8, "%s Control" },
1095         { USB_ID(0x0763, 0x1033), 8, "%s Control" },
1096         /* MOTU Fastlane */
1097         { USB_ID(0x07fd, 0x0001), 0, "%s MIDI A" },
1098         { USB_ID(0x07fd, 0x0001), 1, "%s MIDI B" },
1099         /* Emagic Unitor8/AMT8/MT4 */
1100         { USB_ID(0x086a, 0x0001), 8, "%s Broadcast" },
1101         { USB_ID(0x086a, 0x0002), 8, "%s Broadcast" },
1102         { USB_ID(0x086a, 0x0003), 4, "%s Broadcast" },
1103 };
1104
1105 static void snd_usbmidi_init_substream(snd_usb_midi_t* umidi,
1106                                        int stream, int number,
1107                                        snd_rawmidi_substream_t** rsubstream)
1108 {
1109         int i;
1110         const char *name_format;
1111
1112         snd_rawmidi_substream_t* substream = snd_usbmidi_find_substream(umidi, stream, number);
1113         if (!substream) {
1114                 snd_printd(KERN_ERR "substream %d:%d not found\n", stream, number);
1115                 return;
1116         }
1117
1118         /* TODO: read port name from jack descriptor */
1119         name_format = "%s MIDI %d";
1120         for (i = 0; i < ARRAY_SIZE(snd_usbmidi_port_names); ++i) {
1121                 if (snd_usbmidi_port_names[i].id == umidi->chip->usb_id &&
1122                     snd_usbmidi_port_names[i].port == number) {
1123                         name_format = snd_usbmidi_port_names[i].name_format;
1124                         break;
1125                 }
1126         }
1127         snprintf(substream->name, sizeof(substream->name),
1128                  name_format, umidi->chip->card->shortname, number + 1);
1129
1130         *rsubstream = substream;
1131 }
1132
1133 /*
1134  * Creates the endpoints and their ports.
1135  */
1136 static int snd_usbmidi_create_endpoints(snd_usb_midi_t* umidi,
1137                                         snd_usb_midi_endpoint_info_t* endpoints)
1138 {
1139         int i, j, err;
1140         int out_ports = 0, in_ports = 0;
1141
1142         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1143                 if (endpoints[i].out_cables) {
1144                         err = snd_usbmidi_out_endpoint_create(umidi, &endpoints[i],
1145                                                               &umidi->endpoints[i]);
1146                         if (err < 0)
1147                                 return err;
1148                 }
1149                 if (endpoints[i].in_cables) {
1150                         err = snd_usbmidi_in_endpoint_create(umidi, &endpoints[i],
1151                                                              &umidi->endpoints[i]);
1152                         if (err < 0)
1153                                 return err;
1154                 }
1155
1156                 for (j = 0; j < 0x10; ++j) {
1157                         if (endpoints[i].out_cables & (1 << j)) {
1158                                 snd_usbmidi_init_substream(umidi, SNDRV_RAWMIDI_STREAM_OUTPUT, out_ports,
1159                                                            &umidi->endpoints[i].out->ports[j].substream);
1160                                 ++out_ports;
1161                         }
1162                         if (endpoints[i].in_cables & (1 << j)) {
1163                                 snd_usbmidi_init_substream(umidi, SNDRV_RAWMIDI_STREAM_INPUT, in_ports,
1164                                                            &umidi->endpoints[i].in->ports[j].substream);
1165                                 ++in_ports;
1166                         }
1167                 }
1168         }
1169         snd_printdd(KERN_INFO "created %d output and %d input ports\n",
1170                     out_ports, in_ports);
1171         return 0;
1172 }
1173
1174 /*
1175  * Returns MIDIStreaming device capabilities.
1176  */
1177 static int snd_usbmidi_get_ms_info(snd_usb_midi_t* umidi,
1178                                    snd_usb_midi_endpoint_info_t* endpoints)
1179 {
1180         struct usb_interface* intf;
1181         struct usb_host_interface *hostif;
1182         struct usb_interface_descriptor* intfd;
1183         struct usb_ms_header_descriptor* ms_header;
1184         struct usb_host_endpoint *hostep;
1185         struct usb_endpoint_descriptor* ep;
1186         struct usb_ms_endpoint_descriptor* ms_ep;
1187         int i, epidx;
1188
1189         intf = umidi->iface;
1190         if (!intf)
1191                 return -ENXIO;
1192         hostif = &intf->altsetting[0];
1193         intfd = get_iface_desc(hostif);
1194         ms_header = (struct usb_ms_header_descriptor*)hostif->extra;
1195         if (hostif->extralen >= 7 &&
1196             ms_header->bLength >= 7 &&
1197             ms_header->bDescriptorType == USB_DT_CS_INTERFACE &&
1198             ms_header->bDescriptorSubtype == HEADER)
1199                 snd_printdd(KERN_INFO "MIDIStreaming version %02x.%02x\n",
1200                             ms_header->bcdMSC[1], ms_header->bcdMSC[0]);
1201         else
1202                 snd_printk(KERN_WARNING "MIDIStreaming interface descriptor not found\n");
1203
1204         epidx = 0;
1205         for (i = 0; i < intfd->bNumEndpoints; ++i) {
1206                 hostep = &hostif->endpoint[i];
1207                 ep = get_ep_desc(hostep);
1208                 if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK &&
1209                     (ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_INT)
1210                         continue;
1211                 ms_ep = (struct usb_ms_endpoint_descriptor*)hostep->extra;
1212                 if (hostep->extralen < 4 ||
1213                     ms_ep->bLength < 4 ||
1214                     ms_ep->bDescriptorType != USB_DT_CS_ENDPOINT ||
1215                     ms_ep->bDescriptorSubtype != MS_GENERAL)
1216                         continue;
1217                 if ((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) {
1218                         if (endpoints[epidx].out_ep) {
1219                                 if (++epidx >= MIDI_MAX_ENDPOINTS) {
1220                                         snd_printk(KERN_WARNING "too many endpoints\n");
1221                                         break;
1222                                 }
1223                         }
1224                         endpoints[epidx].out_ep = ep->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1225                         if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
1226                                 endpoints[epidx].out_interval = ep->bInterval;
1227                         endpoints[epidx].out_cables = (1 << ms_ep->bNumEmbMIDIJack) - 1;
1228                         snd_printdd(KERN_INFO "EP %02X: %d jack(s)\n",
1229                                     ep->bEndpointAddress, ms_ep->bNumEmbMIDIJack);
1230                 } else {
1231                         if (endpoints[epidx].in_ep) {
1232                                 if (++epidx >= MIDI_MAX_ENDPOINTS) {
1233                                         snd_printk(KERN_WARNING "too many endpoints\n");
1234                                         break;
1235                                 }
1236                         }
1237                         endpoints[epidx].in_ep = ep->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1238                         if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
1239                                 endpoints[epidx].in_interval = ep->bInterval;
1240                         endpoints[epidx].in_cables = (1 << ms_ep->bNumEmbMIDIJack) - 1;
1241                         snd_printdd(KERN_INFO "EP %02X: %d jack(s)\n",
1242                                     ep->bEndpointAddress, ms_ep->bNumEmbMIDIJack);
1243                 }
1244         }
1245         return 0;
1246 }
1247
1248 /*
1249  * On Roland devices, use the second alternate setting to be able to use
1250  * the interrupt input endpoint.
1251  */
1252 static void snd_usbmidi_switch_roland_altsetting(snd_usb_midi_t* umidi)
1253 {
1254         struct usb_interface* intf;
1255         struct usb_host_interface *hostif;
1256         struct usb_interface_descriptor* intfd;
1257
1258         intf = umidi->iface;
1259         if (!intf || intf->num_altsetting != 2)
1260                 return;
1261
1262         hostif = &intf->altsetting[1];
1263         intfd = get_iface_desc(hostif);
1264         if (intfd->bNumEndpoints != 2 ||
1265             (get_endpoint(hostif, 0)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK ||
1266             (get_endpoint(hostif, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_INT)
1267                 return;
1268
1269         snd_printdd(KERN_INFO "switching to altsetting %d with int ep\n",
1270                     intfd->bAlternateSetting);
1271         usb_set_interface(umidi->chip->dev, intfd->bInterfaceNumber,
1272                           intfd->bAlternateSetting);
1273 }
1274
1275 /*
1276  * Try to find any usable endpoints in the interface.
1277  */
1278 static int snd_usbmidi_detect_endpoints(snd_usb_midi_t* umidi,
1279                                         snd_usb_midi_endpoint_info_t* endpoint,
1280                                         int max_endpoints)
1281 {
1282         struct usb_interface* intf;
1283         struct usb_host_interface *hostif;
1284         struct usb_interface_descriptor* intfd;
1285         struct usb_endpoint_descriptor* epd;
1286         int i, out_eps = 0, in_eps = 0;
1287
1288         if (USB_ID_VENDOR(umidi->chip->usb_id) == 0x0582)
1289                 snd_usbmidi_switch_roland_altsetting(umidi);
1290
1291         if (endpoint[0].out_ep || endpoint[0].in_ep)
1292                 return 0;       
1293
1294         intf = umidi->iface;
1295         if (!intf || intf->num_altsetting < 1)
1296                 return -ENOENT;
1297         hostif = intf->cur_altsetting;
1298         intfd = get_iface_desc(hostif);
1299
1300         for (i = 0; i < intfd->bNumEndpoints; ++i) {
1301                 epd = get_endpoint(hostif, i);
1302                 if ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK &&
1303                     (epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_INT)
1304                         continue;
1305                 if (out_eps < max_endpoints &&
1306                     (epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) {
1307                         endpoint[out_eps].out_ep = epd->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1308                         if ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
1309                                 endpoint[out_eps].out_interval = epd->bInterval;
1310                         ++out_eps;
1311                 }
1312                 if (in_eps < max_endpoints &&
1313                     (epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) {
1314                         endpoint[in_eps].in_ep = epd->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1315                         if ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
1316                                 endpoint[in_eps].in_interval = epd->bInterval;
1317                         ++in_eps;
1318                 }
1319         }
1320         return (out_eps || in_eps) ? 0 : -ENOENT;
1321 }
1322
1323 /*
1324  * Detects the endpoints for one-port-per-endpoint protocols.
1325  */
1326 static int snd_usbmidi_detect_per_port_endpoints(snd_usb_midi_t* umidi,
1327                                                  snd_usb_midi_endpoint_info_t* endpoints)
1328 {
1329         int err, i;
1330         
1331         err = snd_usbmidi_detect_endpoints(umidi, endpoints, MIDI_MAX_ENDPOINTS);
1332         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1333                 if (endpoints[i].out_ep)
1334                         endpoints[i].out_cables = 0x0001;
1335                 if (endpoints[i].in_ep)
1336                         endpoints[i].in_cables = 0x0001;
1337         }
1338         return err;
1339 }
1340
1341 /*
1342  * Detects the endpoints and ports of Yamaha devices.
1343  */
1344 static int snd_usbmidi_detect_yamaha(snd_usb_midi_t* umidi,
1345                                      snd_usb_midi_endpoint_info_t* endpoint)
1346 {
1347         struct usb_interface* intf;
1348         struct usb_host_interface *hostif;
1349         struct usb_interface_descriptor* intfd;
1350         uint8_t* cs_desc;
1351
1352         intf = umidi->iface;
1353         if (!intf)
1354                 return -ENOENT;
1355         hostif = intf->altsetting;
1356         intfd = get_iface_desc(hostif);
1357         if (intfd->bNumEndpoints < 1)
1358                 return -ENOENT;
1359
1360         /*
1361          * For each port there is one MIDI_IN/OUT_JACK descriptor, not
1362          * necessarily with any useful contents.  So simply count 'em.
1363          */
1364         for (cs_desc = hostif->extra;
1365              cs_desc < hostif->extra + hostif->extralen && cs_desc[0] >= 2;
1366              cs_desc += cs_desc[0]) {
1367                 if (cs_desc[1] == CS_AUDIO_INTERFACE) {
1368                         if (cs_desc[2] == MIDI_IN_JACK)
1369                                 endpoint->in_cables = (endpoint->in_cables << 1) | 1;
1370                         else if (cs_desc[2] == MIDI_OUT_JACK)
1371                                 endpoint->out_cables = (endpoint->out_cables << 1) | 1;
1372                 }
1373         }
1374         if (!endpoint->in_cables && !endpoint->out_cables)
1375                 return -ENOENT;
1376
1377         return snd_usbmidi_detect_endpoints(umidi, endpoint, 1);
1378 }
1379
1380 /*
1381  * Creates the endpoints and their ports for Midiman devices.
1382  */
1383 static int snd_usbmidi_create_endpoints_midiman(snd_usb_midi_t* umidi,
1384                                                 snd_usb_midi_endpoint_info_t* endpoint)
1385 {
1386         snd_usb_midi_endpoint_info_t ep_info;
1387         struct usb_interface* intf;
1388         struct usb_host_interface *hostif;
1389         struct usb_interface_descriptor* intfd;
1390         struct usb_endpoint_descriptor* epd;
1391         int cable, err;
1392
1393         intf = umidi->iface;
1394         if (!intf)
1395                 return -ENOENT;
1396         hostif = intf->altsetting;
1397         intfd = get_iface_desc(hostif);
1398         /*
1399          * The various MidiSport devices have more or less random endpoint
1400          * numbers, so we have to identify the endpoints by their index in
1401          * the descriptor array, like the driver for that other OS does.
1402          *
1403          * There is one interrupt input endpoint for all input ports, one
1404          * bulk output endpoint for even-numbered ports, and one for odd-
1405          * numbered ports.  Both bulk output endpoints have corresponding
1406          * input bulk endpoints (at indices 1 and 3) which aren't used.
1407          */
1408         if (intfd->bNumEndpoints < (endpoint->out_cables > 0x0001 ? 5 : 3)) {
1409                 snd_printdd(KERN_ERR "not enough endpoints\n");
1410                 return -ENOENT;
1411         }
1412
1413         epd = get_endpoint(hostif, 0);
1414         if ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) != USB_DIR_IN ||
1415             (epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_INT) {
1416                 snd_printdd(KERN_ERR "endpoint[0] isn't interrupt\n");
1417                 return -ENXIO;
1418         }
1419         epd = get_endpoint(hostif, 2);
1420         if ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) != USB_DIR_OUT ||
1421             (epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK) {
1422                 snd_printdd(KERN_ERR "endpoint[2] isn't bulk output\n");
1423                 return -ENXIO;
1424         }
1425         if (endpoint->out_cables > 0x0001) {
1426                 epd = get_endpoint(hostif, 4);
1427                 if ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) != USB_DIR_OUT ||
1428                     (epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK) {
1429                         snd_printdd(KERN_ERR "endpoint[4] isn't bulk output\n");
1430                         return -ENXIO;
1431                 }
1432         }
1433
1434         ep_info.out_ep = get_endpoint(hostif, 2)->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1435         ep_info.out_cables = endpoint->out_cables & 0x5555;
1436         err = snd_usbmidi_out_endpoint_create(umidi, &ep_info, &umidi->endpoints[0]);
1437         if (err < 0)
1438                 return err;
1439
1440         ep_info.in_ep = get_endpoint(hostif, 0)->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1441         ep_info.in_interval = get_endpoint(hostif, 0)->bInterval;
1442         ep_info.in_cables = endpoint->in_cables;
1443         err = snd_usbmidi_in_endpoint_create(umidi, &ep_info, &umidi->endpoints[0]);
1444         if (err < 0)
1445                 return err;
1446
1447         if (endpoint->out_cables > 0x0001) {
1448                 ep_info.out_ep = get_endpoint(hostif, 4)->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1449                 ep_info.out_cables = endpoint->out_cables & 0xaaaa;
1450                 err = snd_usbmidi_out_endpoint_create(umidi, &ep_info, &umidi->endpoints[1]);
1451                 if (err < 0)
1452                         return err;
1453         }
1454
1455         for (cable = 0; cable < 0x10; ++cable) {
1456                 if (endpoint->out_cables & (1 << cable))
1457                         snd_usbmidi_init_substream(umidi, SNDRV_RAWMIDI_STREAM_OUTPUT, cable,
1458                                                    &umidi->endpoints[cable & 1].out->ports[cable].substream);
1459                 if (endpoint->in_cables & (1 << cable))
1460                         snd_usbmidi_init_substream(umidi, SNDRV_RAWMIDI_STREAM_INPUT, cable,
1461                                                    &umidi->endpoints[0].in->ports[cable].substream);
1462         }
1463         return 0;
1464 }
1465
1466 static int snd_usbmidi_create_rawmidi(snd_usb_midi_t* umidi,
1467                                       int out_ports, int in_ports)
1468 {
1469         snd_rawmidi_t* rmidi;
1470         int err;
1471
1472         err = snd_rawmidi_new(umidi->chip->card, "USB MIDI",
1473                               umidi->chip->next_midi_device++,
1474                               out_ports, in_ports, &rmidi);
1475         if (err < 0)
1476                 return err;
1477         strcpy(rmidi->name, umidi->chip->card->shortname);
1478         rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
1479                             SNDRV_RAWMIDI_INFO_INPUT |
1480                             SNDRV_RAWMIDI_INFO_DUPLEX;
1481         rmidi->private_data = umidi;
1482         rmidi->private_free = snd_usbmidi_rawmidi_free;
1483         snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_usbmidi_output_ops);
1484         snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_usbmidi_input_ops);
1485
1486         umidi->rmidi = rmidi;
1487         return 0;
1488 }
1489
1490 /*
1491  * Temporarily stop input.
1492  */
1493 void snd_usbmidi_input_stop(struct list_head* p)
1494 {
1495         snd_usb_midi_t* umidi;
1496         int i;
1497
1498         umidi = list_entry(p, snd_usb_midi_t, list);
1499         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1500                 snd_usb_midi_endpoint_t* ep = &umidi->endpoints[i];
1501                 if (ep->in)
1502                         usb_kill_urb(ep->in->urb);
1503         }
1504 }
1505
1506 static void snd_usbmidi_input_start_ep(snd_usb_midi_in_endpoint_t* ep)
1507 {
1508         if (ep) {
1509                 struct urb* urb = ep->urb;
1510                 urb->dev = ep->umidi->chip->dev;
1511                 snd_usbmidi_submit_urb(urb, GFP_KERNEL);
1512         }
1513 }
1514
1515 /*
1516  * Resume input after a call to snd_usbmidi_input_stop().
1517  */
1518 void snd_usbmidi_input_start(struct list_head* p)
1519 {
1520         snd_usb_midi_t* umidi;
1521         int i;
1522
1523         umidi = list_entry(p, snd_usb_midi_t, list);
1524         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
1525                 snd_usbmidi_input_start_ep(umidi->endpoints[i].in);
1526 }
1527
1528 /*
1529  * Creates and registers everything needed for a MIDI streaming interface.
1530  */
1531 int snd_usb_create_midi_interface(snd_usb_audio_t* chip,
1532                                   struct usb_interface* iface,
1533                                   const snd_usb_audio_quirk_t* quirk)
1534 {
1535         snd_usb_midi_t* umidi;
1536         snd_usb_midi_endpoint_info_t endpoints[MIDI_MAX_ENDPOINTS];
1537         int out_ports, in_ports;
1538         int i, err;
1539
1540         umidi = kcalloc(1, sizeof(*umidi), GFP_KERNEL);
1541         if (!umidi)
1542                 return -ENOMEM;
1543         umidi->chip = chip;
1544         umidi->iface = iface;
1545         umidi->quirk = quirk;
1546         umidi->usb_protocol_ops = &snd_usbmidi_standard_ops;
1547         init_timer(&umidi->error_timer);
1548         umidi->error_timer.function = snd_usbmidi_error_timer;
1549         umidi->error_timer.data = (unsigned long)umidi;
1550
1551         /* detect the endpoint(s) to use */
1552         memset(endpoints, 0, sizeof(endpoints));
1553         if (!quirk) {
1554                 err = snd_usbmidi_get_ms_info(umidi, endpoints);
1555         } else {
1556                 switch (quirk->type) {
1557                 case QUIRK_MIDI_FIXED_ENDPOINT:
1558                         memcpy(&endpoints[0], quirk->data,
1559                                sizeof(snd_usb_midi_endpoint_info_t));
1560                         err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
1561                         break;
1562                 case QUIRK_MIDI_YAMAHA:
1563                         err = snd_usbmidi_detect_yamaha(umidi, &endpoints[0]);
1564                         break;
1565                 case QUIRK_MIDI_MIDIMAN:
1566                         umidi->usb_protocol_ops = &snd_usbmidi_midiman_ops;
1567                         memcpy(&endpoints[0], quirk->data,
1568                                sizeof(snd_usb_midi_endpoint_info_t));
1569                         err = 0;
1570                         break;
1571                 case QUIRK_MIDI_NOVATION:
1572                         umidi->usb_protocol_ops = &snd_usbmidi_novation_ops;
1573                         err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
1574                         break;
1575                 case QUIRK_MIDI_RAW:
1576                         umidi->usb_protocol_ops = &snd_usbmidi_raw_ops;
1577                         err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
1578                         break;
1579                 case QUIRK_MIDI_EMAGIC:
1580                         umidi->usb_protocol_ops = &snd_usbmidi_emagic_ops;
1581                         memcpy(&endpoints[0], quirk->data,
1582                                sizeof(snd_usb_midi_endpoint_info_t));
1583                         err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
1584                         break;
1585                 case QUIRK_MIDI_MIDITECH:
1586                         err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
1587                         break;
1588                 default:
1589                         snd_printd(KERN_ERR "invalid quirk type %d\n", quirk->type);
1590                         err = -ENXIO;
1591                         break;
1592                 }
1593         }
1594         if (err < 0) {
1595                 kfree(umidi);
1596                 return err;
1597         }
1598
1599         /* create rawmidi device */
1600         out_ports = 0;
1601         in_ports = 0;
1602         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
1603                 out_ports += snd_usbmidi_count_bits(endpoints[i].out_cables);
1604                 in_ports += snd_usbmidi_count_bits(endpoints[i].in_cables);
1605         }
1606         err = snd_usbmidi_create_rawmidi(umidi, out_ports, in_ports);
1607         if (err < 0) {
1608                 kfree(umidi);
1609                 return err;
1610         }
1611
1612         /* create endpoint/port structures */
1613         if (quirk && quirk->type == QUIRK_MIDI_MIDIMAN)
1614                 err = snd_usbmidi_create_endpoints_midiman(umidi, &endpoints[0]);
1615         else
1616                 err = snd_usbmidi_create_endpoints(umidi, endpoints);
1617         if (err < 0) {
1618                 snd_usbmidi_free(umidi);
1619                 return err;
1620         }
1621
1622         list_add(&umidi->list, &umidi->chip->midi_list);
1623
1624         for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i)
1625                 snd_usbmidi_input_start_ep(umidi->endpoints[i].in);
1626         return 0;
1627 }
1628
1629 EXPORT_SYMBOL(snd_usb_create_midi_interface);
1630 EXPORT_SYMBOL(snd_usbmidi_input_stop);
1631 EXPORT_SYMBOL(snd_usbmidi_input_start);
1632 EXPORT_SYMBOL(snd_usbmidi_disconnect);