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