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