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