ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / class / usb-midi.c
1 /*
2   usb-midi.c  --  USB-MIDI driver
3
4   Copyright (C) 2001 
5       NAGANO Daisuke <breeze.nagano@nifty.ne.jp>
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2, or (at your option)
10   any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program; if not, write to the Free Software
19   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21   This driver is based on:
22     - 'Universal Serial Bus Device Class Definition for MIDI Device'
23     - linux/drivers/sound/es1371.c, linux/drivers/usb/audio.c
24     - alsa/lowlevel/pci/cs64xx.c
25     - umidi.c for NetBSD
26  */
27
28 /* ------------------------------------------------------------------------- */
29
30
31 #include <linux/module.h>
32 #include <linux/kernel.h>
33 #include <linux/sched.h>
34 #include <linux/list.h>
35 #include <linux/slab.h>
36 #include <linux/usb.h>
37 #include <linux/poll.h>
38 #include <linux/sound.h>
39 #include <linux/init.h>
40 #include <asm/semaphore.h>
41
42 #include "usb-midi.h"
43
44 /* ------------------------------------------------------------------------- */
45
46 /* More verbose on syslog */
47 #undef MIDI_DEBUG
48
49 #define MIDI_IN_BUFSIZ 1024
50
51 #define HAVE_SUPPORT_USB_MIDI_CLASS
52
53 #undef HAVE_SUPPORT_ALSA
54
55 /* ------------------------------------------------------------------------- */
56
57 static int singlebyte = 0;
58 MODULE_PARM(singlebyte,"i");
59 MODULE_PARM_DESC(singlebyte,"Enable sending MIDI messages with single message packet");
60
61 static int maxdevices = 4;
62 MODULE_PARM(maxdevices,"i");
63 MODULE_PARM_DESC(maxdevices,"Max number of allocatable MIDI device");
64
65 static int uvendor     = -1;
66 MODULE_PARM(uvendor,"i");
67 MODULE_PARM_DESC(uvendor, "The USB Vendor ID of a semi-compliant interface");
68
69 static int uproduct    = -1;
70 MODULE_PARM(uproduct,"i");
71 MODULE_PARM_DESC(uproduct, "The USB Product ID of a semi-compliant interface");
72
73 static int uinterface  = -1;
74 MODULE_PARM(uinterface,"i");
75 MODULE_PARM_DESC(uinterface, "The Interface number of a semi-compliant interface");
76
77 static int ualt        = -1;
78 MODULE_PARM(ualt,"i");
79 MODULE_PARM_DESC(ualt, "The optional alternative setting of a semi-compliant interface");
80
81 static int umin        = -1;
82 MODULE_PARM(umin,"i");
83 MODULE_PARM_DESC(umin, "The input endpoint of a semi-compliant interface");
84
85 static int umout       = -1;
86 MODULE_PARM(umout,"i");
87 MODULE_PARM_DESC(umout, "The output endpoint of a semi-compliant interface");
88
89 static int ucable      = -1;
90 MODULE_PARM(ucable,"i");
91 MODULE_PARM_DESC(ucable, "The cable number used for a semi-compliant interface");
92
93 /** Note -- the usb_string() returns only Latin-1 characters.
94  * (unicode chars <= 255). To support Japanese, a unicode16LE-to-EUC or
95  * unicode16LE-to-JIS routine is needed to wrap around usb_get_string().
96  **/
97 static unsigned short ulangid      = 0x0409; /** 0x0411 for Japanese **/
98 MODULE_PARM(ulangid,"h");
99 MODULE_PARM_DESC(ulangid, "The optional preferred USB Language ID for all devices");
100
101 MODULE_AUTHOR("NAGANO Daisuke <breeze.nagano@nifty.ne.jp>");
102 MODULE_DESCRIPTION("USB-MIDI driver");
103 MODULE_LICENSE("GPL");
104
105 /* ------------------------------------------------------------------------- */
106
107 /** MIDIStreaming Class-Specific Interface Descriptor Subtypes **/
108
109 #define MS_DESCRIPTOR_UNDEFINED 0
110 #define MS_HEADER               1
111 #define MIDI_IN_JACK            2
112 #define MIDI_OUT_JACK           3
113 /* Spec reads: ELEMENT */
114 #define ELEMENT_DESCRIPTOR      4
115
116 #define MS_HEADER_LENGTH        7
117
118 /** MIDIStreaming Class-Specific Endpoint Descriptor Subtypes **/
119
120 #define DESCRIPTOR_UNDEFINED    0
121 /* Spec reads: MS_GENERAL */
122 #define MS_GENERAL_ENDPOINT     1
123
124 /** MIDIStreaming MIDI IN and OUT Jack Types **/
125
126 #define JACK_TYPE_UNDEFINED     0
127 /* Spec reads: EMBEDDED */
128 #define EMBEDDED_JACK           1
129 /* Spec reads: EXTERNAL */
130 #define EXTERNAL_JACK           2
131
132
133 /* structure summary
134   
135       usb_midi_state     usb_device
136        |         |
137       *|        *|       per ep
138      in_ep     out_ep
139        |         |
140       *|        *|       per cable
141       min       mout
142        |         |       (cable to device pairing magic)
143        |         |
144        usb_midi_dev      dev_id (major,minor) == file->private_data
145
146 */
147
148 /* usb_midi_state: corresponds to a USB-MIDI module */
149 struct usb_midi_state {
150         struct list_head   mididev;
151         
152         struct usb_device *usbdev;
153         
154         struct list_head   midiDevList;
155         struct list_head   inEndpointList;
156         struct list_head   outEndpointList;
157         
158         spinlock_t         lock;
159         
160         unsigned int       count; /* usage counter */
161 };
162
163 /* midi_out_endpoint: corresponds to an output endpoint */
164 struct midi_out_endpoint {
165         struct list_head  list;
166         
167         struct usb_device *usbdev;
168         int                endpoint;
169         spinlock_t         lock;
170         wait_queue_head_t  wait;
171         
172         unsigned char     *buf;
173         int                bufWrPtr;
174         int                bufSize;
175         
176         struct urb       *urb;
177 };
178
179 /* midi_in_endpoint: corresponds to an input endpoint */
180 struct midi_in_endpoint {
181         struct list_head   list;
182
183         struct usb_device *usbdev;
184         int                endpoint;
185         spinlock_t         lock;
186         wait_queue_head_t  wait;
187
188         struct usb_mididev *cables[16]; // cables open for read
189         int                 readers;    // number of cables open for read
190
191         struct urb        *urb;
192         unsigned char     *recvBuf;
193         int                recvBufSize;
194         int                urbSubmitted;        //FIXME: == readers > 0
195 };
196
197 /* usb_mididev: corresponds to a logical device */
198 struct usb_mididev {
199         struct list_head       list;
200
201         struct usb_midi_state *midi;
202         int                    dev_midi;
203         mode_t                 open_mode;
204
205         struct {
206                 struct midi_in_endpoint *ep;
207                 int              cableId;
208                 
209 // as we are pushing data from usb_bulk_read to usb_midi_read,
210 // we need a larger, cyclic buffer here.
211                 unsigned char    buf[MIDI_IN_BUFSIZ];
212                 int              bufRdPtr;
213                 int              bufWrPtr;
214                 int              bufRemains;
215         } min;
216
217         struct {
218                 struct midi_out_endpoint *ep;
219                 int              cableId;
220                 
221                 unsigned char    buf[3];
222                 int              bufPtr;
223                 int              bufRemains;
224                 
225                 int              isInExclusive;
226                 unsigned char    lastEvent;
227         } mout;
228
229         int singlebyte;
230 };
231
232 /** Map the high nybble of MIDI voice messages to number of Message bytes.
233  * High nyble ranges from 0x8 to 0xe
234  */
235
236 static int remains_80e0[] = {
237         3,      /** 0x8X Note Off **/
238         3,      /** 0x9X Note On **/
239         3,      /** 0xAX Poly-key pressure **/
240         3,      /** 0xBX Control Change **/
241         2,      /** 0xCX Program Change **/
242         2,      /** 0xDX Channel pressure **/
243         3       /** 0xEX PitchBend Change **/
244 };
245
246 /** Map the messages to a number of Message bytes.
247  *
248  **/
249 static int remains_f0f6[] = {
250         0,      /** 0xF0 **/
251         2,      /** 0XF1 **/
252         3,      /** 0XF2 **/
253         2,      /** 0XF3 **/
254         2,      /** 0XF4 (Undefined by MIDI Spec, and subject to change) **/
255         2,      /** 0XF5 (Undefined by MIDI Spec, and subject to change) **/
256         1       /** 0XF6 **/
257 };
258
259 /** Map the messages to a CIN (Code Index Number).
260  *
261  **/
262 static int cin_f0ff[] = {
263         4,      /** 0xF0 System Exclusive Message Start (special cases may be 6 or 7) */
264         2,      /** 0xF1 **/
265         3,      /** 0xF2 **/
266         2,      /** 0xF3 **/
267         2,      /** 0xF4 **/
268         2,      /** 0xF5 **/
269         5,      /** 0xF6 **/
270         5,      /** 0xF7 End of System Exclusive Message (May be 6 or 7) **/
271         5,      /** 0xF8 **/
272         5,      /** 0xF9 **/
273         5,      /** 0xFA **/
274         5,      /** 0xFB **/
275         5,      /** 0xFC **/
276         5,      /** 0xFD **/
277         5,      /** 0xFE **/
278         5       /** 0xFF **/
279 };
280
281 /** Map MIDIStreaming Event packet Code Index Number (low nybble of byte 0)
282  * to the number of bytes of valid MIDI data.
283  *
284  * CIN of 0 and 1 are NOT USED in MIDIStreaming 1.0.
285  *
286  **/
287 static int cin_to_len[] = {
288         0, 0, 2, 3,
289         3, 1, 2, 3,
290         3, 3, 3, 3,
291         2, 2, 3, 1
292 };
293
294
295 /* ------------------------------------------------------------------------- */
296
297 static struct list_head mididevs = LIST_HEAD_INIT(mididevs);
298
299 static DECLARE_MUTEX(open_sem);
300 static DECLARE_WAIT_QUEUE_HEAD(open_wait);
301
302
303 /* ------------------------------------------------------------------------- */
304
305 static void usb_write_callback(struct urb *urb, struct pt_regs *regs)
306 {
307         struct midi_out_endpoint *ep = (struct midi_out_endpoint *)urb->context;
308
309         if ( waitqueue_active( &ep->wait ) )
310                 wake_up_interruptible( &ep->wait );
311 }
312
313
314 static int usb_write( struct midi_out_endpoint *ep, unsigned char *buf, int len )
315 {
316         struct usb_device *d;
317         int pipe;
318         int ret = 0;
319         int status;
320         int maxretry = 50;
321         
322         DECLARE_WAITQUEUE(wait,current);
323         init_waitqueue_head(&ep->wait);
324
325         d = ep->usbdev;
326         pipe = usb_sndbulkpipe(d, ep->endpoint);
327         usb_fill_bulk_urb( ep->urb, d, pipe, (unsigned char*)buf, len,
328                        usb_write_callback, ep );
329
330         status = usb_submit_urb(ep->urb, GFP_KERNEL);
331     
332         if (status) {
333                 printk(KERN_ERR "usbmidi: Cannot submit urb (%d)\n",status);
334                 ret = -EIO;
335                 goto error;
336         }
337
338         add_wait_queue( &ep->wait, &wait );
339         set_current_state( TASK_INTERRUPTIBLE );
340
341         while( ep->urb->status == -EINPROGRESS ) {
342                 if ( maxretry-- < 0 ) {
343                         printk(KERN_ERR "usbmidi: usb_bulk_msg timed out\n");
344                         ret = -ETIME;
345                         break;
346                 }
347                 interruptible_sleep_on_timeout( &ep->wait, 10 );
348         }
349         set_current_state( TASK_RUNNING );
350         remove_wait_queue( &ep->wait, &wait );
351
352 error:
353         return ret;
354 }
355
356
357 /** Copy data from URB to In endpoint buf.
358  * Discard if CIN == 0 or CIN = 1.
359  *
360  *
361  **/
362
363 static void usb_bulk_read(struct urb *urb, struct pt_regs *regs)
364 {
365         struct midi_in_endpoint *ep = (struct midi_in_endpoint *)(urb->context);
366         unsigned char *data = urb->transfer_buffer;
367         int i, j, wake;
368
369         if ( !ep->urbSubmitted ) {
370                 return;
371         }
372
373         if ( (urb->status == 0) && (urb->actual_length > 0) ) {
374                 wake = 0;
375                 spin_lock( &ep->lock );
376
377                 for(j = 0; j < urb->actual_length; j += 4) {
378                         int cin = (data[j]>>0)&0xf;
379                         int cab = (data[j]>>4)&0xf;
380                         struct usb_mididev *cable = ep->cables[cab];
381                         if ( cable ) {
382                                 int len = cin_to_len[cin]; /** length of MIDI data **/
383                                 for (i = 0; i < len; i++) {
384                                         cable->min.buf[cable->min.bufWrPtr] = data[1+i+j];
385                                         cable->min.bufWrPtr = (cable->min.bufWrPtr+1)%MIDI_IN_BUFSIZ;
386                                         if (cable->min.bufRemains < MIDI_IN_BUFSIZ)
387                                                 cable->min.bufRemains += 1;
388                                         else /** need to drop data **/
389                                                 cable->min.bufRdPtr += (cable->min.bufRdPtr+1)%MIDI_IN_BUFSIZ;
390                                         wake = 1;
391                                 }
392                         }
393                 }
394
395                 spin_unlock ( &ep->lock );
396                 if ( wake ) {
397                         wake_up( &ep->wait );
398                 }
399         }
400
401         /* urb->dev must be reinitialized on 2.4.x kernels */
402         urb->dev = ep->usbdev;
403
404         urb->actual_length = 0;
405         usb_submit_urb(urb, GFP_ATOMIC);
406 }
407
408
409
410 /* ------------------------------------------------------------------------- */
411
412 /* This routine must be called with spin_lock */
413
414 /** Wrapper around usb_write().
415  *  This routine must be called with spin_lock held on ep.
416  *  Called by midiWrite(), putOneMidiEvent(), and  usb_midi_write();
417  **/
418 static int flush_midi_buffer( struct midi_out_endpoint *ep )
419 {
420         int ret=0;
421
422         if ( ep->bufWrPtr > 0 ) {
423                 ret = usb_write( ep, ep->buf, ep->bufWrPtr );
424                 ep->bufWrPtr = 0;
425         }
426
427         return ret;
428 }
429
430
431 /* ------------------------------------------------------------------------- */
432
433
434 /** Given a MIDI Event, determine size of data to be attached to 
435  * USB-MIDI packet.
436  * Returns 1, 2 or 3.
437  * Called by midiWrite();
438  * Uses remains_80e0 and remains_f0f6;
439  **/
440 static int get_remains(int event)
441 {
442         int ret;
443
444         if ( event  < 0x80 ) {
445                 ret = 1;
446         } else if ( event < 0xf0 ) {
447                 ret = remains_80e0[((event-0x80)>>4)&0x0f];
448         } else if ( event < 0xf7 ) {
449                 ret = remains_f0f6[event-0xf0];
450         } else {
451                 ret = 1;
452         }
453
454         return ret;
455 }
456
457 /** Given the output MIDI data in the output buffer, computes a reasonable 
458  * CIN.
459  * Called by putOneMidiEvent().
460  **/
461 static int get_CIN( struct usb_mididev *m )
462 {
463         int cin;
464
465         if ( m->mout.buf[0] == 0xf7 ) {
466                 cin = 5;
467         }
468         else if ( m->mout.buf[1] == 0xf7 ) {
469                 cin = 6;
470         }
471         else if ( m->mout.buf[2] == 0xf7 ) {
472                 cin = 7;
473         }
474         else {
475                 if ( m->mout.isInExclusive == 1 ) {
476                         cin = 4;
477                 } else if ( m->mout.buf[0] < 0x80 ) {
478                         /** One byte that we know nothing about. **/
479                         cin = 0xF; 
480                 } else if ( m->mout.buf[0] < 0xf0 ) {
481                         /** MIDI Voice messages 0x8X to 0xEX map to cin 0x8 to 0xE. **/
482                         cin = (m->mout.buf[0]>>4)&0x0f; 
483                 }
484                 else {
485                         /** Special lookup table exists for real-time events. **/
486                         cin = cin_f0ff[m->mout.buf[0]-0xf0];
487                 }
488         }
489
490         return cin;
491 }
492
493
494 /* ------------------------------------------------------------------------- */
495
496
497
498 /** Move data to USB endpoint buffer.
499  *
500  **/
501 static int put_one_midi_event(struct usb_mididev *m)
502 {
503         int cin;
504         unsigned long flags;
505         struct midi_out_endpoint *ep = m->mout.ep;
506         int ret=0;
507
508         cin = get_CIN( m );
509         if ( cin > 0x0f || cin < 0 ) {
510                 return -EINVAL;
511         }
512
513         spin_lock_irqsave( &ep->lock, flags );
514         ep->buf[ep->bufWrPtr++] = (m->mout.cableId<<4) | cin;
515         ep->buf[ep->bufWrPtr++] = m->mout.buf[0];
516         ep->buf[ep->bufWrPtr++] = m->mout.buf[1];
517         ep->buf[ep->bufWrPtr++] = m->mout.buf[2];
518         if ( ep->bufWrPtr >= ep->bufSize ) {
519                 ret = flush_midi_buffer( ep );
520         }
521         spin_unlock_irqrestore( &ep->lock, flags);
522
523         m->mout.buf[0] = m->mout.buf[1] = m->mout.buf[2] = 0;
524         m->mout.bufPtr = 0;
525
526         return ret;
527 }
528
529 /** Write the MIDI message v on the midi device.
530  *  Called by usb_midi_write();
531  *  Responsible for packaging a MIDI data stream into USB-MIDI packets.
532  **/
533
534 static int midi_write( struct usb_mididev *m, int v )
535 {
536         unsigned long flags;
537         struct midi_out_endpoint *ep = m->mout.ep;
538         int ret=0;
539         unsigned char c = (unsigned char)v;
540         unsigned char sysrt_buf[4];
541
542         if ( m->singlebyte != 0 ) {
543                 /** Simple code to handle the single-byte USB-MIDI protocol. */
544                 spin_lock_irqsave( &ep->lock, flags );
545                 if ( ep->bufWrPtr+4 > ep->bufSize ) {
546                         ret = flush_midi_buffer( ep );
547                         if ( !ret ) {
548                                 spin_unlock_irqrestore( &ep->lock, flags );
549                                 return ret;
550                         }
551                 }
552                 ep->buf[ep->bufWrPtr++] = (m->mout.cableId<<4) |  0x0f; /* single byte */
553                 ep->buf[ep->bufWrPtr++] = c;
554                 ep->buf[ep->bufWrPtr++] = 0;
555                 ep->buf[ep->bufWrPtr++] = 0;
556                 if ( ep->bufWrPtr >= ep->bufSize ) {
557                         ret = flush_midi_buffer( ep );
558                 }
559                 spin_unlock_irqrestore( &ep->lock, flags );
560
561                 return ret;
562         }
563         /** Normal USB-MIDI protocol begins here. */
564
565         if ( c > 0xf7 ) {       /* system: Realtime messages */
566                 /** Realtime messages are written IMMEDIATELY. */
567                 sysrt_buf[0] = (m->mout.cableId<<4) | 0x0f;
568                 sysrt_buf[1] = c;
569                 sysrt_buf[2] = 0;
570                 sysrt_buf[3] = 0;
571                 spin_lock_irqsave( &ep->lock, flags );
572                 ret = usb_write( ep, sysrt_buf, 4 );
573                 spin_unlock_irqrestore( &ep->lock, flags );
574                 /* m->mout.lastEvent = 0; */
575
576                 return ret;
577         }
578
579         if ( c >= 0x80 ) {
580                 if ( c < 0xf0 ) {
581                         m->mout.lastEvent = c;
582                         m->mout.isInExclusive = 0;
583                         m->mout.bufRemains = get_remains(c);
584                 } else if ( c == 0xf0 ) {
585                         /* m->mout.lastEvent = 0; */
586                         m->mout.isInExclusive = 1;
587                         m->mout.bufRemains = get_remains(c);
588                 } else if ( c == 0xf7 && m->mout.isInExclusive == 1 ) {
589                         /* m->mout.lastEvent = 0; */
590                         m->mout.isInExclusive = 0;
591                         m->mout.bufRemains = 1;
592                 } else if ( c > 0xf0 ) {
593                         /* m->mout.lastEvent = 0; */
594                         m->mout.isInExclusive = 0;
595                         m->mout.bufRemains = get_remains(c);
596                 }
597     
598         } else if ( m->mout.bufRemains == 0 && m->mout.isInExclusive == 0 ) {
599                 if ( m->mout.lastEvent == 0 ) {
600                         return 0; /* discard, waiting for the first event */
601                 }
602                 /** track status **/
603                 m->mout.buf[0] = m->mout.lastEvent;
604                 m->mout.bufPtr = 1;
605                 m->mout.bufRemains = get_remains(m->mout.lastEvent)-1;
606         }
607   
608         m->mout.buf[m->mout.bufPtr++] = c;
609         m->mout.bufRemains--;
610         if ( m->mout.bufRemains == 0 || m->mout.bufPtr >= 3) {
611                 ret = put_one_midi_event(m);
612         }
613
614         return ret;
615 }
616
617
618 /* ------------------------------------------------------------------------- */
619
620 /** Basic operation on /dev/midiXX as registered through struct file_operations.
621  *
622  *  Basic contract: Used to change the current read/write position in a file.
623  *  On success, the non-negative position is reported.
624  *  On failure, the negative of an error code is reported.
625  *
626  *  Because a MIDIStream is not a file, all seek operations are doomed to fail.
627  *
628  **/
629 static loff_t usb_midi_llseek(struct file *file, loff_t offset, int origin)
630 {
631         /** Tell user you cannot seek on a PIPE-like device. **/
632         return -ESPIPE;
633 }
634
635
636 /** Basic operation on /dev/midiXX as registered through struct file_operations.
637  *
638  * Basic contract: Block until count bytes have been read or an error occurs.
639  *
640  **/
641
642 static ssize_t usb_midi_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
643 {
644         struct usb_mididev *m = (struct usb_mididev *)file->private_data;
645         struct midi_in_endpoint *ep = m->min.ep;
646         ssize_t ret;
647         DECLARE_WAITQUEUE(wait, current);
648
649         if ( ppos != &file->f_pos ) {
650                 return -ESPIPE;
651         }
652         if ( !access_ok(VERIFY_READ, buffer, count) ) {
653                 return -EFAULT;
654         }
655         if ( count == 0 ) {
656                 return 0;
657         }
658
659         add_wait_queue( &ep->wait, &wait );
660         ret = 0;
661         while( count > 0 ) {
662                 int cnt;
663                 int d = (int)count;
664
665                 cnt = m->min.bufRemains;
666                 if ( cnt > d ) {
667                         cnt = d;
668                 }
669
670                 if ( cnt <= 0 ) {
671                         if ( file->f_flags & O_NONBLOCK ) {
672                                 if (!ret) 
673                                         ret = -EAGAIN;
674                                 break;
675                         }
676                         __set_current_state(TASK_INTERRUPTIBLE);
677                         schedule();
678                         if (signal_pending(current)) {
679                                 if(!ret)
680                                         ret=-ERESTARTSYS;
681                                 break;
682                         }
683                         continue;
684                 }
685
686                 {
687                         int i;
688                         unsigned long flags; /* used to synchronize access to the endpoint */
689                         spin_lock_irqsave( &ep->lock, flags );
690                         for (i = 0; i < cnt; i++) {
691                                 if ( copy_to_user( buffer+i, m->min.buf+m->min.bufRdPtr, 1 ) ) {
692                                         if ( !ret )
693                                                 ret = -EFAULT;
694                                         break;
695                                 }
696                                 m->min.bufRdPtr = (m->min.bufRdPtr+1)%MIDI_IN_BUFSIZ;
697                                 m->min.bufRemains -= 1;
698                         }
699                         spin_unlock_irqrestore( &ep->lock, flags );
700                 }
701
702                 count-=cnt;
703                 buffer+=cnt;
704                 ret+=cnt;
705
706                 break;
707         }
708
709         remove_wait_queue( &ep->wait, &wait );
710         set_current_state(TASK_RUNNING);
711
712         return ret;
713 }
714
715
716 /** Basic operation on /dev/midiXX as registered through struct file_operations.
717  *
718  *  Basic Contract: Take MIDI data byte-by-byte and pass it to
719  *  writeMidi() which packages MIDI data into USB-MIDI stream.
720  *  Then flushMidiData() is called to ensure all bytes have been written
721  *  in a timely fashion.
722  *
723  **/
724
725 static ssize_t usb_midi_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
726 {
727         struct usb_mididev *m = (struct usb_mididev *)file->private_data;
728         ssize_t ret;
729         unsigned long int flags;
730
731         if ( ppos != &file->f_pos ) {
732                 return -ESPIPE;
733         }
734         if ( !access_ok(VERIFY_READ, buffer, count) ) {
735                 return -EFAULT;
736         }
737         if ( count == 0 ) {
738                 return 0;
739         }
740
741         ret = 0;
742         while( count > 0 ) {
743                 unsigned char c;
744
745                 if (copy_from_user((unsigned char *)&c, buffer, 1)) {
746                         if ( ret == 0 )
747                                 ret = -EFAULT;
748                         break;
749                 }
750                 if( midi_write(m, (int)c) ) {
751                         if ( ret == 0 )
752                                 ret = -EFAULT;
753                         break;
754                 }
755                 count--;
756                 buffer++;
757                 ret++;
758         }
759
760         spin_lock_irqsave( &m->mout.ep->lock, flags );
761         if ( flush_midi_buffer(m->mout.ep) < 0 ) {
762                 ret = -EFAULT;
763         }
764         spin_unlock_irqrestore( &m->mout.ep->lock, flags );
765
766         return ret;
767 }
768
769 /** Basic operation on /dev/midiXX as registered through struct file_operations.
770  *
771  * Basic contract:  Wait (spin) until ready to read or write on the file.
772  *
773  **/
774 static unsigned int usb_midi_poll(struct file *file, struct poll_table_struct *wait)
775 {
776         struct usb_mididev *m = (struct usb_mididev *)file->private_data;
777         struct midi_in_endpoint *iep = m->min.ep;
778         struct midi_out_endpoint *oep = m->mout.ep;
779         unsigned long flags;
780         unsigned int mask = 0;
781   
782         if ( file->f_mode & FMODE_READ ) {
783                 poll_wait( file, &iep->wait, wait );
784                 spin_lock_irqsave( &iep->lock, flags );
785                 if ( m->min.bufRemains > 0 )
786                         mask |= POLLIN | POLLRDNORM;
787                 spin_unlock_irqrestore( &iep->lock, flags );
788         }
789
790         if ( file->f_mode & FMODE_WRITE ) {
791                 poll_wait( file, &oep->wait, wait );
792                 spin_lock_irqsave( &oep->lock, flags );
793                 if ( oep->bufWrPtr < oep->bufSize )
794                         mask |= POLLOUT | POLLWRNORM;
795                 spin_unlock_irqrestore( &oep->lock, flags );
796         }
797
798         return mask;
799 }
800
801
802 /** Basic operation on /dev/midiXX as registered through struct file_operations.
803  *
804  * Basic contract: This is always the first operation performed on the
805  * device node. If no method is defined, the open succeeds without any
806  * notification given to the module.
807  *
808  **/
809
810 static int usb_midi_open(struct inode *inode, struct file *file)
811 {
812         int minor = iminor(inode);
813         DECLARE_WAITQUEUE(wait, current);
814         struct list_head      *devs, *mdevs;
815         struct usb_midi_state *s;
816         struct usb_mididev    *m;
817         unsigned long flags;
818         int succeed = 0;
819
820 #if 0
821         printk(KERN_INFO "usb-midi: Open minor= %d.\n", minor);
822 #endif
823
824         for(;;) {
825                 down(&open_sem);
826                 for (devs = mididevs.next; devs != &mididevs; devs = devs->next) {
827                         s = list_entry(devs, struct usb_midi_state, mididev);
828                         for (mdevs = s->midiDevList.next; mdevs != &s->midiDevList; mdevs = mdevs->next) {
829                                 m = list_entry(mdevs, struct usb_mididev, list);
830                                 if ( !((m->dev_midi ^ minor) & ~0xf) )
831                                         goto device_found;
832                         }
833                 }
834                 up(&open_sem);
835                 return -ENODEV;
836
837         device_found:
838                 if ( !s->usbdev ) {
839                         up(&open_sem);
840                         return -EIO;
841                 }
842                 if ( !(m->open_mode & file->f_mode) ) {
843                         break;
844                 }
845                 if ( file->f_flags & O_NONBLOCK ) {
846                         up(&open_sem);
847                         return -EBUSY;
848                 }
849                 __set_current_state(TASK_INTERRUPTIBLE);
850                 add_wait_queue( &open_wait, &wait );
851                 up(&open_sem);
852                 schedule();
853                 remove_wait_queue( &open_wait, &wait );
854                 if ( signal_pending(current) ) {
855                         return -ERESTARTSYS;
856                 }
857         }
858
859         file->private_data = m;
860         spin_lock_irqsave( &s->lock, flags );
861
862         if ( !(m->open_mode & (FMODE_READ | FMODE_WRITE)) ) {
863                 //FIXME: intented semantics unclear here
864                 m->min.bufRdPtr       = 0;
865                 m->min.bufWrPtr       = 0;
866                 m->min.bufRemains     = 0;
867                 spin_lock_init(&m->min.ep->lock);
868
869                 m->mout.bufPtr        = 0;
870                 m->mout.bufRemains    = 0;
871                 m->mout.isInExclusive = 0;
872                 m->mout.lastEvent     = 0;
873                 spin_lock_init(&m->mout.ep->lock);
874         }
875
876         if ( (file->f_mode & FMODE_READ) && m->min.ep != NULL ) {
877                 unsigned long int flagsep;
878                 spin_lock_irqsave( &m->min.ep->lock, flagsep );
879                 m->min.ep->cables[m->min.cableId] = m;
880                 m->min.ep->readers += 1;
881                 m->min.bufRdPtr       = 0;
882                 m->min.bufWrPtr       = 0;
883                 m->min.bufRemains     = 0;
884                 spin_unlock_irqrestore( &m->min.ep->lock, flagsep );
885
886                 if ( !(m->min.ep->urbSubmitted)) {
887
888                         /* urb->dev must be reinitialized on 2.4.x kernels */
889                         m->min.ep->urb->dev = m->min.ep->usbdev;
890
891                         if ( usb_submit_urb(m->min.ep->urb, GFP_ATOMIC) ) {
892                                 printk(KERN_ERR "usbmidi: Cannot submit urb for MIDI-IN\n");
893                         }
894                         m->min.ep->urbSubmitted = 1;
895                 }
896                 m->open_mode |= FMODE_READ;
897                 succeed = 1;
898         }
899
900         if ( (file->f_mode & FMODE_WRITE) && m->mout.ep != NULL ) {
901                 m->mout.bufPtr        = 0;
902                 m->mout.bufRemains    = 0;
903                 m->mout.isInExclusive = 0;
904                 m->mout.lastEvent     = 0;
905                 m->open_mode |= FMODE_WRITE;
906                 succeed = 1;
907         }
908
909         spin_unlock_irqrestore( &s->lock, flags );
910
911         s->count++;
912         up(&open_sem);
913
914         /** Changed to prevent extra increments to USE_COUNT. **/
915         if (!succeed) {
916                 return -EBUSY;
917         }
918
919 #if 0
920         printk(KERN_INFO "usb-midi: Open Succeeded. minor= %d.\n", minor);
921 #endif
922
923         return 0; /** Success. **/
924 }
925
926
927 /** Basic operation on /dev/midiXX as registered through struct file_operations.
928  *
929  *  Basic contract: Close an opened file and deallocate anything we allocated.
930  *  Like open(), this can be missing. If open set file->private_data,
931  *  release() must clear it.
932  *
933  **/
934
935 static int usb_midi_release(struct inode *inode, struct file *file)
936 {
937         struct usb_mididev *m = (struct usb_mididev *)file->private_data;
938         struct usb_midi_state *s = (struct usb_midi_state *)m->midi;
939
940 #if 0
941         printk(KERN_INFO "usb-midi: Close.\n");
942 #endif
943
944         down(&open_sem);
945
946         if ( m->open_mode & FMODE_WRITE ) {
947                 m->open_mode &= ~FMODE_WRITE;
948                 usb_unlink_urb( m->mout.ep->urb );
949         }
950
951         if ( m->open_mode & FMODE_READ ) {
952                 unsigned long int flagsep;
953                 spin_lock_irqsave( &m->min.ep->lock, flagsep );
954                 m->min.ep->cables[m->min.cableId] = 0; // discard cable
955                 m->min.ep->readers -= 1;
956                 m->open_mode &= ~FMODE_READ;
957                 if ( m->min.ep->readers == 0 &&
958                      m->min.ep->urbSubmitted ) {
959                         m->min.ep->urbSubmitted = 0;
960                         usb_unlink_urb(m->min.ep->urb);
961                 }
962                 spin_unlock_irqrestore( &m->min.ep->lock, flagsep );
963         }
964
965         s->count--;
966
967         up(&open_sem);
968         wake_up(&open_wait);
969
970         file->private_data = 0;
971         return 0;
972 }
973
974 static struct file_operations usb_midi_fops = {
975         .owner =        THIS_MODULE,
976         .llseek =       usb_midi_llseek,
977         .read =         usb_midi_read,
978         .write =        usb_midi_write,
979         .poll =         usb_midi_poll,
980         .open =         usb_midi_open,
981         .release =      usb_midi_release,
982 };
983
984 /* ------------------------------------------------------------------------- */
985
986 /** Returns filled midi_in_endpoint structure or null on failure.
987  *
988  * Parameters:
989  *      d        - a usb_device
990  *      endPoint - An usb endpoint in the range 0 to 15.
991  * Called by allocUsbMidiDev();
992  *
993  **/
994
995 static struct midi_in_endpoint *alloc_midi_in_endpoint( struct usb_device *d, int endPoint )
996 {
997         struct midi_in_endpoint *ep;
998         int bufSize;
999         int pipe;
1000
1001         endPoint &= 0x0f; /* Silently force endPoint to lie in range 0 to 15. */
1002
1003         pipe =  usb_rcvbulkpipe( d, endPoint );
1004         bufSize = usb_maxpacket( d, pipe, usb_pipein(pipe) );
1005         /* usb_pipein() = ! usb_pipeout() = true for an in Endpoint */
1006
1007         ep = (struct midi_in_endpoint *)kmalloc(sizeof(struct midi_in_endpoint), GFP_KERNEL);
1008         if ( !ep ) {
1009                 printk(KERN_ERR "usbmidi: no memory for midi in-endpoint\n");
1010                 return NULL;
1011         }
1012         memset( ep, 0, sizeof(struct midi_in_endpoint) );
1013 //      this sets cables[] and readers to 0, too.
1014 //      for (i=0; i<16; i++) ep->cables[i] = 0; // discard cable
1015 //      ep->readers = 0;
1016
1017         ep->endpoint = endPoint;
1018
1019         ep->recvBuf = (unsigned char *)kmalloc(sizeof(unsigned char)*(bufSize), GFP_KERNEL);
1020         if ( !ep->recvBuf ) {
1021                 printk(KERN_ERR "usbmidi: no memory for midi in-endpoint buffer\n");
1022                 kfree(ep);
1023                 return NULL;
1024         }
1025
1026         ep->urb = usb_alloc_urb(0, GFP_KERNEL); /* no ISO */
1027         if ( !ep->urb ) {
1028                 printk(KERN_ERR "usbmidi: no memory for midi in-endpoint urb\n");
1029                 kfree(ep->recvBuf);
1030                 kfree(ep);
1031                 return NULL;
1032         }
1033         usb_fill_bulk_urb( ep->urb, d, 
1034                        usb_rcvbulkpipe(d, endPoint),
1035                        (unsigned char *)ep->recvBuf, bufSize,
1036                        usb_bulk_read, ep );
1037
1038         /* ep->bufRdPtr     = 0; */
1039         /* ep->bufWrPtr     = 0; */
1040         /* ep->bufRemains   = 0; */
1041         /* ep->urbSubmitted = 0; */
1042         ep->recvBufSize  = bufSize;
1043
1044         init_waitqueue_head(&ep->wait);
1045
1046         return ep;
1047 }
1048
1049 static int remove_midi_in_endpoint( struct midi_in_endpoint *min )
1050 {
1051         usb_unlink_urb( min->urb );
1052         usb_free_urb( min->urb );
1053         kfree( min->recvBuf );
1054         kfree( min );
1055
1056         return 0;
1057 }
1058
1059 /** Returns filled midi_out_endpoint structure or null on failure.
1060  *
1061  * Parameters:
1062  *      d        - a usb_device
1063  *      endPoint - An usb endpoint in the range 0 to 15.
1064  * Called by allocUsbMidiDev();
1065  *
1066  **/
1067 static struct midi_out_endpoint *alloc_midi_out_endpoint( struct usb_device *d, int endPoint )
1068 {
1069         struct midi_out_endpoint *ep = NULL;
1070         int pipe;
1071         int bufSize;
1072
1073         endPoint &= 0x0f;
1074         pipe =  usb_sndbulkpipe( d, endPoint );
1075         bufSize = usb_maxpacket( d, pipe, usb_pipeout(pipe) );
1076
1077         ep = (struct midi_out_endpoint *)kmalloc(sizeof(struct midi_out_endpoint), GFP_KERNEL);
1078         if ( !ep ) {
1079                 printk(KERN_ERR "usbmidi: no memory for midi out-endpoint\n");
1080                 return NULL;
1081         }
1082         memset( ep, 0, sizeof(struct midi_out_endpoint) );
1083
1084         ep->endpoint = endPoint;
1085         ep->buf = (unsigned char *)kmalloc(sizeof(unsigned char)*bufSize, GFP_KERNEL);
1086         if ( !ep->buf ) {
1087                 printk(KERN_ERR "usbmidi: no memory for midi out-endpoint buffer\n");
1088                 kfree(ep);
1089                 return NULL;
1090         }
1091
1092         ep->urb = usb_alloc_urb(0, GFP_KERNEL); /* no ISO */
1093         if ( !ep->urb ) {
1094                 printk(KERN_ERR "usbmidi: no memory for midi out-endpoint urb\n");
1095                 kfree(ep->buf);
1096                 kfree(ep);
1097                 return NULL;
1098         }
1099
1100         ep->bufSize       = bufSize;
1101         /* ep->bufWrPtr      = 0; */
1102
1103         init_waitqueue_head(&ep->wait);
1104
1105         return ep;
1106 }
1107
1108
1109 static int remove_midi_out_endpoint( struct midi_out_endpoint *mout )
1110 {
1111         usb_unlink_urb( mout->urb );
1112         usb_free_urb( mout->urb );
1113         kfree( mout->buf );
1114         kfree( mout );
1115
1116         return 0;
1117 }
1118
1119
1120 /** Returns a filled usb_mididev structure, registered as a Linux MIDI device.
1121  *
1122  * Returns null if memory is not available or the device cannot be registered.
1123  * Called by allocUsbMidiDev();
1124  *
1125  **/
1126 static struct usb_mididev *allocMidiDev(
1127         struct usb_midi_state *s,
1128         struct midi_in_endpoint *min,
1129         struct midi_out_endpoint *mout,
1130         int inCableId,
1131         int outCableId )
1132 {
1133         struct usb_mididev *m;
1134
1135         m = (struct usb_mididev *)kmalloc(sizeof(struct usb_mididev), GFP_KERNEL);
1136         if (!m) {
1137                 printk(KERN_ERR "usbmidi: no memory for midi device\n");
1138                 return NULL;
1139         }
1140
1141         memset(m, 0, sizeof(struct usb_mididev));
1142
1143         if ((m->dev_midi = register_sound_midi(&usb_midi_fops, -1)) < 0) {
1144                 printk(KERN_ERR "usbmidi: cannot register midi device\n");
1145                 kfree(m);
1146                 return NULL;
1147         }
1148
1149         m->midi               = s;
1150         /* m->open_mode          = 0; */
1151
1152         if ( min ) {
1153                 m->min.ep             = min;
1154                 m->min.ep->usbdev     = s->usbdev;
1155                 m->min.cableId        = inCableId;
1156         }
1157         /* m->min.bufPtr         = 0; */
1158         /* m->min.bufRemains     = 0; */
1159
1160         if ( mout ) {
1161                 m->mout.ep            = mout;
1162                 m->mout.ep->usbdev    = s->usbdev;
1163                 m->mout.cableId       = outCableId;
1164         }
1165         /* m->mout.bufPtr        = 0; */
1166         /* m->mout.bufRemains    = 0; */
1167         /* m->mout.isInExclusive = 0; */
1168         /* m->mout.lastEvent     = 0; */
1169
1170         m->singlebyte         = singlebyte;
1171
1172         return m;
1173 }
1174
1175
1176 static void release_midi_device( struct usb_midi_state *s )
1177 {
1178         struct usb_mididev *m;
1179         struct midi_in_endpoint *min;
1180         struct midi_out_endpoint *mout;
1181
1182         if ( s->count > 0 ) {
1183                 up(&open_sem);
1184                 return;
1185         }
1186         up( &open_sem );
1187         wake_up( &open_wait );
1188
1189         while(!list_empty(&s->inEndpointList)) {
1190                 min = list_entry(s->inEndpointList.next, struct midi_in_endpoint, list);
1191                 list_del(&min->list);
1192                 remove_midi_in_endpoint(min);
1193         }
1194
1195         while(!list_empty(&s->outEndpointList)) {
1196                 mout = list_entry(s->outEndpointList.next, struct midi_out_endpoint, list);
1197                 list_del(&mout->list);
1198                 remove_midi_out_endpoint(mout);
1199         }
1200
1201         while(!list_empty(&s->midiDevList)) {
1202                 m = list_entry(s->midiDevList.next, struct usb_mididev, list);
1203                 list_del(&m->list);
1204                 kfree(m);
1205         }
1206
1207         kfree(s);
1208
1209         return;
1210 }
1211
1212
1213 /* ------------------------------------------------------------------------- */
1214
1215 /** Utility routine to find a descriptor in a dump of many descriptors.
1216  * Returns start of descriptor or NULL if not found. 
1217  * descStart pointer to list of interfaces.
1218  * descLength length (in bytes) of dump
1219  * after (ignored if NULL) this routine returns only descriptors after "after"
1220  * dtype (mandatory) The descriptor type.
1221  * iface (ignored if -1) returns descriptor at/following given interface
1222  * altSetting (ignored if -1) returns descriptor at/following given altSetting
1223  *
1224  *
1225  *  Called by parseDescriptor(), find_csinterface_descriptor();
1226  *
1227  */
1228 static void *find_descriptor( void *descStart, unsigned int descLength, void *after, unsigned char dtype, int iface, int altSetting )
1229 {
1230         unsigned char *p, *end, *next;
1231         int interfaceNumber = -1, altSet = -1;
1232
1233         p = descStart;
1234         end = p + descLength;
1235         for( ; p < end; ) {
1236                 if ( p[0] < 2 )
1237                         return NULL;
1238                 next = p + p[0];
1239                 if ( next > end )
1240                         return NULL;
1241                 if ( p[1] == USB_DT_INTERFACE ) {
1242                         if ( p[0] < USB_DT_INTERFACE_SIZE )
1243                                 return NULL;
1244                         interfaceNumber = p[2];
1245                         altSet = p[3];
1246                 }
1247                 if ( p[1] == dtype &&
1248                      ( !after || ( p > (unsigned char *)after) ) &&
1249                      ( ( iface == -1) || (iface == interfaceNumber) ) &&
1250                      ( (altSetting == -1) || (altSetting == altSet) )) {
1251                         return p;
1252                 }
1253                 p = next;
1254         }
1255         return NULL;
1256 }
1257
1258 /** Utility to find a class-specific interface descriptor.
1259  *  dsubtype is a descriptor subtype
1260  *  Called by parseDescriptor();
1261  **/
1262 static void *find_csinterface_descriptor(void *descStart, unsigned int descLength, void *after, u8 dsubtype, int iface, int altSetting)
1263 {
1264         unsigned char *p;
1265   
1266         p = find_descriptor( descStart, descLength, after, USB_DT_CS_INTERFACE, iface, altSetting );
1267         while ( p ) {
1268                 if ( p[0] >= 3 && p[2] == dsubtype )
1269                         return p;
1270                 p = find_descriptor( descStart, descLength, p, USB_DT_CS_INTERFACE, 
1271                                      iface, altSetting );
1272         }
1273         return NULL;
1274 }
1275
1276
1277 /** The magic of making a new usb_midi_device from config happens here.
1278  *
1279  * The caller is responsible for free-ing this return value (if not NULL).
1280  *
1281  **/
1282 static struct usb_midi_device *parse_descriptor( struct usb_device *d, unsigned char *buffer, int bufSize, unsigned int ifnum , unsigned int altSetting, int quirks)
1283 {
1284         struct usb_midi_device *u;
1285         unsigned char *p1;
1286         unsigned char *p2;
1287         unsigned char *next;
1288         int iep, oep;
1289         int length;
1290         unsigned long longBits;
1291         int pins, nbytes, offset, shift, jack;
1292 #ifdef HAVE_JACK_STRINGS
1293         /** Jacks can have associated names.  **/
1294         unsigned char jack2string[256];
1295 #endif
1296
1297         u = 0;
1298         /* find audiocontrol interface */
1299         p1 = find_csinterface_descriptor( buffer, bufSize, NULL,
1300                                           MS_HEADER, ifnum, altSetting);
1301
1302         if ( !p1 ) {
1303                 goto error_end;
1304         }
1305
1306         if ( p1[0] < MS_HEADER_LENGTH ) {
1307                 goto error_end;
1308         }
1309
1310         /* Assume success. Since the device corresponds to USB-MIDI spec, we assume
1311            that the rest of the USB 2.0 spec is obeyed. */
1312
1313         u = (struct usb_midi_device *)kmalloc( sizeof(struct usb_midi_device), GFP_KERNEL );
1314         if ( !u ) {
1315                 return NULL;
1316         }
1317         u->deviceName = 0;
1318         u->idVendor = d->descriptor.idVendor;
1319         u->idProduct = d->descriptor.idProduct;
1320         u->interface = ifnum;
1321         u->altSetting = altSetting;
1322         u->in[0].endpoint = -1;
1323         u->in[0].cableId = -1;
1324         u->out[0].endpoint = -1;
1325         u->out[0].cableId = -1;
1326
1327
1328         printk(KERN_INFO "usb-midi: Found MIDIStreaming device corresponding to Release %d.%02d of spec.\n",
1329                (p1[4] >> 4) * 10 + (p1[4] & 0x0f ),
1330                (p1[3] >> 4) * 10 + (p1[3] & 0x0f )
1331                 );
1332
1333         length = p1[5] | (p1[6] << 8);
1334
1335 #ifdef HAVE_JACK_STRINGS
1336         memset(jack2string, 0, sizeof(unsigned char) * 256);
1337 #endif
1338
1339         length -= p1[0];
1340         for (p2 = p1 + p1[0]; length > 0; p2 = next) {
1341                 next = p2 + p2[0];
1342                 length -= p2[0];
1343
1344                 if (p2[0] < 2 )
1345                         break;
1346                 if (p2[1] != USB_DT_CS_INTERFACE)
1347                         break;
1348                 if (p2[2] == MIDI_IN_JACK && p2[0] >= 6 ) {
1349                         jack = p2[4];
1350 #ifdef HAVE_JACK_STRINGS
1351                         jack2string[jack] = p2[5];
1352 #endif
1353                         printk(KERN_INFO "usb-midi: Found IN Jack 0x%02x %s\n",
1354                                jack, (p2[3] == EMBEDDED_JACK)?"EMBEDDED":"EXTERNAL" );
1355                 } else if ( p2[2] == MIDI_OUT_JACK && p2[0] >= 6) {
1356                         pins = p2[5];
1357                         if ( p2[0] < (6 + 2 * pins) )
1358                                 continue;
1359                         jack = p2[4];
1360 #ifdef HAVE_JACK_STRINGS
1361                         jack2string[jack] = p2[5 + 2 * pins];
1362 #endif
1363                         printk(KERN_INFO "usb-midi: Found OUT Jack 0x%02x %s, %d pins\n",
1364                                jack, (p2[3] == EMBEDDED_JACK)?"EMBEDDED":"EXTERNAL", pins );
1365                 } else if ( p2[2] == ELEMENT_DESCRIPTOR  && p2[0]  >= 10) {
1366                         pins = p2[4];
1367                         if ( p2[0] < (9 + 2 * pins ) )
1368                                 continue;
1369                         nbytes = p2[8 + 2 * pins ];
1370                         if ( p2[0] < (10 + 2 * pins + nbytes) )
1371                                 continue;
1372                         longBits = 0L;
1373                         for ( offset = 0, shift = 0; offset < nbytes && offset < 8; offset ++, shift += 8) {
1374                                 longBits |= ((long)(p2[9 + 2 * pins + offset])) << shift;
1375                         }
1376                         jack = p2[3];
1377 #ifdef HAVE_JACK_STRINGS
1378                         jack2string[jack] = p2[9 + 2 * pins + nbytes];
1379 #endif
1380                         printk(KERN_INFO "usb-midi: Found ELEMENT 0x%02x, %d/%d pins in/out, bits: 0x%016lx\n",
1381                                jack, pins, (int)(p2[5 + 2 * pins]), (long)longBits );
1382                 } else {
1383                 }
1384         }
1385
1386         iep=0;
1387         oep=0;
1388
1389         if (quirks==0) {
1390                 /* MIDISTREAM */
1391                 p2 = 0;
1392                 for (p1 = find_descriptor(buffer, bufSize, NULL, USB_DT_ENDPOINT,
1393                                           ifnum, altSetting ); p1; p1 = next ) {
1394                         next = find_descriptor(buffer, bufSize, p1, USB_DT_ENDPOINT,
1395                                                ifnum, altSetting ); 
1396                         p2 = find_descriptor(buffer, bufSize, p1, USB_DT_CS_ENDPOINT,
1397                                              ifnum, altSetting ); 
1398
1399                         if ( p2 && next && ( p2 > next ) )
1400                                 p2 = 0;
1401
1402                         if ( p1[0] < 9 || !p2 || p2[0] < 4 )
1403                                 continue;
1404
1405                         if ( (p1[2] & 0x80) == 0x80 ) {
1406                                 if ( iep < 15 ) {
1407                                         pins = p2[3]; /* not pins -- actually "cables" */
1408                                         if ( pins > 16 )
1409                                                 pins = 16;
1410                                         u->in[iep].endpoint = p1[2];
1411                                         u->in[iep].cableId = ( 1 << pins ) - 1;
1412                                         if ( u->in[iep].cableId )
1413                                                 iep ++;
1414                                         if ( iep < 15 ) {
1415                                                 u->in[iep].endpoint = -1;
1416                                                 u->in[iep].cableId = -1;
1417                                         }
1418                                 }
1419                         } else {
1420                                 if ( oep < 15 ) {
1421                                         pins = p2[3]; /* not pins -- actually "cables" */
1422                                         if ( pins > 16 )
1423                                                 pins = 16;
1424                                         u->out[oep].endpoint = p1[2];
1425                                         u->out[oep].cableId = ( 1 << pins ) - 1;
1426                                         if ( u->out[oep].cableId )
1427                                                 oep ++;
1428                                         if ( oep < 15 ) {
1429                                                 u->out[oep].endpoint = -1;
1430                                                 u->out[oep].cableId = -1;
1431                                         }
1432                                 }
1433                         }
1434         
1435                 }
1436         } else if (quirks==1) {
1437                 /* YAMAHA quirks */
1438                 for (p1 = find_descriptor(buffer, bufSize, NULL, USB_DT_ENDPOINT,
1439                                           ifnum, altSetting ); p1; p1 = next ) {
1440                         next = find_descriptor(buffer, bufSize, p1, USB_DT_ENDPOINT,
1441                                                ifnum, altSetting ); 
1442         
1443                         if ( p1[0] < 7 )
1444                                 continue;
1445
1446                         if ( (p1[2] & 0x80) == 0x80 ) {
1447                                 if ( iep < 15 ) {
1448                                         pins = iep+1;
1449                                         if ( pins > 16 )
1450                                                 pins = 16;
1451                                         u->in[iep].endpoint = p1[2];
1452                                         u->in[iep].cableId = ( 1 << pins ) - 1;
1453                                         if ( u->in[iep].cableId )
1454                                                 iep ++;
1455                                         if ( iep < 15 ) {
1456                                                 u->in[iep].endpoint = -1;
1457                                                 u->in[iep].cableId = -1;
1458                                         }
1459                                 }
1460                         } else {
1461                                 if ( oep < 15 ) {
1462                                         pins = oep+1;
1463                                         if ( pins > 16 )
1464                                                 pins = 16;
1465                                         u->out[oep].endpoint = p1[2];
1466                                         u->out[oep].cableId = ( 1 << pins ) - 1;
1467                                         if ( u->out[oep].cableId )
1468                                                 oep ++;
1469                                         if ( oep < 15 ) {
1470                                                 u->out[oep].endpoint = -1;
1471                                                 u->out[oep].cableId = -1;
1472                                         }
1473                                 }
1474                         }
1475         
1476                 }
1477         }
1478
1479         if ( !iep && ! oep ) {
1480                 goto error_end;
1481         }
1482
1483         return u;
1484
1485 error_end:
1486         kfree(u);
1487         return NULL;
1488 }
1489
1490 /* ------------------------------------------------------------------------- */
1491
1492 /** Returns number between 0 and 16.
1493  *
1494  **/
1495 static int on_bits( unsigned short v )
1496 {
1497         int i;
1498         int ret=0;
1499
1500         for ( i=0 ; i<16 ; i++ ) {
1501                 if ( v & (1<<i) )
1502                         ret++;
1503         }
1504
1505         return ret;
1506 }
1507
1508
1509 /** USB-device will be interrogated for altSetting.
1510  *
1511  * Returns negative on error.
1512  * Called by allocUsbMidiDev();
1513  *
1514  **/
1515
1516 static int get_alt_setting( struct usb_device *d, int ifnum )
1517 {
1518         int alts, alt=0;
1519         struct usb_interface *iface;
1520         struct usb_host_interface *interface;
1521         struct usb_endpoint_descriptor *ep;
1522         int epin, epout;
1523         int i;
1524
1525         iface = usb_ifnum_to_if( d, ifnum );
1526         alts = iface->num_altsetting;
1527
1528         for ( alt=0 ; alt<alts ; alt++ ) {
1529                 interface = &iface->altsetting[alt];
1530                 epin = -1;
1531                 epout = -1;
1532
1533                 for ( i=0 ; i<interface->desc.bNumEndpoints ; i++ ) {
1534                         ep = &interface->endpoint[i].desc;
1535                         if ( (ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK ) {
1536                                 continue;
1537                         }
1538                         if ( (ep->bEndpointAddress & USB_DIR_IN) && epin < 0 ) {
1539                                 epin = i;
1540                         } else if ( epout < 0 ) {
1541                                 epout = i;
1542                         }
1543                         if ( epin >= 0 && epout >= 0 ) {
1544                                 return interface->desc.bAlternateSetting;
1545                         }
1546                 }
1547         }
1548
1549         return -ENODEV;
1550 }
1551
1552
1553 /* ------------------------------------------------------------------------- */
1554
1555
1556 /** Returns 0 if successful in allocating and registering internal structures.
1557  * Returns negative on failure.
1558  * Calls allocMidiDev which additionally registers /dev/midiXX devices.
1559  * Writes messages on success to indicate which /dev/midiXX is which physical
1560  * endpoint.
1561  *
1562  **/
1563 static int alloc_usb_midi_device( struct usb_device *d, struct usb_midi_state *s, struct usb_midi_device *u )
1564 {
1565         struct usb_mididev **mdevs=NULL;
1566         struct midi_in_endpoint *mins[15], *min;
1567         struct midi_out_endpoint *mouts[15], *mout;
1568         int inDevs=0, outDevs=0;
1569         int inEndpoints=0, outEndpoints=0;
1570         int inEndpoint, outEndpoint;
1571         int inCableId, outCableId;
1572         int i;
1573         int devices = 0;
1574         int alt = 0;
1575
1576         /* Obtain altSetting or die.. */
1577         alt = u->altSetting;
1578         if ( alt < 0 ) {
1579                 alt = get_alt_setting( d, u->interface );
1580         }
1581         if ( alt < 0 )
1582                 return -ENXIO;
1583
1584         /* Configure interface */
1585         if ( usb_set_interface( d, u->interface, alt ) < 0 ) {
1586                 return -ENXIO;
1587         }
1588
1589         for ( i = 0 ; i < 15 ; i++ ) {
1590                 mins[i] = NULL;
1591                 mouts[i] = NULL;
1592         }
1593
1594         /* Begin Allocation */
1595         while( inEndpoints < 15
1596                && inDevs < maxdevices
1597                && u->in[inEndpoints].cableId >= 0 ) {
1598                 inDevs += on_bits((unsigned short)u->in[inEndpoints].cableId);
1599                 mins[inEndpoints] = alloc_midi_in_endpoint( d, u->in[inEndpoints].endpoint );
1600                 if ( mins[inEndpoints] == NULL )
1601                         goto error_end;
1602                 inEndpoints++;
1603         }
1604
1605         while( outEndpoints < 15
1606                && outDevs < maxdevices
1607                && u->out[outEndpoints].cableId >= 0 ) {
1608                 outDevs += on_bits((unsigned short)u->out[outEndpoints].cableId);
1609                 mouts[outEndpoints] = alloc_midi_out_endpoint( d, u->out[outEndpoints].endpoint );
1610                 if ( mouts[outEndpoints] == NULL )
1611                         goto error_end;
1612                 outEndpoints++;
1613         }
1614
1615         devices = inDevs > outDevs ? inDevs : outDevs;
1616         devices = maxdevices > devices ? devices : maxdevices;
1617
1618         /* obtain space for device name (iProduct) if not known. */
1619         if ( ! u->deviceName ) {
1620                 mdevs = (struct usb_mididev **)
1621                         kmalloc(sizeof(struct usb_mididevs *)*devices
1622                                 + sizeof(char) * 256, GFP_KERNEL);
1623         } else {
1624                 mdevs = (struct usb_mididev **)
1625                         kmalloc(sizeof(struct usb_mididevs *)*devices, GFP_KERNEL);
1626         }
1627
1628         if ( !mdevs ) {
1629                 /* devices = 0; */
1630                 /* mdevs = NULL; */
1631                 goto error_end;
1632         }
1633         for ( i=0 ; i<devices ; i++ ) {
1634                 mdevs[i] = NULL;
1635         }
1636
1637         /* obtain device name (iProduct) if not known. */
1638         if ( ! u->deviceName ) {
1639                 u->deviceName = (char *) (mdevs + devices);
1640                 if ( ! d->have_langid && d->descriptor.iProduct) {
1641                         alt = usb_get_string(d, 0, 0, u->deviceName, 250);
1642                         if (alt < 0) {
1643                                 printk(KERN_INFO "error getting string descriptor 0 (error=%d)\n", alt);
1644                         } else if (u->deviceName[0] < 4) {
1645                                 printk(KERN_INFO "string descriptor 0 too short (length = %d)\n", alt);
1646                         } else {
1647                                 printk(KERN_INFO "string descriptor 0 found (length = %d)\n", alt);
1648                                 for(; alt >= 4; alt -= 2) {
1649                                         i = u->deviceName[alt-2] | (u->deviceName[alt-1]<< 8);
1650                                         printk(KERN_INFO "usb-midi: langid(%d) 0x%04x\n",
1651                                                (alt-4) >> 1, i);
1652                                         if ( ( ( i ^ ulangid ) & 0xff ) == 0 ) {
1653                                                 d->have_langid = 1;
1654                                                 d->string_langid = i;
1655                                                 printk(KERN_INFO "usb-midi: langid(match) 0x%04x\n", i);
1656                                                 if ( i == ulangid )
1657                                                         break;
1658                                         }
1659                                 }
1660                         }
1661                 }
1662                 u->deviceName[0] = (char) 0;
1663                 if (d->descriptor.iProduct) {
1664                         printk(KERN_INFO "usb-midi: fetchString(%d)\n", d->descriptor.iProduct);
1665                         alt = usb_string(d, d->descriptor.iProduct, u->deviceName, 255);
1666                         if( alt < 0 ) {
1667                                 u->deviceName[0] = (char) 0;
1668                         }
1669                         printk(KERN_INFO "usb-midi: fetchString = %d\n", alt);
1670                 } 
1671                 /* Failsafe */
1672                 if ( !u->deviceName[0] ) {
1673                         if ( d->descriptor.idVendor == USB_VENDOR_ID_ROLAND ) {
1674                                 strcpy(u->deviceName, "Unknown Roland");
1675                         } else if ( d->descriptor.idVendor == USB_VENDOR_ID_STEINBERG  ) {
1676                                 strcpy(u->deviceName, "Unknown Steinberg");
1677                         } else if ( d->descriptor.idVendor == USB_VENDOR_ID_YAMAHA ) {
1678                                 strcpy(u->deviceName, "Unknown Yamaha");
1679                         } else {
1680                                 strcpy(u->deviceName, "Unknown");
1681                         }
1682                 }
1683         }
1684
1685         inEndpoint  = 0; inCableId  = -1;
1686         outEndpoint = 0; outCableId = -1;
1687
1688         for ( i=0 ; i<devices ; i++ ) {
1689                 for ( inCableId ++ ;
1690                       inEndpoint <15
1691                               && mins[inEndpoint] 
1692                               && !(u->in[inEndpoint].cableId & (1<<inCableId)) ;
1693                       inCableId++ ) {
1694                         if ( inCableId >= 16 ) {
1695                                 inEndpoint  ++;
1696                                 inCableId  = 0;
1697                         }
1698                 }
1699                 min  = mins[inEndpoint];
1700                 for ( outCableId ++ ;
1701                       outEndpoint <15
1702                               && mouts[outEndpoint] 
1703                               && !(u->out[outEndpoint].cableId & (1<<outCableId)) ;
1704                       outCableId++ ) {
1705                         if ( outCableId >= 16 ) {
1706                                 outEndpoint  ++;
1707                                 outCableId  = 0;
1708                         }
1709                 }
1710                 mout = mouts[outEndpoint];
1711
1712                 mdevs[i] = allocMidiDev( s, min, mout, inCableId, outCableId );
1713                 if ( mdevs[i] == NULL )
1714                         goto error_end;
1715
1716         }
1717
1718         /* Success! */
1719         for ( i=0 ; i<devices ; i++ ) {
1720                 list_add_tail( &mdevs[i]->list, &s->midiDevList );
1721         }
1722         for ( i=0 ; i<inEndpoints ; i++ ) {
1723                 list_add_tail( &mins[i]->list, &s->inEndpointList );
1724         }
1725         for ( i=0 ; i<outEndpoints ; i++ ) {
1726                 list_add_tail( &mouts[i]->list, &s->outEndpointList );
1727         }
1728
1729         printk(KERN_INFO "usbmidi: found [ %s ] (0x%04x:0x%04x), attached:\n", u->deviceName, u->idVendor, u->idProduct );
1730         for ( i=0 ; i<devices ; i++ ) {
1731                 int dm = (mdevs[i]->dev_midi-2)>>4;
1732                 if ( mdevs[i]->mout.ep != NULL && mdevs[i]->min.ep != NULL ) {
1733                         printk(KERN_INFO "usbmidi: /dev/midi%02d: in (ep:%02x cid:%2d bufsiz:%2d) out (ep:%02x cid:%2d bufsiz:%2d)\n", 
1734                                dm,
1735                                mdevs[i]->min.ep->endpoint|USB_DIR_IN, mdevs[i]->min.cableId, mdevs[i]->min.ep->recvBufSize,
1736                                mdevs[i]->mout.ep->endpoint, mdevs[i]->mout.cableId, mdevs[i]->mout.ep->bufSize);
1737                 } else if ( mdevs[i]->min.ep != NULL ) {
1738                         printk(KERN_INFO "usbmidi: /dev/midi%02d: in (ep:%02x cid:%2d bufsiz:%02d)\n", 
1739                                dm,
1740                                mdevs[i]->min.ep->endpoint|USB_DIR_IN, mdevs[i]->min.cableId, mdevs[i]->min.ep->recvBufSize);
1741                 } else if ( mdevs[i]->mout.ep != NULL ) {
1742                         printk(KERN_INFO "usbmidi: /dev/midi%02d: out (ep:%02x cid:%2d bufsiz:%02d)\n", 
1743                                dm,
1744                                mdevs[i]->mout.ep->endpoint, mdevs[i]->mout.cableId, mdevs[i]->mout.ep->bufSize);
1745                 }
1746         }
1747
1748         kfree(mdevs);
1749         return 0;
1750
1751  error_end:
1752         if ( mdevs != NULL ) {
1753                 for ( i=0 ; i<devices ; i++ ) {
1754                         if ( mdevs[i] != NULL ) {
1755                                 unregister_sound_midi( mdevs[i]->dev_midi );
1756                                 kfree(mdevs[i]);
1757                         }
1758                 }
1759                 kfree(mdevs);
1760         }
1761
1762         for ( i=0 ; i<15 ; i++ ) {
1763                 if ( mins[i] != NULL ) {
1764                         remove_midi_in_endpoint( mins[i] );
1765                 }
1766                 if ( mouts[i] != NULL ) {
1767                         remove_midi_out_endpoint( mouts[i] );
1768                 }
1769         }
1770
1771         return -ENOMEM;
1772 }
1773
1774 /* ------------------------------------------------------------------------- */
1775
1776 /** Attempt to scan YAMAHA's device descriptor and detect correct values of
1777  *  them.
1778  *  Return 0 on succes, negative on failure.
1779  *  Called by usb_midi_probe();
1780  **/
1781
1782 static int detect_yamaha_device( struct usb_device *d,
1783                 struct usb_interface *iface, unsigned int ifnum,
1784                 struct usb_midi_state *s)
1785 {
1786         struct usb_host_interface *interface;
1787         struct usb_midi_device *u;
1788         unsigned char *buffer;
1789         int bufSize;
1790         int i;
1791         int alts=-1;
1792         int ret;
1793
1794         if (d->descriptor.idVendor != USB_VENDOR_ID_YAMAHA) {
1795                 return -EINVAL;
1796         }
1797
1798         for ( i=0 ; i < iface->num_altsetting; i++ ) {
1799                 interface = iface->altsetting + i;
1800
1801                 if ( interface->desc.bInterfaceClass != 255 ||
1802                      interface->desc.bInterfaceSubClass != 0 )
1803                         continue;
1804                 alts = interface->desc.bAlternateSetting;
1805         }
1806         if ( alts == -1 ) {
1807                 return -EINVAL;
1808         }
1809
1810         printk(KERN_INFO "usb-midi: Found YAMAHA USB-MIDI device on dev %04x:%04x, iface %d\n",
1811                d->descriptor.idVendor, d->descriptor.idProduct, ifnum);
1812
1813         i = d->actconfig - d->config;
1814         buffer = d->rawdescriptors[i];
1815         bufSize = d->actconfig->desc.wTotalLength;
1816
1817         u = parse_descriptor( d, buffer, bufSize, ifnum, alts, 1);
1818         if ( u == NULL ) {
1819                 return -EINVAL;
1820         }
1821
1822         ret = alloc_usb_midi_device( d, s, u );
1823
1824         kfree(u);
1825
1826         return ret;
1827 }
1828
1829
1830 /** Scan table of known devices which are only partially compliant with 
1831  * the MIDIStreaming specification.
1832  * Called by usb_midi_probe();
1833  *
1834  **/
1835
1836 static int detect_vendor_specific_device( struct usb_device *d, unsigned int ifnum, struct usb_midi_state *s )
1837 {
1838         struct usb_midi_device *u;
1839         int i;
1840         int ret = -ENXIO;
1841
1842         for ( i=0; i<VENDOR_SPECIFIC_USB_MIDI_DEVICES ; i++ ) {
1843                 u=&(usb_midi_devices[i]);
1844     
1845                 if ( d->descriptor.idVendor != u->idVendor ||
1846                      d->descriptor.idProduct != u->idProduct ||
1847                      ifnum != u->interface )
1848                         continue;
1849
1850                 ret = alloc_usb_midi_device( d, s, u );
1851                 break;
1852         }
1853
1854         return ret;
1855 }
1856
1857
1858 /** Attempt to match any config of an interface to a MIDISTREAMING interface.
1859  *  Returns 0 on success, negative on failure.
1860  * Called by usb_midi_probe();
1861  **/
1862 static int detect_midi_subclass(struct usb_device *d,
1863                 struct usb_interface *iface, unsigned int ifnum,
1864                 struct usb_midi_state *s)
1865 {
1866         struct usb_host_interface *interface;
1867         struct usb_midi_device *u;
1868         unsigned char *buffer;
1869         int bufSize;
1870         int i;
1871         int alts=-1;
1872         int ret;
1873
1874         for ( i=0 ; i < iface->num_altsetting; i++ ) {
1875                 interface = iface->altsetting + i;
1876
1877                 if ( interface->desc.bInterfaceClass != USB_CLASS_AUDIO ||
1878                      interface->desc.bInterfaceSubClass != USB_SUBCLASS_MIDISTREAMING )
1879                         continue;
1880                 alts = interface->desc.bAlternateSetting;
1881         }
1882         if ( alts == -1 ) {
1883                 return -EINVAL;
1884         }
1885
1886         printk(KERN_INFO "usb-midi: Found MIDISTREAMING on dev %04x:%04x, iface %d\n",
1887                d->descriptor.idVendor, d->descriptor.idProduct, ifnum);
1888
1889
1890         /* From USB Spec v2.0, Section 9.5.
1891            If the class or vendor specific descriptors use the same format
1892            as standard descriptors (e.g., start with a length byte and
1893            followed by a type byte), they must be returned interleaved with
1894            standard descriptors in the configuration information returned by
1895            a GetDescriptor(Configuration) request. In this case, the class
1896            or vendor-specific descriptors must follow a related standard
1897            descriptor they modify or extend.
1898         */
1899
1900         i = d->actconfig - d->config;
1901         buffer = d->rawdescriptors[i];
1902         bufSize = d->actconfig->desc.wTotalLength;
1903
1904         u = parse_descriptor( d, buffer, bufSize, ifnum, alts, 0);
1905         if ( u == NULL ) {
1906                 return -EINVAL;
1907         }
1908
1909         ret = alloc_usb_midi_device( d, s, u );
1910
1911         kfree(u);
1912
1913         return ret;
1914 }
1915
1916
1917 /** When user has requested a specific device, match it exactly.
1918  *
1919  * Uses uvendor, uproduct, uinterface, ualt, umin, umout and ucable.
1920  * Called by usb_midi_probe();
1921  *
1922  **/
1923 static int detect_by_hand(struct usb_device *d, unsigned int ifnum, struct usb_midi_state *s)
1924 {
1925         struct usb_midi_device u;
1926
1927         if ( d->descriptor.idVendor != uvendor ||
1928              d->descriptor.idProduct != uproduct ||
1929              ifnum != uinterface ) {
1930                 return -EINVAL;
1931         }
1932
1933         if ( ualt < 0 )
1934                 ualt = -1;
1935
1936         if ( umin   < 0 || umin   > 15 )
1937                 umin   = 0x01 | USB_DIR_IN;
1938         if ( umout  < 0 || umout  > 15 )
1939                 umout  = 0x01;
1940         if ( ucable < 0 || ucable > 15 )
1941                 ucable = 0;
1942
1943         u.deviceName = 0; /* A flag for alloc_usb_midi_device to get device name
1944                              from device. */
1945         u.idVendor   = uvendor;
1946         u.idProduct  = uproduct;
1947         u.interface  = uinterface;
1948         u.altSetting = ualt;
1949
1950         u.in[0].endpoint    = umin;
1951         u.in[0].cableId     = (1<<ucable);
1952
1953         u.out[0].endpoint   = umout;
1954         u.out[0].cableId    = (1<<ucable);
1955
1956         return alloc_usb_midi_device( d, s, &u );
1957 }
1958
1959
1960
1961 /* ------------------------------------------------------------------------- */
1962
1963 static int usb_midi_probe(struct usb_interface *intf, 
1964                           const struct usb_device_id *id)
1965 {
1966         struct usb_midi_state *s;
1967         struct usb_device *dev = interface_to_usbdev(intf);
1968         int ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
1969
1970         s = (struct usb_midi_state *)kmalloc(sizeof(struct usb_midi_state), GFP_KERNEL);
1971         if ( !s )
1972                 return -ENOMEM;
1973
1974         memset( s, 0, sizeof(struct usb_midi_state) );
1975         INIT_LIST_HEAD(&s->midiDevList);
1976         INIT_LIST_HEAD(&s->inEndpointList);
1977         INIT_LIST_HEAD(&s->outEndpointList);
1978         s->usbdev = dev;
1979         s->count  = 0;
1980         spin_lock_init(&s->lock);
1981
1982         if (
1983                 detect_by_hand( dev, ifnum, s ) &&
1984                 detect_midi_subclass( dev, intf, ifnum, s ) &&
1985                 detect_vendor_specific_device( dev, ifnum, s ) &&
1986                 detect_yamaha_device( dev, intf, ifnum, s) ) {
1987                 kfree(s);
1988                 return -EIO;
1989         }
1990
1991         down(&open_sem);
1992         list_add_tail(&s->mididev, &mididevs);
1993         up(&open_sem);
1994
1995         usb_set_intfdata (intf, s);
1996         return 0;
1997 }
1998
1999
2000 static void usb_midi_disconnect(struct usb_interface *intf)
2001 {
2002         struct usb_midi_state *s = usb_get_intfdata (intf);
2003         struct list_head      *list;
2004         struct usb_mididev    *m;
2005
2006         if ( !s )
2007                 return;
2008
2009         if ( s == (struct usb_midi_state *)-1 ) {
2010                 return;
2011         }
2012         if ( !s->usbdev ) {
2013                 return;
2014         }
2015         down(&open_sem);
2016         list_del(&s->mididev);
2017         INIT_LIST_HEAD(&s->mididev);
2018         s->usbdev = NULL;
2019         usb_set_intfdata (intf, NULL);
2020
2021         for ( list = s->midiDevList.next; list != &s->midiDevList; list = list->next ) {
2022                 m = list_entry(list, struct usb_mididev, list);
2023                 wake_up(&(m->min.ep->wait));
2024                 wake_up(&(m->mout.ep->wait));
2025                 if ( m->dev_midi >= 0 ) {
2026                         unregister_sound_midi(m->dev_midi);
2027                 }
2028                 m->dev_midi = -1;
2029         }
2030         release_midi_device(s);
2031         wake_up(&open_wait);
2032 }
2033
2034 /* we want to look at all devices by hand */
2035 static struct usb_device_id id_table[] = {
2036         {.driver_info = 42},
2037         {}
2038 };
2039
2040 static struct usb_driver usb_midi_driver = {
2041         .owner =        THIS_MODULE,
2042         .name =         "midi",
2043         .probe =        usb_midi_probe,
2044         .disconnect =   usb_midi_disconnect,
2045         .id_table =     id_table,
2046 };
2047
2048 /* ------------------------------------------------------------------------- */
2049
2050 static int __init usb_midi_init(void)
2051 {
2052         return usb_register(&usb_midi_driver);
2053 }
2054
2055 static void __exit usb_midi_exit(void)
2056 {
2057         usb_deregister(&usb_midi_driver);
2058 }
2059
2060 module_init(usb_midi_init) ;
2061 module_exit(usb_midi_exit) ;
2062
2063 #ifdef HAVE_ALSA_SUPPORT
2064 #define SNDRV_MAIN_OBJECT_FILE
2065 #include "../../include/driver.h"
2066 #include "../../include/control.h"
2067 #include "../../include/info.h"
2068 #include "../../include/cs46xx.h"
2069
2070 /* ------------------------------------------------------------------------- */
2071
2072 static int snd_usbmidi_input_close(snd_rawmidi_substream_t * substream)
2073 {
2074         return 0;
2075 }
2076
2077 static int snd_usbmidi_input_open(snd_rawmidi_substream_t * substream )
2078 {
2079         return 0;
2080 }
2081
2082 static void snd_usbmidi_input_trigger(snd_rawmidi_substream_t * substream, int up)
2083 {
2084         return 0;
2085 }
2086
2087
2088 /* ------------------------------------------------------------------------- */
2089
2090 static int snd_usbmidi_output_close(snd_rawmidi_substream_t * substream)
2091 {
2092         return 0;
2093 }
2094
2095 static int snd_usbmidi_output_open(snd_rawmidi_substream_t * substream)
2096 {
2097         return 0;
2098 }
2099
2100 static void snd_usb_midi_output_trigger(snd_rawmidi_substream_t * substream,
2101                                         int up)
2102 {
2103         return 0;
2104 }
2105
2106 /* ------------------------------------------------------------------------- */
2107
2108 static snd_rawmidi_ops_t snd_usbmidi_output =
2109 {
2110         .open =         snd_usbmidi_output_open,
2111         .close =        snd_usbmidi_output_close,
2112         .trigger =      snd_usbmidi_output_trigger,
2113 };
2114 static snd_rawmidi_ops_t snd_usbmidi_input =
2115 {
2116         .open =         snd_usbmidi_input_open,
2117         .close =        snd_usbmidi_input_close,
2118         .trigger =      snd_usbmidi_input_trigger,
2119 };
2120
2121 int snd_usbmidi_midi(cs46xx_t *chip, int device, snd_rawmidi_t **rrawmidi)
2122 {
2123         snd_rawmidi_t *rmidi;
2124         int err;
2125
2126         if (rrawmidi)
2127                 *rrawmidi = NULL;
2128         if ((err = snd_rawmidi_new(chip->card, "USB-MIDI", device, 1, 1, &rmidi)) < 0)
2129                 return err;
2130         strcpy(rmidi->name, "USB-MIDI");
2131
2132         snd_rawmidi_set_ops( rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_usbmidi_output );
2133         snd_rawmidi_set_ops( rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_usbmidi_input );
2134
2135         rmidi->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT | SNDRV_RAWMIDI_INFO_INPUT | SNDRV_RAWMIDI_INFO_DUPLEX;
2136
2137         rmidi->private_data = chip;
2138         chip->rmidi = rmidi;
2139         if (rrawmidi)
2140                 *rrawmidi = NULL;
2141
2142         return 0;
2143 }
2144
2145 int snd_usbmidi_create( snd_card_t * card,
2146                         struct pci_dev * pci,
2147                         usbmidi_t ** rchip )
2148 {
2149         usbmidi_t *chip;
2150         int err, idx;
2151         snd_region_t *region;
2152         static snd_device_opt_t ops = {
2153                 .dev_free = snd_usbmidi_dev_free,
2154         };
2155
2156         *rchip = NULL;
2157         chip = snd_magic_kcalloc( usbmidi_t, 0, GFP_KERNEL );
2158         if ( chip == NULL )
2159                 return -ENOMEM;
2160 }
2161
2162 EXPORT_SYMBOL(snd_usbmidi_create);
2163 EXPORT_SYMBOL(snd_usbmidi_midi);
2164 #endif /* HAVE_ALSA_SUPPORT */
2165