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