]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/sound/usb/uaudio.c
Make sure the vendor class quirk only matches the vendor specific
[FreeBSD/FreeBSD.git] / sys / dev / sound / usb / uaudio.c
1 /*      $NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $ */
2 /*      $FreeBSD$ */
3
4 /*-
5  * Copyright (c) 1999 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 /*
38  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
39  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
40  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
41  */
42
43 /*
44  * Also merged:
45  *  $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $
46  *  $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $
47  *  $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $
48  *  $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $
49  */
50
51 #include <sys/stdint.h>
52 #include <sys/stddef.h>
53 #include <sys/param.h>
54 #include <sys/queue.h>
55 #include <sys/types.h>
56 #include <sys/systm.h>
57 #include <sys/kernel.h>
58 #include <sys/bus.h>
59 #include <sys/module.h>
60 #include <sys/lock.h>
61 #include <sys/mutex.h>
62 #include <sys/condvar.h>
63 #include <sys/sysctl.h>
64 #include <sys/sx.h>
65 #include <sys/unistd.h>
66 #include <sys/callout.h>
67 #include <sys/malloc.h>
68 #include <sys/priv.h>
69
70 #include "usbdevs.h"
71 #include <dev/usb/usb.h>
72 #include <dev/usb/usbdi.h>
73 #include <dev/usb/usbdi_util.h>
74
75 #define USB_DEBUG_VAR uaudio_debug
76 #include <dev/usb/usb_debug.h>
77
78 #include <dev/usb/quirk/usb_quirk.h>
79
80 #include <sys/reboot.h>                 /* for bootverbose */
81
82 #ifdef HAVE_KERNEL_OPTION_HEADERS
83 #include "opt_snd.h"
84 #endif
85
86 #include <dev/sound/pcm/sound.h>
87 #include <dev/sound/usb/uaudioreg.h>
88 #include <dev/sound/usb/uaudio.h>
89 #include <dev/sound/chip.h>
90 #include "feeder_if.h"
91
92 static int uaudio_default_rate = 0;             /* use rate list */
93 static int uaudio_default_bits = 32;
94 static int uaudio_default_channels = 0;         /* use default */
95
96 #ifdef USB_DEBUG
97 static int uaudio_debug = 0;
98
99 static SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW, 0, "USB uaudio");
100
101 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RW,
102     &uaudio_debug, 0, "uaudio debug level");
103
104 TUNABLE_INT("hw.usb.uaudio.default_rate", &uaudio_default_rate);
105 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_rate, CTLFLAG_RW,
106     &uaudio_default_rate, 0, "uaudio default sample rate");
107
108 TUNABLE_INT("hw.usb.uaudio.default_bits", &uaudio_default_bits);
109 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_bits, CTLFLAG_RW,
110     &uaudio_default_bits, 0, "uaudio default sample bits");
111
112 TUNABLE_INT("hw.usb.uaudio.default_channels", &uaudio_default_channels);
113 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_channels, CTLFLAG_RW,
114     &uaudio_default_channels, 0, "uaudio default sample channels");
115 #endif
116
117 #define UAUDIO_NFRAMES          64      /* must be factor of 8 due HS-USB */
118 #define UAUDIO_NCHANBUFS        2       /* number of outstanding request */
119 #define UAUDIO_RECURSE_LIMIT    255     /* rounds */
120
121 #define MAKE_WORD(h,l) (((h) << 8) | (l))
122 #define BIT_TEST(bm,bno) (((bm)[(bno) / 8] >> (7 - ((bno) % 8))) & 1)
123 #define UAUDIO_MAX_CHAN(x) (x)
124
125 union uaudio_asid {
126         const struct usb_audio_streaming_interface_descriptor *v1;
127         const struct usb_audio20_streaming_interface_descriptor *v2;
128 };
129
130 union uaudio_asf1d {
131         const struct usb_audio_streaming_type1_descriptor *v1;
132         const struct usb_audio20_streaming_type1_descriptor *v2;
133 };
134
135 union uaudio_sed {
136         const struct usb_audio_streaming_endpoint_descriptor *v1;
137         const struct usb_audio20_streaming_endpoint_descriptor *v2;
138 };
139
140 struct uaudio_mixer_node {
141         int32_t minval;
142         int32_t maxval;
143 #define MIX_MAX_CHAN 8
144         int32_t wValue[MIX_MAX_CHAN];   /* using nchan */
145         uint32_t mul;
146         uint32_t ctl;
147
148         uint16_t wData[MIX_MAX_CHAN];   /* using nchan */
149         uint16_t wIndex;
150
151         uint8_t update[(MIX_MAX_CHAN + 7) / 8];
152         uint8_t nchan;
153         uint8_t type;
154 #define MIX_ON_OFF      1
155 #define MIX_SIGNED_16   2
156 #define MIX_UNSIGNED_16 3
157 #define MIX_SIGNED_8    4
158 #define MIX_SELECTOR    5
159 #define MIX_UNKNOWN     6
160 #define MIX_SIZE(n) ((((n) == MIX_SIGNED_16) || \
161                       ((n) == MIX_UNSIGNED_16)) ? 2 : 1)
162 #define MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
163
164 #define MAX_SELECTOR_INPUT_PIN 256
165         uint8_t slctrtype[MAX_SELECTOR_INPUT_PIN];
166         uint8_t class;
167
168         struct uaudio_mixer_node *next;
169 };
170
171 struct uaudio_chan {
172         struct pcmchan_caps pcm_cap;    /* capabilities */
173
174         struct snd_dbuf *pcm_buf;
175         const struct usb_config *usb_cfg;
176         struct mtx *pcm_mtx;            /* lock protecting this structure */
177         struct uaudio_softc *priv_sc;
178         struct pcm_channel *pcm_ch;
179         struct usb_xfer *xfer[UAUDIO_NCHANBUFS];
180         union uaudio_asf1d p_asf1d;
181         union uaudio_sed p_sed;
182         const usb_endpoint_descriptor_audio_t *p_ed1;
183         const struct uaudio_format *p_fmt;
184
185         uint8_t *buf;                   /* pointer to buffer */
186         uint8_t *start;                 /* upper layer buffer start */
187         uint8_t *end;                   /* upper layer buffer end */
188         uint8_t *cur;                   /* current position in upper layer
189                                          * buffer */
190
191         uint32_t intr_size;             /* in bytes */
192         uint32_t intr_frames;           /* in units */
193         uint32_t sample_rate;
194         uint32_t frames_per_second;
195         uint32_t sample_rem;
196         uint32_t sample_curr;
197
198         uint32_t format;
199         uint32_t pcm_format[2];
200
201         uint16_t bytes_per_frame[2];
202
203         uint16_t sample_size;
204
205         uint8_t valid;
206         uint8_t iface_index;
207         uint8_t iface_alt_index;
208         uint8_t channels;
209 };
210
211 #define UMIDI_CABLES_MAX   16           /* units */
212 #define UMIDI_TX_FRAMES    256          /* units */
213 #define UMIDI_TX_BUFFER    (UMIDI_TX_FRAMES * 4)        /* bytes */
214
215 enum {
216         UMIDI_TX_TRANSFER,
217         UMIDI_RX_TRANSFER,
218         UMIDI_N_TRANSFER,
219 };
220
221 struct umidi_sub_chan {
222         struct usb_fifo_sc fifo;
223         uint8_t *temp_cmd;
224         uint8_t temp_0[4];
225         uint8_t temp_1[4];
226         uint8_t state;
227 #define UMIDI_ST_UNKNOWN   0            /* scan for command */
228 #define UMIDI_ST_1PARAM    1
229 #define UMIDI_ST_2PARAM_1  2
230 #define UMIDI_ST_2PARAM_2  3
231 #define UMIDI_ST_SYSEX_0   4
232 #define UMIDI_ST_SYSEX_1   5
233 #define UMIDI_ST_SYSEX_2   6
234
235         uint8_t read_open:1;
236         uint8_t write_open:1;
237         uint8_t unused:6;
238 };
239
240 struct umidi_chan {
241
242         struct umidi_sub_chan sub[UMIDI_CABLES_MAX];
243         struct mtx mtx;
244
245         struct usb_xfer *xfer[UMIDI_N_TRANSFER];
246
247         uint8_t iface_index;
248         uint8_t iface_alt_index;
249
250         uint8_t read_open_refcount;
251         uint8_t write_open_refcount;
252
253         uint8_t curr_cable;
254         uint8_t max_cable;
255         uint8_t valid;
256         uint8_t single_command;
257 };
258
259 struct uaudio_search_result {
260         uint8_t bit_input[(256 + 7) / 8];
261         uint8_t bit_output[(256 + 7) / 8];
262         uint8_t recurse_level;
263         uint8_t id_max;
264         uint8_t is_input;
265 };
266
267 struct uaudio_softc {
268         struct sbuf sc_sndstat;
269         struct sndcard_func sc_sndcard_func;
270         struct uaudio_chan sc_rec_chan;
271         struct uaudio_chan sc_play_chan;
272         struct umidi_chan sc_midi_chan;
273         struct uaudio_search_result sc_mixer_clocks;
274
275         struct usb_device *sc_udev;
276         struct usb_xfer *sc_mixer_xfer[1];
277         struct uaudio_mixer_node *sc_mixer_root;
278         struct uaudio_mixer_node *sc_mixer_curr;
279
280         uint32_t sc_mix_info;
281         uint32_t sc_recsrc_info;
282
283         uint16_t sc_audio_rev;
284         uint16_t sc_mixer_count;
285
286         uint8_t sc_sndstat_valid;
287         uint8_t sc_mixer_iface_index;
288         uint8_t sc_mixer_iface_no;
289         uint8_t sc_mixer_chan;
290         uint8_t sc_pcm_registered:1;
291         uint8_t sc_mixer_init:1;
292         uint8_t sc_uq_audio_swap_lr:1;
293         uint8_t sc_uq_au_inp_async:1;
294         uint8_t sc_uq_au_no_xu:1;
295         uint8_t sc_uq_bad_adc:1;
296         uint8_t sc_uq_au_vendor_class:1;
297 };
298
299 struct uaudio_terminal_node {
300         union {
301                 const struct usb_descriptor *desc;
302                 const struct usb_audio_input_terminal *it_v1;
303                 const struct usb_audio_output_terminal *ot_v1;
304                 const struct usb_audio_mixer_unit_0 *mu_v1;
305                 const struct usb_audio_selector_unit *su_v1;
306                 const struct usb_audio_feature_unit *fu_v1;
307                 const struct usb_audio_processing_unit_0 *pu_v1;
308                 const struct usb_audio_extension_unit_0 *eu_v1;
309                 const struct usb_audio20_clock_source_unit *csrc_v2;
310                 const struct usb_audio20_clock_selector_unit_0 *csel_v2;
311                 const struct usb_audio20_clock_multiplier_unit *cmul_v2;
312                 const struct usb_audio20_input_terminal *it_v2;
313                 const struct usb_audio20_output_terminal *ot_v2;
314                 const struct usb_audio20_mixer_unit_0 *mu_v2;
315                 const struct usb_audio20_selector_unit *su_v2;
316                 const struct usb_audio20_feature_unit *fu_v2;
317                 const struct usb_audio20_sample_rate_unit *ru_v2;
318                 const struct usb_audio20_processing_unit_0 *pu_v2;
319                 const struct usb_audio20_extension_unit_0 *eu_v2;
320                 const struct usb_audio20_effect_unit *ef_v2;
321         }       u;
322         struct uaudio_search_result usr;
323         struct uaudio_terminal_node *root;
324 };
325
326 struct uaudio_format {
327         uint16_t wFormat;
328         uint8_t bPrecision;
329         uint32_t freebsd_fmt;
330         const char *description;
331 };
332
333 static const struct uaudio_format uaudio10_formats[] = {
334
335         {UA_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
336         {UA_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
337         {UA_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
338         {UA_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
339
340         {UA_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
341         {UA_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
342         {UA_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
343         {UA_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
344
345         {UA_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
346         {UA_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
347
348         {0, 0, 0, NULL}
349 };
350
351 static const struct uaudio_format uaudio20_formats[] = {
352
353         {UA20_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"},
354         {UA20_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"},
355         {UA20_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"},
356         {UA20_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"},
357
358         {UA20_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"},
359         {UA20_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"},
360         {UA20_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"},
361         {UA20_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"},
362
363         {UA20_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"},
364         {UA20_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"},
365
366         {0, 0, 0, NULL}
367 };
368
369 #define UAC_OUTPUT      0
370 #define UAC_INPUT       1
371 #define UAC_EQUAL       2
372 #define UAC_RECORD      3
373 #define UAC_NCLASSES    4
374
375 #ifdef USB_DEBUG
376 static const char *uac_names[] = {
377         "outputs", "inputs", "equalization", "record"
378 };
379
380 #endif
381
382 /* prototypes */
383
384 static device_probe_t uaudio_probe;
385 static device_attach_t uaudio_attach;
386 static device_detach_t uaudio_detach;
387
388 static usb_callback_t uaudio_chan_play_callback;
389 static usb_callback_t uaudio_chan_record_callback;
390 static usb_callback_t uaudio_mixer_write_cfg_callback;
391 static usb_callback_t umidi_bulk_read_callback;
392 static usb_callback_t umidi_bulk_write_callback;
393
394 /* ==== USB audio v1.0 ==== */
395
396 static void     uaudio_mixer_add_mixer(struct uaudio_softc *,
397                     const struct uaudio_terminal_node *, int);
398 static void     uaudio_mixer_add_selector(struct uaudio_softc *,
399                     const struct uaudio_terminal_node *, int);
400 static uint32_t uaudio_mixer_feature_get_bmaControls(
401                     const struct usb_audio_feature_unit *, uint8_t);
402 static void     uaudio_mixer_add_feature(struct uaudio_softc *,
403                     const struct uaudio_terminal_node *, int);
404 static void     uaudio_mixer_add_processing_updown(struct uaudio_softc *,
405                     const struct uaudio_terminal_node *, int);
406 static void     uaudio_mixer_add_processing(struct uaudio_softc *,
407                     const struct uaudio_terminal_node *, int);
408 static void     uaudio_mixer_add_extension(struct uaudio_softc *,
409                     const struct uaudio_terminal_node *, int);
410 static struct   usb_audio_cluster uaudio_mixer_get_cluster(uint8_t,
411                     const struct uaudio_terminal_node *);
412 static uint16_t uaudio_mixer_determine_class(const struct uaudio_terminal_node *,
413                     struct uaudio_mixer_node *);
414 static uint16_t uaudio_mixer_feature_name(const struct uaudio_terminal_node *,
415                     struct uaudio_mixer_node *);
416 static void     uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *,
417                     const uint8_t *, uint8_t, struct uaudio_search_result *);
418 static const void *uaudio_mixer_verify_desc(const void *, uint32_t);
419 static usb_error_t uaudio_set_speed(struct usb_device *, uint8_t, uint32_t);
420 static int      uaudio_mixer_get(struct usb_device *, uint16_t, uint8_t,
421                     struct uaudio_mixer_node *);
422
423 /* ==== USB audio v2.0 ==== */
424
425 static void     uaudio20_mixer_add_mixer(struct uaudio_softc *,
426                     const struct uaudio_terminal_node *, int);
427 static void     uaudio20_mixer_add_selector(struct uaudio_softc *,
428                     const struct uaudio_terminal_node *, int);
429 static void     uaudio20_mixer_add_feature(struct uaudio_softc *,
430                     const struct uaudio_terminal_node *, int);
431 static struct   usb_audio20_cluster uaudio20_mixer_get_cluster(uint8_t,
432                     const struct uaudio_terminal_node *);
433 static uint16_t uaudio20_mixer_determine_class(const struct uaudio_terminal_node *,
434                     struct uaudio_mixer_node *);
435 static uint16_t uaudio20_mixer_feature_name(const struct uaudio_terminal_node *,
436                     struct uaudio_mixer_node *);
437 static void     uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *,
438                     const uint8_t *, uint8_t, struct uaudio_search_result *);
439 static const void *uaudio20_mixer_verify_desc(const void *, uint32_t);
440 static usb_error_t uaudio20_set_speed(struct usb_device *, uint8_t,
441                     uint8_t, uint32_t);
442
443 /* USB audio v1.0 and v2.0 */
444
445 static void     uaudio_chan_fill_info_sub(struct uaudio_softc *,
446                     struct usb_device *, uint32_t, uint8_t, uint8_t);
447 static void     uaudio_chan_fill_info(struct uaudio_softc *,
448                     struct usb_device *);
449 static void     uaudio_mixer_add_ctl_sub(struct uaudio_softc *,
450                     struct uaudio_mixer_node *);
451 static void     uaudio_mixer_add_ctl(struct uaudio_softc *,
452                     struct uaudio_mixer_node *);
453 static void     uaudio_mixer_fill_info(struct uaudio_softc *,
454                     struct usb_device *, void *);
455 static void     uaudio_mixer_ctl_set(struct uaudio_softc *,
456                     struct uaudio_mixer_node *, uint8_t, int32_t val);
457 static int      uaudio_mixer_signext(uint8_t, int);
458 static int      uaudio_mixer_bsd2value(struct uaudio_mixer_node *, int32_t val);
459 static void     uaudio_mixer_init(struct uaudio_softc *);
460 static const struct uaudio_terminal_node *uaudio_mixer_get_input(
461                     const struct uaudio_terminal_node *, uint8_t);
462 static const struct uaudio_terminal_node *uaudio_mixer_get_output(
463                     const struct uaudio_terminal_node *, uint8_t);
464 static void     uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *,
465                     uint8_t, uint8_t, struct uaudio_search_result *);
466 static uint8_t  umidi_convert_to_usb(struct umidi_sub_chan *, uint8_t, uint8_t);
467 static struct   umidi_sub_chan *umidi_sub_by_fifo(struct usb_fifo *);
468 static void     umidi_start_read(struct usb_fifo *);
469 static void     umidi_stop_read(struct usb_fifo *);
470 static void     umidi_start_write(struct usb_fifo *);
471 static void     umidi_stop_write(struct usb_fifo *);
472 static int      umidi_open(struct usb_fifo *, int);
473 static int      umidi_ioctl(struct usb_fifo *, u_long cmd, void *, int);
474 static void     umidi_close(struct usb_fifo *, int);
475 static void     umidi_init(device_t dev);
476 static int      umidi_probe(device_t dev);
477 static int      umidi_detach(device_t dev);
478
479 #ifdef USB_DEBUG
480 static void     uaudio_chan_dump_ep_desc(
481                     const usb_endpoint_descriptor_audio_t *);
482 #endif
483
484 static const struct usb_config
485         uaudio_cfg_record[UAUDIO_NCHANBUFS] = {
486         [0] = {
487                 .type = UE_ISOCHRONOUS,
488                 .endpoint = UE_ADDR_ANY,
489                 .direction = UE_DIR_IN,
490                 .bufsize = 0,   /* use "wMaxPacketSize * frames" */
491                 .frames = UAUDIO_NFRAMES,
492                 .flags = {.short_xfer_ok = 1,},
493                 .callback = &uaudio_chan_record_callback,
494         },
495
496         [1] = {
497                 .type = UE_ISOCHRONOUS,
498                 .endpoint = UE_ADDR_ANY,
499                 .direction = UE_DIR_IN,
500                 .bufsize = 0,   /* use "wMaxPacketSize * frames" */
501                 .frames = UAUDIO_NFRAMES,
502                 .flags = {.short_xfer_ok = 1,},
503                 .callback = &uaudio_chan_record_callback,
504         },
505 };
506
507 static const struct usb_config
508         uaudio_cfg_play[UAUDIO_NCHANBUFS] = {
509         [0] = {
510                 .type = UE_ISOCHRONOUS,
511                 .endpoint = UE_ADDR_ANY,
512                 .direction = UE_DIR_OUT,
513                 .bufsize = 0,   /* use "wMaxPacketSize * frames" */
514                 .frames = UAUDIO_NFRAMES,
515                 .flags = {.short_xfer_ok = 1,},
516                 .callback = &uaudio_chan_play_callback,
517         },
518
519         [1] = {
520                 .type = UE_ISOCHRONOUS,
521                 .endpoint = UE_ADDR_ANY,
522                 .direction = UE_DIR_OUT,
523                 .bufsize = 0,   /* use "wMaxPacketSize * frames" */
524                 .frames = UAUDIO_NFRAMES,
525                 .flags = {.short_xfer_ok = 1,},
526                 .callback = &uaudio_chan_play_callback,
527         },
528 };
529
530 static const struct usb_config
531         uaudio_mixer_config[1] = {
532         [0] = {
533                 .type = UE_CONTROL,
534                 .endpoint = 0x00,       /* Control pipe */
535                 .direction = UE_DIR_ANY,
536                 .bufsize = (sizeof(struct usb_device_request) + 4),
537                 .callback = &uaudio_mixer_write_cfg_callback,
538                 .timeout = 1000,        /* 1 second */
539         },
540 };
541
542 static const
543 uint8_t umidi_cmd_to_len[16] = {
544         [0x0] = 0,                      /* reserved */
545         [0x1] = 0,                      /* reserved */
546         [0x2] = 2,                      /* bytes */
547         [0x3] = 3,                      /* bytes */
548         [0x4] = 3,                      /* bytes */
549         [0x5] = 1,                      /* bytes */
550         [0x6] = 2,                      /* bytes */
551         [0x7] = 3,                      /* bytes */
552         [0x8] = 3,                      /* bytes */
553         [0x9] = 3,                      /* bytes */
554         [0xA] = 3,                      /* bytes */
555         [0xB] = 3,                      /* bytes */
556         [0xC] = 2,                      /* bytes */
557         [0xD] = 2,                      /* bytes */
558         [0xE] = 3,                      /* bytes */
559         [0xF] = 1,                      /* bytes */
560 };
561
562 static const struct usb_config
563         umidi_config[UMIDI_N_TRANSFER] = {
564         [UMIDI_TX_TRANSFER] = {
565                 .type = UE_BULK,
566                 .endpoint = UE_ADDR_ANY,
567                 .direction = UE_DIR_OUT,
568                 .bufsize = UMIDI_TX_BUFFER,
569                 .callback = &umidi_bulk_write_callback,
570         },
571
572         [UMIDI_RX_TRANSFER] = {
573                 .type = UE_BULK,
574                 .endpoint = UE_ADDR_ANY,
575                 .direction = UE_DIR_IN,
576                 .bufsize = 4,   /* bytes */
577                 .flags = {.short_xfer_ok = 1,.proxy_buffer = 1,},
578                 .callback = &umidi_bulk_read_callback,
579         },
580 };
581
582 static devclass_t uaudio_devclass;
583
584 static device_method_t uaudio_methods[] = {
585         DEVMETHOD(device_probe, uaudio_probe),
586         DEVMETHOD(device_attach, uaudio_attach),
587         DEVMETHOD(device_detach, uaudio_detach),
588         DEVMETHOD(device_suspend, bus_generic_suspend),
589         DEVMETHOD(device_resume, bus_generic_resume),
590         DEVMETHOD(device_shutdown, bus_generic_shutdown),
591
592         DEVMETHOD_END
593 };
594
595 static driver_t uaudio_driver = {
596         .name = "uaudio",
597         .methods = uaudio_methods,
598         .size = sizeof(struct uaudio_softc),
599 };
600
601 static const STRUCT_USB_HOST_ID __used uaudio_devs[] = {
602         /* Generic USB audio class match */
603         {USB_IFACE_CLASS(UICLASS_AUDIO),
604          USB_IFACE_SUBCLASS(UISUBCLASS_AUDIOCONTROL),},
605         /* Generic USB MIDI class match */
606         {USB_IFACE_CLASS(UICLASS_AUDIO),
607          USB_IFACE_SUBCLASS(UISUBCLASS_MIDISTREAM),},
608 };
609
610 static int
611 uaudio_probe(device_t dev)
612 {
613         struct usb_attach_arg *uaa = device_get_ivars(dev);
614
615         if (uaa->usb_mode != USB_MODE_HOST)
616                 return (ENXIO);
617
618         /* lookup non-standard device */
619
620         if (uaa->info.bInterfaceClass != UICLASS_AUDIO) {
621                 if (uaa->info.bInterfaceClass != UICLASS_VENDOR ||
622                     usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS) == 0)
623                         return (ENXIO);
624         }
625
626         /* check for AUDIO control interface */
627
628         if (uaa->info.bInterfaceSubClass == UISUBCLASS_AUDIOCONTROL) {
629                 if (usb_test_quirk(uaa, UQ_BAD_AUDIO))
630                         return (ENXIO);
631                 else
632                         return (BUS_PROBE_GENERIC);
633         }
634
635         /* check for MIDI stream */
636
637         if (uaa->info.bInterfaceSubClass == UISUBCLASS_MIDISTREAM) {
638                 if (usb_test_quirk(uaa, UQ_BAD_MIDI))
639                         return (ENXIO);
640                 else
641                         return (BUS_PROBE_GENERIC);
642         }
643         return (ENXIO);
644 }
645
646 static int
647 uaudio_attach(device_t dev)
648 {
649         struct usb_attach_arg *uaa = device_get_ivars(dev);
650         struct uaudio_softc *sc = device_get_softc(dev);
651         struct usb_interface_descriptor *id;
652         device_t child;
653
654         sc->sc_play_chan.priv_sc = sc;
655         sc->sc_rec_chan.priv_sc = sc;
656         sc->sc_udev = uaa->device;
657         sc->sc_mixer_iface_index = uaa->info.bIfaceIndex;
658         sc->sc_mixer_iface_no = uaa->info.bIfaceNum;
659
660         if (usb_test_quirk(uaa, UQ_AUDIO_SWAP_LR))
661                 sc->sc_uq_audio_swap_lr = 1;
662
663         if (usb_test_quirk(uaa, UQ_AU_INP_ASYNC))
664                 sc->sc_uq_au_inp_async = 1;
665
666         if (usb_test_quirk(uaa, UQ_AU_NO_XU))
667                 sc->sc_uq_au_no_xu = 1;
668
669         if (usb_test_quirk(uaa, UQ_BAD_ADC))
670                 sc->sc_uq_bad_adc = 1;
671
672         if (usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS))
673                 sc->sc_uq_au_vendor_class = 1;
674
675         umidi_init(dev);
676
677         device_set_usb_desc(dev);
678
679         id = usbd_get_interface_descriptor(uaa->iface);
680
681         /* must fill mixer info before channel info */
682         uaudio_mixer_fill_info(sc, uaa->device, id);
683
684         /* fill channel info */
685         uaudio_chan_fill_info(sc, uaa->device);
686
687         DPRINTF("audio rev %d.%02x\n",
688             sc->sc_audio_rev >> 8,
689             sc->sc_audio_rev & 0xff);
690
691         DPRINTF("%d mixer controls\n",
692             sc->sc_mixer_count);
693
694         if (sc->sc_play_chan.valid) {
695                 device_printf(dev, "Play: %d Hz, %d ch, %s format.\n",
696                     sc->sc_play_chan.sample_rate,
697                     sc->sc_play_chan.channels,
698                     sc->sc_play_chan.p_fmt->description);
699         } else {
700                 device_printf(dev, "No playback.\n");
701         }
702
703         if (sc->sc_rec_chan.valid) {
704                 device_printf(dev, "Record: %d Hz, %d ch, %s format.\n",
705                     sc->sc_rec_chan.sample_rate,
706                     sc->sc_play_chan.channels,
707                     sc->sc_rec_chan.p_fmt->description);
708         } else {
709                 device_printf(dev, "No recording.\n");
710         }
711
712         if (sc->sc_midi_chan.valid) {
713
714                 if (umidi_probe(dev)) {
715                         goto detach;
716                 }
717                 device_printf(dev, "MIDI sequencer.\n");
718         } else {
719                 device_printf(dev, "No midi sequencer.\n");
720         }
721
722         DPRINTF("doing child attach\n");
723
724         /* attach the children */
725
726         sc->sc_sndcard_func.func = SCF_PCM;
727
728         /*
729          * Only attach a PCM device if we have a playback, recording
730          * or mixer device present:
731          */
732         if (sc->sc_play_chan.valid ||
733             sc->sc_rec_chan.valid ||
734             sc->sc_mix_info) {
735                 child = device_add_child(dev, "pcm", -1);
736
737                 if (child == NULL) {
738                         DPRINTF("out of memory\n");
739                         goto detach;
740                 }
741                 device_set_ivars(child, &sc->sc_sndcard_func);
742         }
743
744         if (bus_generic_attach(dev)) {
745                 DPRINTF("child attach failed\n");
746                 goto detach;
747         }
748         return (0);                     /* success */
749
750 detach:
751         uaudio_detach(dev);
752         return (ENXIO);
753 }
754
755 static void
756 uaudio_pcm_setflags(device_t dev, uint32_t flags)
757 {
758         pcm_setflags(dev, pcm_getflags(dev) | flags);
759 }
760
761 int
762 uaudio_attach_sub(device_t dev, kobj_class_t mixer_class, kobj_class_t chan_class)
763 {
764         struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
765         char status[SND_STATUSLEN];
766
767         uaudio_mixer_init(sc);
768
769         if (sc->sc_uq_audio_swap_lr) {
770                 DPRINTF("hardware has swapped left and right\n");
771                 /* uaudio_pcm_setflags(dev, SD_F_PSWAPLR); */
772         }
773         if (!(sc->sc_mix_info & SOUND_MASK_PCM)) {
774
775                 DPRINTF("emulating master volume\n");
776
777                 /*
778                  * Emulate missing pcm mixer controller
779                  * through FEEDER_VOLUME
780                  */
781                 uaudio_pcm_setflags(dev, SD_F_SOFTPCMVOL);
782         }
783         if (mixer_init(dev, mixer_class, sc)) {
784                 goto detach;
785         }
786         sc->sc_mixer_init = 1;
787
788         snprintf(status, sizeof(status), "at ? %s", PCM_KLDSTRING(snd_uaudio));
789
790         if (pcm_register(dev, sc,
791             sc->sc_play_chan.valid ? 1 : 0,
792             sc->sc_rec_chan.valid ? 1 : 0)) {
793                 goto detach;
794         }
795
796         uaudio_pcm_setflags(dev, SD_F_MPSAFE);
797         sc->sc_pcm_registered = 1;
798
799         if (sc->sc_play_chan.valid) {
800                 pcm_addchan(dev, PCMDIR_PLAY, chan_class, sc);
801         }
802         if (sc->sc_rec_chan.valid) {
803                 pcm_addchan(dev, PCMDIR_REC, chan_class, sc);
804         }
805         pcm_setstatus(dev, status);
806
807         return (0);                     /* success */
808
809 detach:
810         uaudio_detach_sub(dev);
811         return (ENXIO);
812 }
813
814 int
815 uaudio_detach_sub(device_t dev)
816 {
817         struct uaudio_softc *sc = device_get_softc(device_get_parent(dev));
818         int error = 0;
819
820 repeat:
821         if (sc->sc_pcm_registered) {
822                 error = pcm_unregister(dev);
823         } else {
824                 if (sc->sc_mixer_init) {
825                         error = mixer_uninit(dev);
826                 }
827         }
828
829         if (error) {
830                 device_printf(dev, "Waiting for sound application to exit!\n");
831                 usb_pause_mtx(NULL, 2 * hz);
832                 goto repeat;            /* try again */
833         }
834         return (0);                     /* success */
835 }
836
837 static int
838 uaudio_detach(device_t dev)
839 {
840         struct uaudio_softc *sc = device_get_softc(dev);
841
842         /*
843          * Stop USB transfers early so that any audio applications
844          * will time out and close opened /dev/dspX.Y device(s), if
845          * any.
846          */
847         if (sc->sc_play_chan.valid)
848                 usbd_transfer_unsetup(sc->sc_play_chan.xfer, UAUDIO_NCHANBUFS);
849         if (sc->sc_rec_chan.valid)
850                 usbd_transfer_unsetup(sc->sc_rec_chan.xfer, UAUDIO_NCHANBUFS);
851
852         if (bus_generic_detach(dev) != 0) {
853                 DPRINTF("detach failed!\n");
854         }
855         sbuf_delete(&sc->sc_sndstat);
856         sc->sc_sndstat_valid = 0;
857
858         umidi_detach(dev);
859
860         return (0);
861 }
862
863 /*========================================================================*
864  * AS - Audio Stream - routines
865  *========================================================================*/
866
867 #ifdef USB_DEBUG
868 static void
869 uaudio_chan_dump_ep_desc(const usb_endpoint_descriptor_audio_t *ed)
870 {
871         if (ed) {
872                 DPRINTF("endpoint=%p bLength=%d bDescriptorType=%d \n"
873                     "bEndpointAddress=%d bmAttributes=0x%x \n"
874                     "wMaxPacketSize=%d bInterval=%d \n"
875                     "bRefresh=%d bSynchAddress=%d\n",
876                     ed, ed->bLength, ed->bDescriptorType,
877                     ed->bEndpointAddress, ed->bmAttributes,
878                     UGETW(ed->wMaxPacketSize), ed->bInterval,
879                     UEP_HAS_REFRESH(ed) ? ed->bRefresh : 0,
880                     UEP_HAS_SYNCADDR(ed) ? ed->bSynchAddress : 0);
881         }
882 }
883
884 #endif
885
886 /*
887  * The following is a workaround for broken no-name USB audio devices
888  * sold by dealextreme called "3D sound". The problem is that the
889  * manufacturer computed wMaxPacketSize is too small to hold the
890  * actual data sent. In other words the device sometimes sends more
891  * data than it actually reports it can send in a single isochronous
892  * packet.
893  */
894 static void
895 uaudio_record_fix_fs(usb_endpoint_descriptor_audio_t *ep,
896     uint32_t xps, uint32_t add)
897 {
898         uint32_t mps;
899
900         mps = UGETW(ep->wMaxPacketSize);
901
902         /*
903          * If the device indicates it can send more data than what the
904          * sample rate indicates, we apply the workaround.
905          */
906         if (mps > xps) {
907
908                 /* allow additional data */
909                 xps += add;
910
911                 /* check against the maximum USB 1.x length */
912                 if (xps > 1023)
913                         xps = 1023;
914
915                 /* check if we should do an update */
916                 if (mps < xps) {
917                         /* simply update the wMaxPacketSize field */
918                         USETW(ep->wMaxPacketSize, xps);
919                         DPRINTF("Workaround: Updated wMaxPacketSize "
920                             "from %d to %d bytes.\n",
921                             (int)mps, (int)xps);
922                 }
923         }
924 }
925
926 static usb_error_t
927 uaudio20_check_rate(struct usb_device *udev, uint8_t iface_no,
928     uint8_t clockid, uint32_t rate)
929 {
930         struct usb_device_request req;
931         usb_error_t error;
932         uint8_t data[255];
933         uint16_t actlen;
934         uint16_t rates;
935         uint16_t x;
936
937         DPRINTFN(6, "ifaceno=%d clockid=%d rate=%u\n",
938             iface_no, clockid, rate);
939
940         req.bmRequestType = UT_READ_CLASS_INTERFACE;
941         req.bRequest = UA20_CS_RANGE;
942         USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
943         USETW2(req.wIndex, clockid, iface_no);
944         USETW(req.wLength, 255);
945
946         error = usbd_do_request_flags(udev, NULL, &req, data,
947             USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT);
948
949         if (error != 0 || actlen < 2)
950                 return (USB_ERR_INVAL);
951
952         rates = data[0] | (data[1] << 8);
953         actlen = (actlen - 2) / 12;
954
955         if (rates > actlen) {
956                 DPRINTF("Too many rates\n");
957                 rates = actlen;
958         }
959
960         for (x = 0; x != rates; x++) {
961                 uint32_t min = UGETDW(data + 2 + (12 * x));
962                 uint32_t max = UGETDW(data + 6 + (12 * x));
963                 uint32_t res = UGETDW(data + 10 + (12 * x));
964
965                 if (res == 0) {
966                         DPRINTF("Zero residue\n");
967                         res = 1;
968                 }
969
970                 if (min > max) {
971                         DPRINTF("Swapped max and min\n");
972                         uint32_t temp;
973                         temp = min;
974                         min = max;
975                         max = temp;
976                 }
977
978                 if (rate >= min && rate <= max &&
979                     (((rate - min) % res) == 0)) {
980                         return (0);
981                 }
982         }
983         return (USB_ERR_INVAL);
984 }
985
986 static void
987 uaudio_chan_fill_info_sub(struct uaudio_softc *sc, struct usb_device *udev,
988     uint32_t rate, uint8_t channels, uint8_t bit_resolution)
989 {
990         struct usb_descriptor *desc = NULL;
991         union uaudio_asid asid = { NULL };
992         union uaudio_asf1d asf1d = { NULL };
993         union uaudio_sed sed = { NULL };
994         usb_endpoint_descriptor_audio_t *ed1 = NULL;
995         const struct usb_audio_control_descriptor *acdp = NULL;
996         struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
997         struct usb_interface_descriptor *id;
998         const struct uaudio_format *p_fmt = NULL;
999         struct uaudio_chan *chan;
1000         uint16_t curidx = 0xFFFF;
1001         uint16_t lastidx = 0xFFFF;
1002         uint16_t alt_index = 0;
1003         uint16_t audio_rev = 0;
1004         uint16_t x;
1005         uint8_t ep_dir;
1006         uint8_t bChannels;
1007         uint8_t bBitResolution;
1008         uint8_t audio_if = 0;
1009         uint8_t uma_if_class;
1010
1011         while ((desc = usb_desc_foreach(cd, desc))) {
1012
1013                 if ((desc->bDescriptorType == UDESC_INTERFACE) &&
1014                     (desc->bLength >= sizeof(*id))) {
1015
1016                         id = (void *)desc;
1017
1018                         if (id->bInterfaceNumber != lastidx) {
1019                                 lastidx = id->bInterfaceNumber;
1020                                 curidx++;
1021                                 alt_index = 0;
1022
1023                         } else {
1024                                 alt_index++;
1025                         }
1026
1027                         uma_if_class =
1028                             ((id->bInterfaceClass == UICLASS_AUDIO) ||
1029                             ((id->bInterfaceClass == UICLASS_VENDOR) &&
1030                             (sc->sc_uq_au_vendor_class != 0)));
1031
1032                         if ((uma_if_class != 0) && (id->bInterfaceSubClass == UISUBCLASS_AUDIOSTREAM)) {
1033                                 audio_if = 1;
1034                         } else {
1035                                 audio_if = 0;
1036                         }
1037
1038                         if ((uma_if_class != 0) &&
1039                             (id->bInterfaceSubClass == UISUBCLASS_MIDISTREAM)) {
1040
1041                                 /*
1042                                  * XXX could allow multiple MIDI interfaces
1043                                  */
1044
1045                                 if ((sc->sc_midi_chan.valid == 0) &&
1046                                     usbd_get_iface(udev, curidx)) {
1047                                         sc->sc_midi_chan.iface_index = curidx;
1048                                         sc->sc_midi_chan.iface_alt_index = alt_index;
1049                                         sc->sc_midi_chan.valid = 1;
1050                                 }
1051                         }
1052                         asid.v1 = NULL;
1053                         asf1d.v1 = NULL;
1054                         ed1 = NULL;
1055                         sed.v1 = NULL;
1056                 }
1057
1058                 if (audio_if == 0) {
1059                         if ((acdp == NULL) &&
1060                             (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1061                             (desc->bDescriptorSubtype == UDESCSUB_AC_HEADER) &&
1062                             (desc->bLength >= sizeof(*acdp))) {
1063                                 acdp = (void *)desc;
1064                                 audio_rev = UGETW(acdp->bcdADC);
1065                         }
1066
1067                         /*
1068                          * Don't collect any USB audio descriptors if
1069                          * this is not an USB audio stream interface.
1070                          */
1071                         continue;
1072                 }
1073
1074                 if ((acdp != NULL) &&
1075                     (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1076                     (desc->bDescriptorSubtype == AS_GENERAL) &&
1077                     (asid.v1 == NULL)) {
1078                         if (audio_rev >= UAUDIO_VERSION_30) {
1079                                 /* FALLTHROUGH */
1080                         } else if (audio_rev >= UAUDIO_VERSION_20) {
1081                                 if (desc->bLength >= sizeof(*asid.v2)) {
1082                                         asid.v2 = (void *)desc;
1083                                 }
1084                         } else {
1085                                 if (desc->bLength >= sizeof(*asid.v1)) {
1086                                         asid.v1 = (void *)desc;
1087                                 }
1088                         }
1089                 }
1090                 if ((acdp != NULL) &&
1091                     (desc->bDescriptorType == UDESC_CS_INTERFACE) &&
1092                     (desc->bDescriptorSubtype == FORMAT_TYPE) &&
1093                     (asf1d.v1 == NULL)) {
1094                         if (audio_rev >= UAUDIO_VERSION_30) {
1095                                 /* FALLTHROUGH */
1096                         } else if (audio_rev >= UAUDIO_VERSION_20) {
1097                                 if (desc->bLength >= sizeof(*asf1d.v2))
1098                                         asf1d.v2 = (void *)desc;
1099                         } else {
1100                                 if (desc->bLength >= sizeof(*asf1d.v1)) {
1101                                         asf1d.v1 = (void *)desc;
1102
1103                                         if (asf1d.v1->bFormatType != FORMAT_TYPE_I) {
1104                                                 DPRINTFN(11, "ignored bFormatType = %d\n",
1105                                                     asf1d.v1->bFormatType);
1106                                                 asf1d.v1 = NULL;
1107                                                 continue;
1108                                         }
1109                                         if (desc->bLength < (sizeof(*asf1d.v1) +
1110                                             ((asf1d.v1->bSamFreqType == 0) ? 6 :
1111                                             (asf1d.v1->bSamFreqType * 3)))) {
1112                                                 DPRINTFN(11, "invalid descriptor, "
1113                                                     "too short\n");
1114                                                 asf1d.v1 = NULL;
1115                                                 continue;
1116                                         }
1117                                 }
1118                         }
1119                 }
1120                 if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1121                     (desc->bLength >= UEP_MINSIZE) &&
1122                     (ed1 == NULL)) {
1123                         ed1 = (void *)desc;
1124                         if (UE_GET_XFERTYPE(ed1->bmAttributes) != UE_ISOCHRONOUS) {
1125                                 ed1 = NULL;
1126                                 continue;
1127                         }
1128                 }
1129                 if ((acdp != NULL) &&
1130                     (desc->bDescriptorType == UDESC_CS_ENDPOINT) &&
1131                     (desc->bDescriptorSubtype == AS_GENERAL) &&
1132                     (sed.v1 == NULL)) {
1133                         if (audio_rev >= UAUDIO_VERSION_30) {
1134                                 /* FALLTHROUGH */
1135                         } else if (audio_rev >= UAUDIO_VERSION_20) {
1136                                 if (desc->bLength >= sizeof(*sed.v2))
1137                                         sed.v2 = (void *)desc;
1138                         } else {
1139                                 if (desc->bLength >= sizeof(*sed.v1))
1140                                         sed.v1 = (void *)desc;
1141                         }
1142                 }
1143                 if (asid.v1 == NULL || asf1d.v1 == NULL ||
1144                     ed1 == NULL || sed.v1 == NULL) {
1145                         /* need more descriptors */
1146                         continue;
1147                 }
1148
1149                 ep_dir = UE_GET_DIR(ed1->bEndpointAddress);
1150
1151                 /* We ignore sync endpoint information until further. */
1152
1153                 if (audio_rev >= UAUDIO_VERSION_30) {
1154                         goto next_ep;
1155                 } else if (audio_rev >= UAUDIO_VERSION_20) {
1156
1157                         uint32_t dwFormat;
1158                         uint8_t bSubslotSize;
1159
1160                         dwFormat = UGETDW(asid.v2->bmFormats);
1161                         bChannels = asid.v2->bNrChannels;
1162                         bBitResolution = asf1d.v2->bBitResolution;
1163                         bSubslotSize = asf1d.v2->bSubslotSize;
1164
1165                         if (bBitResolution != (bSubslotSize * 8)) {
1166                                 DPRINTF("Invalid bSubslotSize\n");
1167                                 goto next_ep;
1168                         }
1169
1170                         if ((bChannels != channels) ||
1171                             (bBitResolution != bit_resolution)) {
1172                                 DPRINTF("Wrong number of channels\n");
1173                                 goto next_ep;
1174                         }
1175
1176                         for (p_fmt = uaudio20_formats;
1177                             p_fmt->wFormat != 0; p_fmt++) {
1178                                 if ((p_fmt->wFormat & dwFormat) &&
1179                                     (p_fmt->bPrecision == bBitResolution))
1180                                         break;
1181                         }
1182
1183                         if (p_fmt->wFormat == 0) {
1184                                 DPRINTF("Unsupported audio format\n");
1185                                 goto next_ep;
1186                         }
1187
1188                         for (x = 0; x != 256; x++) {
1189                                 if (ep_dir == UE_DIR_OUT) {
1190                                         if (!(sc->sc_mixer_clocks.bit_output[x / 8] &
1191                                             (1 << (x % 8)))) {
1192                                                 continue;
1193                                         }
1194                                 } else {
1195                                         if (!(sc->sc_mixer_clocks.bit_input[x / 8] &
1196                                             (1 << (x % 8)))) {
1197                                                 continue;
1198                                         }
1199                                 }
1200
1201                                 DPRINTF("Checking clock ID=%d\n", x);
1202
1203                                 if (uaudio20_check_rate(udev,
1204                                     sc->sc_mixer_iface_no, x, rate)) {
1205                                         DPRINTF("Unsupported sampling "
1206                                             "rate, id=%d\n", x);
1207                                         goto next_ep;
1208                                 }
1209                         }
1210                 } else {
1211                         uint16_t wFormat;
1212
1213                         wFormat = UGETW(asid.v1->wFormatTag);
1214                         bChannels = UAUDIO_MAX_CHAN(asf1d.v1->bNrChannels);
1215                         bBitResolution = asf1d.v1->bBitResolution;
1216
1217                         if (asf1d.v1->bSamFreqType == 0) {
1218                                 DPRINTFN(16, "Sample rate: %d-%dHz\n",
1219                                     UA_SAMP_LO(asf1d.v1),
1220                                     UA_SAMP_HI(asf1d.v1));
1221
1222                                 if ((rate >= UA_SAMP_LO(asf1d.v1)) &&
1223                                     (rate <= UA_SAMP_HI(asf1d.v1)))
1224                                         goto found_rate;
1225                         } else {
1226
1227                                 for (x = 0; x < asf1d.v1->bSamFreqType; x++) {
1228                                         DPRINTFN(16, "Sample rate = %dHz\n",
1229                                             UA_GETSAMP(asf1d.v1, x));
1230
1231                                         if (rate == UA_GETSAMP(asf1d.v1, x))
1232                                                 goto found_rate;
1233                                 }
1234                         }
1235                         goto next_ep;
1236
1237         found_rate:
1238                         for (p_fmt = uaudio10_formats;
1239                             p_fmt->wFormat != 0; p_fmt++) {
1240                                 if ((p_fmt->wFormat == wFormat) &&
1241                                     (p_fmt->bPrecision == bBitResolution))
1242                                         break;
1243                         }
1244                         if (p_fmt->wFormat == 0) {
1245                                 DPRINTF("Unsupported audio format\n");
1246                                 goto next_ep;
1247                         }
1248
1249                         if ((bChannels != channels) ||
1250                             (bBitResolution != bit_resolution)) {
1251                                 DPRINTF("Wrong number of channels\n");
1252                                 goto next_ep;
1253                         }
1254                 }
1255
1256                 chan = (ep_dir == UE_DIR_IN) ?
1257                     &sc->sc_rec_chan : &sc->sc_play_chan;
1258
1259                 if (chan->valid != 0 ||
1260                     usbd_get_iface(udev, curidx) == NULL) {
1261                         DPRINTF("Channel already exists or "
1262                             "interface is not valid\n");
1263                         goto next_ep;
1264                 }
1265
1266                 chan->valid = 1;
1267 #ifdef USB_DEBUG
1268                 uaudio_chan_dump_ep_desc(ed1);
1269 #endif
1270                 DPRINTF("Sample rate = %dHz, channels = %d, "
1271                     "bits = %d, format = %s\n", rate, channels,
1272                     bit_resolution, p_fmt->description);
1273
1274                 chan->sample_rate = rate;
1275                 chan->p_asf1d = asf1d;
1276                 chan->p_ed1 = ed1;
1277                 chan->p_fmt = p_fmt;
1278                 chan->p_sed = sed;
1279                 chan->iface_index = curidx;
1280                 chan->iface_alt_index = alt_index;
1281
1282                 if (ep_dir == UE_DIR_IN)
1283                         chan->usb_cfg = uaudio_cfg_record;
1284                 else
1285                         chan->usb_cfg = uaudio_cfg_play;
1286
1287                 chan->sample_size = (UAUDIO_MAX_CHAN(channels) *
1288                     p_fmt->bPrecision) / 8;
1289                 chan->channels = channels;
1290
1291                 if (ep_dir == UE_DIR_IN &&
1292                     usbd_get_speed(udev) == USB_SPEED_FULL) {
1293                         uaudio_record_fix_fs(ed1,
1294                             chan->sample_size * (rate / 1000),
1295                             chan->sample_size * (rate / 4000));
1296                 }
1297
1298                 if (sc->sc_sndstat_valid != 0) {
1299                         sbuf_printf(&sc->sc_sndstat, "\n\t"
1300                             "mode %d.%d:(%s) %dch, %dbit, %s, %dHz",
1301                             curidx, alt_index,
1302                             (ep_dir == UE_DIR_IN) ? "input" : "output",
1303                                     channels, p_fmt->bPrecision,
1304                                     p_fmt->description, rate);
1305                 }
1306
1307         next_ep:
1308                 sed.v1 = NULL;
1309                 ed1 = NULL;
1310         }
1311 }
1312
1313 /* This structure defines all the supported rates. */
1314
1315 static const uint32_t uaudio_rate_list[] = {
1316         96000,
1317         88000,
1318         80000,
1319         72000,
1320         64000,
1321         56000,
1322         48000,
1323         44100,
1324         40000,
1325         32000,
1326         24000,
1327         22050,
1328         16000,
1329         11025,
1330         8000,
1331         0
1332 };
1333
1334 static void
1335 uaudio_chan_fill_info(struct uaudio_softc *sc, struct usb_device *udev)
1336 {
1337         uint32_t rate = uaudio_default_rate;
1338         uint8_t z;
1339         uint8_t bits = uaudio_default_bits;
1340         uint8_t y;
1341         uint8_t channels = uaudio_default_channels;
1342         uint8_t x;
1343
1344         bits -= (bits % 8);
1345         if ((bits == 0) || (bits > 32)) {
1346                 /* set a valid value */
1347                 bits = 32;
1348         }
1349         if (channels == 0) {
1350                 switch (usbd_get_speed(udev)) {
1351                 case USB_SPEED_LOW:
1352                 case USB_SPEED_FULL:
1353                         /*
1354                          * Due to high bandwidth usage and problems
1355                          * with HIGH-speed split transactions we
1356                          * disable surround setups on FULL-speed USB
1357                          * by default
1358                          */
1359                         channels = 4;
1360                         break;
1361                 default:
1362                         channels = 16;
1363                         break;
1364                 }
1365         } else if (channels > 16) {
1366                 channels = 16;
1367         }
1368         if (sbuf_new(&sc->sc_sndstat, NULL, 4096, SBUF_AUTOEXTEND)) {
1369                 sc->sc_sndstat_valid = 1;
1370         }
1371         /* try to search for a valid config */
1372
1373         for (x = channels; x; x--) {
1374                 for (y = bits; y; y -= 8) {
1375
1376                         /* try user defined rate, if any */
1377                         if (rate != 0)
1378                                 uaudio_chan_fill_info_sub(sc, udev, rate, x, y);
1379
1380                         /* try find a matching rate, if any */
1381                         for (z = 0; uaudio_rate_list[z]; z++) {
1382                                 uaudio_chan_fill_info_sub(sc, udev, uaudio_rate_list[z], x, y);
1383
1384                                 if (sc->sc_rec_chan.valid &&
1385                                     sc->sc_play_chan.valid) {
1386                                         goto done;
1387                                 }
1388                         }
1389                 }
1390         }
1391
1392 done:
1393         if (sc->sc_sndstat_valid) {
1394                 sbuf_finish(&sc->sc_sndstat);
1395         }
1396 }
1397
1398 static void
1399 uaudio_chan_play_callback(struct usb_xfer *xfer, usb_error_t error)
1400 {
1401         struct uaudio_chan *ch = usbd_xfer_softc(xfer);
1402         struct usb_page_cache *pc;
1403         uint32_t total;
1404         uint32_t blockcount;
1405         uint32_t n;
1406         uint32_t offset;
1407         int actlen;
1408         int sumlen;
1409
1410         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1411
1412         if (ch->end == ch->start) {
1413                 DPRINTF("no buffer!\n");
1414                 return;
1415         }
1416
1417         switch (USB_GET_STATE(xfer)) {
1418         case USB_ST_TRANSFERRED:
1419 tr_transferred:
1420                 if (actlen < sumlen) {
1421                         DPRINTF("short transfer, "
1422                             "%d of %d bytes\n", actlen, sumlen);
1423                 }
1424                 chn_intr(ch->pcm_ch);
1425
1426         case USB_ST_SETUP:
1427                 if (ch->bytes_per_frame[1] > usbd_xfer_max_framelen(xfer)) {
1428                         DPRINTF("bytes per transfer, %d, "
1429                             "exceeds maximum, %d!\n",
1430                             ch->bytes_per_frame[1],
1431                             usbd_xfer_max_framelen(xfer));
1432                         break;
1433                 }
1434
1435                 blockcount = ch->intr_frames;
1436
1437                 /* setup number of frames */
1438                 usbd_xfer_set_frames(xfer, blockcount);
1439
1440                 /* reset total length */
1441                 total = 0;
1442
1443                 /* setup frame lengths */
1444                 for (n = 0; n != blockcount; n++) {
1445                         ch->sample_curr += ch->sample_rem;
1446                         if (ch->sample_curr >= ch->frames_per_second) {
1447                                 ch->sample_curr -= ch->frames_per_second;
1448                                 usbd_xfer_set_frame_len(xfer, n, ch->bytes_per_frame[1]);
1449                                 total += ch->bytes_per_frame[1];
1450                         } else {
1451                                 usbd_xfer_set_frame_len(xfer, n, ch->bytes_per_frame[0]);
1452                                 total += ch->bytes_per_frame[0];
1453                         }
1454                 }
1455
1456                 DPRINTFN(6, "transfer %d bytes\n", total);
1457
1458                 offset = 0;
1459
1460                 pc = usbd_xfer_get_frame(xfer, 0);
1461                 while (total > 0) {
1462
1463                         n = (ch->end - ch->cur);
1464                         if (n > total) {
1465                                 n = total;
1466                         }
1467                         usbd_copy_in(pc, offset, ch->cur, n);
1468
1469                         total -= n;
1470                         ch->cur += n;
1471                         offset += n;
1472
1473                         if (ch->cur >= ch->end) {
1474                                 ch->cur = ch->start;
1475                         }
1476                 }
1477
1478                 usbd_transfer_submit(xfer);
1479                 break;
1480
1481         default:                        /* Error */
1482                 if (error == USB_ERR_CANCELLED) {
1483                         break;
1484                 }
1485                 goto tr_transferred;
1486         }
1487 }
1488
1489 static void
1490 uaudio_chan_record_callback(struct usb_xfer *xfer, usb_error_t error)
1491 {
1492         struct uaudio_chan *ch = usbd_xfer_softc(xfer);
1493         struct usb_page_cache *pc;
1494         uint32_t offset0;
1495         uint32_t offset1;
1496         uint32_t mfl;
1497         int m;
1498         int n;
1499         int len;
1500         int actlen;
1501         int nframes;
1502         int blockcount;
1503
1504         usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
1505         mfl = usbd_xfer_max_framelen(xfer);
1506
1507         if (ch->end == ch->start) {
1508                 DPRINTF("no buffer!\n");
1509                 return;
1510         }
1511
1512         switch (USB_GET_STATE(xfer)) {
1513         case USB_ST_TRANSFERRED:
1514
1515                 DPRINTFN(6, "transferred %d bytes\n", actlen);
1516
1517                 offset0 = 0;
1518                 pc = usbd_xfer_get_frame(xfer, 0);
1519
1520                 for (n = 0; n != nframes; n++) {
1521
1522                         offset1 = offset0;
1523                         len = usbd_xfer_frame_len(xfer, n);
1524
1525                         while (len > 0) {
1526
1527                                 m = (ch->end - ch->cur);
1528
1529                                 if (m > len)
1530                                         m = len;
1531
1532                                 usbd_copy_out(pc, offset1, ch->cur, m);
1533
1534                                 len -= m;
1535                                 offset1 += m;
1536                                 ch->cur += m;
1537
1538                                 if (ch->cur >= ch->end) {
1539                                         ch->cur = ch->start;
1540                                 }
1541                         }
1542
1543                         offset0 += mfl;
1544                 }
1545
1546                 chn_intr(ch->pcm_ch);
1547
1548         case USB_ST_SETUP:
1549 tr_setup:
1550                 blockcount = ch->intr_frames;
1551
1552                 usbd_xfer_set_frames(xfer, blockcount);
1553                 for (n = 0; n < blockcount; n++) {
1554                         usbd_xfer_set_frame_len(xfer, n, mfl);
1555                 }
1556
1557                 usbd_transfer_submit(xfer);
1558                 break;
1559
1560         default:                        /* Error */
1561                 if (error == USB_ERR_CANCELLED) {
1562                         break;
1563                 }
1564                 goto tr_setup;
1565         }
1566 }
1567
1568 void   *
1569 uaudio_chan_init(struct uaudio_softc *sc, struct snd_dbuf *b,
1570     struct pcm_channel *c, int dir)
1571 {
1572         struct uaudio_chan *ch = ((dir == PCMDIR_PLAY) ?
1573             &sc->sc_play_chan : &sc->sc_rec_chan);
1574         uint32_t buf_size;
1575         uint32_t frames;
1576         uint32_t format;
1577         uint16_t fps;
1578         uint8_t endpoint;
1579         uint8_t blocks;
1580         uint8_t iface_index;
1581         uint8_t alt_index;
1582         uint8_t fps_shift;
1583         usb_error_t err;
1584
1585         fps = usbd_get_isoc_fps(sc->sc_udev);
1586
1587         if (fps < 8000) {
1588                 /* FULL speed USB */
1589                 frames = 8;
1590         } else {
1591                 /* HIGH speed USB */
1592                 frames = UAUDIO_NFRAMES;
1593         }
1594
1595         /* setup play/record format */
1596
1597         ch->pcm_cap.fmtlist = ch->pcm_format;
1598
1599         ch->pcm_format[0] = 0;
1600         ch->pcm_format[1] = 0;
1601
1602         ch->pcm_cap.minspeed = ch->sample_rate;
1603         ch->pcm_cap.maxspeed = ch->sample_rate;
1604
1605         /* setup mutex and PCM channel */
1606
1607         ch->pcm_ch = c;
1608         ch->pcm_mtx = c->lock;
1609
1610         format = ch->p_fmt->freebsd_fmt;
1611
1612         switch (ch->channels) {
1613         case 2:
1614                 /* stereo */
1615                 format = SND_FORMAT(format, 2, 0);
1616                 break;
1617         case 1:
1618                 /* mono */
1619                 format = SND_FORMAT(format, 1, 0);
1620                 break;
1621         default:
1622                 /* surround and more */
1623                 format = feeder_matrix_default_format(
1624                     SND_FORMAT(format, ch->channels, 0));
1625                 break;
1626         }
1627
1628         ch->pcm_cap.fmtlist[0] = format;
1629         ch->pcm_cap.fmtlist[1] = 0;
1630
1631         /* check if format is not supported */
1632
1633         if (format == 0) {
1634                 DPRINTF("The selected audio format is not supported\n");
1635                 goto error;
1636         }
1637
1638         /* set alternate interface corresponding to the mode */
1639
1640         endpoint = ch->p_ed1->bEndpointAddress;
1641         iface_index = ch->iface_index;
1642         alt_index = ch->iface_alt_index;
1643
1644         DPRINTF("endpoint=0x%02x, speed=%d, iface=%d alt=%d\n",
1645             endpoint, ch->sample_rate, iface_index, alt_index);
1646
1647         err = usbd_set_alt_interface_index(sc->sc_udev, iface_index, alt_index);
1648         if (err) {
1649                 DPRINTF("setting of alternate index failed: %s!\n",
1650                     usbd_errstr(err));
1651                 goto error;
1652         }
1653         usbd_set_parent_iface(sc->sc_udev, iface_index,
1654             sc->sc_mixer_iface_index);
1655
1656         /*
1657          * Only set the sample rate if the channel reports that it
1658          * supports the frequency control.
1659          */
1660
1661         if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
1662                 /* FALLTHROUGH */
1663         } else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
1664                 unsigned int x;
1665           
1666                 for (x = 0; x != 256; x++) {
1667                         if (dir == PCMDIR_PLAY) {
1668                                 if (!(sc->sc_mixer_clocks.bit_output[x / 8] &
1669                                     (1 << (x % 8)))) {
1670                                         continue;
1671                                 }
1672                         } else {
1673                                 if (!(sc->sc_mixer_clocks.bit_input[x / 8] &
1674                                     (1 << (x % 8)))) {
1675                                         continue;
1676                                 }
1677                         }
1678
1679                         if (uaudio20_set_speed(sc->sc_udev,
1680                             sc->sc_mixer_iface_no, x, ch->sample_rate)) {
1681                                 /*
1682                                  * If the endpoint is adaptive setting
1683                                  * the speed may fail.
1684                                  */
1685                                 DPRINTF("setting of sample rate failed! "
1686                                     "(continuing anyway)\n");
1687                         }
1688                 }
1689         } else if (ch->p_sed.v1->bmAttributes & UA_SED_FREQ_CONTROL) {
1690                 if (uaudio_set_speed(sc->sc_udev, endpoint, ch->sample_rate)) {
1691                         /*
1692                          * If the endpoint is adaptive setting the
1693                          * speed may fail.
1694                          */
1695                         DPRINTF("setting of sample rate failed! "
1696                             "(continuing anyway)\n");
1697                 }
1698         }
1699         if (usbd_transfer_setup(sc->sc_udev, &iface_index, ch->xfer,
1700             ch->usb_cfg, UAUDIO_NCHANBUFS, ch, ch->pcm_mtx)) {
1701                 DPRINTF("could not allocate USB transfers!\n");
1702                 goto error;
1703         }
1704
1705         fps_shift = usbd_xfer_get_fps_shift(ch->xfer[0]);
1706
1707         /* down shift number of frames per second, if any */
1708         fps >>= fps_shift;
1709         frames >>= fps_shift;
1710
1711         /* bytes per frame should not be zero */
1712         ch->bytes_per_frame[0] = ((ch->sample_rate / fps) * ch->sample_size);
1713         ch->bytes_per_frame[1] = (((ch->sample_rate + fps - 1) / fps) * ch->sample_size);
1714
1715         /* setup data rate dithering, if any */
1716         ch->frames_per_second = fps;
1717         ch->sample_rem = ch->sample_rate % fps;
1718         ch->sample_curr = 0;
1719         ch->frames_per_second = fps;
1720
1721         /* compute required buffer size */
1722         buf_size = (ch->bytes_per_frame[1] * frames);
1723
1724         ch->intr_size = buf_size;
1725         ch->intr_frames = frames;
1726
1727         DPRINTF("fps=%d sample_rem=%d\n", fps, ch->sample_rem);
1728
1729         if (ch->intr_frames == 0) {
1730                 DPRINTF("frame shift is too high!\n");
1731                 goto error;
1732         }
1733
1734         /* setup double buffering */
1735         buf_size *= 2;
1736         blocks = 2;
1737
1738         ch->buf = malloc(buf_size, M_DEVBUF, M_WAITOK | M_ZERO);
1739         if (ch->buf == NULL)
1740                 goto error;
1741         if (sndbuf_setup(b, ch->buf, buf_size) != 0)
1742                 goto error;
1743         if (sndbuf_resize(b, blocks, ch->intr_size)) 
1744                 goto error;
1745
1746         ch->start = ch->buf;
1747         ch->end = ch->buf + buf_size;
1748         ch->cur = ch->buf;
1749         ch->pcm_buf = b;
1750
1751         if (ch->pcm_mtx == NULL) {
1752                 DPRINTF("ERROR: PCM channels does not have a mutex!\n");
1753                 goto error;
1754         }
1755
1756         return (ch);
1757
1758 error:
1759         uaudio_chan_free(ch);
1760         return (NULL);
1761 }
1762
1763 int
1764 uaudio_chan_free(struct uaudio_chan *ch)
1765 {
1766         if (ch->buf != NULL) {
1767                 free(ch->buf, M_DEVBUF);
1768                 ch->buf = NULL;
1769         }
1770         usbd_transfer_unsetup(ch->xfer, UAUDIO_NCHANBUFS);
1771
1772         ch->valid = 0;
1773
1774         return (0);
1775 }
1776
1777 int
1778 uaudio_chan_set_param_blocksize(struct uaudio_chan *ch, uint32_t blocksize)
1779 {
1780         return (ch->intr_size);
1781 }
1782
1783 int
1784 uaudio_chan_set_param_fragments(struct uaudio_chan *ch, uint32_t blocksize,
1785     uint32_t blockcount)
1786 {
1787         return (1);
1788 }
1789
1790 int
1791 uaudio_chan_set_param_speed(struct uaudio_chan *ch, uint32_t speed)
1792 {
1793         if (speed != ch->sample_rate) {
1794                 DPRINTF("rate conversion required\n");
1795         }
1796         return (ch->sample_rate);
1797 }
1798
1799 int
1800 uaudio_chan_getptr(struct uaudio_chan *ch)
1801 {
1802         return (ch->cur - ch->start);
1803 }
1804
1805 struct pcmchan_caps *
1806 uaudio_chan_getcaps(struct uaudio_chan *ch)
1807 {
1808         return (&ch->pcm_cap);
1809 }
1810
1811 static struct pcmchan_matrix uaudio_chan_matrix_swap_2_0 = {
1812         .id = SND_CHN_MATRIX_DRV,
1813         .channels = 2,
1814         .ext = 0,
1815         .map = {
1816                 /* Right */
1817                 [0] = {
1818                         .type = SND_CHN_T_FR,
1819                         .members =
1820                             SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FC |
1821                             SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BR |
1822                             SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SR
1823                 },
1824                 /* Left */
1825                 [1] = {
1826                         .type = SND_CHN_T_FL,
1827                         .members =
1828                             SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FC |
1829                             SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BL |
1830                             SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SL
1831                 },
1832                 [2] = {
1833                         .type = SND_CHN_T_MAX,
1834                         .members = 0
1835                 }
1836         },
1837         .mask = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FL,
1838         .offset = {  1,  0, -1, -1, -1, -1, -1, -1, -1,
1839                     -1, -1, -1, -1, -1, -1, -1, -1, -1  }
1840 };
1841
1842 struct pcmchan_matrix *
1843 uaudio_chan_getmatrix(struct uaudio_chan *ch, uint32_t format)
1844 {
1845         struct uaudio_softc *sc;
1846
1847         sc = ch->priv_sc;
1848
1849         if (sc != NULL && sc->sc_uq_audio_swap_lr != 0 &&
1850             AFMT_CHANNEL(format) == 2)
1851                 return (&uaudio_chan_matrix_swap_2_0);
1852
1853         return (feeder_matrix_format_map(format));
1854 }
1855
1856 int
1857 uaudio_chan_set_param_format(struct uaudio_chan *ch, uint32_t format)
1858 {
1859         ch->format = format;
1860         return (0);
1861 }
1862
1863 int
1864 uaudio_chan_start(struct uaudio_chan *ch)
1865 {
1866         ch->cur = ch->start;
1867
1868 #if (UAUDIO_NCHANBUFS != 2)
1869 #error "please update code"
1870 #endif
1871         if (ch->xfer[0]) {
1872                 usbd_transfer_start(ch->xfer[0]);
1873         }
1874         if (ch->xfer[1]) {
1875                 usbd_transfer_start(ch->xfer[1]);
1876         }
1877         return (0);
1878 }
1879
1880 int
1881 uaudio_chan_stop(struct uaudio_chan *ch)
1882 {
1883 #if (UAUDIO_NCHANBUFS != 2)
1884 #error "please update code"
1885 #endif
1886         usbd_transfer_stop(ch->xfer[0]);
1887         usbd_transfer_stop(ch->xfer[1]);
1888         return (0);
1889 }
1890
1891 /*========================================================================*
1892  * AC - Audio Controller - routines
1893  *========================================================================*/
1894
1895 static void
1896 uaudio_mixer_add_ctl_sub(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
1897 {
1898         struct uaudio_mixer_node *p_mc_new =
1899             malloc(sizeof(*p_mc_new), M_USBDEV, M_WAITOK);
1900
1901         if (p_mc_new != NULL) {
1902                 memcpy(p_mc_new, mc, sizeof(*p_mc_new));
1903                 p_mc_new->next = sc->sc_mixer_root;
1904                 sc->sc_mixer_root = p_mc_new;
1905                 sc->sc_mixer_count++;
1906         } else {
1907                 DPRINTF("out of memory\n");
1908         }
1909 }
1910
1911 static void
1912 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct uaudio_mixer_node *mc)
1913 {
1914         int32_t res;
1915
1916         if (mc->class < UAC_NCLASSES) {
1917                 DPRINTF("adding %s.%d\n",
1918                     uac_names[mc->class], mc->ctl);
1919         } else {
1920                 DPRINTF("adding %d\n", mc->ctl);
1921         }
1922
1923         if (mc->type == MIX_ON_OFF) {
1924                 mc->minval = 0;
1925                 mc->maxval = 1;
1926         } else if (mc->type == MIX_SELECTOR) {
1927         } else {
1928
1929                 /* determine min and max values */
1930
1931                 mc->minval = uaudio_mixer_get(sc->sc_udev,
1932                     sc->sc_audio_rev, GET_MIN, mc);
1933                 mc->maxval = uaudio_mixer_get(sc->sc_udev,
1934                     sc->sc_audio_rev, GET_MAX, mc);
1935
1936                 /* check if max and min was swapped */
1937
1938                 if (mc->maxval < mc->minval) {
1939                         res = mc->maxval;
1940                         mc->maxval = mc->minval;
1941                         mc->minval = res;
1942                 }
1943
1944                 /* compute value range */
1945                 mc->mul = mc->maxval - mc->minval;
1946                 if (mc->mul == 0)
1947                         mc->mul = 1;
1948
1949                 /* compute value alignment */
1950                 res = uaudio_mixer_get(sc->sc_udev,
1951                     sc->sc_audio_rev, GET_RES, mc);
1952
1953                 DPRINTF("Resolution = %d\n", (int)res);
1954         }
1955
1956         uaudio_mixer_add_ctl_sub(sc, mc);
1957
1958 #ifdef USB_DEBUG
1959         if (uaudio_debug > 2) {
1960                 uint8_t i;
1961
1962                 for (i = 0; i < mc->nchan; i++) {
1963                         DPRINTF("[mix] wValue=%04x\n", mc->wValue[0]);
1964                 }
1965                 DPRINTF("[mix] wIndex=%04x type=%d ctl='%d' "
1966                     "min=%d max=%d\n",
1967                     mc->wIndex, mc->type, mc->ctl,
1968                     mc->minval, mc->maxval);
1969         }
1970 #endif
1971 }
1972
1973 static void
1974 uaudio_mixer_add_mixer(struct uaudio_softc *sc,
1975     const struct uaudio_terminal_node *iot, int id)
1976 {
1977         struct uaudio_mixer_node mix;
1978
1979         const struct usb_audio_mixer_unit_0 *d0 = iot[id].u.mu_v1;
1980         const struct usb_audio_mixer_unit_1 *d1;
1981
1982         uint32_t bno;                   /* bit number */
1983         uint32_t p;                     /* bit number accumulator */
1984         uint32_t mo;                    /* matching outputs */
1985         uint32_t mc;                    /* matching channels */
1986         uint32_t ichs;                  /* input channels */
1987         uint32_t ochs;                  /* output channels */
1988         uint32_t c;
1989         uint32_t chs;                   /* channels */
1990         uint32_t i;
1991         uint32_t o;
1992
1993         DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
1994             d0->bUnitId, d0->bNrInPins);
1995
1996         /* compute the number of input channels */
1997
1998         ichs = 0;
1999         for (i = 0; i < d0->bNrInPins; i++) {
2000                 ichs += uaudio_mixer_get_cluster(
2001                     d0->baSourceId[i], iot).bNrChannels;
2002         }
2003
2004         d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
2005
2006         /* and the number of output channels */
2007
2008         ochs = d1->bNrChannels;
2009
2010         DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
2011
2012         memset(&mix, 0, sizeof(mix));
2013
2014         mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2015         uaudio_mixer_determine_class(&iot[id], &mix);
2016         mix.type = MIX_SIGNED_16;
2017
2018         if (uaudio_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
2019                 return;
2020
2021         for (p = i = 0; i < d0->bNrInPins; i++) {
2022                 chs = uaudio_mixer_get_cluster(
2023                     d0->baSourceId[i], iot).bNrChannels;
2024                 mc = 0;
2025                 for (c = 0; c < chs; c++) {
2026                         mo = 0;
2027                         for (o = 0; o < ochs; o++) {
2028                                 bno = ((p + c) * ochs) + o;
2029                                 if (BIT_TEST(d1->bmControls, bno))
2030                                         mo++;
2031                         }
2032                         if (mo == 1)
2033                                 mc++;
2034                 }
2035                 if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
2036
2037                         /* repeat bit-scan */
2038
2039                         mc = 0;
2040                         for (c = 0; c < chs; c++) {
2041                                 for (o = 0; o < ochs; o++) {
2042                                         bno = ((p + c) * ochs) + o;
2043                                         if (BIT_TEST(d1->bmControls, bno))
2044                                                 mix.wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
2045                                 }
2046                         }
2047                         mix.nchan = chs;
2048                         uaudio_mixer_add_ctl(sc, &mix);
2049                 }
2050                 p += chs;
2051         }
2052 }
2053
2054 static void
2055 uaudio20_mixer_add_mixer(struct uaudio_softc *sc,
2056     const struct uaudio_terminal_node *iot, int id)
2057 {
2058         struct uaudio_mixer_node mix;
2059
2060         const struct usb_audio20_mixer_unit_0 *d0 = iot[id].u.mu_v2;
2061         const struct usb_audio20_mixer_unit_1 *d1;
2062
2063         uint32_t bno;                   /* bit number */
2064         uint32_t p;                     /* bit number accumulator */
2065         uint32_t mo;                    /* matching outputs */
2066         uint32_t mc;                    /* matching channels */
2067         uint32_t ichs;                  /* input channels */
2068         uint32_t ochs;                  /* output channels */
2069         uint32_t c;
2070         uint32_t chs;                   /* channels */
2071         uint32_t i;
2072         uint32_t o;
2073
2074         DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2075             d0->bUnitId, d0->bNrInPins);
2076
2077         /* compute the number of input channels */
2078
2079         ichs = 0;
2080         for (i = 0; i < d0->bNrInPins; i++) {
2081                 ichs += uaudio20_mixer_get_cluster(
2082                     d0->baSourceId[i], iot).bNrChannels;
2083         }
2084
2085         d1 = (const void *)(d0->baSourceId + d0->bNrInPins);
2086
2087         /* and the number of output channels */
2088
2089         ochs = d1->bNrChannels;
2090
2091         DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs);
2092
2093         memset(&mix, 0, sizeof(mix));
2094
2095         mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2096         uaudio20_mixer_determine_class(&iot[id], &mix);
2097         mix.type = MIX_SIGNED_16;
2098
2099         if (uaudio20_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL)
2100                 return;
2101
2102         for (p = i = 0; i < d0->bNrInPins; i++) {
2103                 chs = uaudio20_mixer_get_cluster(
2104                     d0->baSourceId[i], iot).bNrChannels;
2105                 mc = 0;
2106                 for (c = 0; c < chs; c++) {
2107                         mo = 0;
2108                         for (o = 0; o < ochs; o++) {
2109                                 bno = ((p + c) * ochs) + o;
2110                                 if (BIT_TEST(d1->bmControls, bno))
2111                                         mo++;
2112                         }
2113                         if (mo == 1)
2114                                 mc++;
2115                 }
2116                 if ((mc == chs) && (chs <= MIX_MAX_CHAN)) {
2117
2118                         /* repeat bit-scan */
2119
2120                         mc = 0;
2121                         for (c = 0; c < chs; c++) {
2122                                 for (o = 0; o < ochs; o++) {
2123                                         bno = ((p + c) * ochs) + o;
2124                                         if (BIT_TEST(d1->bmControls, bno))
2125                                                 mix.wValue[mc++] = MAKE_WORD(p + c + 1, o + 1);
2126                                 }
2127                         }
2128                         mix.nchan = chs;
2129                         uaudio_mixer_add_ctl(sc, &mix);
2130                 }
2131                 p += chs;
2132         }
2133 }
2134
2135 static void
2136 uaudio_mixer_add_selector(struct uaudio_softc *sc,
2137     const struct uaudio_terminal_node *iot, int id)
2138 {
2139         const struct usb_audio_selector_unit *d = iot[id].u.su_v1;
2140         struct uaudio_mixer_node mix;
2141         uint16_t i;
2142
2143         DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2144             d->bUnitId, d->bNrInPins);
2145
2146         if (d->bNrInPins == 0) {
2147                 return;
2148         }
2149         memset(&mix, 0, sizeof(mix));
2150
2151         mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
2152         mix.wValue[0] = MAKE_WORD(0, 0);
2153         uaudio_mixer_determine_class(&iot[id], &mix);
2154         mix.nchan = 1;
2155         mix.type = MIX_SELECTOR;
2156
2157         mix.ctl = SOUND_MIXER_NRDEVICES;
2158         mix.minval = 1;
2159         mix.maxval = d->bNrInPins;
2160
2161         if (mix.maxval > MAX_SELECTOR_INPUT_PIN) {
2162                 mix.maxval = MAX_SELECTOR_INPUT_PIN;
2163         }
2164         mix.mul = (mix.maxval - mix.minval);
2165         for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) {
2166                 mix.slctrtype[i] = SOUND_MIXER_NRDEVICES;
2167         }
2168
2169         for (i = 0; i < mix.maxval; i++) {
2170                 mix.slctrtype[i] = uaudio_mixer_feature_name(
2171                     &iot[d->baSourceId[i]], &mix);
2172         }
2173
2174         mix.class = 0;                  /* not used */
2175
2176         uaudio_mixer_add_ctl(sc, &mix);
2177 }
2178
2179 static void
2180 uaudio20_mixer_add_selector(struct uaudio_softc *sc,
2181     const struct uaudio_terminal_node *iot, int id)
2182 {
2183         const struct usb_audio20_selector_unit *d = iot[id].u.su_v2;
2184         struct uaudio_mixer_node mix;
2185         uint16_t i;
2186
2187         DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2188             d->bUnitId, d->bNrInPins);
2189
2190         if (d->bNrInPins == 0)
2191                 return;
2192
2193         memset(&mix, 0, sizeof(mix));
2194
2195         mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
2196         mix.wValue[0] = MAKE_WORD(0, 0);
2197         uaudio20_mixer_determine_class(&iot[id], &mix);
2198         mix.nchan = 1;
2199         mix.type = MIX_SELECTOR;
2200
2201         mix.ctl = SOUND_MIXER_NRDEVICES;
2202         mix.minval = 1;
2203         mix.maxval = d->bNrInPins;
2204
2205         if (mix.maxval > MAX_SELECTOR_INPUT_PIN)
2206                 mix.maxval = MAX_SELECTOR_INPUT_PIN;
2207
2208         mix.mul = (mix.maxval - mix.minval);
2209         for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++)
2210                 mix.slctrtype[i] = SOUND_MIXER_NRDEVICES;
2211
2212         for (i = 0; i < mix.maxval; i++) {
2213                 mix.slctrtype[i] = uaudio20_mixer_feature_name(
2214                     &iot[d->baSourceId[i]], &mix);
2215         }
2216
2217         mix.class = 0;                  /* not used */
2218
2219         uaudio_mixer_add_ctl(sc, &mix);
2220 }
2221
2222 static uint32_t
2223 uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *d,
2224     uint8_t i)
2225 {
2226         uint32_t temp = 0;
2227         uint32_t offset = (i * d->bControlSize);
2228
2229         if (d->bControlSize > 0) {
2230                 temp |= d->bmaControls[offset];
2231                 if (d->bControlSize > 1) {
2232                         temp |= d->bmaControls[offset + 1] << 8;
2233                         if (d->bControlSize > 2) {
2234                                 temp |= d->bmaControls[offset + 2] << 16;
2235                                 if (d->bControlSize > 3) {
2236                                         temp |= d->bmaControls[offset + 3] << 24;
2237                                 }
2238                         }
2239                 }
2240         }
2241         return (temp);
2242 }
2243
2244 static void
2245 uaudio_mixer_add_feature(struct uaudio_softc *sc,
2246     const struct uaudio_terminal_node *iot, int id)
2247 {
2248         const struct usb_audio_feature_unit *d = iot[id].u.fu_v1;
2249         struct uaudio_mixer_node mix;
2250         uint32_t fumask;
2251         uint32_t mmask;
2252         uint32_t cmask;
2253         uint16_t mixernumber;
2254         uint8_t nchan;
2255         uint8_t chan;
2256         uint8_t ctl;
2257         uint8_t i;
2258
2259         if (d->bControlSize == 0) {
2260                 return;
2261         }
2262         memset(&mix, 0, sizeof(mix));
2263
2264         nchan = (d->bLength - 7) / d->bControlSize;
2265         mmask = uaudio_mixer_feature_get_bmaControls(d, 0);
2266         cmask = 0;
2267
2268         if (nchan == 0) {
2269                 return;
2270         }
2271         /* figure out what we can control */
2272
2273         for (chan = 1; chan < nchan; chan++) {
2274                 DPRINTFN(10, "chan=%d mask=%x\n",
2275                     chan, uaudio_mixer_feature_get_bmaControls(d, chan));
2276
2277                 cmask |= uaudio_mixer_feature_get_bmaControls(d, chan);
2278         }
2279
2280         if (nchan > MIX_MAX_CHAN) {
2281                 nchan = MIX_MAX_CHAN;
2282         }
2283         mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
2284
2285         for (ctl = 1; ctl <= LOUDNESS_CONTROL; ctl++) {
2286
2287                 fumask = FU_MASK(ctl);
2288
2289                 DPRINTFN(5, "ctl=%d fumask=0x%04x\n",
2290                     ctl, fumask);
2291
2292                 if (mmask & fumask) {
2293                         mix.nchan = 1;
2294                         mix.wValue[0] = MAKE_WORD(ctl, 0);
2295                 } else if (cmask & fumask) {
2296                         mix.nchan = nchan - 1;
2297                         for (i = 1; i < nchan; i++) {
2298                                 if (uaudio_mixer_feature_get_bmaControls(d, i) & fumask)
2299                                         mix.wValue[i - 1] = MAKE_WORD(ctl, i);
2300                                 else
2301                                         mix.wValue[i - 1] = -1;
2302                         }
2303                 } else {
2304                         continue;
2305                 }
2306
2307                 mixernumber = uaudio_mixer_feature_name(&iot[id], &mix);
2308
2309                 switch (ctl) {
2310                 case MUTE_CONTROL:
2311                         mix.type = MIX_ON_OFF;
2312                         mix.ctl = SOUND_MIXER_NRDEVICES;
2313                         break;
2314
2315                 case VOLUME_CONTROL:
2316                         mix.type = MIX_SIGNED_16;
2317                         mix.ctl = mixernumber;
2318                         break;
2319
2320                 case BASS_CONTROL:
2321                         mix.type = MIX_SIGNED_8;
2322                         mix.ctl = SOUND_MIXER_BASS;
2323                         break;
2324
2325                 case MID_CONTROL:
2326                         mix.type = MIX_SIGNED_8;
2327                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
2328                         break;
2329
2330                 case TREBLE_CONTROL:
2331                         mix.type = MIX_SIGNED_8;
2332                         mix.ctl = SOUND_MIXER_TREBLE;
2333                         break;
2334
2335                 case GRAPHIC_EQUALIZER_CONTROL:
2336                         continue;       /* XXX don't add anything */
2337                         break;
2338
2339                 case AGC_CONTROL:
2340                         mix.type = MIX_ON_OFF;
2341                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
2342                         break;
2343
2344                 case DELAY_CONTROL:
2345                         mix.type = MIX_UNSIGNED_16;
2346                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
2347                         break;
2348
2349                 case BASS_BOOST_CONTROL:
2350                         mix.type = MIX_ON_OFF;
2351                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
2352                         break;
2353
2354                 case LOUDNESS_CONTROL:
2355                         mix.type = MIX_ON_OFF;
2356                         mix.ctl = SOUND_MIXER_LOUD;     /* Is this correct ? */
2357                         break;
2358
2359                 default:
2360                         mix.type = MIX_UNKNOWN;
2361                         break;
2362                 }
2363
2364                 if (mix.type != MIX_UNKNOWN)
2365                         uaudio_mixer_add_ctl(sc, &mix);
2366         }
2367 }
2368
2369 static void
2370 uaudio20_mixer_add_feature(struct uaudio_softc *sc,
2371     const struct uaudio_terminal_node *iot, int id)
2372 {
2373         const struct usb_audio20_feature_unit *d = iot[id].u.fu_v2;
2374         struct uaudio_mixer_node mix;
2375         uint32_t ctl;
2376         uint32_t mmask;
2377         uint32_t cmask;
2378         uint16_t mixernumber;
2379         uint8_t nchan;
2380         uint8_t chan;
2381         uint8_t i;
2382         uint8_t what;
2383
2384         if (UGETDW(d->bmaControls[0]) == 0)
2385                 return;
2386
2387         memset(&mix, 0, sizeof(mix));
2388
2389         nchan = (d->bLength - 6) / 4;
2390         mmask = UGETDW(d->bmaControls[0]);
2391         cmask = 0;
2392
2393         if (nchan == 0)
2394                 return;
2395
2396         /* figure out what we can control */
2397
2398         for (chan = 1; chan < nchan; chan++)
2399                 cmask |= UGETDW(d->bmaControls[chan]);
2400
2401         if (nchan > MIX_MAX_CHAN)
2402                 nchan = MIX_MAX_CHAN;
2403
2404         mix.wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no);
2405
2406         for (ctl = 3; ctl != 0; ctl <<= 2) {
2407
2408                 mixernumber = uaudio20_mixer_feature_name(&iot[id], &mix);
2409
2410                 switch (ctl) {
2411                 case (3 << 0):
2412                         mix.type = MIX_ON_OFF;
2413                         mix.ctl = SOUND_MIXER_NRDEVICES;
2414                         what = MUTE_CONTROL;
2415                         break;
2416                 case (3 << 2): 
2417                         mix.type = MIX_SIGNED_16;
2418                         mix.ctl = mixernumber;
2419                         what = VOLUME_CONTROL;
2420                         break;
2421                 case (3 << 4):
2422                         mix.type = MIX_SIGNED_8;
2423                         mix.ctl = SOUND_MIXER_BASS;
2424                         what = BASS_CONTROL;
2425                         break;
2426                 case (3 << 6):
2427                         mix.type = MIX_SIGNED_8;
2428                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
2429                         what = MID_CONTROL;
2430                         break;
2431                 case (3 << 8):
2432                         mix.type = MIX_SIGNED_8;
2433                         mix.ctl = SOUND_MIXER_TREBLE;
2434                         what = TREBLE_CONTROL;
2435                         break;
2436                 case (3 << 12):
2437                         mix.type = MIX_ON_OFF;
2438                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
2439                         what = AGC_CONTROL;
2440                         break;
2441                 case (3 << 14):
2442                         mix.type = MIX_UNSIGNED_16;
2443                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
2444                         what = DELAY_CONTROL;
2445                         break;
2446                 case (3 << 16):
2447                         mix.type = MIX_ON_OFF;
2448                         mix.ctl = SOUND_MIXER_NRDEVICES;        /* XXXXX */
2449                         what = BASS_BOOST_CONTROL;
2450                         break;
2451                 case (3 << 18):
2452                         mix.type = MIX_ON_OFF;
2453                         mix.ctl = SOUND_MIXER_LOUD;     /* Is this correct ? */
2454                         what = LOUDNESS_CONTROL;
2455                         break;
2456                 case (3 << 20):
2457                         mix.type = MIX_SIGNED_16;
2458                         mix.ctl = mixernumber;
2459                         what = INPUT_GAIN_CONTROL;
2460                         break;
2461                 case (3 << 22):
2462                         mix.type = MIX_SIGNED_16;
2463                         mix.ctl = mixernumber;
2464                         what = INPUT_GAIN_PAD_CONTROL;
2465                         break;
2466                 default:
2467                         continue;
2468                 }
2469
2470                 if ((mmask & ctl) == ctl) {
2471                         mix.nchan = 1;
2472                         mix.wValue[0] = MAKE_WORD(what, 0);
2473                 } else if ((cmask & ctl) == ctl) {
2474                         mix.nchan = nchan - 1;
2475                         for (i = 1; i < nchan; i++) {
2476                                 if ((UGETDW(d->bmaControls[i]) & ctl) == ctl)
2477                                         mix.wValue[i - 1] = MAKE_WORD(what, i);
2478                                 else
2479                                         mix.wValue[i - 1] = -1;
2480                         }
2481                 } else {
2482                         continue;
2483                 }
2484
2485                 if (mix.type != MIX_UNKNOWN)
2486                         uaudio_mixer_add_ctl(sc, &mix);
2487         }
2488 }
2489
2490 static void
2491 uaudio_mixer_add_processing_updown(struct uaudio_softc *sc,
2492     const struct uaudio_terminal_node *iot, int id)
2493 {
2494         const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
2495         const struct usb_audio_processing_unit_1 *d1 =
2496         (const void *)(d0->baSourceId + d0->bNrInPins);
2497         const struct usb_audio_processing_unit_updown *ud =
2498         (const void *)(d1->bmControls + d1->bControlSize);
2499         struct uaudio_mixer_node mix;
2500         uint8_t i;
2501
2502         if (uaudio_mixer_verify_desc(d0, sizeof(*ud)) == NULL) {
2503                 return;
2504         }
2505         if (uaudio_mixer_verify_desc(d0, sizeof(*ud) + (2 * ud->bNrModes))
2506             == NULL) {
2507                 return;
2508         }
2509         DPRINTFN(3, "bUnitId=%d bNrModes=%d\n",
2510             d0->bUnitId, ud->bNrModes);
2511
2512         if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
2513                 DPRINTF("no mode select\n");
2514                 return;
2515         }
2516         memset(&mix, 0, sizeof(mix));
2517
2518         mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2519         mix.nchan = 1;
2520         mix.wValue[0] = MAKE_WORD(UD_MODE_SELECT_CONTROL, 0);
2521         uaudio_mixer_determine_class(&iot[id], &mix);
2522         mix.type = MIX_ON_OFF;          /* XXX */
2523
2524         for (i = 0; i < ud->bNrModes; i++) {
2525                 DPRINTFN(3, "i=%d bm=0x%x\n", i, UGETW(ud->waModes[i]));
2526                 /* XXX */
2527         }
2528
2529         uaudio_mixer_add_ctl(sc, &mix);
2530 }
2531
2532 static void
2533 uaudio_mixer_add_processing(struct uaudio_softc *sc,
2534     const struct uaudio_terminal_node *iot, int id)
2535 {
2536         const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1;
2537         const struct usb_audio_processing_unit_1 *d1 =
2538         (const void *)(d0->baSourceId + d0->bNrInPins);
2539         struct uaudio_mixer_node mix;
2540         uint16_t ptype;
2541
2542         memset(&mix, 0, sizeof(mix));
2543
2544         ptype = UGETW(d0->wProcessType);
2545
2546         DPRINTFN(3, "wProcessType=%d bUnitId=%d "
2547             "bNrInPins=%d\n", ptype, d0->bUnitId, d0->bNrInPins);
2548
2549         if (d1->bControlSize == 0) {
2550                 return;
2551         }
2552         if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
2553                 mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2554                 mix.nchan = 1;
2555                 mix.wValue[0] = MAKE_WORD(XX_ENABLE_CONTROL, 0);
2556                 uaudio_mixer_determine_class(&iot[id], &mix);
2557                 mix.type = MIX_ON_OFF;
2558                 uaudio_mixer_add_ctl(sc, &mix);
2559         }
2560         switch (ptype) {
2561         case UPDOWNMIX_PROCESS:
2562                 uaudio_mixer_add_processing_updown(sc, iot, id);
2563                 break;
2564
2565         case DOLBY_PROLOGIC_PROCESS:
2566         case P3D_STEREO_EXTENDER_PROCESS:
2567         case REVERBATION_PROCESS:
2568         case CHORUS_PROCESS:
2569         case DYN_RANGE_COMP_PROCESS:
2570         default:
2571                 DPRINTF("unit %d, type=%d is not implemented\n",
2572                     d0->bUnitId, ptype);
2573                 break;
2574         }
2575 }
2576
2577 static void
2578 uaudio_mixer_add_extension(struct uaudio_softc *sc,
2579     const struct uaudio_terminal_node *iot, int id)
2580 {
2581         const struct usb_audio_extension_unit_0 *d0 = iot[id].u.eu_v1;
2582         const struct usb_audio_extension_unit_1 *d1 =
2583         (const void *)(d0->baSourceId + d0->bNrInPins);
2584         struct uaudio_mixer_node mix;
2585
2586         DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n",
2587             d0->bUnitId, d0->bNrInPins);
2588
2589         if (sc->sc_uq_au_no_xu) {
2590                 return;
2591         }
2592         if (d1->bControlSize == 0) {
2593                 return;
2594         }
2595         if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
2596
2597                 memset(&mix, 0, sizeof(mix));
2598
2599                 mix.wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no);
2600                 mix.nchan = 1;
2601                 mix.wValue[0] = MAKE_WORD(UA_EXT_ENABLE, 0);
2602                 uaudio_mixer_determine_class(&iot[id], &mix);
2603                 mix.type = MIX_ON_OFF;
2604
2605                 uaudio_mixer_add_ctl(sc, &mix);
2606         }
2607 }
2608
2609 static const void *
2610 uaudio_mixer_verify_desc(const void *arg, uint32_t len)
2611 {
2612         const struct usb_audio_mixer_unit_1 *d1;
2613         const struct usb_audio_extension_unit_1 *e1;
2614         const struct usb_audio_processing_unit_1 *u1;
2615
2616         union {
2617                 const struct usb_descriptor *desc;
2618                 const struct usb_audio_input_terminal *it;
2619                 const struct usb_audio_output_terminal *ot;
2620                 const struct usb_audio_mixer_unit_0 *mu;
2621                 const struct usb_audio_selector_unit *su;
2622                 const struct usb_audio_feature_unit *fu;
2623                 const struct usb_audio_processing_unit_0 *pu;
2624                 const struct usb_audio_extension_unit_0 *eu;
2625         }     u;
2626
2627         u.desc = arg;
2628
2629         if (u.desc == NULL) {
2630                 goto error;
2631         }
2632         if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) {
2633                 goto error;
2634         }
2635         switch (u.desc->bDescriptorSubtype) {
2636         case UDESCSUB_AC_INPUT:
2637                 len += sizeof(*u.it);
2638                 break;
2639
2640         case UDESCSUB_AC_OUTPUT:
2641                 len += sizeof(*u.ot);
2642                 break;
2643
2644         case UDESCSUB_AC_MIXER:
2645                 len += sizeof(*u.mu);
2646
2647                 if (u.desc->bLength < len) {
2648                         goto error;
2649                 }
2650                 len += u.mu->bNrInPins;
2651
2652                 if (u.desc->bLength < len) {
2653                         goto error;
2654                 }
2655                 d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
2656
2657                 len += sizeof(*d1);
2658                 break;
2659
2660         case UDESCSUB_AC_SELECTOR:
2661                 len += sizeof(*u.su);
2662
2663                 if (u.desc->bLength < len) {
2664                         goto error;
2665                 }
2666                 len += u.su->bNrInPins;
2667                 break;
2668
2669         case UDESCSUB_AC_FEATURE:
2670                 len += (sizeof(*u.fu) + 1);
2671                 break;
2672
2673         case UDESCSUB_AC_PROCESSING:
2674                 len += sizeof(*u.pu);
2675
2676                 if (u.desc->bLength < len) {
2677                         goto error;
2678                 }
2679                 len += u.pu->bNrInPins;
2680
2681                 if (u.desc->bLength < len) {
2682                         goto error;
2683                 }
2684                 u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
2685
2686                 len += sizeof(*u1);
2687
2688                 if (u.desc->bLength < len) {
2689                         goto error;
2690                 }
2691                 len += u1->bControlSize;
2692
2693                 break;
2694
2695         case UDESCSUB_AC_EXTENSION:
2696                 len += sizeof(*u.eu);
2697
2698                 if (u.desc->bLength < len) {
2699                         goto error;
2700                 }
2701                 len += u.eu->bNrInPins;
2702
2703                 if (u.desc->bLength < len) {
2704                         goto error;
2705                 }
2706                 e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
2707
2708                 len += sizeof(*e1);
2709
2710                 if (u.desc->bLength < len) {
2711                         goto error;
2712                 }
2713                 len += e1->bControlSize;
2714                 break;
2715
2716         default:
2717                 goto error;
2718         }
2719
2720         if (u.desc->bLength < len) {
2721                 goto error;
2722         }
2723         return (u.desc);
2724
2725 error:
2726         if (u.desc) {
2727                 DPRINTF("invalid descriptor, type=%d, "
2728                     "sub_type=%d, len=%d of %d bytes\n",
2729                     u.desc->bDescriptorType,
2730                     u.desc->bDescriptorSubtype,
2731                     u.desc->bLength, len);
2732         }
2733         return (NULL);
2734 }
2735
2736 static const void *
2737 uaudio20_mixer_verify_desc(const void *arg, uint32_t len)
2738 {
2739         const struct usb_audio20_mixer_unit_1 *d1;
2740         const struct usb_audio20_extension_unit_1 *e1;
2741         const struct usb_audio20_processing_unit_1 *u1;
2742         const struct usb_audio20_clock_selector_unit_1 *c1;
2743
2744         union {
2745                 const struct usb_descriptor *desc;
2746                 const struct usb_audio20_clock_source_unit *csrc;
2747                 const struct usb_audio20_clock_selector_unit_0 *csel;
2748                 const struct usb_audio20_clock_multiplier_unit *cmul;
2749                 const struct usb_audio20_input_terminal *it;
2750                 const struct usb_audio20_output_terminal *ot;
2751                 const struct usb_audio20_mixer_unit_0 *mu;
2752                 const struct usb_audio20_selector_unit *su;
2753                 const struct usb_audio20_feature_unit *fu;
2754                 const struct usb_audio20_sample_rate_unit *ru;
2755                 const struct usb_audio20_processing_unit_0 *pu;
2756                 const struct usb_audio20_extension_unit_0 *eu;
2757                 const struct usb_audio20_effect_unit *ef;
2758         }     u;
2759
2760         u.desc = arg;
2761
2762         if (u.desc == NULL)
2763                 goto error;
2764
2765         if (u.desc->bDescriptorType != UDESC_CS_INTERFACE)
2766                 goto error;
2767
2768         switch (u.desc->bDescriptorSubtype) {
2769         case UDESCSUB_AC_INPUT:
2770                 len += sizeof(*u.it);
2771                 break;
2772
2773         case UDESCSUB_AC_OUTPUT:
2774                 len += sizeof(*u.ot);
2775                 break;
2776
2777         case UDESCSUB_AC_MIXER:
2778                 len += sizeof(*u.mu);
2779
2780                 if (u.desc->bLength < len)
2781                         goto error;
2782                 len += u.mu->bNrInPins;
2783
2784                 if (u.desc->bLength < len)
2785                         goto error;
2786
2787                 d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins);
2788
2789                 len += sizeof(*d1) + d1->bNrChannels;
2790                 break;
2791
2792         case UDESCSUB_AC_SELECTOR:
2793                 len += sizeof(*u.su);
2794
2795                 if (u.desc->bLength < len)
2796                         goto error;
2797
2798                 len += u.su->bNrInPins;
2799                 break;
2800
2801         case UDESCSUB_AC_FEATURE:
2802                 len += sizeof(*u.fu) + 1;
2803
2804                 if (u.desc->bLength < len)
2805                         goto error;
2806                 break;
2807
2808         case UDESCSUB_AC_EFFECT:
2809                 len += sizeof(*u.ef) + 4;
2810                 break;
2811
2812         case UDESCSUB_AC_PROCESSING_V2:
2813                 len += sizeof(*u.pu);
2814
2815                 if (u.desc->bLength < len)
2816                         goto error;
2817
2818                 len += u.pu->bNrInPins;
2819
2820                 if (u.desc->bLength < len)
2821                         goto error;
2822
2823                 u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins);
2824
2825                 len += sizeof(*u1);
2826                 break;
2827
2828         case UDESCSUB_AC_EXTENSION_V2:
2829                 len += sizeof(*u.eu);
2830
2831                 if (u.desc->bLength < len)
2832                         goto error;
2833
2834                 len += u.eu->bNrInPins;
2835
2836                 if (u.desc->bLength < len)
2837                         goto error;
2838
2839                 e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins);
2840
2841                 len += sizeof(*e1);
2842                 break;
2843
2844         case UDESCSUB_AC_CLOCK_SRC:
2845                 len += sizeof(*u.csrc);
2846                 break;
2847
2848         case UDESCSUB_AC_CLOCK_SEL:
2849                 len += sizeof(*u.csel);
2850
2851                 if (u.desc->bLength < len)
2852                         goto error;
2853
2854                 len += u.csel->bNrInPins;
2855
2856                 if (u.desc->bLength < len)
2857                         goto error;
2858
2859                 c1 = (const void *)(u.csel->baCSourceId + u.csel->bNrInPins);
2860
2861                 len += sizeof(*c1);
2862                 break;
2863
2864         case UDESCSUB_AC_CLOCK_MUL:
2865                 len += sizeof(*u.cmul);
2866                 break;
2867
2868         case UDESCSUB_AC_SAMPLE_RT:
2869                 len += sizeof(*u.ru);
2870                 break;
2871
2872         default:
2873                 goto error;
2874         }
2875
2876         if (u.desc->bLength < len)
2877                 goto error;
2878
2879         return (u.desc);
2880
2881 error:
2882         if (u.desc) {
2883                 DPRINTF("invalid descriptor, type=%d, "
2884                     "sub_type=%d, len=%d of %d bytes\n",
2885                     u.desc->bDescriptorType,
2886                     u.desc->bDescriptorSubtype,
2887                     u.desc->bLength, len);
2888         }
2889         return (NULL);
2890 }
2891
2892 static struct usb_audio_cluster
2893 uaudio_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
2894 {
2895         struct usb_audio_cluster r;
2896         const struct usb_descriptor *dp;
2897         uint8_t i;
2898
2899         for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {    /* avoid infinite loops */
2900                 dp = iot[id].u.desc;
2901                 if (dp == NULL) {
2902                         goto error;
2903                 }
2904                 switch (dp->bDescriptorSubtype) {
2905                 case UDESCSUB_AC_INPUT:
2906                         r.bNrChannels = iot[id].u.it_v1->bNrChannels;
2907                         r.wChannelConfig[0] = iot[id].u.it_v1->wChannelConfig[0];
2908                         r.wChannelConfig[1] = iot[id].u.it_v1->wChannelConfig[1];
2909                         r.iChannelNames = iot[id].u.it_v1->iChannelNames;
2910                         goto done;
2911
2912                 case UDESCSUB_AC_OUTPUT:
2913                         id = iot[id].u.ot_v1->bSourceId;
2914                         break;
2915
2916                 case UDESCSUB_AC_MIXER:
2917                         r = *(const struct usb_audio_cluster *)
2918                             &iot[id].u.mu_v1->baSourceId[
2919                             iot[id].u.mu_v1->bNrInPins];
2920                         goto done;
2921
2922                 case UDESCSUB_AC_SELECTOR:
2923                         if (iot[id].u.su_v1->bNrInPins > 0) {
2924                                 /* XXX This is not really right */
2925                                 id = iot[id].u.su_v1->baSourceId[0];
2926                         }
2927                         break;
2928
2929                 case UDESCSUB_AC_FEATURE:
2930                         id = iot[id].u.fu_v1->bSourceId;
2931                         break;
2932
2933                 case UDESCSUB_AC_PROCESSING:
2934                         r = *((const struct usb_audio_cluster *)
2935                             &iot[id].u.pu_v1->baSourceId[
2936                             iot[id].u.pu_v1->bNrInPins]);
2937                         goto done;
2938
2939                 case UDESCSUB_AC_EXTENSION:
2940                         r = *((const struct usb_audio_cluster *)
2941                             &iot[id].u.eu_v1->baSourceId[
2942                             iot[id].u.eu_v1->bNrInPins]);
2943                         goto done;
2944
2945                 default:
2946                         goto error;
2947                 }
2948         }
2949 error:
2950         DPRINTF("bad data\n");
2951         memset(&r, 0, sizeof(r));
2952 done:
2953         return (r);
2954 }
2955
2956 static struct usb_audio20_cluster
2957 uaudio20_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot)
2958 {
2959         struct usb_audio20_cluster r;
2960         const struct usb_descriptor *dp;
2961         uint8_t i;
2962
2963         for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) {    /* avoid infinite loops */
2964                 dp = iot[id].u.desc;
2965                 if (dp == NULL)
2966                         goto error;
2967
2968                 switch (dp->bDescriptorSubtype) {
2969                 case UDESCSUB_AC_INPUT:
2970                         r.bNrChannels = iot[id].u.it_v2->bNrChannels;
2971                         r.bmChannelConfig[0] = iot[id].u.it_v2->bmChannelConfig[0];
2972                         r.bmChannelConfig[1] = iot[id].u.it_v2->bmChannelConfig[1];
2973                         r.bmChannelConfig[2] = iot[id].u.it_v2->bmChannelConfig[2];
2974                         r.bmChannelConfig[3] = iot[id].u.it_v2->bmChannelConfig[3];
2975                         r.iChannelNames = iot[id].u.it_v2->iTerminal;
2976                         goto done;
2977
2978                 case UDESCSUB_AC_OUTPUT:
2979                         id = iot[id].u.ot_v2->bSourceId;
2980                         break;
2981
2982                 case UDESCSUB_AC_MIXER:
2983                         r = *(const struct usb_audio20_cluster *)
2984                             &iot[id].u.mu_v2->baSourceId[
2985                             iot[id].u.mu_v2->bNrInPins];
2986                         goto done;
2987
2988                 case UDESCSUB_AC_SELECTOR:
2989                         if (iot[id].u.su_v2->bNrInPins > 0) {
2990                                 /* XXX This is not really right */
2991                                 id = iot[id].u.su_v2->baSourceId[0];
2992                         }
2993                         break;
2994
2995                 case UDESCSUB_AC_SAMPLE_RT:
2996                         id = iot[id].u.ru_v2->bSourceId;
2997                         break;
2998
2999                 case UDESCSUB_AC_EFFECT:
3000                         id = iot[id].u.ef_v2->bSourceId;
3001                         break;
3002
3003                 case UDESCSUB_AC_FEATURE:
3004                         id = iot[id].u.fu_v2->bSourceId;
3005                         break;
3006
3007                 case UDESCSUB_AC_PROCESSING_V2:
3008                         r = *((const struct usb_audio20_cluster *)
3009                             &iot[id].u.pu_v2->baSourceId[
3010                             iot[id].u.pu_v2->bNrInPins]);
3011                         goto done;
3012
3013                 case UDESCSUB_AC_EXTENSION_V2:
3014                         r = *((const struct usb_audio20_cluster *)
3015                             &iot[id].u.eu_v2->baSourceId[
3016                             iot[id].u.eu_v2->bNrInPins]);
3017                         goto done;
3018
3019                 default:
3020                         goto error;
3021                 }
3022         }
3023 error:
3024         DPRINTF("Bad data!\n");
3025         memset(&r, 0, sizeof(r));
3026 done:
3027         return (r);
3028 }
3029
3030 static uint16_t
3031 uaudio_mixer_determine_class(const struct uaudio_terminal_node *iot,
3032     struct uaudio_mixer_node *mix)
3033 {
3034         uint16_t terminal_type = 0x0000;
3035         const struct uaudio_terminal_node *input[2];
3036         const struct uaudio_terminal_node *output[2];
3037
3038         input[0] = uaudio_mixer_get_input(iot, 0);
3039         input[1] = uaudio_mixer_get_input(iot, 1);
3040
3041         output[0] = uaudio_mixer_get_output(iot, 0);
3042         output[1] = uaudio_mixer_get_output(iot, 1);
3043
3044         /*
3045          * check if there is only
3046          * one output terminal:
3047          */
3048         if (output[0] && (!output[1])) {
3049                 terminal_type =
3050                     UGETW(output[0]->u.ot_v1->wTerminalType);
3051         }
3052         /*
3053          * If the only output terminal is USB,
3054          * the class is UAC_RECORD.
3055          */
3056         if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
3057
3058                 mix->class = UAC_RECORD;
3059                 if (input[0] && (!input[1])) {
3060                         terminal_type =
3061                             UGETW(input[0]->u.it_v1->wTerminalType);
3062                 } else {
3063                         terminal_type = 0;
3064                 }
3065                 goto done;
3066         }
3067         /*
3068          * if the unit is connected to just
3069          * one input terminal, the
3070          * class is UAC_INPUT:
3071          */
3072         if (input[0] && (!input[1])) {
3073                 mix->class = UAC_INPUT;
3074                 terminal_type =
3075                     UGETW(input[0]->u.it_v1->wTerminalType);
3076                 goto done;
3077         }
3078         /*
3079          * Otherwise, the class is UAC_OUTPUT.
3080          */
3081         mix->class = UAC_OUTPUT;
3082 done:
3083         return (terminal_type);
3084 }
3085
3086 static uint16_t
3087 uaudio20_mixer_determine_class(const struct uaudio_terminal_node *iot,
3088     struct uaudio_mixer_node *mix)
3089 {
3090         uint16_t terminal_type = 0x0000;
3091         const struct uaudio_terminal_node *input[2];
3092         const struct uaudio_terminal_node *output[2];
3093
3094         input[0] = uaudio_mixer_get_input(iot, 0);
3095         input[1] = uaudio_mixer_get_input(iot, 1);
3096
3097         output[0] = uaudio_mixer_get_output(iot, 0);
3098         output[1] = uaudio_mixer_get_output(iot, 1);
3099
3100         /*
3101          * check if there is only
3102          * one output terminal:
3103          */
3104         if (output[0] && (!output[1]))
3105                 terminal_type = UGETW(output[0]->u.ot_v2->wTerminalType);
3106         /*
3107          * If the only output terminal is USB,
3108          * the class is UAC_RECORD.
3109          */
3110         if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
3111
3112                 mix->class = UAC_RECORD;
3113                 if (input[0] && (!input[1])) {
3114                         terminal_type =
3115                             UGETW(input[0]->u.it_v2->wTerminalType);
3116                 } else {
3117                         terminal_type = 0;
3118                 }
3119                 goto done;
3120         }
3121         /*
3122          * if the unit is connected to just
3123          * one input terminal, the
3124          * class is UAC_INPUT:
3125          */
3126         if (input[0] && (!input[1])) {
3127                 mix->class = UAC_INPUT;
3128                 terminal_type =
3129                     UGETW(input[0]->u.it_v2->wTerminalType);
3130                 goto done;
3131         }
3132         /*
3133          * Otherwise, the class is UAC_OUTPUT.
3134          */
3135         mix->class = UAC_OUTPUT;
3136 done:
3137         return (terminal_type);
3138 }
3139
3140 struct uaudio_tt_to_feature {
3141         uint16_t terminal_type;
3142         uint16_t feature;
3143 };
3144
3145 static const struct uaudio_tt_to_feature uaudio_tt_to_feature[] = {
3146
3147         {UAT_STREAM, SOUND_MIXER_PCM},
3148
3149         {UATI_MICROPHONE, SOUND_MIXER_MIC},
3150         {UATI_DESKMICROPHONE, SOUND_MIXER_MIC},
3151         {UATI_PERSONALMICROPHONE, SOUND_MIXER_MIC},
3152         {UATI_OMNIMICROPHONE, SOUND_MIXER_MIC},
3153         {UATI_MICROPHONEARRAY, SOUND_MIXER_MIC},
3154         {UATI_PROCMICROPHONEARR, SOUND_MIXER_MIC},
3155
3156         {UATO_SPEAKER, SOUND_MIXER_SPEAKER},
3157         {UATO_DESKTOPSPEAKER, SOUND_MIXER_SPEAKER},
3158         {UATO_ROOMSPEAKER, SOUND_MIXER_SPEAKER},
3159         {UATO_COMMSPEAKER, SOUND_MIXER_SPEAKER},
3160
3161         {UATE_ANALOGCONN, SOUND_MIXER_LINE},
3162         {UATE_LINECONN, SOUND_MIXER_LINE},
3163         {UATE_LEGACYCONN, SOUND_MIXER_LINE},
3164
3165         {UATE_DIGITALAUIFC, SOUND_MIXER_ALTPCM},
3166         {UATE_SPDIF, SOUND_MIXER_ALTPCM},
3167         {UATE_1394DA, SOUND_MIXER_ALTPCM},
3168         {UATE_1394DV, SOUND_MIXER_ALTPCM},
3169
3170         {UATF_CDPLAYER, SOUND_MIXER_CD},
3171
3172         {UATF_SYNTHESIZER, SOUND_MIXER_SYNTH},
3173
3174         {UATF_VIDEODISCAUDIO, SOUND_MIXER_VIDEO},
3175         {UATF_DVDAUDIO, SOUND_MIXER_VIDEO},
3176         {UATF_TVTUNERAUDIO, SOUND_MIXER_VIDEO},
3177
3178         /* telephony terminal types */
3179         {UATT_UNDEFINED, SOUND_MIXER_PHONEIN},  /* SOUND_MIXER_PHONEOUT */
3180         {UATT_PHONELINE, SOUND_MIXER_PHONEIN},  /* SOUND_MIXER_PHONEOUT */
3181         {UATT_TELEPHONE, SOUND_MIXER_PHONEIN},  /* SOUND_MIXER_PHONEOUT */
3182         {UATT_DOWNLINEPHONE, SOUND_MIXER_PHONEIN},      /* SOUND_MIXER_PHONEOUT */
3183
3184         {UATF_RADIORECV, SOUND_MIXER_RADIO},
3185         {UATF_RADIOXMIT, SOUND_MIXER_RADIO},
3186
3187         {UAT_UNDEFINED, SOUND_MIXER_VOLUME},
3188         {UAT_VENDOR, SOUND_MIXER_VOLUME},
3189         {UATI_UNDEFINED, SOUND_MIXER_VOLUME},
3190
3191         /* output terminal types */
3192         {UATO_UNDEFINED, SOUND_MIXER_VOLUME},
3193         {UATO_DISPLAYAUDIO, SOUND_MIXER_VOLUME},
3194         {UATO_SUBWOOFER, SOUND_MIXER_VOLUME},
3195         {UATO_HEADPHONES, SOUND_MIXER_VOLUME},
3196
3197         /* bidir terminal types */
3198         {UATB_UNDEFINED, SOUND_MIXER_VOLUME},
3199         {UATB_HANDSET, SOUND_MIXER_VOLUME},
3200         {UATB_HEADSET, SOUND_MIXER_VOLUME},
3201         {UATB_SPEAKERPHONE, SOUND_MIXER_VOLUME},
3202         {UATB_SPEAKERPHONEESUP, SOUND_MIXER_VOLUME},
3203         {UATB_SPEAKERPHONEECANC, SOUND_MIXER_VOLUME},
3204
3205         /* external terminal types */
3206         {UATE_UNDEFINED, SOUND_MIXER_VOLUME},
3207
3208         /* embedded function terminal types */
3209         {UATF_UNDEFINED, SOUND_MIXER_VOLUME},
3210         {UATF_CALIBNOISE, SOUND_MIXER_VOLUME},
3211         {UATF_EQUNOISE, SOUND_MIXER_VOLUME},
3212         {UATF_DAT, SOUND_MIXER_VOLUME},
3213         {UATF_DCC, SOUND_MIXER_VOLUME},
3214         {UATF_MINIDISK, SOUND_MIXER_VOLUME},
3215         {UATF_ANALOGTAPE, SOUND_MIXER_VOLUME},
3216         {UATF_PHONOGRAPH, SOUND_MIXER_VOLUME},
3217         {UATF_VCRAUDIO, SOUND_MIXER_VOLUME},
3218         {UATF_SATELLITE, SOUND_MIXER_VOLUME},
3219         {UATF_CABLETUNER, SOUND_MIXER_VOLUME},
3220         {UATF_DSS, SOUND_MIXER_VOLUME},
3221         {UATF_MULTITRACK, SOUND_MIXER_VOLUME},
3222         {0xffff, SOUND_MIXER_VOLUME},
3223
3224         /* default */
3225         {0x0000, SOUND_MIXER_VOLUME},
3226 };
3227
3228 static uint16_t
3229 uaudio_mixer_feature_name(const struct uaudio_terminal_node *iot,
3230     struct uaudio_mixer_node *mix)
3231 {
3232         const struct uaudio_tt_to_feature *uat = uaudio_tt_to_feature;
3233         uint16_t terminal_type = uaudio_mixer_determine_class(iot, mix);
3234
3235         if ((mix->class == UAC_RECORD) && (terminal_type == 0)) {
3236                 return (SOUND_MIXER_IMIX);
3237         }
3238         while (uat->terminal_type) {
3239                 if (uat->terminal_type == terminal_type) {
3240                         break;
3241                 }
3242                 uat++;
3243         }
3244
3245         DPRINTF("terminal_type=0x%04x -> %d\n",
3246             terminal_type, uat->feature);
3247
3248         return (uat->feature);
3249 }
3250
3251 static uint16_t
3252 uaudio20_mixer_feature_name(const struct uaudio_terminal_node *iot,
3253     struct uaudio_mixer_node *mix)
3254 {
3255         const struct uaudio_tt_to_feature *uat;
3256         uint16_t terminal_type = uaudio20_mixer_determine_class(iot, mix);
3257
3258         if ((mix->class == UAC_RECORD) && (terminal_type == 0))
3259                 return (SOUND_MIXER_IMIX);
3260         
3261         for (uat = uaudio_tt_to_feature; uat->terminal_type != 0; uat++) {
3262                 if (uat->terminal_type == terminal_type)
3263                         break;
3264         }
3265
3266         DPRINTF("terminal_type=0x%04x -> %d\n",
3267             terminal_type, uat->feature);
3268
3269         return (uat->feature);
3270 }
3271
3272 static const struct uaudio_terminal_node *
3273 uaudio_mixer_get_input(const struct uaudio_terminal_node *iot, uint8_t i)
3274 {
3275         struct uaudio_terminal_node *root = iot->root;
3276         uint8_t n;
3277
3278         n = iot->usr.id_max;
3279         do {
3280                 if (iot->usr.bit_input[n / 8] & (1 << (n % 8))) {
3281                         if (!i--)
3282                                 return (root + n);
3283                 }
3284         } while (n--);
3285
3286         return (NULL);
3287 }
3288
3289 static const struct uaudio_terminal_node *
3290 uaudio_mixer_get_output(const struct uaudio_terminal_node *iot, uint8_t i)
3291 {
3292         struct uaudio_terminal_node *root = iot->root;
3293         uint8_t n;
3294
3295         n = iot->usr.id_max;
3296         do {
3297                 if (iot->usr.bit_output[n / 8] & (1 << (n % 8))) {
3298                         if (!i--)
3299                                 return (root + n);
3300                 }
3301         } while (n--);
3302
3303         return (NULL);
3304 }
3305
3306 static void
3307 uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
3308     const uint8_t *p_id, uint8_t n_id,
3309     struct uaudio_search_result *info)
3310 {
3311         struct uaudio_terminal_node *iot;
3312         uint8_t n;
3313         uint8_t i;
3314         uint8_t is_last;
3315
3316 top:
3317         for (n = 0; n < n_id; n++) {
3318
3319                 i = p_id[n];
3320
3321                 if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
3322                         DPRINTF("avoided going into a circle at id=%d!\n", i);
3323                         return;
3324                 }
3325
3326                 info->recurse_level++;
3327
3328                 iot = (root + i);
3329
3330                 if (iot->u.desc == NULL)
3331                         continue;
3332
3333                 is_last = ((n + 1) == n_id);
3334
3335                 switch (iot->u.desc->bDescriptorSubtype) {
3336                 case UDESCSUB_AC_INPUT:
3337                         info->bit_input[i / 8] |= (1 << (i % 8));
3338                         break;
3339
3340                 case UDESCSUB_AC_FEATURE:
3341                         if (is_last) {
3342                                 p_id = &iot->u.fu_v1->bSourceId;
3343                                 n_id = 1;
3344                                 goto top;
3345                         }
3346                         uaudio_mixer_find_inputs_sub(
3347                             root, &iot->u.fu_v1->bSourceId, 1, info);
3348                         break;
3349
3350                 case UDESCSUB_AC_OUTPUT:
3351                         if (is_last) {
3352                                 p_id = &iot->u.ot_v1->bSourceId;
3353                                 n_id = 1;
3354                                 goto top;
3355                         }
3356                         uaudio_mixer_find_inputs_sub(
3357                             root, &iot->u.ot_v1->bSourceId, 1, info);
3358                         break;
3359
3360                 case UDESCSUB_AC_MIXER:
3361                         if (is_last) {
3362                                 p_id = iot->u.mu_v1->baSourceId;
3363                                 n_id = iot->u.mu_v1->bNrInPins;
3364                                 goto top;
3365                         }
3366                         uaudio_mixer_find_inputs_sub(
3367                             root, iot->u.mu_v1->baSourceId,
3368                             iot->u.mu_v1->bNrInPins, info);
3369                         break;
3370
3371                 case UDESCSUB_AC_SELECTOR:
3372                         if (is_last) {
3373                                 p_id = iot->u.su_v1->baSourceId;
3374                                 n_id = iot->u.su_v1->bNrInPins;
3375                                 goto top;
3376                         }
3377                         uaudio_mixer_find_inputs_sub(
3378                             root, iot->u.su_v1->baSourceId,
3379                             iot->u.su_v1->bNrInPins, info);
3380                         break;
3381
3382                 case UDESCSUB_AC_PROCESSING:
3383                         if (is_last) {
3384                                 p_id = iot->u.pu_v1->baSourceId;
3385                                 n_id = iot->u.pu_v1->bNrInPins;
3386                                 goto top;
3387                         }
3388                         uaudio_mixer_find_inputs_sub(
3389                             root, iot->u.pu_v1->baSourceId,
3390                             iot->u.pu_v1->bNrInPins, info);
3391                         break;
3392
3393                 case UDESCSUB_AC_EXTENSION:
3394                         if (is_last) {
3395                                 p_id = iot->u.eu_v1->baSourceId;
3396                                 n_id = iot->u.eu_v1->bNrInPins;
3397                                 goto top;
3398                         }
3399                         uaudio_mixer_find_inputs_sub(
3400                             root, iot->u.eu_v1->baSourceId,
3401                             iot->u.eu_v1->bNrInPins, info);
3402                         break;
3403
3404                 default:
3405                         break;
3406                 }
3407         }
3408 }
3409
3410 static void
3411 uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *root,
3412     const uint8_t *p_id, uint8_t n_id,
3413     struct uaudio_search_result *info)
3414 {
3415         struct uaudio_terminal_node *iot;
3416         uint8_t n;
3417         uint8_t i;
3418         uint8_t is_last;
3419
3420 top:
3421         for (n = 0; n < n_id; n++) {
3422
3423                 i = p_id[n];
3424
3425                 if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
3426                         DPRINTF("avoided going into a circle at id=%d!\n", i);
3427                         return;
3428                 }
3429
3430                 info->recurse_level++;
3431
3432                 iot = (root + i);
3433
3434                 if (iot->u.desc == NULL)
3435                         continue;
3436
3437                 is_last = ((n + 1) == n_id);
3438
3439                 switch (iot->u.desc->bDescriptorSubtype) {
3440                 case UDESCSUB_AC_INPUT:
3441                         info->bit_input[i / 8] |= (1 << (i % 8));
3442                         break;
3443
3444                 case UDESCSUB_AC_OUTPUT:
3445                         if (is_last) {
3446                                 p_id = &iot->u.ot_v2->bSourceId;
3447                                 n_id = 1;
3448                                 goto top;
3449                         }
3450                         uaudio20_mixer_find_inputs_sub(
3451                             root, &iot->u.ot_v2->bSourceId, 1, info);
3452                         break;
3453
3454                 case UDESCSUB_AC_MIXER:
3455                         if (is_last) {
3456                                 p_id = iot->u.mu_v2->baSourceId;
3457                                 n_id = iot->u.mu_v2->bNrInPins;
3458                                 goto top;
3459                         }
3460                         uaudio20_mixer_find_inputs_sub(
3461                             root, iot->u.mu_v2->baSourceId,
3462                             iot->u.mu_v2->bNrInPins, info);
3463                         break;
3464
3465                 case UDESCSUB_AC_SELECTOR:
3466                         if (is_last) {
3467                                 p_id = iot->u.su_v2->baSourceId;
3468                                 n_id = iot->u.su_v2->bNrInPins;
3469                                 goto top;
3470                         }
3471                         uaudio20_mixer_find_inputs_sub(
3472                             root, iot->u.su_v2->baSourceId,
3473                             iot->u.su_v2->bNrInPins, info);
3474                         break;
3475
3476                 case UDESCSUB_AC_SAMPLE_RT:
3477                         if (is_last) {
3478                                 p_id = &iot->u.ru_v2->bSourceId;
3479                                 n_id = 1;
3480                                 goto top;
3481                         }
3482                         uaudio20_mixer_find_inputs_sub(
3483                             root, &iot->u.ru_v2->bSourceId,
3484                             1, info);
3485                         break;
3486
3487                 case UDESCSUB_AC_EFFECT:
3488                         if (is_last) {
3489                                 p_id = &iot->u.ef_v2->bSourceId;
3490                                 n_id = 1;
3491                                 goto top;
3492                         }
3493                         uaudio20_mixer_find_inputs_sub(
3494                             root, &iot->u.ef_v2->bSourceId,
3495                             1, info);
3496                         break;
3497
3498                 case UDESCSUB_AC_FEATURE:
3499                         if (is_last) {
3500                                 p_id = &iot->u.fu_v2->bSourceId;
3501                                 n_id = 1;
3502                                 goto top;
3503                         }
3504                         uaudio20_mixer_find_inputs_sub(
3505                             root, &iot->u.fu_v2->bSourceId, 1, info);
3506                         break;
3507
3508                 case UDESCSUB_AC_PROCESSING_V2:
3509                         if (is_last) {
3510                                 p_id = iot->u.pu_v2->baSourceId;
3511                                 n_id = iot->u.pu_v2->bNrInPins;
3512                                 goto top;
3513                         }
3514                         uaudio20_mixer_find_inputs_sub(
3515                             root, iot->u.pu_v2->baSourceId,
3516                             iot->u.pu_v2->bNrInPins, info);
3517                         break;
3518
3519                 case UDESCSUB_AC_EXTENSION_V2:
3520                         if (is_last) {
3521                                 p_id = iot->u.eu_v2->baSourceId;
3522                                 n_id = iot->u.eu_v2->bNrInPins;
3523                                 goto top;
3524                         }
3525                         uaudio20_mixer_find_inputs_sub(
3526                             root, iot->u.eu_v2->baSourceId,
3527                             iot->u.eu_v2->bNrInPins, info);
3528                         break;
3529                 default:
3530                         break;
3531                 }
3532         }
3533 }
3534
3535 static void
3536 uaudio20_mixer_find_clocks_sub(struct uaudio_terminal_node *root,
3537     const uint8_t *p_id, uint8_t n_id,
3538     struct uaudio_search_result *info)
3539 {
3540         struct uaudio_terminal_node *iot;
3541         uint8_t n;
3542         uint8_t i;
3543         uint8_t is_last;
3544         uint8_t id;
3545
3546 top:
3547         for (n = 0; n < n_id; n++) {
3548
3549                 i = p_id[n];
3550
3551                 if (info->recurse_level == UAUDIO_RECURSE_LIMIT) {
3552                         DPRINTF("avoided going into a circle at id=%d!\n", i);
3553                         return;
3554                 }
3555
3556                 info->recurse_level++;
3557
3558                 iot = (root + i);
3559
3560                 if (iot->u.desc == NULL)
3561                         continue;
3562
3563                 is_last = ((n + 1) == n_id);
3564
3565                 switch (iot->u.desc->bDescriptorSubtype) {
3566                 case UDESCSUB_AC_INPUT:
3567                         info->is_input = 1;
3568                         if (is_last) {
3569                                 p_id = &iot->u.it_v2->bCSourceId;
3570                                 n_id = 1;
3571                                 goto top;
3572                         }
3573                         uaudio20_mixer_find_clocks_sub(root,
3574                             &iot->u.it_v2->bCSourceId, 1, info);
3575                         break;
3576
3577                 case UDESCSUB_AC_OUTPUT:
3578                         info->is_input = 0;
3579                         if (is_last) {
3580                                 p_id = &iot->u.ot_v2->bCSourceId;
3581                                 n_id = 1;
3582                                 goto top;
3583                         }
3584                         uaudio20_mixer_find_clocks_sub(root,
3585                             &iot->u.ot_v2->bCSourceId, 1, info);
3586                         break;
3587
3588                 case UDESCSUB_AC_CLOCK_SEL:
3589                         if (is_last) {
3590                                 p_id = iot->u.csel_v2->baCSourceId;
3591                                 n_id = iot->u.csel_v2->bNrInPins;
3592                                 goto top;
3593                         }
3594                         uaudio20_mixer_find_clocks_sub(root,
3595                             iot->u.csel_v2->baCSourceId,
3596                             iot->u.csel_v2->bNrInPins, info);
3597                         break;
3598
3599                 case UDESCSUB_AC_CLOCK_MUL:
3600                         if (is_last) {
3601                                 p_id = &iot->u.cmul_v2->bCSourceId;
3602                                 n_id = 1;
3603                                 goto top;
3604                         }
3605                         uaudio20_mixer_find_clocks_sub(root,
3606                             &iot->u.cmul_v2->bCSourceId,
3607                             1, info);
3608                         break;
3609
3610                 case UDESCSUB_AC_CLOCK_SRC:
3611
3612                         id = iot->u.csrc_v2->bClockId;
3613
3614                         switch (info->is_input) {
3615                         case 0:
3616                                 info->bit_output[id / 8] |= (1 << (id % 8));
3617                                 break;
3618                         case 1:
3619                                 info->bit_input[id / 8] |= (1 << (id % 8));
3620                                 break;
3621                         default:
3622                                 break;
3623                         }
3624                         break;
3625
3626                 default:
3627                         break;
3628                 }
3629         }
3630 }
3631
3632 static void
3633 uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *root, uint8_t id,
3634     uint8_t n_id, struct uaudio_search_result *info)
3635 {
3636         struct uaudio_terminal_node *iot = (root + id);
3637         uint8_t j;
3638
3639         j = n_id;
3640         do {
3641                 if ((j != id) && ((root + j)->u.desc) &&
3642                     ((root + j)->u.desc->bDescriptorSubtype == UDESCSUB_AC_OUTPUT)) {
3643
3644                         /*
3645                          * "j" (output) <--- virtual wire <--- "id" (input)
3646                          *
3647                          * if "j" has "id" on the input, then "id" have "j" on
3648                          * the output, because they are connected:
3649                          */
3650                         if ((root + j)->usr.bit_input[id / 8] & (1 << (id % 8))) {
3651                                 iot->usr.bit_output[j / 8] |= (1 << (j % 8));
3652                         }
3653                 }
3654         } while (j--);
3655 }
3656
3657 static void
3658 uaudio_mixer_fill_info(struct uaudio_softc *sc,
3659     struct usb_device *udev, void *desc)
3660 {
3661         const struct usb_audio_control_descriptor *acdp;
3662         struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev);
3663         const struct usb_descriptor *dp;
3664         const struct usb_audio_unit *au;
3665         struct uaudio_terminal_node *iot = NULL;
3666         uint16_t wTotalLen;
3667         uint8_t ID_max = 0;             /* inclusive */
3668         uint8_t i;
3669
3670         desc = usb_desc_foreach(cd, desc);
3671
3672         if (desc == NULL) {
3673                 DPRINTF("no Audio Control header\n");
3674                 goto done;
3675         }
3676         acdp = desc;
3677
3678         if ((acdp->bLength < sizeof(*acdp)) ||
3679             (acdp->bDescriptorType != UDESC_CS_INTERFACE) ||
3680             (acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)) {
3681                 DPRINTF("invalid Audio Control header\n");
3682                 goto done;
3683         }
3684         /* "wTotalLen" is allowed to be corrupt */
3685         wTotalLen = UGETW(acdp->wTotalLength) - acdp->bLength;
3686
3687         /* get USB audio revision */
3688         sc->sc_audio_rev = UGETW(acdp->bcdADC);
3689
3690         DPRINTFN(3, "found AC header, vers=%03x, len=%d\n",
3691             sc->sc_audio_rev, wTotalLen);
3692
3693         iot = malloc(sizeof(struct uaudio_terminal_node) * 256, M_TEMP,
3694             M_WAITOK | M_ZERO);
3695
3696         if (iot == NULL) {
3697                 DPRINTF("no memory!\n");
3698                 goto done;
3699         }
3700         while ((desc = usb_desc_foreach(cd, desc))) {
3701
3702                 dp = desc;
3703
3704                 if (dp->bLength > wTotalLen) {
3705                         break;
3706                 } else {
3707                         wTotalLen -= dp->bLength;
3708                 }
3709
3710                 if (sc->sc_audio_rev >= UAUDIO_VERSION_30)
3711                         au = NULL;
3712                 else if (sc->sc_audio_rev >= UAUDIO_VERSION_20)
3713                         au = uaudio20_mixer_verify_desc(dp, 0);
3714                 else
3715                         au = uaudio_mixer_verify_desc(dp, 0);
3716
3717                 if (au) {
3718                         iot[au->bUnitId].u.desc = (const void *)au;
3719                         if (au->bUnitId > ID_max)
3720                                 ID_max = au->bUnitId;
3721                 }
3722         }
3723
3724         DPRINTF("Maximum ID=%d\n", ID_max);
3725
3726         /*
3727          * determine sourcing inputs for
3728          * all nodes in the tree:
3729          */
3730         i = ID_max;
3731         do {
3732                 if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
3733                         /* FALLTHROUGH */
3734                 } else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
3735                         uaudio20_mixer_find_inputs_sub(iot,
3736                             &i, 1, &((iot + i)->usr));
3737
3738                         sc->sc_mixer_clocks.is_input = 255;
3739                         sc->sc_mixer_clocks.recurse_level = 0;
3740
3741                         uaudio20_mixer_find_clocks_sub(iot,
3742                             &i, 1, &sc->sc_mixer_clocks);
3743                 } else {
3744                         uaudio_mixer_find_inputs_sub(iot,
3745                             &i, 1, &((iot + i)->usr));
3746                 }
3747         } while (i--);
3748
3749         /*
3750          * determine outputs for
3751          * all nodes in the tree:
3752          */
3753         i = ID_max;
3754         do {
3755                 uaudio_mixer_find_outputs_sub(iot,
3756                     i, ID_max, &((iot + i)->usr));
3757         } while (i--);
3758
3759         /* set "id_max" and "root" */
3760
3761         i = ID_max;
3762         do {
3763                 (iot + i)->usr.id_max = ID_max;
3764                 (iot + i)->root = iot;
3765         } while (i--);
3766
3767         /*
3768          * Scan the config to create a linked list of "mixer" nodes:
3769          */
3770
3771         i = ID_max;
3772         do {
3773                 dp = iot[i].u.desc;
3774
3775                 if (dp == NULL)
3776                         continue;
3777
3778                 DPRINTFN(11, "id=%d subtype=%d\n",
3779                     i, dp->bDescriptorSubtype);
3780
3781                 if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
3782                         continue;
3783                 } else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
3784
3785                         switch (dp->bDescriptorSubtype) {
3786                         case UDESCSUB_AC_HEADER:
3787                                 DPRINTF("unexpected AC header\n");
3788                                 break;
3789
3790                         case UDESCSUB_AC_INPUT:
3791                         case UDESCSUB_AC_OUTPUT:
3792                         case UDESCSUB_AC_PROCESSING_V2:
3793                         case UDESCSUB_AC_EXTENSION_V2:
3794                         case UDESCSUB_AC_EFFECT:
3795                         case UDESCSUB_AC_CLOCK_SRC:
3796                         case UDESCSUB_AC_CLOCK_SEL:
3797                         case UDESCSUB_AC_CLOCK_MUL:
3798                         case UDESCSUB_AC_SAMPLE_RT:
3799                                 break;
3800
3801                         case UDESCSUB_AC_MIXER:
3802                                 uaudio20_mixer_add_mixer(sc, iot, i);
3803                                 break;
3804
3805                         case UDESCSUB_AC_SELECTOR:
3806                                 uaudio20_mixer_add_selector(sc, iot, i);
3807                                 break;
3808
3809                         case UDESCSUB_AC_FEATURE:
3810                                 uaudio20_mixer_add_feature(sc, iot, i);
3811                                 break;
3812
3813                         default:
3814                                 DPRINTF("bad AC desc subtype=0x%02x\n",
3815                                     dp->bDescriptorSubtype);
3816                                 break;
3817                         }
3818                         continue;
3819                 }
3820
3821                 switch (dp->bDescriptorSubtype) {
3822                 case UDESCSUB_AC_HEADER:
3823                         DPRINTF("unexpected AC header\n");
3824                         break;
3825
3826                 case UDESCSUB_AC_INPUT:
3827                 case UDESCSUB_AC_OUTPUT:
3828                         break;
3829
3830                 case UDESCSUB_AC_MIXER:
3831                         uaudio_mixer_add_mixer(sc, iot, i);
3832                         break;
3833
3834                 case UDESCSUB_AC_SELECTOR:
3835                         uaudio_mixer_add_selector(sc, iot, i);
3836                         break;
3837
3838                 case UDESCSUB_AC_FEATURE:
3839                         uaudio_mixer_add_feature(sc, iot, i);
3840                         break;
3841
3842                 case UDESCSUB_AC_PROCESSING:
3843                         uaudio_mixer_add_processing(sc, iot, i);
3844                         break;
3845
3846                 case UDESCSUB_AC_EXTENSION:
3847                         uaudio_mixer_add_extension(sc, iot, i);
3848                         break;
3849
3850                 default:
3851                         DPRINTF("bad AC desc subtype=0x%02x\n",
3852                             dp->bDescriptorSubtype);
3853                         break;
3854                 }
3855
3856         } while (i--);
3857
3858 done:
3859         free(iot, M_TEMP);
3860 }
3861
3862 static int
3863 uaudio_mixer_get(struct usb_device *udev, uint16_t audio_rev,
3864     uint8_t what, struct uaudio_mixer_node *mc)
3865 {
3866         struct usb_device_request req;
3867         int val;
3868         uint8_t data[2 + (2 * 3)];
3869         usb_error_t err;
3870
3871         if (mc->wValue[0] == -1)
3872                 return (0);
3873
3874         if (audio_rev >= UAUDIO_VERSION_30)
3875                 return (0);
3876         else if (audio_rev >= UAUDIO_VERSION_20) {
3877                 if (what == GET_CUR) {
3878                         req.bRequest = UA20_CS_CUR;
3879                         USETW(req.wLength, 2);
3880                 } else {
3881                         req.bRequest = UA20_CS_RANGE;
3882                         USETW(req.wLength, 8);
3883                 }
3884         } else {
3885                 uint16_t len = MIX_SIZE(mc->type);
3886
3887                 req.bRequest = what;
3888                 USETW(req.wLength, len);
3889         }
3890
3891         req.bmRequestType = UT_READ_CLASS_INTERFACE;
3892         USETW(req.wValue, mc->wValue[0]);
3893         USETW(req.wIndex, mc->wIndex);
3894
3895         memset(data, 0, sizeof(data));
3896
3897         err = usbd_do_request(udev, NULL, &req, data);
3898         if (err) {
3899                 DPRINTF("err=%s\n", usbd_errstr(err));
3900                 return (0);
3901         }
3902
3903         if (audio_rev >= UAUDIO_VERSION_30) {
3904                 val = 0;
3905         } else if (audio_rev >= UAUDIO_VERSION_20) {
3906                 switch (what) {
3907                 case GET_CUR:
3908                         val = (data[0] | (data[1] << 8));
3909                         break;
3910                 case GET_MIN:
3911                         val = (data[2] | (data[3] << 8));
3912                         break;
3913                 case GET_MAX:
3914                         val = (data[4] | (data[5] << 8));
3915                         break;
3916                 case GET_RES:
3917                         val = (data[6] | (data[7] << 8));
3918                         break;
3919                 default:
3920                         val = 0;
3921                         break;
3922                 }
3923         } else {
3924                 val = (data[0] | (data[1] << 8));
3925         }
3926
3927         if (what == GET_CUR || what == GET_MIN || what == GET_MAX)
3928                 val = uaudio_mixer_signext(mc->type, val);
3929
3930         DPRINTFN(3, "val=%d\n", val);
3931
3932         return (val);
3933 }
3934
3935 static void
3936 uaudio_mixer_write_cfg_callback(struct usb_xfer *xfer, usb_error_t error)
3937 {
3938         struct usb_device_request req;
3939         struct uaudio_softc *sc = usbd_xfer_softc(xfer);
3940         struct uaudio_mixer_node *mc = sc->sc_mixer_curr;
3941         struct usb_page_cache *pc;
3942         uint16_t len;
3943         uint8_t repeat = 1;
3944         uint8_t update;
3945         uint8_t chan;
3946         uint8_t buf[2];
3947
3948         DPRINTF("\n");
3949
3950         switch (USB_GET_STATE(xfer)) {
3951         case USB_ST_TRANSFERRED:
3952 tr_transferred:
3953         case USB_ST_SETUP:
3954 tr_setup:
3955
3956                 if (mc == NULL) {
3957                         mc = sc->sc_mixer_root;
3958                         sc->sc_mixer_curr = mc;
3959                         sc->sc_mixer_chan = 0;
3960                         repeat = 0;
3961                 }
3962                 while (mc) {
3963                         while (sc->sc_mixer_chan < mc->nchan) {
3964
3965                                 chan = sc->sc_mixer_chan;
3966
3967                                 sc->sc_mixer_chan++;
3968
3969                                 update = ((mc->update[chan / 8] & (1 << (chan % 8))) &&
3970                                     (mc->wValue[chan] != -1));
3971
3972                                 mc->update[chan / 8] &= ~(1 << (chan % 8));
3973
3974                                 if (update) {
3975
3976                                         req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
3977                                         USETW(req.wValue, mc->wValue[chan]);
3978                                         USETW(req.wIndex, mc->wIndex);
3979
3980                                         if (sc->sc_audio_rev >= UAUDIO_VERSION_30) {
3981                                                 return;
3982                                         } else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) {
3983                                                 len = 2;
3984                                                 req.bRequest = UA20_CS_CUR;
3985                                                 USETW(req.wLength, len);
3986                                         } else {
3987                                                 len = MIX_SIZE(mc->type);
3988                                                 req.bRequest = SET_CUR;
3989                                                 USETW(req.wLength, len);
3990                                         }
3991
3992                                         buf[0] = (mc->wData[chan] & 0xFF);
3993                                         buf[1] = (mc->wData[chan] >> 8) & 0xFF;
3994
3995                                         pc = usbd_xfer_get_frame(xfer, 0);
3996                                         usbd_copy_in(pc, 0, &req, sizeof(req));
3997                                         pc = usbd_xfer_get_frame(xfer, 1);
3998                                         usbd_copy_in(pc, 0, buf, len);
3999
4000                                         usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
4001                                         usbd_xfer_set_frame_len(xfer, 1, len);
4002                                         usbd_xfer_set_frames(xfer, len ? 2 : 1);
4003                                         usbd_transfer_submit(xfer);
4004                                         return;
4005                                 }
4006                         }
4007
4008                         mc = mc->next;
4009                         sc->sc_mixer_curr = mc;
4010                         sc->sc_mixer_chan = 0;
4011                 }
4012
4013                 if (repeat) {
4014                         goto tr_setup;
4015                 }
4016                 break;
4017
4018         default:                        /* Error */
4019                 DPRINTF("error=%s\n", usbd_errstr(error));
4020                 if (error == USB_ERR_CANCELLED) {
4021                         /* do nothing - we are detaching */
4022                         break;
4023                 }
4024                 goto tr_transferred;
4025         }
4026 }
4027
4028 static usb_error_t
4029 uaudio_set_speed(struct usb_device *udev, uint8_t endpt, uint32_t speed)
4030 {
4031         struct usb_device_request req;
4032         uint8_t data[3];
4033
4034         DPRINTFN(6, "endpt=%d speed=%u\n", endpt, speed);
4035
4036         req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
4037         req.bRequest = SET_CUR;
4038         USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
4039         USETW(req.wIndex, endpt);
4040         USETW(req.wLength, 3);
4041         data[0] = speed;
4042         data[1] = speed >> 8;
4043         data[2] = speed >> 16;
4044
4045         return (usbd_do_request(udev, NULL, &req, data));
4046 }
4047
4048 static usb_error_t
4049 uaudio20_set_speed(struct usb_device *udev, uint8_t iface_no,
4050     uint8_t clockid, uint32_t speed)
4051 {
4052         struct usb_device_request req;
4053         uint8_t data[4];
4054
4055         DPRINTFN(6, "ifaceno=%d clockid=%d speed=%u\n",
4056             iface_no, clockid, speed);
4057
4058         req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
4059         req.bRequest = UA20_CS_CUR;
4060         USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0);
4061         USETW2(req.wIndex, clockid, iface_no);
4062         USETW(req.wLength, 4);
4063         data[0] = speed;
4064         data[1] = speed >> 8;
4065         data[2] = speed >> 16;
4066         data[3] = speed >> 24;
4067
4068         return (usbd_do_request(udev, NULL, &req, data));
4069 }
4070
4071 static int
4072 uaudio_mixer_signext(uint8_t type, int val)
4073 {
4074         if (!MIX_UNSIGNED(type)) {
4075                 if (MIX_SIZE(type) == 2) {
4076                         val = (int16_t)val;
4077                 } else {
4078                         val = (int8_t)val;
4079                 }
4080         }
4081         return (val);
4082 }
4083
4084 static int
4085 uaudio_mixer_bsd2value(struct uaudio_mixer_node *mc, int32_t val)
4086 {
4087         if (mc->type == MIX_ON_OFF) {
4088                 val = (val != 0);
4089         } else if (mc->type == MIX_SELECTOR) {
4090                 if ((val < mc->minval) ||
4091                     (val > mc->maxval)) {
4092                         val = mc->minval;
4093                 }
4094         } else {
4095
4096                 /* compute actual volume */
4097                 val = (val * mc->mul) / 255;
4098
4099                 /* add lower offset */
4100                 val = val + mc->minval;
4101
4102                 /* make sure we don't write a value out of range */
4103                 if (val > mc->maxval)
4104                         val = mc->maxval;
4105                 else if (val < mc->minval)
4106                         val = mc->minval;
4107         }
4108
4109         DPRINTFN(6, "type=0x%03x val=%d min=%d max=%d val=%d\n",
4110             mc->type, val, mc->minval, mc->maxval, val);
4111         return (val);
4112 }
4113
4114 static void
4115 uaudio_mixer_ctl_set(struct uaudio_softc *sc, struct uaudio_mixer_node *mc,
4116     uint8_t chan, int32_t val)
4117 {
4118         val = uaudio_mixer_bsd2value(mc, val);
4119
4120         mc->update[chan / 8] |= (1 << (chan % 8));
4121         mc->wData[chan] = val;
4122
4123         /* start the transfer, if not already started */
4124
4125         usbd_transfer_start(sc->sc_mixer_xfer[0]);
4126 }
4127
4128 static void
4129 uaudio_mixer_init(struct uaudio_softc *sc)
4130 {
4131         struct uaudio_mixer_node *mc;
4132         int32_t i;
4133
4134         for (mc = sc->sc_mixer_root; mc;
4135             mc = mc->next) {
4136
4137                 if (mc->ctl != SOUND_MIXER_NRDEVICES) {
4138                         /*
4139                          * Set device mask bits. See
4140                          * /usr/include/machine/soundcard.h
4141                          */
4142                         sc->sc_mix_info |= (1 << mc->ctl);
4143                 }
4144                 if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
4145                     (mc->type == MIX_SELECTOR)) {
4146
4147                         for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
4148                                 if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES) {
4149                                         continue;
4150                                 }
4151                                 sc->sc_recsrc_info |= 1 << mc->slctrtype[i - 1];
4152                         }
4153                 }
4154         }
4155 }
4156
4157 int
4158 uaudio_mixer_init_sub(struct uaudio_softc *sc, struct snd_mixer *m)
4159 {
4160         DPRINTF("\n");
4161
4162         if (usbd_transfer_setup(sc->sc_udev, &sc->sc_mixer_iface_index,
4163             sc->sc_mixer_xfer, uaudio_mixer_config, 1, sc,
4164             mixer_get_lock(m))) {
4165                 DPRINTFN(0, "could not allocate USB "
4166                     "transfer for audio mixer!\n");
4167                 return (ENOMEM);
4168         }
4169         if (!(sc->sc_mix_info & SOUND_MASK_VOLUME)) {
4170                 mix_setparentchild(m, SOUND_MIXER_VOLUME, SOUND_MASK_PCM);
4171                 mix_setrealdev(m, SOUND_MIXER_VOLUME, SOUND_MIXER_NONE);
4172         }
4173         mix_setdevs(m, sc->sc_mix_info);
4174         mix_setrecdevs(m, sc->sc_recsrc_info);
4175         return (0);
4176 }
4177
4178 int
4179 uaudio_mixer_uninit_sub(struct uaudio_softc *sc)
4180 {
4181         DPRINTF("\n");
4182
4183         usbd_transfer_unsetup(sc->sc_mixer_xfer, 1);
4184
4185         return (0);
4186 }
4187
4188 void
4189 uaudio_mixer_set(struct uaudio_softc *sc, unsigned type,
4190     unsigned left, unsigned right)
4191 {
4192         struct uaudio_mixer_node *mc;
4193
4194         for (mc = sc->sc_mixer_root; mc;
4195             mc = mc->next) {
4196
4197                 if (mc->ctl == type) {
4198                         if (mc->nchan == 2) {
4199                                 /* set Right */
4200                                 uaudio_mixer_ctl_set(sc, mc, 1, (int)(right * 255) / 100);
4201                         }
4202                         /* set Left or Mono */
4203                         uaudio_mixer_ctl_set(sc, mc, 0, (int)(left * 255) / 100);
4204                 }
4205         }
4206 }
4207
4208 uint32_t
4209 uaudio_mixer_setrecsrc(struct uaudio_softc *sc, uint32_t src)
4210 {
4211         struct uaudio_mixer_node *mc;
4212         uint32_t mask;
4213         uint32_t temp;
4214         int32_t i;
4215
4216         for (mc = sc->sc_mixer_root; mc;
4217             mc = mc->next) {
4218
4219                 if ((mc->ctl == SOUND_MIXER_NRDEVICES) &&
4220                     (mc->type == MIX_SELECTOR)) {
4221
4222                         /* compute selector mask */
4223
4224                         mask = 0;
4225                         for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
4226                                 mask |= (1 << mc->slctrtype[i - 1]);
4227                         }
4228
4229                         temp = mask & src;
4230                         if (temp == 0) {
4231                                 continue;
4232                         }
4233                         /* find the first set bit */
4234                         temp = (-temp) & temp;
4235
4236                         /* update "src" */
4237                         src &= ~mask;
4238                         src |= temp;
4239
4240                         for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) {
4241                                 if (temp != (1 << mc->slctrtype[i - 1])) {
4242                                         continue;
4243                                 }
4244                                 uaudio_mixer_ctl_set(sc, mc, 0, i);
4245                                 break;
4246                         }
4247                 }
4248         }
4249         return (src);
4250 }
4251
4252 /*========================================================================*
4253  * MIDI support routines
4254  *========================================================================*/
4255
4256 static void
4257 umidi_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
4258 {
4259         struct umidi_chan *chan = usbd_xfer_softc(xfer);
4260         struct umidi_sub_chan *sub;
4261         struct usb_page_cache *pc;
4262         uint8_t buf[4];
4263         uint8_t cmd_len;
4264         uint8_t cn;
4265         uint16_t pos;
4266         int actlen;
4267
4268         usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
4269
4270         switch (USB_GET_STATE(xfer)) {
4271         case USB_ST_TRANSFERRED:
4272
4273                 DPRINTF("actlen=%d bytes\n", actlen);
4274
4275                 pos = 0;
4276                 pc = usbd_xfer_get_frame(xfer, 0);
4277
4278                 while (actlen >= 4) {
4279
4280                         /* copy out the MIDI data */
4281                         usbd_copy_out(pc, pos, buf, 4);
4282                         /* command length */
4283                         cmd_len = umidi_cmd_to_len[buf[0] & 0xF];
4284                         /* cable number */
4285                         cn = buf[0] >> 4;
4286                         /*
4287                          * Lookup sub-channel. The index is range
4288                          * checked below.
4289                          */
4290                         sub = &chan->sub[cn];
4291
4292                         if ((cmd_len != 0) &&
4293                             (cn < chan->max_cable) &&
4294                             (sub->read_open != 0)) {
4295
4296                                 /* Send data to the application */
4297                                 usb_fifo_put_data_linear(
4298                                     sub->fifo.fp[USB_FIFO_RX],
4299                                     buf + 1, cmd_len, 1);
4300                         }
4301                         actlen -= 4;
4302                         pos += 4;
4303                 }
4304
4305         case USB_ST_SETUP:
4306                 DPRINTF("start\n");
4307 tr_setup:
4308                 usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
4309                 usbd_transfer_submit(xfer);
4310                 break;
4311
4312         default:
4313                 DPRINTF("error=%s\n", usbd_errstr(error));
4314
4315                 if (error != USB_ERR_CANCELLED) {
4316                         /* try to clear stall first */
4317                         usbd_xfer_set_stall(xfer);
4318                         goto tr_setup;
4319                 }
4320                 break;
4321         }
4322 }
4323
4324 /*
4325  * The following statemachine, that converts MIDI commands to
4326  * USB MIDI packets, derives from Linux's usbmidi.c, which
4327  * was written by "Clemens Ladisch":
4328  *
4329  * Returns:
4330  *    0: No command
4331  * Else: Command is complete
4332  */
4333 static uint8_t
4334 umidi_convert_to_usb(struct umidi_sub_chan *sub, uint8_t cn, uint8_t b)
4335 {
4336         uint8_t p0 = (cn << 4);
4337
4338         if (b >= 0xf8) {
4339                 sub->temp_0[0] = p0 | 0x0f;
4340                 sub->temp_0[1] = b;
4341                 sub->temp_0[2] = 0;
4342                 sub->temp_0[3] = 0;
4343                 sub->temp_cmd = sub->temp_0;
4344                 return (1);
4345
4346         } else if (b >= 0xf0) {
4347                 switch (b) {
4348                 case 0xf0:              /* system exclusive begin */
4349                         sub->temp_1[1] = b;
4350                         sub->state = UMIDI_ST_SYSEX_1;
4351                         break;
4352                 case 0xf1:              /* MIDI time code */
4353                 case 0xf3:              /* song select */
4354                         sub->temp_1[1] = b;
4355                         sub->state = UMIDI_ST_1PARAM;
4356                         break;
4357                 case 0xf2:              /* song position pointer */
4358                         sub->temp_1[1] = b;
4359                         sub->state = UMIDI_ST_2PARAM_1;
4360                         break;
4361                 case 0xf4:              /* unknown */
4362                 case 0xf5:              /* unknown */
4363                         sub->state = UMIDI_ST_UNKNOWN;
4364                         break;
4365                 case 0xf6:              /* tune request */
4366                         sub->temp_1[0] = p0 | 0x05;
4367                         sub->temp_1[1] = 0xf6;
4368                         sub->temp_1[2] = 0;
4369                         sub->temp_1[3] = 0;
4370                         sub->temp_cmd = sub->temp_1;
4371                         sub->state = UMIDI_ST_UNKNOWN;
4372                         return (1);
4373
4374                 case 0xf7:              /* system exclusive end */
4375                         switch (sub->state) {
4376                         case UMIDI_ST_SYSEX_0:
4377                                 sub->temp_1[0] = p0 | 0x05;
4378                                 sub->temp_1[1] = 0xf7;
4379                                 sub->temp_1[2] = 0;
4380                                 sub->temp_1[3] = 0;
4381                                 sub->temp_cmd = sub->temp_1;
4382                                 sub->state = UMIDI_ST_UNKNOWN;
4383                                 return (1);
4384                         case UMIDI_ST_SYSEX_1:
4385                                 sub->temp_1[0] = p0 | 0x06;
4386                                 sub->temp_1[2] = 0xf7;
4387                                 sub->temp_1[3] = 0;
4388                                 sub->temp_cmd = sub->temp_1;
4389                                 sub->state = UMIDI_ST_UNKNOWN;
4390                                 return (1);
4391                         case UMIDI_ST_SYSEX_2:
4392                                 sub->temp_1[0] = p0 | 0x07;
4393                                 sub->temp_1[3] = 0xf7;
4394                                 sub->temp_cmd = sub->temp_1;
4395                                 sub->state = UMIDI_ST_UNKNOWN;
4396                                 return (1);
4397                         }
4398                         sub->state = UMIDI_ST_UNKNOWN;
4399                         break;
4400                 }
4401         } else if (b >= 0x80) {
4402                 sub->temp_1[1] = b;
4403                 if ((b >= 0xc0) && (b <= 0xdf)) {
4404                         sub->state = UMIDI_ST_1PARAM;
4405                 } else {
4406                         sub->state = UMIDI_ST_2PARAM_1;
4407                 }
4408         } else {                        /* b < 0x80 */
4409                 switch (sub->state) {
4410                 case UMIDI_ST_1PARAM:
4411                         if (sub->temp_1[1] < 0xf0) {
4412                                 p0 |= sub->temp_1[1] >> 4;
4413                         } else {
4414                                 p0 |= 0x02;
4415                                 sub->state = UMIDI_ST_UNKNOWN;
4416                         }
4417                         sub->temp_1[0] = p0;
4418                         sub->temp_1[2] = b;
4419                         sub->temp_1[3] = 0;
4420                         sub->temp_cmd = sub->temp_1;
4421                         return (1);
4422                 case UMIDI_ST_2PARAM_1:
4423                         sub->temp_1[2] = b;
4424                         sub->state = UMIDI_ST_2PARAM_2;
4425                         break;
4426                 case UMIDI_ST_2PARAM_2:
4427                         if (sub->temp_1[1] < 0xf0) {
4428                                 p0 |= sub->temp_1[1] >> 4;
4429                                 sub->state = UMIDI_ST_2PARAM_1;
4430                         } else {
4431                                 p0 |= 0x03;
4432                                 sub->state = UMIDI_ST_UNKNOWN;
4433                         }
4434                         sub->temp_1[0] = p0;
4435                         sub->temp_1[3] = b;
4436                         sub->temp_cmd = sub->temp_1;
4437                         return (1);
4438                 case UMIDI_ST_SYSEX_0:
4439                         sub->temp_1[1] = b;
4440                         sub->state = UMIDI_ST_SYSEX_1;
4441                         break;
4442                 case UMIDI_ST_SYSEX_1:
4443                         sub->temp_1[2] = b;
4444                         sub->state = UMIDI_ST_SYSEX_2;
4445                         break;
4446                 case UMIDI_ST_SYSEX_2:
4447                         sub->temp_1[0] = p0 | 0x04;
4448                         sub->temp_1[3] = b;
4449                         sub->temp_cmd = sub->temp_1;
4450                         sub->state = UMIDI_ST_SYSEX_0;
4451                         return (1);
4452                 default:
4453                         break;
4454                 }
4455         }
4456         return (0);
4457 }
4458
4459 static void
4460 umidi_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
4461 {
4462         struct umidi_chan *chan = usbd_xfer_softc(xfer);
4463         struct umidi_sub_chan *sub;
4464         struct usb_page_cache *pc;
4465         uint32_t actlen;
4466         uint16_t nframes;
4467         uint8_t buf;
4468         uint8_t start_cable;
4469         uint8_t tr_any;
4470         int len;
4471
4472         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
4473
4474         /*
4475          * NOTE: Some MIDI devices only accept 4 bytes of data per
4476          * short terminated USB transfer.
4477          */
4478         switch (USB_GET_STATE(xfer)) {
4479         case USB_ST_TRANSFERRED:
4480                 DPRINTF("actlen=%d bytes\n", len);
4481
4482         case USB_ST_SETUP:
4483 tr_setup:
4484                 DPRINTF("start\n");
4485
4486                 nframes = 0;    /* reset */
4487                 start_cable = chan->curr_cable;
4488                 tr_any = 0;
4489                 pc = usbd_xfer_get_frame(xfer, 0);
4490
4491                 while (1) {
4492
4493                         /* round robin de-queueing */
4494
4495                         sub = &chan->sub[chan->curr_cable];
4496
4497                         if (sub->write_open) {
4498                                 usb_fifo_get_data_linear(sub->fifo.fp[USB_FIFO_TX],
4499                                     &buf, 1, &actlen, 0);
4500                         } else {
4501                                 actlen = 0;
4502                         }
4503
4504                         if (actlen) {
4505
4506                                 tr_any = 1;
4507
4508                                 DPRINTF("byte=0x%02x from FIFO %u\n", buf,
4509                                     (unsigned int)chan->curr_cable);
4510
4511                                 if (umidi_convert_to_usb(sub, chan->curr_cable, buf)) {
4512
4513                                         DPRINTF("sub=0x%02x 0x%02x 0x%02x 0x%02x\n",
4514                                             sub->temp_cmd[0], sub->temp_cmd[1],
4515                                             sub->temp_cmd[2], sub->temp_cmd[3]);
4516
4517                                         usbd_copy_in(pc, nframes * 4, sub->temp_cmd, 4);
4518
4519                                         nframes++;
4520
4521                                         if ((nframes >= UMIDI_TX_FRAMES) || (chan->single_command != 0))
4522                                                 break;
4523                                 } else {
4524                                         continue;
4525                                 }
4526                         }
4527
4528                         chan->curr_cable++;
4529                         if (chan->curr_cable >= chan->max_cable)
4530                                 chan->curr_cable = 0;
4531
4532                         if (chan->curr_cable == start_cable) {
4533                                 if (tr_any == 0)
4534                                         break;
4535                                 tr_any = 0;
4536                         }
4537                 }
4538
4539                 if (nframes != 0) {
4540                         DPRINTF("Transferring %d frames\n", (int)nframes);
4541                         usbd_xfer_set_frame_len(xfer, 0, 4 * nframes);
4542                         usbd_transfer_submit(xfer);
4543                 }
4544                 break;
4545
4546         default:                        /* Error */
4547
4548                 DPRINTF("error=%s\n", usbd_errstr(error));
4549
4550                 if (error != USB_ERR_CANCELLED) {
4551                         /* try to clear stall first */
4552                         usbd_xfer_set_stall(xfer);
4553                         goto tr_setup;
4554                 }
4555                 break;
4556         }
4557 }
4558
4559 static struct umidi_sub_chan *
4560 umidi_sub_by_fifo(struct usb_fifo *fifo)
4561 {
4562         struct umidi_chan *chan = usb_fifo_softc(fifo);
4563         struct umidi_sub_chan *sub;
4564         uint32_t n;
4565
4566         for (n = 0; n < UMIDI_CABLES_MAX; n++) {
4567                 sub = &chan->sub[n];
4568                 if ((sub->fifo.fp[USB_FIFO_RX] == fifo) ||
4569                     (sub->fifo.fp[USB_FIFO_TX] == fifo)) {
4570                         return (sub);
4571                 }
4572         }
4573
4574         panic("%s:%d cannot find usb_fifo!\n",
4575             __FILE__, __LINE__);
4576
4577         return (NULL);
4578 }
4579
4580 static void
4581 umidi_start_read(struct usb_fifo *fifo)
4582 {
4583         struct umidi_chan *chan = usb_fifo_softc(fifo);
4584
4585         usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
4586 }
4587
4588 static void
4589 umidi_stop_read(struct usb_fifo *fifo)
4590 {
4591         struct umidi_chan *chan = usb_fifo_softc(fifo);
4592         struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
4593
4594         DPRINTF("\n");
4595
4596         sub->read_open = 0;
4597
4598         if (--(chan->read_open_refcount) == 0) {
4599                 /*
4600                  * XXX don't stop the read transfer here, hence that causes
4601                  * problems with some MIDI adapters
4602                  */
4603                 DPRINTF("(stopping read transfer)\n");
4604         }
4605 }
4606
4607 static void
4608 umidi_start_write(struct usb_fifo *fifo)
4609 {
4610         struct umidi_chan *chan = usb_fifo_softc(fifo);
4611
4612         usbd_transfer_start(chan->xfer[UMIDI_TX_TRANSFER]);
4613 }
4614
4615 static void
4616 umidi_stop_write(struct usb_fifo *fifo)
4617 {
4618         struct umidi_chan *chan = usb_fifo_softc(fifo);
4619         struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
4620
4621         DPRINTF("\n");
4622
4623         sub->write_open = 0;
4624
4625         if (--(chan->write_open_refcount) == 0) {
4626                 DPRINTF("(stopping write transfer)\n");
4627                 usbd_transfer_stop(chan->xfer[UMIDI_TX_TRANSFER]);
4628         }
4629 }
4630
4631 static int
4632 umidi_open(struct usb_fifo *fifo, int fflags)
4633 {
4634         struct umidi_chan *chan = usb_fifo_softc(fifo);
4635         struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo);
4636
4637         if (fflags & FREAD) {
4638                 if (usb_fifo_alloc_buffer(fifo, 4, (1024 / 4))) {
4639                         return (ENOMEM);
4640                 }
4641                 mtx_lock(&chan->mtx);
4642                 chan->read_open_refcount++;
4643                 sub->read_open = 1;
4644                 mtx_unlock(&chan->mtx);
4645         }
4646         if (fflags & FWRITE) {
4647                 if (usb_fifo_alloc_buffer(fifo, 32, (1024 / 32))) {
4648                         return (ENOMEM);
4649                 }
4650                 /* clear stall first */
4651                 mtx_lock(&chan->mtx);
4652                 usbd_xfer_set_stall(chan->xfer[UMIDI_TX_TRANSFER]);
4653                 chan->write_open_refcount++;
4654                 sub->write_open = 1;
4655
4656                 /* reset */
4657                 sub->state = UMIDI_ST_UNKNOWN;
4658                 mtx_unlock(&chan->mtx);
4659         }
4660         return (0);                     /* success */
4661 }
4662
4663 static void
4664 umidi_close(struct usb_fifo *fifo, int fflags)
4665 {
4666         if (fflags & FREAD) {
4667                 usb_fifo_free_buffer(fifo);
4668         }
4669         if (fflags & FWRITE) {
4670                 usb_fifo_free_buffer(fifo);
4671         }
4672 }
4673
4674
4675 static int
4676 umidi_ioctl(struct usb_fifo *fifo, u_long cmd, void *data,
4677     int fflags)
4678 {
4679         return (ENODEV);
4680 }
4681
4682 static void
4683 umidi_init(device_t dev)
4684 {
4685         struct uaudio_softc *sc = device_get_softc(dev);
4686         struct umidi_chan *chan = &sc->sc_midi_chan;
4687
4688         mtx_init(&chan->mtx, "umidi lock", NULL, MTX_DEF | MTX_RECURSE);
4689 }
4690
4691 static struct usb_fifo_methods umidi_fifo_methods = {
4692         .f_start_read = &umidi_start_read,
4693         .f_start_write = &umidi_start_write,
4694         .f_stop_read = &umidi_stop_read,
4695         .f_stop_write = &umidi_stop_write,
4696         .f_open = &umidi_open,
4697         .f_close = &umidi_close,
4698         .f_ioctl = &umidi_ioctl,
4699         .basename[0] = "umidi",
4700 };
4701
4702 static int
4703 umidi_probe(device_t dev)
4704 {
4705         struct uaudio_softc *sc = device_get_softc(dev);
4706         struct usb_attach_arg *uaa = device_get_ivars(dev);
4707         struct umidi_chan *chan = &sc->sc_midi_chan;
4708         struct umidi_sub_chan *sub;
4709         int unit = device_get_unit(dev);
4710         int error;
4711         uint32_t n;
4712
4713         if (usb_test_quirk(uaa, UQ_SINGLE_CMD_MIDI))
4714                 chan->single_command = 1;
4715
4716         if (usbd_set_alt_interface_index(sc->sc_udev, chan->iface_index,
4717             chan->iface_alt_index)) {
4718                 DPRINTF("setting of alternate index failed!\n");
4719                 goto detach;
4720         }
4721         usbd_set_parent_iface(sc->sc_udev, chan->iface_index,
4722             sc->sc_mixer_iface_index);
4723
4724         error = usbd_transfer_setup(uaa->device, &chan->iface_index,
4725             chan->xfer, umidi_config, UMIDI_N_TRANSFER,
4726             chan, &chan->mtx);
4727         if (error) {
4728                 DPRINTF("error=%s\n", usbd_errstr(error));
4729                 goto detach;
4730         }
4731         if ((chan->max_cable > UMIDI_CABLES_MAX) ||
4732             (chan->max_cable == 0)) {
4733                 chan->max_cable = UMIDI_CABLES_MAX;
4734         }
4735
4736         for (n = 0; n < chan->max_cable; n++) {
4737
4738                 sub = &chan->sub[n];
4739
4740                 error = usb_fifo_attach(sc->sc_udev, chan, &chan->mtx,
4741                     &umidi_fifo_methods, &sub->fifo, unit, n,
4742                     chan->iface_index,
4743                     UID_ROOT, GID_OPERATOR, 0644);
4744                 if (error) {
4745                         goto detach;
4746                 }
4747         }
4748
4749         mtx_lock(&chan->mtx);
4750
4751         /* clear stall first */
4752         usbd_xfer_set_stall(chan->xfer[UMIDI_RX_TRANSFER]);
4753
4754         /*
4755          * NOTE: At least one device will not work properly unless the
4756          * BULK IN pipe is open all the time. This might have to do
4757          * about that the internal queues of the device overflow if we
4758          * don't read them regularly.
4759          */
4760         usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]);
4761
4762         mtx_unlock(&chan->mtx);
4763
4764         return (0);                     /* success */
4765
4766 detach:
4767         return (ENXIO);                 /* failure */
4768 }
4769
4770 static int
4771 umidi_detach(device_t dev)
4772 {
4773         struct uaudio_softc *sc = device_get_softc(dev);
4774         struct umidi_chan *chan = &sc->sc_midi_chan;
4775         uint32_t n;
4776
4777         for (n = 0; n < UMIDI_CABLES_MAX; n++) {
4778                 usb_fifo_detach(&chan->sub[n].fifo);
4779         }
4780
4781         mtx_lock(&chan->mtx);
4782
4783         usbd_transfer_stop(chan->xfer[UMIDI_RX_TRANSFER]);
4784
4785         mtx_unlock(&chan->mtx);
4786
4787         usbd_transfer_unsetup(chan->xfer, UMIDI_N_TRANSFER);
4788
4789         mtx_destroy(&chan->mtx);
4790
4791         return (0);
4792 }
4793
4794 DRIVER_MODULE(uaudio, uhub, uaudio_driver, uaudio_devclass, NULL, 0);
4795 MODULE_DEPEND(uaudio, usb, 1, 1, 1);
4796 MODULE_DEPEND(uaudio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
4797 MODULE_VERSION(uaudio, 1);