]> git.karo-electronics.de Git - linux-beck.git/blob - sound/usb/usbaudio.c
ALSA: usbaudio: implement basic set of class v2.0 parser
[linux-beck.git] / sound / usb / usbaudio.c
1 /*
2  *   (Tentative) USB Audio Driver for ALSA
3  *
4  *   Main and PCM part
5  *
6  *   Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
7  *
8  *   Many codes borrowed from audio.c by
9  *          Alan Cox (alan@lxorguk.ukuu.org.uk)
10  *          Thomas Sailer (sailer@ife.ee.ethz.ch)
11  *
12  *
13  *   This program is free software; you can redistribute it and/or modify
14  *   it under the terms of the GNU General Public License as published by
15  *   the Free Software Foundation; either version 2 of the License, or
16  *   (at your option) any later version.
17  *
18  *   This program is distributed in the hope that it will be useful,
19  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *   GNU General Public License for more details.
22  *
23  *   You should have received a copy of the GNU General Public License
24  *   along with this program; if not, write to the Free Software
25  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
26  *
27  *
28  *  NOTES:
29  *
30  *   - async unlink should be used for avoiding the sleep inside lock.
31  *     2.4.22 usb-uhci seems buggy for async unlinking and results in
32  *     oops.  in such a cse, pass async_unlink=0 option.
33  *   - the linked URBs would be preferred but not used so far because of
34  *     the instability of unlinking.
35  *   - type II is not supported properly.  there is no device which supports
36  *     this type *correctly*.  SB extigy looks as if it supports, but it's
37  *     indeed an AC3 stream packed in SPDIF frames (i.e. no real AC3 stream).
38  */
39
40
41 #include <linux/bitops.h>
42 #include <linux/init.h>
43 #include <linux/list.h>
44 #include <linux/slab.h>
45 #include <linux/string.h>
46 #include <linux/usb.h>
47 #include <linux/moduleparam.h>
48 #include <linux/mutex.h>
49 #include <linux/usb/audio.h>
50
51 #include <sound/core.h>
52 #include <sound/info.h>
53 #include <sound/pcm.h>
54 #include <sound/pcm_params.h>
55 #include <sound/initval.h>
56
57 #include "usbaudio.h"
58
59
60 MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
61 MODULE_DESCRIPTION("USB Audio");
62 MODULE_LICENSE("GPL");
63 MODULE_SUPPORTED_DEVICE("{{Generic,USB Audio}}");
64
65
66 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;      /* Index 0-MAX */
67 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;       /* ID for this card */
68 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;/* Enable this card */
69 /* Vendor/product IDs for this card */
70 static int vid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 };
71 static int pid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 };
72 static int nrpacks = 8;         /* max. number of packets per urb */
73 static int async_unlink = 1;
74 static int device_setup[SNDRV_CARDS]; /* device parameter for this card*/
75 static int ignore_ctl_error;
76
77 module_param_array(index, int, NULL, 0444);
78 MODULE_PARM_DESC(index, "Index value for the USB audio adapter.");
79 module_param_array(id, charp, NULL, 0444);
80 MODULE_PARM_DESC(id, "ID string for the USB audio adapter.");
81 module_param_array(enable, bool, NULL, 0444);
82 MODULE_PARM_DESC(enable, "Enable USB audio adapter.");
83 module_param_array(vid, int, NULL, 0444);
84 MODULE_PARM_DESC(vid, "Vendor ID for the USB audio device.");
85 module_param_array(pid, int, NULL, 0444);
86 MODULE_PARM_DESC(pid, "Product ID for the USB audio device.");
87 module_param(nrpacks, int, 0644);
88 MODULE_PARM_DESC(nrpacks, "Max. number of packets per URB.");
89 module_param(async_unlink, bool, 0444);
90 MODULE_PARM_DESC(async_unlink, "Use async unlink mode.");
91 module_param_array(device_setup, int, NULL, 0444);
92 MODULE_PARM_DESC(device_setup, "Specific device setup (if needed).");
93 module_param(ignore_ctl_error, bool, 0444);
94 MODULE_PARM_DESC(ignore_ctl_error,
95                  "Ignore errors from USB controller for mixer interfaces.");
96
97 /*
98  * debug the h/w constraints
99  */
100 /* #define HW_CONST_DEBUG */
101
102
103 /*
104  *
105  */
106
107 #define MAX_PACKS       20
108 #define MAX_PACKS_HS    (MAX_PACKS * 8) /* in high speed mode */
109 #define MAX_URBS        8
110 #define SYNC_URBS       4       /* always four urbs for sync */
111 #define MAX_QUEUE       24      /* try not to exceed this queue length, in ms */
112
113 struct audioformat {
114         struct list_head list;
115         snd_pcm_format_t format;        /* format type */
116         unsigned int channels;          /* # channels */
117         unsigned int fmt_type;          /* USB audio format type (1-3) */
118         unsigned int frame_size;        /* samples per frame for non-audio */
119         int iface;                      /* interface number */
120         unsigned char altsetting;       /* corresponding alternate setting */
121         unsigned char altset_idx;       /* array index of altenate setting */
122         unsigned char attributes;       /* corresponding attributes of cs endpoint */
123         unsigned char endpoint;         /* endpoint */
124         unsigned char ep_attr;          /* endpoint attributes */
125         unsigned char datainterval;     /* log_2 of data packet interval */
126         unsigned int maxpacksize;       /* max. packet size */
127         unsigned int rates;             /* rate bitmasks */
128         unsigned int rate_min, rate_max;        /* min/max rates */
129         unsigned int nr_rates;          /* number of rate table entries */
130         unsigned int *rate_table;       /* rate table */
131 };
132
133 struct snd_usb_substream;
134
135 struct snd_urb_ctx {
136         struct urb *urb;
137         unsigned int buffer_size;       /* size of data buffer, if data URB */
138         struct snd_usb_substream *subs;
139         int index;      /* index for urb array */
140         int packets;    /* number of packets per urb */
141 };
142
143 struct snd_urb_ops {
144         int (*prepare)(struct snd_usb_substream *subs, struct snd_pcm_runtime *runtime, struct urb *u);
145         int (*retire)(struct snd_usb_substream *subs, struct snd_pcm_runtime *runtime, struct urb *u);
146         int (*prepare_sync)(struct snd_usb_substream *subs, struct snd_pcm_runtime *runtime, struct urb *u);
147         int (*retire_sync)(struct snd_usb_substream *subs, struct snd_pcm_runtime *runtime, struct urb *u);
148 };
149
150 struct snd_usb_substream {
151         struct snd_usb_stream *stream;
152         struct usb_device *dev;
153         struct snd_pcm_substream *pcm_substream;
154         int direction;  /* playback or capture */
155         int interface;  /* current interface */
156         int endpoint;   /* assigned endpoint */
157         struct audioformat *cur_audiofmt;       /* current audioformat pointer (for hw_params callback) */
158         unsigned int cur_rate;          /* current rate (for hw_params callback) */
159         unsigned int period_bytes;      /* current period bytes (for hw_params callback) */
160         unsigned int format;     /* USB data format */
161         unsigned int datapipe;   /* the data i/o pipe */
162         unsigned int syncpipe;   /* 1 - async out or adaptive in */
163         unsigned int datainterval;      /* log_2 of data packet interval */
164         unsigned int syncinterval;  /* P for adaptive mode, 0 otherwise */
165         unsigned int freqn;      /* nominal sampling rate in fs/fps in Q16.16 format */
166         unsigned int freqm;      /* momentary sampling rate in fs/fps in Q16.16 format */
167         unsigned int freqmax;    /* maximum sampling rate, used for buffer management */
168         unsigned int phase;      /* phase accumulator */
169         unsigned int maxpacksize;       /* max packet size in bytes */
170         unsigned int maxframesize;      /* max packet size in frames */
171         unsigned int curpacksize;       /* current packet size in bytes (for capture) */
172         unsigned int curframesize;      /* current packet size in frames (for capture) */
173         unsigned int fill_max: 1;       /* fill max packet size always */
174         unsigned int txfr_quirk:1;      /* allow sub-frame alignment */
175         unsigned int fmt_type;          /* USB audio format type (1-3) */
176
177         unsigned int running: 1;        /* running status */
178
179         unsigned int hwptr_done;        /* processed byte position in the buffer */
180         unsigned int transfer_done;             /* processed frames since last period update */
181         unsigned long active_mask;      /* bitmask of active urbs */
182         unsigned long unlink_mask;      /* bitmask of unlinked urbs */
183
184         unsigned int nurbs;                     /* # urbs */
185         struct snd_urb_ctx dataurb[MAX_URBS];   /* data urb table */
186         struct snd_urb_ctx syncurb[SYNC_URBS];  /* sync urb table */
187         char *syncbuf;                          /* sync buffer for all sync URBs */
188         dma_addr_t sync_dma;                    /* DMA address of syncbuf */
189
190         u64 formats;                    /* format bitmasks (all or'ed) */
191         unsigned int num_formats;               /* number of supported audio formats (list) */
192         struct list_head fmt_list;      /* format list */
193         struct snd_pcm_hw_constraint_list rate_list;    /* limited rates */
194         spinlock_t lock;
195
196         struct snd_urb_ops ops;         /* callbacks (must be filled at init) */
197 };
198
199
200 struct snd_usb_stream {
201         struct snd_usb_audio *chip;
202         struct snd_pcm *pcm;
203         int pcm_index;
204         unsigned int fmt_type;          /* USB audio format type (1-3) */
205         struct snd_usb_substream substream[2];
206         struct list_head list;
207 };
208
209
210 /*
211  * we keep the snd_usb_audio_t instances by ourselves for merging
212  * the all interfaces on the same card as one sound device.
213  */
214
215 static DEFINE_MUTEX(register_mutex);
216 static struct snd_usb_audio *usb_chip[SNDRV_CARDS];
217
218
219 /*
220  * convert a sampling rate into our full speed format (fs/1000 in Q16.16)
221  * this will overflow at approx 524 kHz
222  */
223 static inline unsigned get_usb_full_speed_rate(unsigned int rate)
224 {
225         return ((rate << 13) + 62) / 125;
226 }
227
228 /*
229  * convert a sampling rate into USB high speed format (fs/8000 in Q16.16)
230  * this will overflow at approx 4 MHz
231  */
232 static inline unsigned get_usb_high_speed_rate(unsigned int rate)
233 {
234         return ((rate << 10) + 62) / 125;
235 }
236
237 /* convert our full speed USB rate into sampling rate in Hz */
238 static inline unsigned get_full_speed_hz(unsigned int usb_rate)
239 {
240         return (usb_rate * 125 + (1 << 12)) >> 13;
241 }
242
243 /* convert our high speed USB rate into sampling rate in Hz */
244 static inline unsigned get_high_speed_hz(unsigned int usb_rate)
245 {
246         return (usb_rate * 125 + (1 << 9)) >> 10;
247 }
248
249
250 /*
251  * prepare urb for full speed capture sync pipe
252  *
253  * fill the length and offset of each urb descriptor.
254  * the fixed 10.14 frequency is passed through the pipe.
255  */
256 static int prepare_capture_sync_urb(struct snd_usb_substream *subs,
257                                     struct snd_pcm_runtime *runtime,
258                                     struct urb *urb)
259 {
260         unsigned char *cp = urb->transfer_buffer;
261         struct snd_urb_ctx *ctx = urb->context;
262
263         urb->dev = ctx->subs->dev; /* we need to set this at each time */
264         urb->iso_frame_desc[0].length = 3;
265         urb->iso_frame_desc[0].offset = 0;
266         cp[0] = subs->freqn >> 2;
267         cp[1] = subs->freqn >> 10;
268         cp[2] = subs->freqn >> 18;
269         return 0;
270 }
271
272 /*
273  * prepare urb for high speed capture sync pipe
274  *
275  * fill the length and offset of each urb descriptor.
276  * the fixed 12.13 frequency is passed as 16.16 through the pipe.
277  */
278 static int prepare_capture_sync_urb_hs(struct snd_usb_substream *subs,
279                                        struct snd_pcm_runtime *runtime,
280                                        struct urb *urb)
281 {
282         unsigned char *cp = urb->transfer_buffer;
283         struct snd_urb_ctx *ctx = urb->context;
284
285         urb->dev = ctx->subs->dev; /* we need to set this at each time */
286         urb->iso_frame_desc[0].length = 4;
287         urb->iso_frame_desc[0].offset = 0;
288         cp[0] = subs->freqn;
289         cp[1] = subs->freqn >> 8;
290         cp[2] = subs->freqn >> 16;
291         cp[3] = subs->freqn >> 24;
292         return 0;
293 }
294
295 /*
296  * process after capture sync complete
297  * - nothing to do
298  */
299 static int retire_capture_sync_urb(struct snd_usb_substream *subs,
300                                    struct snd_pcm_runtime *runtime,
301                                    struct urb *urb)
302 {
303         return 0;
304 }
305
306 /*
307  * prepare urb for capture data pipe
308  *
309  * fill the offset and length of each descriptor.
310  *
311  * we use a temporary buffer to write the captured data.
312  * since the length of written data is determined by host, we cannot
313  * write onto the pcm buffer directly...  the data is thus copied
314  * later at complete callback to the global buffer.
315  */
316 static int prepare_capture_urb(struct snd_usb_substream *subs,
317                                struct snd_pcm_runtime *runtime,
318                                struct urb *urb)
319 {
320         int i, offs;
321         struct snd_urb_ctx *ctx = urb->context;
322
323         offs = 0;
324         urb->dev = ctx->subs->dev; /* we need to set this at each time */
325         for (i = 0; i < ctx->packets; i++) {
326                 urb->iso_frame_desc[i].offset = offs;
327                 urb->iso_frame_desc[i].length = subs->curpacksize;
328                 offs += subs->curpacksize;
329         }
330         urb->transfer_buffer_length = offs;
331         urb->number_of_packets = ctx->packets;
332         return 0;
333 }
334
335 /*
336  * process after capture complete
337  *
338  * copy the data from each desctiptor to the pcm buffer, and
339  * update the current position.
340  */
341 static int retire_capture_urb(struct snd_usb_substream *subs,
342                               struct snd_pcm_runtime *runtime,
343                               struct urb *urb)
344 {
345         unsigned long flags;
346         unsigned char *cp;
347         int i;
348         unsigned int stride, frames, bytes, oldptr;
349         int period_elapsed = 0;
350
351         stride = runtime->frame_bits >> 3;
352
353         for (i = 0; i < urb->number_of_packets; i++) {
354                 cp = (unsigned char *)urb->transfer_buffer + urb->iso_frame_desc[i].offset;
355                 if (urb->iso_frame_desc[i].status) {
356                         snd_printd(KERN_ERR "frame %d active: %d\n", i, urb->iso_frame_desc[i].status);
357                         // continue;
358                 }
359                 bytes = urb->iso_frame_desc[i].actual_length;
360                 frames = bytes / stride;
361                 if (!subs->txfr_quirk)
362                         bytes = frames * stride;
363                 if (bytes % (runtime->sample_bits >> 3) != 0) {
364 #ifdef CONFIG_SND_DEBUG_VERBOSE
365                         int oldbytes = bytes;
366 #endif
367                         bytes = frames * stride;
368                         snd_printdd(KERN_ERR "Corrected urb data len. %d->%d\n",
369                                                         oldbytes, bytes);
370                 }
371                 /* update the current pointer */
372                 spin_lock_irqsave(&subs->lock, flags);
373                 oldptr = subs->hwptr_done;
374                 subs->hwptr_done += bytes;
375                 if (subs->hwptr_done >= runtime->buffer_size * stride)
376                         subs->hwptr_done -= runtime->buffer_size * stride;
377                 frames = (bytes + (oldptr % stride)) / stride;
378                 subs->transfer_done += frames;
379                 if (subs->transfer_done >= runtime->period_size) {
380                         subs->transfer_done -= runtime->period_size;
381                         period_elapsed = 1;
382                 }
383                 spin_unlock_irqrestore(&subs->lock, flags);
384                 /* copy a data chunk */
385                 if (oldptr + bytes > runtime->buffer_size * stride) {
386                         unsigned int bytes1 =
387                                         runtime->buffer_size * stride - oldptr;
388                         memcpy(runtime->dma_area + oldptr, cp, bytes1);
389                         memcpy(runtime->dma_area, cp + bytes1, bytes - bytes1);
390                 } else {
391                         memcpy(runtime->dma_area + oldptr, cp, bytes);
392                 }
393         }
394         if (period_elapsed)
395                 snd_pcm_period_elapsed(subs->pcm_substream);
396         return 0;
397 }
398
399 /*
400  * Process after capture complete when paused.  Nothing to do.
401  */
402 static int retire_paused_capture_urb(struct snd_usb_substream *subs,
403                                      struct snd_pcm_runtime *runtime,
404                                      struct urb *urb)
405 {
406         return 0;
407 }
408
409
410 /*
411  * prepare urb for full speed playback sync pipe
412  *
413  * set up the offset and length to receive the current frequency.
414  */
415
416 static int prepare_playback_sync_urb(struct snd_usb_substream *subs,
417                                      struct snd_pcm_runtime *runtime,
418                                      struct urb *urb)
419 {
420         struct snd_urb_ctx *ctx = urb->context;
421
422         urb->dev = ctx->subs->dev; /* we need to set this at each time */
423         urb->iso_frame_desc[0].length = 3;
424         urb->iso_frame_desc[0].offset = 0;
425         return 0;
426 }
427
428 /*
429  * prepare urb for high speed playback sync pipe
430  *
431  * set up the offset and length to receive the current frequency.
432  */
433
434 static int prepare_playback_sync_urb_hs(struct snd_usb_substream *subs,
435                                         struct snd_pcm_runtime *runtime,
436                                         struct urb *urb)
437 {
438         struct snd_urb_ctx *ctx = urb->context;
439
440         urb->dev = ctx->subs->dev; /* we need to set this at each time */
441         urb->iso_frame_desc[0].length = 4;
442         urb->iso_frame_desc[0].offset = 0;
443         return 0;
444 }
445
446 /*
447  * process after full speed playback sync complete
448  *
449  * retrieve the current 10.14 frequency from pipe, and set it.
450  * the value is referred in prepare_playback_urb().
451  */
452 static int retire_playback_sync_urb(struct snd_usb_substream *subs,
453                                     struct snd_pcm_runtime *runtime,
454                                     struct urb *urb)
455 {
456         unsigned int f;
457         unsigned long flags;
458
459         if (urb->iso_frame_desc[0].status == 0 &&
460             urb->iso_frame_desc[0].actual_length == 3) {
461                 f = combine_triple((u8*)urb->transfer_buffer) << 2;
462                 if (f >= subs->freqn - subs->freqn / 8 && f <= subs->freqmax) {
463                         spin_lock_irqsave(&subs->lock, flags);
464                         subs->freqm = f;
465                         spin_unlock_irqrestore(&subs->lock, flags);
466                 }
467         }
468
469         return 0;
470 }
471
472 /*
473  * process after high speed playback sync complete
474  *
475  * retrieve the current 12.13 frequency from pipe, and set it.
476  * the value is referred in prepare_playback_urb().
477  */
478 static int retire_playback_sync_urb_hs(struct snd_usb_substream *subs,
479                                        struct snd_pcm_runtime *runtime,
480                                        struct urb *urb)
481 {
482         unsigned int f;
483         unsigned long flags;
484
485         if (urb->iso_frame_desc[0].status == 0 &&
486             urb->iso_frame_desc[0].actual_length == 4) {
487                 f = combine_quad((u8*)urb->transfer_buffer) & 0x0fffffff;
488                 if (f >= subs->freqn - subs->freqn / 8 && f <= subs->freqmax) {
489                         spin_lock_irqsave(&subs->lock, flags);
490                         subs->freqm = f;
491                         spin_unlock_irqrestore(&subs->lock, flags);
492                 }
493         }
494
495         return 0;
496 }
497
498 /*
499  * process after E-Mu 0202/0404/Tracker Pre high speed playback sync complete
500  *
501  * These devices return the number of samples per packet instead of the number
502  * of samples per microframe.
503  */
504 static int retire_playback_sync_urb_hs_emu(struct snd_usb_substream *subs,
505                                            struct snd_pcm_runtime *runtime,
506                                            struct urb *urb)
507 {
508         unsigned int f;
509         unsigned long flags;
510
511         if (urb->iso_frame_desc[0].status == 0 &&
512             urb->iso_frame_desc[0].actual_length == 4) {
513                 f = combine_quad((u8*)urb->transfer_buffer) & 0x0fffffff;
514                 f >>= subs->datainterval;
515                 if (f >= subs->freqn - subs->freqn / 8 && f <= subs->freqmax) {
516                         spin_lock_irqsave(&subs->lock, flags);
517                         subs->freqm = f;
518                         spin_unlock_irqrestore(&subs->lock, flags);
519                 }
520         }
521
522         return 0;
523 }
524
525 /* determine the number of frames in the next packet */
526 static int snd_usb_audio_next_packet_size(struct snd_usb_substream *subs)
527 {
528         if (subs->fill_max)
529                 return subs->maxframesize;
530         else {
531                 subs->phase = (subs->phase & 0xffff)
532                         + (subs->freqm << subs->datainterval);
533                 return min(subs->phase >> 16, subs->maxframesize);
534         }
535 }
536
537 /*
538  * Prepare urb for streaming before playback starts or when paused.
539  *
540  * We don't have any data, so we send silence.
541  */
542 static int prepare_nodata_playback_urb(struct snd_usb_substream *subs,
543                                        struct snd_pcm_runtime *runtime,
544                                        struct urb *urb)
545 {
546         unsigned int i, offs, counts;
547         struct snd_urb_ctx *ctx = urb->context;
548         int stride = runtime->frame_bits >> 3;
549
550         offs = 0;
551         urb->dev = ctx->subs->dev;
552         for (i = 0; i < ctx->packets; ++i) {
553                 counts = snd_usb_audio_next_packet_size(subs);
554                 urb->iso_frame_desc[i].offset = offs * stride;
555                 urb->iso_frame_desc[i].length = counts * stride;
556                 offs += counts;
557         }
558         urb->number_of_packets = ctx->packets;
559         urb->transfer_buffer_length = offs * stride;
560         memset(urb->transfer_buffer,
561                subs->cur_audiofmt->format == SNDRV_PCM_FORMAT_U8 ? 0x80 : 0,
562                offs * stride);
563         return 0;
564 }
565
566 /*
567  * prepare urb for playback data pipe
568  *
569  * Since a URB can handle only a single linear buffer, we must use double
570  * buffering when the data to be transferred overflows the buffer boundary.
571  * To avoid inconsistencies when updating hwptr_done, we use double buffering
572  * for all URBs.
573  */
574 static int prepare_playback_urb(struct snd_usb_substream *subs,
575                                 struct snd_pcm_runtime *runtime,
576                                 struct urb *urb)
577 {
578         int i, stride;
579         unsigned int counts, frames, bytes;
580         unsigned long flags;
581         int period_elapsed = 0;
582         struct snd_urb_ctx *ctx = urb->context;
583
584         stride = runtime->frame_bits >> 3;
585
586         frames = 0;
587         urb->dev = ctx->subs->dev; /* we need to set this at each time */
588         urb->number_of_packets = 0;
589         spin_lock_irqsave(&subs->lock, flags);
590         for (i = 0; i < ctx->packets; i++) {
591                 counts = snd_usb_audio_next_packet_size(subs);
592                 /* set up descriptor */
593                 urb->iso_frame_desc[i].offset = frames * stride;
594                 urb->iso_frame_desc[i].length = counts * stride;
595                 frames += counts;
596                 urb->number_of_packets++;
597                 subs->transfer_done += counts;
598                 if (subs->transfer_done >= runtime->period_size) {
599                         subs->transfer_done -= runtime->period_size;
600                         period_elapsed = 1;
601                         if (subs->fmt_type == USB_FORMAT_TYPE_II) {
602                                 if (subs->transfer_done > 0) {
603                                         /* FIXME: fill-max mode is not
604                                          * supported yet */
605                                         frames -= subs->transfer_done;
606                                         counts -= subs->transfer_done;
607                                         urb->iso_frame_desc[i].length =
608                                                 counts * stride;
609                                         subs->transfer_done = 0;
610                                 }
611                                 i++;
612                                 if (i < ctx->packets) {
613                                         /* add a transfer delimiter */
614                                         urb->iso_frame_desc[i].offset =
615                                                 frames * stride;
616                                         urb->iso_frame_desc[i].length = 0;
617                                         urb->number_of_packets++;
618                                 }
619                                 break;
620                         }
621                 }
622                 if (period_elapsed) /* finish at the period boundary */
623                         break;
624         }
625         bytes = frames * stride;
626         if (subs->hwptr_done + bytes > runtime->buffer_size * stride) {
627                 /* err, the transferred area goes over buffer boundary. */
628                 unsigned int bytes1 =
629                         runtime->buffer_size * stride - subs->hwptr_done;
630                 memcpy(urb->transfer_buffer,
631                        runtime->dma_area + subs->hwptr_done, bytes1);
632                 memcpy(urb->transfer_buffer + bytes1,
633                        runtime->dma_area, bytes - bytes1);
634         } else {
635                 memcpy(urb->transfer_buffer,
636                        runtime->dma_area + subs->hwptr_done, bytes);
637         }
638         subs->hwptr_done += bytes;
639         if (subs->hwptr_done >= runtime->buffer_size * stride)
640                 subs->hwptr_done -= runtime->buffer_size * stride;
641         runtime->delay += frames;
642         spin_unlock_irqrestore(&subs->lock, flags);
643         urb->transfer_buffer_length = bytes;
644         if (period_elapsed)
645                 snd_pcm_period_elapsed(subs->pcm_substream);
646         return 0;
647 }
648
649 /*
650  * process after playback data complete
651  * - decrease the delay count again
652  */
653 static int retire_playback_urb(struct snd_usb_substream *subs,
654                                struct snd_pcm_runtime *runtime,
655                                struct urb *urb)
656 {
657         unsigned long flags;
658         int stride = runtime->frame_bits >> 3;
659         int processed = urb->transfer_buffer_length / stride;
660
661         spin_lock_irqsave(&subs->lock, flags);
662         if (processed > runtime->delay)
663                 runtime->delay = 0;
664         else
665                 runtime->delay -= processed;
666         spin_unlock_irqrestore(&subs->lock, flags);
667         return 0;
668 }
669
670
671 /*
672  */
673 static struct snd_urb_ops audio_urb_ops[2] = {
674         {
675                 .prepare =      prepare_nodata_playback_urb,
676                 .retire =       retire_playback_urb,
677                 .prepare_sync = prepare_playback_sync_urb,
678                 .retire_sync =  retire_playback_sync_urb,
679         },
680         {
681                 .prepare =      prepare_capture_urb,
682                 .retire =       retire_capture_urb,
683                 .prepare_sync = prepare_capture_sync_urb,
684                 .retire_sync =  retire_capture_sync_urb,
685         },
686 };
687
688 static struct snd_urb_ops audio_urb_ops_high_speed[2] = {
689         {
690                 .prepare =      prepare_nodata_playback_urb,
691                 .retire =       retire_playback_urb,
692                 .prepare_sync = prepare_playback_sync_urb_hs,
693                 .retire_sync =  retire_playback_sync_urb_hs,
694         },
695         {
696                 .prepare =      prepare_capture_urb,
697                 .retire =       retire_capture_urb,
698                 .prepare_sync = prepare_capture_sync_urb_hs,
699                 .retire_sync =  retire_capture_sync_urb,
700         },
701 };
702
703 /*
704  * complete callback from data urb
705  */
706 static void snd_complete_urb(struct urb *urb)
707 {
708         struct snd_urb_ctx *ctx = urb->context;
709         struct snd_usb_substream *subs = ctx->subs;
710         struct snd_pcm_substream *substream = ctx->subs->pcm_substream;
711         int err = 0;
712
713         if ((subs->running && subs->ops.retire(subs, substream->runtime, urb)) ||
714             !subs->running || /* can be stopped during retire callback */
715             (err = subs->ops.prepare(subs, substream->runtime, urb)) < 0 ||
716             (err = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
717                 clear_bit(ctx->index, &subs->active_mask);
718                 if (err < 0) {
719                         snd_printd(KERN_ERR "cannot submit urb (err = %d)\n", err);
720                         snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
721                 }
722         }
723 }
724
725
726 /*
727  * complete callback from sync urb
728  */
729 static void snd_complete_sync_urb(struct urb *urb)
730 {
731         struct snd_urb_ctx *ctx = urb->context;
732         struct snd_usb_substream *subs = ctx->subs;
733         struct snd_pcm_substream *substream = ctx->subs->pcm_substream;
734         int err = 0;
735
736         if ((subs->running && subs->ops.retire_sync(subs, substream->runtime, urb)) ||
737             !subs->running || /* can be stopped during retire callback */
738             (err = subs->ops.prepare_sync(subs, substream->runtime, urb)) < 0 ||
739             (err = usb_submit_urb(urb, GFP_ATOMIC)) < 0) {
740                 clear_bit(ctx->index + 16, &subs->active_mask);
741                 if (err < 0) {
742                         snd_printd(KERN_ERR "cannot submit sync urb (err = %d)\n", err);
743                         snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
744                 }
745         }
746 }
747
748
749 /*
750  * unlink active urbs.
751  */
752 static int deactivate_urbs(struct snd_usb_substream *subs, int force, int can_sleep)
753 {
754         unsigned int i;
755         int async;
756
757         subs->running = 0;
758
759         if (!force && subs->stream->chip->shutdown) /* to be sure... */
760                 return -EBADFD;
761
762         async = !can_sleep && async_unlink;
763
764         if (!async && in_interrupt())
765                 return 0;
766
767         for (i = 0; i < subs->nurbs; i++) {
768                 if (test_bit(i, &subs->active_mask)) {
769                         if (!test_and_set_bit(i, &subs->unlink_mask)) {
770                                 struct urb *u = subs->dataurb[i].urb;
771                                 if (async)
772                                         usb_unlink_urb(u);
773                                 else
774                                         usb_kill_urb(u);
775                         }
776                 }
777         }
778         if (subs->syncpipe) {
779                 for (i = 0; i < SYNC_URBS; i++) {
780                         if (test_bit(i+16, &subs->active_mask)) {
781                                 if (!test_and_set_bit(i+16, &subs->unlink_mask)) {
782                                         struct urb *u = subs->syncurb[i].urb;
783                                         if (async)
784                                                 usb_unlink_urb(u);
785                                         else
786                                                 usb_kill_urb(u);
787                                 }
788                         }
789                 }
790         }
791         return 0;
792 }
793
794
795 static const char *usb_error_string(int err)
796 {
797         switch (err) {
798         case -ENODEV:
799                 return "no device";
800         case -ENOENT:
801                 return "endpoint not enabled";
802         case -EPIPE:
803                 return "endpoint stalled";
804         case -ENOSPC:
805                 return "not enough bandwidth";
806         case -ESHUTDOWN:
807                 return "device disabled";
808         case -EHOSTUNREACH:
809                 return "device suspended";
810         case -EINVAL:
811         case -EAGAIN:
812         case -EFBIG:
813         case -EMSGSIZE:
814                 return "internal error";
815         default:
816                 return "unknown error";
817         }
818 }
819
820 /*
821  * set up and start data/sync urbs
822  */
823 static int start_urbs(struct snd_usb_substream *subs, struct snd_pcm_runtime *runtime)
824 {
825         unsigned int i;
826         int err;
827
828         if (subs->stream->chip->shutdown)
829                 return -EBADFD;
830
831         for (i = 0; i < subs->nurbs; i++) {
832                 if (snd_BUG_ON(!subs->dataurb[i].urb))
833                         return -EINVAL;
834                 if (subs->ops.prepare(subs, runtime, subs->dataurb[i].urb) < 0) {
835                         snd_printk(KERN_ERR "cannot prepare datapipe for urb %d\n", i);
836                         goto __error;
837                 }
838         }
839         if (subs->syncpipe) {
840                 for (i = 0; i < SYNC_URBS; i++) {
841                         if (snd_BUG_ON(!subs->syncurb[i].urb))
842                                 return -EINVAL;
843                         if (subs->ops.prepare_sync(subs, runtime, subs->syncurb[i].urb) < 0) {
844                                 snd_printk(KERN_ERR "cannot prepare syncpipe for urb %d\n", i);
845                                 goto __error;
846                         }
847                 }
848         }
849
850         subs->active_mask = 0;
851         subs->unlink_mask = 0;
852         subs->running = 1;
853         for (i = 0; i < subs->nurbs; i++) {
854                 err = usb_submit_urb(subs->dataurb[i].urb, GFP_ATOMIC);
855                 if (err < 0) {
856                         snd_printk(KERN_ERR "cannot submit datapipe "
857                                    "for urb %d, error %d: %s\n",
858                                    i, err, usb_error_string(err));
859                         goto __error;
860                 }
861                 set_bit(i, &subs->active_mask);
862         }
863         if (subs->syncpipe) {
864                 for (i = 0; i < SYNC_URBS; i++) {
865                         err = usb_submit_urb(subs->syncurb[i].urb, GFP_ATOMIC);
866                         if (err < 0) {
867                                 snd_printk(KERN_ERR "cannot submit syncpipe "
868                                            "for urb %d, error %d: %s\n",
869                                            i, err, usb_error_string(err));
870                                 goto __error;
871                         }
872                         set_bit(i + 16, &subs->active_mask);
873                 }
874         }
875         return 0;
876
877  __error:
878         // snd_pcm_stop(subs->pcm_substream, SNDRV_PCM_STATE_XRUN);
879         deactivate_urbs(subs, 0, 0);
880         return -EPIPE;
881 }
882
883
884 /*
885  *  wait until all urbs are processed.
886  */
887 static int wait_clear_urbs(struct snd_usb_substream *subs)
888 {
889         unsigned long end_time = jiffies + msecs_to_jiffies(1000);
890         unsigned int i;
891         int alive;
892
893         do {
894                 alive = 0;
895                 for (i = 0; i < subs->nurbs; i++) {
896                         if (test_bit(i, &subs->active_mask))
897                                 alive++;
898                 }
899                 if (subs->syncpipe) {
900                         for (i = 0; i < SYNC_URBS; i++) {
901                                 if (test_bit(i + 16, &subs->active_mask))
902                                         alive++;
903                         }
904                 }
905                 if (! alive)
906                         break;
907                 schedule_timeout_uninterruptible(1);
908         } while (time_before(jiffies, end_time));
909         if (alive)
910                 snd_printk(KERN_ERR "timeout: still %d active urbs..\n", alive);
911         return 0;
912 }
913
914
915 /*
916  * return the current pcm pointer.  just based on the hwptr_done value.
917  */
918 static snd_pcm_uframes_t snd_usb_pcm_pointer(struct snd_pcm_substream *substream)
919 {
920         struct snd_usb_substream *subs;
921         unsigned int hwptr_done;
922         
923         subs = (struct snd_usb_substream *)substream->runtime->private_data;
924         spin_lock(&subs->lock);
925         hwptr_done = subs->hwptr_done;
926         spin_unlock(&subs->lock);
927         return hwptr_done / (substream->runtime->frame_bits >> 3);
928 }
929
930
931 /*
932  * start/stop playback substream
933  */
934 static int snd_usb_pcm_playback_trigger(struct snd_pcm_substream *substream,
935                                         int cmd)
936 {
937         struct snd_usb_substream *subs = substream->runtime->private_data;
938
939         switch (cmd) {
940         case SNDRV_PCM_TRIGGER_START:
941         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
942                 subs->ops.prepare = prepare_playback_urb;
943                 return 0;
944         case SNDRV_PCM_TRIGGER_STOP:
945                 return deactivate_urbs(subs, 0, 0);
946         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
947                 subs->ops.prepare = prepare_nodata_playback_urb;
948                 return 0;
949         default:
950                 return -EINVAL;
951         }
952 }
953
954 /*
955  * start/stop capture substream
956  */
957 static int snd_usb_pcm_capture_trigger(struct snd_pcm_substream *substream,
958                                        int cmd)
959 {
960         struct snd_usb_substream *subs = substream->runtime->private_data;
961
962         switch (cmd) {
963         case SNDRV_PCM_TRIGGER_START:
964                 subs->ops.retire = retire_capture_urb;
965                 return start_urbs(subs, substream->runtime);
966         case SNDRV_PCM_TRIGGER_STOP:
967                 return deactivate_urbs(subs, 0, 0);
968         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
969                 subs->ops.retire = retire_paused_capture_urb;
970                 return 0;
971         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
972                 subs->ops.retire = retire_capture_urb;
973                 return 0;
974         default:
975                 return -EINVAL;
976         }
977 }
978
979
980 /*
981  * release a urb data
982  */
983 static void release_urb_ctx(struct snd_urb_ctx *u)
984 {
985         if (u->urb) {
986                 if (u->buffer_size)
987                         usb_buffer_free(u->subs->dev, u->buffer_size,
988                                         u->urb->transfer_buffer,
989                                         u->urb->transfer_dma);
990                 usb_free_urb(u->urb);
991                 u->urb = NULL;
992         }
993 }
994
995 /*
996  * release a substream
997  */
998 static void release_substream_urbs(struct snd_usb_substream *subs, int force)
999 {
1000         int i;
1001
1002         /* stop urbs (to be sure) */
1003         deactivate_urbs(subs, force, 1);
1004         wait_clear_urbs(subs);
1005
1006         for (i = 0; i < MAX_URBS; i++)
1007                 release_urb_ctx(&subs->dataurb[i]);
1008         for (i = 0; i < SYNC_URBS; i++)
1009                 release_urb_ctx(&subs->syncurb[i]);
1010         usb_buffer_free(subs->dev, SYNC_URBS * 4,
1011                         subs->syncbuf, subs->sync_dma);
1012         subs->syncbuf = NULL;
1013         subs->nurbs = 0;
1014 }
1015
1016 /*
1017  * initialize a substream for plaback/capture
1018  */
1019 static int init_substream_urbs(struct snd_usb_substream *subs, unsigned int period_bytes,
1020                                unsigned int rate, unsigned int frame_bits)
1021 {
1022         unsigned int maxsize, i;
1023         int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
1024         unsigned int urb_packs, total_packs, packs_per_ms;
1025
1026         /* calculate the frequency in 16.16 format */
1027         if (snd_usb_get_speed(subs->dev) == USB_SPEED_FULL)
1028                 subs->freqn = get_usb_full_speed_rate(rate);
1029         else
1030                 subs->freqn = get_usb_high_speed_rate(rate);
1031         subs->freqm = subs->freqn;
1032         /* calculate max. frequency */
1033         if (subs->maxpacksize) {
1034                 /* whatever fits into a max. size packet */
1035                 maxsize = subs->maxpacksize;
1036                 subs->freqmax = (maxsize / (frame_bits >> 3))
1037                                 << (16 - subs->datainterval);
1038         } else {
1039                 /* no max. packet size: just take 25% higher than nominal */
1040                 subs->freqmax = subs->freqn + (subs->freqn >> 2);
1041                 maxsize = ((subs->freqmax + 0xffff) * (frame_bits >> 3))
1042                                 >> (16 - subs->datainterval);
1043         }
1044         subs->phase = 0;
1045
1046         if (subs->fill_max)
1047                 subs->curpacksize = subs->maxpacksize;
1048         else
1049                 subs->curpacksize = maxsize;
1050
1051         if (snd_usb_get_speed(subs->dev) == USB_SPEED_HIGH)
1052                 packs_per_ms = 8 >> subs->datainterval;
1053         else
1054                 packs_per_ms = 1;
1055
1056         if (is_playback) {
1057                 urb_packs = max(nrpacks, 1);
1058                 urb_packs = min(urb_packs, (unsigned int)MAX_PACKS);
1059         } else
1060                 urb_packs = 1;
1061         urb_packs *= packs_per_ms;
1062         if (subs->syncpipe)
1063                 urb_packs = min(urb_packs, 1U << subs->syncinterval);
1064
1065         /* decide how many packets to be used */
1066         if (is_playback) {
1067                 unsigned int minsize, maxpacks;
1068                 /* determine how small a packet can be */
1069                 minsize = (subs->freqn >> (16 - subs->datainterval))
1070                           * (frame_bits >> 3);
1071                 /* with sync from device, assume it can be 12% lower */
1072                 if (subs->syncpipe)
1073                         minsize -= minsize >> 3;
1074                 minsize = max(minsize, 1u);
1075                 total_packs = (period_bytes + minsize - 1) / minsize;
1076                 /* we need at least two URBs for queueing */
1077                 if (total_packs < 2) {
1078                         total_packs = 2;
1079                 } else {
1080                         /* and we don't want too long a queue either */
1081                         maxpacks = max(MAX_QUEUE * packs_per_ms, urb_packs * 2);
1082                         total_packs = min(total_packs, maxpacks);
1083                 }
1084         } else {
1085                 while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
1086                         urb_packs >>= 1;
1087                 total_packs = MAX_URBS * urb_packs;
1088         }
1089         subs->nurbs = (total_packs + urb_packs - 1) / urb_packs;
1090         if (subs->nurbs > MAX_URBS) {
1091                 /* too much... */
1092                 subs->nurbs = MAX_URBS;
1093                 total_packs = MAX_URBS * urb_packs;
1094         } else if (subs->nurbs < 2) {
1095                 /* too little - we need at least two packets
1096                  * to ensure contiguous playback/capture
1097                  */
1098                 subs->nurbs = 2;
1099         }
1100
1101         /* allocate and initialize data urbs */
1102         for (i = 0; i < subs->nurbs; i++) {
1103                 struct snd_urb_ctx *u = &subs->dataurb[i];
1104                 u->index = i;
1105                 u->subs = subs;
1106                 u->packets = (i + 1) * total_packs / subs->nurbs
1107                         - i * total_packs / subs->nurbs;
1108                 u->buffer_size = maxsize * u->packets;
1109                 if (subs->fmt_type == USB_FORMAT_TYPE_II)
1110                         u->packets++; /* for transfer delimiter */
1111                 u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
1112                 if (!u->urb)
1113                         goto out_of_memory;
1114                 u->urb->transfer_buffer =
1115                         usb_buffer_alloc(subs->dev, u->buffer_size, GFP_KERNEL,
1116                                          &u->urb->transfer_dma);
1117                 if (!u->urb->transfer_buffer)
1118                         goto out_of_memory;
1119                 u->urb->pipe = subs->datapipe;
1120                 u->urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
1121                 u->urb->interval = 1 << subs->datainterval;
1122                 u->urb->context = u;
1123                 u->urb->complete = snd_complete_urb;
1124         }
1125
1126         if (subs->syncpipe) {
1127                 /* allocate and initialize sync urbs */
1128                 subs->syncbuf = usb_buffer_alloc(subs->dev, SYNC_URBS * 4,
1129                                                  GFP_KERNEL, &subs->sync_dma);
1130                 if (!subs->syncbuf)
1131                         goto out_of_memory;
1132                 for (i = 0; i < SYNC_URBS; i++) {
1133                         struct snd_urb_ctx *u = &subs->syncurb[i];
1134                         u->index = i;
1135                         u->subs = subs;
1136                         u->packets = 1;
1137                         u->urb = usb_alloc_urb(1, GFP_KERNEL);
1138                         if (!u->urb)
1139                                 goto out_of_memory;
1140                         u->urb->transfer_buffer = subs->syncbuf + i * 4;
1141                         u->urb->transfer_dma = subs->sync_dma + i * 4;
1142                         u->urb->transfer_buffer_length = 4;
1143                         u->urb->pipe = subs->syncpipe;
1144                         u->urb->transfer_flags = URB_ISO_ASAP |
1145                                                  URB_NO_TRANSFER_DMA_MAP;
1146                         u->urb->number_of_packets = 1;
1147                         u->urb->interval = 1 << subs->syncinterval;
1148                         u->urb->context = u;
1149                         u->urb->complete = snd_complete_sync_urb;
1150                 }
1151         }
1152         return 0;
1153
1154 out_of_memory:
1155         release_substream_urbs(subs, 0);
1156         return -ENOMEM;
1157 }
1158
1159
1160 /*
1161  * find a matching audio format
1162  */
1163 static struct audioformat *find_format(struct snd_usb_substream *subs, unsigned int format,
1164                                        unsigned int rate, unsigned int channels)
1165 {
1166         struct list_head *p;
1167         struct audioformat *found = NULL;
1168         int cur_attr = 0, attr;
1169
1170         list_for_each(p, &subs->fmt_list) {
1171                 struct audioformat *fp;
1172                 fp = list_entry(p, struct audioformat, list);
1173                 if (fp->format != format || fp->channels != channels)
1174                         continue;
1175                 if (rate < fp->rate_min || rate > fp->rate_max)
1176                         continue;
1177                 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
1178                         unsigned int i;
1179                         for (i = 0; i < fp->nr_rates; i++)
1180                                 if (fp->rate_table[i] == rate)
1181                                         break;
1182                         if (i >= fp->nr_rates)
1183                                 continue;
1184                 }
1185                 attr = fp->ep_attr & EP_ATTR_MASK;
1186                 if (! found) {
1187                         found = fp;
1188                         cur_attr = attr;
1189                         continue;
1190                 }
1191                 /* avoid async out and adaptive in if the other method
1192                  * supports the same format.
1193                  * this is a workaround for the case like
1194                  * M-audio audiophile USB.
1195                  */
1196                 if (attr != cur_attr) {
1197                         if ((attr == EP_ATTR_ASYNC &&
1198                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
1199                             (attr == EP_ATTR_ADAPTIVE &&
1200                              subs->direction == SNDRV_PCM_STREAM_CAPTURE))
1201                                 continue;
1202                         if ((cur_attr == EP_ATTR_ASYNC &&
1203                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
1204                             (cur_attr == EP_ATTR_ADAPTIVE &&
1205                              subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
1206                                 found = fp;
1207                                 cur_attr = attr;
1208                                 continue;
1209                         }
1210                 }
1211                 /* find the format with the largest max. packet size */
1212                 if (fp->maxpacksize > found->maxpacksize) {
1213                         found = fp;
1214                         cur_attr = attr;
1215                 }
1216         }
1217         return found;
1218 }
1219
1220
1221 /*
1222  * initialize the picth control and sample rate
1223  */
1224 static int init_usb_pitch(struct usb_device *dev, int iface,
1225                           struct usb_host_interface *alts,
1226                           struct audioformat *fmt)
1227 {
1228         unsigned int ep;
1229         unsigned char data[1];
1230         int err;
1231
1232         ep = get_endpoint(alts, 0)->bEndpointAddress;
1233         /* if endpoint has pitch control, enable it */
1234         if (fmt->attributes & EP_CS_ATTR_PITCH_CONTROL) {
1235                 data[0] = 1;
1236                 if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR,
1237                                            USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
1238                                            PITCH_CONTROL << 8, ep, data, 1, 1000)) < 0) {
1239                         snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH\n",
1240                                    dev->devnum, iface, ep);
1241                         return err;
1242                 }
1243         }
1244         return 0;
1245 }
1246
1247 static int init_usb_sample_rate(struct usb_device *dev, int iface,
1248                                 struct usb_host_interface *alts,
1249                                 struct audioformat *fmt, int rate)
1250 {
1251         unsigned int ep;
1252         unsigned char data[3];
1253         int err;
1254
1255         ep = get_endpoint(alts, 0)->bEndpointAddress;
1256         /* if endpoint has sampling rate control, set it */
1257         if (fmt->attributes & EP_CS_ATTR_SAMPLE_RATE) {
1258                 int crate;
1259                 data[0] = rate;
1260                 data[1] = rate >> 8;
1261                 data[2] = rate >> 16;
1262                 if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR,
1263                                            USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
1264                                            SAMPLING_FREQ_CONTROL << 8, ep, data, 3, 1000)) < 0) {
1265                         snd_printk(KERN_ERR "%d:%d:%d: cannot set freq %d to ep %#x\n",
1266                                    dev->devnum, iface, fmt->altsetting, rate, ep);
1267                         return err;
1268                 }
1269                 if ((err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), GET_CUR,
1270                                            USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_IN,
1271                                            SAMPLING_FREQ_CONTROL << 8, ep, data, 3, 1000)) < 0) {
1272                         snd_printk(KERN_WARNING "%d:%d:%d: cannot get freq at ep %#x\n",
1273                                    dev->devnum, iface, fmt->altsetting, ep);
1274                         return 0; /* some devices don't support reading */
1275                 }
1276                 crate = data[0] | (data[1] << 8) | (data[2] << 16);
1277                 if (crate != rate) {
1278                         snd_printd(KERN_WARNING "current rate %d is different from the runtime rate %d\n", crate, rate);
1279                         // runtime->rate = crate;
1280                 }
1281         }
1282         return 0;
1283 }
1284
1285 /*
1286  * For E-Mu 0404USB/0202USB/TrackerPre sample rate should be set for device,
1287  * not for interface.
1288  */
1289 static void set_format_emu_quirk(struct snd_usb_substream *subs,
1290                                  struct audioformat *fmt)
1291 {
1292         unsigned char emu_samplerate_id = 0;
1293
1294         /* When capture is active
1295          * sample rate shouldn't be changed
1296          * by playback substream
1297          */
1298         if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK) {
1299                 if (subs->stream->substream[SNDRV_PCM_STREAM_CAPTURE].interface != -1)
1300                         return;
1301         }
1302
1303         switch (fmt->rate_min) {
1304         case 48000:
1305                 emu_samplerate_id = EMU_QUIRK_SR_48000HZ;
1306                 break;
1307         case 88200:
1308                 emu_samplerate_id = EMU_QUIRK_SR_88200HZ;
1309                 break;
1310         case 96000:
1311                 emu_samplerate_id = EMU_QUIRK_SR_96000HZ;
1312                 break;
1313         case 176400:
1314                 emu_samplerate_id = EMU_QUIRK_SR_176400HZ;
1315                 break;
1316         case 192000:
1317                 emu_samplerate_id = EMU_QUIRK_SR_192000HZ;
1318                 break;
1319         default:
1320                 emu_samplerate_id = EMU_QUIRK_SR_44100HZ;
1321                 break;
1322         }
1323         snd_emuusb_set_samplerate(subs->stream->chip, emu_samplerate_id);
1324 }
1325
1326 /*
1327  * find a matching format and set up the interface
1328  */
1329 static int set_format(struct snd_usb_substream *subs, struct audioformat *fmt)
1330 {
1331         struct usb_device *dev = subs->dev;
1332         struct usb_host_interface *alts;
1333         struct usb_interface_descriptor *altsd;
1334         struct usb_interface *iface;
1335         unsigned int ep, attr;
1336         int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
1337         int err;
1338
1339         iface = usb_ifnum_to_if(dev, fmt->iface);
1340         if (WARN_ON(!iface))
1341                 return -EINVAL;
1342         alts = &iface->altsetting[fmt->altset_idx];
1343         altsd = get_iface_desc(alts);
1344         if (WARN_ON(altsd->bAlternateSetting != fmt->altsetting))
1345                 return -EINVAL;
1346
1347         if (fmt == subs->cur_audiofmt)
1348                 return 0;
1349
1350         /* close the old interface */
1351         if (subs->interface >= 0 && subs->interface != fmt->iface) {
1352                 if (usb_set_interface(subs->dev, subs->interface, 0) < 0) {
1353                         snd_printk(KERN_ERR "%d:%d:%d: return to setting 0 failed\n",
1354                                 dev->devnum, fmt->iface, fmt->altsetting);
1355                         return -EIO;
1356                 }
1357                 subs->interface = -1;
1358                 subs->format = 0;
1359         }
1360
1361         /* set interface */
1362         if (subs->interface != fmt->iface || subs->format != fmt->altset_idx) {
1363                 if (usb_set_interface(dev, fmt->iface, fmt->altsetting) < 0) {
1364                         snd_printk(KERN_ERR "%d:%d:%d: usb_set_interface failed\n",
1365                                    dev->devnum, fmt->iface, fmt->altsetting);
1366                         return -EIO;
1367                 }
1368                 snd_printdd(KERN_INFO "setting usb interface %d:%d\n", fmt->iface, fmt->altsetting);
1369                 subs->interface = fmt->iface;
1370                 subs->format = fmt->altset_idx;
1371         }
1372
1373         /* create a data pipe */
1374         ep = fmt->endpoint & USB_ENDPOINT_NUMBER_MASK;
1375         if (is_playback)
1376                 subs->datapipe = usb_sndisocpipe(dev, ep);
1377         else
1378                 subs->datapipe = usb_rcvisocpipe(dev, ep);
1379         subs->datainterval = fmt->datainterval;
1380         subs->syncpipe = subs->syncinterval = 0;
1381         subs->maxpacksize = fmt->maxpacksize;
1382         subs->fill_max = 0;
1383
1384         /* we need a sync pipe in async OUT or adaptive IN mode */
1385         /* check the number of EP, since some devices have broken
1386          * descriptors which fool us.  if it has only one EP,
1387          * assume it as adaptive-out or sync-in.
1388          */
1389         attr = fmt->ep_attr & EP_ATTR_MASK;
1390         if (((is_playback && attr == EP_ATTR_ASYNC) ||
1391              (! is_playback && attr == EP_ATTR_ADAPTIVE)) &&
1392             altsd->bNumEndpoints >= 2) {
1393                 /* check sync-pipe endpoint */
1394                 /* ... and check descriptor size before accessing bSynchAddress
1395                    because there is a version of the SB Audigy 2 NX firmware lacking
1396                    the audio fields in the endpoint descriptors */
1397                 if ((get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != 0x01 ||
1398                     (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
1399                      get_endpoint(alts, 1)->bSynchAddress != 0)) {
1400                         snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
1401                                    dev->devnum, fmt->iface, fmt->altsetting);
1402                         return -EINVAL;
1403                 }
1404                 ep = get_endpoint(alts, 1)->bEndpointAddress;
1405                 if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
1406                     (( is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
1407                      (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
1408                         snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
1409                                    dev->devnum, fmt->iface, fmt->altsetting);
1410                         return -EINVAL;
1411                 }
1412                 ep &= USB_ENDPOINT_NUMBER_MASK;
1413                 if (is_playback)
1414                         subs->syncpipe = usb_rcvisocpipe(dev, ep);
1415                 else
1416                         subs->syncpipe = usb_sndisocpipe(dev, ep);
1417                 if (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
1418                     get_endpoint(alts, 1)->bRefresh >= 1 &&
1419                     get_endpoint(alts, 1)->bRefresh <= 9)
1420                         subs->syncinterval = get_endpoint(alts, 1)->bRefresh;
1421                 else if (snd_usb_get_speed(subs->dev) == USB_SPEED_FULL)
1422                         subs->syncinterval = 1;
1423                 else if (get_endpoint(alts, 1)->bInterval >= 1 &&
1424                          get_endpoint(alts, 1)->bInterval <= 16)
1425                         subs->syncinterval = get_endpoint(alts, 1)->bInterval - 1;
1426                 else
1427                         subs->syncinterval = 3;
1428         }
1429
1430         /* always fill max packet size */
1431         if (fmt->attributes & EP_CS_ATTR_FILL_MAX)
1432                 subs->fill_max = 1;
1433
1434         if ((err = init_usb_pitch(dev, subs->interface, alts, fmt)) < 0)
1435                 return err;
1436
1437         subs->cur_audiofmt = fmt;
1438
1439         switch (subs->stream->chip->usb_id) {
1440         case USB_ID(0x041e, 0x3f02): /* E-Mu 0202 USB */
1441         case USB_ID(0x041e, 0x3f04): /* E-Mu 0404 USB */
1442         case USB_ID(0x041e, 0x3f0a): /* E-Mu Tracker Pre */
1443                 set_format_emu_quirk(subs, fmt);
1444                 break;
1445         }
1446
1447 #if 0
1448         printk(KERN_DEBUG
1449                "setting done: format = %d, rate = %d..%d, channels = %d\n",
1450                fmt->format, fmt->rate_min, fmt->rate_max, fmt->channels);
1451         printk(KERN_DEBUG
1452                "  datapipe = 0x%0x, syncpipe = 0x%0x\n",
1453                subs->datapipe, subs->syncpipe);
1454 #endif
1455
1456         return 0;
1457 }
1458
1459 /*
1460  * hw_params callback
1461  *
1462  * allocate a buffer and set the given audio format.
1463  *
1464  * so far we use a physically linear buffer although packetize transfer
1465  * doesn't need a continuous area.
1466  * if sg buffer is supported on the later version of alsa, we'll follow
1467  * that.
1468  */
1469 static int snd_usb_hw_params(struct snd_pcm_substream *substream,
1470                              struct snd_pcm_hw_params *hw_params)
1471 {
1472         struct snd_usb_substream *subs = substream->runtime->private_data;
1473         struct audioformat *fmt;
1474         unsigned int channels, rate, format;
1475         int ret, changed;
1476
1477         ret = snd_pcm_lib_alloc_vmalloc_buffer(substream,
1478                                                params_buffer_bytes(hw_params));
1479         if (ret < 0)
1480                 return ret;
1481
1482         format = params_format(hw_params);
1483         rate = params_rate(hw_params);
1484         channels = params_channels(hw_params);
1485         fmt = find_format(subs, format, rate, channels);
1486         if (!fmt) {
1487                 snd_printd(KERN_DEBUG "cannot set format: format = %#x, rate = %d, channels = %d\n",
1488                            format, rate, channels);
1489                 return -EINVAL;
1490         }
1491
1492         changed = subs->cur_audiofmt != fmt ||
1493                 subs->period_bytes != params_period_bytes(hw_params) ||
1494                 subs->cur_rate != rate;
1495         if ((ret = set_format(subs, fmt)) < 0)
1496                 return ret;
1497
1498         if (subs->cur_rate != rate) {
1499                 struct usb_host_interface *alts;
1500                 struct usb_interface *iface;
1501                 iface = usb_ifnum_to_if(subs->dev, fmt->iface);
1502                 alts = &iface->altsetting[fmt->altset_idx];
1503                 ret = init_usb_sample_rate(subs->dev, subs->interface, alts, fmt, rate);
1504                 if (ret < 0)
1505                         return ret;
1506                 subs->cur_rate = rate;
1507         }
1508
1509         if (changed) {
1510                 /* format changed */
1511                 release_substream_urbs(subs, 0);
1512                 /* influenced: period_bytes, channels, rate, format, */
1513                 ret = init_substream_urbs(subs, params_period_bytes(hw_params),
1514                                           params_rate(hw_params),
1515                                           snd_pcm_format_physical_width(params_format(hw_params)) * params_channels(hw_params));
1516         }
1517
1518         return ret;
1519 }
1520
1521 /*
1522  * hw_free callback
1523  *
1524  * reset the audio format and release the buffer
1525  */
1526 static int snd_usb_hw_free(struct snd_pcm_substream *substream)
1527 {
1528         struct snd_usb_substream *subs = substream->runtime->private_data;
1529
1530         subs->cur_audiofmt = NULL;
1531         subs->cur_rate = 0;
1532         subs->period_bytes = 0;
1533         if (!subs->stream->chip->shutdown)
1534                 release_substream_urbs(subs, 0);
1535         return snd_pcm_lib_free_vmalloc_buffer(substream);
1536 }
1537
1538 /*
1539  * prepare callback
1540  *
1541  * only a few subtle things...
1542  */
1543 static int snd_usb_pcm_prepare(struct snd_pcm_substream *substream)
1544 {
1545         struct snd_pcm_runtime *runtime = substream->runtime;
1546         struct snd_usb_substream *subs = runtime->private_data;
1547
1548         if (! subs->cur_audiofmt) {
1549                 snd_printk(KERN_ERR "usbaudio: no format is specified!\n");
1550                 return -ENXIO;
1551         }
1552
1553         /* some unit conversions in runtime */
1554         subs->maxframesize = bytes_to_frames(runtime, subs->maxpacksize);
1555         subs->curframesize = bytes_to_frames(runtime, subs->curpacksize);
1556
1557         /* reset the pointer */
1558         subs->hwptr_done = 0;
1559         subs->transfer_done = 0;
1560         subs->phase = 0;
1561         runtime->delay = 0;
1562
1563         /* clear urbs (to be sure) */
1564         deactivate_urbs(subs, 0, 1);
1565         wait_clear_urbs(subs);
1566
1567         /* for playback, submit the URBs now; otherwise, the first hwptr_done
1568          * updates for all URBs would happen at the same time when starting */
1569         if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK) {
1570                 subs->ops.prepare = prepare_nodata_playback_urb;
1571                 return start_urbs(subs, runtime);
1572         } else
1573                 return 0;
1574 }
1575
1576 static struct snd_pcm_hardware snd_usb_hardware =
1577 {
1578         .info =                 SNDRV_PCM_INFO_MMAP |
1579                                 SNDRV_PCM_INFO_MMAP_VALID |
1580                                 SNDRV_PCM_INFO_BATCH |
1581                                 SNDRV_PCM_INFO_INTERLEAVED |
1582                                 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1583                                 SNDRV_PCM_INFO_PAUSE,
1584         .buffer_bytes_max =     1024 * 1024,
1585         .period_bytes_min =     64,
1586         .period_bytes_max =     512 * 1024,
1587         .periods_min =          2,
1588         .periods_max =          1024,
1589 };
1590
1591 /*
1592  * h/w constraints
1593  */
1594
1595 #ifdef HW_CONST_DEBUG
1596 #define hwc_debug(fmt, args...) printk(KERN_DEBUG fmt, ##args)
1597 #else
1598 #define hwc_debug(fmt, args...) /**/
1599 #endif
1600
1601 static int hw_check_valid_format(struct snd_usb_substream *subs,
1602                                  struct snd_pcm_hw_params *params,
1603                                  struct audioformat *fp)
1604 {
1605         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1606         struct snd_interval *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1607         struct snd_mask *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1608         struct snd_interval *pt = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1609         unsigned int ptime;
1610
1611         /* check the format */
1612         if (!snd_mask_test(fmts, fp->format)) {
1613                 hwc_debug("   > check: no supported format %d\n", fp->format);
1614                 return 0;
1615         }
1616         /* check the channels */
1617         if (fp->channels < ct->min || fp->channels > ct->max) {
1618                 hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
1619                 return 0;
1620         }
1621         /* check the rate is within the range */
1622         if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
1623                 hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
1624                 return 0;
1625         }
1626         if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
1627                 hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
1628                 return 0;
1629         }
1630         /* check whether the period time is >= the data packet interval */
1631         if (snd_usb_get_speed(subs->dev) == USB_SPEED_HIGH) {
1632                 ptime = 125 * (1 << fp->datainterval);
1633                 if (ptime > pt->max || (ptime == pt->max && pt->openmax)) {
1634                         hwc_debug("   > check: ptime %u > max %u\n", ptime, pt->max);
1635                         return 0;
1636                 }
1637         }
1638         return 1;
1639 }
1640
1641 static int hw_rule_rate(struct snd_pcm_hw_params *params,
1642                         struct snd_pcm_hw_rule *rule)
1643 {
1644         struct snd_usb_substream *subs = rule->private;
1645         struct list_head *p;
1646         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1647         unsigned int rmin, rmax;
1648         int changed;
1649
1650         hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
1651         changed = 0;
1652         rmin = rmax = 0;
1653         list_for_each(p, &subs->fmt_list) {
1654                 struct audioformat *fp;
1655                 fp = list_entry(p, struct audioformat, list);
1656                 if (!hw_check_valid_format(subs, params, fp))
1657                         continue;
1658                 if (changed++) {
1659                         if (rmin > fp->rate_min)
1660                                 rmin = fp->rate_min;
1661                         if (rmax < fp->rate_max)
1662                                 rmax = fp->rate_max;
1663                 } else {
1664                         rmin = fp->rate_min;
1665                         rmax = fp->rate_max;
1666                 }
1667         }
1668
1669         if (!changed) {
1670                 hwc_debug("  --> get empty\n");
1671                 it->empty = 1;
1672                 return -EINVAL;
1673         }
1674
1675         changed = 0;
1676         if (it->min < rmin) {
1677                 it->min = rmin;
1678                 it->openmin = 0;
1679                 changed = 1;
1680         }
1681         if (it->max > rmax) {
1682                 it->max = rmax;
1683                 it->openmax = 0;
1684                 changed = 1;
1685         }
1686         if (snd_interval_checkempty(it)) {
1687                 it->empty = 1;
1688                 return -EINVAL;
1689         }
1690         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1691         return changed;
1692 }
1693
1694
1695 static int hw_rule_channels(struct snd_pcm_hw_params *params,
1696                             struct snd_pcm_hw_rule *rule)
1697 {
1698         struct snd_usb_substream *subs = rule->private;
1699         struct list_head *p;
1700         struct snd_interval *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1701         unsigned int rmin, rmax;
1702         int changed;
1703
1704         hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
1705         changed = 0;
1706         rmin = rmax = 0;
1707         list_for_each(p, &subs->fmt_list) {
1708                 struct audioformat *fp;
1709                 fp = list_entry(p, struct audioformat, list);
1710                 if (!hw_check_valid_format(subs, params, fp))
1711                         continue;
1712                 if (changed++) {
1713                         if (rmin > fp->channels)
1714                                 rmin = fp->channels;
1715                         if (rmax < fp->channels)
1716                                 rmax = fp->channels;
1717                 } else {
1718                         rmin = fp->channels;
1719                         rmax = fp->channels;
1720                 }
1721         }
1722
1723         if (!changed) {
1724                 hwc_debug("  --> get empty\n");
1725                 it->empty = 1;
1726                 return -EINVAL;
1727         }
1728
1729         changed = 0;
1730         if (it->min < rmin) {
1731                 it->min = rmin;
1732                 it->openmin = 0;
1733                 changed = 1;
1734         }
1735         if (it->max > rmax) {
1736                 it->max = rmax;
1737                 it->openmax = 0;
1738                 changed = 1;
1739         }
1740         if (snd_interval_checkempty(it)) {
1741                 it->empty = 1;
1742                 return -EINVAL;
1743         }
1744         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1745         return changed;
1746 }
1747
1748 static int hw_rule_format(struct snd_pcm_hw_params *params,
1749                           struct snd_pcm_hw_rule *rule)
1750 {
1751         struct snd_usb_substream *subs = rule->private;
1752         struct list_head *p;
1753         struct snd_mask *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1754         u64 fbits;
1755         u32 oldbits[2];
1756         int changed;
1757
1758         hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
1759         fbits = 0;
1760         list_for_each(p, &subs->fmt_list) {
1761                 struct audioformat *fp;
1762                 fp = list_entry(p, struct audioformat, list);
1763                 if (!hw_check_valid_format(subs, params, fp))
1764                         continue;
1765                 fbits |= (1ULL << fp->format);
1766         }
1767
1768         oldbits[0] = fmt->bits[0];
1769         oldbits[1] = fmt->bits[1];
1770         fmt->bits[0] &= (u32)fbits;
1771         fmt->bits[1] &= (u32)(fbits >> 32);
1772         if (!fmt->bits[0] && !fmt->bits[1]) {
1773                 hwc_debug("  --> get empty\n");
1774                 return -EINVAL;
1775         }
1776         changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
1777         hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
1778         return changed;
1779 }
1780
1781 static int hw_rule_period_time(struct snd_pcm_hw_params *params,
1782                                struct snd_pcm_hw_rule *rule)
1783 {
1784         struct snd_usb_substream *subs = rule->private;
1785         struct audioformat *fp;
1786         struct snd_interval *it;
1787         unsigned char min_datainterval;
1788         unsigned int pmin;
1789         int changed;
1790
1791         it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_PERIOD_TIME);
1792         hwc_debug("hw_rule_period_time: (%u,%u)\n", it->min, it->max);
1793         min_datainterval = 0xff;
1794         list_for_each_entry(fp, &subs->fmt_list, list) {
1795                 if (!hw_check_valid_format(subs, params, fp))
1796                         continue;
1797                 min_datainterval = min(min_datainterval, fp->datainterval);
1798         }
1799         if (min_datainterval == 0xff) {
1800                 hwc_debug("  --> get emtpy\n");
1801                 it->empty = 1;
1802                 return -EINVAL;
1803         }
1804         pmin = 125 * (1 << min_datainterval);
1805         changed = 0;
1806         if (it->min < pmin) {
1807                 it->min = pmin;
1808                 it->openmin = 0;
1809                 changed = 1;
1810         }
1811         if (snd_interval_checkempty(it)) {
1812                 it->empty = 1;
1813                 return -EINVAL;
1814         }
1815         hwc_debug("  --> (%u,%u) (changed = %d)\n", it->min, it->max, changed);
1816         return changed;
1817 }
1818
1819 /*
1820  *  If the device supports unusual bit rates, does the request meet these?
1821  */
1822 static int snd_usb_pcm_check_knot(struct snd_pcm_runtime *runtime,
1823                                   struct snd_usb_substream *subs)
1824 {
1825         struct audioformat *fp;
1826         int count = 0, needs_knot = 0;
1827         int err;
1828
1829         list_for_each_entry(fp, &subs->fmt_list, list) {
1830                 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)
1831                         return 0;
1832                 count += fp->nr_rates;
1833                 if (fp->rates & SNDRV_PCM_RATE_KNOT)
1834                         needs_knot = 1;
1835         }
1836         if (!needs_knot)
1837                 return 0;
1838
1839         subs->rate_list.count = count;
1840         subs->rate_list.list = kmalloc(sizeof(int) * count, GFP_KERNEL);
1841         subs->rate_list.mask = 0;
1842         count = 0;
1843         list_for_each_entry(fp, &subs->fmt_list, list) {
1844                 int i;
1845                 for (i = 0; i < fp->nr_rates; i++)
1846                         subs->rate_list.list[count++] = fp->rate_table[i];
1847         }
1848         err = snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1849                                          &subs->rate_list);
1850         if (err < 0)
1851                 return err;
1852
1853         return 0;
1854 }
1855
1856
1857 /*
1858  * set up the runtime hardware information.
1859  */
1860
1861 static int setup_hw_info(struct snd_pcm_runtime *runtime, struct snd_usb_substream *subs)
1862 {
1863         struct list_head *p;
1864         unsigned int pt, ptmin;
1865         int param_period_time_if_needed;
1866         int err;
1867
1868         runtime->hw.formats = subs->formats;
1869
1870         runtime->hw.rate_min = 0x7fffffff;
1871         runtime->hw.rate_max = 0;
1872         runtime->hw.channels_min = 256;
1873         runtime->hw.channels_max = 0;
1874         runtime->hw.rates = 0;
1875         ptmin = UINT_MAX;
1876         /* check min/max rates and channels */
1877         list_for_each(p, &subs->fmt_list) {
1878                 struct audioformat *fp;
1879                 fp = list_entry(p, struct audioformat, list);
1880                 runtime->hw.rates |= fp->rates;
1881                 if (runtime->hw.rate_min > fp->rate_min)
1882                         runtime->hw.rate_min = fp->rate_min;
1883                 if (runtime->hw.rate_max < fp->rate_max)
1884                         runtime->hw.rate_max = fp->rate_max;
1885                 if (runtime->hw.channels_min > fp->channels)
1886                         runtime->hw.channels_min = fp->channels;
1887                 if (runtime->hw.channels_max < fp->channels)
1888                         runtime->hw.channels_max = fp->channels;
1889                 if (fp->fmt_type == USB_FORMAT_TYPE_II && fp->frame_size > 0) {
1890                         /* FIXME: there might be more than one audio formats... */
1891                         runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1892                                 fp->frame_size;
1893                 }
1894                 pt = 125 * (1 << fp->datainterval);
1895                 ptmin = min(ptmin, pt);
1896         }
1897
1898         param_period_time_if_needed = SNDRV_PCM_HW_PARAM_PERIOD_TIME;
1899         if (snd_usb_get_speed(subs->dev) != USB_SPEED_HIGH)
1900                 /* full speed devices have fixed data packet interval */
1901                 ptmin = 1000;
1902         if (ptmin == 1000)
1903                 /* if period time doesn't go below 1 ms, no rules needed */
1904                 param_period_time_if_needed = -1;
1905         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1906                                      ptmin, UINT_MAX);
1907
1908         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1909                                        hw_rule_rate, subs,
1910                                        SNDRV_PCM_HW_PARAM_FORMAT,
1911                                        SNDRV_PCM_HW_PARAM_CHANNELS,
1912                                        param_period_time_if_needed,
1913                                        -1)) < 0)
1914                 return err;
1915         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1916                                        hw_rule_channels, subs,
1917                                        SNDRV_PCM_HW_PARAM_FORMAT,
1918                                        SNDRV_PCM_HW_PARAM_RATE,
1919                                        param_period_time_if_needed,
1920                                        -1)) < 0)
1921                 return err;
1922         if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1923                                        hw_rule_format, subs,
1924                                        SNDRV_PCM_HW_PARAM_RATE,
1925                                        SNDRV_PCM_HW_PARAM_CHANNELS,
1926                                        param_period_time_if_needed,
1927                                        -1)) < 0)
1928                 return err;
1929         if (param_period_time_if_needed >= 0) {
1930                 err = snd_pcm_hw_rule_add(runtime, 0,
1931                                           SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1932                                           hw_rule_period_time, subs,
1933                                           SNDRV_PCM_HW_PARAM_FORMAT,
1934                                           SNDRV_PCM_HW_PARAM_CHANNELS,
1935                                           SNDRV_PCM_HW_PARAM_RATE,
1936                                           -1);
1937                 if (err < 0)
1938                         return err;
1939         }
1940         if ((err = snd_usb_pcm_check_knot(runtime, subs)) < 0)
1941                 return err;
1942         return 0;
1943 }
1944
1945 static int snd_usb_pcm_open(struct snd_pcm_substream *substream, int direction)
1946 {
1947         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1948         struct snd_pcm_runtime *runtime = substream->runtime;
1949         struct snd_usb_substream *subs = &as->substream[direction];
1950
1951         subs->interface = -1;
1952         subs->format = 0;
1953         runtime->hw = snd_usb_hardware;
1954         runtime->private_data = subs;
1955         subs->pcm_substream = substream;
1956         return setup_hw_info(runtime, subs);
1957 }
1958
1959 static int snd_usb_pcm_close(struct snd_pcm_substream *substream, int direction)
1960 {
1961         struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
1962         struct snd_usb_substream *subs = &as->substream[direction];
1963
1964         if (!as->chip->shutdown && subs->interface >= 0) {
1965                 usb_set_interface(subs->dev, subs->interface, 0);
1966                 subs->interface = -1;
1967         }
1968         subs->pcm_substream = NULL;
1969         return 0;
1970 }
1971
1972 static int snd_usb_playback_open(struct snd_pcm_substream *substream)
1973 {
1974         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK);
1975 }
1976
1977 static int snd_usb_playback_close(struct snd_pcm_substream *substream)
1978 {
1979         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
1980 }
1981
1982 static int snd_usb_capture_open(struct snd_pcm_substream *substream)
1983 {
1984         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE);
1985 }
1986
1987 static int snd_usb_capture_close(struct snd_pcm_substream *substream)
1988 {
1989         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
1990 }
1991
1992 static struct snd_pcm_ops snd_usb_playback_ops = {
1993         .open =         snd_usb_playback_open,
1994         .close =        snd_usb_playback_close,
1995         .ioctl =        snd_pcm_lib_ioctl,
1996         .hw_params =    snd_usb_hw_params,
1997         .hw_free =      snd_usb_hw_free,
1998         .prepare =      snd_usb_pcm_prepare,
1999         .trigger =      snd_usb_pcm_playback_trigger,
2000         .pointer =      snd_usb_pcm_pointer,
2001         .page =         snd_pcm_lib_get_vmalloc_page,
2002         .mmap =         snd_pcm_lib_mmap_vmalloc,
2003 };
2004
2005 static struct snd_pcm_ops snd_usb_capture_ops = {
2006         .open =         snd_usb_capture_open,
2007         .close =        snd_usb_capture_close,
2008         .ioctl =        snd_pcm_lib_ioctl,
2009         .hw_params =    snd_usb_hw_params,
2010         .hw_free =      snd_usb_hw_free,
2011         .prepare =      snd_usb_pcm_prepare,
2012         .trigger =      snd_usb_pcm_capture_trigger,
2013         .pointer =      snd_usb_pcm_pointer,
2014         .page =         snd_pcm_lib_get_vmalloc_page,
2015         .mmap =         snd_pcm_lib_mmap_vmalloc,
2016 };
2017
2018
2019
2020 /*
2021  * helper functions
2022  */
2023
2024 /*
2025  * combine bytes and get an integer value
2026  */
2027 unsigned int snd_usb_combine_bytes(unsigned char *bytes, int size)
2028 {
2029         switch (size) {
2030         case 1:  return *bytes;
2031         case 2:  return combine_word(bytes);
2032         case 3:  return combine_triple(bytes);
2033         case 4:  return combine_quad(bytes);
2034         default: return 0;
2035         }
2036 }
2037
2038 /*
2039  * parse descriptor buffer and return the pointer starting the given
2040  * descriptor type.
2041  */
2042 void *snd_usb_find_desc(void *descstart, int desclen, void *after, u8 dtype)
2043 {
2044         u8 *p, *end, *next;
2045
2046         p = descstart;
2047         end = p + desclen;
2048         for (; p < end;) {
2049                 if (p[0] < 2)
2050                         return NULL;
2051                 next = p + p[0];
2052                 if (next > end)
2053                         return NULL;
2054                 if (p[1] == dtype && (!after || (void *)p > after)) {
2055                         return p;
2056                 }
2057                 p = next;
2058         }
2059         return NULL;
2060 }
2061
2062 /*
2063  * find a class-specified interface descriptor with the given subtype.
2064  */
2065 void *snd_usb_find_csint_desc(void *buffer, int buflen, void *after, u8 dsubtype)
2066 {
2067         unsigned char *p = after;
2068
2069         while ((p = snd_usb_find_desc(buffer, buflen, p,
2070                                       USB_DT_CS_INTERFACE)) != NULL) {
2071                 if (p[0] >= 3 && p[2] == dsubtype)
2072                         return p;
2073         }
2074         return NULL;
2075 }
2076
2077 /*
2078  * Wrapper for usb_control_msg().
2079  * Allocates a temp buffer to prevent dmaing from/to the stack.
2080  */
2081 int snd_usb_ctl_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
2082                     __u8 requesttype, __u16 value, __u16 index, void *data,
2083                     __u16 size, int timeout)
2084 {
2085         int err;
2086         void *buf = NULL;
2087
2088         if (size > 0) {
2089                 buf = kmemdup(data, size, GFP_KERNEL);
2090                 if (!buf)
2091                         return -ENOMEM;
2092         }
2093         err = usb_control_msg(dev, pipe, request, requesttype,
2094                               value, index, buf, size, timeout);
2095         if (size > 0) {
2096                 memcpy(data, buf, size);
2097                 kfree(buf);
2098         }
2099         return err;
2100 }
2101
2102
2103 /*
2104  * entry point for linux usb interface
2105  */
2106
2107 static int usb_audio_probe(struct usb_interface *intf,
2108                            const struct usb_device_id *id);
2109 static void usb_audio_disconnect(struct usb_interface *intf);
2110
2111 #ifdef CONFIG_PM
2112 static int usb_audio_suspend(struct usb_interface *intf, pm_message_t message);
2113 static int usb_audio_resume(struct usb_interface *intf);
2114 #else
2115 #define usb_audio_suspend NULL
2116 #define usb_audio_resume NULL
2117 #endif
2118
2119 static struct usb_device_id usb_audio_ids [] = {
2120 #include "usbquirks.h"
2121     { .match_flags = (USB_DEVICE_ID_MATCH_INT_CLASS | USB_DEVICE_ID_MATCH_INT_SUBCLASS),
2122       .bInterfaceClass = USB_CLASS_AUDIO,
2123       .bInterfaceSubClass = USB_SUBCLASS_AUDIO_CONTROL },
2124     { }                                         /* Terminating entry */
2125 };
2126
2127 MODULE_DEVICE_TABLE (usb, usb_audio_ids);
2128
2129 static struct usb_driver usb_audio_driver = {
2130         .name =         "snd-usb-audio",
2131         .probe =        usb_audio_probe,
2132         .disconnect =   usb_audio_disconnect,
2133         .suspend =      usb_audio_suspend,
2134         .resume =       usb_audio_resume,
2135         .id_table =     usb_audio_ids,
2136 };
2137
2138
2139 #if defined(CONFIG_PROC_FS) && defined(CONFIG_SND_VERBOSE_PROCFS)
2140
2141 /*
2142  * proc interface for list the supported pcm formats
2143  */
2144 static void proc_dump_substream_formats(struct snd_usb_substream *subs, struct snd_info_buffer *buffer)
2145 {
2146         struct list_head *p;
2147         static char *sync_types[4] = {
2148                 "NONE", "ASYNC", "ADAPTIVE", "SYNC"
2149         };
2150
2151         list_for_each(p, &subs->fmt_list) {
2152                 struct audioformat *fp;
2153                 fp = list_entry(p, struct audioformat, list);
2154                 snd_iprintf(buffer, "  Interface %d\n", fp->iface);
2155                 snd_iprintf(buffer, "    Altset %d\n", fp->altsetting);
2156                 snd_iprintf(buffer, "    Format: %s\n",
2157                             snd_pcm_format_name(fp->format));
2158                 snd_iprintf(buffer, "    Channels: %d\n", fp->channels);
2159                 snd_iprintf(buffer, "    Endpoint: %d %s (%s)\n",
2160                             fp->endpoint & USB_ENDPOINT_NUMBER_MASK,
2161                             fp->endpoint & USB_DIR_IN ? "IN" : "OUT",
2162                             sync_types[(fp->ep_attr & EP_ATTR_MASK) >> 2]);
2163                 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS) {
2164                         snd_iprintf(buffer, "    Rates: %d - %d (continuous)\n",
2165                                     fp->rate_min, fp->rate_max);
2166                 } else {
2167                         unsigned int i;
2168                         snd_iprintf(buffer, "    Rates: ");
2169                         for (i = 0; i < fp->nr_rates; i++) {
2170                                 if (i > 0)
2171                                         snd_iprintf(buffer, ", ");
2172                                 snd_iprintf(buffer, "%d", fp->rate_table[i]);
2173                         }
2174                         snd_iprintf(buffer, "\n");
2175                 }
2176                 if (snd_usb_get_speed(subs->dev) == USB_SPEED_HIGH)
2177                         snd_iprintf(buffer, "    Data packet interval: %d us\n",
2178                                     125 * (1 << fp->datainterval));
2179                 // snd_iprintf(buffer, "    Max Packet Size = %d\n", fp->maxpacksize);
2180                 // snd_iprintf(buffer, "    EP Attribute = %#x\n", fp->attributes);
2181         }
2182 }
2183
2184 static void proc_dump_substream_status(struct snd_usb_substream *subs, struct snd_info_buffer *buffer)
2185 {
2186         if (subs->running) {
2187                 unsigned int i;
2188                 snd_iprintf(buffer, "  Status: Running\n");
2189                 snd_iprintf(buffer, "    Interface = %d\n", subs->interface);
2190                 snd_iprintf(buffer, "    Altset = %d\n", subs->format);
2191                 snd_iprintf(buffer, "    URBs = %d [ ", subs->nurbs);
2192                 for (i = 0; i < subs->nurbs; i++)
2193                         snd_iprintf(buffer, "%d ", subs->dataurb[i].packets);
2194                 snd_iprintf(buffer, "]\n");
2195                 snd_iprintf(buffer, "    Packet Size = %d\n", subs->curpacksize);
2196                 snd_iprintf(buffer, "    Momentary freq = %u Hz (%#x.%04x)\n",
2197                             snd_usb_get_speed(subs->dev) == USB_SPEED_FULL
2198                             ? get_full_speed_hz(subs->freqm)
2199                             : get_high_speed_hz(subs->freqm),
2200                             subs->freqm >> 16, subs->freqm & 0xffff);
2201         } else {
2202                 snd_iprintf(buffer, "  Status: Stop\n");
2203         }
2204 }
2205
2206 static void proc_pcm_format_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer)
2207 {
2208         struct snd_usb_stream *stream = entry->private_data;
2209
2210         snd_iprintf(buffer, "%s : %s\n", stream->chip->card->longname, stream->pcm->name);
2211
2212         if (stream->substream[SNDRV_PCM_STREAM_PLAYBACK].num_formats) {
2213                 snd_iprintf(buffer, "\nPlayback:\n");
2214                 proc_dump_substream_status(&stream->substream[SNDRV_PCM_STREAM_PLAYBACK], buffer);
2215                 proc_dump_substream_formats(&stream->substream[SNDRV_PCM_STREAM_PLAYBACK], buffer);
2216         }
2217         if (stream->substream[SNDRV_PCM_STREAM_CAPTURE].num_formats) {
2218                 snd_iprintf(buffer, "\nCapture:\n");
2219                 proc_dump_substream_status(&stream->substream[SNDRV_PCM_STREAM_CAPTURE], buffer);
2220                 proc_dump_substream_formats(&stream->substream[SNDRV_PCM_STREAM_CAPTURE], buffer);
2221         }
2222 }
2223
2224 static void proc_pcm_format_add(struct snd_usb_stream *stream)
2225 {
2226         struct snd_info_entry *entry;
2227         char name[32];
2228         struct snd_card *card = stream->chip->card;
2229
2230         sprintf(name, "stream%d", stream->pcm_index);
2231         if (!snd_card_proc_new(card, name, &entry))
2232                 snd_info_set_text_ops(entry, stream, proc_pcm_format_read);
2233 }
2234
2235 #else
2236
2237 static inline void proc_pcm_format_add(struct snd_usb_stream *stream)
2238 {
2239 }
2240
2241 #endif
2242
2243 /*
2244  * initialize the substream instance.
2245  */
2246
2247 static void init_substream(struct snd_usb_stream *as, int stream, struct audioformat *fp)
2248 {
2249         struct snd_usb_substream *subs = &as->substream[stream];
2250
2251         INIT_LIST_HEAD(&subs->fmt_list);
2252         spin_lock_init(&subs->lock);
2253
2254         subs->stream = as;
2255         subs->direction = stream;
2256         subs->dev = as->chip->dev;
2257         subs->txfr_quirk = as->chip->txfr_quirk;
2258         if (snd_usb_get_speed(subs->dev) == USB_SPEED_FULL) {
2259                 subs->ops = audio_urb_ops[stream];
2260         } else {
2261                 subs->ops = audio_urb_ops_high_speed[stream];
2262                 switch (as->chip->usb_id) {
2263                 case USB_ID(0x041e, 0x3f02): /* E-Mu 0202 USB */
2264                 case USB_ID(0x041e, 0x3f04): /* E-Mu 0404 USB */
2265                 case USB_ID(0x041e, 0x3f0a): /* E-Mu Tracker Pre */
2266                         subs->ops.retire_sync = retire_playback_sync_urb_hs_emu;
2267                         break;
2268                 }
2269         }
2270         snd_pcm_set_ops(as->pcm, stream,
2271                         stream == SNDRV_PCM_STREAM_PLAYBACK ?
2272                         &snd_usb_playback_ops : &snd_usb_capture_ops);
2273
2274         list_add_tail(&fp->list, &subs->fmt_list);
2275         subs->formats |= 1ULL << fp->format;
2276         subs->endpoint = fp->endpoint;
2277         subs->num_formats++;
2278         subs->fmt_type = fp->fmt_type;
2279 }
2280
2281
2282 /*
2283  * free a substream
2284  */
2285 static void free_substream(struct snd_usb_substream *subs)
2286 {
2287         struct list_head *p, *n;
2288
2289         if (!subs->num_formats)
2290                 return; /* not initialized */
2291         list_for_each_safe(p, n, &subs->fmt_list) {
2292                 struct audioformat *fp = list_entry(p, struct audioformat, list);
2293                 kfree(fp->rate_table);
2294                 kfree(fp);
2295         }
2296         kfree(subs->rate_list.list);
2297 }
2298
2299
2300 /*
2301  * free a usb stream instance
2302  */
2303 static void snd_usb_audio_stream_free(struct snd_usb_stream *stream)
2304 {
2305         free_substream(&stream->substream[0]);
2306         free_substream(&stream->substream[1]);
2307         list_del(&stream->list);
2308         kfree(stream);
2309 }
2310
2311 static void snd_usb_audio_pcm_free(struct snd_pcm *pcm)
2312 {
2313         struct snd_usb_stream *stream = pcm->private_data;
2314         if (stream) {
2315                 stream->pcm = NULL;
2316                 snd_usb_audio_stream_free(stream);
2317         }
2318 }
2319
2320
2321 /*
2322  * add this endpoint to the chip instance.
2323  * if a stream with the same endpoint already exists, append to it.
2324  * if not, create a new pcm stream.
2325  */
2326 static int add_audio_endpoint(struct snd_usb_audio *chip, int stream, struct audioformat *fp)
2327 {
2328         struct list_head *p;
2329         struct snd_usb_stream *as;
2330         struct snd_usb_substream *subs;
2331         struct snd_pcm *pcm;
2332         int err;
2333
2334         list_for_each(p, &chip->pcm_list) {
2335                 as = list_entry(p, struct snd_usb_stream, list);
2336                 if (as->fmt_type != fp->fmt_type)
2337                         continue;
2338                 subs = &as->substream[stream];
2339                 if (!subs->endpoint)
2340                         continue;
2341                 if (subs->endpoint == fp->endpoint) {
2342                         list_add_tail(&fp->list, &subs->fmt_list);
2343                         subs->num_formats++;
2344                         subs->formats |= 1ULL << fp->format;
2345                         return 0;
2346                 }
2347         }
2348         /* look for an empty stream */
2349         list_for_each(p, &chip->pcm_list) {
2350                 as = list_entry(p, struct snd_usb_stream, list);
2351                 if (as->fmt_type != fp->fmt_type)
2352                         continue;
2353                 subs = &as->substream[stream];
2354                 if (subs->endpoint)
2355                         continue;
2356                 err = snd_pcm_new_stream(as->pcm, stream, 1);
2357                 if (err < 0)
2358                         return err;
2359                 init_substream(as, stream, fp);
2360                 return 0;
2361         }
2362
2363         /* create a new pcm */
2364         as = kzalloc(sizeof(*as), GFP_KERNEL);
2365         if (!as)
2366                 return -ENOMEM;
2367         as->pcm_index = chip->pcm_devs;
2368         as->chip = chip;
2369         as->fmt_type = fp->fmt_type;
2370         err = snd_pcm_new(chip->card, "USB Audio", chip->pcm_devs,
2371                           stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0,
2372                           stream == SNDRV_PCM_STREAM_PLAYBACK ? 0 : 1,
2373                           &pcm);
2374         if (err < 0) {
2375                 kfree(as);
2376                 return err;
2377         }
2378         as->pcm = pcm;
2379         pcm->private_data = as;
2380         pcm->private_free = snd_usb_audio_pcm_free;
2381         pcm->info_flags = 0;
2382         if (chip->pcm_devs > 0)
2383                 sprintf(pcm->name, "USB Audio #%d", chip->pcm_devs);
2384         else
2385                 strcpy(pcm->name, "USB Audio");
2386
2387         init_substream(as, stream, fp);
2388
2389         list_add(&as->list, &chip->pcm_list);
2390         chip->pcm_devs++;
2391
2392         proc_pcm_format_add(as);
2393
2394         return 0;
2395 }
2396
2397
2398 /*
2399  * check if the device uses big-endian samples
2400  */
2401 static int is_big_endian_format(struct snd_usb_audio *chip, struct audioformat *fp)
2402 {
2403         switch (chip->usb_id) {
2404         case USB_ID(0x0763, 0x2001): /* M-Audio Quattro: captured data only */
2405                 if (fp->endpoint & USB_DIR_IN)
2406                         return 1;
2407                 break;
2408         case USB_ID(0x0763, 0x2003): /* M-Audio Audiophile USB */
2409                 if (device_setup[chip->index] == 0x00 ||
2410                     fp->altsetting==1 || fp->altsetting==2 || fp->altsetting==3)
2411                         return 1;
2412         }
2413         return 0;
2414 }
2415
2416 /*
2417  * parse the audio format type I descriptor
2418  * and returns the corresponding pcm format
2419  *
2420  * @dev: usb device
2421  * @fp: audioformat record
2422  * @format: the format tag (wFormatTag)
2423  * @fmt: the format type descriptor
2424  */
2425 static int parse_audio_format_i_type(struct snd_usb_audio *chip,
2426                                      struct audioformat *fp,
2427                                      int format, void *_fmt,
2428                                      int protocol)
2429 {
2430         int pcm_format, i;
2431         int sample_width, sample_bytes;
2432
2433         switch (protocol) {
2434         case UAC_VERSION_1: {
2435                 struct uac_format_type_i_discrete_descriptor *fmt = _fmt;
2436                 sample_width = fmt->bBitResolution;
2437                 sample_bytes = fmt->bSubframeSize;
2438                 break;
2439         }
2440
2441         case UAC_VERSION_2: {
2442                 struct uac_format_type_i_ext_descriptor *fmt = _fmt;
2443                 sample_width = fmt->bBitResolution;
2444                 sample_bytes = fmt->bSubslotSize;
2445
2446                 /*
2447                  * FIXME
2448                  * USB audio class v2 devices specify a bitmap of possible
2449                  * audio formats rather than one fix value. For now, we just
2450                  * pick one of them and report that as the only possible
2451                  * value for this setting.
2452                  * The bit allocation map is in fact compatible to the
2453                  * wFormatTag of the v1 AS streaming descriptors, which is why
2454                  * we can simply map the matrix.
2455                  */
2456
2457                 for (i = 0; i < 5; i++)
2458                         if (format & (1UL << i)) {
2459                                 format = i + 1;
2460                                 break;
2461                         }
2462
2463                 break;
2464         }
2465
2466         default:
2467                 return -EINVAL;
2468         }
2469
2470         /* FIXME: correct endianess and sign? */
2471         pcm_format = -1;
2472
2473         switch (format) {
2474         case 0: /* some devices don't define this correctly... */
2475                 snd_printdd(KERN_INFO "%d:%u:%d : format type 0 is detected, processed as PCM\n",
2476                             chip->dev->devnum, fp->iface, fp->altsetting);
2477                 /* fall-through */
2478         case USB_AUDIO_FORMAT_PCM:
2479                 if (sample_width > sample_bytes * 8) {
2480                         snd_printk(KERN_INFO "%d:%u:%d : sample bitwidth %d in over sample bytes %d\n",
2481                                    chip->dev->devnum, fp->iface, fp->altsetting,
2482                                    sample_width, sample_bytes);
2483                 }
2484                 /* check the format byte size */
2485                 printk(" XXXXX SAMPLE BYTES %d\n", sample_bytes);
2486                 switch (sample_bytes) {
2487                 case 1:
2488                         pcm_format = SNDRV_PCM_FORMAT_S8;
2489                         break;
2490                 case 2:
2491                         if (is_big_endian_format(chip, fp))
2492                                 pcm_format = SNDRV_PCM_FORMAT_S16_BE; /* grrr, big endian!! */
2493                         else
2494                                 pcm_format = SNDRV_PCM_FORMAT_S16_LE;
2495                         break;
2496                 case 3:
2497                         if (is_big_endian_format(chip, fp))
2498                                 pcm_format = SNDRV_PCM_FORMAT_S24_3BE; /* grrr, big endian!! */
2499                         else
2500                                 pcm_format = SNDRV_PCM_FORMAT_S24_3LE;
2501                         break;
2502                 case 4:
2503                         pcm_format = SNDRV_PCM_FORMAT_S32_LE;
2504                         break;
2505                 default:
2506                         snd_printk(KERN_INFO "%d:%u:%d : unsupported sample bitwidth %d in %d bytes\n",
2507                                    chip->dev->devnum, fp->iface, fp->altsetting,
2508                                    sample_width, sample_bytes);
2509                         break;
2510                 }
2511                 break;
2512         case USB_AUDIO_FORMAT_PCM8:
2513                 pcm_format = SNDRV_PCM_FORMAT_U8;
2514
2515                 /* Dallas DS4201 workaround: it advertises U8 format, but really
2516                    supports S8. */
2517                 if (chip->usb_id == USB_ID(0x04fa, 0x4201))
2518                         pcm_format = SNDRV_PCM_FORMAT_S8;
2519                 break;
2520         case USB_AUDIO_FORMAT_IEEE_FLOAT:
2521                 pcm_format = SNDRV_PCM_FORMAT_FLOAT_LE;
2522                 break;
2523         case USB_AUDIO_FORMAT_ALAW:
2524                 pcm_format = SNDRV_PCM_FORMAT_A_LAW;
2525                 break;
2526         case USB_AUDIO_FORMAT_MU_LAW:
2527                 pcm_format = SNDRV_PCM_FORMAT_MU_LAW;
2528                 break;
2529         default:
2530                 snd_printk(KERN_INFO "%d:%u:%d : unsupported format type %d\n",
2531                            chip->dev->devnum, fp->iface, fp->altsetting, format);
2532                 break;
2533         }
2534         return pcm_format;
2535 }
2536
2537
2538 /*
2539  * parse the format descriptor and stores the possible sample rates
2540  * on the audioformat table (audio class v1).
2541  *
2542  * @dev: usb device
2543  * @fp: audioformat record
2544  * @fmt: the format descriptor
2545  * @offset: the start offset of descriptor pointing the rate type
2546  *          (7 for type I and II, 8 for type II)
2547  */
2548 static int parse_audio_format_rates_v1(struct snd_usb_audio *chip, struct audioformat *fp,
2549                                        unsigned char *fmt, int offset)
2550 {
2551         int nr_rates = fmt[offset];
2552
2553         if (fmt[0] < offset + 1 + 3 * (nr_rates ? nr_rates : 2)) {
2554                 snd_printk(KERN_ERR "%d:%u:%d : invalid FORMAT_TYPE desc\n",
2555                                    chip->dev->devnum, fp->iface, fp->altsetting);
2556                 return -1;
2557         }
2558
2559         if (nr_rates) {
2560                 /*
2561                  * build the rate table and bitmap flags
2562                  */
2563                 int r, idx;
2564
2565                 fp->rate_table = kmalloc(sizeof(int) * nr_rates, GFP_KERNEL);
2566                 if (fp->rate_table == NULL) {
2567                         snd_printk(KERN_ERR "cannot malloc\n");
2568                         return -1;
2569                 }
2570
2571                 fp->nr_rates = 0;
2572                 fp->rate_min = fp->rate_max = 0;
2573                 for (r = 0, idx = offset + 1; r < nr_rates; r++, idx += 3) {
2574                         unsigned int rate = combine_triple(&fmt[idx]);
2575                         if (!rate)
2576                                 continue;
2577                         /* C-Media CM6501 mislabels its 96 kHz altsetting */
2578                         if (rate == 48000 && nr_rates == 1 &&
2579                             (chip->usb_id == USB_ID(0x0d8c, 0x0201) ||
2580                              chip->usb_id == USB_ID(0x0d8c, 0x0102)) &&
2581                             fp->altsetting == 5 && fp->maxpacksize == 392)
2582                                 rate = 96000;
2583                         fp->rate_table[fp->nr_rates] = rate;
2584                         if (!fp->rate_min || rate < fp->rate_min)
2585                                 fp->rate_min = rate;
2586                         if (!fp->rate_max || rate > fp->rate_max)
2587                                 fp->rate_max = rate;
2588                         fp->rates |= snd_pcm_rate_to_rate_bit(rate);
2589                         fp->nr_rates++;
2590                 }
2591                 if (!fp->nr_rates) {
2592                         hwc_debug("All rates were zero. Skipping format!\n");
2593                         return -1;
2594                 }
2595         } else {
2596                 /* continuous rates */
2597                 fp->rates = SNDRV_PCM_RATE_CONTINUOUS;
2598                 fp->rate_min = combine_triple(&fmt[offset + 1]);
2599                 fp->rate_max = combine_triple(&fmt[offset + 4]);
2600         }
2601         return 0;
2602 }
2603
2604 /*
2605  * parse the format descriptor and stores the possible sample rates
2606  * on the audioformat table (audio class v2).
2607  */
2608 static int parse_audio_format_rates_v2(struct snd_usb_audio *chip,
2609                                        struct audioformat *fp,
2610                                        struct usb_host_interface *iface)
2611 {
2612         struct usb_device *dev = chip->dev;
2613         unsigned char tmp[2], *data;
2614         int i, nr_rates, data_size, ret = 0;
2615
2616         /* get the number of sample rates first by only fetching 2 bytes */
2617         ret = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), CS_RANGE,
2618                                USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
2619                                0x0100, chip->clock_id << 8, tmp, sizeof(tmp), 1000);
2620
2621         if (ret < 0) {
2622                 snd_printk(KERN_ERR "unable to retrieve number of sample rates\n");
2623                 goto err;
2624         }
2625
2626         nr_rates = (tmp[1] << 8) | tmp[0];
2627         data_size = 2 + 12 * nr_rates;
2628         data = kzalloc(data_size, GFP_KERNEL);
2629         if (!data) {
2630                 ret = -ENOMEM;
2631                 goto err;
2632         }
2633
2634         /* now get the full information */
2635         ret = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), CS_RANGE,
2636                                USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN,
2637                                0x0100, chip->clock_id << 8, data, data_size, 1000);
2638
2639         if (ret < 0) {
2640                 snd_printk(KERN_ERR "unable to retrieve sample rate range\n");
2641                 ret = -EINVAL;
2642                 goto err_free;
2643         }
2644
2645         fp->rate_table = kmalloc(sizeof(int) * nr_rates, GFP_KERNEL);
2646         if (!fp->rate_table) {
2647                 ret = -ENOMEM;
2648                 goto err_free;
2649         }
2650
2651         fp->nr_rates = 0;
2652         fp->rate_min = fp->rate_max = 0;
2653
2654         for (i = 0; i < nr_rates; i++) {
2655                 int rate = combine_quad(&data[2 + 12 * i]);
2656
2657                 fp->rate_table[fp->nr_rates] = rate;
2658                 if (!fp->rate_min || rate < fp->rate_min)
2659                         fp->rate_min = rate;
2660                 if (!fp->rate_max || rate > fp->rate_max)
2661                         fp->rate_max = rate;
2662                 fp->rates |= snd_pcm_rate_to_rate_bit(rate);
2663                 fp->nr_rates++;
2664         }
2665
2666 err_free:
2667         kfree(data);
2668 err:
2669         return ret;
2670 }
2671
2672 /*
2673  * parse the format type I and III descriptors
2674  */
2675 static int parse_audio_format_i(struct snd_usb_audio *chip,
2676                                 struct audioformat *fp,
2677                                 int format, void *_fmt,
2678                                 struct usb_host_interface *iface)
2679 {
2680         struct usb_interface_descriptor *altsd = get_iface_desc(iface);
2681         struct uac_format_type_i_discrete_descriptor *fmt = _fmt;
2682         int protocol = altsd->bInterfaceProtocol;
2683         int pcm_format, ret;
2684
2685         if (fmt->bFormatType == USB_FORMAT_TYPE_III) {
2686                 /* FIXME: the format type is really IECxxx
2687                  *        but we give normal PCM format to get the existing
2688                  *        apps working...
2689                  */
2690                 switch (chip->usb_id) {
2691
2692                 case USB_ID(0x0763, 0x2003): /* M-Audio Audiophile USB */
2693                         if (device_setup[chip->index] == 0x00 && 
2694                             fp->altsetting == 6)
2695                                 pcm_format = SNDRV_PCM_FORMAT_S16_BE;
2696                         else
2697                                 pcm_format = SNDRV_PCM_FORMAT_S16_LE;
2698                         break;
2699                 default:
2700                         pcm_format = SNDRV_PCM_FORMAT_S16_LE;
2701                 }
2702         } else {
2703                 pcm_format = parse_audio_format_i_type(chip, fp, format, fmt, protocol);
2704                 if (pcm_format < 0)
2705                         return -1;
2706         }
2707
2708         fp->format = pcm_format;
2709
2710         /* gather possible sample rates */
2711         /* audio class v1 reports possible sample rates as part of the
2712          * proprietary class specific descriptor.
2713          * audio class v2 uses class specific EP0 range requests for that.
2714          */
2715         switch (protocol) {
2716         case UAC_VERSION_1:
2717                 fp->channels = fmt->bNrChannels;
2718                 ret = parse_audio_format_rates_v1(chip, fp, _fmt, 7);
2719                 break;
2720         case UAC_VERSION_2:
2721                 /* fp->channels is already set in this case */
2722                 ret = parse_audio_format_rates_v2(chip, fp, iface);
2723                 break;
2724         }
2725
2726         if (fp->channels < 1) {
2727                 snd_printk(KERN_ERR "%d:%u:%d : invalid channels %d\n",
2728                            chip->dev->devnum, fp->iface, fp->altsetting, fp->channels);
2729                 return -1;
2730         }
2731
2732         return ret;
2733 }
2734
2735 /*
2736  * parse the format type II descriptor
2737  */
2738 static int parse_audio_format_ii(struct snd_usb_audio *chip,
2739                                  struct audioformat *fp,
2740                                  int format, void *_fmt,
2741                                  struct usb_host_interface *iface)
2742 {
2743         int brate, framesize, ret;
2744         struct usb_interface_descriptor *altsd = get_iface_desc(iface);
2745         int protocol = altsd->bInterfaceProtocol;
2746
2747         switch (format) {
2748         case USB_AUDIO_FORMAT_AC3:
2749                 /* FIXME: there is no AC3 format defined yet */
2750                 // fp->format = SNDRV_PCM_FORMAT_AC3;
2751                 fp->format = SNDRV_PCM_FORMAT_U8; /* temporarily hack to receive byte streams */
2752                 break;
2753         case USB_AUDIO_FORMAT_MPEG:
2754                 fp->format = SNDRV_PCM_FORMAT_MPEG;
2755                 break;
2756         default:
2757                 snd_printd(KERN_INFO "%d:%u:%d : unknown format tag %#x is detected.  processed as MPEG.\n",
2758                            chip->dev->devnum, fp->iface, fp->altsetting, format);
2759                 fp->format = SNDRV_PCM_FORMAT_MPEG;
2760                 break;
2761         }
2762
2763         fp->channels = 1;
2764
2765         switch (protocol) {
2766         case UAC_VERSION_1: {
2767                 struct uac_format_type_ii_discrete_descriptor *fmt = _fmt;
2768                 brate = le16_to_cpu(fmt->wMaxBitRate);
2769                 framesize = le16_to_cpu(fmt->wSamplesPerFrame);
2770                 snd_printd(KERN_INFO "found format II with max.bitrate = %d, frame size=%d\n", brate, framesize);
2771                 fp->frame_size = framesize;
2772                 ret = parse_audio_format_rates_v1(chip, fp, _fmt, 8); /* fmt[8..] sample rates */
2773                 break;
2774         }
2775         case UAC_VERSION_2: {
2776                 struct uac_format_type_ii_ext_descriptor *fmt = _fmt;
2777                 brate = le16_to_cpu(fmt->wMaxBitRate);
2778                 framesize = le16_to_cpu(fmt->wSamplesPerFrame);
2779                 snd_printd(KERN_INFO "found format II with max.bitrate = %d, frame size=%d\n", brate, framesize);
2780                 fp->frame_size = framesize;
2781                 ret = parse_audio_format_rates_v2(chip, fp, iface);
2782                 break;
2783         }
2784         }
2785
2786         return ret;
2787 }
2788
2789 static int parse_audio_format(struct snd_usb_audio *chip, struct audioformat *fp,
2790                               int format, unsigned char *fmt, int stream,
2791                               struct usb_host_interface *iface)
2792 {
2793         int err;
2794
2795         switch (fmt[3]) {
2796         case USB_FORMAT_TYPE_I:
2797         case USB_FORMAT_TYPE_III:
2798                 err = parse_audio_format_i(chip, fp, format, fmt, iface);
2799                 break;
2800         case USB_FORMAT_TYPE_II:
2801                 err = parse_audio_format_ii(chip, fp, format, fmt, iface);
2802                 break;
2803         default:
2804                 snd_printd(KERN_INFO "%d:%u:%d : format type %d is not supported yet\n",
2805                            chip->dev->devnum, fp->iface, fp->altsetting, fmt[3]);
2806                 return -1;
2807         }
2808         fp->fmt_type = fmt[3];
2809         if (err < 0)
2810                 return err;
2811 #if 1
2812         /* FIXME: temporary hack for extigy/audigy 2 nx/zs */
2813         /* extigy apparently supports sample rates other than 48k
2814          * but not in ordinary way.  so we enable only 48k atm.
2815          */
2816         if (chip->usb_id == USB_ID(0x041e, 0x3000) ||
2817             chip->usb_id == USB_ID(0x041e, 0x3020) ||
2818             chip->usb_id == USB_ID(0x041e, 0x3061)) {
2819                 if (fmt[3] == USB_FORMAT_TYPE_I &&
2820                     fp->rates != SNDRV_PCM_RATE_48000 &&
2821                     fp->rates != SNDRV_PCM_RATE_96000)
2822                         return -1;
2823         }
2824 #endif
2825         return 0;
2826 }
2827
2828 static unsigned char parse_datainterval(struct snd_usb_audio *chip,
2829                                         struct usb_host_interface *alts)
2830 {
2831         if (snd_usb_get_speed(chip->dev) == USB_SPEED_HIGH &&
2832             get_endpoint(alts, 0)->bInterval >= 1 &&
2833             get_endpoint(alts, 0)->bInterval <= 4)
2834                 return get_endpoint(alts, 0)->bInterval - 1;
2835         else
2836                 return 0;
2837 }
2838
2839 static int audiophile_skip_setting_quirk(struct snd_usb_audio *chip,
2840                                          int iface, int altno);
2841 static int parse_audio_endpoints(struct snd_usb_audio *chip, int iface_no)
2842 {
2843         struct usb_device *dev;
2844         struct usb_interface *iface;
2845         struct usb_host_interface *alts;
2846         struct usb_interface_descriptor *altsd;
2847         int i, altno, err, stream;
2848         int format = 0, num_channels = 0;
2849         struct audioformat *fp = NULL;
2850         unsigned char *fmt, *csep;
2851         int num, protocol;
2852
2853         dev = chip->dev;
2854
2855         /* parse the interface's altsettings */
2856         iface = usb_ifnum_to_if(dev, iface_no);
2857
2858         num = iface->num_altsetting;
2859
2860         /*
2861          * Dallas DS4201 workaround: It presents 5 altsettings, but the last
2862          * one misses syncpipe, and does not produce any sound.
2863          */
2864         if (chip->usb_id == USB_ID(0x04fa, 0x4201))
2865                 num = 4;
2866
2867         for (i = 0; i < num; i++) {
2868                 alts = &iface->altsetting[i];
2869                 altsd = get_iface_desc(alts);
2870                 protocol = altsd->bInterfaceProtocol;
2871                 /* skip invalid one */
2872                 if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
2873                      altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
2874                     (altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIO_STREAMING &&
2875                      altsd->bInterfaceSubClass != USB_SUBCLASS_VENDOR_SPEC) ||
2876                     altsd->bNumEndpoints < 1 ||
2877                     le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize) == 0)
2878                         continue;
2879                 /* must be isochronous */
2880                 if ((get_endpoint(alts, 0)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
2881                     USB_ENDPOINT_XFER_ISOC)
2882                         continue;
2883                 /* check direction */
2884                 stream = (get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN) ?
2885                         SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
2886                 altno = altsd->bAlternateSetting;
2887         
2888                 /* audiophile usb: skip altsets incompatible with device_setup
2889                  */
2890                 if (chip->usb_id == USB_ID(0x0763, 0x2003) && 
2891                     audiophile_skip_setting_quirk(chip, iface_no, altno))
2892                         continue;
2893
2894                 /* get audio formats */
2895                 switch (protocol) {
2896                 case UAC_VERSION_1: {
2897                         struct uac_as_header_descriptor_v1 *as =
2898                                 snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, AS_GENERAL);
2899
2900                         if (!as) {
2901                                 snd_printk(KERN_ERR "%d:%u:%d : AS_GENERAL descriptor not found\n",
2902                                            dev->devnum, iface_no, altno);
2903                                 continue;
2904                         }
2905
2906                         if (as->bLength < sizeof(*as)) {
2907                                 snd_printk(KERN_ERR "%d:%u:%d : invalid AS_GENERAL desc\n",
2908                                            dev->devnum, iface_no, altno);
2909                                 continue;
2910                         }
2911
2912                         format = le16_to_cpu(as->wFormatTag); /* remember the format value */
2913                         break;
2914                 }
2915
2916                 case UAC_VERSION_2: {
2917                         struct uac_as_header_descriptor_v2 *as =
2918                                 snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, AS_GENERAL);
2919
2920                         if (!as) {
2921                                 snd_printk(KERN_ERR "%d:%u:%d : AS_GENERAL descriptor not found\n",
2922                                            dev->devnum, iface_no, altno);
2923                                 continue;
2924                         }
2925
2926                         if (as->bLength < sizeof(*as)) {
2927                                 snd_printk(KERN_ERR "%d:%u:%d : invalid AS_GENERAL desc\n",
2928                                            dev->devnum, iface_no, altno);
2929                                 continue;
2930                         }
2931
2932                         num_channels = as->bNrChannels;
2933                         format = le32_to_cpu(as->bmFormats);
2934
2935                         break;
2936                 }
2937
2938                 default:
2939                         snd_printk(KERN_ERR "%d:%u:%d : unknown interface protocol %04x\n",
2940                                    dev->devnum, iface_no, altno, protocol);
2941                         continue;
2942                 }
2943
2944                 /* get format type */
2945                 fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, FORMAT_TYPE);
2946                 if (!fmt) {
2947                         snd_printk(KERN_ERR "%d:%u:%d : no FORMAT_TYPE desc\n",
2948                                    dev->devnum, iface_no, altno);
2949                         continue;
2950                 }
2951                 if (((protocol == UAC_VERSION_1) && (fmt[0] < 8)) ||
2952                     ((protocol == UAC_VERSION_2) && (fmt[0] != 6))) {
2953                         snd_printk(KERN_ERR "%d:%u:%d : invalid FORMAT_TYPE desc\n",
2954                                    dev->devnum, iface_no, altno);
2955                         continue;
2956                 }
2957
2958                 /*
2959                  * Blue Microphones workaround: The last altsetting is identical
2960                  * with the previous one, except for a larger packet size, but
2961                  * is actually a mislabeled two-channel setting; ignore it.
2962                  */
2963                 if (fmt[4] == 1 && fmt[5] == 2 && altno == 2 && num == 3 &&
2964                     fp && fp->altsetting == 1 && fp->channels == 1 &&
2965                     fp->format == SNDRV_PCM_FORMAT_S16_LE &&
2966                     protocol == UAC_VERSION_1 &&
2967                     le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize) ==
2968                                                         fp->maxpacksize * 2)
2969                         continue;
2970
2971                 csep = snd_usb_find_desc(alts->endpoint[0].extra, alts->endpoint[0].extralen, NULL, USB_DT_CS_ENDPOINT);
2972                 /* Creamware Noah has this descriptor after the 2nd endpoint */
2973                 if (!csep && altsd->bNumEndpoints >= 2)
2974                         csep = snd_usb_find_desc(alts->endpoint[1].extra, alts->endpoint[1].extralen, NULL, USB_DT_CS_ENDPOINT);
2975                 if (!csep || csep[0] < 7 || csep[2] != EP_GENERAL) {
2976                         snd_printk(KERN_WARNING "%d:%u:%d : no or invalid"
2977                                    " class specific endpoint descriptor\n",
2978                                    dev->devnum, iface_no, altno);
2979                         csep = NULL;
2980                 }
2981
2982                 fp = kzalloc(sizeof(*fp), GFP_KERNEL);
2983                 if (! fp) {
2984                         snd_printk(KERN_ERR "cannot malloc\n");
2985                         return -ENOMEM;
2986                 }
2987
2988                 fp->iface = iface_no;
2989                 fp->altsetting = altno;
2990                 fp->altset_idx = i;
2991                 fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
2992                 fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
2993                 fp->datainterval = parse_datainterval(chip, alts);
2994                 fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
2995                 /* num_channels is only set for v2 interfaces */
2996                 fp->channels = num_channels;
2997                 if (snd_usb_get_speed(dev) == USB_SPEED_HIGH)
2998                         fp->maxpacksize = (((fp->maxpacksize >> 11) & 3) + 1)
2999                                         * (fp->maxpacksize & 0x7ff);
3000                 fp->attributes = csep ? csep[3] : 0;
3001
3002                 /* some quirks for attributes here */
3003
3004                 switch (chip->usb_id) {
3005                 case USB_ID(0x0a92, 0x0053): /* AudioTrak Optoplay */
3006                         /* Optoplay sets the sample rate attribute although
3007                          * it seems not supporting it in fact.
3008                          */
3009                         fp->attributes &= ~EP_CS_ATTR_SAMPLE_RATE;
3010                         break;
3011                 case USB_ID(0x041e, 0x3020): /* Creative SB Audigy 2 NX */
3012                 case USB_ID(0x0763, 0x2003): /* M-Audio Audiophile USB */
3013                         /* doesn't set the sample rate attribute, but supports it */
3014                         fp->attributes |= EP_CS_ATTR_SAMPLE_RATE;
3015                         break;
3016                 case USB_ID(0x047f, 0x0ca1): /* plantronics headset */
3017                 case USB_ID(0x077d, 0x07af): /* Griffin iMic (note that there is
3018                                                 an older model 77d:223) */
3019                 /*
3020                  * plantronics headset and Griffin iMic have set adaptive-in
3021                  * although it's really not...
3022                  */
3023                         fp->ep_attr &= ~EP_ATTR_MASK;
3024                         if (stream == SNDRV_PCM_STREAM_PLAYBACK)
3025                                 fp->ep_attr |= EP_ATTR_ADAPTIVE;
3026                         else
3027                                 fp->ep_attr |= EP_ATTR_SYNC;
3028                         break;
3029                 }
3030
3031                 /* ok, let's parse further... */
3032                 if (parse_audio_format(chip, fp, format, fmt, stream, alts) < 0) {
3033                         kfree(fp->rate_table);
3034                         kfree(fp);
3035                         continue;
3036                 }
3037
3038                 snd_printdd(KERN_INFO "%d:%u:%d: add audio endpoint %#x\n", dev->devnum, iface_no, altno, fp->endpoint);
3039                 err = add_audio_endpoint(chip, stream, fp);
3040                 if (err < 0) {
3041                         kfree(fp->rate_table);
3042                         kfree(fp);
3043                         return err;
3044                 }
3045                 /* try to set the interface... */
3046                 usb_set_interface(chip->dev, iface_no, altno);
3047                 init_usb_pitch(chip->dev, iface_no, alts, fp);
3048                 init_usb_sample_rate(chip->dev, iface_no, alts, fp, fp->rate_max);
3049         }
3050         return 0;
3051 }
3052
3053
3054 /*
3055  * disconnect streams
3056  * called from snd_usb_audio_disconnect()
3057  */
3058 static void snd_usb_stream_disconnect(struct list_head *head)
3059 {
3060         int idx;
3061         struct snd_usb_stream *as;
3062         struct snd_usb_substream *subs;
3063
3064         as = list_entry(head, struct snd_usb_stream, list);
3065         for (idx = 0; idx < 2; idx++) {
3066                 subs = &as->substream[idx];
3067                 if (!subs->num_formats)
3068                         return;
3069                 release_substream_urbs(subs, 1);
3070                 subs->interface = -1;
3071         }
3072 }
3073
3074 static int snd_usb_create_stream(struct snd_usb_audio *chip, int ctrlif, int interface)
3075 {
3076         struct usb_device *dev = chip->dev;
3077         struct usb_host_interface *alts;
3078         struct usb_interface_descriptor *altsd;
3079         struct usb_interface *iface = usb_ifnum_to_if(dev, interface);
3080
3081         if (!iface) {
3082                 snd_printk(KERN_ERR "%d:%u:%d : does not exist\n",
3083                            dev->devnum, ctrlif, interface);
3084                 return -EINVAL;
3085         }
3086
3087         if (usb_interface_claimed(iface)) {
3088                 snd_printdd(KERN_INFO "%d:%d:%d: skipping, already claimed\n",
3089                                                 dev->devnum, ctrlif, interface);
3090                 return -EINVAL;
3091         }
3092
3093         alts = &iface->altsetting[0];
3094         altsd = get_iface_desc(alts);
3095         if ((altsd->bInterfaceClass == USB_CLASS_AUDIO ||
3096              altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC) &&
3097             altsd->bInterfaceSubClass == USB_SUBCLASS_MIDI_STREAMING) {
3098                 int err = snd_usbmidi_create(chip->card, iface,
3099                                              &chip->midi_list, NULL);
3100                 if (err < 0) {
3101                         snd_printk(KERN_ERR "%d:%u:%d: cannot create sequencer device\n",
3102                                                 dev->devnum, ctrlif, interface);
3103                         return -EINVAL;
3104                 }
3105                 usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
3106
3107                 return 0;
3108         }
3109
3110         if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
3111              altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
3112             altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIO_STREAMING) {
3113                 snd_printdd(KERN_ERR "%d:%u:%d: skipping non-supported interface %d\n",
3114                                         dev->devnum, ctrlif, interface, altsd->bInterfaceClass);
3115                 /* skip non-supported classes */
3116                 return -EINVAL;
3117         }
3118
3119         if (snd_usb_get_speed(dev) == USB_SPEED_LOW) {
3120                 snd_printk(KERN_ERR "low speed audio streaming not supported\n");
3121                 return -EINVAL;
3122         }
3123
3124         if (! parse_audio_endpoints(chip, interface)) {
3125                 usb_set_interface(dev, interface, 0); /* reset the current interface */
3126                 usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
3127                 return -EINVAL;
3128         }
3129
3130         return 0;
3131 }
3132
3133 /*
3134  * parse audio control descriptor and create pcm/midi streams
3135  */
3136 static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)
3137 {
3138         struct usb_device *dev = chip->dev;
3139         struct usb_host_interface *host_iface;
3140         struct usb_interface_descriptor *altsd;
3141         void *control_header;
3142         int i, protocol;
3143
3144         /* find audiocontrol interface */
3145         host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];
3146         control_header = snd_usb_find_csint_desc(host_iface->extra,
3147                                                  host_iface->extralen,
3148                                                  NULL, HEADER);
3149         altsd = get_iface_desc(host_iface);
3150         protocol = altsd->bInterfaceProtocol;
3151
3152         if (!control_header) {
3153                 snd_printk(KERN_ERR "cannot find HEADER\n");
3154                 return -EINVAL;
3155         }
3156
3157         switch (protocol) {
3158         case UAC_VERSION_1: {
3159                 struct uac_ac_header_descriptor_v1 *h1 = control_header;
3160
3161                 if (!h1->bInCollection) {
3162                         snd_printk(KERN_INFO "skipping empty audio interface (v1)\n");
3163                         return -EINVAL;
3164                 }
3165
3166                 if (h1->bLength < sizeof(*h1) + h1->bInCollection) {
3167                         snd_printk(KERN_ERR "invalid HEADER (v1)\n");
3168                         return -EINVAL;
3169                 }
3170
3171                 for (i = 0; i < h1->bInCollection; i++)
3172                         snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);
3173
3174                 break;
3175         }
3176
3177         case UAC_VERSION_2: {
3178                 struct uac_clock_source_descriptor *cs;
3179                 struct usb_interface_assoc_descriptor *assoc =
3180                         usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
3181
3182                 if (!assoc) {
3183                         snd_printk(KERN_ERR "Audio class v2 interfaces need an interface association\n");
3184                         return -EINVAL;
3185                 }
3186
3187                 /* FIXME: for now, we expect there is at least one clock source
3188                  * descriptor and we always take the first one.
3189                  * We should properly support devices with multiple clock sources,
3190                  * clock selectors and sample rate conversion units. */
3191
3192                 cs = snd_usb_find_csint_desc(host_iface->extra, host_iface->extralen,
3193                                                 NULL, CLOCK_SOURCE);
3194
3195                 if (!cs) {
3196                         snd_printk(KERN_ERR "CLOCK_SOURCE descriptor not found\n");
3197                         return -EINVAL;
3198                 }
3199
3200                 chip->clock_id = cs->bClockID;
3201
3202                 for (i = 0; i < assoc->bInterfaceCount; i++) {
3203                         int intf = assoc->bFirstInterface + i;
3204
3205                         if (intf != ctrlif)
3206                                 snd_usb_create_stream(chip, ctrlif, intf);
3207                 }
3208
3209                 break;
3210         }
3211
3212         default:
3213                 snd_printk(KERN_ERR "unknown protocol version 0x%02x\n", protocol);
3214                 return -EINVAL;
3215         }
3216
3217         return 0;
3218 }
3219
3220 /*
3221  * create a stream for an endpoint/altsetting without proper descriptors
3222  */
3223 static int create_fixed_stream_quirk(struct snd_usb_audio *chip,
3224                                      struct usb_interface *iface,
3225                                      const struct snd_usb_audio_quirk *quirk)
3226 {
3227         struct audioformat *fp;
3228         struct usb_host_interface *alts;
3229         int stream, err;
3230         unsigned *rate_table = NULL;
3231
3232         fp = kmemdup(quirk->data, sizeof(*fp), GFP_KERNEL);
3233         if (! fp) {
3234                 snd_printk(KERN_ERR "cannot memdup\n");
3235                 return -ENOMEM;
3236         }
3237         if (fp->nr_rates > 0) {
3238                 rate_table = kmalloc(sizeof(int) * fp->nr_rates, GFP_KERNEL);
3239                 if (!rate_table) {
3240                         kfree(fp);
3241                         return -ENOMEM;
3242                 }
3243                 memcpy(rate_table, fp->rate_table, sizeof(int) * fp->nr_rates);
3244                 fp->rate_table = rate_table;
3245         }
3246
3247         stream = (fp->endpoint & USB_DIR_IN)
3248                 ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
3249         err = add_audio_endpoint(chip, stream, fp);
3250         if (err < 0) {
3251                 kfree(fp);
3252                 kfree(rate_table);
3253                 return err;
3254         }
3255         if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber ||
3256             fp->altset_idx >= iface->num_altsetting) {
3257                 kfree(fp);
3258                 kfree(rate_table);
3259                 return -EINVAL;
3260         }
3261         alts = &iface->altsetting[fp->altset_idx];
3262         fp->datainterval = parse_datainterval(chip, alts);
3263         fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
3264         usb_set_interface(chip->dev, fp->iface, 0);
3265         init_usb_pitch(chip->dev, fp->iface, alts, fp);
3266         init_usb_sample_rate(chip->dev, fp->iface, alts, fp, fp->rate_max);
3267         return 0;
3268 }
3269
3270 /*
3271  * create a stream for an interface with proper descriptors
3272  */
3273 static int create_standard_audio_quirk(struct snd_usb_audio *chip,
3274                                        struct usb_interface *iface,
3275                                        const struct snd_usb_audio_quirk *quirk)
3276 {
3277         struct usb_host_interface *alts;
3278         struct usb_interface_descriptor *altsd;
3279         int err;
3280
3281         alts = &iface->altsetting[0];
3282         altsd = get_iface_desc(alts);
3283         err = parse_audio_endpoints(chip, altsd->bInterfaceNumber);
3284         if (err < 0) {
3285                 snd_printk(KERN_ERR "cannot setup if %d: error %d\n",
3286                            altsd->bInterfaceNumber, err);
3287                 return err;
3288         }
3289         /* reset the current interface */
3290         usb_set_interface(chip->dev, altsd->bInterfaceNumber, 0);
3291         return 0;
3292 }
3293
3294 /*
3295  * Create a stream for an Edirol UA-700/UA-25/UA-4FX interface.  
3296  * The only way to detect the sample rate is by looking at wMaxPacketSize.
3297  */
3298 static int create_uaxx_quirk(struct snd_usb_audio *chip,
3299                               struct usb_interface *iface,
3300                               const struct snd_usb_audio_quirk *quirk)
3301 {
3302         static const struct audioformat ua_format = {
3303                 .format = SNDRV_PCM_FORMAT_S24_3LE,
3304                 .channels = 2,
3305                 .fmt_type = USB_FORMAT_TYPE_I,
3306                 .altsetting = 1,
3307                 .altset_idx = 1,
3308                 .rates = SNDRV_PCM_RATE_CONTINUOUS,
3309         };
3310         struct usb_host_interface *alts;
3311         struct usb_interface_descriptor *altsd;
3312         struct audioformat *fp;
3313         int stream, err;
3314
3315         /* both PCM and MIDI interfaces have 2 or more altsettings */
3316         if (iface->num_altsetting < 2)
3317                 return -ENXIO;
3318         alts = &iface->altsetting[1];
3319         altsd = get_iface_desc(alts);
3320
3321         if (altsd->bNumEndpoints == 2) {
3322                 static const struct snd_usb_midi_endpoint_info ua700_ep = {
3323                         .out_cables = 0x0003,
3324                         .in_cables  = 0x0003
3325                 };
3326                 static const struct snd_usb_audio_quirk ua700_quirk = {
3327                         .type = QUIRK_MIDI_FIXED_ENDPOINT,
3328                         .data = &ua700_ep
3329                 };
3330                 static const struct snd_usb_midi_endpoint_info uaxx_ep = {
3331                         .out_cables = 0x0001,
3332                         .in_cables  = 0x0001
3333                 };
3334                 static const struct snd_usb_audio_quirk uaxx_quirk = {
3335                         .type = QUIRK_MIDI_FIXED_ENDPOINT,
3336                         .data = &uaxx_ep
3337                 };
3338                 const struct snd_usb_audio_quirk *quirk =
3339                         chip->usb_id == USB_ID(0x0582, 0x002b)
3340                         ? &ua700_quirk : &uaxx_quirk;
3341                 return snd_usbmidi_create(chip->card, iface,
3342                                           &chip->midi_list, quirk);
3343         }
3344
3345         if (altsd->bNumEndpoints != 1)
3346                 return -ENXIO;
3347
3348         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
3349         if (!fp)
3350                 return -ENOMEM;
3351         memcpy(fp, &ua_format, sizeof(*fp));
3352
3353         fp->iface = altsd->bInterfaceNumber;
3354         fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
3355         fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
3356         fp->datainterval = 0;
3357         fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
3358
3359         switch (fp->maxpacksize) {
3360         case 0x120:
3361                 fp->rate_max = fp->rate_min = 44100;
3362                 break;
3363         case 0x138:
3364         case 0x140:
3365                 fp->rate_max = fp->rate_min = 48000;
3366                 break;
3367         case 0x258:
3368         case 0x260:
3369                 fp->rate_max = fp->rate_min = 96000;
3370                 break;
3371         default:
3372                 snd_printk(KERN_ERR "unknown sample rate\n");
3373                 kfree(fp);
3374                 return -ENXIO;
3375         }
3376
3377         stream = (fp->endpoint & USB_DIR_IN)
3378                 ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
3379         err = add_audio_endpoint(chip, stream, fp);
3380         if (err < 0) {
3381                 kfree(fp);
3382                 return err;
3383         }
3384         usb_set_interface(chip->dev, fp->iface, 0);
3385         return 0;
3386 }
3387
3388 /*
3389  * Create a stream for an Edirol UA-1000 interface.
3390  */
3391 static int create_ua1000_quirk(struct snd_usb_audio *chip,
3392                                struct usb_interface *iface,
3393                                const struct snd_usb_audio_quirk *quirk)
3394 {
3395         static const struct audioformat ua1000_format = {
3396                 .format = SNDRV_PCM_FORMAT_S32_LE,
3397                 .fmt_type = USB_FORMAT_TYPE_I,
3398                 .altsetting = 1,
3399                 .altset_idx = 1,
3400                 .attributes = 0,
3401                 .rates = SNDRV_PCM_RATE_CONTINUOUS,
3402         };
3403         struct usb_host_interface *alts;
3404         struct usb_interface_descriptor *altsd;
3405         struct audioformat *fp;
3406         int stream, err;
3407
3408         if (iface->num_altsetting != 2)
3409                 return -ENXIO;
3410         alts = &iface->altsetting[1];
3411         altsd = get_iface_desc(alts);
3412         if (alts->extralen != 11 || alts->extra[1] != USB_DT_CS_INTERFACE ||
3413             altsd->bNumEndpoints != 1)
3414                 return -ENXIO;
3415
3416         fp = kmemdup(&ua1000_format, sizeof(*fp), GFP_KERNEL);
3417         if (!fp)
3418                 return -ENOMEM;
3419
3420         fp->channels = alts->extra[4];
3421         fp->iface = altsd->bInterfaceNumber;
3422         fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
3423         fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
3424         fp->datainterval = parse_datainterval(chip, alts);
3425         fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
3426         fp->rate_max = fp->rate_min = combine_triple(&alts->extra[8]);
3427
3428         stream = (fp->endpoint & USB_DIR_IN)
3429                 ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
3430         err = add_audio_endpoint(chip, stream, fp);
3431         if (err < 0) {
3432                 kfree(fp);
3433                 return err;
3434         }
3435         /* FIXME: playback must be synchronized to capture */
3436         usb_set_interface(chip->dev, fp->iface, 0);
3437         return 0;
3438 }
3439
3440 static int snd_usb_create_quirk(struct snd_usb_audio *chip,
3441                                 struct usb_interface *iface,
3442                                 const struct snd_usb_audio_quirk *quirk);
3443
3444 /*
3445  * handle the quirks for the contained interfaces
3446  */
3447 static int create_composite_quirk(struct snd_usb_audio *chip,
3448                                   struct usb_interface *iface,
3449                                   const struct snd_usb_audio_quirk *quirk)
3450 {
3451         int probed_ifnum = get_iface_desc(iface->altsetting)->bInterfaceNumber;
3452         int err;
3453
3454         for (quirk = quirk->data; quirk->ifnum >= 0; ++quirk) {
3455                 iface = usb_ifnum_to_if(chip->dev, quirk->ifnum);
3456                 if (!iface)
3457                         continue;
3458                 if (quirk->ifnum != probed_ifnum &&
3459                     usb_interface_claimed(iface))
3460                         continue;
3461                 err = snd_usb_create_quirk(chip, iface, quirk);
3462                 if (err < 0)
3463                         return err;
3464                 if (quirk->ifnum != probed_ifnum)
3465                         usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
3466         }
3467         return 0;
3468 }
3469
3470 static int ignore_interface_quirk(struct snd_usb_audio *chip,
3471                                   struct usb_interface *iface,
3472                                   const struct snd_usb_audio_quirk *quirk)
3473 {
3474         return 0;
3475 }
3476
3477 /*
3478  * Allow alignment on audio sub-slot (channel samples) rather than
3479  * on audio slots (audio frames)
3480  */
3481 static int create_align_transfer_quirk(struct snd_usb_audio *chip,
3482                                   struct usb_interface *iface,
3483                                   const struct snd_usb_audio_quirk *quirk)
3484 {
3485         chip->txfr_quirk = 1;
3486         return 1;       /* Continue with creating streams and mixer */
3487 }
3488
3489
3490 /*
3491  * boot quirks
3492  */
3493
3494 #define EXTIGY_FIRMWARE_SIZE_OLD 794
3495 #define EXTIGY_FIRMWARE_SIZE_NEW 483
3496
3497 static int snd_usb_extigy_boot_quirk(struct usb_device *dev, struct usb_interface *intf)
3498 {
3499         struct usb_host_config *config = dev->actconfig;
3500         int err;
3501
3502         if (le16_to_cpu(get_cfg_desc(config)->wTotalLength) == EXTIGY_FIRMWARE_SIZE_OLD ||
3503             le16_to_cpu(get_cfg_desc(config)->wTotalLength) == EXTIGY_FIRMWARE_SIZE_NEW) {
3504                 snd_printdd("sending Extigy boot sequence...\n");
3505                 /* Send message to force it to reconnect with full interface. */
3506                 err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev,0),
3507                                       0x10, 0x43, 0x0001, 0x000a, NULL, 0, 1000);
3508                 if (err < 0) snd_printdd("error sending boot message: %d\n", err);
3509                 err = usb_get_descriptor(dev, USB_DT_DEVICE, 0,
3510                                 &dev->descriptor, sizeof(dev->descriptor));
3511                 config = dev->actconfig;
3512                 if (err < 0) snd_printdd("error usb_get_descriptor: %d\n", err);
3513                 err = usb_reset_configuration(dev);
3514                 if (err < 0) snd_printdd("error usb_reset_configuration: %d\n", err);
3515                 snd_printdd("extigy_boot: new boot length = %d\n",
3516                             le16_to_cpu(get_cfg_desc(config)->wTotalLength));
3517                 return -ENODEV; /* quit this anyway */
3518         }
3519         return 0;
3520 }
3521
3522 static int snd_usb_audigy2nx_boot_quirk(struct usb_device *dev)
3523 {
3524         u8 buf = 1;
3525
3526         snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), 0x2a,
3527                         USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_OTHER,
3528                         0, 0, &buf, 1, 1000);
3529         if (buf == 0) {
3530                 snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0x29,
3531                                 USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_OTHER,
3532                                 1, 2000, NULL, 0, 1000);
3533                 return -ENODEV;
3534         }
3535         return 0;
3536 }
3537
3538 /*
3539  * C-Media CM106/CM106+ have four 16-bit internal registers that are nicely
3540  * documented in the device's data sheet.
3541  */
3542 static int snd_usb_cm106_write_int_reg(struct usb_device *dev, int reg, u16 value)
3543 {
3544         u8 buf[4];
3545         buf[0] = 0x20;
3546         buf[1] = value & 0xff;
3547         buf[2] = (value >> 8) & 0xff;
3548         buf[3] = reg;
3549         return snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), USB_REQ_SET_CONFIGURATION,
3550                                USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT,
3551                                0, 0, &buf, 4, 1000);
3552 }
3553
3554 static int snd_usb_cm106_boot_quirk(struct usb_device *dev)
3555 {
3556         /*
3557          * Enable line-out driver mode, set headphone source to front
3558          * channels, enable stereo mic.
3559          */
3560         return snd_usb_cm106_write_int_reg(dev, 2, 0x8004);
3561 }
3562
3563 /*
3564  * C-Media CM6206 is based on CM106 with two additional
3565  * registers that are not documented in the data sheet.
3566  * Values here are chosen based on sniffing USB traffic
3567  * under Windows.
3568  */
3569 static int snd_usb_cm6206_boot_quirk(struct usb_device *dev)
3570 {
3571         int err, reg;
3572         int val[] = {0x200c, 0x3000, 0xf800, 0x143f, 0x0000, 0x3000};
3573
3574         for (reg = 0; reg < ARRAY_SIZE(val); reg++) {
3575                 err = snd_usb_cm106_write_int_reg(dev, reg, val[reg]);
3576                 if (err < 0)
3577                         return err;
3578         }
3579
3580         return err;
3581 }
3582
3583 /*
3584  * This call will put the synth in "USB send" mode, i.e it will send MIDI
3585  * messages through USB (this is disabled at startup). The synth will
3586  * acknowledge by sending a sysex on endpoint 0x85 and by displaying a USB
3587  * sign on its LCD. Values here are chosen based on sniffing USB traffic
3588  * under Windows.
3589  */
3590 static int snd_usb_accessmusic_boot_quirk(struct usb_device *dev)
3591 {
3592         int err, actual_length;
3593
3594         /* "midi send" enable */
3595         static const u8 seq[] = { 0x4e, 0x73, 0x52, 0x01 };
3596
3597         void *buf = kmemdup(seq, ARRAY_SIZE(seq), GFP_KERNEL);
3598         if (!buf)
3599                 return -ENOMEM;
3600         err = usb_interrupt_msg(dev, usb_sndintpipe(dev, 0x05), buf,
3601                         ARRAY_SIZE(seq), &actual_length, 1000);
3602         kfree(buf);
3603         if (err < 0)
3604                 return err;
3605
3606         return 0;
3607 }
3608
3609 /*
3610  * Setup quirks
3611  */
3612 #define AUDIOPHILE_SET                  0x01 /* if set, parse device_setup */
3613 #define AUDIOPHILE_SET_DTS              0x02 /* if set, enable DTS Digital Output */
3614 #define AUDIOPHILE_SET_96K              0x04 /* 48-96KHz rate if set, 8-48KHz otherwise */
3615 #define AUDIOPHILE_SET_24B              0x08 /* 24bits sample if set, 16bits otherwise */
3616 #define AUDIOPHILE_SET_DI               0x10 /* if set, enable Digital Input */
3617 #define AUDIOPHILE_SET_MASK             0x1F /* bit mask for setup value */
3618 #define AUDIOPHILE_SET_24B_48K_DI       0x19 /* value for 24bits+48KHz+Digital Input */
3619 #define AUDIOPHILE_SET_24B_48K_NOTDI    0x09 /* value for 24bits+48KHz+No Digital Input */
3620 #define AUDIOPHILE_SET_16B_48K_DI       0x11 /* value for 16bits+48KHz+Digital Input */
3621 #define AUDIOPHILE_SET_16B_48K_NOTDI    0x01 /* value for 16bits+48KHz+No Digital Input */
3622
3623 static int audiophile_skip_setting_quirk(struct snd_usb_audio *chip,
3624                                          int iface, int altno)
3625 {
3626         /* Reset ALL ifaces to 0 altsetting.
3627          * Call it for every possible altsetting of every interface.
3628          */
3629         usb_set_interface(chip->dev, iface, 0);
3630
3631         if (device_setup[chip->index] & AUDIOPHILE_SET) {
3632                 if ((device_setup[chip->index] & AUDIOPHILE_SET_DTS)
3633                     && altno != 6)
3634                         return 1; /* skip this altsetting */
3635                 if ((device_setup[chip->index] & AUDIOPHILE_SET_96K)
3636                     && altno != 1)
3637                         return 1; /* skip this altsetting */
3638                 if ((device_setup[chip->index] & AUDIOPHILE_SET_MASK) ==
3639                     AUDIOPHILE_SET_24B_48K_DI && altno != 2)
3640                         return 1; /* skip this altsetting */
3641                 if ((device_setup[chip->index] & AUDIOPHILE_SET_MASK) ==
3642                     AUDIOPHILE_SET_24B_48K_NOTDI && altno != 3)
3643                         return 1; /* skip this altsetting */
3644                 if ((device_setup[chip->index] & AUDIOPHILE_SET_MASK) ==
3645                     AUDIOPHILE_SET_16B_48K_DI && altno != 4)
3646                         return 1; /* skip this altsetting */
3647                 if ((device_setup[chip->index] & AUDIOPHILE_SET_MASK) ==
3648                     AUDIOPHILE_SET_16B_48K_NOTDI && altno != 5)
3649                         return 1; /* skip this altsetting */
3650         }       
3651         return 0; /* keep this altsetting */
3652 }
3653
3654 static int create_any_midi_quirk(struct snd_usb_audio *chip,
3655                                  struct usb_interface *intf,
3656                                  const struct snd_usb_audio_quirk *quirk)
3657 {
3658         return snd_usbmidi_create(chip->card, intf, &chip->midi_list, quirk);
3659 }
3660
3661 /*
3662  * audio-interface quirks
3663  *
3664  * returns zero if no standard audio/MIDI parsing is needed.
3665  * returns a postive value if standard audio/midi interfaces are parsed
3666  * after this.
3667  * returns a negative value at error.
3668  */
3669 static int snd_usb_create_quirk(struct snd_usb_audio *chip,
3670                                 struct usb_interface *iface,
3671                                 const struct snd_usb_audio_quirk *quirk)
3672 {
3673         typedef int (*quirk_func_t)(struct snd_usb_audio *, struct usb_interface *,
3674                                     const struct snd_usb_audio_quirk *);
3675         static const quirk_func_t quirk_funcs[] = {
3676                 [QUIRK_IGNORE_INTERFACE] = ignore_interface_quirk,
3677                 [QUIRK_COMPOSITE] = create_composite_quirk,
3678                 [QUIRK_MIDI_STANDARD_INTERFACE] = create_any_midi_quirk,
3679                 [QUIRK_MIDI_FIXED_ENDPOINT] = create_any_midi_quirk,
3680                 [QUIRK_MIDI_YAMAHA] = create_any_midi_quirk,
3681                 [QUIRK_MIDI_MIDIMAN] = create_any_midi_quirk,
3682                 [QUIRK_MIDI_NOVATION] = create_any_midi_quirk,
3683                 [QUIRK_MIDI_FASTLANE] = create_any_midi_quirk,
3684                 [QUIRK_MIDI_EMAGIC] = create_any_midi_quirk,
3685                 [QUIRK_MIDI_CME] = create_any_midi_quirk,
3686                 [QUIRK_AUDIO_STANDARD_INTERFACE] = create_standard_audio_quirk,
3687                 [QUIRK_AUDIO_FIXED_ENDPOINT] = create_fixed_stream_quirk,
3688                 [QUIRK_AUDIO_EDIROL_UA1000] = create_ua1000_quirk,
3689                 [QUIRK_AUDIO_EDIROL_UAXX] = create_uaxx_quirk,
3690                 [QUIRK_AUDIO_ALIGN_TRANSFER] = create_align_transfer_quirk
3691         };
3692
3693         if (quirk->type < QUIRK_TYPE_COUNT) {
3694                 return quirk_funcs[quirk->type](chip, iface, quirk);
3695         } else {
3696                 snd_printd(KERN_ERR "invalid quirk type %d\n", quirk->type);
3697                 return -ENXIO;
3698         }
3699 }
3700
3701
3702 /*
3703  * common proc files to show the usb device info
3704  */
3705 static void proc_audio_usbbus_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer)
3706 {
3707         struct snd_usb_audio *chip = entry->private_data;
3708         if (!chip->shutdown)
3709                 snd_iprintf(buffer, "%03d/%03d\n", chip->dev->bus->busnum, chip->dev->devnum);
3710 }
3711
3712 static void proc_audio_usbid_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer)
3713 {
3714         struct snd_usb_audio *chip = entry->private_data;
3715         if (!chip->shutdown)
3716                 snd_iprintf(buffer, "%04x:%04x\n", 
3717                             USB_ID_VENDOR(chip->usb_id),
3718                             USB_ID_PRODUCT(chip->usb_id));
3719 }
3720
3721 static void snd_usb_audio_create_proc(struct snd_usb_audio *chip)
3722 {
3723         struct snd_info_entry *entry;
3724         if (!snd_card_proc_new(chip->card, "usbbus", &entry))
3725                 snd_info_set_text_ops(entry, chip, proc_audio_usbbus_read);
3726         if (!snd_card_proc_new(chip->card, "usbid", &entry))
3727                 snd_info_set_text_ops(entry, chip, proc_audio_usbid_read);
3728 }
3729
3730 /*
3731  * free the chip instance
3732  *
3733  * here we have to do not much, since pcm and controls are already freed
3734  *
3735  */
3736
3737 static int snd_usb_audio_free(struct snd_usb_audio *chip)
3738 {
3739         kfree(chip);
3740         return 0;
3741 }
3742
3743 static int snd_usb_audio_dev_free(struct snd_device *device)
3744 {
3745         struct snd_usb_audio *chip = device->device_data;
3746         return snd_usb_audio_free(chip);
3747 }
3748
3749
3750 /*
3751  * create a chip instance and set its names.
3752  */
3753 static int snd_usb_audio_create(struct usb_device *dev, int idx,
3754                                 const struct snd_usb_audio_quirk *quirk,
3755                                 struct snd_usb_audio **rchip)
3756 {
3757         struct snd_card *card;
3758         struct snd_usb_audio *chip;
3759         int err, len;
3760         char component[14];
3761         static struct snd_device_ops ops = {
3762                 .dev_free =     snd_usb_audio_dev_free,
3763         };
3764
3765         *rchip = NULL;
3766
3767         if (snd_usb_get_speed(dev) != USB_SPEED_LOW &&
3768             snd_usb_get_speed(dev) != USB_SPEED_FULL &&
3769             snd_usb_get_speed(dev) != USB_SPEED_HIGH) {
3770                 snd_printk(KERN_ERR "unknown device speed %d\n", snd_usb_get_speed(dev));
3771                 return -ENXIO;
3772         }
3773
3774         err = snd_card_create(index[idx], id[idx], THIS_MODULE, 0, &card);
3775         if (err < 0) {
3776                 snd_printk(KERN_ERR "cannot create card instance %d\n", idx);
3777                 return err;
3778         }
3779
3780         chip = kzalloc(sizeof(*chip), GFP_KERNEL);
3781         if (! chip) {
3782                 snd_card_free(card);
3783                 return -ENOMEM;
3784         }
3785
3786         chip->index = idx;
3787         chip->dev = dev;
3788         chip->card = card;
3789         chip->usb_id = USB_ID(le16_to_cpu(dev->descriptor.idVendor),
3790                               le16_to_cpu(dev->descriptor.idProduct));
3791         INIT_LIST_HEAD(&chip->pcm_list);
3792         INIT_LIST_HEAD(&chip->midi_list);
3793         INIT_LIST_HEAD(&chip->mixer_list);
3794
3795         if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
3796                 snd_usb_audio_free(chip);
3797                 snd_card_free(card);
3798                 return err;
3799         }
3800
3801         strcpy(card->driver, "USB-Audio");
3802         sprintf(component, "USB%04x:%04x",
3803                 USB_ID_VENDOR(chip->usb_id), USB_ID_PRODUCT(chip->usb_id));
3804         snd_component_add(card, component);
3805
3806         /* retrieve the device string as shortname */
3807         if (quirk && quirk->product_name) {
3808                 strlcpy(card->shortname, quirk->product_name, sizeof(card->shortname));
3809         } else {
3810                 if (!dev->descriptor.iProduct ||
3811                     usb_string(dev, dev->descriptor.iProduct,
3812                                card->shortname, sizeof(card->shortname)) <= 0) {
3813                         /* no name available from anywhere, so use ID */
3814                         sprintf(card->shortname, "USB Device %#04x:%#04x",
3815                                 USB_ID_VENDOR(chip->usb_id),
3816                                 USB_ID_PRODUCT(chip->usb_id));
3817                 }
3818         }
3819
3820         /* retrieve the vendor and device strings as longname */
3821         if (quirk && quirk->vendor_name) {
3822                 len = strlcpy(card->longname, quirk->vendor_name, sizeof(card->longname));
3823         } else {
3824                 if (dev->descriptor.iManufacturer)
3825                         len = usb_string(dev, dev->descriptor.iManufacturer,
3826                                          card->longname, sizeof(card->longname));
3827                 else
3828                         len = 0;
3829                 /* we don't really care if there isn't any vendor string */
3830         }
3831         if (len > 0)
3832                 strlcat(card->longname, " ", sizeof(card->longname));
3833
3834         strlcat(card->longname, card->shortname, sizeof(card->longname));
3835
3836         len = strlcat(card->longname, " at ", sizeof(card->longname));
3837
3838         if (len < sizeof(card->longname))
3839                 usb_make_path(dev, card->longname + len, sizeof(card->longname) - len);
3840
3841         strlcat(card->longname,
3842                 snd_usb_get_speed(dev) == USB_SPEED_LOW ? ", low speed" :
3843                 snd_usb_get_speed(dev) == USB_SPEED_FULL ? ", full speed" :
3844                 ", high speed",
3845                 sizeof(card->longname));
3846
3847         snd_usb_audio_create_proc(chip);
3848
3849         *rchip = chip;
3850         return 0;
3851 }
3852
3853
3854 /*
3855  * probe the active usb device
3856  *
3857  * note that this can be called multiple times per a device, when it
3858  * includes multiple audio control interfaces.
3859  *
3860  * thus we check the usb device pointer and creates the card instance
3861  * only at the first time.  the successive calls of this function will
3862  * append the pcm interface to the corresponding card.
3863  */
3864 static void *snd_usb_audio_probe(struct usb_device *dev,
3865                                  struct usb_interface *intf,
3866                                  const struct usb_device_id *usb_id)
3867 {
3868         const struct snd_usb_audio_quirk *quirk = (const struct snd_usb_audio_quirk *)usb_id->driver_info;
3869         int i, err;
3870         struct snd_usb_audio *chip;
3871         struct usb_host_interface *alts;
3872         int ifnum;
3873         u32 id;
3874
3875         alts = &intf->altsetting[0];
3876         ifnum = get_iface_desc(alts)->bInterfaceNumber;
3877         id = USB_ID(le16_to_cpu(dev->descriptor.idVendor),
3878                     le16_to_cpu(dev->descriptor.idProduct));
3879         if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)
3880                 goto __err_val;
3881
3882         /* SB Extigy needs special boot-up sequence */
3883         /* if more models come, this will go to the quirk list. */
3884         if (id == USB_ID(0x041e, 0x3000)) {
3885                 if (snd_usb_extigy_boot_quirk(dev, intf) < 0)
3886                         goto __err_val;
3887         }
3888         /* SB Audigy 2 NX needs its own boot-up magic, too */
3889         if (id == USB_ID(0x041e, 0x3020)) {
3890                 if (snd_usb_audigy2nx_boot_quirk(dev) < 0)
3891                         goto __err_val;
3892         }
3893
3894         /* C-Media CM106 / Turtle Beach Audio Advantage Roadie */
3895         if (id == USB_ID(0x10f5, 0x0200)) {
3896                 if (snd_usb_cm106_boot_quirk(dev) < 0)
3897                         goto __err_val;
3898         }
3899
3900         /* C-Media CM6206 / CM106-Like Sound Device */
3901         if (id == USB_ID(0x0d8c, 0x0102)) {
3902                 if (snd_usb_cm6206_boot_quirk(dev) < 0)
3903                         goto __err_val;
3904         }
3905
3906         /* Access Music VirusTI Desktop */
3907         if (id == USB_ID(0x133e, 0x0815)) {
3908                 if (snd_usb_accessmusic_boot_quirk(dev) < 0)
3909                         goto __err_val;
3910         }
3911
3912         /*
3913          * found a config.  now register to ALSA
3914          */
3915
3916         /* check whether it's already registered */
3917         chip = NULL;
3918         mutex_lock(&register_mutex);
3919         for (i = 0; i < SNDRV_CARDS; i++) {
3920                 if (usb_chip[i] && usb_chip[i]->dev == dev) {
3921                         if (usb_chip[i]->shutdown) {
3922                                 snd_printk(KERN_ERR "USB device is in the shutdown state, cannot create a card instance\n");
3923                                 goto __error;
3924                         }
3925                         chip = usb_chip[i];
3926                         break;
3927                 }
3928         }
3929         if (! chip) {
3930                 /* it's a fresh one.
3931                  * now look for an empty slot and create a new card instance
3932                  */
3933                 for (i = 0; i < SNDRV_CARDS; i++)
3934                         if (enable[i] && ! usb_chip[i] &&
3935                             (vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&
3936                             (pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {
3937                                 if (snd_usb_audio_create(dev, i, quirk, &chip) < 0) {
3938                                         goto __error;
3939                                 }
3940                                 snd_card_set_dev(chip->card, &intf->dev);
3941                                 break;
3942                         }
3943                 if (!chip) {
3944                         printk(KERN_ERR "no available usb audio device\n");
3945                         goto __error;
3946                 }
3947         }
3948
3949         chip->txfr_quirk = 0;
3950         err = 1; /* continue */
3951         if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {
3952                 /* need some special handlings */
3953                 if ((err = snd_usb_create_quirk(chip, intf, quirk)) < 0)
3954                         goto __error;
3955         }
3956
3957         if (err > 0) {
3958                 /* create normal USB audio interfaces */
3959                 if (snd_usb_create_streams(chip, ifnum) < 0 ||
3960                     snd_usb_create_mixer(chip, ifnum, ignore_ctl_error) < 0) {
3961                         goto __error;
3962                 }
3963         }
3964
3965         /* we are allowed to call snd_card_register() many times */
3966         if (snd_card_register(chip->card) < 0) {
3967                 goto __error;
3968         }
3969
3970         usb_chip[chip->index] = chip;
3971         chip->num_interfaces++;
3972         mutex_unlock(&register_mutex);
3973         return chip;
3974
3975  __error:
3976         if (chip && !chip->num_interfaces)
3977                 snd_card_free(chip->card);
3978         mutex_unlock(&register_mutex);
3979  __err_val:
3980         return NULL;
3981 }
3982
3983 /*
3984  * we need to take care of counter, since disconnection can be called also
3985  * many times as well as usb_audio_probe().
3986  */
3987 static void snd_usb_audio_disconnect(struct usb_device *dev, void *ptr)
3988 {
3989         struct snd_usb_audio *chip;
3990         struct snd_card *card;
3991         struct list_head *p;
3992
3993         if (ptr == (void *)-1L)
3994                 return;
3995
3996         chip = ptr;
3997         card = chip->card;
3998         mutex_lock(&register_mutex);
3999         chip->shutdown = 1;
4000         chip->num_interfaces--;
4001         if (chip->num_interfaces <= 0) {
4002                 snd_card_disconnect(card);
4003                 /* release the pcm resources */
4004                 list_for_each(p, &chip->pcm_list) {
4005                         snd_usb_stream_disconnect(p);
4006                 }
4007                 /* release the midi resources */
4008                 list_for_each(p, &chip->midi_list) {
4009                         snd_usbmidi_disconnect(p);
4010                 }
4011                 /* release mixer resources */
4012                 list_for_each(p, &chip->mixer_list) {
4013                         snd_usb_mixer_disconnect(p);
4014                 }
4015                 usb_chip[chip->index] = NULL;
4016                 mutex_unlock(&register_mutex);
4017                 snd_card_free_when_closed(card);
4018         } else {
4019                 mutex_unlock(&register_mutex);
4020         }
4021 }
4022
4023 /*
4024  * new 2.5 USB kernel API
4025  */
4026 static int usb_audio_probe(struct usb_interface *intf,
4027                            const struct usb_device_id *id)
4028 {
4029         void *chip;
4030         chip = snd_usb_audio_probe(interface_to_usbdev(intf), intf, id);
4031         if (chip) {
4032                 usb_set_intfdata(intf, chip);
4033                 return 0;
4034         } else
4035                 return -EIO;
4036 }
4037
4038 static void usb_audio_disconnect(struct usb_interface *intf)
4039 {
4040         snd_usb_audio_disconnect(interface_to_usbdev(intf),
4041                                  usb_get_intfdata(intf));
4042 }
4043
4044 #ifdef CONFIG_PM
4045 static int usb_audio_suspend(struct usb_interface *intf, pm_message_t message)
4046 {
4047         struct snd_usb_audio *chip = usb_get_intfdata(intf);
4048         struct list_head *p;
4049         struct snd_usb_stream *as;
4050
4051         if (chip == (void *)-1L)
4052                 return 0;
4053
4054         snd_power_change_state(chip->card, SNDRV_CTL_POWER_D3hot);
4055         if (!chip->num_suspended_intf++) {
4056                 list_for_each(p, &chip->pcm_list) {
4057                         as = list_entry(p, struct snd_usb_stream, list);
4058                         snd_pcm_suspend_all(as->pcm);
4059                 }
4060         }
4061
4062         return 0;
4063 }
4064
4065 static int usb_audio_resume(struct usb_interface *intf)
4066 {
4067         struct snd_usb_audio *chip = usb_get_intfdata(intf);
4068
4069         if (chip == (void *)-1L)
4070                 return 0;
4071         if (--chip->num_suspended_intf)
4072                 return 0;
4073         /*
4074          * ALSA leaves material resumption to user space
4075          * we just notify
4076          */
4077
4078         snd_power_change_state(chip->card, SNDRV_CTL_POWER_D0);
4079
4080         return 0;
4081 }
4082 #endif          /* CONFIG_PM */
4083
4084 static int __init snd_usb_audio_init(void)
4085 {
4086         if (nrpacks < 1 || nrpacks > MAX_PACKS) {
4087                 printk(KERN_WARNING "invalid nrpacks value.\n");
4088                 return -EINVAL;
4089         }
4090         return usb_register(&usb_audio_driver);
4091 }
4092
4093
4094 static void __exit snd_usb_audio_cleanup(void)
4095 {
4096         usb_deregister(&usb_audio_driver);
4097 }
4098
4099 module_init(snd_usb_audio_init);
4100 module_exit(snd_usb_audio_cleanup);