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