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