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