v2.4.10.4 -> v2.4.10.5
[opensuse:kernel.git] / drivers / usb / audio.c
1 /*****************************************************************************/
2
3 /*
4  *      audio.c  --  USB Audio Class driver
5  *
6  *      Copyright (C) 1999, 2000, 2001
7  *          Alan Cox (alan@lxorguk.ukuu.org.uk)
8  *          Thomas Sailer (sailer@ife.ee.ethz.ch)
9  *
10  *      This program is free software; you can redistribute it and/or modify
11  *      it under the terms of the GNU General Public License as published by
12  *      the Free Software Foundation; either version 2 of the License, or
13  *      (at your option) any later version.
14  *
15  * Debugging:
16  *      Use the 'lsusb' utility to dump the descriptors.
17  *
18  * 1999-09-07:  Alan Cox
19  *              Parsing Audio descriptor patch
20  * 1999-09-08:  Thomas Sailer
21  *              Added OSS compatible data io functions; both parts of the
22  *              driver remain to be glued together
23  * 1999-09-10:  Thomas Sailer
24  *              Beautified the driver. Added sample format conversions.
25  *              Still not properly glued with the parsing code.
26  *              The parsing code seems to have its problems btw,
27  *              Since it parses all available configs but doesn't
28  *              store which iface/altsetting belongs to which config.
29  * 1999-09-20:  Thomas Sailer
30  *              Threw out Alan's parsing code and implemented my own one.
31  *              You cannot reasonnably linearly parse audio descriptors,
32  *              especially the AudioClass descriptors have to be considered
33  *              pointer lists. Mixer parsing untested, due to lack of device.
34  *              First stab at synch pipe implementation, the Dallas USB DAC
35  *              wants to use an Asynch out pipe. usb_audio_state now basically
36  *              only contains lists of mixer and wave devices. We can therefore
37  *              now have multiple mixer/wave devices per USB device.
38  * 1999-10-28:  Thomas Sailer
39  *              Converted to URB API. Fixed a taskstate/wakeup semantics mistake
40  *              that made the driver consume all available CPU cycles.
41  *              Now runs stable on UHCI-Acher/Fliegl/Sailer.
42  * 1999-10-31:  Thomas Sailer
43  *              Audio can now be unloaded if it is not in use by any mixer
44  *              or dsp client (formerly you had to disconnect the audio devices
45  *              from the USB port)
46  *              Finally, about three months after ordering, my "Maxxtro SPK222"
47  *              speakers arrived, isn't disdata a great mail order company 8-)
48  *              Parse class specific endpoint descriptor of the audiostreaming
49  *              interfaces and take the endpoint attributes from there.
50  *              Unbelievably, the Philips USB DAC has a sampling rate range
51  *              of over a decade, yet does not support the sampling rate control!
52  *              No wonder it sounds so bad, has very audible sampling rate
53  *              conversion distortion. Don't try to listen to it using
54  *              decent headphones!
55  *              "Let's make things better" -> but please Philips start with your
56  *              own stuff!!!!
57  * 1999-11-02:  Thomas Sailer
58  *              It takes the Philips boxes several seconds to acquire synchronisation
59  *              that means they won't play short sounds. Should probably maintain
60  *              the ISO datastream even if there's nothing to play.
61  *              Fix counting the total_bytes counter, RealPlayer G2 depends on it.
62  * 1999-12-20:  Thomas Sailer
63  *              Fix bad bug in conversion to per interface probing.
64  *              disconnect was called multiple times for the audio device,
65  *              leading to a premature freeing of the audio structures
66  * 2000-05-13:  Thomas Sailer
67  *              I don't remember who changed the find_format routine,
68  *              but the change was completely broken for the Dallas
69  *              chip. Anyway taking sampling rate into account in find_format
70  *              is bad and should not be done unless there are devices with
71  *              completely broken audio descriptors. Unless someone shows
72  *              me such a descriptor, I will not allow find_format to
73  *              take the sampling rate into account.
74  *              Also, the former find_format made:
75  *              - mpg123 play mono instead of stereo
76  *              - sox completely fail for wav's with sample rates < 44.1kHz
77  *                  for the Dallas chip.
78  *              Also fix a rather long standing problem with applications that
79  *              use "small" writes producing no sound at all.
80  * 2000-05-15:  Thomas Sailer
81  *              My fears came true, the Philips camera indeed has pretty stupid
82  *              audio descriptors.
83  * 2000-05-17:  Thomas Sailer
84  *              Nemsoft spotted my stupid last minute change, thanks
85  * 2000-05-19:  Thomas Sailer
86  *              Fixed FEATURE_UNIT thinkos found thanks to the KC Technology
87  *              Xtend device. Basically the driver treated FEATURE_UNIT's sourced
88  *              by mono terminals as stereo.
89  * 2000-05-20:  Thomas Sailer
90  *              SELECTOR support (and thus selecting record channels from the mixer).
91  *              Somewhat peculiar due to OSS interface limitations. Only works
92  *              for channels where a "slider" is already in front of it (i.e.
93  *              a MIXER unit or a FEATURE unit with volume capability).
94  * 2000-11-26:  Thomas Sailer
95  *              Workaround for Dallas DS4201. The DS4201 uses PCM8 as format tag for
96  *              its 8 bit modes, but expects signed data (and should therefore have used PCM).
97  * 2001-03-10:  Thomas Sailer
98  *              provide abs function, prevent picking up a bogus kernel macro
99  *              for abs. Bug report by Andrew Morton <andrewm@uow.edu.au>
100  * 2001-06-16:  Bryce Nesbitt <bryce@obviously.com>
101  *              Fix SNDCTL_DSP_STEREO API violation
102  */
103
104 /*
105  * Strategy:
106  *
107  * Alan Cox and Thomas Sailer are starting to dig at opposite ends and
108  * are hoping to meet in the middle, just like tunnel diggers :)
109  * Alan tackles the descriptor parsing, Thomas the actual data IO and the
110  * OSS compatible interface.
111  *
112  * Data IO implementation issues
113  *
114  * A mmap'able ring buffer per direction is implemented, because
115  * almost every OSS app expects it. It is however impractical to
116  * transmit/receive USB data directly into and out of the ring buffer,
117  * due to alignment and synchronisation issues. Instead, the ring buffer
118  * feeds a constant time delay line that handles the USB issues.
119  *
120  * Now we first try to find an alternate setting that exactly matches
121  * the sample format requested by the user. If we find one, we do not
122  * need to perform any sample rate conversions. If there is no matching
123  * altsetting, we choose the closest one and perform sample format
124  * conversions. We never do sample rate conversion; these are too
125  * expensive to be performed in the kernel.
126  *
127  * Current status:
128  * - Pretty stable on UHCI-Acher/Fliegl/Sailer
129  * - Does not work on OHCI due to lack of OHCI driver supporting URB's
130  *
131  * Generally: Due to the brokenness of the Audio Class spec
132  * it seems generally impossible to write a generic Audio Class driver,
133  * so a reasonable driver should implement the features that are actually
134  * used.
135  *
136  * Parsing implementation issues
137  *
138  * One cannot reasonably parse the AudioClass descriptors linearly.
139  * Therefore the current implementation features routines to look
140  * for a specific descriptor in the descriptor list.
141  *
142  * How does the parsing work? First, all interfaces are searched
143  * for an AudioControl class interface. If found, the config descriptor
144  * that belongs to the current configuration is fetched from the device.
145  * Then the HEADER descriptor is fetched. It contains a list of
146  * all AudioStreaming and MIDIStreaming devices. This list is then walked,
147  * and all AudioStreaming interfaces are classified into input and output
148  * interfaces (according to the endpoint0 direction in altsetting1) (MIDIStreaming
149  * is currently not supported). The input & output list is then used
150  * to group inputs and outputs together and issued pairwise to the
151  * AudioStreaming class parser. Finally, all OUTPUT_TERMINAL descriptors
152  * are walked and issued to the mixer construction routine.
153  *
154  * The AudioStreaming parser simply enumerates all altsettings belonging
155  * to the specified interface. It looks for AS_GENERAL and FORMAT_TYPE
156  * class specific descriptors to extract the sample format/sample rate
157  * data. Only sample format types PCM and PCM8 are supported right now, and
158  * only FORMAT_TYPE_I is handled. The isochronous data endpoint needs to
159  * be the first endpoint of the interface, and the optional synchronisation
160  * isochronous endpoint the second one.
161  *
162  * Mixer construction works as follows: The various TERMINAL and UNIT
163  * descriptors span a tree from the root (OUTPUT_TERMINAL) through the
164  * intermediate nodes (UNITs) to the leaves (INPUT_TERMINAL). We walk
165  * that tree in a depth first manner. FEATURE_UNITs may contribute volume,
166  * bass and treble sliders to the mixer, MIXER_UNITs volume sliders.
167  * The terminal type encoded in the INPUT_TERMINALs feeds a heuristic
168  * to determine "meaningful" OSS slider numbers, however we will see
169  * how well this works in practice. Other features are not used at the
170  * moment, they seem less often used. Also, it seems difficult at least
171  * to construct recording source switches from SELECTOR_UNITs, but
172  * since there are not many USB ADC's available, we leave that for later.
173  */
174
175 /*****************************************************************************/
176
177 #include <linux/version.h>
178 #include <linux/kernel.h>
179 #include <linux/slab.h>
180 #include <linux/string.h>
181 #include <linux/timer.h>
182 #include <linux/sched.h>
183 #include <linux/smp_lock.h>
184 #include <linux/module.h>
185 #include <linux/sound.h>
186 #include <linux/soundcard.h>
187 #include <linux/list.h>
188 #include <linux/vmalloc.h>
189 #include <linux/wrapper.h>
190 #include <linux/init.h>
191 #include <linux/poll.h>
192 #include <linux/bitops.h>
193 #include <asm/uaccess.h>
194 #include <asm/io.h>
195 #include <linux/usb.h>
196
197 #include "audio.h"
198
199 /*
200  * Version Information
201  */
202 #define DRIVER_VERSION "v1.0.0"
203 #define DRIVER_AUTHOR "Alan Cox <alan@lxorguk.ukuu.org.uk>, Thomas Sailer (sailer@ife.ee.ethz.ch)"
204 #define DRIVER_DESC "USB Audio Class driver"
205
206 #define AUDIO_DEBUG 1
207
208 #define SND_DEV_DSP16   5 
209
210 #define dprintk(x)
211
212 #undef abs
213 extern int abs(int __x) __attribute__ ((__const__)); /* Shut up warning */
214
215 /* --------------------------------------------------------------------- */
216
217 /*
218  * Linked list of all audio devices...
219  */
220 static struct list_head audiodevs = LIST_HEAD_INIT(audiodevs);
221 static DECLARE_MUTEX(open_sem);
222
223 /*
224  * wait queue for processes wanting to open an USB audio device
225  */
226 static DECLARE_WAIT_QUEUE_HEAD(open_wait);
227
228
229 #define MAXFORMATS        MAX_ALT
230 #define DMABUFSHIFT       17  /* 128k worth of DMA buffer */
231 #define NRSGBUF           (1U<<(DMABUFSHIFT-PAGE_SHIFT))
232
233 /*
234  * This influences:
235  * - Latency
236  * - Interrupt rate
237  * - Synchronisation behaviour
238  * Don't touch this if you don't understand all of the above.
239  */
240 #define DESCFRAMES  5
241 #define SYNCFRAMES  DESCFRAMES
242
243 #define MIXFLG_STEREOIN   1
244 #define MIXFLG_STEREOOUT  2
245
246 struct mixerchannel {
247         __u16 value;
248         __u16 osschannel;  /* number of the OSS channel */
249         __s16 minval, maxval;
250         __u16 slctunitid;
251         __u8 unitid;
252         __u8 selector;
253         __u8 chnum;
254         __u8 flags;
255 };
256
257 struct audioformat {
258         unsigned int format;
259         unsigned int sratelo;
260         unsigned int sratehi;
261         unsigned char altsetting;
262         unsigned char attributes;
263 };
264
265 struct dmabuf {
266         /* buffer data format */
267         unsigned int format;
268         unsigned int srate;
269         /* physical buffer */
270         unsigned char *sgbuf[NRSGBUF];
271         unsigned bufsize;
272         unsigned numfrag;
273         unsigned fragshift;
274         unsigned wrptr, rdptr;
275         unsigned total_bytes;
276         int count;
277         unsigned error; /* over/underrun */
278         wait_queue_head_t wait;
279         /* redundant, but makes calculations easier */
280         unsigned fragsize;
281         unsigned dmasize;
282         /* OSS stuff */
283         unsigned mapped:1;
284         unsigned ready:1;
285         unsigned ossfragshift;
286         int ossmaxfrags;
287         unsigned subdivision;
288 };
289
290 struct usb_audio_state;
291
292 #define FLG_URB0RUNNING   1
293 #define FLG_URB1RUNNING   2
294 #define FLG_SYNC0RUNNING  4
295 #define FLG_SYNC1RUNNING  8
296 #define FLG_RUNNING      16
297 #define FLG_CONNECTED    32
298
299 struct my_data_urb {
300         urb_t urb;
301         iso_packet_descriptor_t isoframe[DESCFRAMES];
302 };
303
304 struct my_sync_urb {
305         urb_t urb;
306         iso_packet_descriptor_t isoframe[SYNCFRAMES];
307 };
308
309
310 struct usb_audiodev {
311         struct list_head list;
312         struct usb_audio_state *state;
313         
314         /* soundcore stuff */
315         int dev_audio;
316
317         /* wave stuff */
318         mode_t open_mode;
319         spinlock_t lock;         /* DMA buffer access spinlock */
320
321         struct usbin {
322                 int interface;           /* Interface number, -1 means not used */
323                 unsigned int format;     /* USB data format */
324                 unsigned int datapipe;   /* the data input pipe */
325                 unsigned int syncpipe;   /* the synchronisation pipe - 0 for anything but adaptive IN mode */
326                 unsigned int syncinterval;  /* P for adaptive IN mode, 0 otherwise */
327                 unsigned int freqn;      /* nominal sampling rate in USB format, i.e. fs/1000 in Q10.14 */
328                 unsigned int freqmax;    /* maximum sampling rate, used for buffer management */
329                 unsigned int phase;      /* phase accumulator */
330                 unsigned int flags;      /* see FLG_ defines */
331                 
332                 struct my_data_urb durb[2];  /* ISO descriptors for the data endpoint */
333                 struct my_sync_urb surb[2];  /* ISO sync pipe descriptor if needed */
334                 
335                 struct dmabuf dma;
336         } usbin;
337
338         struct usbout {
339                 int interface;           /* Interface number, -1 means not used */
340                 unsigned int format;     /* USB data format */
341                 unsigned int datapipe;   /* the data input pipe */
342                 unsigned int syncpipe;   /* the synchronisation pipe - 0 for anything but asynchronous OUT mode */
343                 unsigned int syncinterval;  /* P for asynchronous OUT mode, 0 otherwise */
344                 unsigned int freqn;      /* nominal sampling rate in USB format, i.e. fs/1000 in Q10.14 */
345                 unsigned int freqm;      /* momentary sampling rate in USB format, i.e. fs/1000 in Q10.14 */
346                 unsigned int freqmax;    /* maximum sampling rate, used for buffer management */
347                 unsigned int phase;      /* phase accumulator */
348                 unsigned int flags;      /* see FLG_ defines */
349
350                 struct my_data_urb durb[2];  /* ISO descriptors for the data endpoint */
351                 struct my_sync_urb surb[2];  /* ISO sync pipe descriptor if needed */
352                 
353                 struct dmabuf dma;
354         } usbout;
355
356
357         unsigned int numfmtin, numfmtout;
358         struct audioformat fmtin[MAXFORMATS];
359         struct audioformat fmtout[MAXFORMATS];
360 };  
361
362 struct usb_mixerdev {
363         struct list_head list;
364         struct usb_audio_state *state;
365
366         /* soundcore stuff */
367         int dev_mixer;
368
369         unsigned char iface;  /* interface number of the AudioControl interface */
370
371         /* USB format descriptions */
372         unsigned int numch, modcnt;
373
374         /* mixch is last and gets allocated dynamically */
375         struct mixerchannel ch[0];
376 };
377
378 struct usb_audio_state {
379         struct list_head audiodev;
380
381         /* USB device */
382         struct usb_device *usbdev;
383
384         struct list_head audiolist;
385         struct list_head mixerlist;
386
387         unsigned count;  /* usage counter; NOTE: the usb stack is also considered a user */
388 };
389
390 /* private audio format extensions */
391 #define AFMT_STEREO        0x80000000
392 #define AFMT_ISSTEREO(x)   ((x) & AFMT_STEREO)
393 #define AFMT_IS16BIT(x)    ((x) & (AFMT_S16_LE|AFMT_S16_BE|AFMT_U16_LE|AFMT_U16_BE))
394 #define AFMT_ISUNSIGNED(x) ((x) & (AFMT_U8|AFMT_U16_LE|AFMT_U16_BE))
395 #define AFMT_BYTESSHIFT(x) ((AFMT_ISSTEREO(x) ? 1 : 0) + (AFMT_IS16BIT(x) ? 1 : 0))
396 #define AFMT_BYTES(x)      (1<<AFMT_BYTESSHFIT(x))
397
398 /* --------------------------------------------------------------------- */
399
400 /* prevent picking up a bogus abs macro */
401 #undef abs
402 extern inline int abs(int x)
403 {
404         if (x < 0)
405                 return -x;
406         return x;
407 }
408                                 
409 /* --------------------------------------------------------------------- */
410
411 extern inline unsigned ld2(unsigned int x)
412 {
413         unsigned r = 0;
414         
415         if (x >= 0x10000) {
416                 x >>= 16;
417                 r += 16;
418         }
419         if (x >= 0x100) {
420                 x >>= 8;
421                 r += 8;
422         }
423         if (x >= 0x10) {
424                 x >>= 4;
425                 r += 4;
426         }
427         if (x >= 4) {
428                 x >>= 2;
429                 r += 2;
430         }
431         if (x >= 2)
432                 r++;
433         return r;
434 }
435
436 /* --------------------------------------------------------------------- */
437
438 /*
439  * OSS compatible ring buffer management. The ring buffer may be mmap'ed into
440  * an application address space.
441  *
442  * I first used the rvmalloc stuff copied from bttv. Alan Cox did not like it, so
443  * we now use an array of pointers to a single page each. This saves us the
444  * kernel page table manipulations, but we have to do a page table alike mechanism
445  * (though only one indirection) in software.
446  */
447
448 static void dmabuf_release(struct dmabuf *db)
449 {
450         unsigned int nr;
451         void *p;
452
453         for(nr = 0; nr < NRSGBUF; nr++) {
454                 if (!(p = db->sgbuf[nr]))
455                         continue;
456                 mem_map_unreserve(virt_to_page(p));
457                 free_page((unsigned long)p);
458                 db->sgbuf[nr] = NULL;
459         }
460         db->mapped = db->ready = 0;
461 }
462
463 static int dmabuf_init(struct dmabuf *db)
464 {
465         unsigned int nr, bytepersec, bufs;
466         void *p;
467
468         /* initialize some fields */
469         db->rdptr = db->wrptr = db->total_bytes = db->count = db->error = 0;
470         /* calculate required buffer size */
471         bytepersec = db->srate << AFMT_BYTESSHIFT(db->format);
472         bufs = 1U << DMABUFSHIFT;
473         if (db->ossfragshift) {
474                 if ((1000 << db->ossfragshift) < bytepersec)
475                         db->fragshift = ld2(bytepersec/1000);
476                 else
477                         db->fragshift = db->ossfragshift;
478         } else {
479                 db->fragshift = ld2(bytepersec/100/(db->subdivision ? db->subdivision : 1));
480                 if (db->fragshift < 3)
481                         db->fragshift = 3;
482         }
483         db->numfrag = bufs >> db->fragshift;
484         while (db->numfrag < 4 && db->fragshift > 3) {
485                 db->fragshift--;
486                 db->numfrag = bufs >> db->fragshift;
487         }
488         db->fragsize = 1 << db->fragshift;
489         if (db->ossmaxfrags >= 4 && db->ossmaxfrags < db->numfrag)
490                 db->numfrag = db->ossmaxfrags;
491         db->dmasize = db->numfrag << db->fragshift;
492         for(nr = 0; nr < NRSGBUF; nr++) {
493                 if (!db->sgbuf[nr]) {
494                         p = (void *)get_free_page(GFP_KERNEL);
495                         if (!p)
496                                 return -ENOMEM;
497                         db->sgbuf[nr] = p;
498                         mem_map_reserve(virt_to_page(p));
499                 }
500                 memset(db->sgbuf[nr], AFMT_ISUNSIGNED(db->format) ? 0x80 : 0, PAGE_SIZE);
501                 if ((nr << PAGE_SHIFT) >= db->dmasize)
502                         break;
503         }
504         db->bufsize = nr << PAGE_SHIFT;
505         db->ready = 1;
506         dprintk((KERN_DEBUG "usbaudio: dmabuf_init bytepersec %d bufs %d ossfragshift %d ossmaxfrags %d "
507                  "fragshift %d fragsize %d numfrag %d dmasize %d bufsize %d fmt 0x%x srate %d\n",
508                  bytepersec, bufs, db->ossfragshift, db->ossmaxfrags, db->fragshift, db->fragsize,
509                  db->numfrag, db->dmasize, db->bufsize, db->format, db->srate));
510         return 0;
511 }
512
513 static int dmabuf_mmap(struct dmabuf *db, unsigned long start, unsigned long size, pgprot_t prot)
514 {
515         unsigned int nr;
516
517         if (!db->ready || db->mapped || (start | size) & (PAGE_SIZE-1) || size > db->bufsize)
518                 return -EINVAL;
519         size >>= PAGE_SHIFT;
520         for(nr = 0; nr < size; nr++)
521                 if (!db->sgbuf[nr])
522                         return -EINVAL;
523         db->mapped = 1;
524         for(nr = 0; nr < size; nr++) {
525                 if (remap_page_range(start, virt_to_phys(db->sgbuf[nr]), PAGE_SIZE, prot))
526                         return -EAGAIN;
527                 start += PAGE_SIZE;
528         }
529         return 0;
530 }
531
532 static void dmabuf_copyin(struct dmabuf *db, const void *buffer, unsigned int size)
533 {
534         unsigned int pgrem, rem;
535
536         db->total_bytes += size;
537         for (;;) {
538                 if (size <= 0)
539                         return;
540                 pgrem = ((~db->wrptr) & (PAGE_SIZE-1)) + 1;
541                 if (pgrem > size)
542                         pgrem = size;
543                 rem = db->dmasize - db->wrptr;
544                 if (pgrem > rem)
545                         pgrem = rem;
546                 memcpy((db->sgbuf[db->wrptr >> PAGE_SHIFT]) + (db->wrptr & (PAGE_SIZE-1)), buffer, pgrem);
547                 size -= pgrem;
548                 (char *)buffer += pgrem;
549                 db->wrptr += pgrem;
550                 if (db->wrptr >= db->dmasize)
551                         db->wrptr = 0;
552         }
553 }
554
555 static void dmabuf_copyout(struct dmabuf *db, void *buffer, unsigned int size)
556 {
557         unsigned int pgrem, rem;
558
559         db->total_bytes += size;
560         for (;;) {
561                 if (size <= 0)
562                         return;
563                 pgrem = ((~db->rdptr) & (PAGE_SIZE-1)) + 1;
564                 if (pgrem > size)
565                         pgrem = size;
566                 rem = db->dmasize - db->rdptr;
567                 if (pgrem > rem)
568                         pgrem = rem;
569                 memcpy(buffer, (db->sgbuf[db->rdptr >> PAGE_SHIFT]) + (db->rdptr & (PAGE_SIZE-1)), pgrem);
570                 size -= pgrem;
571                 (char *)buffer += pgrem;
572                 db->rdptr += pgrem;
573                 if (db->rdptr >= db->dmasize)
574                         db->rdptr = 0;
575         }
576 }
577
578 static int dmabuf_copyin_user(struct dmabuf *db, unsigned int ptr, const void *buffer, unsigned int size)
579 {
580         unsigned int pgrem, rem;
581
582         if (!db->ready || db->mapped)
583                 return -EINVAL;
584         for (;;) {
585                 if (size <= 0)
586                         return 0;
587                 pgrem = ((~ptr) & (PAGE_SIZE-1)) + 1;
588                 if (pgrem > size)
589                         pgrem = size;
590                 rem = db->dmasize - ptr;
591                 if (pgrem > rem)
592                         pgrem = rem;
593                 if (copy_from_user((db->sgbuf[ptr >> PAGE_SHIFT]) + (ptr & (PAGE_SIZE-1)), buffer, pgrem))
594                         return -EFAULT;
595                 size -= pgrem;
596                 (char *)buffer += pgrem;
597                 ptr += pgrem;
598                 if (ptr >= db->dmasize)
599                         ptr = 0;
600         }
601 }
602
603 static int dmabuf_copyout_user(struct dmabuf *db, unsigned int ptr, void *buffer, unsigned int size)
604 {
605         unsigned int pgrem, rem;
606
607         if (!db->ready || db->mapped)
608                 return -EINVAL;
609         for (;;) {
610                 if (size <= 0)
611                         return 0;
612                 pgrem = ((~ptr) & (PAGE_SIZE-1)) + 1;
613                 if (pgrem > size)
614                         pgrem = size;
615                 rem = db->dmasize - ptr;
616                 if (pgrem > rem)
617                         pgrem = rem;
618                 if (copy_to_user(buffer, (db->sgbuf[ptr >> PAGE_SHIFT]) + (ptr & (PAGE_SIZE-1)), pgrem))
619                         return -EFAULT;
620                 size -= pgrem;
621                 (char *)buffer += pgrem;
622                 ptr += pgrem;
623                 if (ptr >= db->dmasize)
624                         ptr = 0;
625         }
626 }
627
628 /* --------------------------------------------------------------------- */
629 /*
630  * USB I/O code. We do sample format conversion if necessary
631  */
632
633 static void usbin_stop(struct usb_audiodev *as)
634 {
635         struct usbin *u = &as->usbin;
636         unsigned long flags;
637         unsigned int i, notkilled = 1;
638
639         spin_lock_irqsave(&as->lock, flags);
640         u->flags &= ~FLG_RUNNING;
641         i = u->flags;
642         spin_unlock_irqrestore(&as->lock, flags);
643         while (i & (FLG_URB0RUNNING|FLG_URB1RUNNING|FLG_SYNC0RUNNING|FLG_SYNC1RUNNING)) {
644                 set_current_state(notkilled ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
645                 schedule_timeout(1);
646                 spin_lock_irqsave(&as->lock, flags);
647                 i = u->flags;
648                 spin_unlock_irqrestore(&as->lock, flags);
649                 if (notkilled && signal_pending(current)) {
650                         if (i & FLG_URB0RUNNING)
651                                 usb_unlink_urb(&u->durb[0].urb);
652                         if (i & FLG_URB1RUNNING)
653                                 usb_unlink_urb(&u->durb[1].urb);
654                         if (i & FLG_SYNC0RUNNING)
655                                 usb_unlink_urb(&u->surb[0].urb);
656                         if (i & FLG_SYNC1RUNNING)
657                                 usb_unlink_urb(&u->surb[1].urb);
658                         notkilled = 0;
659                 }
660         }
661         set_current_state(TASK_RUNNING);
662         if (u->durb[0].urb.transfer_buffer)
663                 kfree(u->durb[0].urb.transfer_buffer);
664         if (u->durb[1].urb.transfer_buffer)
665                 kfree(u->durb[1].urb.transfer_buffer);
666         if (u->surb[0].urb.transfer_buffer)
667                 kfree(u->surb[0].urb.transfer_buffer);
668         if (u->surb[1].urb.transfer_buffer)
669                 kfree(u->surb[1].urb.transfer_buffer);
670         u->durb[0].urb.transfer_buffer = u->durb[1].urb.transfer_buffer = 
671                 u->surb[0].urb.transfer_buffer = u->surb[1].urb.transfer_buffer = NULL;
672 }
673
674 static inline void usbin_release(struct usb_audiodev *as)
675 {
676         usbin_stop(as);
677 }
678
679 static void usbin_disc(struct usb_audiodev *as)
680 {
681         struct usbin *u = &as->usbin;
682
683         unsigned long flags;
684
685         spin_lock_irqsave(&as->lock, flags);
686         u->flags &= ~(FLG_RUNNING | FLG_CONNECTED);
687         spin_unlock_irqrestore(&as->lock, flags);
688         usbin_stop(as);
689 }
690
691 static void conversion(const void *ibuf, unsigned int ifmt, void *obuf, unsigned int ofmt, void *tmp, unsigned int scnt)
692 {
693         unsigned int cnt, i;
694         __s16 *sp, *sp2, s;
695         unsigned char *bp;
696
697         cnt = scnt;
698         if (AFMT_ISSTEREO(ifmt))
699                 cnt <<= 1;
700         sp = ((__s16 *)tmp) + cnt;
701         switch (ifmt & ~AFMT_STEREO) {
702         case AFMT_U8:
703                 for (bp = ((unsigned char *)ibuf)+cnt, i = 0; i < cnt; i++) {
704                         bp--;
705                         sp--;
706                         *sp = (*bp ^ 0x80) << 8;
707                 }
708                 break;
709                         
710         case AFMT_S8:
711                 for (bp = ((unsigned char *)ibuf)+cnt, i = 0; i < cnt; i++) {
712                         bp--;
713                         sp--;
714                         *sp = *bp << 8;
715                 }
716                 break;
717                 
718         case AFMT_U16_LE:
719                 for (bp = ((unsigned char *)ibuf)+2*cnt, i = 0; i < cnt; i++) {
720                         bp -= 2;
721                         sp--;
722                         *sp = (bp[0] | (bp[1] << 8)) ^ 0x8000;
723                 }
724                 break;
725
726         case AFMT_U16_BE:
727                 for (bp = ((unsigned char *)ibuf)+2*cnt, i = 0; i < cnt; i++) {
728                         bp -= 2;
729                         sp--;
730                         *sp = (bp[1] | (bp[0] << 8)) ^ 0x8000;
731                 }
732                 break;
733
734         case AFMT_S16_LE:
735                 for (bp = ((unsigned char *)ibuf)+2*cnt, i = 0; i < cnt; i++) {
736                         bp -= 2;
737                         sp--;
738                         *sp = bp[0] | (bp[1] << 8);
739                 }
740                 break;
741
742         case AFMT_S16_BE:
743                 for (bp = ((unsigned char *)ibuf)+2*cnt, i = 0; i < cnt; i++) {
744                         bp -= 2;
745                         sp--;
746                         *sp = bp[1] | (bp[0] << 8);
747                 }
748                 break;
749         }
750         if (!AFMT_ISSTEREO(ifmt) && AFMT_ISSTEREO(ofmt)) {
751                 /* expand from mono to stereo */
752                 for (sp = ((__s16 *)tmp)+scnt, sp2 = ((__s16 *)tmp)+2*scnt, i = 0; i < scnt; i++) {
753                         sp--;
754                         sp2 -= 2;
755                         sp2[0] = sp2[1] = sp[0];
756                 }
757         }
758         if (AFMT_ISSTEREO(ifmt) && !AFMT_ISSTEREO(ofmt)) {
759                 /* contract from stereo to mono */
760                 for (sp = sp2 = ((__s16 *)tmp), i = 0; i < scnt; i++, sp++, sp2 += 2)
761                         sp[0] = (sp2[0] + sp2[1]) >> 1;
762         }
763         cnt = scnt;
764         if (AFMT_ISSTEREO(ofmt))
765                 cnt <<= 1;
766         sp = ((__s16 *)tmp);
767         bp = ((unsigned char *)obuf);
768         switch (ofmt & ~AFMT_STEREO) {
769         case AFMT_U8:
770                 for (i = 0; i < cnt; i++, sp++, bp++)
771                         *bp = (*sp >> 8) ^ 0x80;
772                 break;
773
774         case AFMT_S8:
775                 for (i = 0; i < cnt; i++, sp++, bp++)
776                         *bp = *sp >> 8;
777                 break;
778
779         case AFMT_U16_LE:
780                 for (i = 0; i < cnt; i++, sp++, bp += 2) {
781                         s = *sp;
782                         bp[0] = s;
783                         bp[1] = (s >> 8) ^ 0x80;
784                 }
785                 break;
786
787         case AFMT_U16_BE:
788                 for (i = 0; i < cnt; i++, sp++, bp += 2) {
789                         s = *sp;
790                         bp[1] = s;
791                         bp[0] = (s >> 8) ^ 0x80;
792                 }
793                 break;
794
795         case AFMT_S16_LE:
796                 for (i = 0; i < cnt; i++, sp++, bp += 2) {
797                         s = *sp;
798                         bp[0] = s;
799                         bp[1] = s >> 8;
800                 }
801                 break;
802
803         case AFMT_S16_BE:
804                 for (i = 0; i < cnt; i++, sp++, bp += 2) {
805                         s = *sp;
806                         bp[1] = s;
807                         bp[0] = s >> 8;
808                 }
809                 break;
810         }
811         
812 }
813
814 static void usbin_convert(struct usbin *u, unsigned char *buffer, unsigned int samples)
815 {
816         union {
817                 __s16 s[64];
818                 unsigned char b[0];
819         } tmp;
820         unsigned int scnt, maxs, ufmtsh, dfmtsh;
821
822         ufmtsh = AFMT_BYTESSHIFT(u->format);
823         dfmtsh = AFMT_BYTESSHIFT(u->dma.format);
824         maxs = (AFMT_ISSTEREO(u->dma.format | u->format)) ? 32 : 64;
825         while (samples > 0) {
826                 scnt = samples;
827                 if (scnt > maxs)
828                         scnt = maxs;
829                 conversion(buffer, u->format, tmp.b, u->dma.format, tmp.b, scnt);
830                 dmabuf_copyin(&u->dma, tmp.b, scnt << dfmtsh);
831                 buffer += scnt << ufmtsh;
832                 samples -= scnt;
833         }
834 }               
835
836 static int usbin_prepare_desc(struct usbin *u, purb_t urb)
837 {
838         unsigned int i, maxsize, offs;
839
840         maxsize = (u->freqmax + 0x3fff) >> (14 - AFMT_BYTESSHIFT(u->format));
841         //printk(KERN_DEBUG "usbin_prepare_desc: maxsize %d freq 0x%x format 0x%x\n", maxsize, u->freqn, u->format);
842         for (i = offs = 0; i < DESCFRAMES; i++, offs += maxsize) {
843                 urb->iso_frame_desc[i].length = maxsize;
844                 urb->iso_frame_desc[i].offset = offs;
845         }
846         return 0;
847 }
848
849 /*
850  * return value: 0 if descriptor should be restarted, -1 otherwise
851  * convert sample format on the fly if necessary
852  */
853 static int usbin_retire_desc(struct usbin *u, purb_t urb)
854 {
855         unsigned int i, ufmtsh, dfmtsh, err = 0, cnt, scnt, dmafree;
856         unsigned char *cp;
857
858         ufmtsh = AFMT_BYTESSHIFT(u->format);
859         dfmtsh = AFMT_BYTESSHIFT(u->dma.format);
860         for (i = 0; i < DESCFRAMES; i++) {
861                 cp = ((unsigned char *)urb->transfer_buffer) + urb->iso_frame_desc[i].offset;
862                 if (urb->iso_frame_desc[i].status) {
863                         dprintk((KERN_DEBUG "usbin_retire_desc: frame %u status %d\n", i, urb->iso_frame_desc[i].status));
864                         continue;
865                 }
866                 scnt = urb->iso_frame_desc[i].actual_length >> ufmtsh;
867                 if (!scnt)
868                         continue;
869                 cnt = scnt << dfmtsh;
870                 if (!u->dma.mapped) {
871                         dmafree = u->dma.dmasize - u->dma.count;
872                         if (cnt > dmafree) {
873                                 scnt = dmafree >> dfmtsh;
874                                 cnt = scnt << dfmtsh;
875                                 err++;
876                         }
877                 }
878                 u->dma.count += cnt;
879                 if (u->format == u->dma.format) {
880                         /* we do not need format conversion */
881                         dprintk((KERN_DEBUG "usbaudio: no sample format conversion\n"));
882                         dmabuf_copyin(&u->dma, cp, cnt);
883                 } else {
884                         /* we need sampling format conversion */
885                         dprintk((KERN_DEBUG "usbaudio: sample format conversion %x != %x\n", u->format, u->dma.format));
886                         usbin_convert(u, cp, scnt);
887                 }
888         }
889         if (err)
890                 u->dma.error++;
891         if (u->dma.count >= (signed)u->dma.fragsize)
892                 wake_up(&u->dma.wait);
893         return err ? -1 : 0;
894 }
895
896 static void usbin_completed(struct urb *urb)
897 {
898         struct usb_audiodev *as = (struct usb_audiodev *)urb->context;
899         struct usbin *u = &as->usbin;
900         unsigned long flags;
901         unsigned int mask;
902         int suret = USB_ST_NOERROR;
903
904 #if 0
905         printk(KERN_DEBUG "usbin_completed: status %d errcnt %d flags 0x%x\n", urb->status, urb->error_count, u->flags);
906 #endif
907         if (urb == &u->durb[0].urb)
908                 mask = FLG_URB0RUNNING;
909         else if (urb == &u->durb[1].urb)
910                 mask = FLG_URB1RUNNING;
911         else {
912                 mask = 0;
913                 printk(KERN_ERR "usbin_completed: panic: unknown URB\n");
914         }
915         urb->dev = as->state->usbdev;
916         spin_lock_irqsave(&as->lock, flags);
917         if (!usbin_retire_desc(u, urb) &&
918             u->flags & FLG_RUNNING &&
919             !usbin_prepare_desc(u, urb) && 
920             (suret = usb_submit_urb(urb)) == USB_ST_NOERROR) {
921                 u->flags |= mask;
922         } else {
923                 u->flags &= ~(mask | FLG_RUNNING);
924                 wake_up(&u->dma.wait);
925                 printk(KERN_DEBUG "usbin_completed: descriptor not restarted (usb_submit_urb: %d)\n", suret);
926         }
927         spin_unlock_irqrestore(&as->lock, flags);
928 }
929
930 /*
931  * we output sync data
932  */
933 static int usbin_sync_prepare_desc(struct usbin *u, purb_t urb)
934 {
935         unsigned char *cp = urb->transfer_buffer;
936         unsigned int i, offs;
937         
938         for (i = offs = 0; i < SYNCFRAMES; i++, offs += 3, cp += 3) {
939                 urb->iso_frame_desc[i].length = 3;
940                 urb->iso_frame_desc[i].offset = offs;
941                 cp[0] = u->freqn;
942                 cp[1] = u->freqn >> 8;
943                 cp[2] = u->freqn >> 16;
944         }
945         return 0;
946 }
947
948 /*
949  * return value: 0 if descriptor should be restarted, -1 otherwise
950  */
951 static int usbin_sync_retire_desc(struct usbin *u, purb_t urb)
952 {
953         unsigned int i;
954         
955         for (i = 0; i < SYNCFRAMES; i++)
956                 if (urb->iso_frame_desc[0].status)
957                         dprintk((KERN_DEBUG "usbin_sync_retire_desc: frame %u status %d\n", i, urb->iso_frame_desc[i].status));
958         return 0;
959 }
960
961 static void usbin_sync_completed(struct urb *urb)
962 {
963         struct usb_audiodev *as = (struct usb_audiodev *)urb->context;
964         struct usbin *u = &as->usbin;
965         unsigned long flags;
966         unsigned int mask;
967         int suret = USB_ST_NOERROR;
968
969 #if 0
970         printk(KERN_DEBUG "usbin_sync_completed: status %d errcnt %d flags 0x%x\n", urb->status, urb->error_count, u->flags);
971 #endif
972         if (urb == &u->surb[0].urb)
973                 mask = FLG_SYNC0RUNNING;
974         else if (urb == &u->surb[1].urb)
975                 mask = FLG_SYNC1RUNNING;
976         else {
977                 mask = 0;
978                 printk(KERN_ERR "usbin_sync_completed: panic: unknown URB\n");
979         }
980         urb->dev = as->state->usbdev;
981         spin_lock_irqsave(&as->lock, flags);
982         if (!usbin_sync_retire_desc(u, urb) &&
983             u->flags & FLG_RUNNING &&
984             !usbin_sync_prepare_desc(u, urb) && 
985             (suret = usb_submit_urb(urb)) == USB_ST_NOERROR) {
986                 u->flags |= mask;
987         } else {
988                 u->flags &= ~(mask | FLG_RUNNING);
989                 wake_up(&u->dma.wait);
990                 dprintk((KERN_DEBUG "usbin_sync_completed: descriptor not restarted (usb_submit_urb: %d)\n", suret));
991         }
992         spin_unlock_irqrestore(&as->lock, flags);
993 }
994
995 static int usbin_start(struct usb_audiodev *as)
996 {
997         struct usb_device *dev = as->state->usbdev;
998         struct usbin *u = &as->usbin;
999         purb_t urb;
1000         unsigned long flags;
1001         unsigned int maxsze, bufsz;
1002
1003 #if 0
1004         printk(KERN_DEBUG "usbin_start: device %d ufmt 0x%08x dfmt 0x%08x srate %d\n",
1005                dev->devnum, u->format, u->dma.format, u->dma.srate);
1006 #endif
1007         /* allocate USB storage if not already done */
1008         spin_lock_irqsave(&as->lock, flags);
1009         if (!(u->flags & FLG_CONNECTED)) {
1010                 spin_unlock_irqrestore(&as->lock, flags);
1011                 return -EIO;
1012         }
1013         if (!(u->flags & FLG_RUNNING)) {
1014                 spin_unlock_irqrestore(&as->lock, flags);
1015                 u->freqn = ((u->dma.srate << 11) + 62) / 125; /* this will overflow at approx 2MSPS */
1016                 u->freqmax = u->freqn + (u->freqn >> 2);
1017                 u->phase = 0;
1018                 maxsze = (u->freqmax + 0x3fff) >> (14 - AFMT_BYTESSHIFT(u->format));
1019                 bufsz = DESCFRAMES * maxsze;
1020                 if (u->durb[0].urb.transfer_buffer)
1021                         kfree(u->durb[0].urb.transfer_buffer);
1022                 u->durb[0].urb.transfer_buffer = kmalloc(bufsz, GFP_KERNEL);
1023                 u->durb[0].urb.transfer_buffer_length = bufsz;
1024                 if (u->durb[1].urb.transfer_buffer)
1025                         kfree(u->durb[1].urb.transfer_buffer);
1026                 u->durb[1].urb.transfer_buffer = kmalloc(bufsz, GFP_KERNEL);
1027                 u->durb[1].urb.transfer_buffer_length = bufsz;
1028                 if (u->syncpipe) {
1029                         if (u->surb[0].urb.transfer_buffer)
1030                                 kfree(u->surb[0].urb.transfer_buffer);
1031                         u->surb[0].urb.transfer_buffer = kmalloc(3*SYNCFRAMES, GFP_KERNEL);
1032                         u->surb[0].urb.transfer_buffer_length = 3*SYNCFRAMES;
1033                         if (u->surb[1].urb.transfer_buffer)
1034                                 kfree(u->surb[1].urb.transfer_buffer);
1035                         u->surb[1].urb.transfer_buffer = kmalloc(3*SYNCFRAMES, GFP_KERNEL);
1036                         u->surb[1].urb.transfer_buffer_length = 3*SYNCFRAMES;
1037                 }
1038                 if (!u->durb[0].urb.transfer_buffer || !u->durb[1].urb.transfer_buffer || 
1039                     (u->syncpipe && (!u->surb[0].urb.transfer_buffer || !u->surb[1].urb.transfer_buffer))) {
1040                         printk(KERN_ERR "usbaudio: cannot start playback device %d\n", dev->devnum);
1041                         return 0;
1042                 }
1043                 spin_lock_irqsave(&as->lock, flags);
1044         }
1045         if (u->dma.count >= u->dma.dmasize && !u->dma.mapped) {
1046                 spin_unlock_irqrestore(&as->lock, flags);
1047                 return 0;
1048         }
1049         u->flags |= FLG_RUNNING;
1050         if (!(u->flags & FLG_URB0RUNNING)) {
1051                 urb = &u->durb[0].urb;
1052                 urb->dev = dev;
1053                 urb->pipe = u->datapipe;
1054                 urb->transfer_flags = USB_ISO_ASAP;
1055                 urb->number_of_packets = DESCFRAMES;
1056                 urb->context = as;
1057                 urb->complete = usbin_completed;
1058                 if (!usbin_prepare_desc(u, urb) && !usb_submit_urb(urb))
1059                         u->flags |= FLG_URB0RUNNING;
1060                 else
1061                         u->flags &= ~FLG_RUNNING;
1062         }
1063         if (u->flags & FLG_RUNNING && !(u->flags & FLG_URB1RUNNING)) {
1064                 urb = &u->durb[1].urb;
1065                 urb->dev = dev;
1066                 urb->pipe = u->datapipe;
1067                 urb->transfer_flags = USB_ISO_ASAP;
1068                 urb->number_of_packets = DESCFRAMES;
1069                 urb->context = as;
1070                 urb->complete = usbin_completed;
1071                 if (!usbin_prepare_desc(u, urb) && !usb_submit_urb(urb))
1072                         u->flags |= FLG_URB1RUNNING;
1073                 else
1074                         u->flags &= ~FLG_RUNNING;
1075         }
1076         if (u->syncpipe) {
1077                 if (u->flags & FLG_RUNNING && !(u->flags & FLG_SYNC0RUNNING)) {
1078                         urb = &u->surb[0].urb;
1079                         urb->dev = dev;
1080                         urb->pipe = u->syncpipe;
1081                         urb->transfer_flags = USB_ISO_ASAP;
1082                         urb->number_of_packets = SYNCFRAMES;
1083                         urb->context = as;
1084                         urb->complete = usbin_sync_completed;
1085                         /* stride: u->syncinterval */
1086                         if (!usbin_sync_prepare_desc(u, urb) && !usb_submit_urb(urb))
1087                                 u->flags |= FLG_SYNC0RUNNING;
1088                         else
1089                                 u->flags &= ~FLG_RUNNING;
1090                 }
1091                 if (u->flags & FLG_RUNNING && !(u->flags & FLG_SYNC1RUNNING)) {
1092                         urb = &u->surb[1].urb;
1093                         urb->dev = dev;
1094                         urb->pipe = u->syncpipe;
1095                         urb->transfer_flags = USB_ISO_ASAP;
1096                         urb->number_of_packets = SYNCFRAMES;
1097                         urb->context = as;
1098                         urb->complete = usbin_sync_completed;
1099                         /* stride: u->syncinterval */
1100                         if (!usbin_sync_prepare_desc(u, urb) && !usb_submit_urb(urb))
1101                                 u->flags |= FLG_SYNC1RUNNING;
1102                         else
1103                                 u->flags &= ~FLG_RUNNING;
1104                 }
1105         }
1106         spin_unlock_irqrestore(&as->lock, flags);
1107         return 0;
1108 }
1109
1110 static void usbout_stop(struct usb_audiodev *as)
1111 {
1112         struct usbout *u = &as->usbout;
1113         unsigned long flags;
1114         unsigned int i, notkilled = 1;
1115
1116         spin_lock_irqsave(&as->lock, flags);
1117         u->flags &= ~FLG_RUNNING;
1118         i = u->flags;
1119         spin_unlock_irqrestore(&as->lock, flags);
1120         while (i & (FLG_URB0RUNNING|FLG_URB1RUNNING|FLG_SYNC0RUNNING|FLG_SYNC1RUNNING)) {
1121                 set_current_state(notkilled ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
1122                 schedule_timeout(1);
1123                 spin_lock_irqsave(&as->lock, flags);
1124                 i = u->flags;
1125                 spin_unlock_irqrestore(&as->lock, flags);
1126                 if (notkilled && signal_pending(current)) {
1127                         if (i & FLG_URB0RUNNING)
1128                                 usb_unlink_urb(&u->durb[0].urb);
1129                         if (i & FLG_URB1RUNNING)
1130                                 usb_unlink_urb(&u->durb[1].urb);
1131                         if (i & FLG_SYNC0RUNNING)
1132                                 usb_unlink_urb(&u->surb[0].urb);
1133                         if (i & FLG_SYNC1RUNNING)
1134                                 usb_unlink_urb(&u->surb[1].urb);
1135                         notkilled = 0;
1136                 }
1137         }
1138         set_current_state(TASK_RUNNING);
1139         if (u->durb[0].urb.transfer_buffer)
1140                 kfree(u->durb[0].urb.transfer_buffer);
1141         if (u->durb[1].urb.transfer_buffer)
1142                 kfree(u->durb[1].urb.transfer_buffer);
1143         if (u->surb[0].urb.transfer_buffer)
1144                 kfree(u->surb[0].urb.transfer_buffer);
1145         if (u->surb[1].urb.transfer_buffer)
1146                 kfree(u->surb[1].urb.transfer_buffer);
1147         u->durb[0].urb.transfer_buffer = u->durb[1].urb.transfer_buffer = 
1148                 u->surb[0].urb.transfer_buffer = u->surb[1].urb.transfer_buffer = NULL;
1149 }
1150
1151 static inline void usbout_release(struct usb_audiodev *as)
1152 {
1153         usbout_stop(as);
1154 }
1155
1156 static void usbout_disc(struct usb_audiodev *as)
1157 {
1158         struct usbout *u = &as->usbout;
1159         unsigned long flags;
1160
1161         spin_lock_irqsave(&as->lock, flags);
1162         u->flags &= ~(FLG_RUNNING | FLG_CONNECTED);
1163         spin_unlock_irqrestore(&as->lock, flags);
1164         usbout_stop(as);
1165 }
1166
1167 static void usbout_convert(struct usbout *u, unsigned char *buffer, unsigned int samples)
1168 {
1169         union {
1170                 __s16 s[64];
1171                 unsigned char b[0];
1172         } tmp;
1173         unsigned int scnt, maxs, ufmtsh, dfmtsh;
1174
1175         ufmtsh = AFMT_BYTESSHIFT(u->format);
1176         dfmtsh = AFMT_BYTESSHIFT(u->dma.format);
1177         maxs = (AFMT_ISSTEREO(u->dma.format | u->format)) ? 32 : 64;
1178         while (samples > 0) {
1179                 scnt = samples;
1180                 if (scnt > maxs)
1181                         scnt = maxs;
1182                 dmabuf_copyout(&u->dma, tmp.b, scnt << dfmtsh);
1183                 conversion(tmp.b, u->dma.format, buffer, u->format, tmp.b, scnt);
1184                 buffer += scnt << ufmtsh;
1185                 samples -= scnt;
1186         }
1187 }               
1188
1189 static int usbout_prepare_desc(struct usbout *u, purb_t urb)
1190 {
1191         unsigned int i, ufmtsh, dfmtsh, err = 0, cnt, scnt, offs;
1192         unsigned char *cp = urb->transfer_buffer;
1193
1194         ufmtsh = AFMT_BYTESSHIFT(u->format);
1195         dfmtsh = AFMT_BYTESSHIFT(u->dma.format);
1196         for (i = offs = 0; i < DESCFRAMES; i++) {
1197                 urb->iso_frame_desc[i].offset = offs;
1198                 u->phase = (u->phase & 0x3fff) + u->freqm;
1199                 scnt = u->phase >> 14;
1200                 if (!scnt) {
1201                         urb->iso_frame_desc[i].length = 0;
1202                         continue;
1203                 }
1204                 cnt = scnt << dfmtsh;
1205                 if (!u->dma.mapped) {
1206                         if (cnt > u->dma.count) {
1207                                 scnt = u->dma.count >> dfmtsh;
1208                                 cnt = scnt << dfmtsh;
1209                                 err++;
1210                         }
1211                         u->dma.count -= cnt;
1212                 } else
1213                         u->dma.count += cnt;
1214                 if (u->format == u->dma.format) {
1215                         /* we do not need format conversion */
1216                         dmabuf_copyout(&u->dma, cp, cnt);
1217                 } else {
1218                         /* we need sampling format conversion */
1219                         usbout_convert(u, cp, scnt);
1220                 }
1221                 cnt = scnt << ufmtsh;
1222                 urb->iso_frame_desc[i].length = cnt;
1223                 offs += cnt;
1224                 cp += cnt;
1225         }
1226         if (err)
1227                 u->dma.error++;
1228         if (u->dma.mapped) {
1229                 if (u->dma.count >= (signed)u->dma.fragsize)
1230                         wake_up(&u->dma.wait);
1231         } else {
1232                 if ((signed)u->dma.dmasize >= u->dma.count + (signed)u->dma.fragsize)
1233                         wake_up(&u->dma.wait);
1234         }
1235         return err ? -1 : 0;
1236 }
1237
1238 /*
1239  * return value: 0 if descriptor should be restarted, -1 otherwise
1240  */
1241 static int usbout_retire_desc(struct usbout *u, purb_t urb)
1242 {
1243         unsigned int i;
1244
1245         for (i = 0; i < DESCFRAMES; i++) {
1246                 if (urb->iso_frame_desc[i].status) {
1247                         dprintk((KERN_DEBUG "usbout_retire_desc: frame %u status %d\n", i, urb->iso_frame_desc[i].status));
1248                         continue;
1249                 }
1250         }
1251         return 0;
1252 }
1253
1254 static void usbout_completed(struct urb *urb)
1255 {
1256         struct usb_audiodev *as = (struct usb_audiodev *)urb->context;
1257         struct usbout *u = &as->usbout;
1258         unsigned long flags;
1259         unsigned int mask;
1260         int suret = USB_ST_NOERROR;
1261
1262 #if 0
1263         printk(KERN_DEBUG "usbout_completed: status %d errcnt %d flags 0x%x\n", urb->status, urb->error_count, u->flags);
1264 #endif
1265         if (urb == &u->durb[0].urb)
1266                 mask = FLG_URB0RUNNING;
1267         else if (urb == &u->durb[1].urb)
1268                 mask = FLG_URB1RUNNING;
1269         else {
1270                 mask = 0;
1271                 printk(KERN_ERR "usbout_completed: panic: unknown URB\n");
1272         }
1273         urb->dev = as->state->usbdev;
1274         spin_lock_irqsave(&as->lock, flags);
1275         if (!usbout_retire_desc(u, urb) &&
1276             u->flags & FLG_RUNNING &&
1277             !usbout_prepare_desc(u, urb) && 
1278             (suret = usb_submit_urb(urb)) == USB_ST_NOERROR) {
1279                 u->flags |= mask;
1280         } else {
1281                 u->flags &= ~(mask | FLG_RUNNING);
1282                 wake_up(&u->dma.wait);
1283                 dprintk((KERN_DEBUG "usbout_completed: descriptor not restarted (usb_submit_urb: %d)\n", suret));
1284         }
1285         spin_unlock_irqrestore(&as->lock, flags);
1286 }
1287
1288 static int usbout_sync_prepare_desc(struct usbout *u, purb_t urb)
1289 {
1290         unsigned int i, offs;
1291
1292         for (i = offs = 0; i < SYNCFRAMES; i++, offs += 3) {
1293                 urb->iso_frame_desc[i].length = 3;
1294                 urb->iso_frame_desc[i].offset = offs;
1295         }
1296         return 0;
1297 }
1298
1299 /*
1300  * return value: 0 if descriptor should be restarted, -1 otherwise
1301  */
1302 static int usbout_sync_retire_desc(struct usbout *u, purb_t urb)
1303 {
1304         unsigned char *cp = urb->transfer_buffer;
1305         unsigned int f, i;
1306
1307         for (i = 0; i < SYNCFRAMES; i++, cp += 3) {
1308                 if (urb->iso_frame_desc[i].status) {
1309                         dprintk((KERN_DEBUG "usbout_sync_retire_desc: frame %u status %d\n", i, urb->iso_frame_desc[i].status));
1310                         continue;
1311                 }
1312                 if (urb->iso_frame_desc[i].actual_length < 3) {
1313                         dprintk((KERN_DEBUG "usbout_sync_retire_desc: frame %u length %d\n", i, urb->iso_frame_desc[i].actual_length));
1314                         continue;
1315                 }
1316                 f = cp[0] | (cp[1] << 8) | (cp[2] << 16);
1317                 if (abs(f - u->freqn) > (u->freqn >> 3) || f > u->freqmax) {
1318                         printk(KERN_WARNING "usbout_sync_retire_desc: requested frequency %u (nominal %u) out of range!\n", f, u->freqn);
1319                         continue;
1320                 }
1321                 u->freqm = f;
1322         }
1323         return 0;
1324 }
1325
1326 static void usbout_sync_completed(struct urb *urb)
1327 {
1328         struct usb_audiodev *as = (struct usb_audiodev *)urb->context;
1329         struct usbout *u = &as->usbout;
1330         unsigned long flags;
1331         unsigned int mask;
1332         int suret = USB_ST_NOERROR;
1333
1334 #if 0
1335         printk(KERN_DEBUG "usbout_sync_completed: status %d errcnt %d flags 0x%x\n", urb->status, urb->error_count, u->flags);
1336 #endif
1337         if (urb == &u->surb[0].urb)
1338                 mask = FLG_SYNC0RUNNING;
1339         else if (urb == &u->surb[1].urb)
1340                 mask = FLG_SYNC1RUNNING;
1341         else {
1342                 mask = 0;
1343                 printk(KERN_ERR "usbout_sync_completed: panic: unknown URB\n");
1344         }
1345         urb->dev = as->state->usbdev;
1346         spin_lock_irqsave(&as->lock, flags);
1347         if (!usbout_sync_retire_desc(u, urb) &&
1348             u->flags & FLG_RUNNING &&
1349             !usbout_sync_prepare_desc(u, urb) && 
1350             (suret = usb_submit_urb(urb)) == USB_ST_NOERROR) {
1351                 u->flags |= mask;
1352         } else {
1353                 u->flags &= ~(mask | FLG_RUNNING);
1354                 wake_up(&u->dma.wait);
1355                 dprintk((KERN_DEBUG "usbout_sync_completed: descriptor not restarted (usb_submit_urb: %d)\n", suret));
1356         }
1357         spin_unlock_irqrestore(&as->lock, flags);
1358 }
1359
1360 static int usbout_start(struct usb_audiodev *as)
1361 {
1362         struct usb_device *dev = as->state->usbdev;
1363         struct usbout *u = &as->usbout;
1364         purb_t urb;
1365         unsigned long flags;
1366         unsigned int maxsze, bufsz;
1367
1368 #if 0
1369         printk(KERN_DEBUG "usbout_start: device %d ufmt 0x%08x dfmt 0x%08x srate %d\n",
1370                dev->devnum, u->format, u->dma.format, u->dma.srate);
1371 #endif
1372         /* allocate USB storage if not already done */
1373         spin_lock_irqsave(&as->lock, flags);
1374         if (!(u->flags & FLG_CONNECTED)) {
1375                 spin_unlock_irqrestore(&as->lock, flags);
1376                 return -EIO;
1377         }
1378         if (!(u->flags & FLG_RUNNING)) {
1379                 spin_unlock_irqrestore(&as->lock, flags);
1380                 u->freqn = u->freqm = ((u->dma.srate << 11) + 62) / 125; /* this will overflow at approx 2MSPS */
1381                 u->freqmax = u->freqn + (u->freqn >> 2);
1382                 u->phase = 0;
1383                 maxsze = (u->freqmax + 0x3fff) >> (14 - AFMT_BYTESSHIFT(u->format));
1384                 bufsz = DESCFRAMES * maxsze;
1385                 if (u->durb[0].urb.transfer_buffer)
1386                         kfree(u->durb[0].urb.transfer_buffer);
1387                 u->durb[0].urb.transfer_buffer = kmalloc(bufsz, GFP_KERNEL);
1388                 u->durb[0].urb.transfer_buffer_length = bufsz;
1389                 if (u->durb[1].urb.transfer_buffer)
1390                         kfree(u->durb[1].urb.transfer_buffer);
1391                 u->durb[1].urb.transfer_buffer = kmalloc(bufsz, GFP_KERNEL);
1392                 u->durb[1].urb.transfer_buffer_length = bufsz;
1393                 if (u->syncpipe) {
1394                         if (u->surb[0].urb.transfer_buffer)
1395                                 kfree(u->surb[0].urb.transfer_buffer);
1396                         u->surb[0].urb.transfer_buffer = kmalloc(3*SYNCFRAMES, GFP_KERNEL);
1397                         u->surb[0].urb.transfer_buffer_length = 3*SYNCFRAMES;
1398                         if (u->surb[1].urb.transfer_buffer)
1399                                 kfree(u->surb[1].urb.transfer_buffer);
1400                         u->surb[1].urb.transfer_buffer = kmalloc(3*SYNCFRAMES, GFP_KERNEL);
1401                         u->surb[1].urb.transfer_buffer_length = 3*SYNCFRAMES;
1402                 }
1403                 if (!u->durb[0].urb.transfer_buffer || !u->durb[1].urb.transfer_buffer || 
1404                     (u->syncpipe && (!u->surb[0].urb.transfer_buffer || !u->surb[1].urb.transfer_buffer))) {
1405                         printk(KERN_ERR "usbaudio: cannot start playback device %d\n", dev->devnum);
1406                         return 0;
1407                 }
1408                 spin_lock_irqsave(&as->lock, flags);
1409         }
1410         if (u->dma.count <= 0 && !u->dma.mapped) {
1411                 spin_unlock_irqrestore(&as->lock, flags);
1412                 return 0;
1413         }
1414         u->flags |= FLG_RUNNING;
1415         if (!(u->flags & FLG_URB0RUNNING)) {
1416                 urb = &u->durb[0].urb;
1417                 urb->dev = dev;
1418                 urb->pipe = u->datapipe;
1419                 urb->transfer_flags = USB_ISO_ASAP;
1420                 urb->number_of_packets = DESCFRAMES;
1421                 urb->context = as;
1422                 urb->complete = usbout_completed;
1423                 if (!usbout_prepare_desc(u, urb) && !usb_submit_urb(urb))
1424                         u->flags |= FLG_URB0RUNNING;
1425                 else
1426                         u->flags &= ~FLG_RUNNING;
1427         }
1428         if (u->flags & FLG_RUNNING && !(u->flags & FLG_URB1RUNNING)) {
1429                 urb = &u->durb[1].urb;
1430                 urb->dev = dev;
1431                 urb->pipe = u->datapipe;
1432                 urb->transfer_flags = USB_ISO_ASAP;
1433                 urb->number_of_packets = DESCFRAMES;
1434                 urb->context = as;
1435                 urb->complete = usbout_completed;
1436                 if (!usbout_prepare_desc(u, urb) && !usb_submit_urb(urb))
1437                         u->flags |= FLG_URB1RUNNING;
1438                 else
1439                         u->flags &= ~FLG_RUNNING;
1440         }
1441         if (u->syncpipe) {
1442                 if (u->flags & FLG_RUNNING && !(u->flags & FLG_SYNC0RUNNING)) {
1443                         urb = &u->surb[0].urb;
1444                         urb->dev = dev;
1445                         urb->pipe = u->syncpipe;
1446                         urb->transfer_flags = USB_ISO_ASAP;
1447                         urb->number_of_packets = SYNCFRAMES;
1448                         urb->context = as;
1449                         urb->complete = usbout_sync_completed;
1450                         /* stride: u->syncinterval */
1451                         if (!usbout_sync_prepare_desc(u, urb) && !usb_submit_urb(urb))
1452                                 u->flags |= FLG_SYNC0RUNNING;
1453                         else
1454                                 u->flags &= ~FLG_RUNNING;
1455                 }
1456                 if (u->flags & FLG_RUNNING && !(u->flags & FLG_SYNC1RUNNING)) {
1457                         urb = &u->surb[1].urb;
1458                         urb->dev = dev;
1459                         urb->pipe = u->syncpipe;
1460                         urb->transfer_flags = USB_ISO_ASAP;
1461                         urb->number_of_packets = SYNCFRAMES;
1462                         urb->context = as;
1463                         urb->complete = usbout_sync_completed;
1464                         /* stride: u->syncinterval */
1465                         if (!usbout_sync_prepare_desc(u, urb) && !usb_submit_urb(urb))
1466                                 u->flags |= FLG_SYNC1RUNNING;
1467                         else
1468                                 u->flags &= ~FLG_RUNNING;
1469                 }
1470         }
1471         spin_unlock_irqrestore(&as->lock, flags);
1472         return 0;
1473 }
1474
1475 /* --------------------------------------------------------------------- */
1476
1477 static unsigned int format_goodness(struct audioformat *afp, unsigned int fmt, unsigned int srate)
1478 {
1479         unsigned int g = 0;
1480
1481         if (srate < afp->sratelo)
1482                 g += afp->sratelo - srate;
1483         if (srate > afp->sratehi)
1484                 g += srate - afp->sratehi;
1485         if (AFMT_ISSTEREO(afp->format) && !AFMT_ISSTEREO(fmt))
1486                 g += 0x100000;
1487         if (!AFMT_ISSTEREO(afp->format) && AFMT_ISSTEREO(fmt))
1488                 g += 0x400000;
1489         if (AFMT_IS16BIT(afp->format) && !AFMT_IS16BIT(fmt))
1490                 g += 0x100000;
1491         if (!AFMT_IS16BIT(afp->format) && AFMT_IS16BIT(fmt))
1492                 g += 0x400000;
1493         return g;
1494 }
1495
1496 static int find_format(struct audioformat *afp, unsigned int nr, unsigned int fmt, unsigned int srate)
1497 {
1498         unsigned int i, g, gb = ~0;
1499         int j = -1; /* default to failure */
1500
1501         /* find "best" format (according to format_goodness) */
1502         for (i = 0; i < nr; i++) {
1503                 g = format_goodness(&afp[i], fmt, srate);
1504                 if (g >= gb) 
1505                         continue;
1506                 j = i;
1507                 gb = g;
1508         }
1509         return j;
1510 }
1511
1512 static int set_format_in(struct usb_audiodev *as)
1513 {
1514         struct usb_device *dev = as->state->usbdev;
1515         struct usb_config_descriptor *config = dev->actconfig;
1516         struct usb_interface_descriptor *alts;
1517         struct usb_interface *iface;
1518         struct usbin *u = &as->usbin;
1519         struct dmabuf *d = &u->dma;
1520         struct audioformat *fmt;
1521         unsigned int ep;
1522         unsigned char data[3];
1523         int fmtnr, ret;
1524
1525         if (u->interface < 0 || u->interface >= config->bNumInterfaces)
1526                 return 0;
1527         iface = &config->interface[u->interface];
1528
1529         fmtnr = find_format(as->fmtin, as->numfmtin, d->format, d->srate);
1530         if (fmtnr < 0) {
1531                 printk(KERN_ERR "usbaudio: set_format_in(): failed to find desired format/speed combination.\n");
1532                 return -1;
1533         }
1534
1535         fmt = as->fmtin + fmtnr;
1536         alts = &iface->altsetting[fmt->altsetting];
1537         u->format = fmt->format;
1538         u->datapipe = usb_rcvisocpipe(dev, alts->endpoint[0].bEndpointAddress & 0xf);
1539         u->syncpipe = u->syncinterval = 0;
1540         if ((alts->endpoint[0].bmAttributes & 0x0c) == 0x08) {
1541                 if (alts->bNumEndpoints < 2 ||
1542                     alts->endpoint[1].bmAttributes != 0x01 ||
1543                     alts->endpoint[1].bSynchAddress != 0 ||
1544                     alts->endpoint[1].bEndpointAddress != (alts->endpoint[0].bSynchAddress & 0x7f)) {
1545                         printk(KERN_ERR "usbaudio: device %d interface %d altsetting %d invalid synch pipe\n",
1546                                dev->devnum, u->interface, fmt->altsetting);
1547                         return -1;
1548                 }
1549                 u->syncpipe = usb_sndisocpipe(dev, alts->endpoint[1].bEndpointAddress & 0xf);
1550                 u->syncinterval = alts->endpoint[1].bRefresh;
1551         }
1552         if (d->srate < fmt->sratelo)
1553                 d->srate = fmt->sratelo;
1554         if (d->srate > fmt->sratehi)
1555                 d->srate = fmt->sratehi;
1556         dprintk((KERN_DEBUG "usbaudio: set_format_in: usb_set_interface %u %u\n", alts->bInterfaceNumber, fmt->altsetting));
1557         if (usb_set_interface(dev, alts->bInterfaceNumber, fmt->altsetting) < 0) {
1558                 printk(KERN_WARNING "usbaudio: usb_set_interface failed, device %d interface %d altsetting %d\n",
1559                        dev->devnum, u->interface, fmt->altsetting);
1560                 return -1;
1561         }
1562         if (fmt->sratelo == fmt->sratehi)
1563                 return 0;
1564         ep = usb_pipeendpoint(u->datapipe) | (u->datapipe & USB_DIR_IN);
1565         /* if endpoint has pitch control, enable it */
1566         if (fmt->attributes & 0x02) {
1567                 data[0] = 1;
1568                 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT, 
1569                                            PITCH_CONTROL << 8, ep, data, 1, HZ)) < 0) {
1570                         printk(KERN_ERR "usbaudio: failure (error %d) to set output pitch control device %d interface %u endpoint 0x%x to %u\n",
1571                                ret, dev->devnum, u->interface, ep, d->srate);
1572                         return -1;
1573                 }
1574         }
1575         /* if endpoint has sampling rate control, set it */
1576         if (fmt->attributes & 0x01) {
1577                 data[0] = d->srate;
1578                 data[1] = d->srate >> 8;
1579                 data[2] = d->srate >> 16;
1580                 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT, 
1581                                            SAMPLING_FREQ_CONTROL << 8, ep, data, 3, HZ)) < 0) {
1582                         printk(KERN_ERR "usbaudio: failure (error %d) to set input sampling frequency device %d interface %u endpoint 0x%x to %u\n",
1583                                ret, dev->devnum, u->interface, ep, d->srate);
1584                         return -1;
1585                 }
1586                 if ((ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), GET_CUR, USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_IN,
1587                                            SAMPLING_FREQ_CONTROL << 8, ep, data, 3, HZ)) < 0) {
1588                         printk(KERN_ERR "usbaudio: failure (error %d) to get input sampling frequency device %d interface %u endpoint 0x%x\n",
1589                                ret, dev->devnum, u->interface, ep);
1590                         return -1;
1591                 }
1592                 dprintk((KERN_DEBUG "usbaudio: set_format_in: device %d interface %d altsetting %d srate req: %u real %u\n",
1593                         dev->devnum, u->interface, fmt->altsetting, d->srate, data[0] | (data[1] << 8) | (data[2] << 16)));
1594                 d->srate = data[0] | (data[1] << 8) | (data[2] << 16);
1595         }
1596         dprintk((KERN_DEBUG "usbaudio: set_format_in: USB format 0x%x, DMA format 0x%x srate %u\n", u->format, d->format, d->srate));
1597         return 0;
1598 }
1599
1600 static int set_format_out(struct usb_audiodev *as)
1601 {
1602         struct usb_device *dev = as->state->usbdev;
1603         struct usb_config_descriptor *config = dev->actconfig;
1604         struct usb_interface_descriptor *alts;
1605         struct usb_interface *iface;    
1606         struct usbout *u = &as->usbout;
1607         struct dmabuf *d = &u->dma;
1608         struct audioformat *fmt;
1609         unsigned int ep;
1610         unsigned char data[3];
1611         int fmtnr, ret;
1612
1613         if (u->interface < 0 || u->interface >= config->bNumInterfaces)
1614                 return 0;
1615         iface = &config->interface[u->interface];
1616
1617         fmtnr = find_format(as->fmtout, as->numfmtout, d->format, d->srate);
1618         if (fmtnr < 0) {
1619                 printk(KERN_ERR "usbaudio: set_format_out(): failed to find desired format/speed combination.\n");
1620                 return -1;
1621         }
1622
1623         fmt = as->fmtout + fmtnr;
1624         u->format = fmt->format;
1625         alts = &iface->altsetting[fmt->altsetting];
1626         u->datapipe = usb_sndisocpipe(dev, alts->endpoint[0].bEndpointAddress & 0xf);
1627         u->syncpipe = u->syncinterval = 0;
1628         if ((alts->endpoint[0].bmAttributes & 0x0c) == 0x04) {
1629 #if 0
1630                 printk(KERN_DEBUG "bNumEndpoints 0x%02x endpoint[1].bmAttributes 0x%02x\n"
1631                        KERN_DEBUG "endpoint[1].bSynchAddress 0x%02x endpoint[1].bEndpointAddress 0x%02x\n"
1632                        KERN_DEBUG "endpoint[0].bSynchAddress 0x%02x\n", alts->bNumEndpoints,
1633                        alts->endpoint[1].bmAttributes, alts->endpoint[1].bSynchAddress,
1634                        alts->endpoint[1].bEndpointAddress, alts->endpoint[0].bSynchAddress);
1635 #endif
1636                 if (alts->bNumEndpoints < 2 ||
1637                     alts->endpoint[1].bmAttributes != 0x01 ||
1638                     alts->endpoint[1].bSynchAddress != 0 ||
1639                     alts->endpoint[1].bEndpointAddress != (alts->endpoint[0].bSynchAddress | 0x80)) {
1640                         printk(KERN_ERR "usbaudio: device %d interface %d altsetting %d invalid synch pipe\n",
1641                                dev->devnum, u->interface, fmt->altsetting);
1642                         return -1;
1643                 }
1644                 u->syncpipe = usb_rcvisocpipe(dev, alts->endpoint[1].bEndpointAddress & 0xf);
1645                 u->syncinterval = alts->endpoint[1].bRefresh;
1646         }
1647         if (d->srate < fmt->sratelo)
1648                 d->srate = fmt->sratelo;
1649         if (d->srate > fmt->sratehi)
1650                 d->srate = fmt->sratehi;
1651         dprintk((KERN_DEBUG "usbaudio: set_format_out: usb_set_interface %u %u\n", alts->bInterfaceNumber, fmt->altsetting));
1652         if (usb_set_interface(dev, u->interface, fmt->altsetting) < 0) {
1653                 printk(KERN_WARNING "usbaudio: usb_set_interface failed, device %d interface %d altsetting %d\n",
1654                        dev->devnum, u->interface, fmt->altsetting);
1655                 return -1;
1656         }
1657         if (fmt->sratelo == fmt->sratehi)
1658                 return 0;
1659         ep = usb_pipeendpoint(u->datapipe) | (u->datapipe & USB_DIR_IN);
1660         /* if endpoint has pitch control, enable it */
1661         if (fmt->attributes & 0x02) {
1662                 data[0] = 1;
1663                 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT, 
1664                                            PITCH_CONTROL << 8, ep, data, 1, HZ)) < 0) {
1665                         printk(KERN_ERR "usbaudio: failure (error %d) to set output pitch control device %d interface %u endpoint 0x%x to %u\n",
1666                                ret, dev->devnum, u->interface, ep, d->srate);
1667                         return -1;
1668                 }
1669         }
1670         /* if endpoint has sampling rate control, set it */
1671         if (fmt->attributes & 0x01) {
1672                 data[0] = d->srate;
1673                 data[1] = d->srate >> 8;
1674                 data[2] = d->srate >> 16;
1675                 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT, 
1676                                            SAMPLING_FREQ_CONTROL << 8, ep, data, 3, HZ)) < 0) {
1677                         printk(KERN_ERR "usbaudio: failure (error %d) to set output sampling frequency device %d interface %u endpoint 0x%x to %u\n",
1678                                ret, dev->devnum, u->interface, ep, d->srate);
1679                         return -1;
1680                 }
1681                 if ((ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), GET_CUR, USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_IN,
1682                                            SAMPLING_FREQ_CONTROL << 8, ep, data, 3, HZ)) < 0) {
1683                         printk(KERN_ERR "usbaudio: failure (error %d) to get output sampling frequency device %d interface %u endpoint 0x%x\n",
1684                                ret, dev->devnum, u->interface, ep);
1685                         return -1;
1686                 }
1687                 dprintk((KERN_DEBUG "usbaudio: set_format_out: device %d interface %d altsetting %d srate req: %u real %u\n",
1688                         dev->devnum, u->interface, fmt->altsetting, d->srate, data[0] | (data[1] << 8) | (data[2] << 16)));
1689                 d->srate = data[0] | (data[1] << 8) | (data[2] << 16);
1690         }
1691         dprintk((KERN_DEBUG "usbaudio: set_format_out: USB format 0x%x, DMA format 0x%x srate %u\n", u->format, d->format, d->srate));
1692         return 0;
1693 }
1694
1695 static int set_format(struct usb_audiodev *s, unsigned int fmode, unsigned int fmt, unsigned int srate)
1696 {
1697         int ret1 = 0, ret2 = 0;
1698
1699         if (!(fmode & (FMODE_READ|FMODE_WRITE)))
1700                 return -EINVAL;
1701         if (fmode & FMODE_READ) {
1702                 usbin_stop(s);
1703                 s->usbin.dma.ready = 0;
1704                 if (fmt == AFMT_QUERY)
1705                         fmt = s->usbin.dma.format;
1706                 else
1707                         s->usbin.dma.format = fmt;
1708                 if (!srate)
1709                         srate = s->usbin.dma.srate;
1710                 else
1711                         s->usbin.dma.srate = srate;
1712         }
1713         if (fmode & FMODE_WRITE) {
1714                 usbout_stop(s);
1715                 s->usbout.dma.ready = 0;
1716                 if (fmt == AFMT_QUERY)
1717                         fmt = s->usbout.dma.format;
1718                 else
1719                         s->usbout.dma.format = fmt;
1720                 if (!srate)
1721                         srate = s->usbout.dma.srate;
1722                 else
1723                         s->usbout.dma.srate = srate;
1724         }
1725         if (fmode & FMODE_READ)
1726                 ret1 = set_format_in(s);
1727         if (fmode & FMODE_WRITE)
1728                 ret2 = set_format_out(s);
1729         return ret1 ? ret1 : ret2;
1730 }
1731
1732 /* --------------------------------------------------------------------- */
1733
1734 static int wrmixer(struct usb_mixerdev *ms, unsigned mixch, unsigned value)
1735 {
1736         struct usb_device *dev = ms->state->usbdev;
1737         unsigned char data[2];
1738         struct mixerchannel *ch;
1739         int v1, v2, v3;
1740
1741         if (mixch >= ms->numch)
1742                 return -1;
1743         ch = &ms->ch[mixch];
1744         v3 = ch->maxval - ch->minval;
1745         v1 = value & 0xff;
1746         v2 = (value >> 8) & 0xff;
1747         if (v1 > 100)
1748                 v1 = 100;
1749         if (v2 > 100)
1750                 v2 = 100;
1751         if (!(ch->flags & (MIXFLG_STEREOIN | MIXFLG_STEREOOUT)))
1752                 v2 = v1;
1753         ch->value = v1 | (v2 << 8);
1754         v1 = (v1 * v3) / 100 + ch->minval;
1755         v2 = (v2 * v3) / 100 + ch->minval;
1756         switch (ch->selector) {
1757         case 0:  /* mixer unit request */
1758                 data[0] = v1;
1759                 data[1] = v1 >> 8;
1760                 if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
1761                                     (ch->chnum << 8) | 1, ms->iface | (ch->unitid << 8), data, 2, HZ) < 0)
1762                         goto err;
1763                 if (!(ch->flags & (MIXFLG_STEREOIN | MIXFLG_STEREOOUT)))
1764                         return 0;
1765                 data[0] = v2;
1766                 data[1] = v2 >> 8;
1767                 if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
1768                                     ((ch->chnum + !!(ch->flags & MIXFLG_STEREOIN)) << 8) | (1 + !!(ch->flags & MIXFLG_STEREOOUT)),
1769                                     ms->iface | (ch->unitid << 8), data, 2, HZ) < 0)
1770                         goto err;
1771                 return 0;
1772
1773                 /* various feature unit controls */
1774         case VOLUME_CONTROL:
1775                 data[0] = v1;
1776                 data[1] = v1 >> 8;
1777                 if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
1778                                     (ch->selector << 8) | ch->chnum, ms->iface | (ch->unitid << 8), data, 2, HZ) < 0)
1779                         goto err;
1780                 if (!(ch->flags & (MIXFLG_STEREOIN | MIXFLG_STEREOOUT)))
1781                         return 0;
1782                 data[0] = v2;
1783                 data[1] = v2 >> 8;
1784                 if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
1785                                     (ch->selector << 8) | (ch->chnum + 1), ms->iface | (ch->unitid << 8), data, 2, HZ) < 0)
1786                         goto err;
1787                 return 0;
1788                 
1789         case BASS_CONTROL:
1790         case MID_CONTROL:
1791         case TREBLE_CONTROL:
1792                 data[0] = v1 >> 8;
1793                 if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
1794                                     (ch->selector << 8) | ch->chnum, ms->iface | (ch->unitid << 8), data, 1, HZ) < 0)
1795                         goto err;
1796                 if (!(ch->flags & (MIXFLG_STEREOIN | MIXFLG_STEREOOUT)))
1797                         return 0;
1798                 data[0] = v2 >> 8;
1799                 if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
1800                                     (ch->selector << 8) | (ch->chnum + 1), ms->iface | (ch->unitid << 8), data, 1, HZ) < 0)
1801                         goto err;
1802                 return 0;
1803
1804         default:
1805                 return -1;
1806         }
1807         return 0;
1808
1809  err:
1810         printk(KERN_ERR "usbaudio: mixer request device %u if %u unit %u ch %u selector %u failed\n", 
1811                 dev->devnum, ms->iface, ch->unitid, ch->chnum, ch->selector);
1812         return -1;
1813 }
1814
1815 static int get_rec_src(struct usb_mixerdev *ms)
1816 {
1817         struct usb_device *dev = ms->state->usbdev;
1818         unsigned int mask = 0, retmask = 0;
1819         unsigned int i, j;
1820         unsigned char buf;
1821         int err = 0;
1822
1823         for (i = 0; i < ms->numch; i++) {
1824                 if (!ms->ch[i].slctunitid || (mask & (1 << i)))
1825                         continue;
1826                 if (usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), GET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
1827                                     0, ms->iface | (ms->ch[i].slctunitid << 8), &buf, 1, HZ) < 0) {
1828                         err = -EIO;
1829                         printk(KERN_ERR "usbaudio: selector read request device %u if %u unit %u failed\n", 
1830                                dev->devnum, ms->iface, ms->ch[i].slctunitid & 0xff);
1831                         continue;
1832                 }
1833                 for (j = i; j < ms->numch; j++) {
1834                         if ((ms->ch[i].slctunitid ^ ms->ch[j].slctunitid) & 0xff)
1835                                 continue;
1836                         mask |= 1 << j;
1837                         if (buf == (ms->ch[j].slctunitid >> 8))
1838                                 retmask |= 1 << ms->ch[j].osschannel;
1839                 }
1840         }
1841         if (err)
1842                 return -EIO;
1843         return retmask;
1844 }
1845
1846 static int set_rec_src(struct usb_mixerdev *ms, int srcmask)
1847 {
1848         struct usb_device *dev = ms->state->usbdev;
1849         unsigned int mask = 0, smask, bmask;
1850         unsigned int i, j;
1851         unsigned char buf;
1852         int err = 0;
1853
1854         for (i = 0; i < ms->numch; i++) {
1855                 if (!ms->ch[i].slctunitid || (mask & (1 << i)))
1856                         continue;
1857                 if (usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), GET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
1858                                     0, ms->iface | (ms->ch[i].slctunitid << 8), &buf, 1, HZ) < 0) {
1859                         err = -EIO;
1860                         printk(KERN_ERR "usbaudio: selector read request device %u if %u unit %u failed\n", 
1861                                dev->devnum, ms->iface, ms->ch[i].slctunitid & 0xff);
1862                         continue;
1863                 }
1864                 /* first generate smask */
1865                 smask = bmask = 0;
1866                 for (j = i; j < ms->numch; j++) {
1867                         if ((ms->ch[i].slctunitid ^ ms->ch[j].slctunitid) & 0xff)
1868                                 continue;
1869                         smask |= 1 << ms->ch[j].osschannel;
1870                         if (buf == (ms->ch[j].slctunitid >> 8))
1871                                 bmask |= 1 << ms->ch[j].osschannel;
1872                         mask |= 1 << j;
1873                 }
1874                 /* check for multiple set sources */
1875                 j = hweight32(srcmask & smask);
1876                 if (j == 0)
1877                         continue;
1878                 if (j > 1)
1879                         srcmask &= ~bmask;
1880                 for (j = i; j < ms->numch; j++) {
1881                         if ((ms->ch[i].slctunitid ^ ms->ch[j].slctunitid) & 0xff)
1882                                 continue;
1883                         if (!(srcmask & (1 << ms->ch[j].osschannel)))
1884                                 continue;
1885                         buf = ms->ch[j].slctunitid >> 8;
1886                         if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR, USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
1887                                     0, ms->iface | (ms->ch[j].slctunitid << 8), &buf, 1, HZ) < 0) {
1888                                 err = -EIO;
1889                                 printk(KERN_ERR "usbaudio: selector write request device %u if %u unit %u failed\n", 
1890                                        dev->devnum, ms->iface, ms->ch[j].slctunitid & 0xff);
1891                                 continue;
1892                         }
1893                 }
1894         }
1895         return err ? -EIO : 0;
1896 }
1897
1898 /* --------------------------------------------------------------------- */
1899
1900 /*
1901  * should be called with open_sem hold, so that no new processes
1902  * look at the audio device to be destroyed
1903  */
1904
1905 static void release(struct usb_audio_state *s)
1906 {
1907         struct usb_audiodev *as;
1908         struct usb_mixerdev *ms;
1909
1910         s->count--;
1911         if (s->count) {
1912                 up(&open_sem);
1913                 return;
1914         }
1915         up(&open_sem);
1916         wake_up(&open_wait);
1917         while (!list_empty(&s->audiolist)) {
1918                 as = list_entry(s->audiolist.next, struct usb_audiodev, list);
1919                 list_del(&as->list);
1920                 usbin_release(as);
1921                 usbout_release(as);
1922                 dmabuf_release(&as->usbin.dma);
1923                 dmabuf_release(&as->usbout.dma);
1924                 kfree(as);
1925         }
1926         while (!list_empty(&s->mixerlist)) {
1927                 ms = list_entry(s->mixerlist.next, struct usb_mixerdev, list);
1928                 list_del(&ms->list);
1929                 kfree(ms);
1930         }
1931         kfree(s);
1932 }
1933
1934 extern inline int prog_dmabuf_in(struct usb_audiodev *as)
1935 {
1936         usbin_stop(as);
1937         return dmabuf_init(&as->usbin.dma);
1938 }
1939
1940 extern inline int prog_dmabuf_out(struct usb_audiodev *as)
1941 {
1942         usbout_stop(as);
1943         return dmabuf_init(&as->usbout.dma);
1944 }
1945
1946 /* --------------------------------------------------------------------- */
1947
1948 static int usb_audio_open_mixdev(struct inode *inode, struct file *file)
1949 {
1950         int minor = MINOR(inode->i_rdev);
1951         struct list_head *devs, *mdevs;
1952         struct usb_mixerdev *ms;
1953         struct usb_audio_state *s;
1954
1955         down(&open_sem);
1956         for (devs = audiodevs.next; devs != &audiodevs; devs = devs->next) {
1957                 s = list_entry(devs, struct usb_audio_state, audiodev);
1958                 for (mdevs = s->mixerlist.next; mdevs != &s->mixerlist; mdevs = mdevs->next) {
1959                         ms = list_entry(mdevs, struct usb_mixerdev, list);
1960                         if (ms->dev_mixer == minor)
1961                                 goto mixer_found;
1962                 }
1963         }
1964         up(&open_sem);
1965         return -ENODEV;
1966
1967  mixer_found:
1968         if (!s->usbdev) {
1969                 up(&open_sem);
1970                 return -EIO;
1971         }
1972         file->private_data = ms;
1973         s->count++;
1974
1975         up(&open_sem);
1976         return 0;
1977 }
1978
1979 static int usb_audio_release_mixdev(struct inode *inode, struct file *file)
1980 {
1981         struct usb_mixerdev *ms = (struct usb_mixerdev *)file->private_data;
1982         struct usb_audio_state *s;
1983
1984         lock_kernel();
1985         s = ms->state;
1986         down(&open_sem);
1987         release(s);
1988         unlock_kernel();
1989         return 0;
1990 }
1991
1992 static int usb_audio_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1993 {
1994         struct usb_mixerdev *ms = (struct usb_mixerdev *)file->private_data;
1995         int i, j, val;
1996
1997         if (!ms->state->usbdev)
1998                 return -ENODEV;
1999   
2000         if (cmd == SOUND_MIXER_INFO) {
2001                 mixer_info info;
2002                 strncpy(info.id, "USB_AUDIO", sizeof(info.id));
2003                 strncpy(info.name, "USB Audio Class Driver", sizeof(info.name));
2004                 info.modify_counter = ms->modcnt;
2005                 if (copy_to_user((void *)arg, &info, sizeof(info)))
2006                         return -EFAULT;
2007                 return 0;
2008         }
2009         if (cmd == SOUND_OLD_MIXER_INFO) {
2010                 _old_mixer_info info;
2011                 strncpy(info.id, "USB_AUDIO", sizeof(info.id));
2012                 strncpy(info.name, "USB Audio Class Driver", sizeof(info.name));
2013                 if (copy_to_user((void *)arg, &info, sizeof(info)))
2014                         return -EFAULT;
2015                 return 0;
2016         }
2017         if (cmd == OSS_GETVERSION)
2018                 return put_user(SOUND_VERSION, (int *)arg);
2019         if (_IOC_TYPE(cmd) != 'M' || _IOC_SIZE(cmd) != sizeof(int))
2020                 return -EINVAL;
2021         if (_IOC_DIR(cmd) == _IOC_READ) {
2022                 switch (_IOC_NR(cmd)) {
2023                 case SOUND_MIXER_RECSRC: /* Arg contains a bit for each recording source */
2024                         val = get_rec_src(ms);
2025                         if (val < 0)
2026                                 return val;
2027                         return put_user(val, (int *)arg);
2028
2029                 case SOUND_MIXER_DEVMASK: /* Arg contains a bit for each supported device */
2030                         for (val = i = 0; i < ms->numch; i++)
2031                                 val |= 1 << ms->ch[i].osschannel;
2032                         return put_user(val, (int *)arg);
2033
2034                 case SOUND_MIXER_RECMASK: /* Arg contains a bit for each supported recording source */
2035                         for (val = i = 0; i < ms->numch; i++)
2036                                 if (ms->ch[i].slctunitid)
2037                                         val |= 1 << ms->ch[i].osschannel;
2038                         return put_user(val, (int *)arg);
2039
2040                 case SOUND_MIXER_STEREODEVS: /* Mixer channels supporting stereo */
2041                         for (val = i = 0; i < ms->numch; i++)
2042                                 if (ms->ch[i].flags & (MIXFLG_STEREOIN | MIXFLG_STEREOOUT))
2043                                         val |= 1 << ms->ch[i].osschannel;
2044                         return put_user(val, (int *)arg);
2045                         
2046                 case SOUND_MIXER_CAPS:
2047                         return put_user(SOUND_CAP_EXCL_INPUT, (int *)arg);
2048
2049                 default:
2050                         i = _IOC_NR(cmd);
2051                         if (i >= SOUND_MIXER_NRDEVICES)
2052                                 return -EINVAL;
2053                         for (j = 0; j < ms->numch; j++) {
2054                                 if (ms->ch[j].osschannel == i) {
2055                                         return put_user(ms->ch[j].value, (int *)arg);
2056                                 }
2057                         }
2058                         return -EINVAL;
2059                 }
2060         }
2061         if (_IOC_DIR(cmd) != (_IOC_READ|_IOC_WRITE)) 
2062                 return -EINVAL;
2063         ms->modcnt++;
2064         switch (_IOC_NR(cmd)) {
2065         case SOUND_MIXER_RECSRC: /* Arg contains a bit for each recording source */
2066                 if (get_user(val, (int *)arg))
2067                         return -EFAULT;
2068                 return set_rec_src(ms, val);
2069
2070         default:
2071                 i = _IOC_NR(cmd);
2072                 if (i >= SOUND_MIXER_NRDEVICES)
2073                         return -EINVAL;
2074                 for (j = 0; j < ms->numch && ms->ch[j].osschannel != i; j++);
2075                 if (j >= ms->numch)
2076                         return -EINVAL;
2077                 if (get_user(val, (int *)arg))
2078                         return -EFAULT;
2079                 if (wrmixer(ms, j, val))
2080                         return -EIO;
2081                 return put_user(ms->ch[j].value, (int *)arg);
2082         }
2083 }
2084
2085 static /*const*/ struct file_operations usb_mixer_fops = {
2086         owner:          THIS_MODULE,
2087         llseek:         no_llseek,
2088         ioctl:          usb_audio_ioctl_mixdev,
2089         open:           usb_audio_open_mixdev,
2090         release:        usb_audio_release_mixdev,
2091 };
2092
2093 /* --------------------------------------------------------------------- */
2094
2095 static int drain_out(struct usb_audiodev *as, int nonblock)
2096 {
2097         DECLARE_WAITQUEUE(wait, current);
2098         unsigned long flags;
2099         int count, tmo;
2100         
2101         if (as->usbout.dma.mapped || !as->usbout.dma.ready)
2102                 return 0;
2103         usbout_start(as);
2104         add_wait_queue(&as->usbout.dma.wait, &wait);
2105         for (;;) {
2106                 __set_current_state(TASK_INTERRUPTIBLE);
2107                 spin_lock_irqsave(&as->lock, flags);
2108                 count = as->usbout.dma.count;
2109                 spin_unlock_irqrestore(&as->lock, flags);
2110                 if (count <= 0)
2111                         break;
2112                 if (signal_pending(current))
2113                         break;
2114                 if (nonblock) {
2115                         remove_wait_queue(&as->usbout.dma.wait, &wait);
2116                         set_current_state(TASK_RUNNING);
2117                         return -EBUSY;
2118                 }
2119                 tmo = 3 * HZ * count / as->usbout.dma.srate;
2120                 tmo >>= AFMT_BYTESSHIFT(as->usbout.dma.format);
2121                 if (!schedule_timeout(tmo + 1)) {
2122                         printk(KERN_DEBUG "usbaudio: dma timed out??\n");
2123                         break;
2124                 }
2125         }
2126         remove_wait_queue(&as->usbout.dma.wait, &wait);
2127         set_current_state(TASK_RUNNING);
2128         if (signal_pending(current))
2129                 return -ERESTARTSYS;
2130         return 0;
2131 }
2132
2133 /* --------------------------------------------------------------------- */
2134
2135 static ssize_t usb_audio_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
2136 {
2137         struct usb_audiodev *as = (struct usb_audiodev *)file->private_data;
2138         DECLARE_WAITQUEUE(wait, current);
2139         ssize_t ret = 0;
2140         unsigned long flags;
2141         unsigned int ptr;
2142         int cnt, err;
2143
2144         if (ppos != &file->f_pos)
2145                 return -ESPIPE;
2146         if (as->usbin.dma.mapped)
2147                 return -ENXIO;
2148         if (!as->usbin.dma.ready && (ret = prog_dmabuf_in(as)))
2149                 return ret;
2150         if (!access_ok(VERIFY_WRITE, buffer, count))
2151                 return -EFAULT;
2152         add_wait_queue(&as->usbin.dma.wait, &wait);
2153         while (count > 0) {
2154                 spin_lock_irqsave(&as->lock, flags);
2155                 ptr = as->usbin.dma.rdptr;
2156                 cnt = as->usbin.dma.count;
2157                 /* set task state early to avoid wakeup races */
2158                 if (cnt <= 0)
2159                         __set_current_state(TASK_INTERRUPTIBLE);
2160                 spin_unlock_irqrestore(&as->lock, flags);
2161                 if (cnt > count)
2162                         cnt = count;
2163                 if (cnt <= 0) {
2164                         if (usbin_start(as)) {
2165                                 if (!ret)
2166                                         ret = -ENODEV;
2167                                 break;
2168                         }
2169                         if (file->f_flags & O_NONBLOCK) {
2170                                 if (!ret)
2171                                         ret = -EAGAIN;
2172                                 break;
2173                         }
2174                         schedule();
2175                         if (signal_pending(current)) {
2176                                 if (!ret)
2177                                         ret = -ERESTARTSYS;
2178                                 break;
2179                         }
2180                         continue;
2181                 }
2182                 if ((err = dmabuf_copyout_user(&as->usbin.dma, ptr, buffer, cnt))) {
2183                         if (!ret)
2184                                 ret = err;
2185                         break;
2186                 }
2187                 ptr += cnt;
2188                 if (ptr >= as->usbin.dma.dmasize)
2189                         ptr -= as->usbin.dma.dmasize;
2190                 spin_lock_irqsave(&as->lock, flags);
2191                 as->usbin.dma.rdptr = ptr;
2192                 as->usbin.dma.count -= cnt;
2193                 spin_unlock_irqrestore(&as->lock, flags);
2194                 count -= cnt;
2195                 buffer += cnt;
2196                 ret += cnt;
2197         }
2198         __set_current_state(TASK_RUNNING);
2199         remove_wait_queue(&as->usbin.dma.wait, &wait);
2200         return ret;
2201 }
2202
2203 static ssize_t usb_audio_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
2204 {
2205         struct usb_audiodev *as = (struct usb_audiodev *)file->private_data;
2206         DECLARE_WAITQUEUE(wait, current);
2207         ssize_t ret = 0;
2208         unsigned long flags;
2209         unsigned int ptr;
2210         unsigned int start_thr;
2211         int cnt, err;
2212
2213         if (ppos != &file->f_pos)
2214                 return -ESPIPE;
2215         if (as->usbout.dma.mapped)
2216                 return -ENXIO;
2217         if (!as->usbout.dma.ready && (ret = prog_dmabuf_out(as)))
2218                 return ret;
2219         if (!access_ok(VERIFY_READ, buffer, count))
2220                 return -EFAULT;
2221         start_thr = (as->usbout.dma.srate << AFMT_BYTESSHIFT(as->usbout.dma.format)) / (1000 / (3 * DESCFRAMES));
2222         add_wait_queue(&as->usbout.dma.wait, &wait);
2223         while (count > 0) {
2224 #if 0
2225                 printk(KERN_DEBUG "usb_audio_write: count %u dma: count %u rdptr %u wrptr %u dmasize %u fragsize %u flags 0x%02x taskst 0x%lx\n",
2226                        count, as->usbout.dma.count, as->usbout.dma.rdptr, as->usbout.dma.wrptr, as->usbout.dma.dmasize, as->usbout.dma.fragsize,
2227                        as->usbout.flags, current->state);
2228 #endif
2229                 spin_lock_irqsave(&as->lock, flags);
2230                 if (as->usbout.dma.count < 0) {
2231                         as->usbout.dma.count = 0;
2232                         as->usbout.dma.rdptr = as->usbout.dma.wrptr;
2233                 }
2234                 ptr = as->usbout.dma.wrptr;
2235                 cnt = as->usbout.dma.dmasize - as->usbout.dma.count;
2236                 /* set task state early to avoid wakeup races */
2237                 if (cnt <= 0)
2238                         __set_current_state(TASK_INTERRUPTIBLE);
2239                 spin_unlock_irqrestore(&as->lock, flags);
2240                 if (cnt > count)
2241                         cnt = count;
2242                 if (cnt <= 0) {
2243                         if (usbout_start(as)) {
2244                                 if (!ret)
2245                                         ret = -ENODEV;
2246                                 break;
2247                         }
2248                         if (file->f_flags & O_NONBLOCK) {
2249                                 if (!ret)
2250                                         ret = -EAGAIN;
2251                                 break;
2252                         }
2253                         schedule();
2254                         if (signal_pending(current)) {
2255                                 if (!ret)
2256                                         ret = -ERESTARTSYS;
2257                                 break;
2258                         }
2259                         continue;
2260                 }
2261                 if ((err = dmabuf_copyin_user(&as->usbout.dma, ptr, buffer, cnt))) {
2262                         if (!ret)
2263                                 ret = err;
2264                         break;
2265                 }
2266                 ptr += cnt;
2267                 if (ptr >= as->usbout.dma.dmasize)
2268                         ptr -= as->usbout.dma.dmasize;
2269                 spin_lock_irqsave(&as->lock, flags);
2270                 as->usbout.dma.wrptr = ptr;
2271                 as->usbout.dma.count += cnt;
2272                 spin_unlock_irqrestore(&as->lock, flags);
2273                 count -= cnt;
2274                 buffer += cnt;
2275                 ret += cnt;
2276                 if (as->usbout.dma.count >= start_thr && usbout_start(as)) {
2277                         if (!ret)
2278                                 ret = -ENODEV;
2279                         break;
2280                 }
2281         }
2282         __set_current_state(TASK_RUNNING);
2283         remove_wait_queue(&as->usbout.dma.wait, &wait);
2284         return ret;
2285 }
2286
2287 /* Called without the kernel lock - fine */
2288 static unsigned int usb_audio_poll(struct file *file, struct poll_table_struct *wait)
2289 {
2290         struct usb_audiodev *as = (struct usb_audiodev *)file->private_data;
2291         unsigned long flags;
2292         unsigned int mask = 0;
2293
2294         if (file->f_mode & FMODE_WRITE) {
2295                 if (!as->usbout.dma.ready)
2296                         prog_dmabuf_out(as);
2297                 poll_wait(file, &as->usbout.dma.wait, wait);
2298         }
2299         if (file->f_mode & FMODE_READ) {
2300                 if (!as->usbin.dma.ready)
2301                         prog_dmabuf_in(as);
2302                 poll_wait(file, &as->usbin.dma.wait, wait);
2303         }
2304         spin_lock_irqsave(&as->lock, flags);
2305         if (file->f_mode & FMODE_READ) {
2306                 if (as->usbin.dma.count >= (signed)as->usbin.dma.fragsize)
2307                         mask |= POLLIN | POLLRDNORM;
2308         }
2309         if (file->f_mode & FMODE_WRITE) {
2310                 if (as->usbout.dma.mapped) {
2311                         if (as->usbout.dma.count >= (signed)as->usbout.dma.fragsize) 
2312                                 mask |= POLLOUT | POLLWRNORM;
2313                 } else {
2314                         if ((signed)as->usbout.dma.dmasize >= as->usbout.dma.count + (signed)as->usbout.dma.fragsize)
2315                                 mask |= POLLOUT | POLLWRNORM;
2316                 }
2317         }
2318         spin_unlock_irqrestore(&as->lock, flags);
2319         return mask;
2320 }
2321
2322 static int usb_audio_mmap(struct file *file, struct vm_area_struct *vma)
2323 {
2324         struct usb_audiodev *as = (struct usb_audiodev *)file->private_data;
2325         struct dmabuf *db;
2326         int ret = -EINVAL;
2327
2328         lock_kernel();
2329         if (vma->vm_flags & VM_WRITE) {
2330                 if ((ret = prog_dmabuf_out(as)) != 0)
2331                         goto out;
2332                 db = &as->usbout.dma;
2333         } else if (vma->vm_flags & VM_READ) {
2334                 if ((ret = prog_dmabuf_in(as)) != 0)
2335                         goto out;
2336                 db = &as->usbin.dma;
2337         } else
2338                 goto out;
2339
2340         ret = -EINVAL;
2341         if (vma->vm_pgoff != 0)
2342                 goto out;
2343
2344         ret = dmabuf_mmap(db,  vma->vm_start, vma->vm_end - vma->vm_start, vma->vm_page_prot);
2345 out:
2346         unlock_kernel();
2347         return ret;
2348 }
2349
2350 static int usb_audio_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2351 {
2352         struct usb_audiodev *as = (struct usb_audiodev *)file->private_data;
2353         struct usb_audio_state *s = as->state;
2354         unsigned long flags;
2355         audio_buf_info abinfo;
2356         count_info cinfo;
2357         int val = 0;
2358         int val2, mapped, ret;
2359
2360         if (!s->usbdev)
2361                 return -EIO;
2362         mapped = ((file->f_mode & FMODE_WRITE) && as->usbout.dma.mapped) ||
2363                 ((file->f_mode & FMODE_READ) && as->usbin.dma.mapped);
2364 #if 0
2365         if (arg)
2366                 get_user(val, (int *)arg);
2367         printk(KERN_DEBUG "usbaudio: usb_audio_ioctl cmd=%x arg=%lx *arg=%d\n", cmd, arg, val)
2368 #endif
2369         switch (cmd) {
2370         case OSS_GETVERSION:
2371                 return put_user(SOUND_VERSION, (int *)arg);
2372
2373         case SNDCTL_DSP_SYNC:
2374                 if (file->f_mode & FMODE_WRITE)
2375                         return drain_out(as, 0/*file->f_flags & O_NONBLOCK*/);
2376                 return 0;
2377
2378         case SNDCTL_DSP_SETDUPLEX:
2379                 return 0;
2380
2381         case SNDCTL_DSP_GETCAPS:
2382                 return put_user(DSP_CAP_DUPLEX | DSP_CAP_REALTIME | DSP_CAP_TRIGGER | 
2383                                 DSP_CAP_MMAP | DSP_CAP_BATCH, (int *)arg);
2384
2385         case SNDCTL_DSP_RESET:
2386                 if (file->f_mode & FMODE_WRITE) {
2387                         usbout_stop(as);
2388                         as->usbout.dma.rdptr = as->usbout.dma.wrptr = as->usbout.dma.count = as->usbout.dma.total_bytes = 0;
2389                 }
2390                 if (file->f_mode & FMODE_READ) {
2391                         usbin_stop(as);
2392                         as->usbin.dma.rdptr = as->usbin.dma.wrptr = as->usbin.dma.count = as->usbin.dma.total_bytes = 0;
2393                 }
2394                 return 0;
2395
2396         case SNDCTL_DSP_SPEED:
2397                 if (get_user(val, (int *)arg))
2398                         return -EFAULT;
2399                 if (val >= 0) {
2400                         if (val < 4000)
2401                                 val = 4000;
2402                         if (val > 100000)
2403                                 val = 100000;
2404                         if (set_format(as, file->f_mode, AFMT_QUERY, val))
2405                                 return -EIO;
2406                 }
2407                 return put_user((file->f_mode & FMODE_READ) ? as->usbin.dma.srate : as->usbout.dma.srate, (int *)arg);
2408
2409         case SNDCTL_DSP_STEREO:
2410                 if (get_user(val, (int *)arg))
2411                         return -EFAULT;
2412                 val2 = (file->f_mode & FMODE_READ) ? as->usbin.dma.format : as->usbout.dma.format;
2413                 if (val)
2414                         val2 |= AFMT_STEREO;
2415                 else
2416                         val2 &= ~AFMT_STEREO;
2417                 if (set_format(as, file->f_mode, val2, 0))
2418                         return -EIO;
2419                 return 0;
2420
2421         case SNDCTL_DSP_CHANNELS:
2422                 if (get_user(val, (int *)arg))
2423                         return -EFAULT;
2424                 if (val != 0) {
2425                         val2 = (file->f_mode & FMODE_READ) ? as->usbin.dma.format : as->usbout.dma.format;
2426                         if (val == 1)
2427                                 val2 &= ~AFMT_STEREO;
2428                         else
2429                                 val2 |= AFMT_STEREO;
2430                         if (set_format(as, file->f_mode, val2, 0))
2431                                 return -EIO;
2432                 }
2433                 val2 = (file->f_mode & FMODE_READ) ? as->usbin.dma.format : as->usbout.dma.format;
2434                 return put_user(AFMT_ISSTEREO(val2) ? 2 : 1, (int *)arg);
2435
2436         case SNDCTL_DSP_GETFMTS: /* Returns a mask */
2437                 return put_user(AFMT_U8 | AFMT_U16_LE | AFMT_U16_BE |
2438                                 AFMT_S8 | AFMT_S16_LE | AFMT_S16_BE, (int *)arg);
2439
2440         case SNDCTL_DSP_SETFMT: /* Selects ONE fmt*/
2441                 if (get_user(val, (int *)arg))
2442                         return -EFAULT;
2443                 if (val != AFMT_QUERY) {
2444                         if (hweight32(val) != 1)
2445                                 return -EINVAL;
2446                         if (!(val & (AFMT_U8 | AFMT_U16_LE | AFMT_U16_BE |
2447                                      AFMT_S8 | AFMT_S16_LE | AFMT_S16_BE)))
2448                                 return -EINVAL;
2449                         val2 = (file->f_mode & FMODE_READ) ? as->usbin.dma.format : as->usbout.dma.format;
2450                         val |= val2 & AFMT_STEREO;
2451                         if (set_format(as, file->f_mode, val, 0))
2452                                 return -EIO;
2453                 }
2454                 val2 = (file->f_mode & FMODE_READ) ? as->usbin.dma.format : as->usbout.dma.format;
2455                 return put_user(val2 & ~AFMT_STEREO, (int *)arg);
2456
2457         case SNDCTL_DSP_POST:
2458                 return 0;
2459
2460         case SNDCTL_DSP_GETTRIGGER:
2461                 val = 0;
2462                 if (file->f_mode & FMODE_READ && as->usbin.flags & FLG_RUNNING) 
2463                         val |= PCM_ENABLE_INPUT;
2464                 if (file->f_mode & FMODE_WRITE && as->usbout.flags & FLG_RUNNING) 
2465                         val |= PCM_ENABLE_OUTPUT;
2466                 return put_user(val, (int *)arg);
2467
2468         case SNDCTL_DSP_SETTRIGGER:
2469                 if (get_user(val, (int *)arg))
2470                         return -EFAULT;
2471                 if (file->f_mode & FMODE_READ) {
2472                         if (val & PCM_ENABLE_INPUT) {
2473                                 if (!as->usbin.dma.ready && (ret = prog_dmabuf_in(as)))
2474                                         return ret;
2475                                 if (usbin_start(as))
2476                                         return -ENODEV;
2477                         } else
2478                                 usbin_stop(as);
2479                 }
2480                 if (file->f_mode & FMODE_WRITE) {
2481                         if (val & PCM_ENABLE_OUTPUT) {
2482                                 if (!as->usbout.dma.ready && (ret = prog_dmabuf_out(as)))
2483                                         return ret;
2484                                 if (usbout_start(as))
2485                                         return -ENODEV;
2486                         } else
2487                                 usbout_stop(as);
2488                 }
2489                 return 0;
2490
2491         case SNDCTL_DSP_GETOSPACE:
2492                 if (!(file->f_mode & FMODE_WRITE))
2493                         return -EINVAL;
2494                 if (!(as->usbout.flags & FLG_RUNNING) && (val = prog_dmabuf_out(as)) != 0)
2495                         return val;
2496                 spin_lock_irqsave(&as->lock, flags);
2497                 abinfo.fragsize = as->usbout.dma.fragsize;
2498                 abinfo.bytes = as->usbout.dma.dmasize - as->usbout.dma.count;
2499                 abinfo.fragstotal = as->usbout.dma.numfrag;
2500                 abinfo.fragments = abinfo.bytes >> as->usbout.dma.fragshift;      
2501                 spin_unlock_irqrestore(&as->lock, flags);
2502                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2503
2504         case SNDCTL_DSP_GETISPACE:
2505                 if (!(file->f_mode & FMODE_READ))
2506                         return -EINVAL;
2507                 if (!(as->usbin.flags & FLG_RUNNING) && (val = prog_dmabuf_in(as)) != 0)
2508                         return val;
2509                 spin_lock_irqsave(&as->lock, flags);
2510                 abinfo.fragsize = as->usbin.dma.fragsize;
2511                 abinfo.bytes = as->usbin.dma.count;
2512                 abinfo.fragstotal = as->usbin.dma.numfrag;
2513                 abinfo.fragments = abinfo.bytes >> as->usbin.dma.fragshift;      
2514                 spin_unlock_irqrestore(&as->lock, flags);
2515                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2516                 
2517         case SNDCTL_DSP_NONBLOCK:
2518                 file->f_flags |= O_NONBLOCK;
2519                 return 0;
2520
2521         case SNDCTL_DSP_GETODELAY:
2522                 if (!(file->f_mode & FMODE_WRITE))
2523                         return -EINVAL;
2524                 spin_lock_irqsave(&as->lock, flags);
2525                 val = as->usbout.dma.count;
2526                 spin_unlock_irqrestore(&as->lock, flags);
2527                 return put_user(val, (int *)arg);
2528
2529         case SNDCTL_DSP_GETIPTR:
2530                 if (!(file->f_mode & FMODE_READ))
2531                         return -EINVAL;
2532                 spin_lock_irqsave(&as->lock, flags);
2533                 cinfo.bytes = as->usbin.dma.total_bytes;
2534                 cinfo.blocks = as->usbin.dma.count >> as->usbin.dma.fragshift;
2535                 cinfo.ptr = as->usbin.dma.wrptr;
2536                 if (as->usbin.dma.mapped)
2537                         as->usbin.dma.count &= as->usbin.dma.fragsize-1;
2538                 spin_unlock_irqrestore(&as->lock, flags);
2539                 return copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
2540
2541         case SNDCTL_DSP_GETOPTR:
2542                 if (!(file->f_mode & FMODE_WRITE))
2543                         return -EINVAL;
2544                 spin_lock_irqsave(&as->lock, flags);
2545                 cinfo.bytes = as->usbout.dma.total_bytes;
2546                 cinfo.blocks = as->usbout.dma.count >> as->usbout.dma.fragshift;
2547                 cinfo.ptr = as->usbout.dma.rdptr;
2548                 if (as->usbout.dma.mapped)
2549                         as->usbout.dma.count &= as->usbout.dma.fragsize-1;
2550                 spin_unlock_irqrestore(&as->lock, flags);
2551                 return copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
2552
2553        case SNDCTL_DSP_GETBLKSIZE:
2554                 if (file->f_mode & FMODE_WRITE) {
2555                         if ((val = prog_dmabuf_out(as)))
2556                                 return val;
2557                         return put_user(as->usbout.dma.fragsize, (int *)arg);
2558                 }
2559                 if ((val = prog_dmabuf_in(as)))
2560                         return val;
2561                 return put_user(as->usbin.dma.fragsize, (int *)arg);
2562
2563         case SNDCTL_DSP_SETFRAGMENT:
2564                 if (get_user(val, (int *)arg))
2565                         return -EFAULT;
2566                 if (file->f_mode & FMODE_READ) {
2567                         as->usbin.dma.ossfragshift = val & 0xffff;
2568                         as->usbin.dma.ossmaxfrags = (val >> 16) & 0xffff;
2569                         if (as->usbin.dma.ossfragshift < 4)
2570                                 as->usbin.dma.ossfragshift = 4;
2571                         if (as->usbin.dma.ossfragshift > 15)
2572                                 as->usbin.dma.ossfragshift = 15;
2573                         if (as->usbin.dma.ossmaxfrags < 4)
2574                                 as->usbin.dma.ossmaxfrags = 4;
2575                 }
2576                 if (file->f_mode & FMODE_WRITE) {
2577                         as->usbout.dma.ossfragshift = val & 0xffff;
2578                         as->usbout.dma.ossmaxfrags = (val >> 16) & 0xffff;
2579                         if (as->usbout.dma.ossfragshift < 4)
2580                                 as->usbout.dma.ossfragshift = 4;
2581                         if (as->usbout.dma.ossfragshift > 15)
2582                                 as->usbout.dma.ossfragshift = 15;
2583                         if (as->usbout.dma.ossmaxfrags < 4)
2584                                 as->usbout.dma.ossmaxfrags = 4;
2585                 }
2586                 return 0;
2587
2588         case SNDCTL_DSP_SUBDIVIDE:
2589                 if ((file->f_mode & FMODE_READ && as->usbin.dma.subdivision) ||
2590                     (file->f_mode & FMODE_WRITE && as->usbout.dma.subdivision))
2591                         return -EINVAL;
2592                 if (get_user(val, (int *)arg))
2593                         return -EFAULT;
2594                 if (val != 1 && val != 2 && val != 4)
2595                         return -EINVAL;
2596                 if (file->f_mode & FMODE_READ)
2597                         as->usbin.dma.subdivision = val;
2598                 if (file->f_mode & FMODE_WRITE)
2599                         as->usbout.dma.subdivision = val;
2600                 return 0;
2601
2602         case SOUND_PCM_READ_RATE:
2603                 return put_user((file->f_mode & FMODE_READ) ? as->usbin.dma.srate : as->usbout.dma.srate, (int *)arg);
2604
2605         case SOUND_PCM_READ_CHANNELS:
2606                 val2 = (file->f_mode & FMODE_READ) ? as->usbin.dma.format : as->usbout.dma.format;
2607                 return put_user(AFMT_ISSTEREO(val2) ? 2 : 1, (int *)arg);
2608
2609         case SOUND_PCM_READ_BITS:
2610                 val2 = (file->f_mode & FMODE_READ) ? as->usbin.dma.format : as->usbout.dma.format;
2611                 return put_user(AFMT_IS16BIT(val2) ? 16 : 8, (int *)arg);
2612
2613         case SOUND_PCM_WRITE_FILTER:
2614         case SNDCTL_DSP_SETSYNCRO:
2615         case SOUND_PCM_READ_FILTER:
2616                 return -EINVAL;
2617         }
2618         dprintk((KERN_DEBUG "usbaudio: usb_audio_ioctl - no command found\n"));
2619         return -ENOIOCTLCMD;
2620 }
2621
2622 static int usb_audio_open(struct inode *inode, struct file *file)