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