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