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