vserver 2.0-rc4
[linux-2.6.git] / sound / usb / usbaudio.c
1 /*
2  *   (Tentative) USB Audio Driver for ALSA
3  *
4  *   Main and PCM part
5  *
6  *   Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
7  *
8  *   Many codes borrowed from audio.c by
9  *          Alan Cox (alan@lxorguk.ukuu.org.uk)
10  *          Thomas Sailer (sailer@ife.ee.ethz.ch)
11  *
12  *
13  *   This program is free software; you can redistribute it and/or modify
14  *   it under the terms of the GNU General Public License as published by
15  *   the Free Software Foundation; either version 2 of the License, or
16  *   (at your option) any later version.
17  *
18  *   This program is distributed in the hope that it will be useful,
19  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *   GNU General Public License for more details.
22  *
23  *   You should have received a copy of the GNU General Public License
24  *   along with this program; if not, write to the Free Software
25  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
26  *
27  *
28  *  NOTES:
29  *
30  *   - async unlink should be used for avoiding the sleep inside lock.
31  *     2.4.22 usb-uhci seems buggy for async unlinking and results in
32  *     oops.  in such a cse, pass async_unlink=0 option.
33  *   - the linked URBs would be preferred but not used so far because of
34  *     the instability of unlinking.
35  *   - type II is not supported properly.  there is no device which supports
36  *     this type *correctly*.  SB extigy looks as if it supports, but it's
37  *     indeed an AC3 stream packed in SPDIF frames (i.e. no real AC3 stream).
38  */
39
40
41 #include <sound/driver.h>
42 #include <linux/bitops.h>
43 #include <linux/init.h>
44 #include <linux/list.h>
45 #include <linux/slab.h>
46 #include <linux/string.h>
47 #include <linux/usb.h>
48 #include <linux/moduleparam.h>
49 #include <sound/core.h>
50 #include <sound/info.h>
51 #include <sound/pcm.h>
52 #include <sound/pcm_params.h>
53 #include <sound/initval.h>
54
55 #include "usbaudio.h"
56
57
58 MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
59 MODULE_DESCRIPTION("USB Audio");
60 MODULE_LICENSE("GPL");
61 MODULE_SUPPORTED_DEVICE("{{Generic,USB Audio}}");
62
63
64 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;      /* Index 0-MAX */
65 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;       /* ID for this card */
66 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;      /* Enable this card */
67 static int vid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 }; /* Vendor ID for this card */
68 static int pid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 }; /* Product ID for this card */
69 static int nrpacks = 4;         /* max. number of packets per urb */
70 static int async_unlink = 1;
71
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                         if (snd_usb_get_speed(subs->dev) == USB_SPEED_HIGH)
1055                                 u->urb->interval = 8;
1056                         else
1057                                 u->urb->interval = 1;
1058                         u->urb->context = u;
1059                         u->urb->complete = snd_usb_complete_callback(snd_complete_sync_urb);
1060                 }
1061         }
1062         return 0;
1063 }
1064
1065
1066 /*
1067  * find a matching audio format
1068  */
1069 static struct audioformat *find_format(snd_usb_substream_t *subs, unsigned int format,
1070                                        unsigned int rate, unsigned int channels)
1071 {
1072         struct list_head *p;
1073         struct audioformat *found = NULL;
1074         int cur_attr = 0, attr;
1075
1076         list_for_each(p, &subs->fmt_list) {
1077                 struct audioformat *fp;
1078                 fp = list_entry(p, struct audioformat, list);
1079                 if (fp->format != format || fp->channels != channels)
1080                         continue;
1081                 if (rate < fp->rate_min || rate > fp->rate_max)
1082                         continue;
1083                 if (! (fp->rates & SNDRV_PCM_RATE_CONTINUOUS)) {
1084                         unsigned int i;
1085                         for (i = 0; i < fp->nr_rates; i++)
1086                                 if (fp->rate_table[i] == rate)
1087                                         break;
1088                         if (i >= fp->nr_rates)
1089                                 continue;
1090                 }
1091                 attr = fp->ep_attr & EP_ATTR_MASK;
1092                 if (! found) {
1093                         found = fp;
1094                         cur_attr = attr;
1095                         continue;
1096                 }
1097                 /* avoid async out and adaptive in if the other method
1098                  * supports the same format.
1099                  * this is a workaround for the case like
1100                  * M-audio audiophile USB.
1101                  */
1102                 if (attr != cur_attr) {
1103                         if ((attr == EP_ATTR_ASYNC &&
1104                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
1105                             (attr == EP_ATTR_ADAPTIVE &&
1106                              subs->direction == SNDRV_PCM_STREAM_CAPTURE))
1107                                 continue;
1108                         if ((cur_attr == EP_ATTR_ASYNC &&
1109                              subs->direction == SNDRV_PCM_STREAM_PLAYBACK) ||
1110                             (cur_attr == EP_ATTR_ADAPTIVE &&
1111                              subs->direction == SNDRV_PCM_STREAM_CAPTURE)) {
1112                                 found = fp;
1113                                 cur_attr = attr;
1114                                 continue;
1115                         }
1116                 }
1117                 /* find the format with the largest max. packet size */
1118                 if (fp->maxpacksize > found->maxpacksize) {
1119                         found = fp;
1120                         cur_attr = attr;
1121                 }
1122         }
1123         return found;
1124 }
1125
1126
1127 /*
1128  * initialize the picth control and sample rate
1129  */
1130 static int init_usb_pitch(struct usb_device *dev, int iface,
1131                           struct usb_host_interface *alts,
1132                           struct audioformat *fmt)
1133 {
1134         unsigned int ep;
1135         unsigned char data[1];
1136         int err;
1137
1138         ep = get_endpoint(alts, 0)->bEndpointAddress;
1139         /* if endpoint has pitch control, enable it */
1140         if (fmt->attributes & EP_CS_ATTR_PITCH_CONTROL) {
1141                 data[0] = 1;
1142                 if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR,
1143                                            USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
1144                                            PITCH_CONTROL << 8, ep, data, 1, HZ)) < 0) {
1145                         snd_printk(KERN_ERR "%d:%d:%d: cannot set enable PITCH\n",
1146                                    dev->devnum, iface, ep);
1147                         return err;
1148                 }
1149         }
1150         return 0;
1151 }
1152
1153 static int init_usb_sample_rate(struct usb_device *dev, int iface,
1154                                 struct usb_host_interface *alts,
1155                                 struct audioformat *fmt, int rate)
1156 {
1157         unsigned int ep;
1158         unsigned char data[3];
1159         int err;
1160
1161         ep = get_endpoint(alts, 0)->bEndpointAddress;
1162         /* if endpoint has sampling rate control, set it */
1163         if (fmt->attributes & EP_CS_ATTR_SAMPLE_RATE) {
1164                 int crate;
1165                 data[0] = rate;
1166                 data[1] = rate >> 8;
1167                 data[2] = rate >> 16;
1168                 if ((err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), SET_CUR,
1169                                            USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
1170                                            SAMPLING_FREQ_CONTROL << 8, ep, data, 3, HZ)) < 0) {
1171                         snd_printk(KERN_ERR "%d:%d:%d: cannot set freq %d to ep 0x%x\n",
1172                                    dev->devnum, iface, fmt->altsetting, rate, ep);
1173                         return err;
1174                 }
1175                 if ((err = snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), GET_CUR,
1176                                            USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_IN,
1177                                            SAMPLING_FREQ_CONTROL << 8, ep, data, 3, HZ)) < 0) {
1178                         snd_printk(KERN_WARNING "%d:%d:%d: cannot get freq at ep 0x%x\n",
1179                                    dev->devnum, iface, fmt->altsetting, ep);
1180                         return 0; /* some devices don't support reading */
1181                 }
1182                 crate = data[0] | (data[1] << 8) | (data[2] << 16);
1183                 if (crate != rate) {
1184                         snd_printd(KERN_WARNING "current rate %d is different from the runtime rate %d\n", crate, rate);
1185                         // runtime->rate = crate;
1186                 }
1187         }
1188         return 0;
1189 }
1190
1191 /*
1192  * find a matching format and set up the interface
1193  */
1194 static int set_format(snd_usb_substream_t *subs, struct audioformat *fmt)
1195 {
1196         struct usb_device *dev = subs->dev;
1197         struct usb_host_interface *alts;
1198         struct usb_interface_descriptor *altsd;
1199         struct usb_interface *iface;
1200         unsigned int ep, attr;
1201         int is_playback = subs->direction == SNDRV_PCM_STREAM_PLAYBACK;
1202         int err;
1203
1204         iface = usb_ifnum_to_if(dev, fmt->iface);
1205         snd_assert(iface, return -EINVAL);
1206         alts = &iface->altsetting[fmt->altset_idx];
1207         altsd = get_iface_desc(alts);
1208         snd_assert(altsd->bAlternateSetting == fmt->altsetting, return -EINVAL);
1209
1210         if (fmt == subs->cur_audiofmt)
1211                 return 0;
1212
1213         /* close the old interface */
1214         if (subs->interface >= 0 && subs->interface != fmt->iface) {
1215                 usb_set_interface(subs->dev, subs->interface, 0);
1216                 subs->interface = -1;
1217                 subs->format = 0;
1218         }
1219
1220         /* set interface */
1221         if (subs->interface != fmt->iface || subs->format != fmt->altset_idx) {
1222                 if (usb_set_interface(dev, fmt->iface, fmt->altsetting) < 0) {
1223                         snd_printk(KERN_ERR "%d:%d:%d: usb_set_interface failed\n",
1224                                    dev->devnum, fmt->iface, fmt->altsetting);
1225                         return -EIO;
1226                 }
1227                 snd_printdd(KERN_INFO "setting usb interface %d:%d\n", fmt->iface, fmt->altsetting);
1228                 subs->interface = fmt->iface;
1229                 subs->format = fmt->altset_idx;
1230         }
1231
1232         /* create a data pipe */
1233         ep = fmt->endpoint & USB_ENDPOINT_NUMBER_MASK;
1234         if (is_playback)
1235                 subs->datapipe = usb_sndisocpipe(dev, ep);
1236         else
1237                 subs->datapipe = usb_rcvisocpipe(dev, ep);
1238         subs->syncpipe = subs->syncinterval = 0;
1239         subs->maxpacksize = fmt->maxpacksize;
1240         subs->fill_max = 0;
1241
1242         /* we need a sync pipe in async OUT or adaptive IN mode */
1243         /* check the number of EP, since some devices have broken
1244          * descriptors which fool us.  if it has only one EP,
1245          * assume it as adaptive-out or sync-in.
1246          */
1247         attr = fmt->ep_attr & EP_ATTR_MASK;
1248         if (((is_playback && attr == EP_ATTR_ASYNC) ||
1249              (! is_playback && attr == EP_ATTR_ADAPTIVE)) &&
1250             altsd->bNumEndpoints >= 2) {
1251                 /* check sync-pipe endpoint */
1252                 /* ... and check descriptor size before accessing bSynchAddress
1253                    because there is a version of the SB Audigy 2 NX firmware lacking
1254                    the audio fields in the endpoint descriptors */
1255                 if ((get_endpoint(alts, 1)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != 0x01 ||
1256                     (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
1257                      get_endpoint(alts, 1)->bSynchAddress != 0)) {
1258                         snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
1259                                    dev->devnum, fmt->iface, fmt->altsetting);
1260                         return -EINVAL;
1261                 }
1262                 ep = get_endpoint(alts, 1)->bEndpointAddress;
1263                 if (get_endpoint(alts, 0)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
1264                     (( is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress | USB_DIR_IN)) ||
1265                      (!is_playback && ep != (unsigned int)(get_endpoint(alts, 0)->bSynchAddress & ~USB_DIR_IN)))) {
1266                         snd_printk(KERN_ERR "%d:%d:%d : invalid synch pipe\n",
1267                                    dev->devnum, fmt->iface, fmt->altsetting);
1268                         return -EINVAL;
1269                 }
1270                 ep &= USB_ENDPOINT_NUMBER_MASK;
1271                 if (is_playback)
1272                         subs->syncpipe = usb_rcvisocpipe(dev, ep);
1273                 else
1274                         subs->syncpipe = usb_sndisocpipe(dev, ep);
1275                 subs->syncinterval = get_endpoint(alts, 1)->bRefresh;
1276         }
1277
1278         /* always fill max packet size */
1279         if (fmt->attributes & EP_CS_ATTR_FILL_MAX)
1280                 subs->fill_max = 1;
1281
1282         if ((err = init_usb_pitch(dev, subs->interface, alts, fmt)) < 0)
1283                 return err;
1284
1285         subs->cur_audiofmt = fmt;
1286
1287 #if 0
1288         printk("setting done: format = %d, rate = %d, channels = %d\n",
1289                fmt->format, fmt->rate, fmt->channels);
1290         printk("  datapipe = 0x%0x, syncpipe = 0x%0x\n",
1291                subs->datapipe, subs->syncpipe);
1292 #endif
1293
1294         return 0;
1295 }
1296
1297 /*
1298  * hw_params callback
1299  *
1300  * allocate a buffer and set the given audio format.
1301  *
1302  * so far we use a physically linear buffer although packetize transfer
1303  * doesn't need a continuous area.
1304  * if sg buffer is supported on the later version of alsa, we'll follow
1305  * that.
1306  */
1307 static int snd_usb_hw_params(snd_pcm_substream_t *substream,
1308                              snd_pcm_hw_params_t *hw_params)
1309 {
1310         snd_usb_substream_t *subs = (snd_usb_substream_t *)substream->runtime->private_data;
1311         struct audioformat *fmt;
1312         unsigned int channels, rate, format;
1313         int ret, changed;
1314
1315         ret = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
1316         if (ret < 0)
1317                 return ret;
1318
1319         format = params_format(hw_params);
1320         rate = params_rate(hw_params);
1321         channels = params_channels(hw_params);
1322         fmt = find_format(subs, format, rate, channels);
1323         if (! fmt) {
1324                 snd_printd(KERN_DEBUG "cannot set format: format = %s, rate = %d, channels = %d\n",
1325                            snd_pcm_format_name(format), rate, channels);
1326                 return -EINVAL;
1327         }
1328
1329         changed = subs->cur_audiofmt != fmt ||
1330                 subs->period_bytes != params_period_bytes(hw_params) ||
1331                 subs->cur_rate != rate;
1332         if ((ret = set_format(subs, fmt)) < 0)
1333                 return ret;
1334
1335         if (subs->cur_rate != rate) {
1336                 struct usb_host_interface *alts;
1337                 struct usb_interface *iface;
1338                 iface = usb_ifnum_to_if(subs->dev, fmt->iface);
1339                 alts = &iface->altsetting[fmt->altset_idx];
1340                 ret = init_usb_sample_rate(subs->dev, subs->interface, alts, fmt, rate);
1341                 if (ret < 0)
1342                         return ret;
1343                 subs->cur_rate = rate;
1344         }
1345
1346         if (changed) {
1347                 /* format changed */
1348                 release_substream_urbs(subs, 0);
1349                 /* influenced: period_bytes, channels, rate, format, */
1350                 ret = init_substream_urbs(subs, params_period_bytes(hw_params),
1351                                           params_rate(hw_params),
1352                                           snd_pcm_format_physical_width(params_format(hw_params)) * params_channels(hw_params));
1353         }
1354
1355         return ret;
1356 }
1357
1358 /*
1359  * hw_free callback
1360  *
1361  * reset the audio format and release the buffer
1362  */
1363 static int snd_usb_hw_free(snd_pcm_substream_t *substream)
1364 {
1365         snd_usb_substream_t *subs = (snd_usb_substream_t *)substream->runtime->private_data;
1366
1367         subs->cur_audiofmt = NULL;
1368         subs->cur_rate = 0;
1369         subs->period_bytes = 0;
1370         release_substream_urbs(subs, 0);
1371         return snd_pcm_lib_free_pages(substream);
1372 }
1373
1374 /*
1375  * prepare callback
1376  *
1377  * only a few subtle things...
1378  */
1379 static int snd_usb_pcm_prepare(snd_pcm_substream_t *substream)
1380 {
1381         snd_pcm_runtime_t *runtime = substream->runtime;
1382         snd_usb_substream_t *subs = (snd_usb_substream_t *)runtime->private_data;
1383
1384         if (! subs->cur_audiofmt) {
1385                 snd_printk(KERN_ERR "usbaudio: no format is specified!\n");
1386                 return -ENXIO;
1387         }
1388
1389         /* some unit conversions in runtime */
1390         subs->maxframesize = bytes_to_frames(runtime, subs->maxpacksize);
1391         subs->curframesize = bytes_to_frames(runtime, subs->curpacksize);
1392
1393         /* reset the pointer */
1394         subs->hwptr = 0;
1395         subs->hwptr_done = 0;
1396         subs->transfer_sched = 0;
1397         subs->transfer_done = 0;
1398         subs->phase = 0;
1399
1400         /* clear urbs (to be sure) */
1401         deactivate_urbs(subs, 0, 1);
1402         wait_clear_urbs(subs);
1403
1404         return 0;
1405 }
1406
1407 static snd_pcm_hardware_t snd_usb_playback =
1408 {
1409         .info =                 (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
1410                                  SNDRV_PCM_INFO_BLOCK_TRANSFER |
1411                                  SNDRV_PCM_INFO_MMAP_VALID),
1412         .buffer_bytes_max =     (128*1024),
1413         .period_bytes_min =     64,
1414         .period_bytes_max =     (128*1024),
1415         .periods_min =          2,
1416         .periods_max =          1024,
1417 };
1418
1419 static snd_pcm_hardware_t snd_usb_capture =
1420 {
1421         .info =                 (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
1422                                  SNDRV_PCM_INFO_BLOCK_TRANSFER |
1423                                  SNDRV_PCM_INFO_MMAP_VALID),
1424         .buffer_bytes_max =     (128*1024),
1425         .period_bytes_min =     64,
1426         .period_bytes_max =     (128*1024),
1427         .periods_min =          2,
1428         .periods_max =          1024,
1429 };
1430
1431 /*
1432  * h/w constraints
1433  */
1434
1435 #ifdef HW_CONST_DEBUG
1436 #define hwc_debug(fmt, args...) printk(KERN_DEBUG fmt, ##args)
1437 #else
1438 #define hwc_debug(fmt, args...) /**/
1439 #endif
1440
1441 static int hw_check_valid_format(snd_pcm_hw_params_t *params, struct audioformat *fp)
1442 {
1443         snd_interval_t *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1444         snd_interval_t *ct = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1445         snd_mask_t *fmts = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1446
1447         /* check the format */
1448         if (! snd_mask_test(fmts, fp->format)) {
1449                 hwc_debug("   > check: no supported format %d\n", fp->format);
1450                 return 0;
1451         }
1452         /* check the channels */
1453         if (fp->channels < ct->min || fp->channels > ct->max) {
1454                 hwc_debug("   > check: no valid channels %d (%d/%d)\n", fp->channels, ct->min, ct->max);
1455                 return 0;
1456         }
1457         /* check the rate is within the range */
1458         if (fp->rate_min > it->max || (fp->rate_min == it->max && it->openmax)) {
1459                 hwc_debug("   > check: rate_min %d > max %d\n", fp->rate_min, it->max);
1460                 return 0;
1461         }
1462         if (fp->rate_max < it->min || (fp->rate_max == it->min && it->openmin)) {
1463                 hwc_debug("   > check: rate_max %d < min %d\n", fp->rate_max, it->min);
1464                 return 0;
1465         }
1466         return 1;
1467 }
1468
1469 static int hw_rule_rate(snd_pcm_hw_params_t *params,
1470                         snd_pcm_hw_rule_t *rule)
1471 {
1472         snd_usb_substream_t *subs = rule->private;
1473         struct list_head *p;
1474         snd_interval_t *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
1475         unsigned int rmin, rmax;
1476         int changed;
1477
1478         hwc_debug("hw_rule_rate: (%d,%d)\n", it->min, it->max);
1479         changed = 0;
1480         rmin = rmax = 0;
1481         list_for_each(p, &subs->fmt_list) {
1482                 struct audioformat *fp;
1483                 fp = list_entry(p, struct audioformat, list);
1484                 if (! hw_check_valid_format(params, fp))
1485                         continue;
1486                 if (changed++) {
1487                         if (rmin > fp->rate_min)
1488                                 rmin = fp->rate_min;
1489                         if (rmax < fp->rate_max)
1490                                 rmax = fp->rate_max;
1491                 } else {
1492                         rmin = fp->rate_min;
1493                         rmax = fp->rate_max;
1494                 }
1495         }
1496
1497         if (! changed) {
1498                 hwc_debug("  --> get empty\n");
1499                 it->empty = 1;
1500                 return -EINVAL;
1501         }
1502
1503         changed = 0;
1504         if (it->min < rmin) {
1505                 it->min = rmin;
1506                 it->openmin = 0;
1507                 changed = 1;
1508         }
1509         if (it->max > rmax) {
1510                 it->max = rmax;
1511                 it->openmax = 0;
1512                 changed = 1;
1513         }
1514         if (snd_interval_checkempty(it)) {
1515                 it->empty = 1;
1516                 return -EINVAL;
1517         }
1518         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1519         return changed;
1520 }
1521
1522
1523 static int hw_rule_channels(snd_pcm_hw_params_t *params,
1524                             snd_pcm_hw_rule_t *rule)
1525 {
1526         snd_usb_substream_t *subs = rule->private;
1527         struct list_head *p;
1528         snd_interval_t *it = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
1529         unsigned int rmin, rmax;
1530         int changed;
1531
1532         hwc_debug("hw_rule_channels: (%d,%d)\n", it->min, it->max);
1533         changed = 0;
1534         rmin = rmax = 0;
1535         list_for_each(p, &subs->fmt_list) {
1536                 struct audioformat *fp;
1537                 fp = list_entry(p, struct audioformat, list);
1538                 if (! hw_check_valid_format(params, fp))
1539                         continue;
1540                 if (changed++) {
1541                         if (rmin > fp->channels)
1542                                 rmin = fp->channels;
1543                         if (rmax < fp->channels)
1544                                 rmax = fp->channels;
1545                 } else {
1546                         rmin = fp->channels;
1547                         rmax = fp->channels;
1548                 }
1549         }
1550
1551         if (! changed) {
1552                 hwc_debug("  --> get empty\n");
1553                 it->empty = 1;
1554                 return -EINVAL;
1555         }
1556
1557         changed = 0;
1558         if (it->min < rmin) {
1559                 it->min = rmin;
1560                 it->openmin = 0;
1561                 changed = 1;
1562         }
1563         if (it->max > rmax) {
1564                 it->max = rmax;
1565                 it->openmax = 0;
1566                 changed = 1;
1567         }
1568         if (snd_interval_checkempty(it)) {
1569                 it->empty = 1;
1570                 return -EINVAL;
1571         }
1572         hwc_debug("  --> (%d, %d) (changed = %d)\n", it->min, it->max, changed);
1573         return changed;
1574 }
1575
1576 static int hw_rule_format(snd_pcm_hw_params_t *params,
1577                           snd_pcm_hw_rule_t *rule)
1578 {
1579         snd_usb_substream_t *subs = rule->private;
1580         struct list_head *p;
1581         snd_mask_t *fmt = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1582         u64 fbits;
1583         u32 oldbits[2];
1584         int changed;
1585
1586         hwc_debug("hw_rule_format: %x:%x\n", fmt->bits[0], fmt->bits[1]);
1587         fbits = 0;
1588         list_for_each(p, &subs->fmt_list) {
1589                 struct audioformat *fp;
1590                 fp = list_entry(p, struct audioformat, list);
1591                 if (! hw_check_valid_format(params, fp))
1592                         continue;
1593                 fbits |= (1ULL << fp->format);
1594         }
1595
1596         oldbits[0] = fmt->bits[0];
1597         oldbits[1] = fmt->bits[1];
1598         fmt->bits[0] &= (u32)fbits;
1599         fmt->bits[1] &= (u32)(fbits >> 32);
1600         if (! fmt->bits[0] && ! fmt->bits[1]) {
1601                 hwc_debug("  --> get empty\n");
1602                 return -EINVAL;
1603         }
1604         changed = (oldbits[0] != fmt->bits[0] || oldbits[1] != fmt->bits[1]);
1605         hwc_debug("  --> %x:%x (changed = %d)\n", fmt->bits[0], fmt->bits[1], changed);
1606         return changed;
1607 }
1608
1609 /*
1610  * check whether the registered audio formats need special hw-constraints
1611  */
1612 static int check_hw_params_convention(snd_usb_substream_t *subs)
1613 {
1614         int i;
1615         u32 channels[64];
1616         u32 rates[64];
1617         u32 cmaster, rmaster;
1618         u32 rate_min = 0, rate_max = 0;
1619         struct list_head *p;
1620
1621         memset(channels, 0, sizeof(channels));
1622         memset(rates, 0, sizeof(rates));
1623
1624         list_for_each(p, &subs->fmt_list) {
1625                 struct audioformat *f;
1626                 f = list_entry(p, struct audioformat, list);
1627                 /* unconventional channels? */
1628                 if (f->channels > 32)
1629                         return 1;
1630                 /* continuous rate min/max matches? */
1631                 if (f->rates & SNDRV_PCM_RATE_CONTINUOUS) {
1632                         if (rate_min && f->rate_min != rate_min)
1633                                 return 1;
1634                         if (rate_max && f->rate_max != rate_max)
1635                                 return 1;
1636                         rate_min = f->rate_min;
1637                         rate_max = f->rate_max;
1638                 }
1639                 /* combination of continuous rates and fixed rates? */
1640                 if (rates[f->format] & SNDRV_PCM_RATE_CONTINUOUS) {
1641                         if (f->rates != rates[f->format])
1642                                 return 1;
1643                 }
1644                 if (f->rates & SNDRV_PCM_RATE_CONTINUOUS) {
1645                         if (rates[f->format] && rates[f->format] != f->rates)
1646                                 return 1;
1647                 }
1648                 channels[f->format] |= (1 << f->channels);
1649                 rates[f->format] |= f->rates;
1650         }
1651         /* check whether channels and rates match for all formats */
1652         cmaster = rmaster = 0;
1653         for (i = 0; i < 64; i++) {
1654                 if (cmaster != channels[i] && cmaster && channels[i])
1655                         return 1;
1656                 if (rmaster != rates[i] && rmaster && rates[i])
1657                         return 1;
1658                 if (channels[i])
1659                         cmaster = channels[i];
1660                 if (rates[i])
1661                         rmaster = rates[i];
1662         }
1663         /* check whether channels match for all distinct rates */
1664         memset(channels, 0, sizeof(channels));
1665         list_for_each(p, &subs->fmt_list) {
1666                 struct audioformat *f;
1667                 f = list_entry(p, struct audioformat, list);
1668                 if (f->rates & SNDRV_PCM_RATE_CONTINUOUS)
1669                         continue;
1670                 for (i = 0; i < 32; i++) {
1671                         if (f->rates & (1 << i))
1672                                 channels[i] |= (1 << f->channels);
1673                 }
1674         }
1675         cmaster = 0;
1676         for (i = 0; i < 32; i++) {
1677                 if (cmaster != channels[i] && cmaster && channels[i])
1678                         return 1;
1679                 if (channels[i])
1680                         cmaster = channels[i];
1681         }
1682         return 0;
1683 }
1684
1685
1686 /*
1687  * set up the runtime hardware information.
1688  */
1689
1690 static int setup_hw_info(snd_pcm_runtime_t *runtime, snd_usb_substream_t *subs)
1691 {
1692         struct list_head *p;
1693         int err;
1694
1695         runtime->hw.formats = subs->formats;
1696
1697         runtime->hw.rate_min = 0x7fffffff;
1698         runtime->hw.rate_max = 0;
1699         runtime->hw.channels_min = 256;
1700         runtime->hw.channels_max = 0;
1701         runtime->hw.rates = 0;
1702         /* check min/max rates and channels */
1703         list_for_each(p, &subs->fmt_list) {
1704                 struct audioformat *fp;
1705                 fp = list_entry(p, struct audioformat, list);
1706                 runtime->hw.rates |= fp->rates;
1707                 if (runtime->hw.rate_min > fp->rate_min)
1708                         runtime->hw.rate_min = fp->rate_min;
1709                 if (runtime->hw.rate_max < fp->rate_max)
1710                         runtime->hw.rate_max = fp->rate_max;
1711                 if (runtime->hw.channels_min > fp->channels)
1712                         runtime->hw.channels_min = fp->channels;
1713                 if (runtime->hw.channels_max < fp->channels)
1714                         runtime->hw.channels_max = fp->channels;
1715                 if (fp->fmt_type == USB_FORMAT_TYPE_II && fp->frame_size > 0) {
1716                         /* FIXME: there might be more than one audio formats... */
1717                         runtime->hw.period_bytes_min = runtime->hw.period_bytes_max =
1718                                 fp->frame_size;
1719                 }
1720         }
1721
1722         /* set the period time minimum 1ms */
1723         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME,
1724                                      1000 * MIN_PACKS_URB,
1725                                      /*(nrpacks * MAX_URBS) * 1000*/ UINT_MAX);
1726
1727         if (check_hw_params_convention(subs)) {
1728                 hwc_debug("setting extra hw constraints...\n");
1729                 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1730                                                hw_rule_rate, subs,
1731                                                SNDRV_PCM_HW_PARAM_FORMAT,
1732                                                SNDRV_PCM_HW_PARAM_CHANNELS,
1733                                                -1)) < 0)
1734                         return err;
1735                 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
1736                                                hw_rule_channels, subs,
1737                                                SNDRV_PCM_HW_PARAM_FORMAT,
1738                                                SNDRV_PCM_HW_PARAM_RATE,
1739                                                -1)) < 0)
1740                         return err;
1741                 if ((err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1742                                                hw_rule_format, subs,
1743                                                SNDRV_PCM_HW_PARAM_RATE,
1744                                                SNDRV_PCM_HW_PARAM_CHANNELS,
1745                                                -1)) < 0)
1746                         return err;
1747         }
1748         return 0;
1749 }
1750
1751 static int snd_usb_pcm_open(snd_pcm_substream_t *substream, int direction,
1752                             snd_pcm_hardware_t *hw)
1753 {
1754         snd_usb_stream_t *as = snd_pcm_substream_chip(substream);
1755         snd_pcm_runtime_t *runtime = substream->runtime;
1756         snd_usb_substream_t *subs = &as->substream[direction];
1757
1758         subs->interface = -1;
1759         subs->format = 0;
1760         runtime->hw = *hw;
1761         runtime->private_data = subs;
1762         subs->pcm_substream = substream;
1763         return setup_hw_info(runtime, subs);
1764 }
1765
1766 static int snd_usb_pcm_close(snd_pcm_substream_t *substream, int direction)
1767 {
1768         snd_usb_stream_t *as = snd_pcm_substream_chip(substream);
1769         snd_usb_substream_t *subs = &as->substream[direction];
1770
1771         if (subs->interface >= 0) {
1772                 usb_set_interface(subs->dev, subs->interface, 0);
1773                 subs->interface = -1;
1774         }
1775         subs->pcm_substream = NULL;
1776         return 0;
1777 }
1778
1779 static int snd_usb_playback_open(snd_pcm_substream_t *substream)
1780 {
1781         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_PLAYBACK, &snd_usb_playback);
1782 }
1783
1784 static int snd_usb_playback_close(snd_pcm_substream_t *substream)
1785 {
1786         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_PLAYBACK);
1787 }
1788
1789 static int snd_usb_capture_open(snd_pcm_substream_t *substream)
1790 {
1791         return snd_usb_pcm_open(substream, SNDRV_PCM_STREAM_CAPTURE, &snd_usb_capture);
1792 }
1793
1794 static int snd_usb_capture_close(snd_pcm_substream_t *substream)
1795 {
1796         return snd_usb_pcm_close(substream, SNDRV_PCM_STREAM_CAPTURE);
1797 }
1798
1799 static snd_pcm_ops_t snd_usb_playback_ops = {
1800         .open =         snd_usb_playback_open,
1801         .close =        snd_usb_playback_close,
1802         .ioctl =        snd_pcm_lib_ioctl,
1803         .hw_params =    snd_usb_hw_params,
1804         .hw_free =      snd_usb_hw_free,
1805         .prepare =      snd_usb_pcm_prepare,
1806         .trigger =      snd_usb_pcm_trigger,
1807         .pointer =      snd_usb_pcm_pointer,
1808 };
1809
1810 static snd_pcm_ops_t snd_usb_capture_ops = {
1811         .open =         snd_usb_capture_open,
1812         .close =        snd_usb_capture_close,
1813         .ioctl =        snd_pcm_lib_ioctl,
1814         .hw_params =    snd_usb_hw_params,
1815         .hw_free =      snd_usb_hw_free,
1816         .prepare =      snd_usb_pcm_prepare,
1817         .trigger =      snd_usb_pcm_trigger,
1818         .pointer =      snd_usb_pcm_pointer,
1819 };
1820
1821
1822
1823 /*
1824  * helper functions
1825  */
1826
1827 /*
1828  * combine bytes and get an integer value
1829  */
1830 unsigned int snd_usb_combine_bytes(unsigned char *bytes, int size)
1831 {
1832         switch (size) {
1833         case 1:  return *bytes;
1834         case 2:  return combine_word(bytes);
1835         case 3:  return combine_triple(bytes);
1836         case 4:  return combine_quad(bytes);
1837         default: return 0;
1838         }
1839 }
1840
1841 /*
1842  * parse descriptor buffer and return the pointer starting the given
1843  * descriptor type.
1844  */
1845 void *snd_usb_find_desc(void *descstart, int desclen, void *after, u8 dtype)
1846 {
1847         u8 *p, *end, *next;
1848
1849         p = descstart;
1850         end = p + desclen;
1851         for (; p < end;) {
1852                 if (p[0] < 2)
1853                         return NULL;
1854                 next = p + p[0];
1855                 if (next > end)
1856                         return NULL;
1857                 if (p[1] == dtype && (!after || (void *)p > after)) {
1858                         return p;
1859                 }
1860                 p = next;
1861         }
1862         return NULL;
1863 }
1864
1865 /*
1866  * find a class-specified interface descriptor with the given subtype.
1867  */
1868 void *snd_usb_find_csint_desc(void *buffer, int buflen, void *after, u8 dsubtype)
1869 {
1870         unsigned char *p = after;
1871
1872         while ((p = snd_usb_find_desc(buffer, buflen, p,
1873                                       USB_DT_CS_INTERFACE)) != NULL) {
1874                 if (p[0] >= 3 && p[2] == dsubtype)
1875                         return p;
1876         }
1877         return NULL;
1878 }
1879
1880 /*
1881  * Wrapper for usb_control_msg().
1882  * Allocates a temp buffer to prevent dmaing from/to the stack.
1883  */
1884 int snd_usb_ctl_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
1885                     __u8 requesttype, __u16 value, __u16 index, void *data,
1886                     __u16 size, int timeout)
1887 {
1888         int err;
1889         void *buf = NULL;
1890
1891         if (size > 0) {
1892                 buf = kmalloc(size, GFP_KERNEL);
1893                 if (!buf)
1894                         return -ENOMEM;
1895                 memcpy(buf, data, size);
1896         }
1897         err = usb_control_msg(dev, pipe, request, requesttype,
1898                               value, index, buf, size, timeout);
1899         if (size > 0) {
1900                 memcpy(data, buf, size);
1901                 kfree(buf);
1902         }
1903         return err;
1904 }
1905
1906
1907 /*
1908  * entry point for linux usb interface
1909  */
1910
1911 static int usb_audio_probe(struct usb_interface *intf,
1912                            const struct usb_device_id *id);
1913 static void usb_audio_disconnect(struct usb_interface *intf);
1914
1915 static struct usb_device_id usb_audio_ids [] = {
1916 #include "usbquirks.h"
1917     { .match_flags = (USB_DEVICE_ID_MATCH_INT_CLASS | USB_DEVICE_ID_MATCH_INT_SUBCLASS),
1918       .bInterfaceClass = USB_CLASS_AUDIO,
1919       .bInterfaceSubClass = USB_SUBCLASS_AUDIO_CONTROL },
1920     { }                                         /* Terminating entry */
1921 };
1922
1923 MODULE_DEVICE_TABLE (usb, usb_audio_ids);
1924
1925 static struct usb_driver usb_audio_driver = {
1926         .owner =        THIS_MODULE,
1927         .name =         "snd-usb-audio",
1928         .probe =        usb_audio_probe,
1929         .disconnect =   usb_audio_disconnect,
1930         .id_table =     usb_audio_ids,
1931 };
1932
1933
1934 /*
1935  * proc interface for list the supported pcm formats
1936  */
1937 static void proc_dump_substream_formats(snd_usb_substream_t *subs, snd_info_buffer_t *buffer)
1938 {
1939         struct list_head *p;
1940         static char *sync_types[4] = {
1941                 "NONE", "ASYNC", "ADAPTIVE", "SYNC"
1942         };
1943
1944         list_for_each(p, &subs->fmt_list) {
1945                 struct audioformat *fp;
1946                 fp = list_entry(p, struct audioformat, list);
1947                 snd_iprintf(buffer, "  Interface %d\n", fp->iface);
1948                 snd_iprintf(buffer, "    Altset %d\n", fp->altsetting);
1949                 snd_iprintf(buffer, "    Format: %s\n", snd_pcm_format_name(fp->format));
1950                 snd_iprintf(buffer, "    Channels: %d\n", fp->channels);
1951                 snd_iprintf(buffer, "    Endpoint: %d %s (%s)\n",
1952                             fp->endpoint & USB_ENDPOINT_NUMBER_MASK,
1953                             fp->endpoint & USB_DIR_IN ? "IN" : "OUT",
1954                             sync_types[(fp->ep_attr & EP_ATTR_MASK) >> 2]);
1955                 if (fp->rates & SNDRV_PCM_RATE_CONTINUOUS) {
1956                         snd_iprintf(buffer, "    Rates: %d - %d (continuous)\n",
1957                                     fp->rate_min, fp->rate_max);
1958                 } else {
1959                         unsigned int i;
1960                         snd_iprintf(buffer, "    Rates: ");
1961                         for (i = 0; i < fp->nr_rates; i++) {
1962                                 if (i > 0)
1963                                         snd_iprintf(buffer, ", ");
1964                                 snd_iprintf(buffer, "%d", fp->rate_table[i]);
1965                         }
1966                         snd_iprintf(buffer, "\n");
1967                 }
1968                 // snd_iprintf(buffer, "    Max Packet Size = %d\n", fp->maxpacksize);
1969                 // snd_iprintf(buffer, "    EP Attribute = 0x%x\n", fp->attributes);
1970         }
1971 }
1972
1973 static void proc_dump_substream_status(snd_usb_substream_t *subs, snd_info_buffer_t *buffer)
1974 {
1975         if (subs->running) {
1976                 unsigned int i;
1977                 snd_iprintf(buffer, "  Status: Running\n");
1978                 snd_iprintf(buffer, "    Interface = %d\n", subs->interface);
1979                 snd_iprintf(buffer, "    Altset = %d\n", subs->format);
1980                 snd_iprintf(buffer, "    URBs = %d [ ", subs->nurbs);
1981                 for (i = 0; i < subs->nurbs; i++)
1982                         snd_iprintf(buffer, "%d ", subs->dataurb[i].packets);
1983                 snd_iprintf(buffer, "]\n");
1984                 snd_iprintf(buffer, "    Packet Size = %d\n", subs->curpacksize);
1985                 snd_iprintf(buffer, "    Momentary freq = %u Hz\n",
1986                             snd_usb_get_speed(subs->dev) == USB_SPEED_FULL
1987                             ? get_full_speed_hz(subs->freqm)
1988                             : get_high_speed_hz(subs->freqm));
1989         } else {
1990                 snd_iprintf(buffer, "  Status: Stop\n");
1991         }
1992 }
1993
1994 static void proc_pcm_format_read(snd_info_entry_t *entry, snd_info_buffer_t *buffer)
1995 {
1996         snd_usb_stream_t *stream = entry->private_data;
1997
1998         snd_iprintf(buffer, "%s : %s\n", stream->chip->card->longname, stream->pcm->name);
1999
2000         if (stream->substream[SNDRV_PCM_STREAM_PLAYBACK].num_formats) {
2001                 snd_iprintf(buffer, "\nPlayback:\n");
2002                 proc_dump_substream_status(&stream->substream[SNDRV_PCM_STREAM_PLAYBACK], buffer);
2003                 proc_dump_substream_formats(&stream->substream[SNDRV_PCM_STREAM_PLAYBACK], buffer);
2004         }
2005         if (stream->substream[SNDRV_PCM_STREAM_CAPTURE].num_formats) {
2006                 snd_iprintf(buffer, "\nCapture:\n");
2007                 proc_dump_substream_status(&stream->substream[SNDRV_PCM_STREAM_CAPTURE], buffer);
2008                 proc_dump_substream_formats(&stream->substream[SNDRV_PCM_STREAM_CAPTURE], buffer);
2009         }
2010 }
2011
2012 static void proc_pcm_format_add(snd_usb_stream_t *stream)
2013 {
2014         snd_info_entry_t *entry;
2015         char name[32];
2016         snd_card_t *card = stream->chip->card;
2017
2018         sprintf(name, "stream%d", stream->pcm_index);
2019         if (! snd_card_proc_new(card, name, &entry))
2020                 snd_info_set_text_ops(entry, stream, 1024, proc_pcm_format_read);
2021 }
2022
2023
2024 /*
2025  * initialize the substream instance.
2026  */
2027
2028 static void init_substream(snd_usb_stream_t *as, int stream, struct audioformat *fp)
2029 {
2030         snd_usb_substream_t *subs = &as->substream[stream];
2031
2032         INIT_LIST_HEAD(&subs->fmt_list);
2033         spin_lock_init(&subs->lock);
2034
2035         subs->stream = as;
2036         subs->direction = stream;
2037         subs->dev = as->chip->dev;
2038         if (snd_usb_get_speed(subs->dev) == USB_SPEED_FULL)
2039                 subs->ops = audio_urb_ops[stream];
2040         else
2041                 subs->ops = audio_urb_ops_high_speed[stream];
2042         snd_pcm_lib_preallocate_pages(as->pcm->streams[stream].substream,
2043                                       SNDRV_DMA_TYPE_CONTINUOUS,
2044                                       snd_dma_continuous_data(GFP_KERNEL),
2045                                       64 * 1024, 128 * 1024);
2046         snd_pcm_set_ops(as->pcm, stream,
2047                         stream == SNDRV_PCM_STREAM_PLAYBACK ?
2048                         &snd_usb_playback_ops : &snd_usb_capture_ops);
2049
2050         list_add_tail(&fp->list, &subs->fmt_list);
2051         subs->formats |= 1ULL << fp->format;
2052         subs->endpoint = fp->endpoint;
2053         subs->num_formats++;
2054         subs->fmt_type = fp->fmt_type;
2055 }
2056
2057
2058 /*
2059  * free a substream
2060  */
2061 static void free_substream(snd_usb_substream_t *subs)
2062 {
2063         struct list_head *p, *n;
2064
2065         if (! subs->num_formats)
2066                 return; /* not initialized */
2067         list_for_each_safe(p, n, &subs->fmt_list) {
2068                 struct audioformat *fp = list_entry(p, struct audioformat, list);
2069                 kfree(fp->rate_table);
2070                 kfree(fp);
2071         }
2072 }
2073
2074
2075 /*
2076  * free a usb stream instance
2077  */
2078 static void snd_usb_audio_stream_free(snd_usb_stream_t *stream)
2079 {
2080         free_substream(&stream->substream[0]);
2081         free_substream(&stream->substream[1]);
2082         list_del(&stream->list);
2083         kfree(stream);
2084 }
2085
2086 static void snd_usb_audio_pcm_free(snd_pcm_t *pcm)
2087 {
2088         snd_usb_stream_t *stream = pcm->private_data;
2089         if (stream) {
2090                 stream->pcm = NULL;
2091                 snd_pcm_lib_preallocate_free_for_all(pcm);
2092                 snd_usb_audio_stream_free(stream);
2093         }
2094 }
2095
2096
2097 /*
2098  * add this endpoint to the chip instance.
2099  * if a stream with the same endpoint already exists, append to it.
2100  * if not, create a new pcm stream.
2101  */
2102 static int add_audio_endpoint(snd_usb_audio_t *chip, int stream, struct audioformat *fp)
2103 {
2104         struct list_head *p;
2105         snd_usb_stream_t *as;
2106         snd_usb_substream_t *subs;
2107         snd_pcm_t *pcm;
2108         int err;
2109
2110         list_for_each(p, &chip->pcm_list) {
2111                 as = list_entry(p, snd_usb_stream_t, list);
2112                 if (as->fmt_type != fp->fmt_type)
2113                         continue;
2114                 subs = &as->substream[stream];
2115                 if (! subs->endpoint)
2116                         continue;
2117                 if (subs->endpoint == fp->endpoint) {
2118                         list_add_tail(&fp->list, &subs->fmt_list);
2119                         subs->num_formats++;
2120                         subs->formats |= 1ULL << fp->format;
2121                         return 0;
2122                 }
2123         }
2124         /* look for an empty stream */
2125         list_for_each(p, &chip->pcm_list) {
2126                 as = list_entry(p, snd_usb_stream_t, list);
2127                 if (as->fmt_type != fp->fmt_type)
2128                         continue;
2129                 subs = &as->substream[stream];
2130                 if (subs->endpoint)
2131                         continue;
2132                 err = snd_pcm_new_stream(as->pcm, stream, 1);
2133                 if (err < 0)
2134                         return err;
2135                 init_substream(as, stream, fp);
2136                 return 0;
2137         }
2138
2139         /* create a new pcm */
2140         as = kmalloc(sizeof(*as), GFP_KERNEL);
2141         if (! as)
2142                 return -ENOMEM;
2143         memset(as, 0, sizeof(*as));
2144         as->pcm_index = chip->pcm_devs;
2145         as->chip = chip;
2146         as->fmt_type = fp->fmt_type;
2147         err = snd_pcm_new(chip->card, "USB Audio", chip->pcm_devs,
2148                           stream == SNDRV_PCM_STREAM_PLAYBACK ? 1 : 0,
2149                           stream == SNDRV_PCM_STREAM_PLAYBACK ? 0 : 1,
2150                           &pcm);
2151         if (err < 0) {
2152                 kfree(as);
2153                 return err;
2154         }
2155         as->pcm = pcm;
2156         pcm->private_data = as;
2157         pcm->private_free = snd_usb_audio_pcm_free;
2158         pcm->info_flags = 0;
2159         if (chip->pcm_devs > 0)
2160                 sprintf(pcm->name, "USB Audio #%d", chip->pcm_devs);
2161         else
2162                 strcpy(pcm->name, "USB Audio");
2163
2164         init_substream(as, stream, fp);
2165
2166         list_add(&as->list, &chip->pcm_list);
2167         chip->pcm_devs++;
2168
2169         proc_pcm_format_add(as);
2170
2171         return 0;
2172 }
2173
2174
2175 /*
2176  * check if the device uses big-endian samples
2177  */
2178 static int is_big_endian_format(struct usb_device *dev, struct audioformat *fp)
2179 {
2180         /* M-Audio */
2181         if (le16_to_cpu(dev->descriptor.idVendor) == 0x0763) {
2182                 /* Quattro: captured data only */
2183                 if (le16_to_cpu(dev->descriptor.idProduct) == 0x2001 &&
2184                     fp->endpoint & USB_DIR_IN)
2185                         return 1;
2186                 /* Audiophile USB */
2187                 if (le16_to_cpu(dev->descriptor.idProduct) == 0x2003)
2188                         return 1;
2189         }
2190         return 0;
2191 }
2192
2193 /*
2194  * parse the audio format type I descriptor
2195  * and returns the corresponding pcm format
2196  *
2197  * @dev: usb device
2198  * @fp: audioformat record
2199  * @format: the format tag (wFormatTag)
2200  * @fmt: the format type descriptor
2201  */
2202 static int parse_audio_format_i_type(struct usb_device *dev, struct audioformat *fp,
2203                                      int format, unsigned char *fmt)
2204 {
2205         int pcm_format;
2206         int sample_width, sample_bytes;
2207
2208         /* FIXME: correct endianess and sign? */
2209         pcm_format = -1;
2210         sample_width = fmt[6];
2211         sample_bytes = fmt[5];
2212         switch (format) {
2213         case 0: /* some devices don't define this correctly... */
2214                 snd_printdd(KERN_INFO "%d:%u:%d : format type 0 is detected, processed as PCM\n",
2215                             dev->devnum, fp->iface, fp->altsetting);
2216                 /* fall-through */
2217         case USB_AUDIO_FORMAT_PCM:
2218                 if (sample_width > sample_bytes * 8) {
2219                         snd_printk(KERN_INFO "%d:%u:%d : sample bitwidth %d in over sample bytes %d\n",
2220                                    dev->devnum, fp->iface, fp->altsetting,
2221                                    sample_width, sample_bytes);
2222                 }
2223                 /* check the format byte size */
2224                 switch (fmt[5]) {
2225                 case 1:
2226                         pcm_format = SNDRV_PCM_FORMAT_S8;
2227                         break;
2228                 case 2:
2229                         if (is_big_endian_format(dev, fp))
2230                                 pcm_format = SNDRV_PCM_FORMAT_S16_BE; /* grrr, big endian!! */
2231                         else
2232                                 pcm_format = SNDRV_PCM_FORMAT_S16_LE;
2233                         break;
2234                 case 3:
2235                         if (is_big_endian_format(dev, fp))
2236                                 pcm_format = SNDRV_PCM_FORMAT_S24_3BE; /* grrr, big endian!! */
2237                         else
2238                                 pcm_format = SNDRV_PCM_FORMAT_S24_3LE;
2239                         break;
2240                 case 4:
2241                         pcm_format = SNDRV_PCM_FORMAT_S32_LE;
2242                         break;
2243                 default:
2244                         snd_printk(KERN_INFO "%d:%u:%d : unsupported sample bitwidth %d in %d bytes\n",
2245                                    dev->devnum, fp->iface, fp->altsetting, sample_width, sample_bytes);
2246                         break;
2247                 }
2248                 break;
2249         case USB_AUDIO_FORMAT_PCM8:
2250                 /* Dallas DS4201 workaround */
2251                 if (le16_to_cpu(dev->descriptor.idVendor) == 0x04fa &&
2252                     le16_to_cpu(dev->descriptor.idProduct) == 0x4201)
2253                         pcm_format = SNDRV_PCM_FORMAT_S8;
2254                 else
2255                         pcm_format = SNDRV_PCM_FORMAT_U8;
2256                 break;
2257         case USB_AUDIO_FORMAT_IEEE_FLOAT:
2258                 pcm_format = SNDRV_PCM_FORMAT_FLOAT_LE;
2259                 break;
2260         case USB_AUDIO_FORMAT_ALAW:
2261                 pcm_format = SNDRV_PCM_FORMAT_A_LAW;
2262                 break;
2263         case USB_AUDIO_FORMAT_MU_LAW:
2264                 pcm_format = SNDRV_PCM_FORMAT_MU_LAW;
2265                 break;
2266         default:
2267                 snd_printk(KERN_INFO "%d:%u:%d : unsupported format type %d\n",
2268                            dev->devnum, fp->iface, fp->altsetting, format);
2269                 break;
2270         }
2271         return pcm_format;
2272 }
2273
2274
2275 /*
2276  * parse the format descriptor and stores the possible sample rates
2277  * on the audioformat table.
2278  *
2279  * @dev: usb device
2280  * @fp: audioformat record
2281  * @fmt: the format descriptor
2282  * @offset: the start offset of descriptor pointing the rate type
2283  *          (7 for type I and II, 8 for type II)
2284  */
2285 static int parse_audio_format_rates(struct usb_device *dev, struct audioformat *fp,
2286                                     unsigned char *fmt, int offset)
2287 {
2288         int nr_rates = fmt[offset];
2289         if (fmt[0] < offset + 1 + 3 * (nr_rates ? nr_rates : 2)) {
2290                 snd_printk(KERN_ERR "%d:%u:%d : invalid FORMAT_TYPE desc\n",
2291                                    dev->devnum, fp->iface, fp->altsetting);
2292                 return -1;
2293         }
2294
2295         if (nr_rates) {
2296                 /*
2297                  * build the rate table and bitmap flags
2298                  */
2299                 int r, idx, c;
2300                 /* this table corresponds to the SNDRV_PCM_RATE_XXX bit */
2301                 static unsigned int conv_rates[] = {
2302                         5512, 8000, 11025, 16000, 22050, 32000, 44100, 48000,
2303                         64000, 88200, 96000, 176400, 192000
2304                 };
2305                 fp->rate_table = kmalloc(sizeof(int) * nr_rates, GFP_KERNEL);
2306                 if (fp->rate_table == NULL) {
2307                         snd_printk(KERN_ERR "cannot malloc\n");
2308                         return -1;
2309                 }
2310
2311                 fp->nr_rates = nr_rates;
2312                 fp->rate_min = fp->rate_max = combine_triple(&fmt[8]);
2313                 for (r = 0, idx = offset + 1; r < nr_rates; r++, idx += 3) {
2314                         unsigned int rate = fp->rate_table[r] = combine_triple(&fmt[idx]);
2315                         if (rate < fp->rate_min)
2316                                 fp->rate_min = rate;
2317                         else if (rate > fp->rate_max)
2318                                 fp->rate_max = rate;
2319                         for (c = 0; c < (int)ARRAY_SIZE(conv_rates); c++) {
2320                                 if (rate == conv_rates[c]) {
2321                                         fp->rates |= (1 << c);
2322                                         break;
2323                                 }
2324                         }
2325                 }
2326         } else {
2327                 /* continuous rates */
2328                 fp->rates = SNDRV_PCM_RATE_CONTINUOUS;
2329                 fp->rate_min = combine_triple(&fmt[offset + 1]);
2330                 fp->rate_max = combine_triple(&fmt[offset + 4]);
2331         }
2332         return 0;
2333 }
2334
2335 /*
2336  * parse the format type I and III descriptors
2337  */
2338 static int parse_audio_format_i(struct usb_device *dev, struct audioformat *fp,
2339                                 int format, unsigned char *fmt)
2340 {
2341         int pcm_format;
2342
2343         if (fmt[3] == USB_FORMAT_TYPE_III) {
2344                 /* FIXME: the format type is really IECxxx
2345                  *        but we give normal PCM format to get the existing
2346                  *        apps working...
2347                  */
2348                 pcm_format = SNDRV_PCM_FORMAT_S16_LE;
2349         } else {
2350                 pcm_format = parse_audio_format_i_type(dev, fp, format, fmt);
2351                 if (pcm_format < 0)
2352                         return -1;
2353         }
2354         fp->format = pcm_format;
2355         fp->channels = fmt[4];
2356         if (fp->channels < 1) {
2357                 snd_printk(KERN_ERR "%d:%u:%d : invalid channels %d\n",
2358                            dev->devnum, fp->iface, fp->altsetting, fp->channels);
2359                 return -1;
2360         }
2361         return parse_audio_format_rates(dev, fp, fmt, 7);
2362 }
2363
2364 /*
2365  * prase the format type II descriptor
2366  */
2367 static int parse_audio_format_ii(struct usb_device *dev, struct audioformat *fp,
2368                                  int format, unsigned char *fmt)
2369 {
2370         int brate, framesize;
2371         switch (format) {
2372         case USB_AUDIO_FORMAT_AC3:
2373                 /* FIXME: there is no AC3 format defined yet */
2374                 // fp->format = SNDRV_PCM_FORMAT_AC3;
2375                 fp->format = SNDRV_PCM_FORMAT_U8; /* temporarily hack to receive byte streams */
2376                 break;
2377         case USB_AUDIO_FORMAT_MPEG:
2378                 fp->format = SNDRV_PCM_FORMAT_MPEG;
2379                 break;
2380         default:
2381                 snd_printd(KERN_INFO "%d:%u:%d : unknown format tag 0x%x is detected.  processed as MPEG.\n",
2382                            dev->devnum, fp->iface, fp->altsetting, format);
2383                 fp->format = SNDRV_PCM_FORMAT_MPEG;
2384                 break;
2385         }
2386         fp->channels = 1;
2387         brate = combine_word(&fmt[4]);  /* fmt[4,5] : wMaxBitRate (in kbps) */
2388         framesize = combine_word(&fmt[6]); /* fmt[6,7]: wSamplesPerFrame */
2389         snd_printd(KERN_INFO "found format II with max.bitrate = %d, frame size=%d\n", brate, framesize);
2390         fp->frame_size = framesize;
2391         return parse_audio_format_rates(dev, fp, fmt, 8); /* fmt[8..] sample rates */
2392 }
2393
2394 static int parse_audio_format(struct usb_device *dev, struct audioformat *fp,
2395                               int format, unsigned char *fmt, int stream)
2396 {
2397         int err;
2398
2399         switch (fmt[3]) {
2400         case USB_FORMAT_TYPE_I:
2401         case USB_FORMAT_TYPE_III:
2402                 err = parse_audio_format_i(dev, fp, format, fmt);
2403                 break;
2404         case USB_FORMAT_TYPE_II:
2405                 err = parse_audio_format_ii(dev, fp, format, fmt);
2406                 break;
2407         default:
2408                 snd_printd(KERN_INFO "%d:%u:%d : format type %d is not supported yet\n",
2409                            dev->devnum, fp->iface, fp->altsetting, fmt[3]);
2410                 return -1;
2411         }
2412         fp->fmt_type = fmt[3];
2413         if (err < 0)
2414                 return err;
2415 #if 1
2416         /* FIXME: temporary hack for extigy */
2417         /* extigy apparently supports sample rates other than 48k
2418          * but not in ordinary way.  so we enable only 48k atm.
2419          */
2420         if (le16_to_cpu(dev->descriptor.idVendor) == 0x041e && 
2421             le16_to_cpu(dev->descriptor.idProduct) == 0x3000) {
2422                 if (fmt[3] == USB_FORMAT_TYPE_I &&
2423                     stream == SNDRV_PCM_STREAM_PLAYBACK &&
2424                     fp->rates != SNDRV_PCM_RATE_48000)
2425                         return -1; /* use 48k only */
2426         }
2427 #endif
2428         return 0;
2429 }
2430
2431 static int parse_audio_endpoints(snd_usb_audio_t *chip, int iface_no)
2432 {
2433         struct usb_device *dev;
2434         struct usb_interface *iface;
2435         struct usb_host_interface *alts;
2436         struct usb_interface_descriptor *altsd;
2437         int i, altno, err, stream;
2438         int format;
2439         struct audioformat *fp;
2440         unsigned char *fmt, *csep;
2441
2442         dev = chip->dev;
2443
2444         /* parse the interface's altsettings */
2445         iface = usb_ifnum_to_if(dev, iface_no);
2446         for (i = 0; i < iface->num_altsetting; i++) {
2447                 alts = &iface->altsetting[i];
2448                 altsd = get_iface_desc(alts);
2449                 /* skip invalid one */
2450                 if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
2451                      altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
2452                     (altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIO_STREAMING &&
2453                      altsd->bInterfaceSubClass != USB_SUBCLASS_VENDOR_SPEC) ||
2454                     altsd->bNumEndpoints < 1 ||
2455                     le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize) == 0)
2456                         continue;
2457                 /* must be isochronous */
2458                 if ((get_endpoint(alts, 0)->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) !=
2459                     USB_ENDPOINT_XFER_ISOC)
2460                         continue;
2461                 /* check direction */
2462                 stream = (get_endpoint(alts, 0)->bEndpointAddress & USB_DIR_IN) ?
2463                         SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
2464                 altno = altsd->bAlternateSetting;
2465
2466                 /* get audio formats */
2467                 fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, AS_GENERAL);
2468                 if (!fmt) {
2469                         snd_printk(KERN_ERR "%d:%u:%d : AS_GENERAL descriptor not found\n",
2470                                    dev->devnum, iface_no, altno);
2471                         continue;
2472                 }
2473
2474                 if (fmt[0] < 7) {
2475                         snd_printk(KERN_ERR "%d:%u:%d : invalid AS_GENERAL desc\n",
2476                                    dev->devnum, iface_no, altno);
2477                         continue;
2478                 }
2479
2480                 format = (fmt[6] << 8) | fmt[5]; /* remember the format value */
2481
2482                 /* get format type */
2483                 fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL, FORMAT_TYPE);
2484                 if (!fmt) {
2485                         snd_printk(KERN_ERR "%d:%u:%d : no FORMAT_TYPE desc\n",
2486                                    dev->devnum, iface_no, altno);
2487                         continue;
2488                 }
2489                 if (fmt[0] < 8) {
2490                         snd_printk(KERN_ERR "%d:%u:%d : invalid FORMAT_TYPE desc\n",
2491                                    dev->devnum, iface_no, altno);
2492                         continue;
2493                 }
2494
2495                 csep = snd_usb_find_desc(alts->endpoint[0].extra, alts->endpoint[0].extralen, NULL, USB_DT_CS_ENDPOINT);
2496                 /* Creamware Noah has this descriptor after the 2nd endpoint */
2497                 if (!csep && altsd->bNumEndpoints >= 2)
2498                         csep = snd_usb_find_desc(alts->endpoint[1].extra, alts->endpoint[1].extralen, NULL, USB_DT_CS_ENDPOINT);
2499                 if (!csep || csep[0] < 7 || csep[2] != EP_GENERAL) {
2500                         snd_printk(KERN_ERR "%d:%u:%d : no or invalid class specific endpoint descriptor\n",
2501                                    dev->devnum, iface_no, altno);
2502                         continue;
2503                 }
2504
2505                 fp = kmalloc(sizeof(*fp), GFP_KERNEL);
2506                 if (! fp) {
2507                         snd_printk(KERN_ERR "cannot malloc\n");
2508                         return -ENOMEM;
2509                 }
2510
2511                 memset(fp, 0, sizeof(*fp));
2512                 fp->iface = iface_no;
2513                 fp->altsetting = altno;
2514                 fp->altset_idx = i;
2515                 fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
2516                 fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
2517                 /* FIXME: decode wMaxPacketSize of high bandwith endpoints */
2518                 fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
2519                 fp->attributes = csep[3];
2520
2521                 /* some quirks for attributes here */
2522
2523                 /* workaround for AudioTrak Optoplay */
2524                 if (le16_to_cpu(dev->descriptor.idVendor) == 0x0a92 &&
2525                     le16_to_cpu(dev->descriptor.idProduct) == 0x0053) {
2526                         /* Optoplay sets the sample rate attribute although
2527                          * it seems not supporting it in fact.
2528                          */
2529                         fp->attributes &= ~EP_CS_ATTR_SAMPLE_RATE;
2530                 }
2531
2532                 /* workaround for M-Audio Audiophile USB */
2533                 if (le16_to_cpu(dev->descriptor.idVendor) == 0x0763 &&
2534                     le16_to_cpu(dev->descriptor.idProduct) == 0x2003) {
2535                         /* doesn't set the sample rate attribute, but supports it */
2536                         fp->attributes |= EP_CS_ATTR_SAMPLE_RATE;
2537                 }
2538
2539                 /*
2540                  * plantronics headset and Griffin iMic have set adaptive-in
2541                  * although it's really not...
2542                  */
2543                 if ((le16_to_cpu(dev->descriptor.idVendor) == 0x047f &&
2544                      le16_to_cpu(dev->descriptor.idProduct) == 0x0ca1) ||
2545                     /* Griffin iMic (note that there is an older model 77d:223) */
2546                     (le16_to_cpu(dev->descriptor.idVendor) == 0x077d &&
2547                      le16_to_cpu(dev->descriptor.idProduct) == 0x07af)) {
2548                         fp->ep_attr &= ~EP_ATTR_MASK;
2549                         if (stream == SNDRV_PCM_STREAM_PLAYBACK)
2550                                 fp->ep_attr |= EP_ATTR_ADAPTIVE;
2551                         else
2552                                 fp->ep_attr |= EP_ATTR_SYNC;
2553                 }
2554
2555                 /* ok, let's parse further... */
2556                 if (parse_audio_format(dev, fp, format, fmt, stream) < 0) {
2557                         kfree(fp->rate_table);
2558                         kfree(fp);
2559                         continue;
2560                 }
2561
2562                 snd_printdd(KERN_INFO "%d:%u:%d: add audio endpoint 0x%x\n", dev->devnum, iface_no, i, fp->endpoint);
2563                 err = add_audio_endpoint(chip, stream, fp);
2564                 if (err < 0) {
2565                         kfree(fp->rate_table);
2566                         kfree(fp);
2567                         return err;
2568                 }
2569                 /* try to set the interface... */
2570                 usb_set_interface(chip->dev, iface_no, altno);
2571                 init_usb_pitch(chip->dev, iface_no, alts, fp);
2572                 init_usb_sample_rate(chip->dev, iface_no, alts, fp, fp->rate_max);
2573         }
2574         return 0;
2575 }
2576
2577
2578 /*
2579  * disconnect streams
2580  * called from snd_usb_audio_disconnect()
2581  */
2582 static void snd_usb_stream_disconnect(struct list_head *head, struct usb_driver *driver)
2583 {
2584         int idx;
2585         snd_usb_stream_t *as;
2586         snd_usb_substream_t *subs;
2587
2588         as = list_entry(head, snd_usb_stream_t, list);
2589         for (idx = 0; idx < 2; idx++) {
2590                 subs = &as->substream[idx];
2591                 if (!subs->num_formats)
2592                         return;
2593                 release_substream_urbs(subs, 1);
2594                 subs->interface = -1;
2595         }
2596 }
2597
2598 /*
2599  * parse audio control descriptor and create pcm/midi streams
2600  */
2601 static int snd_usb_create_streams(snd_usb_audio_t *chip, int ctrlif)
2602 {
2603         struct usb_device *dev = chip->dev;
2604         struct usb_host_interface *host_iface;
2605         struct usb_interface *iface;
2606         unsigned char *p1;
2607         int i, j;
2608
2609         /* find audiocontrol interface */
2610         host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];
2611         if (!(p1 = snd_usb_find_csint_desc(host_iface->extra, host_iface->extralen, NULL, HEADER))) {
2612                 snd_printk(KERN_ERR "cannot find HEADER\n");
2613                 return -EINVAL;
2614         }
2615         if (! p1[7] || p1[0] < 8 + p1[7]) {
2616                 snd_printk(KERN_ERR "invalid HEADER\n");
2617                 return -EINVAL;
2618         }
2619
2620         /*
2621          * parse all USB audio streaming interfaces
2622          */
2623         for (i = 0; i < p1[7]; i++) {
2624                 struct usb_host_interface *alts;
2625                 struct usb_interface_descriptor *altsd;
2626                 j = p1[8 + i];
2627                 iface = usb_ifnum_to_if(dev, j);
2628                 if (!iface) {
2629                         snd_printk(KERN_ERR "%d:%u:%d : does not exist\n",
2630                                    dev->devnum, ctrlif, j);
2631                         continue;
2632                 }
2633                 if (usb_interface_claimed(iface)) {
2634                         snd_printdd(KERN_INFO "%d:%d:%d: skipping, already claimed\n", dev->devnum, ctrlif, j);
2635                         continue;
2636                 }
2637                 alts = &iface->altsetting[0];
2638                 altsd = get_iface_desc(alts);
2639                 if ((altsd->bInterfaceClass == USB_CLASS_AUDIO ||
2640                      altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC) &&
2641                     altsd->bInterfaceSubClass == USB_SUBCLASS_MIDI_STREAMING) {
2642                         if (snd_usb_create_midi_interface(chip, iface, NULL) < 0) {
2643                                 snd_printk(KERN_ERR "%d:%u:%d: cannot create sequencer device\n", dev->devnum, ctrlif, j);
2644                                 continue;
2645                         }
2646                         usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
2647                         continue;
2648                 }
2649                 if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
2650                      altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
2651                     altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIO_STREAMING) {
2652                         snd_printdd(KERN_ERR "%d:%u:%d: skipping non-supported interface %d\n", dev->devnum, ctrlif, j, altsd->bInterfaceClass);
2653                         /* skip non-supported classes */
2654                         continue;
2655                 }
2656                 if (! parse_audio_endpoints(chip, j)) {
2657                         usb_set_interface(dev, j, 0); /* reset the current interface */
2658                         usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
2659                 }
2660         }
2661
2662         return 0;
2663 }
2664
2665 /*
2666  * create a stream for an endpoint/altsetting without proper descriptors
2667  */
2668 static int create_fixed_stream_quirk(snd_usb_audio_t *chip,
2669                                      struct usb_interface *iface,
2670                                      const snd_usb_audio_quirk_t *quirk)
2671 {
2672         struct audioformat *fp;
2673         struct usb_host_interface *alts;
2674         int stream, err;
2675         int *rate_table = NULL;
2676
2677         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
2678         if (! fp) {
2679                 snd_printk(KERN_ERR "cannot malloc\n");
2680                 return -ENOMEM;
2681         }
2682         memcpy(fp, quirk->data, sizeof(*fp));
2683         if (fp->nr_rates > 0) {
2684                 rate_table = kmalloc(sizeof(int) * fp->nr_rates, GFP_KERNEL);
2685                 if (!rate_table) {
2686                         kfree(fp);
2687                         return -ENOMEM;
2688                 }
2689                 memcpy(rate_table, fp->rate_table, sizeof(int) * fp->nr_rates);
2690                 fp->rate_table = rate_table;
2691         }
2692
2693         stream = (fp->endpoint & USB_DIR_IN)
2694                 ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
2695         err = add_audio_endpoint(chip, stream, fp);
2696         if (err < 0) {
2697                 kfree(fp);
2698                 kfree(rate_table);
2699                 return err;
2700         }
2701         if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber ||
2702             fp->altset_idx >= iface->num_altsetting) {
2703                 kfree(fp);
2704                 kfree(rate_table);
2705                 return -EINVAL;
2706         }
2707         alts = &iface->altsetting[fp->altset_idx];
2708         usb_set_interface(chip->dev, fp->iface, 0);
2709         init_usb_pitch(chip->dev, fp->iface, alts, fp);
2710         init_usb_sample_rate(chip->dev, fp->iface, alts, fp, fp->rate_max);
2711         return 0;
2712 }
2713
2714 /*
2715  * create a stream for an interface with proper descriptors
2716  */
2717 static int create_standard_interface_quirk(snd_usb_audio_t *chip,
2718                                            struct usb_interface *iface,
2719                                            const snd_usb_audio_quirk_t *quirk)
2720 {
2721         struct usb_host_interface *alts;
2722         struct usb_interface_descriptor *altsd;
2723         int err;
2724
2725         alts = &iface->altsetting[0];
2726         altsd = get_iface_desc(alts);
2727         switch (quirk->type) {
2728         case QUIRK_AUDIO_STANDARD_INTERFACE:
2729                 err = parse_audio_endpoints(chip, altsd->bInterfaceNumber);
2730                 if (!err)
2731                         usb_set_interface(chip->dev, altsd->bInterfaceNumber, 0); /* reset the current interface */
2732                 break;
2733         case QUIRK_MIDI_STANDARD_INTERFACE:
2734                 err = snd_usb_create_midi_interface(chip, iface, NULL);
2735                 break;
2736         default:
2737                 snd_printd(KERN_ERR "invalid quirk type %d\n", quirk->type);
2738                 return -ENXIO;
2739         }
2740         if (err < 0) {
2741                 snd_printk(KERN_ERR "cannot setup if %d: error %d\n",
2742                            altsd->bInterfaceNumber, err);
2743                 return err;
2744         }
2745         return 0;
2746 }
2747
2748 /*
2749  * Create a stream for an Edirol UA-700/UA-25 interface.  The only way
2750  * to detect the sample rate is by looking at wMaxPacketSize.
2751  */
2752 static int create_ua700_ua25_quirk(snd_usb_audio_t *chip,
2753                                    struct usb_interface *iface)
2754 {
2755         static const struct audioformat ua_format = {
2756                 .format = SNDRV_PCM_FORMAT_S24_3LE,
2757                 .channels = 2,
2758                 .fmt_type = USB_FORMAT_TYPE_I,
2759                 .altsetting = 1,
2760                 .altset_idx = 1,
2761                 .rates = SNDRV_PCM_RATE_CONTINUOUS,
2762         };
2763         struct usb_host_interface *alts;
2764         struct usb_interface_descriptor *altsd;
2765         struct audioformat *fp;
2766         int stream, err;
2767
2768         /* both PCM and MIDI interfaces have 2 altsettings */
2769         if (iface->num_altsetting != 2)
2770                 return -ENXIO;
2771         alts = &iface->altsetting[1];
2772         altsd = get_iface_desc(alts);
2773
2774         if (altsd->bNumEndpoints == 2) {
2775                 static const snd_usb_midi_endpoint_info_t ua700_ep = {
2776                         .out_cables = 0x0003,
2777                         .in_cables  = 0x0003
2778                 };
2779                 static const snd_usb_audio_quirk_t ua700_quirk = {
2780                         .type = QUIRK_MIDI_FIXED_ENDPOINT,
2781                         .data = &ua700_ep
2782                 };
2783                 static const snd_usb_midi_endpoint_info_t ua25_ep = {
2784                         .out_cables = 0x0001,
2785                         .in_cables  = 0x0001
2786                 };
2787                 static const snd_usb_audio_quirk_t ua25_quirk = {
2788                         .type = QUIRK_MIDI_FIXED_ENDPOINT,
2789                         .data = &ua25_ep
2790                 };
2791                 if (le16_to_cpu(chip->dev->descriptor.idProduct) == 0x002b)
2792                         return snd_usb_create_midi_interface(chip, iface,
2793                                                              &ua700_quirk);
2794                 else
2795                         return snd_usb_create_midi_interface(chip, iface,
2796                                                              &ua25_quirk);
2797         }
2798
2799         if (altsd->bNumEndpoints != 1)
2800                 return -ENXIO;
2801
2802         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
2803         if (!fp)
2804                 return -ENOMEM;
2805         memcpy(fp, &ua_format, sizeof(*fp));
2806
2807         fp->iface = altsd->bInterfaceNumber;
2808         fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
2809         fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
2810         fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
2811
2812         switch (fp->maxpacksize) {
2813         case 0x120:
2814                 fp->rate_max = fp->rate_min = 44100;
2815                 break;
2816         case 0x138:
2817         case 0x140:
2818                 fp->rate_max = fp->rate_min = 48000;
2819                 break;
2820         case 0x258:
2821         case 0x260:
2822                 fp->rate_max = fp->rate_min = 96000;
2823                 break;
2824         default:
2825                 snd_printk(KERN_ERR "unknown sample rate\n");
2826                 kfree(fp);
2827                 return -ENXIO;
2828         }
2829
2830         stream = (fp->endpoint & USB_DIR_IN)
2831                 ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
2832         err = add_audio_endpoint(chip, stream, fp);
2833         if (err < 0) {
2834                 kfree(fp);
2835                 return err;
2836         }
2837         usb_set_interface(chip->dev, fp->iface, 0);
2838         return 0;
2839 }
2840
2841 /*
2842  * Create a stream for an Edirol UA-1000 interface.
2843  */
2844 static int create_ua1000_quirk(snd_usb_audio_t *chip, struct usb_interface *iface)
2845 {
2846         static const struct audioformat ua1000_format = {
2847                 .format = SNDRV_PCM_FORMAT_S32_LE,
2848                 .fmt_type = USB_FORMAT_TYPE_I,
2849                 .altsetting = 1,
2850                 .altset_idx = 1,
2851                 .attributes = 0,
2852                 .rates = SNDRV_PCM_RATE_CONTINUOUS,
2853         };
2854         struct usb_host_interface *alts;
2855         struct usb_interface_descriptor *altsd;
2856         struct audioformat *fp;
2857         int stream, err;
2858
2859         if (iface->num_altsetting != 2)
2860                 return -ENXIO;
2861         alts = &iface->altsetting[1];
2862         altsd = get_iface_desc(alts);
2863         if (alts->extralen != 11 || alts->extra[1] != CS_AUDIO_INTERFACE ||
2864             altsd->bNumEndpoints != 1)
2865                 return -ENXIO;
2866
2867         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
2868         if (!fp)
2869                 return -ENOMEM;
2870         memcpy(fp, &ua1000_format, sizeof(*fp));
2871
2872         fp->channels = alts->extra[4];
2873         fp->iface = altsd->bInterfaceNumber;
2874         fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
2875         fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
2876         fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
2877         fp->rate_max = fp->rate_min = combine_triple(&alts->extra[8]);
2878
2879         stream = (fp->endpoint & USB_DIR_IN)
2880                 ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
2881         err = add_audio_endpoint(chip, stream, fp);
2882         if (err < 0) {
2883                 kfree(fp);
2884                 return err;
2885         }
2886         /* FIXME: playback must be synchronized to capture */
2887         usb_set_interface(chip->dev, fp->iface, 0);
2888         return 0;
2889 }
2890
2891 static int snd_usb_create_quirk(snd_usb_audio_t *chip,
2892                                 struct usb_interface *iface,
2893                                 const snd_usb_audio_quirk_t *quirk);
2894
2895 /*
2896  * handle the quirks for the contained interfaces
2897  */
2898 static int create_composite_quirk(snd_usb_audio_t *chip,
2899                                   struct usb_interface *iface,
2900                                   const snd_usb_audio_quirk_t *quirk)
2901 {
2902         int probed_ifnum = get_iface_desc(iface->altsetting)->bInterfaceNumber;
2903         int err;
2904
2905         for (quirk = quirk->data; quirk->ifnum >= 0; ++quirk) {
2906                 iface = usb_ifnum_to_if(chip->dev, quirk->ifnum);
2907                 if (!iface)
2908                         continue;
2909                 if (quirk->ifnum != probed_ifnum &&
2910                     usb_interface_claimed(iface))
2911                         continue;
2912                 err = snd_usb_create_quirk(chip, iface, quirk);
2913                 if (err < 0)
2914                         return err;
2915                 if (quirk->ifnum != probed_ifnum)
2916                         usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
2917         }
2918         return 0;
2919 }
2920
2921
2922 /*
2923  * boot quirks
2924  */
2925
2926 #define EXTIGY_FIRMWARE_SIZE_OLD 794
2927 #define EXTIGY_FIRMWARE_SIZE_NEW 483
2928
2929 static int snd_usb_extigy_boot_quirk(struct usb_device *dev, struct usb_interface *intf)
2930 {
2931         struct usb_host_config *config = dev->actconfig;
2932         int err;
2933
2934         if (le16_to_cpu(get_cfg_desc(config)->wTotalLength) == EXTIGY_FIRMWARE_SIZE_OLD ||
2935             le16_to_cpu(get_cfg_desc(config)->wTotalLength) == EXTIGY_FIRMWARE_SIZE_NEW) {
2936                 snd_printdd("sending Extigy boot sequence...\n");
2937                 /* Send message to force it to reconnect with full interface. */
2938                 err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev,0),
2939                                       0x10, 0x43, 0x0001, 0x000a, NULL, 0, HZ);
2940                 if (err < 0) snd_printdd("error sending boot message: %d\n", err);
2941                 err = usb_get_descriptor(dev, USB_DT_DEVICE, 0,
2942                                 &dev->descriptor, sizeof(dev->descriptor));
2943                 config = dev->actconfig;
2944                 if (err < 0) snd_printdd("error usb_get_descriptor: %d\n", err);
2945                 err = usb_reset_configuration(dev);
2946                 if (err < 0) snd_printdd("error usb_reset_configuration: %d\n", err);
2947                 snd_printdd("extigy_boot: new boot length = %d\n",
2948                             le16_to_cpu(get_cfg_desc(config)->wTotalLength));
2949                 return -ENODEV; /* quit this anyway */
2950         }
2951         return 0;
2952 }
2953
2954
2955 /*
2956  * audio-interface quirks
2957  *
2958  * returns zero if no standard audio/MIDI parsing is needed.
2959  * returns a postive value if standard audio/midi interfaces are parsed
2960  * after this.
2961  * returns a negative value at error.
2962  */
2963 static int snd_usb_create_quirk(snd_usb_audio_t *chip,
2964                                 struct usb_interface *iface,
2965                                 const snd_usb_audio_quirk_t *quirk)
2966 {
2967         switch (quirk->type) {
2968         case QUIRK_MIDI_FIXED_ENDPOINT:
2969         case QUIRK_MIDI_YAMAHA:
2970         case QUIRK_MIDI_MIDIMAN:
2971                 return snd_usb_create_midi_interface(chip, iface, quirk);
2972         case QUIRK_COMPOSITE:
2973                 return create_composite_quirk(chip, iface, quirk);
2974         case QUIRK_AUDIO_FIXED_ENDPOINT:
2975                 return create_fixed_stream_quirk(chip, iface, quirk);
2976         case QUIRK_AUDIO_STANDARD_INTERFACE:
2977         case QUIRK_MIDI_STANDARD_INTERFACE:
2978                 return create_standard_interface_quirk(chip, iface, quirk);
2979         case QUIRK_AUDIO_EDIROL_UA700_UA25:
2980                 return create_ua700_ua25_quirk(chip, iface);
2981         case QUIRK_AUDIO_EDIROL_UA1000:
2982                 return create_ua1000_quirk(chip, iface);
2983         default:
2984                 snd_printd(KERN_ERR "invalid quirk type %d\n", quirk->type);
2985                 return -ENXIO;
2986         }
2987 }
2988
2989
2990 /*
2991  * common proc files to show the usb device info
2992  */
2993 static void proc_audio_usbbus_read(snd_info_entry_t *entry, snd_info_buffer_t *buffer)
2994 {
2995         snd_usb_audio_t *chip = entry->private_data;
2996         if (! chip->shutdown)
2997                 snd_iprintf(buffer, "%03d/%03d\n", chip->dev->bus->busnum, chip->dev->devnum);
2998 }
2999
3000 static void proc_audio_usbid_read(snd_info_entry_t *entry, snd_info_buffer_t *buffer)
3001 {
3002         snd_usb_audio_t *chip = entry->private_data;
3003         if (! chip->shutdown)
3004                 snd_iprintf(buffer, "%04x:%04x\n", 
3005                             le16_to_cpu(chip->dev->descriptor.idVendor),
3006                             le16_to_cpu(chip->dev->descriptor.idProduct));
3007 }
3008
3009 static void snd_usb_audio_create_proc(snd_usb_audio_t *chip)
3010 {
3011         snd_info_entry_t *entry;
3012         if (! snd_card_proc_new(chip->card, "usbbus", &entry))
3013                 snd_info_set_text_ops(entry, chip, 1024, proc_audio_usbbus_read);
3014         if (! snd_card_proc_new(chip->card, "usbid", &entry))
3015                 snd_info_set_text_ops(entry, chip, 1024, proc_audio_usbid_read);
3016 }
3017
3018 /*
3019  * free the chip instance
3020  *
3021  * here we have to do not much, since pcm and controls are already freed
3022  *
3023  */
3024
3025 static int snd_usb_audio_free(snd_usb_audio_t *chip)
3026 {
3027         kfree(chip);
3028         return 0;
3029 }
3030
3031 static int snd_usb_audio_dev_free(snd_device_t *device)
3032 {
3033         snd_usb_audio_t *chip = device->device_data;
3034         return snd_usb_audio_free(chip);
3035 }
3036
3037
3038 /*
3039  * create a chip instance and set its names.
3040  */
3041 static int snd_usb_audio_create(struct usb_device *dev, int idx,
3042                                 const snd_usb_audio_quirk_t *quirk,
3043                                 snd_usb_audio_t **rchip)
3044 {
3045         snd_card_t *card;
3046         snd_usb_audio_t *chip;
3047         int err, len;
3048         char component[14];
3049         static snd_device_ops_t ops = {
3050                 .dev_free =     snd_usb_audio_dev_free,
3051         };
3052
3053         *rchip = NULL;
3054
3055         if (snd_usb_get_speed(dev) != USB_SPEED_FULL &&
3056             snd_usb_get_speed(dev) != USB_SPEED_HIGH) {
3057                 snd_printk(KERN_ERR "unknown device speed %d\n", snd_usb_get_speed(dev));
3058                 return -ENXIO;
3059         }
3060
3061         card = snd_card_new(index[idx], id[idx], THIS_MODULE, 0);
3062         if (card == NULL) {
3063                 snd_printk(KERN_ERR "cannot create card instance %d\n", idx);
3064                 return -ENOMEM;
3065         }
3066
3067         chip = kcalloc(1, sizeof(*chip), GFP_KERNEL);
3068         if (! chip) {
3069                 snd_card_free(card);
3070                 return -ENOMEM;
3071         }
3072
3073         chip->index = idx;
3074         chip->dev = dev;
3075         chip->card = card;
3076         INIT_LIST_HEAD(&chip->pcm_list);
3077         INIT_LIST_HEAD(&chip->midi_list);
3078
3079         if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
3080                 snd_usb_audio_free(chip);
3081                 snd_card_free(card);
3082                 return err;
3083         }
3084
3085         strcpy(card->driver, "USB-Audio");
3086         sprintf(component, "USB%04x:%04x",
3087                 le16_to_cpu(dev->descriptor.idVendor),
3088                 le16_to_cpu(dev->descriptor.idProduct));
3089         snd_component_add(card, component);
3090
3091         /* retrieve the device string as shortname */
3092         if (quirk && quirk->product_name) {
3093                 strlcpy(card->shortname, quirk->product_name, sizeof(card->shortname));
3094         } else {
3095                 if (!dev->descriptor.iProduct ||
3096                     usb_string(dev, dev->descriptor.iProduct,
3097                                card->shortname, sizeof(card->shortname)) <= 0) {
3098                         /* no name available from anywhere, so use ID */
3099                         sprintf(card->shortname, "USB Device %#04x:%#04x",
3100                                 le16_to_cpu(dev->descriptor.idVendor),
3101                                 le16_to_cpu(dev->descriptor.idProduct));
3102                 }
3103         }
3104
3105         /* retrieve the vendor and device strings as longname */
3106         if (quirk && quirk->vendor_name) {
3107                 len = strlcpy(card->longname, quirk->vendor_name, sizeof(card->longname));
3108         } else {
3109                 if (dev->descriptor.iManufacturer)
3110                         len = usb_string(dev, dev->descriptor.iManufacturer,
3111                                          card->longname, sizeof(card->longname));
3112                 else
3113                         len = 0;
3114                 /* we don't really care if there isn't any vendor string */
3115         }
3116         if (len > 0)
3117                 strlcat(card->longname, " ", sizeof(card->longname));
3118
3119         strlcat(card->longname, card->shortname, sizeof(card->longname));
3120
3121         len = strlcat(card->longname, " at ", sizeof(card->longname));
3122
3123         if (len < sizeof(card->longname))
3124                 usb_make_path(dev, card->longname + len, sizeof(card->longname) - len);
3125
3126         strlcat(card->longname,
3127                 snd_usb_get_speed(dev) == USB_SPEED_FULL ? ", full speed" : ", high speed",
3128                 sizeof(card->longname));
3129
3130         snd_usb_audio_create_proc(chip);
3131
3132         snd_card_set_dev(card, &dev->dev);
3133
3134         *rchip = chip;
3135         return 0;
3136 }
3137
3138
3139 /*
3140  * probe the active usb device
3141  *
3142  * note that this can be called multiple times per a device, when it
3143  * includes multiple audio control interfaces.
3144  *
3145  * thus we check the usb device pointer and creates the card instance
3146  * only at the first time.  the successive calls of this function will
3147  * append the pcm interface to the corresponding card.
3148  */
3149 static void *snd_usb_audio_probe(struct usb_device *dev,
3150                                  struct usb_interface *intf,
3151                                  const struct usb_device_id *usb_id)
3152 {
3153         struct usb_host_config *config = dev->actconfig;
3154         const snd_usb_audio_quirk_t *quirk = (const snd_usb_audio_quirk_t *)usb_id->driver_info;
3155         int i, err;
3156         snd_usb_audio_t *chip;
3157         struct usb_host_interface *alts;
3158         int ifnum;
3159
3160         alts = &intf->altsetting[0];
3161         ifnum = get_iface_desc(alts)->bInterfaceNumber;
3162
3163         if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)
3164                 goto __err_val;
3165
3166         /* SB Extigy needs special boot-up sequence */
3167         /* if more models come, this will go to the quirk list. */
3168         if (le16_to_cpu(dev->descriptor.idVendor) == 0x041e && 
3169             le16_to_cpu(dev->descriptor.idProduct) == 0x3000) {
3170                 if (snd_usb_extigy_boot_quirk(dev, intf) < 0)
3171                         goto __err_val;
3172                 config = dev->actconfig;
3173         }
3174
3175         /*
3176          * found a config.  now register to ALSA
3177          */
3178
3179         /* check whether it's already registered */
3180         chip = NULL;
3181         down(&register_mutex);
3182         for (i = 0; i < SNDRV_CARDS; i++) {
3183                 if (usb_chip[i] && usb_chip[i]->dev == dev) {
3184                         if (usb_chip[i]->shutdown) {
3185                                 snd_printk(KERN_ERR "USB device is in the shutdown state, cannot create a card instance\n");
3186                                 goto __error;
3187                         }
3188                         chip = usb_chip[i];
3189                         break;
3190                 }
3191         }
3192         if (! chip) {
3193                 /* it's a fresh one.
3194                  * now look for an empty slot and create a new card instance
3195                  */
3196                 /* first, set the current configuration for this device */
3197                 if (usb_reset_configuration(dev) < 0) {
3198                         snd_printk(KERN_ERR "cannot reset configuration (value 0x%x)\n", get_cfg_desc(config)->bConfigurationValue);
3199                         goto __error;
3200                 }
3201                 for (i = 0; i < SNDRV_CARDS; i++)
3202                         if (enable[i] && ! usb_chip[i] &&
3203                             (vid[i] == -1 || vid[i] == le16_to_cpu(dev->descriptor.idVendor)) &&
3204                             (pid[i] == -1 || pid[i] == le16_to_cpu(dev->descriptor.idProduct))) {
3205                                 if (snd_usb_audio_create(dev, i, quirk, &chip) < 0) {
3206                                         goto __error;
3207                                 }
3208                                 break;
3209                         }
3210                 if (! chip) {
3211                         snd_printk(KERN_ERR "no available usb audio device\n");
3212                         goto __error;
3213                 }
3214         }
3215
3216         err = 1; /* continue */
3217         if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {
3218                 /* need some special handlings */
3219                 if ((err = snd_usb_create_quirk(chip, intf, quirk)) < 0)
3220                         goto __error;
3221         }
3222
3223         if (err > 0) {
3224                 /* create normal USB audio interfaces */
3225                 if (snd_usb_create_streams(chip, ifnum) < 0 ||
3226                     snd_usb_create_mixer(chip, ifnum) < 0) {
3227                         goto __error;
3228                 }
3229         }
3230
3231         /* we are allowed to call snd_card_register() many times */
3232         if (snd_card_register(chip->card) < 0) {
3233                 goto __error;
3234         }
3235
3236         usb_chip[chip->index] = chip;
3237         chip->num_interfaces++;
3238         up(&register_mutex);
3239         return chip;
3240
3241  __error:
3242         if (chip && !chip->num_interfaces)
3243                 snd_card_free(chip->card);
3244         up(&register_mutex);
3245  __err_val:
3246         return NULL;
3247 }
3248
3249 /*
3250  * we need to take care of counter, since disconnection can be called also
3251  * many times as well as usb_audio_probe().
3252  */
3253 static void snd_usb_audio_disconnect(struct usb_device *dev, void *ptr)
3254 {
3255         snd_usb_audio_t *chip;
3256         snd_card_t *card;
3257         struct list_head *p;
3258
3259         if (ptr == (void *)-1L)
3260                 return;
3261
3262         chip = ptr;
3263         card = chip->card;
3264         down(&register_mutex);
3265         chip->shutdown = 1;
3266         chip->num_interfaces--;
3267         if (chip->num_interfaces <= 0) {
3268                 snd_card_disconnect(card);
3269                 /* release the pcm resources */
3270                 list_for_each(p, &chip->pcm_list) {
3271                         snd_usb_stream_disconnect(p, &usb_audio_driver);
3272                 }
3273                 /* release the midi resources */
3274                 list_for_each(p, &chip->midi_list) {
3275                         snd_usbmidi_disconnect(p, &usb_audio_driver);
3276                 }
3277                 usb_chip[chip->index] = NULL;
3278                 up(&register_mutex);
3279                 snd_card_free(card);
3280         } else {
3281                 up(&register_mutex);
3282         }
3283 }
3284
3285 /*
3286  * new 2.5 USB kernel API
3287  */
3288 static int usb_audio_probe(struct usb_interface *intf,
3289                            const struct usb_device_id *id)
3290 {
3291         void *chip;
3292         chip = snd_usb_audio_probe(interface_to_usbdev(intf), intf, id);
3293         if (chip) {
3294                 dev_set_drvdata(&intf->dev, chip);
3295                 return 0;
3296         } else
3297                 return -EIO;
3298 }
3299
3300 static void usb_audio_disconnect(struct usb_interface *intf)
3301 {
3302         snd_usb_audio_disconnect(interface_to_usbdev(intf),
3303                                  dev_get_drvdata(&intf->dev));
3304 }
3305
3306
3307 static int __init snd_usb_audio_init(void)
3308 {
3309         if (nrpacks < MIN_PACKS_URB || nrpacks > MAX_PACKS) {
3310                 printk(KERN_WARNING "invalid nrpacks value.\n");
3311                 return -EINVAL;
3312         }
3313         usb_register(&usb_audio_driver);
3314         return 0;
3315 }
3316
3317
3318 static void __exit snd_usb_audio_cleanup(void)
3319 {
3320         usb_deregister(&usb_audio_driver);
3321 }
3322
3323 module_init(snd_usb_audio_init);
3324 module_exit(snd_usb_audio_cleanup);