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