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