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