xref: /netbsd-src/sys/dev/usb/uaudio.c (revision 274254cdae52594c1aa480a736aef78313d15c9c)
1 /*	$NetBSD: uaudio.c,v 1.115 2009/03/09 15:59:33 uebayasi Exp $	*/
2 
3 /*
4  * Copyright (c) 1999 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Lennart Augustsson (lennart@augustsson.net) at
9  * Carlstedt Research & Technology.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
35  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
36  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
37  */
38 
39 #include <sys/cdefs.h>
40 __KERNEL_RCSID(0, "$NetBSD: uaudio.c,v 1.115 2009/03/09 15:59:33 uebayasi Exp $");
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/malloc.h>
46 #include <sys/device.h>
47 #include <sys/ioctl.h>
48 #include <sys/file.h>
49 #include <sys/reboot.h>		/* for bootverbose */
50 #include <sys/select.h>
51 #include <sys/proc.h>
52 #include <sys/vnode.h>
53 #include <sys/poll.h>
54 #include <sys/module.h>
55 
56 #include <sys/audioio.h>
57 #include <dev/audio_if.h>
58 #include <dev/audiovar.h>
59 #include <dev/mulaw.h>
60 #include <dev/auconv.h>
61 
62 #include <dev/usb/usb.h>
63 #include <dev/usb/usbdi.h>
64 #include <dev/usb/usbdi_util.h>
65 #include <dev/usb/usb_quirks.h>
66 
67 #include <dev/usb/uaudioreg.h>
68 
69 /* #define UAUDIO_DEBUG */
70 /* #define UAUDIO_MULTIPLE_ENDPOINTS */
71 #ifdef UAUDIO_DEBUG
72 #define DPRINTF(x)	do { if (uaudiodebug) logprintf x; } while (0)
73 #define DPRINTFN(n,x)	do { if (uaudiodebug>(n)) logprintf x; } while (0)
74 int	uaudiodebug = 0;
75 #else
76 #define DPRINTF(x)
77 #define DPRINTFN(n,x)
78 #endif
79 
80 #define UAUDIO_NCHANBUFS 6	/* number of outstanding request */
81 #define UAUDIO_NFRAMES   10	/* ms of sound in each request */
82 
83 
84 #define MIX_MAX_CHAN 8
85 struct mixerctl {
86 	uint16_t	wValue[MIX_MAX_CHAN]; /* using nchan */
87 	uint16_t	wIndex;
88 	uint8_t		nchan;
89 	uint8_t		type;
90 #define MIX_ON_OFF	1
91 #define MIX_SIGNED_16	2
92 #define MIX_UNSIGNED_16	3
93 #define MIX_SIGNED_8	4
94 #define MIX_SELECTOR	5
95 #define MIX_SIZE(n) ((n) == MIX_SIGNED_16 || (n) == MIX_UNSIGNED_16 ? 2 : 1)
96 #define MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
97 	int		minval, maxval;
98 	u_int		delta;
99 	u_int		mul;
100 	uint8_t		class;
101 	char		ctlname[MAX_AUDIO_DEV_LEN];
102 	const char	*ctlunit;
103 };
104 #define MAKE(h,l) (((h) << 8) | (l))
105 
106 struct as_info {
107 	uint8_t		alt;
108 	uint8_t		encoding;
109 	uint8_t		attributes; /* Copy of bmAttributes of
110 				     * usb_audio_streaming_endpoint_descriptor
111 				     */
112 	usbd_interface_handle	ifaceh;
113 	const usb_interface_descriptor_t *idesc;
114 	const usb_endpoint_descriptor_audio_t *edesc;
115 	const usb_endpoint_descriptor_audio_t *edesc1;
116 	const struct usb_audio_streaming_type1_descriptor *asf1desc;
117 	struct audio_format *aformat;
118 	int		sc_busy;	/* currently used */
119 };
120 
121 struct chan {
122 	void	(*intr)(void *);	/* DMA completion intr handler */
123 	void	*arg;		/* arg for intr() */
124 	usbd_pipe_handle pipe;
125 	usbd_pipe_handle sync_pipe;
126 
127 	u_int	sample_size;
128 	u_int	sample_rate;
129 	u_int	bytes_per_frame;
130 	u_int	fraction;	/* fraction/1000 is the extra samples/frame */
131 	u_int	residue;	/* accumulates the fractional samples */
132 
133 	u_char	*start;		/* upper layer buffer start */
134 	u_char	*end;		/* upper layer buffer end */
135 	u_char	*cur;		/* current position in upper layer buffer */
136 	int	blksize;	/* chunk size to report up */
137 	int	transferred;	/* transferred bytes not reported up */
138 
139 	int	altidx;		/* currently used altidx */
140 
141 	int	curchanbuf;
142 	struct chanbuf {
143 		struct chan	*chan;
144 		usbd_xfer_handle xfer;
145 		u_char		*buffer;
146 		uint16_t	sizes[UAUDIO_NFRAMES];
147 		uint16_t	offsets[UAUDIO_NFRAMES];
148 		uint16_t	size;
149 	} chanbufs[UAUDIO_NCHANBUFS];
150 
151 	struct uaudio_softc *sc; /* our softc */
152 };
153 
154 struct uaudio_softc {
155 	USBBASEDEVICE	sc_dev;		/* base device */
156 	usbd_device_handle sc_udev;	/* USB device */
157 	int		sc_ac_iface;	/* Audio Control interface */
158 	usbd_interface_handle	sc_ac_ifaceh;
159 	struct chan	sc_playchan;	/* play channel */
160 	struct chan	sc_recchan;	/* record channel */
161 	int		sc_nullalt;
162 	int		sc_audio_rev;
163 	struct as_info	*sc_alts;	/* alternate settings */
164 	int		sc_nalts;	/* # of alternate settings */
165 	int		sc_altflags;
166 #define HAS_8		0x01
167 #define HAS_16		0x02
168 #define HAS_8U		0x04
169 #define HAS_ALAW	0x08
170 #define HAS_MULAW	0x10
171 #define UA_NOFRAC	0x20		/* don't do sample rate adjustment */
172 #define HAS_24		0x40
173 	int		sc_mode;	/* play/record capability */
174 	struct mixerctl *sc_ctls;	/* mixer controls */
175 	int		sc_nctls;	/* # of mixer controls */
176 	device_ptr_t	sc_audiodev;
177 	struct audio_format *sc_formats;
178 	int		sc_nformats;
179 	struct audio_encoding_set *sc_encodings;
180 	u_int		sc_channel_config;
181 	char		sc_dying;
182 };
183 
184 struct terminal_list {
185 	int size;
186 	uint16_t terminals[1];
187 };
188 #define TERMINAL_LIST_SIZE(N)	(offsetof(struct terminal_list, terminals) \
189 				+ sizeof(uint16_t) * (N))
190 
191 struct io_terminal {
192 	union {
193 		const uaudio_cs_descriptor_t *desc;
194 		const struct usb_audio_input_terminal *it;
195 		const struct usb_audio_output_terminal *ot;
196 		const struct usb_audio_mixer_unit *mu;
197 		const struct usb_audio_selector_unit *su;
198 		const struct usb_audio_feature_unit *fu;
199 		const struct usb_audio_processing_unit *pu;
200 		const struct usb_audio_extension_unit *eu;
201 	} d;
202 	int inputs_size;
203 	struct terminal_list **inputs; /* list of source input terminals */
204 	struct terminal_list *output; /* list of destination output terminals */
205 	int direct;		/* directly connected to an output terminal */
206 };
207 
208 #define UAC_OUTPUT	0
209 #define UAC_INPUT	1
210 #define UAC_EQUAL	2
211 #define UAC_RECORD	3
212 #define UAC_NCLASSES	4
213 #ifdef UAUDIO_DEBUG
214 Static const char *uac_names[] = {
215 	AudioCoutputs, AudioCinputs, AudioCequalization, AudioCrecord,
216 };
217 #endif
218 
219 Static usbd_status uaudio_identify_ac
220 	(struct uaudio_softc *, const usb_config_descriptor_t *);
221 Static usbd_status uaudio_identify_as
222 	(struct uaudio_softc *, const usb_config_descriptor_t *);
223 Static usbd_status uaudio_process_as
224 	(struct uaudio_softc *, const char *, int *, int,
225 	 const usb_interface_descriptor_t *);
226 
227 Static void	uaudio_add_alt(struct uaudio_softc *, const struct as_info *);
228 
229 Static const usb_interface_descriptor_t *uaudio_find_iface
230 	(const char *, int, int *, int);
231 
232 Static void	uaudio_mixer_add_ctl(struct uaudio_softc *, struct mixerctl *);
233 Static char	*uaudio_id_name
234 	(struct uaudio_softc *, const struct io_terminal *, int);
235 #ifdef UAUDIO_DEBUG
236 Static void	uaudio_dump_cluster(const struct usb_audio_cluster *);
237 #endif
238 Static struct usb_audio_cluster uaudio_get_cluster
239 	(int, const struct io_terminal *);
240 Static void	uaudio_add_input
241 	(struct uaudio_softc *, const struct io_terminal *, int);
242 Static void	uaudio_add_output
243 	(struct uaudio_softc *, const struct io_terminal *, int);
244 Static void	uaudio_add_mixer
245 	(struct uaudio_softc *, const struct io_terminal *, int);
246 Static void	uaudio_add_selector
247 	(struct uaudio_softc *, const struct io_terminal *, int);
248 #ifdef UAUDIO_DEBUG
249 Static const char *uaudio_get_terminal_name(int);
250 #endif
251 Static int	uaudio_determine_class
252 	(const struct io_terminal *, struct mixerctl *);
253 Static const char *uaudio_feature_name
254 	(const struct io_terminal *, struct mixerctl *);
255 Static void	uaudio_add_feature
256 	(struct uaudio_softc *, const struct io_terminal *, int);
257 Static void	uaudio_add_processing_updown
258 	(struct uaudio_softc *, const struct io_terminal *, int);
259 Static void	uaudio_add_processing
260 	(struct uaudio_softc *, const struct io_terminal *, int);
261 Static void	uaudio_add_extension
262 	(struct uaudio_softc *, const struct io_terminal *, int);
263 Static struct terminal_list *uaudio_merge_terminal_list
264 	(const struct io_terminal *);
265 Static struct terminal_list *uaudio_io_terminaltype
266 	(int, struct io_terminal *, int);
267 Static usbd_status uaudio_identify
268 	(struct uaudio_softc *, const usb_config_descriptor_t *);
269 
270 Static int	uaudio_signext(int, int);
271 Static int	uaudio_value2bsd(struct mixerctl *, int);
272 Static int	uaudio_bsd2value(struct mixerctl *, int);
273 Static int	uaudio_get(struct uaudio_softc *, int, int, int, int, int);
274 Static int	uaudio_ctl_get
275 	(struct uaudio_softc *, int, struct mixerctl *, int);
276 Static void	uaudio_set
277 	(struct uaudio_softc *, int, int, int, int, int, int);
278 Static void	uaudio_ctl_set
279 	(struct uaudio_softc *, int, struct mixerctl *, int, int);
280 
281 Static usbd_status uaudio_set_speed(struct uaudio_softc *, int, u_int);
282 
283 Static usbd_status uaudio_chan_open(struct uaudio_softc *, struct chan *);
284 Static void	uaudio_chan_close(struct uaudio_softc *, struct chan *);
285 Static usbd_status uaudio_chan_alloc_buffers
286 	(struct uaudio_softc *, struct chan *);
287 Static void	uaudio_chan_free_buffers(struct uaudio_softc *, struct chan *);
288 Static void	uaudio_chan_init
289 	(struct chan *, int, const struct audio_params *, int);
290 Static void	uaudio_chan_set_param(struct chan *, u_char *, u_char *, int);
291 Static void	uaudio_chan_ptransfer(struct chan *);
292 Static void	uaudio_chan_pintr
293 	(usbd_xfer_handle, usbd_private_handle, usbd_status);
294 
295 Static void	uaudio_chan_rtransfer(struct chan *);
296 Static void	uaudio_chan_rintr
297 	(usbd_xfer_handle, usbd_private_handle, usbd_status);
298 
299 Static int	uaudio_open(void *, int);
300 Static void	uaudio_close(void *);
301 Static int	uaudio_drain(void *);
302 Static int	uaudio_query_encoding(void *, struct audio_encoding *);
303 Static int	uaudio_set_params
304 	(void *, int, int, struct audio_params *, struct audio_params *,
305 	 stream_filter_list_t *, stream_filter_list_t *);
306 Static int	uaudio_round_blocksize(void *, int, int, const audio_params_t *);
307 Static int	uaudio_trigger_output
308 	(void *, void *, void *, int, void (*)(void *), void *,
309 	 const audio_params_t *);
310 Static int	uaudio_trigger_input
311 	(void *, void *, void *, int, void (*)(void *), void *,
312 	 const audio_params_t *);
313 Static int	uaudio_halt_in_dma(void *);
314 Static int	uaudio_halt_out_dma(void *);
315 Static int	uaudio_getdev(void *, struct audio_device *);
316 Static int	uaudio_mixer_set_port(void *, mixer_ctrl_t *);
317 Static int	uaudio_mixer_get_port(void *, mixer_ctrl_t *);
318 Static int	uaudio_query_devinfo(void *, mixer_devinfo_t *);
319 Static int	uaudio_get_props(void *);
320 
321 Static const struct audio_hw_if uaudio_hw_if = {
322 	uaudio_open,
323 	uaudio_close,
324 	uaudio_drain,
325 	uaudio_query_encoding,
326 	uaudio_set_params,
327 	uaudio_round_blocksize,
328 	NULL,
329 	NULL,
330 	NULL,
331 	NULL,
332 	NULL,
333 	uaudio_halt_out_dma,
334 	uaudio_halt_in_dma,
335 	NULL,
336 	uaudio_getdev,
337 	NULL,
338 	uaudio_mixer_set_port,
339 	uaudio_mixer_get_port,
340 	uaudio_query_devinfo,
341 	NULL,
342 	NULL,
343 	NULL,
344 	NULL,
345 	uaudio_get_props,
346 	uaudio_trigger_output,
347 	uaudio_trigger_input,
348 	NULL,
349 	NULL,
350 };
351 
352 Static struct audio_device uaudio_device = {
353 	"USB audio",
354 	"",
355 	"uaudio"
356 };
357 
358 int uaudio_match(device_t, cfdata_t, void *);
359 void uaudio_attach(device_t, device_t, void *);
360 int uaudio_detach(device_t, int);
361 void uaudio_childdet(device_t, device_t);
362 int uaudio_activate(device_t, enum devact);
363 
364 extern struct cfdriver uaudio_cd;
365 
366 CFATTACH_DECL2_NEW(uaudio, sizeof(struct uaudio_softc),
367     uaudio_match, uaudio_attach, uaudio_detach, uaudio_activate, NULL,
368     uaudio_childdet);
369 
370 USB_MATCH(uaudio)
371 {
372 	USB_IFMATCH_START(uaudio, uaa);
373 
374 	/* Trigger on the control interface. */
375 	if (uaa->class != UICLASS_AUDIO ||
376 	    uaa->subclass != UISUBCLASS_AUDIOCONTROL ||
377 	    (usbd_get_quirks(uaa->device)->uq_flags & UQ_BAD_AUDIO))
378 		return UMATCH_NONE;
379 
380 	return UMATCH_IFACECLASS_IFACESUBCLASS;
381 }
382 
383 USB_ATTACH(uaudio)
384 {
385 	USB_IFATTACH_START(uaudio, sc, uaa);
386 	usb_interface_descriptor_t *id;
387 	usb_config_descriptor_t *cdesc;
388 	char *devinfop;
389 	usbd_status err;
390 	int i, j, found;
391 
392 	sc->sc_dev = self;
393 
394 	devinfop = usbd_devinfo_alloc(uaa->device, 0);
395 	aprint_normal(": %s\n", devinfop);
396 	aprint_naive("\n");
397 	usbd_devinfo_free(devinfop);
398 
399 	sc->sc_udev = uaa->device;
400 
401 	cdesc = usbd_get_config_descriptor(sc->sc_udev);
402 	if (cdesc == NULL) {
403 		aprint_error_dev(self,
404 		    "failed to get configuration descriptor\n");
405 		USB_ATTACH_ERROR_RETURN;
406 	}
407 
408 	err = uaudio_identify(sc, cdesc);
409 	if (err) {
410 		aprint_error_dev(self,
411 		    "audio descriptors make no sense, error=%d\n", err);
412 		USB_ATTACH_ERROR_RETURN;
413 	}
414 
415 	sc->sc_ac_ifaceh = uaa->iface;
416 	/* Pick up the AS interface. */
417 	for (i = 0; i < uaa->nifaces; i++) {
418 		if (uaa->ifaces[i] == NULL)
419 			continue;
420 		id = usbd_get_interface_descriptor(uaa->ifaces[i]);
421 		if (id == NULL)
422 			continue;
423 		found = 0;
424 		for (j = 0; j < sc->sc_nalts; j++) {
425 			if (id->bInterfaceNumber ==
426 			    sc->sc_alts[j].idesc->bInterfaceNumber) {
427 				sc->sc_alts[j].ifaceh = uaa->ifaces[i];
428 				found = 1;
429 			}
430 		}
431 		if (found)
432 			uaa->ifaces[i] = NULL;
433 	}
434 
435 	for (j = 0; j < sc->sc_nalts; j++) {
436 		if (sc->sc_alts[j].ifaceh == NULL) {
437 			aprint_error_dev(self,
438 			    "alt %d missing AS interface(s)\n", j);
439 			USB_ATTACH_ERROR_RETURN;
440 		}
441 	}
442 
443 	aprint_normal_dev(self, "audio rev %d.%02x\n",
444 	       sc->sc_audio_rev >> 8, sc->sc_audio_rev & 0xff);
445 
446 	sc->sc_playchan.sc = sc->sc_recchan.sc = sc;
447 	sc->sc_playchan.altidx = -1;
448 	sc->sc_recchan.altidx = -1;
449 
450 	if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_FRAC)
451 		sc->sc_altflags |= UA_NOFRAC;
452 
453 #ifndef UAUDIO_DEBUG
454 	if (bootverbose)
455 #endif
456 		aprint_normal_dev(self, "%d mixer controls\n",
457 		    sc->sc_nctls);
458 
459 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
460 			   USBDEV(sc->sc_dev));
461 
462 	DPRINTF(("uaudio_attach: doing audio_attach_mi\n"));
463 #if defined(__OpenBSD__)
464 	audio_attach_mi(&uaudio_hw_if, sc, &sc->sc_dev);
465 #else
466 	sc->sc_audiodev = audio_attach_mi(&uaudio_hw_if, sc, sc->sc_dev);
467 #endif
468 
469 	USB_ATTACH_SUCCESS_RETURN;
470 }
471 
472 int
473 uaudio_activate(device_ptr_t self, enum devact act)
474 {
475 	struct uaudio_softc *sc;
476 	int rv;
477 
478 	sc = device_private(self);
479 	rv = 0;
480 	switch (act) {
481 	case DVACT_ACTIVATE:
482 		return EOPNOTSUPP;
483 
484 	case DVACT_DEACTIVATE:
485 		if (sc->sc_audiodev != NULL)
486 			rv = config_deactivate(sc->sc_audiodev);
487 		sc->sc_dying = 1;
488 		break;
489 	}
490 	return rv;
491 }
492 
493 void
494 uaudio_childdet(device_t self, device_t child)
495 {
496 	struct uaudio_softc *sc = device_private(self);
497 
498 	KASSERT(sc->sc_audiodev == child);
499 	sc->sc_audiodev = NULL;
500 }
501 
502 int
503 uaudio_detach(device_t self, int flags)
504 {
505 	struct uaudio_softc *sc = device_private(self);
506 	int rv;
507 
508 	rv = 0;
509 	/* Wait for outstanding requests to complete. */
510 	usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
511 
512 	if (sc->sc_audiodev != NULL)
513 		rv = config_detach(sc->sc_audiodev, flags);
514 
515 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
516 			   USBDEV(sc->sc_dev));
517 
518 	if (sc->sc_formats != NULL)
519 		free(sc->sc_formats, M_USBDEV);
520 	auconv_delete_encodings(sc->sc_encodings);
521 	return rv;
522 }
523 
524 Static int
525 uaudio_query_encoding(void *addr, struct audio_encoding *fp)
526 {
527 	struct uaudio_softc *sc;
528 	int flags;
529 
530 	sc = addr;
531 	flags = sc->sc_altflags;
532 	if (sc->sc_dying)
533 		return EIO;
534 
535 	if (sc->sc_nalts == 0 || flags == 0)
536 		return ENXIO;
537 
538 	return auconv_query_encoding(sc->sc_encodings, fp);
539 }
540 
541 Static const usb_interface_descriptor_t *
542 uaudio_find_iface(const char *tbuf, int size, int *offsp, int subtype)
543 {
544 	const usb_interface_descriptor_t *d;
545 
546 	while (*offsp < size) {
547 		d = (const void *)(tbuf + *offsp);
548 		*offsp += d->bLength;
549 		if (d->bDescriptorType == UDESC_INTERFACE &&
550 		    d->bInterfaceClass == UICLASS_AUDIO &&
551 		    d->bInterfaceSubClass == subtype)
552 			return d;
553 	}
554 	return NULL;
555 }
556 
557 Static void
558 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct mixerctl *mc)
559 {
560 	int res;
561 	size_t len;
562 	struct mixerctl *nmc;
563 
564 	if (mc->class < UAC_NCLASSES) {
565 		DPRINTF(("%s: adding %s.%s\n",
566 			 __func__, uac_names[mc->class], mc->ctlname));
567 	} else {
568 		DPRINTF(("%s: adding %s\n", __func__, mc->ctlname));
569 	}
570 	len = sizeof(*mc) * (sc->sc_nctls + 1);
571 	nmc = malloc(len, M_USBDEV, M_NOWAIT);
572 	if (nmc == NULL) {
573 		aprint_error("uaudio_mixer_add_ctl: no memory\n");
574 		return;
575 	}
576 	/* Copy old data, if there was any */
577 	if (sc->sc_nctls != 0) {
578 		memcpy(nmc, sc->sc_ctls, sizeof(*mc) * (sc->sc_nctls));
579 		free(sc->sc_ctls, M_USBDEV);
580 	}
581 	sc->sc_ctls = nmc;
582 
583 	mc->delta = 0;
584 	if (mc->type == MIX_ON_OFF) {
585 		mc->minval = 0;
586 		mc->maxval = 1;
587 	} else if (mc->type == MIX_SELECTOR) {
588 		;
589 	} else {
590 		/* Determine min and max values. */
591 		mc->minval = uaudio_signext(mc->type,
592 			uaudio_get(sc, GET_MIN, UT_READ_CLASS_INTERFACE,
593 				   mc->wValue[0], mc->wIndex,
594 				   MIX_SIZE(mc->type)));
595 		mc->maxval = 1 + uaudio_signext(mc->type,
596 			uaudio_get(sc, GET_MAX, UT_READ_CLASS_INTERFACE,
597 				   mc->wValue[0], mc->wIndex,
598 				   MIX_SIZE(mc->type)));
599 		mc->mul = mc->maxval - mc->minval;
600 		if (mc->mul == 0)
601 			mc->mul = 1;
602 		res = uaudio_get(sc, GET_RES, UT_READ_CLASS_INTERFACE,
603 				 mc->wValue[0], mc->wIndex,
604 				 MIX_SIZE(mc->type));
605 		if (res > 0)
606 			mc->delta = (res * 255 + mc->mul/2) / mc->mul;
607 	}
608 
609 	sc->sc_ctls[sc->sc_nctls++] = *mc;
610 
611 #ifdef UAUDIO_DEBUG
612 	if (uaudiodebug > 2) {
613 		int i;
614 		DPRINTF(("uaudio_mixer_add_ctl: wValue=%04x",mc->wValue[0]));
615 		for (i = 1; i < mc->nchan; i++)
616 			DPRINTF((",%04x", mc->wValue[i]));
617 		DPRINTF((" wIndex=%04x type=%d name='%s' unit='%s' "
618 			 "min=%d max=%d\n",
619 			 mc->wIndex, mc->type, mc->ctlname, mc->ctlunit,
620 			 mc->minval, mc->maxval));
621 	}
622 #endif
623 }
624 
625 Static char *
626 uaudio_id_name(struct uaudio_softc *sc,
627     const struct io_terminal *iot, int id)
628 {
629 	static char tbuf[32];
630 
631 	snprintf(tbuf, sizeof(tbuf), "i%d", id);
632 	return tbuf;
633 }
634 
635 #ifdef UAUDIO_DEBUG
636 Static void
637 uaudio_dump_cluster(const struct usb_audio_cluster *cl)
638 {
639 	static const char *channel_names[16] = {
640 		"LEFT", "RIGHT", "CENTER", "LFE",
641 		"LEFT_SURROUND", "RIGHT_SURROUND", "LEFT_CENTER", "RIGHT_CENTER",
642 		"SURROUND", "LEFT_SIDE", "RIGHT_SIDE", "TOP",
643 		"RESERVED12", "RESERVED13", "RESERVED14", "RESERVED15",
644 	};
645 	int cc, i, first;
646 
647 	cc = UGETW(cl->wChannelConfig);
648 	logprintf("cluster: bNrChannels=%u wChannelConfig=0x%.4x",
649 		  cl->bNrChannels, cc);
650 	first = TRUE;
651 	for (i = 0; cc != 0; i++) {
652 		if (cc & 1) {
653 			logprintf("%c%s", first ? '<' : ',', channel_names[i]);
654 			first = FALSE;
655 		}
656 		cc = cc >> 1;
657 	}
658 	logprintf("> iChannelNames=%u", cl->iChannelNames);
659 }
660 #endif
661 
662 Static struct usb_audio_cluster
663 uaudio_get_cluster(int id, const struct io_terminal *iot)
664 {
665 	struct usb_audio_cluster r;
666 	const uaudio_cs_descriptor_t *dp;
667 	int i;
668 
669 	for (i = 0; i < 25; i++) { /* avoid infinite loops */
670 		dp = iot[id].d.desc;
671 		if (dp == 0)
672 			goto bad;
673 		switch (dp->bDescriptorSubtype) {
674 		case UDESCSUB_AC_INPUT:
675 			r.bNrChannels = iot[id].d.it->bNrChannels;
676 			USETW(r.wChannelConfig, UGETW(iot[id].d.it->wChannelConfig));
677 			r.iChannelNames = iot[id].d.it->iChannelNames;
678 			return r;
679 		case UDESCSUB_AC_OUTPUT:
680 			id = iot[id].d.ot->bSourceId;
681 			break;
682 		case UDESCSUB_AC_MIXER:
683 			r = *(const struct usb_audio_cluster *)
684 				&iot[id].d.mu->baSourceId[iot[id].d.mu->bNrInPins];
685 			return r;
686 		case UDESCSUB_AC_SELECTOR:
687 			/* XXX This is not really right */
688 			id = iot[id].d.su->baSourceId[0];
689 			break;
690 		case UDESCSUB_AC_FEATURE:
691 			id = iot[id].d.fu->bSourceId;
692 			break;
693 		case UDESCSUB_AC_PROCESSING:
694 			r = *(const struct usb_audio_cluster *)
695 				&iot[id].d.pu->baSourceId[iot[id].d.pu->bNrInPins];
696 			return r;
697 		case UDESCSUB_AC_EXTENSION:
698 			r = *(const struct usb_audio_cluster *)
699 				&iot[id].d.eu->baSourceId[iot[id].d.eu->bNrInPins];
700 			return r;
701 		default:
702 			goto bad;
703 		}
704 	}
705  bad:
706 	aprint_error("uaudio_get_cluster: bad data\n");
707 	memset(&r, 0, sizeof r);
708 	return r;
709 
710 }
711 
712 Static void
713 uaudio_add_input(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
714 {
715 	const struct usb_audio_input_terminal *d;
716 
717 	d = iot[id].d.it;
718 #ifdef UAUDIO_DEBUG
719 	DPRINTFN(2,("uaudio_add_input: bTerminalId=%d wTerminalType=0x%04x "
720 		    "bAssocTerminal=%d bNrChannels=%d wChannelConfig=%d "
721 		    "iChannelNames=%d iTerminal=%d\n",
722 		    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
723 		    d->bNrChannels, UGETW(d->wChannelConfig),
724 		    d->iChannelNames, d->iTerminal));
725 #endif
726 	/* If USB input terminal, record wChannelConfig */
727 	if ((UGETW(d->wTerminalType) & 0xff00) != 0x0100)
728 		return;
729 	sc->sc_channel_config = UGETW(d->wChannelConfig);
730 }
731 
732 Static void
733 uaudio_add_output(struct uaudio_softc *sc,
734     const struct io_terminal *iot, int id)
735 {
736 #ifdef UAUDIO_DEBUG
737 	const struct usb_audio_output_terminal *d;
738 
739 	d = iot[id].d.ot;
740 	DPRINTFN(2,("uaudio_add_output: bTerminalId=%d wTerminalType=0x%04x "
741 		    "bAssocTerminal=%d bSourceId=%d iTerminal=%d\n",
742 		    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
743 		    d->bSourceId, d->iTerminal));
744 #endif
745 }
746 
747 Static void
748 uaudio_add_mixer(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
749 {
750 	const struct usb_audio_mixer_unit *d;
751 	const struct usb_audio_mixer_unit_1 *d1;
752 	int c, chs, ichs, ochs, i, o, bno, p, mo, mc, k;
753 	const uByte *bm;
754 	struct mixerctl mix;
755 
756 	d = iot[id].d.mu;
757 	DPRINTFN(2,("uaudio_add_mixer: bUnitId=%d bNrInPins=%d\n",
758 		    d->bUnitId, d->bNrInPins));
759 
760 	/* Compute the number of input channels */
761 	ichs = 0;
762 	for (i = 0; i < d->bNrInPins; i++)
763 		ichs += uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
764 
765 	/* and the number of output channels */
766 	d1 = (const struct usb_audio_mixer_unit_1 *)&d->baSourceId[d->bNrInPins];
767 	ochs = d1->bNrChannels;
768 	DPRINTFN(2,("uaudio_add_mixer: ichs=%d ochs=%d\n", ichs, ochs));
769 
770 	bm = d1->bmControls;
771 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
772 	uaudio_determine_class(&iot[id], &mix);
773 	mix.type = MIX_SIGNED_16;
774 	mix.ctlunit = AudioNvolume;
775 #define _BIT(bno) ((bm[bno / 8] >> (7 - bno % 8)) & 1)
776 	for (p = i = 0; i < d->bNrInPins; i++) {
777 		chs = uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
778 		mc = 0;
779 		for (c = 0; c < chs; c++) {
780 			mo = 0;
781 			for (o = 0; o < ochs; o++) {
782 				bno = (p + c) * ochs + o;
783 				if (_BIT(bno))
784 					mo++;
785 			}
786 			if (mo == 1)
787 				mc++;
788 		}
789 		if (mc == chs && chs <= MIX_MAX_CHAN) {
790 			k = 0;
791 			for (c = 0; c < chs; c++)
792 				for (o = 0; o < ochs; o++) {
793 					bno = (p + c) * ochs + o;
794 					if (_BIT(bno))
795 						mix.wValue[k++] =
796 							MAKE(p+c+1, o+1);
797 				}
798 			snprintf(mix.ctlname, sizeof(mix.ctlname), "mix%d-%s",
799 			    d->bUnitId, uaudio_id_name(sc, iot,
800 			    d->baSourceId[i]));
801 			mix.nchan = chs;
802 			uaudio_mixer_add_ctl(sc, &mix);
803 		} else {
804 			/* XXX */
805 		}
806 #undef _BIT
807 		p += chs;
808 	}
809 
810 }
811 
812 Static void
813 uaudio_add_selector(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
814 {
815 	const struct usb_audio_selector_unit *d;
816 	struct mixerctl mix;
817 	int i, wp;
818 
819 	d = iot[id].d.su;
820 	DPRINTFN(2,("uaudio_add_selector: bUnitId=%d bNrInPins=%d\n",
821 		    d->bUnitId, d->bNrInPins));
822 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
823 	mix.wValue[0] = MAKE(0, 0);
824 	uaudio_determine_class(&iot[id], &mix);
825 	mix.nchan = 1;
826 	mix.type = MIX_SELECTOR;
827 	mix.ctlunit = "";
828 	mix.minval = 1;
829 	mix.maxval = d->bNrInPins;
830 	mix.mul = mix.maxval - mix.minval;
831 	wp = snprintf(mix.ctlname, MAX_AUDIO_DEV_LEN, "sel%d-", d->bUnitId);
832 	for (i = 1; i <= d->bNrInPins; i++) {
833 		wp += snprintf(mix.ctlname + wp, MAX_AUDIO_DEV_LEN - wp,
834 			       "i%d", d->baSourceId[i - 1]);
835 		if (wp > MAX_AUDIO_DEV_LEN - 1)
836 			break;
837 	}
838 	uaudio_mixer_add_ctl(sc, &mix);
839 }
840 
841 #ifdef UAUDIO_DEBUG
842 Static const char *
843 uaudio_get_terminal_name(int terminal_type)
844 {
845 	static char tbuf[100];
846 
847 	switch (terminal_type) {
848 	/* USB terminal types */
849 	case UAT_UNDEFINED:	return "UAT_UNDEFINED";
850 	case UAT_STREAM:	return "UAT_STREAM";
851 	case UAT_VENDOR:	return "UAT_VENDOR";
852 	/* input terminal types */
853 	case UATI_UNDEFINED:	return "UATI_UNDEFINED";
854 	case UATI_MICROPHONE:	return "UATI_MICROPHONE";
855 	case UATI_DESKMICROPHONE:	return "UATI_DESKMICROPHONE";
856 	case UATI_PERSONALMICROPHONE:	return "UATI_PERSONALMICROPHONE";
857 	case UATI_OMNIMICROPHONE:	return "UATI_OMNIMICROPHONE";
858 	case UATI_MICROPHONEARRAY:	return "UATI_MICROPHONEARRAY";
859 	case UATI_PROCMICROPHONEARR:	return "UATI_PROCMICROPHONEARR";
860 	/* output terminal types */
861 	case UATO_UNDEFINED:	return "UATO_UNDEFINED";
862 	case UATO_SPEAKER:	return "UATO_SPEAKER";
863 	case UATO_HEADPHONES:	return "UATO_HEADPHONES";
864 	case UATO_DISPLAYAUDIO:	return "UATO_DISPLAYAUDIO";
865 	case UATO_DESKTOPSPEAKER:	return "UATO_DESKTOPSPEAKER";
866 	case UATO_ROOMSPEAKER:	return "UATO_ROOMSPEAKER";
867 	case UATO_COMMSPEAKER:	return "UATO_COMMSPEAKER";
868 	case UATO_SUBWOOFER:	return "UATO_SUBWOOFER";
869 	/* bidir terminal types */
870 	case UATB_UNDEFINED:	return "UATB_UNDEFINED";
871 	case UATB_HANDSET:	return "UATB_HANDSET";
872 	case UATB_HEADSET:	return "UATB_HEADSET";
873 	case UATB_SPEAKERPHONE:	return "UATB_SPEAKERPHONE";
874 	case UATB_SPEAKERPHONEESUP:	return "UATB_SPEAKERPHONEESUP";
875 	case UATB_SPEAKERPHONEECANC:	return "UATB_SPEAKERPHONEECANC";
876 	/* telephony terminal types */
877 	case UATT_UNDEFINED:	return "UATT_UNDEFINED";
878 	case UATT_PHONELINE:	return "UATT_PHONELINE";
879 	case UATT_TELEPHONE:	return "UATT_TELEPHONE";
880 	case UATT_DOWNLINEPHONE:	return "UATT_DOWNLINEPHONE";
881 	/* external terminal types */
882 	case UATE_UNDEFINED:	return "UATE_UNDEFINED";
883 	case UATE_ANALOGCONN:	return "UATE_ANALOGCONN";
884 	case UATE_LINECONN:	return "UATE_LINECONN";
885 	case UATE_LEGACYCONN:	return "UATE_LEGACYCONN";
886 	case UATE_DIGITALAUIFC:	return "UATE_DIGITALAUIFC";
887 	case UATE_SPDIF:	return "UATE_SPDIF";
888 	case UATE_1394DA:	return "UATE_1394DA";
889 	case UATE_1394DV:	return "UATE_1394DV";
890 	/* embedded function terminal types */
891 	case UATF_UNDEFINED:	return "UATF_UNDEFINED";
892 	case UATF_CALIBNOISE:	return "UATF_CALIBNOISE";
893 	case UATF_EQUNOISE:	return "UATF_EQUNOISE";
894 	case UATF_CDPLAYER:	return "UATF_CDPLAYER";
895 	case UATF_DAT:	return "UATF_DAT";
896 	case UATF_DCC:	return "UATF_DCC";
897 	case UATF_MINIDISK:	return "UATF_MINIDISK";
898 	case UATF_ANALOGTAPE:	return "UATF_ANALOGTAPE";
899 	case UATF_PHONOGRAPH:	return "UATF_PHONOGRAPH";
900 	case UATF_VCRAUDIO:	return "UATF_VCRAUDIO";
901 	case UATF_VIDEODISCAUDIO:	return "UATF_VIDEODISCAUDIO";
902 	case UATF_DVDAUDIO:	return "UATF_DVDAUDIO";
903 	case UATF_TVTUNERAUDIO:	return "UATF_TVTUNERAUDIO";
904 	case UATF_SATELLITE:	return "UATF_SATELLITE";
905 	case UATF_CABLETUNER:	return "UATF_CABLETUNER";
906 	case UATF_DSS:	return "UATF_DSS";
907 	case UATF_RADIORECV:	return "UATF_RADIORECV";
908 	case UATF_RADIOXMIT:	return "UATF_RADIOXMIT";
909 	case UATF_MULTITRACK:	return "UATF_MULTITRACK";
910 	case UATF_SYNTHESIZER:	return "UATF_SYNTHESIZER";
911 	default:
912 		snprintf(tbuf, sizeof(tbuf), "unknown type (0x%.4x)", terminal_type);
913 		return tbuf;
914 	}
915 }
916 #endif
917 
918 Static int
919 uaudio_determine_class(const struct io_terminal *iot, struct mixerctl *mix)
920 {
921 	int terminal_type;
922 
923 	if (iot == NULL || iot->output == NULL) {
924 		mix->class = UAC_OUTPUT;
925 		return 0;
926 	}
927 	terminal_type = 0;
928 	if (iot->output->size == 1)
929 		terminal_type = iot->output->terminals[0];
930 	/*
931 	 * If the only output terminal is USB,
932 	 * the class is UAC_RECORD.
933 	 */
934 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
935 		mix->class = UAC_RECORD;
936 		if (iot->inputs_size == 1
937 		    && iot->inputs[0] != NULL
938 		    && iot->inputs[0]->size == 1)
939 			return iot->inputs[0]->terminals[0];
940 		else
941 			return 0;
942 	}
943 	/*
944 	 * If the ultimate destination of the unit is just one output
945 	 * terminal and the unit is connected to the output terminal
946 	 * directly, the class is UAC_OUTPUT.
947 	 */
948 	if (terminal_type != 0 && iot->direct) {
949 		mix->class = UAC_OUTPUT;
950 		return terminal_type;
951 	}
952 	/*
953 	 * If the unit is connected to just one input terminal,
954 	 * the class is UAC_INPUT.
955 	 */
956 	if (iot->inputs_size == 1 && iot->inputs[0] != NULL
957 	    && iot->inputs[0]->size == 1) {
958 		mix->class = UAC_INPUT;
959 		return iot->inputs[0]->terminals[0];
960 	}
961 	/*
962 	 * Otherwise, the class is UAC_OUTPUT.
963 	 */
964 	mix->class = UAC_OUTPUT;
965 	return terminal_type;
966 }
967 
968 Static const char *
969 uaudio_feature_name(const struct io_terminal *iot, struct mixerctl *mix)
970 {
971 	int terminal_type;
972 
973 	terminal_type = uaudio_determine_class(iot, mix);
974 	if (mix->class == UAC_RECORD && terminal_type == 0)
975 		return AudioNmixerout;
976 	DPRINTF(("%s: terminal_type=%s\n", __func__,
977 		 uaudio_get_terminal_name(terminal_type)));
978 	switch (terminal_type) {
979 	case UAT_STREAM:
980 		return AudioNdac;
981 
982 	case UATI_MICROPHONE:
983 	case UATI_DESKMICROPHONE:
984 	case UATI_PERSONALMICROPHONE:
985 	case UATI_OMNIMICROPHONE:
986 	case UATI_MICROPHONEARRAY:
987 	case UATI_PROCMICROPHONEARR:
988 		return AudioNmicrophone;
989 
990 	case UATO_SPEAKER:
991 	case UATO_DESKTOPSPEAKER:
992 	case UATO_ROOMSPEAKER:
993 	case UATO_COMMSPEAKER:
994 		return AudioNspeaker;
995 
996 	case UATO_HEADPHONES:
997 		return AudioNheadphone;
998 
999 	case UATO_SUBWOOFER:
1000 		return AudioNlfe;
1001 
1002 	/* telephony terminal types */
1003 	case UATT_UNDEFINED:
1004 	case UATT_PHONELINE:
1005 	case UATT_TELEPHONE:
1006 	case UATT_DOWNLINEPHONE:
1007 		return "phone";
1008 
1009 	case UATE_ANALOGCONN:
1010 	case UATE_LINECONN:
1011 	case UATE_LEGACYCONN:
1012 		return AudioNline;
1013 
1014 	case UATE_DIGITALAUIFC:
1015 	case UATE_SPDIF:
1016 	case UATE_1394DA:
1017 	case UATE_1394DV:
1018 		return AudioNaux;
1019 
1020 	case UATF_CDPLAYER:
1021 		return AudioNcd;
1022 
1023 	case UATF_SYNTHESIZER:
1024 		return AudioNfmsynth;
1025 
1026 	case UATF_VIDEODISCAUDIO:
1027 	case UATF_DVDAUDIO:
1028 	case UATF_TVTUNERAUDIO:
1029 		return AudioNvideo;
1030 
1031 	case UAT_UNDEFINED:
1032 	case UAT_VENDOR:
1033 	case UATI_UNDEFINED:
1034 /* output terminal types */
1035 	case UATO_UNDEFINED:
1036 	case UATO_DISPLAYAUDIO:
1037 /* bidir terminal types */
1038 	case UATB_UNDEFINED:
1039 	case UATB_HANDSET:
1040 	case UATB_HEADSET:
1041 	case UATB_SPEAKERPHONE:
1042 	case UATB_SPEAKERPHONEESUP:
1043 	case UATB_SPEAKERPHONEECANC:
1044 /* external terminal types */
1045 	case UATE_UNDEFINED:
1046 /* embedded function terminal types */
1047 	case UATF_UNDEFINED:
1048 	case UATF_CALIBNOISE:
1049 	case UATF_EQUNOISE:
1050 	case UATF_DAT:
1051 	case UATF_DCC:
1052 	case UATF_MINIDISK:
1053 	case UATF_ANALOGTAPE:
1054 	case UATF_PHONOGRAPH:
1055 	case UATF_VCRAUDIO:
1056 	case UATF_SATELLITE:
1057 	case UATF_CABLETUNER:
1058 	case UATF_DSS:
1059 	case UATF_RADIORECV:
1060 	case UATF_RADIOXMIT:
1061 	case UATF_MULTITRACK:
1062 	case 0xffff:
1063 	default:
1064 		DPRINTF(("%s: 'master' for 0x%.4x\n", __func__, terminal_type));
1065 		return AudioNmaster;
1066 	}
1067 	return AudioNmaster;
1068 }
1069 
1070 Static void
1071 uaudio_add_feature(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1072 {
1073 	const struct usb_audio_feature_unit *d;
1074 	const uByte *ctls;
1075 	int ctlsize;
1076 	int nchan;
1077 	u_int fumask, mmask, cmask;
1078 	struct mixerctl mix;
1079 	int chan, ctl, i, unit;
1080 	const char *mixername;
1081 
1082 #define GET(i) (ctls[(i)*ctlsize] | \
1083 		(ctlsize > 1 ? ctls[(i)*ctlsize+1] << 8 : 0))
1084 	d = iot[id].d.fu;
1085 	ctls = d->bmaControls;
1086 	ctlsize = d->bControlSize;
1087 	nchan = (d->bLength - 7) / ctlsize;
1088 	mmask = GET(0);
1089 	/* Figure out what we can control */
1090 	for (cmask = 0, chan = 1; chan < nchan; chan++) {
1091 		DPRINTFN(9,("uaudio_add_feature: chan=%d mask=%x\n",
1092 			    chan, GET(chan)));
1093 		cmask |= GET(chan);
1094 	}
1095 
1096 	DPRINTFN(1,("uaudio_add_feature: bUnitId=%d, "
1097 		    "%d channels, mmask=0x%04x, cmask=0x%04x\n",
1098 		    d->bUnitId, nchan, mmask, cmask));
1099 
1100 	if (nchan > MIX_MAX_CHAN)
1101 		nchan = MIX_MAX_CHAN;
1102 	unit = d->bUnitId;
1103 	mix.wIndex = MAKE(unit, sc->sc_ac_iface);
1104 	for (ctl = MUTE_CONTROL; ctl < LOUDNESS_CONTROL; ctl++) {
1105 		fumask = FU_MASK(ctl);
1106 		DPRINTFN(4,("uaudio_add_feature: ctl=%d fumask=0x%04x\n",
1107 			    ctl, fumask));
1108 		if (mmask & fumask) {
1109 			mix.nchan = 1;
1110 			mix.wValue[0] = MAKE(ctl, 0);
1111 		} else if (cmask & fumask) {
1112 			mix.nchan = nchan - 1;
1113 			for (i = 1; i < nchan; i++) {
1114 				if (GET(i) & fumask)
1115 					mix.wValue[i-1] = MAKE(ctl, i);
1116 				else
1117 					mix.wValue[i-1] = -1;
1118 			}
1119 		} else {
1120 			continue;
1121 		}
1122 #undef GET
1123 		mixername = uaudio_feature_name(&iot[id], &mix);
1124 		switch (ctl) {
1125 		case MUTE_CONTROL:
1126 			mix.type = MIX_ON_OFF;
1127 			mix.ctlunit = "";
1128 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1129 				 "%s.%s", mixername, AudioNmute);
1130 			break;
1131 		case VOLUME_CONTROL:
1132 			mix.type = MIX_SIGNED_16;
1133 			mix.ctlunit = AudioNvolume;
1134 			strlcpy(mix.ctlname, mixername, sizeof(mix.ctlname));
1135 			break;
1136 		case BASS_CONTROL:
1137 			mix.type = MIX_SIGNED_8;
1138 			mix.ctlunit = AudioNbass;
1139 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1140 				 "%s.%s", mixername, AudioNbass);
1141 			break;
1142 		case MID_CONTROL:
1143 			mix.type = MIX_SIGNED_8;
1144 			mix.ctlunit = AudioNmid;
1145 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1146 				 "%s.%s", mixername, AudioNmid);
1147 			break;
1148 		case TREBLE_CONTROL:
1149 			mix.type = MIX_SIGNED_8;
1150 			mix.ctlunit = AudioNtreble;
1151 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1152 				 "%s.%s", mixername, AudioNtreble);
1153 			break;
1154 		case GRAPHIC_EQUALIZER_CONTROL:
1155 			continue; /* XXX don't add anything */
1156 			break;
1157 		case AGC_CONTROL:
1158 			mix.type = MIX_ON_OFF;
1159 			mix.ctlunit = "";
1160 			snprintf(mix.ctlname, sizeof(mix.ctlname), "%s.%s",
1161 				 mixername, AudioNagc);
1162 			break;
1163 		case DELAY_CONTROL:
1164 			mix.type = MIX_UNSIGNED_16;
1165 			mix.ctlunit = "4 ms";
1166 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1167 				 "%s.%s", mixername, AudioNdelay);
1168 			break;
1169 		case BASS_BOOST_CONTROL:
1170 			mix.type = MIX_ON_OFF;
1171 			mix.ctlunit = "";
1172 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1173 				 "%s.%s", mixername, AudioNbassboost);
1174 			break;
1175 		case LOUDNESS_CONTROL:
1176 			mix.type = MIX_ON_OFF;
1177 			mix.ctlunit = "";
1178 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1179 				 "%s.%s", mixername, AudioNloudness);
1180 			break;
1181 		}
1182 		uaudio_mixer_add_ctl(sc, &mix);
1183 	}
1184 }
1185 
1186 Static void
1187 uaudio_add_processing_updown(struct uaudio_softc *sc,
1188 			     const struct io_terminal *iot, int id)
1189 {
1190 	const struct usb_audio_processing_unit *d;
1191 	const struct usb_audio_processing_unit_1 *d1;
1192 	const struct usb_audio_processing_unit_updown *ud;
1193 	struct mixerctl mix;
1194 	int i;
1195 
1196 	d = iot[id].d.pu;
1197 	d1 = (const struct usb_audio_processing_unit_1 *)
1198 	    &d->baSourceId[d->bNrInPins];
1199 	ud = (const struct usb_audio_processing_unit_updown *)
1200 	    &d1->bmControls[d1->bControlSize];
1201 	DPRINTFN(2,("uaudio_add_processing_updown: bUnitId=%d bNrModes=%d\n",
1202 		    d->bUnitId, ud->bNrModes));
1203 
1204 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
1205 		DPRINTF(("uaudio_add_processing_updown: no mode select\n"));
1206 		return;
1207 	}
1208 
1209 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1210 	mix.nchan = 1;
1211 	mix.wValue[0] = MAKE(UD_MODE_SELECT_CONTROL, 0);
1212 	uaudio_determine_class(&iot[id], &mix);
1213 	mix.type = MIX_ON_OFF;	/* XXX */
1214 	mix.ctlunit = "";
1215 	snprintf(mix.ctlname, sizeof(mix.ctlname), "pro%d-mode", d->bUnitId);
1216 
1217 	for (i = 0; i < ud->bNrModes; i++) {
1218 		DPRINTFN(2,("uaudio_add_processing_updown: i=%d bm=0x%x\n",
1219 			    i, UGETW(ud->waModes[i])));
1220 		/* XXX */
1221 	}
1222 	uaudio_mixer_add_ctl(sc, &mix);
1223 }
1224 
1225 Static void
1226 uaudio_add_processing(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1227 {
1228 	const struct usb_audio_processing_unit *d;
1229 	const struct usb_audio_processing_unit_1 *d1;
1230 	int ptype;
1231 	struct mixerctl mix;
1232 
1233 	d = iot[id].d.pu;
1234 	d1 = (const struct usb_audio_processing_unit_1 *)
1235 	    &d->baSourceId[d->bNrInPins];
1236 	ptype = UGETW(d->wProcessType);
1237 	DPRINTFN(2,("uaudio_add_processing: wProcessType=%d bUnitId=%d "
1238 		    "bNrInPins=%d\n", ptype, d->bUnitId, d->bNrInPins));
1239 
1240 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
1241 		mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1242 		mix.nchan = 1;
1243 		mix.wValue[0] = MAKE(XX_ENABLE_CONTROL, 0);
1244 		uaudio_determine_class(&iot[id], &mix);
1245 		mix.type = MIX_ON_OFF;
1246 		mix.ctlunit = "";
1247 		snprintf(mix.ctlname, sizeof(mix.ctlname), "pro%d.%d-enable",
1248 		    d->bUnitId, ptype);
1249 		uaudio_mixer_add_ctl(sc, &mix);
1250 	}
1251 
1252 	switch(ptype) {
1253 	case UPDOWNMIX_PROCESS:
1254 		uaudio_add_processing_updown(sc, iot, id);
1255 		break;
1256 	case DOLBY_PROLOGIC_PROCESS:
1257 	case P3D_STEREO_EXTENDER_PROCESS:
1258 	case REVERBATION_PROCESS:
1259 	case CHORUS_PROCESS:
1260 	case DYN_RANGE_COMP_PROCESS:
1261 	default:
1262 #ifdef UAUDIO_DEBUG
1263 		aprint_debug(
1264 		    "uaudio_add_processing: unit %d, type=%d not impl.\n",
1265 		    d->bUnitId, ptype);
1266 #endif
1267 		break;
1268 	}
1269 }
1270 
1271 Static void
1272 uaudio_add_extension(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1273 {
1274 	const struct usb_audio_extension_unit *d;
1275 	const struct usb_audio_extension_unit_1 *d1;
1276 	struct mixerctl mix;
1277 
1278 	d = iot[id].d.eu;
1279 	d1 = (const struct usb_audio_extension_unit_1 *)
1280 	    &d->baSourceId[d->bNrInPins];
1281 	DPRINTFN(2,("uaudio_add_extension: bUnitId=%d bNrInPins=%d\n",
1282 		    d->bUnitId, d->bNrInPins));
1283 
1284 	if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_XU)
1285 		return;
1286 
1287 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
1288 		mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1289 		mix.nchan = 1;
1290 		mix.wValue[0] = MAKE(UA_EXT_ENABLE, 0);
1291 		uaudio_determine_class(&iot[id], &mix);
1292 		mix.type = MIX_ON_OFF;
1293 		mix.ctlunit = "";
1294 		snprintf(mix.ctlname, sizeof(mix.ctlname), "ext%d-enable",
1295 		    d->bUnitId);
1296 		uaudio_mixer_add_ctl(sc, &mix);
1297 	}
1298 }
1299 
1300 Static struct terminal_list*
1301 uaudio_merge_terminal_list(const struct io_terminal *iot)
1302 {
1303 	struct terminal_list *tml;
1304 	uint16_t *ptm;
1305 	int i, len;
1306 
1307 	len = 0;
1308 	if (iot->inputs == NULL)
1309 		return NULL;
1310 	for (i = 0; i < iot->inputs_size; i++) {
1311 		if (iot->inputs[i] != NULL)
1312 			len += iot->inputs[i]->size;
1313 	}
1314 	tml = malloc(TERMINAL_LIST_SIZE(len), M_TEMP, M_NOWAIT);
1315 	if (tml == NULL) {
1316 		aprint_error("uaudio_merge_terminal_list: no memory\n");
1317 		return NULL;
1318 	}
1319 	tml->size = 0;
1320 	ptm = tml->terminals;
1321 	for (i = 0; i < iot->inputs_size; i++) {
1322 		if (iot->inputs[i] == NULL)
1323 			continue;
1324 		if (iot->inputs[i]->size > len)
1325 			break;
1326 		memcpy(ptm, iot->inputs[i]->terminals,
1327 		       iot->inputs[i]->size * sizeof(uint16_t));
1328 		tml->size += iot->inputs[i]->size;
1329 		ptm += iot->inputs[i]->size;
1330 		len -= iot->inputs[i]->size;
1331 	}
1332 	return tml;
1333 }
1334 
1335 Static struct terminal_list *
1336 uaudio_io_terminaltype(int outtype, struct io_terminal *iot, int id)
1337 {
1338 	struct terminal_list *tml;
1339 	struct io_terminal *it;
1340 	int src_id, i;
1341 
1342 	it = &iot[id];
1343 	if (it->output != NULL) {
1344 		/* already has outtype? */
1345 		for (i = 0; i < it->output->size; i++)
1346 			if (it->output->terminals[i] == outtype)
1347 				return uaudio_merge_terminal_list(it);
1348 		tml = malloc(TERMINAL_LIST_SIZE(it->output->size + 1),
1349 			     M_TEMP, M_NOWAIT);
1350 		if (tml == NULL) {
1351 			aprint_error("uaudio_io_terminaltype: no memory\n");
1352 			return uaudio_merge_terminal_list(it);
1353 		}
1354 		memcpy(tml, it->output, TERMINAL_LIST_SIZE(it->output->size));
1355 		tml->terminals[it->output->size] = outtype;
1356 		tml->size++;
1357 		free(it->output, M_TEMP);
1358 		it->output = tml;
1359 		if (it->inputs != NULL) {
1360 			for (i = 0; i < it->inputs_size; i++)
1361 				if (it->inputs[i] != NULL)
1362 					free(it->inputs[i], M_TEMP);
1363 			free(it->inputs, M_TEMP);
1364 		}
1365 		it->inputs_size = 0;
1366 		it->inputs = NULL;
1367 	} else {		/* end `iot[id] != NULL' */
1368 		it->inputs_size = 0;
1369 		it->inputs = NULL;
1370 		it->output = malloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
1371 		if (it->output == NULL) {
1372 			aprint_error("uaudio_io_terminaltype: no memory\n");
1373 			return NULL;
1374 		}
1375 		it->output->terminals[0] = outtype;
1376 		it->output->size = 1;
1377 		it->direct = FALSE;
1378 	}
1379 
1380 	switch (it->d.desc->bDescriptorSubtype) {
1381 	case UDESCSUB_AC_INPUT:
1382 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1383 		if (it->inputs == NULL) {
1384 			aprint_error("uaudio_io_terminaltype: no memory\n");
1385 			return NULL;
1386 		}
1387 		tml = malloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
1388 		if (tml == NULL) {
1389 			aprint_error("uaudio_io_terminaltype: no memory\n");
1390 			free(it->inputs, M_TEMP);
1391 			it->inputs = NULL;
1392 			return NULL;
1393 		}
1394 		it->inputs[0] = tml;
1395 		tml->terminals[0] = UGETW(it->d.it->wTerminalType);
1396 		tml->size = 1;
1397 		it->inputs_size = 1;
1398 		return uaudio_merge_terminal_list(it);
1399 	case UDESCSUB_AC_FEATURE:
1400 		src_id = it->d.fu->bSourceId;
1401 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1402 		if (it->inputs == NULL) {
1403 			aprint_error("uaudio_io_terminaltype: no memory\n");
1404 			return uaudio_io_terminaltype(outtype, iot, src_id);
1405 		}
1406 		it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
1407 		it->inputs_size = 1;
1408 		return uaudio_merge_terminal_list(it);
1409 	case UDESCSUB_AC_OUTPUT:
1410 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1411 		if (it->inputs == NULL) {
1412 			aprint_error("uaudio_io_terminaltype: no memory\n");
1413 			return NULL;
1414 		}
1415 		src_id = it->d.ot->bSourceId;
1416 		it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
1417 		it->inputs_size = 1;
1418 		iot[src_id].direct = TRUE;
1419 		return NULL;
1420 	case UDESCSUB_AC_MIXER:
1421 		it->inputs_size = 0;
1422 		it->inputs = malloc(sizeof(struct terminal_list *)
1423 				    * it->d.mu->bNrInPins, M_TEMP, M_NOWAIT);
1424 		if (it->inputs == NULL) {
1425 			aprint_error("uaudio_io_terminaltype: no memory\n");
1426 			return NULL;
1427 		}
1428 		for (i = 0; i < it->d.mu->bNrInPins; i++) {
1429 			src_id = it->d.mu->baSourceId[i];
1430 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1431 							       src_id);
1432 			it->inputs_size++;
1433 		}
1434 		return uaudio_merge_terminal_list(it);
1435 	case UDESCSUB_AC_SELECTOR:
1436 		it->inputs_size = 0;
1437 		it->inputs = malloc(sizeof(struct terminal_list *)
1438 				    * it->d.su->bNrInPins, M_TEMP, M_NOWAIT);
1439 		if (it->inputs == NULL) {
1440 			aprint_error("uaudio_io_terminaltype: no memory\n");
1441 			return NULL;
1442 		}
1443 		for (i = 0; i < it->d.su->bNrInPins; i++) {
1444 			src_id = it->d.su->baSourceId[i];
1445 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1446 							       src_id);
1447 			it->inputs_size++;
1448 		}
1449 		return uaudio_merge_terminal_list(it);
1450 	case UDESCSUB_AC_PROCESSING:
1451 		it->inputs_size = 0;
1452 		it->inputs = malloc(sizeof(struct terminal_list *)
1453 				    * it->d.pu->bNrInPins, M_TEMP, M_NOWAIT);
1454 		if (it->inputs == NULL) {
1455 			aprint_error("uaudio_io_terminaltype: no memory\n");
1456 			return NULL;
1457 		}
1458 		for (i = 0; i < it->d.pu->bNrInPins; i++) {
1459 			src_id = it->d.pu->baSourceId[i];
1460 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1461 							       src_id);
1462 			it->inputs_size++;
1463 		}
1464 		return uaudio_merge_terminal_list(it);
1465 	case UDESCSUB_AC_EXTENSION:
1466 		it->inputs_size = 0;
1467 		it->inputs = malloc(sizeof(struct terminal_list *)
1468 				    * it->d.eu->bNrInPins, M_TEMP, M_NOWAIT);
1469 		if (it->inputs == NULL) {
1470 			aprint_error("uaudio_io_terminaltype: no memory\n");
1471 			return NULL;
1472 		}
1473 		for (i = 0; i < it->d.eu->bNrInPins; i++) {
1474 			src_id = it->d.eu->baSourceId[i];
1475 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1476 							       src_id);
1477 			it->inputs_size++;
1478 		}
1479 		return uaudio_merge_terminal_list(it);
1480 	case UDESCSUB_AC_HEADER:
1481 	default:
1482 		return NULL;
1483 	}
1484 }
1485 
1486 Static usbd_status
1487 uaudio_identify(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
1488 {
1489 	usbd_status err;
1490 
1491 	err = uaudio_identify_ac(sc, cdesc);
1492 	if (err)
1493 		return err;
1494 	return uaudio_identify_as(sc, cdesc);
1495 }
1496 
1497 Static void
1498 uaudio_add_alt(struct uaudio_softc *sc, const struct as_info *ai)
1499 {
1500 	size_t len;
1501 	struct as_info *nai;
1502 
1503 	len = sizeof(*ai) * (sc->sc_nalts + 1);
1504 	nai = malloc(len, M_USBDEV, M_NOWAIT);
1505 	if (nai == NULL) {
1506 		aprint_error("uaudio_add_alt: no memory\n");
1507 		return;
1508 	}
1509 	/* Copy old data, if there was any */
1510 	if (sc->sc_nalts != 0) {
1511 		memcpy(nai, sc->sc_alts, sizeof(*ai) * (sc->sc_nalts));
1512 		free(sc->sc_alts, M_USBDEV);
1513 	}
1514 	sc->sc_alts = nai;
1515 	DPRINTFN(2,("uaudio_add_alt: adding alt=%d, enc=%d\n",
1516 		    ai->alt, ai->encoding));
1517 	sc->sc_alts[sc->sc_nalts++] = *ai;
1518 }
1519 
1520 Static usbd_status
1521 uaudio_process_as(struct uaudio_softc *sc, const char *tbuf, int *offsp,
1522 		  int size, const usb_interface_descriptor_t *id)
1523 #define offs (*offsp)
1524 {
1525 	const struct usb_audio_streaming_interface_descriptor *asid;
1526 	const struct usb_audio_streaming_type1_descriptor *asf1d;
1527 	const usb_endpoint_descriptor_audio_t *ed;
1528 	const usb_endpoint_descriptor_audio_t *epdesc1;
1529 	const struct usb_audio_streaming_endpoint_descriptor *sed;
1530 	int format, chan, prec, enc;
1531 	int dir, type, sync;
1532 	struct as_info ai;
1533 	const char *format_str;
1534 
1535 	asid = (const void *)(tbuf + offs);
1536 	if (asid->bDescriptorType != UDESC_CS_INTERFACE ||
1537 	    asid->bDescriptorSubtype != AS_GENERAL)
1538 		return USBD_INVAL;
1539 	DPRINTF(("uaudio_process_as: asid: bTerminakLink=%d wFormatTag=%d\n",
1540 		 asid->bTerminalLink, UGETW(asid->wFormatTag)));
1541 	offs += asid->bLength;
1542 	if (offs > size)
1543 		return USBD_INVAL;
1544 
1545 	asf1d = (const void *)(tbuf + offs);
1546 	if (asf1d->bDescriptorType != UDESC_CS_INTERFACE ||
1547 	    asf1d->bDescriptorSubtype != FORMAT_TYPE)
1548 		return USBD_INVAL;
1549 	offs += asf1d->bLength;
1550 	if (offs > size)
1551 		return USBD_INVAL;
1552 
1553 	if (asf1d->bFormatType != FORMAT_TYPE_I) {
1554 		aprint_error_dev(sc->sc_dev,
1555 		    "ignored setting with type %d format\n", UGETW(asid->wFormatTag));
1556 		return USBD_NORMAL_COMPLETION;
1557 	}
1558 
1559 	ed = (const void *)(tbuf + offs);
1560 	if (ed->bDescriptorType != UDESC_ENDPOINT)
1561 		return USBD_INVAL;
1562 	DPRINTF(("uaudio_process_as: endpoint[0] bLength=%d bDescriptorType=%d "
1563 		 "bEndpointAddress=%d bmAttributes=0x%x wMaxPacketSize=%d "
1564 		 "bInterval=%d bRefresh=%d bSynchAddress=%d\n",
1565 		 ed->bLength, ed->bDescriptorType, ed->bEndpointAddress,
1566 		 ed->bmAttributes, UGETW(ed->wMaxPacketSize),
1567 		 ed->bInterval, ed->bRefresh, ed->bSynchAddress));
1568 	offs += ed->bLength;
1569 	if (offs > size)
1570 		return USBD_INVAL;
1571 	if (UE_GET_XFERTYPE(ed->bmAttributes) != UE_ISOCHRONOUS)
1572 		return USBD_INVAL;
1573 
1574 	dir = UE_GET_DIR(ed->bEndpointAddress);
1575 	type = UE_GET_ISO_TYPE(ed->bmAttributes);
1576 	if ((usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_INP_ASYNC) &&
1577 	    dir == UE_DIR_IN && type == UE_ISO_ADAPT)
1578 		type = UE_ISO_ASYNC;
1579 
1580 	/* We can't handle endpoints that need a sync pipe yet. */
1581 	sync = FALSE;
1582 	if (dir == UE_DIR_IN && type == UE_ISO_ADAPT) {
1583 		sync = TRUE;
1584 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
1585 		aprint_error_dev(sc->sc_dev,
1586 		    "ignored input endpoint of type adaptive\n");
1587 		return USBD_NORMAL_COMPLETION;
1588 #endif
1589 	}
1590 	if (dir != UE_DIR_IN && type == UE_ISO_ASYNC) {
1591 		sync = TRUE;
1592 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
1593 		aprint_error_dev(sc->sc_dev,
1594 		    "ignored output endpoint of type async\n");
1595 		return USBD_NORMAL_COMPLETION;
1596 #endif
1597 	}
1598 
1599 	sed = (const void *)(tbuf + offs);
1600 	if (sed->bDescriptorType != UDESC_CS_ENDPOINT ||
1601 	    sed->bDescriptorSubtype != AS_GENERAL)
1602 		return USBD_INVAL;
1603 	DPRINTF((" streadming_endpoint: offset=%d bLength=%d\n", offs, sed->bLength));
1604 	offs += sed->bLength;
1605 	if (offs > size)
1606 		return USBD_INVAL;
1607 
1608 #ifdef UAUDIO_MULTIPLE_ENDPOINTS
1609 	if (sync && id->bNumEndpoints <= 1) {
1610 		aprint_error_dev(sc->sc_dev,
1611 		    "a sync-pipe endpoint but no other endpoint\n");
1612 		return USBD_INVAL;
1613 	}
1614 #endif
1615 	if (!sync && id->bNumEndpoints > 1) {
1616 		aprint_error_dev(sc->sc_dev,
1617 		    "non sync-pipe endpoint but multiple endpoints\n");
1618 		return USBD_INVAL;
1619 	}
1620 	epdesc1 = NULL;
1621 	if (id->bNumEndpoints > 1) {
1622 		epdesc1 = (const void*)(tbuf + offs);
1623 		if (epdesc1->bDescriptorType != UDESC_ENDPOINT)
1624 			return USBD_INVAL;
1625 		DPRINTF(("uaudio_process_as: endpoint[1] bLength=%d "
1626 			 "bDescriptorType=%d bEndpointAddress=%d "
1627 			 "bmAttributes=0x%x wMaxPacketSize=%d bInterval=%d "
1628 			 "bRefresh=%d bSynchAddress=%d\n",
1629 			 epdesc1->bLength, epdesc1->bDescriptorType,
1630 			 epdesc1->bEndpointAddress, epdesc1->bmAttributes,
1631 			 UGETW(epdesc1->wMaxPacketSize), epdesc1->bInterval,
1632 			 epdesc1->bRefresh, epdesc1->bSynchAddress));
1633 		offs += epdesc1->bLength;
1634 		if (offs > size)
1635 			return USBD_INVAL;
1636 		if (epdesc1->bSynchAddress != 0) {
1637 			aprint_error_dev(sc->sc_dev,
1638 			    "invalid endpoint: bSynchAddress=0\n");
1639 			return USBD_INVAL;
1640 		}
1641 		if (UE_GET_XFERTYPE(epdesc1->bmAttributes) != UE_ISOCHRONOUS) {
1642 			aprint_error_dev(sc->sc_dev,
1643 			    "invalid endpoint: bmAttributes=0x%x\n",
1644 			     epdesc1->bmAttributes);
1645 			return USBD_INVAL;
1646 		}
1647 		if (epdesc1->bEndpointAddress != ed->bSynchAddress) {
1648 			aprint_error_dev(sc->sc_dev,
1649 			    "invalid endpoint addresses: "
1650 			    "ep[0]->bSynchAddress=0x%x "
1651 			    "ep[1]->bEndpointAddress=0x%x\n",
1652 			    ed->bSynchAddress, epdesc1->bEndpointAddress);
1653 			return USBD_INVAL;
1654 		}
1655 		/* UE_GET_ADDR(epdesc1->bEndpointAddress), and epdesc1->bRefresh */
1656 	}
1657 
1658 	format = UGETW(asid->wFormatTag);
1659 	chan = asf1d->bNrChannels;
1660 	prec = asf1d->bBitResolution;
1661 	if (prec != 8 && prec != 16 && prec != 24) {
1662 		aprint_error_dev(sc->sc_dev,
1663 		    "ignored setting with precision %d\n", prec);
1664 		return USBD_NORMAL_COMPLETION;
1665 	}
1666 	switch (format) {
1667 	case UA_FMT_PCM:
1668 		if (prec == 8) {
1669 			sc->sc_altflags |= HAS_8;
1670 		} else if (prec == 16) {
1671 			sc->sc_altflags |= HAS_16;
1672 		} else if (prec == 24) {
1673 			sc->sc_altflags |= HAS_24;
1674 		}
1675 		enc = AUDIO_ENCODING_SLINEAR_LE;
1676 		format_str = "pcm";
1677 		break;
1678 	case UA_FMT_PCM8:
1679 		enc = AUDIO_ENCODING_ULINEAR_LE;
1680 		sc->sc_altflags |= HAS_8U;
1681 		format_str = "pcm8";
1682 		break;
1683 	case UA_FMT_ALAW:
1684 		enc = AUDIO_ENCODING_ALAW;
1685 		sc->sc_altflags |= HAS_ALAW;
1686 		format_str = "alaw";
1687 		break;
1688 	case UA_FMT_MULAW:
1689 		enc = AUDIO_ENCODING_ULAW;
1690 		sc->sc_altflags |= HAS_MULAW;
1691 		format_str = "mulaw";
1692 		break;
1693 	case UA_FMT_IEEE_FLOAT:
1694 	default:
1695 		aprint_error_dev(sc->sc_dev,
1696 		    "ignored setting with format %d\n", format);
1697 		return USBD_NORMAL_COMPLETION;
1698 	}
1699 #ifdef UAUDIO_DEBUG
1700 	aprint_debug_dev(sc->sc_dev, "%s: %dch, %d/%dbit, %s,",
1701 	       dir == UE_DIR_IN ? "recording" : "playback",
1702 	       chan, prec, asf1d->bSubFrameSize * 8, format_str);
1703 	if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
1704 		aprint_debug(" %d-%dHz\n", UA_SAMP_LO(asf1d),
1705 		    UA_SAMP_HI(asf1d));
1706 	} else {
1707 		int r;
1708 		aprint_debug(" %d", UA_GETSAMP(asf1d, 0));
1709 		for (r = 1; r < asf1d->bSamFreqType; r++)
1710 			aprint_debug(",%d", UA_GETSAMP(asf1d, r));
1711 		aprint_debug("Hz\n");
1712 	}
1713 #endif
1714 	ai.alt = id->bAlternateSetting;
1715 	ai.encoding = enc;
1716 	ai.attributes = sed->bmAttributes;
1717 	ai.idesc = id;
1718 	ai.edesc = ed;
1719 	ai.edesc1 = epdesc1;
1720 	ai.asf1desc = asf1d;
1721 	ai.sc_busy = 0;
1722 	ai.aformat = NULL;
1723 	ai.ifaceh = NULL;
1724 	uaudio_add_alt(sc, &ai);
1725 #ifdef UAUDIO_DEBUG
1726 	if (ai.attributes & UA_SED_FREQ_CONTROL)
1727 		DPRINTFN(1, ("uaudio_process_as:  FREQ_CONTROL\n"));
1728 	if (ai.attributes & UA_SED_PITCH_CONTROL)
1729 		DPRINTFN(1, ("uaudio_process_as:  PITCH_CONTROL\n"));
1730 #endif
1731 	sc->sc_mode |= (dir == UE_DIR_OUT) ? AUMODE_PLAY : AUMODE_RECORD;
1732 
1733 	return USBD_NORMAL_COMPLETION;
1734 }
1735 #undef offs
1736 
1737 Static usbd_status
1738 uaudio_identify_as(struct uaudio_softc *sc,
1739 		   const usb_config_descriptor_t *cdesc)
1740 {
1741 	const usb_interface_descriptor_t *id;
1742 	const char *tbuf;
1743 	struct audio_format *auf;
1744 	const struct usb_audio_streaming_type1_descriptor *t1desc;
1745 	int size, offs;
1746 	int i, j;
1747 
1748 	size = UGETW(cdesc->wTotalLength);
1749 	tbuf = (const char *)cdesc;
1750 
1751 	/* Locate the AudioStreaming interface descriptor. */
1752 	offs = 0;
1753 	id = uaudio_find_iface(tbuf, size, &offs, UISUBCLASS_AUDIOSTREAM);
1754 	if (id == NULL)
1755 		return USBD_INVAL;
1756 
1757 	/* Loop through all the alternate settings. */
1758 	while (offs <= size) {
1759 		DPRINTFN(2, ("uaudio_identify: interface=%d offset=%d\n",
1760 		    id->bInterfaceNumber, offs));
1761 		switch (id->bNumEndpoints) {
1762 		case 0:
1763 			DPRINTFN(2, ("uaudio_identify: AS null alt=%d\n",
1764 				     id->bAlternateSetting));
1765 			sc->sc_nullalt = id->bAlternateSetting;
1766 			break;
1767 		case 1:
1768 #ifdef UAUDIO_MULTIPLE_ENDPOINTS
1769 		case 2:
1770 #endif
1771 			uaudio_process_as(sc, tbuf, &offs, size, id);
1772 			break;
1773 		default:
1774 			aprint_error_dev(sc->sc_dev,
1775 			    "ignored audio interface with %d endpoints\n",
1776 			     id->bNumEndpoints);
1777 			break;
1778 		}
1779 		id = uaudio_find_iface(tbuf, size, &offs,UISUBCLASS_AUDIOSTREAM);
1780 		if (id == NULL)
1781 			break;
1782 	}
1783 	if (offs > size)
1784 		return USBD_INVAL;
1785 	DPRINTF(("uaudio_identify_as: %d alts available\n", sc->sc_nalts));
1786 
1787 	if (sc->sc_mode == 0) {
1788 		aprint_error_dev(sc->sc_dev, "no usable endpoint found\n");
1789 		return USBD_INVAL;
1790 	}
1791 
1792 	/* build audio_format array */
1793 	sc->sc_formats = malloc(sizeof(struct audio_format) * sc->sc_nalts,
1794 				M_USBDEV, M_NOWAIT);
1795 	if (sc->sc_formats == NULL)
1796 		return USBD_NOMEM;
1797 	sc->sc_nformats = sc->sc_nalts;
1798 	for (i = 0; i < sc->sc_nalts; i++) {
1799 		auf = &sc->sc_formats[i];
1800 		t1desc = sc->sc_alts[i].asf1desc;
1801 		auf->driver_data = NULL;
1802 		if (UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress) == UE_DIR_OUT)
1803 			auf->mode = AUMODE_PLAY;
1804 		else
1805 			auf->mode = AUMODE_RECORD;
1806 		auf->encoding = sc->sc_alts[i].encoding;
1807 		auf->validbits = t1desc->bBitResolution;
1808 		auf->precision = t1desc->bSubFrameSize * 8;
1809 		auf->channels = t1desc->bNrChannels;
1810 		auf->channel_mask = sc->sc_channel_config;
1811 		auf->frequency_type = t1desc->bSamFreqType;
1812 		if (t1desc->bSamFreqType == UA_SAMP_CONTNUOUS) {
1813 			auf->frequency[0] = UA_SAMP_LO(t1desc);
1814 			auf->frequency[1] = UA_SAMP_HI(t1desc);
1815 		} else {
1816 			for (j = 0; j  < t1desc->bSamFreqType; j++) {
1817 				if (j >= AUFMT_MAX_FREQUENCIES) {
1818 					aprint_error("%s: please increase "
1819 					       "AUFMT_MAX_FREQUENCIES to %d\n",
1820 					       __func__, t1desc->bSamFreqType);
1821 					break;
1822 				}
1823 				auf->frequency[j] = UA_GETSAMP(t1desc, j);
1824 			}
1825 		}
1826 		sc->sc_alts[i].aformat = auf;
1827 	}
1828 
1829 	if (0 != auconv_create_encodings(sc->sc_formats, sc->sc_nformats,
1830 					 &sc->sc_encodings)) {
1831 		free(sc->sc_formats, M_DEVBUF);
1832 		sc->sc_formats = NULL;
1833 		return ENOMEM;
1834 	}
1835 
1836 	return USBD_NORMAL_COMPLETION;
1837 }
1838 
1839 Static usbd_status
1840 uaudio_identify_ac(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
1841 {
1842 	struct io_terminal* iot;
1843 	const usb_interface_descriptor_t *id;
1844 	const struct usb_audio_control_descriptor *acdp;
1845 	const uaudio_cs_descriptor_t *dp;
1846 	const struct usb_audio_output_terminal *pot;
1847 	struct terminal_list *tml;
1848 	const char *tbuf, *ibuf, *ibufend;
1849 	int size, offs, aclen, ndps, i, j;
1850 
1851 	size = UGETW(cdesc->wTotalLength);
1852 	tbuf = (const char *)cdesc;
1853 
1854 	/* Locate the AudioControl interface descriptor. */
1855 	offs = 0;
1856 	id = uaudio_find_iface(tbuf, size, &offs, UISUBCLASS_AUDIOCONTROL);
1857 	if (id == NULL)
1858 		return USBD_INVAL;
1859 	if (offs + sizeof *acdp > size)
1860 		return USBD_INVAL;
1861 	sc->sc_ac_iface = id->bInterfaceNumber;
1862 	DPRINTFN(2,("uaudio_identify_ac: AC interface is %d\n", sc->sc_ac_iface));
1863 
1864 	/* A class-specific AC interface header should follow. */
1865 	ibuf = tbuf + offs;
1866 	acdp = (const struct usb_audio_control_descriptor *)ibuf;
1867 	if (acdp->bDescriptorType != UDESC_CS_INTERFACE ||
1868 	    acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)
1869 		return USBD_INVAL;
1870 	aclen = UGETW(acdp->wTotalLength);
1871 	if (offs + aclen > size)
1872 		return USBD_INVAL;
1873 
1874 	if (!(usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_BAD_ADC) &&
1875 	     UGETW(acdp->bcdADC) != UAUDIO_VERSION)
1876 		return USBD_INVAL;
1877 
1878 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
1879 	DPRINTFN(2,("uaudio_identify_ac: found AC header, vers=%03x, len=%d\n",
1880 		 sc->sc_audio_rev, aclen));
1881 
1882 	sc->sc_nullalt = -1;
1883 
1884 	/* Scan through all the AC specific descriptors */
1885 	ibufend = ibuf + aclen;
1886 	dp = (const uaudio_cs_descriptor_t *)ibuf;
1887 	ndps = 0;
1888 	iot = malloc(sizeof(struct io_terminal) * 256, M_TEMP, M_NOWAIT | M_ZERO);
1889 	if (iot == NULL) {
1890 		aprint_error("%s: no memory\n", __func__);
1891 		return USBD_NOMEM;
1892 	}
1893 	for (;;) {
1894 		ibuf += dp->bLength;
1895 		if (ibuf >= ibufend)
1896 			break;
1897 		dp = (const uaudio_cs_descriptor_t *)ibuf;
1898 		if (ibuf + dp->bLength > ibufend) {
1899 			free(iot, M_TEMP);
1900 			return USBD_INVAL;
1901 		}
1902 		if (dp->bDescriptorType != UDESC_CS_INTERFACE) {
1903 			aprint_error(
1904 			    "uaudio_identify_ac: skip desc type=0x%02x\n",
1905 			    dp->bDescriptorType);
1906 			continue;
1907 		}
1908 		i = ((const struct usb_audio_input_terminal *)dp)->bTerminalId;
1909 		iot[i].d.desc = dp;
1910 		if (i > ndps)
1911 			ndps = i;
1912 	}
1913 	ndps++;
1914 
1915 	/* construct io_terminal */
1916 	for (i = 0; i < ndps; i++) {
1917 		dp = iot[i].d.desc;
1918 		if (dp == NULL)
1919 			continue;
1920 		if (dp->bDescriptorSubtype != UDESCSUB_AC_OUTPUT)
1921 			continue;
1922 		pot = iot[i].d.ot;
1923 		tml = uaudio_io_terminaltype(UGETW(pot->wTerminalType), iot, i);
1924 		if (tml != NULL)
1925 			free(tml, M_TEMP);
1926 	}
1927 
1928 #ifdef UAUDIO_DEBUG
1929 	for (i = 0; i < 256; i++) {
1930 		struct usb_audio_cluster cluster;
1931 
1932 		if (iot[i].d.desc == NULL)
1933 			continue;
1934 		logprintf("id %d:\t", i);
1935 		switch (iot[i].d.desc->bDescriptorSubtype) {
1936 		case UDESCSUB_AC_INPUT:
1937 			logprintf("AC_INPUT type=%s\n", uaudio_get_terminal_name
1938 				  (UGETW(iot[i].d.it->wTerminalType)));
1939 			logprintf("\t");
1940 			cluster = uaudio_get_cluster(i, iot);
1941 			uaudio_dump_cluster(&cluster);
1942 			logprintf("\n");
1943 			break;
1944 		case UDESCSUB_AC_OUTPUT:
1945 			logprintf("AC_OUTPUT type=%s ", uaudio_get_terminal_name
1946 				  (UGETW(iot[i].d.ot->wTerminalType)));
1947 			logprintf("src=%d\n", iot[i].d.ot->bSourceId);
1948 			break;
1949 		case UDESCSUB_AC_MIXER:
1950 			logprintf("AC_MIXER src=");
1951 			for (j = 0; j < iot[i].d.mu->bNrInPins; j++)
1952 				logprintf("%d ", iot[i].d.mu->baSourceId[j]);
1953 			logprintf("\n\t");
1954 			cluster = uaudio_get_cluster(i, iot);
1955 			uaudio_dump_cluster(&cluster);
1956 			logprintf("\n");
1957 			break;
1958 		case UDESCSUB_AC_SELECTOR:
1959 			logprintf("AC_SELECTOR src=");
1960 			for (j = 0; j < iot[i].d.su->bNrInPins; j++)
1961 				logprintf("%d ", iot[i].d.su->baSourceId[j]);
1962 			logprintf("\n");
1963 			break;
1964 		case UDESCSUB_AC_FEATURE:
1965 			logprintf("AC_FEATURE src=%d\n", iot[i].d.fu->bSourceId);
1966 			break;
1967 		case UDESCSUB_AC_PROCESSING:
1968 			logprintf("AC_PROCESSING src=");
1969 			for (j = 0; j < iot[i].d.pu->bNrInPins; j++)
1970 				logprintf("%d ", iot[i].d.pu->baSourceId[j]);
1971 			logprintf("\n\t");
1972 			cluster = uaudio_get_cluster(i, iot);
1973 			uaudio_dump_cluster(&cluster);
1974 			logprintf("\n");
1975 			break;
1976 		case UDESCSUB_AC_EXTENSION:
1977 			logprintf("AC_EXTENSION src=");
1978 			for (j = 0; j < iot[i].d.eu->bNrInPins; j++)
1979 				logprintf("%d ", iot[i].d.eu->baSourceId[j]);
1980 			logprintf("\n\t");
1981 			cluster = uaudio_get_cluster(i, iot);
1982 			uaudio_dump_cluster(&cluster);
1983 			logprintf("\n");
1984 			break;
1985 		default:
1986 			logprintf("unknown audio control (subtype=%d)\n",
1987 				  iot[i].d.desc->bDescriptorSubtype);
1988 		}
1989 		for (j = 0; j < iot[i].inputs_size; j++) {
1990 			int k;
1991 			logprintf("\tinput%d: ", j);
1992 			tml = iot[i].inputs[j];
1993 			if (tml == NULL) {
1994 				logprintf("NULL\n");
1995 				continue;
1996 			}
1997 			for (k = 0; k < tml->size; k++)
1998 				logprintf("%s ", uaudio_get_terminal_name
1999 					  (tml->terminals[k]));
2000 			logprintf("\n");
2001 		}
2002 		logprintf("\toutput: ");
2003 		tml = iot[i].output;
2004 		for (j = 0; j < tml->size; j++)
2005 			logprintf("%s ", uaudio_get_terminal_name(tml->terminals[j]));
2006 		logprintf("\n");
2007 	}
2008 #endif
2009 
2010 	for (i = 0; i < ndps; i++) {
2011 		dp = iot[i].d.desc;
2012 		if (dp == NULL)
2013 			continue;
2014 		DPRINTF(("uaudio_identify_ac: id=%d subtype=%d\n",
2015 			 i, dp->bDescriptorSubtype));
2016 		switch (dp->bDescriptorSubtype) {
2017 		case UDESCSUB_AC_HEADER:
2018 			aprint_error("uaudio_identify_ac: unexpected AC header\n");
2019 			break;
2020 		case UDESCSUB_AC_INPUT:
2021 			uaudio_add_input(sc, iot, i);
2022 			break;
2023 		case UDESCSUB_AC_OUTPUT:
2024 			uaudio_add_output(sc, iot, i);
2025 			break;
2026 		case UDESCSUB_AC_MIXER:
2027 			uaudio_add_mixer(sc, iot, i);
2028 			break;
2029 		case UDESCSUB_AC_SELECTOR:
2030 			uaudio_add_selector(sc, iot, i);
2031 			break;
2032 		case UDESCSUB_AC_FEATURE:
2033 			uaudio_add_feature(sc, iot, i);
2034 			break;
2035 		case UDESCSUB_AC_PROCESSING:
2036 			uaudio_add_processing(sc, iot, i);
2037 			break;
2038 		case UDESCSUB_AC_EXTENSION:
2039 			uaudio_add_extension(sc, iot, i);
2040 			break;
2041 		default:
2042 			aprint_error(
2043 			    "uaudio_identify_ac: bad AC desc subtype=0x%02x\n",
2044 			    dp->bDescriptorSubtype);
2045 			break;
2046 		}
2047 	}
2048 
2049 	/* delete io_terminal */
2050 	for (i = 0; i < 256; i++) {
2051 		if (iot[i].d.desc == NULL)
2052 			continue;
2053 		if (iot[i].inputs != NULL) {
2054 			for (j = 0; j < iot[i].inputs_size; j++) {
2055 				if (iot[i].inputs[j] != NULL)
2056 					free(iot[i].inputs[j], M_TEMP);
2057 			}
2058 			free(iot[i].inputs, M_TEMP);
2059 		}
2060 		if (iot[i].output != NULL)
2061 			free(iot[i].output, M_TEMP);
2062 		iot[i].d.desc = NULL;
2063 	}
2064 	free(iot, M_TEMP);
2065 
2066 	return USBD_NORMAL_COMPLETION;
2067 }
2068 
2069 Static int
2070 uaudio_query_devinfo(void *addr, mixer_devinfo_t *mi)
2071 {
2072 	struct uaudio_softc *sc;
2073 	struct mixerctl *mc;
2074 	int n, nctls, i;
2075 
2076 	DPRINTFN(2,("uaudio_query_devinfo: index=%d\n", mi->index));
2077 	sc = addr;
2078 	if (sc->sc_dying)
2079 		return EIO;
2080 
2081 	n = mi->index;
2082 	nctls = sc->sc_nctls;
2083 
2084 	switch (n) {
2085 	case UAC_OUTPUT:
2086 		mi->type = AUDIO_MIXER_CLASS;
2087 		mi->mixer_class = UAC_OUTPUT;
2088 		mi->next = mi->prev = AUDIO_MIXER_LAST;
2089 		strlcpy(mi->label.name, AudioCoutputs, sizeof(mi->label.name));
2090 		return 0;
2091 	case UAC_INPUT:
2092 		mi->type = AUDIO_MIXER_CLASS;
2093 		mi->mixer_class = UAC_INPUT;
2094 		mi->next = mi->prev = AUDIO_MIXER_LAST;
2095 		strlcpy(mi->label.name, AudioCinputs, sizeof(mi->label.name));
2096 		return 0;
2097 	case UAC_EQUAL:
2098 		mi->type = AUDIO_MIXER_CLASS;
2099 		mi->mixer_class = UAC_EQUAL;
2100 		mi->next = mi->prev = AUDIO_MIXER_LAST;
2101 		strlcpy(mi->label.name, AudioCequalization,
2102 		    sizeof(mi->label.name));
2103 		return 0;
2104 	case UAC_RECORD:
2105 		mi->type = AUDIO_MIXER_CLASS;
2106 		mi->mixer_class = UAC_RECORD;
2107 		mi->next = mi->prev = AUDIO_MIXER_LAST;
2108 		strlcpy(mi->label.name, AudioCrecord, sizeof(mi->label.name));
2109 		return 0;
2110 	default:
2111 		break;
2112 	}
2113 
2114 	n -= UAC_NCLASSES;
2115 	if (n < 0 || n >= nctls)
2116 		return ENXIO;
2117 
2118 	mc = &sc->sc_ctls[n];
2119 	strlcpy(mi->label.name, mc->ctlname, sizeof(mi->label.name));
2120 	mi->mixer_class = mc->class;
2121 	mi->next = mi->prev = AUDIO_MIXER_LAST;	/* XXX */
2122 	switch (mc->type) {
2123 	case MIX_ON_OFF:
2124 		mi->type = AUDIO_MIXER_ENUM;
2125 		mi->un.e.num_mem = 2;
2126 		strlcpy(mi->un.e.member[0].label.name, AudioNoff,
2127 		    sizeof(mi->un.e.member[0].label.name));
2128 		mi->un.e.member[0].ord = 0;
2129 		strlcpy(mi->un.e.member[1].label.name, AudioNon,
2130 		    sizeof(mi->un.e.member[1].label.name));
2131 		mi->un.e.member[1].ord = 1;
2132 		break;
2133 	case MIX_SELECTOR:
2134 		mi->type = AUDIO_MIXER_ENUM;
2135 		mi->un.e.num_mem = mc->maxval - mc->minval + 1;
2136 		for (i = 0; i <= mc->maxval - mc->minval; i++) {
2137 			snprintf(mi->un.e.member[i].label.name,
2138 				 sizeof(mi->un.e.member[i].label.name),
2139 				 "%d", i + mc->minval);
2140 			mi->un.e.member[i].ord = i + mc->minval;
2141 		}
2142 		break;
2143 	default:
2144 		mi->type = AUDIO_MIXER_VALUE;
2145 		strncpy(mi->un.v.units.name, mc->ctlunit, MAX_AUDIO_DEV_LEN);
2146 		mi->un.v.num_channels = mc->nchan;
2147 		mi->un.v.delta = mc->delta;
2148 		break;
2149 	}
2150 	return 0;
2151 }
2152 
2153 Static int
2154 uaudio_open(void *addr, int flags)
2155 {
2156 	struct uaudio_softc *sc;
2157 
2158 	sc = addr;
2159 	DPRINTF(("uaudio_open: sc=%p\n", sc));
2160 	if (sc->sc_dying)
2161 		return EIO;
2162 
2163 	if ((flags & FWRITE) && !(sc->sc_mode & AUMODE_PLAY))
2164 		return EACCES;
2165 	if ((flags & FREAD) && !(sc->sc_mode & AUMODE_RECORD))
2166 		return EACCES;
2167 
2168 	return 0;
2169 }
2170 
2171 /*
2172  * Close function is called at splaudio().
2173  */
2174 Static void
2175 uaudio_close(void *addr)
2176 {
2177 }
2178 
2179 Static int
2180 uaudio_drain(void *addr)
2181 {
2182 	struct uaudio_softc *sc;
2183 
2184 	sc = addr;
2185 	usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
2186 
2187 	return 0;
2188 }
2189 
2190 Static int
2191 uaudio_halt_out_dma(void *addr)
2192 {
2193 	struct uaudio_softc *sc;
2194 
2195 	DPRINTF(("uaudio_halt_out_dma: enter\n"));
2196 	sc = addr;
2197 	if (sc->sc_playchan.pipe != NULL) {
2198 		uaudio_chan_close(sc, &sc->sc_playchan);
2199 		sc->sc_playchan.pipe = NULL;
2200 		uaudio_chan_free_buffers(sc, &sc->sc_playchan);
2201 		sc->sc_playchan.intr = NULL;
2202 	}
2203 	return 0;
2204 }
2205 
2206 Static int
2207 uaudio_halt_in_dma(void *addr)
2208 {
2209 	struct uaudio_softc *sc;
2210 
2211 	DPRINTF(("uaudio_halt_in_dma: enter\n"));
2212 	sc = addr;
2213 	if (sc->sc_recchan.pipe != NULL) {
2214 		uaudio_chan_close(sc, &sc->sc_recchan);
2215 		sc->sc_recchan.pipe = NULL;
2216 		uaudio_chan_free_buffers(sc, &sc->sc_recchan);
2217 		sc->sc_recchan.intr = NULL;
2218 	}
2219 	return 0;
2220 }
2221 
2222 Static int
2223 uaudio_getdev(void *addr, struct audio_device *retp)
2224 {
2225 	struct uaudio_softc *sc;
2226 
2227 	DPRINTF(("uaudio_mixer_getdev:\n"));
2228 	sc = addr;
2229 	if (sc->sc_dying)
2230 		return EIO;
2231 
2232 	*retp = uaudio_device;
2233 	return 0;
2234 }
2235 
2236 /*
2237  * Make sure the block size is large enough to hold all outstanding transfers.
2238  */
2239 Static int
2240 uaudio_round_blocksize(void *addr, int blk,
2241 		       int mode, const audio_params_t *param)
2242 {
2243 	struct uaudio_softc *sc;
2244 	int b;
2245 
2246 	sc = addr;
2247 	DPRINTF(("uaudio_round_blocksize: blk=%d mode=%s\n", blk,
2248 	    mode == AUMODE_PLAY ? "AUMODE_PLAY" : "AUMODE_RECORD"));
2249 
2250 	/* chan.bytes_per_frame can be 0. */
2251 	if (mode == AUMODE_PLAY || sc->sc_recchan.bytes_per_frame <= 0) {
2252 		b = param->sample_rate * UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
2253 
2254 		/*
2255 		 * This does not make accurate value in the case
2256 		 * of b % USB_FRAMES_PER_SECOND != 0
2257 		 */
2258 		b /= USB_FRAMES_PER_SECOND;
2259 
2260 		b *= param->precision / 8 * param->channels;
2261 	} else {
2262 		/*
2263 		 * use wMaxPacketSize in bytes_per_frame.
2264 		 * See uaudio_set_params() and uaudio_chan_init()
2265 		 */
2266 		b = sc->sc_recchan.bytes_per_frame
2267 		    * UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
2268 	}
2269 
2270 	if (b <= 0)
2271 		b = 1;
2272 	blk = blk <= b ? b : blk / b * b;
2273 
2274 #ifdef DIAGNOSTIC
2275 	if (blk <= 0) {
2276 		aprint_debug("uaudio_round_blocksize: blk=%d\n", blk);
2277 		blk = 512;
2278 	}
2279 #endif
2280 
2281 	DPRINTF(("uaudio_round_blocksize: resultant blk=%d\n", blk));
2282 	return blk;
2283 }
2284 
2285 Static int
2286 uaudio_get_props(void *addr)
2287 {
2288 	return AUDIO_PROP_FULLDUPLEX | AUDIO_PROP_INDEPENDENT;
2289 
2290 }
2291 
2292 Static int
2293 uaudio_get(struct uaudio_softc *sc, int which, int type, int wValue,
2294 	   int wIndex, int len)
2295 {
2296 	usb_device_request_t req;
2297 	u_int8_t data[4];
2298 	usbd_status err;
2299 	int val;
2300 
2301 	if (wValue == -1)
2302 		return 0;
2303 
2304 	req.bmRequestType = type;
2305 	req.bRequest = which;
2306 	USETW(req.wValue, wValue);
2307 	USETW(req.wIndex, wIndex);
2308 	USETW(req.wLength, len);
2309 	DPRINTFN(2,("uaudio_get: type=0x%02x req=0x%02x wValue=0x%04x "
2310 		    "wIndex=0x%04x len=%d\n",
2311 		    type, which, wValue, wIndex, len));
2312 	err = usbd_do_request(sc->sc_udev, &req, data);
2313 	if (err) {
2314 		DPRINTF(("uaudio_get: err=%s\n", usbd_errstr(err)));
2315 		return -1;
2316 	}
2317 	switch (len) {
2318 	case 1:
2319 		val = data[0];
2320 		break;
2321 	case 2:
2322 		val = data[0] | (data[1] << 8);
2323 		break;
2324 	default:
2325 		DPRINTF(("uaudio_get: bad length=%d\n", len));
2326 		return -1;
2327 	}
2328 	DPRINTFN(2,("uaudio_get: val=%d\n", val));
2329 	return val;
2330 }
2331 
2332 Static void
2333 uaudio_set(struct uaudio_softc *sc, int which, int type, int wValue,
2334 	   int wIndex, int len, int val)
2335 {
2336 	usb_device_request_t req;
2337 	u_int8_t data[4];
2338 	usbd_status err;
2339 
2340 	if (wValue == -1)
2341 		return;
2342 
2343 	req.bmRequestType = type;
2344 	req.bRequest = which;
2345 	USETW(req.wValue, wValue);
2346 	USETW(req.wIndex, wIndex);
2347 	USETW(req.wLength, len);
2348 	switch (len) {
2349 	case 1:
2350 		data[0] = val;
2351 		break;
2352 	case 2:
2353 		data[0] = val;
2354 		data[1] = val >> 8;
2355 		break;
2356 	default:
2357 		return;
2358 	}
2359 	DPRINTFN(2,("uaudio_set: type=0x%02x req=0x%02x wValue=0x%04x "
2360 		    "wIndex=0x%04x len=%d, val=%d\n",
2361 		    type, which, wValue, wIndex, len, val & 0xffff));
2362 	err = usbd_do_request(sc->sc_udev, &req, data);
2363 #ifdef UAUDIO_DEBUG
2364 	if (err)
2365 		DPRINTF(("uaudio_set: err=%d\n", err));
2366 #endif
2367 }
2368 
2369 Static int
2370 uaudio_signext(int type, int val)
2371 {
2372 	if (!MIX_UNSIGNED(type)) {
2373 		if (MIX_SIZE(type) == 2)
2374 			val = (int16_t)val;
2375 		else
2376 			val = (int8_t)val;
2377 	}
2378 	return val;
2379 }
2380 
2381 Static int
2382 uaudio_value2bsd(struct mixerctl *mc, int val)
2383 {
2384 	DPRINTFN(5, ("uaudio_value2bsd: type=%03x val=%d min=%d max=%d ",
2385 		     mc->type, val, mc->minval, mc->maxval));
2386 	if (mc->type == MIX_ON_OFF) {
2387 		val = (val != 0);
2388 	} else if (mc->type == MIX_SELECTOR) {
2389 		if (val < mc->minval || val > mc->maxval)
2390 			val = mc->minval;
2391 	} else
2392 		val = ((uaudio_signext(mc->type, val) - mc->minval) * 255
2393 			+ mc->mul/2) / mc->mul;
2394 	DPRINTFN(5, ("val'=%d\n", val));
2395 	return val;
2396 }
2397 
2398 int
2399 uaudio_bsd2value(struct mixerctl *mc, int val)
2400 {
2401 	DPRINTFN(5,("uaudio_bsd2value: type=%03x val=%d min=%d max=%d ",
2402 		    mc->type, val, mc->minval, mc->maxval));
2403 	if (mc->type == MIX_ON_OFF) {
2404 		val = (val != 0);
2405 	} else if (mc->type == MIX_SELECTOR) {
2406 		if (val < mc->minval || val > mc->maxval)
2407 			val = mc->minval;
2408 	} else
2409 		val = (val + mc->delta/2) * mc->mul / 255 + mc->minval;
2410 	DPRINTFN(5, ("val'=%d\n", val));
2411 	return val;
2412 }
2413 
2414 Static int
2415 uaudio_ctl_get(struct uaudio_softc *sc, int which, struct mixerctl *mc,
2416 	       int chan)
2417 {
2418 	int val;
2419 
2420 	DPRINTFN(5,("uaudio_ctl_get: which=%d chan=%d\n", which, chan));
2421 	val = uaudio_get(sc, which, UT_READ_CLASS_INTERFACE, mc->wValue[chan],
2422 			 mc->wIndex, MIX_SIZE(mc->type));
2423 	return uaudio_value2bsd(mc, val);
2424 }
2425 
2426 Static void
2427 uaudio_ctl_set(struct uaudio_softc *sc, int which, struct mixerctl *mc,
2428 	       int chan, int val)
2429 {
2430 	val = uaudio_bsd2value(mc, val);
2431 	uaudio_set(sc, which, UT_WRITE_CLASS_INTERFACE, mc->wValue[chan],
2432 		   mc->wIndex, MIX_SIZE(mc->type), val);
2433 }
2434 
2435 Static int
2436 uaudio_mixer_get_port(void *addr, mixer_ctrl_t *cp)
2437 {
2438 	struct uaudio_softc *sc;
2439 	struct mixerctl *mc;
2440 	int i, n, vals[MIX_MAX_CHAN], val;
2441 
2442 	DPRINTFN(2,("uaudio_mixer_get_port: index=%d\n", cp->dev));
2443 	sc = addr;
2444 	if (sc->sc_dying)
2445 		return EIO;
2446 
2447 	n = cp->dev - UAC_NCLASSES;
2448 	if (n < 0 || n >= sc->sc_nctls)
2449 		return ENXIO;
2450 	mc = &sc->sc_ctls[n];
2451 
2452 	if (mc->type == MIX_ON_OFF) {
2453 		if (cp->type != AUDIO_MIXER_ENUM)
2454 			return EINVAL;
2455 		cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
2456 	} else if (mc->type == MIX_SELECTOR) {
2457 		if (cp->type != AUDIO_MIXER_ENUM)
2458 			return EINVAL;
2459 		cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
2460 	} else {
2461 		if (cp->type != AUDIO_MIXER_VALUE)
2462 			return EINVAL;
2463 		if (cp->un.value.num_channels != 1 &&
2464 		    cp->un.value.num_channels != mc->nchan)
2465 			return EINVAL;
2466 		for (i = 0; i < mc->nchan; i++)
2467 			vals[i] = uaudio_ctl_get(sc, GET_CUR, mc, i);
2468 		if (cp->un.value.num_channels == 1 && mc->nchan != 1) {
2469 			for (val = 0, i = 0; i < mc->nchan; i++)
2470 				val += vals[i];
2471 			vals[0] = val / mc->nchan;
2472 		}
2473 		for (i = 0; i < cp->un.value.num_channels; i++)
2474 			cp->un.value.level[i] = vals[i];
2475 	}
2476 
2477 	return 0;
2478 }
2479 
2480 Static int
2481 uaudio_mixer_set_port(void *addr, mixer_ctrl_t *cp)
2482 {
2483 	struct uaudio_softc *sc;
2484 	struct mixerctl *mc;
2485 	int i, n, vals[MIX_MAX_CHAN];
2486 
2487 	DPRINTFN(2,("uaudio_mixer_set_port: index = %d\n", cp->dev));
2488 	sc = addr;
2489 	if (sc->sc_dying)
2490 		return EIO;
2491 
2492 	n = cp->dev - UAC_NCLASSES;
2493 	if (n < 0 || n >= sc->sc_nctls)
2494 		return ENXIO;
2495 	mc = &sc->sc_ctls[n];
2496 
2497 	if (mc->type == MIX_ON_OFF) {
2498 		if (cp->type != AUDIO_MIXER_ENUM)
2499 			return EINVAL;
2500 		uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
2501 	} else if (mc->type == MIX_SELECTOR) {
2502 		if (cp->type != AUDIO_MIXER_ENUM)
2503 			return EINVAL;
2504 		uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
2505 	} else {
2506 		if (cp->type != AUDIO_MIXER_VALUE)
2507 			return EINVAL;
2508 		if (cp->un.value.num_channels == 1)
2509 			for (i = 0; i < mc->nchan; i++)
2510 				vals[i] = cp->un.value.level[0];
2511 		else if (cp->un.value.num_channels == mc->nchan)
2512 			for (i = 0; i < mc->nchan; i++)
2513 				vals[i] = cp->un.value.level[i];
2514 		else
2515 			return EINVAL;
2516 		for (i = 0; i < mc->nchan; i++)
2517 			uaudio_ctl_set(sc, SET_CUR, mc, i, vals[i]);
2518 	}
2519 	return 0;
2520 }
2521 
2522 Static int
2523 uaudio_trigger_input(void *addr, void *start, void *end, int blksize,
2524 		     void (*intr)(void *), void *arg,
2525 		     const audio_params_t *param)
2526 {
2527 	struct uaudio_softc *sc;
2528 	struct chan *ch;
2529 	usbd_status err;
2530 	int i, s;
2531 
2532 	sc = addr;
2533 	if (sc->sc_dying)
2534 		return EIO;
2535 
2536 	DPRINTFN(3,("uaudio_trigger_input: sc=%p start=%p end=%p "
2537 		    "blksize=%d\n", sc, start, end, blksize));
2538 	ch = &sc->sc_recchan;
2539 	uaudio_chan_set_param(ch, start, end, blksize);
2540 	DPRINTFN(3,("uaudio_trigger_input: sample_size=%d bytes/frame=%d "
2541 		    "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
2542 		    ch->fraction));
2543 
2544 	err = uaudio_chan_alloc_buffers(sc, ch);
2545 	if (err)
2546 		return EIO;
2547 
2548 	err = uaudio_chan_open(sc, ch);
2549 	if (err) {
2550 		uaudio_chan_free_buffers(sc, ch);
2551 		return EIO;
2552 	}
2553 
2554 	ch->intr = intr;
2555 	ch->arg = arg;
2556 
2557 	s = splusb();
2558 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX -1 shouldn't be needed */
2559 		uaudio_chan_rtransfer(ch);
2560 	splx(s);
2561 
2562 	return 0;
2563 }
2564 
2565 Static int
2566 uaudio_trigger_output(void *addr, void *start, void *end, int blksize,
2567 		      void (*intr)(void *), void *arg,
2568 		      const audio_params_t *param)
2569 {
2570 	struct uaudio_softc *sc;
2571 	struct chan *ch;
2572 	usbd_status err;
2573 	int i, s;
2574 
2575 	sc = addr;
2576 	if (sc->sc_dying)
2577 		return EIO;
2578 
2579 	DPRINTFN(3,("uaudio_trigger_output: sc=%p start=%p end=%p "
2580 		    "blksize=%d\n", sc, start, end, blksize));
2581 	ch = &sc->sc_playchan;
2582 	uaudio_chan_set_param(ch, start, end, blksize);
2583 	DPRINTFN(3,("uaudio_trigger_output: sample_size=%d bytes/frame=%d "
2584 		    "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
2585 		    ch->fraction));
2586 
2587 	err = uaudio_chan_alloc_buffers(sc, ch);
2588 	if (err)
2589 		return EIO;
2590 
2591 	err = uaudio_chan_open(sc, ch);
2592 	if (err) {
2593 		uaudio_chan_free_buffers(sc, ch);
2594 		return EIO;
2595 	}
2596 
2597 	ch->intr = intr;
2598 	ch->arg = arg;
2599 
2600 	s = splusb();
2601 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX */
2602 		uaudio_chan_ptransfer(ch);
2603 	splx(s);
2604 
2605 	return 0;
2606 }
2607 
2608 /* Set up a pipe for a channel. */
2609 Static usbd_status
2610 uaudio_chan_open(struct uaudio_softc *sc, struct chan *ch)
2611 {
2612 	struct as_info *as;
2613 	int endpt;
2614 	usbd_status err;
2615 
2616 	as = &sc->sc_alts[ch->altidx];
2617 	endpt = as->edesc->bEndpointAddress;
2618 	DPRINTF(("uaudio_chan_open: endpt=0x%02x, speed=%d, alt=%d\n",
2619 		 endpt, ch->sample_rate, as->alt));
2620 
2621 	/* Set alternate interface corresponding to the mode. */
2622 	err = usbd_set_interface(as->ifaceh, as->alt);
2623 	if (err)
2624 		return err;
2625 
2626 	/*
2627 	 * If just one sampling rate is supported,
2628 	 * no need to call uaudio_set_speed().
2629 	 * Roland SD-90 freezes by a SAMPLING_FREQ_CONTROL request.
2630 	 */
2631 	if (as->asf1desc->bSamFreqType != 1) {
2632 		err = uaudio_set_speed(sc, endpt, ch->sample_rate);
2633 		if (err) {
2634 			DPRINTF(("uaudio_chan_open: set_speed failed err=%s\n",
2635 				 usbd_errstr(err)));
2636 		}
2637 	}
2638 
2639 	ch->pipe = 0;
2640 	ch->sync_pipe = 0;
2641 	DPRINTF(("uaudio_chan_open: create pipe to 0x%02x\n", endpt));
2642 	err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->pipe);
2643 	if (err)
2644 		return err;
2645 	if (as->edesc1 != NULL) {
2646 		endpt = as->edesc1->bEndpointAddress;
2647 		DPRINTF(("uaudio_chan_open: create sync-pipe to 0x%02x\n", endpt));
2648 		err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->sync_pipe);
2649 	}
2650 	return err;
2651 }
2652 
2653 Static void
2654 uaudio_chan_close(struct uaudio_softc *sc, struct chan *ch)
2655 {
2656 	struct as_info *as;
2657 
2658 	as = &sc->sc_alts[ch->altidx];
2659 	as->sc_busy = 0;
2660 	AUFMT_VALIDATE(as->aformat);
2661 	if (sc->sc_nullalt >= 0) {
2662 		DPRINTF(("uaudio_chan_close: set null alt=%d\n",
2663 			 sc->sc_nullalt));
2664 		usbd_set_interface(as->ifaceh, sc->sc_nullalt);
2665 	}
2666 	if (ch->pipe) {
2667 		usbd_abort_pipe(ch->pipe);
2668 		usbd_close_pipe(ch->pipe);
2669 	}
2670 	if (ch->sync_pipe) {
2671 		usbd_abort_pipe(ch->sync_pipe);
2672 		usbd_close_pipe(ch->sync_pipe);
2673 	}
2674 }
2675 
2676 Static usbd_status
2677 uaudio_chan_alloc_buffers(struct uaudio_softc *sc, struct chan *ch)
2678 {
2679 	usbd_xfer_handle xfer;
2680 	void *tbuf;
2681 	int i, size;
2682 
2683 	size = (ch->bytes_per_frame + ch->sample_size) * UAUDIO_NFRAMES;
2684 	for (i = 0; i < UAUDIO_NCHANBUFS; i++) {
2685 		xfer = usbd_alloc_xfer(sc->sc_udev);
2686 		if (xfer == 0)
2687 			goto bad;
2688 		ch->chanbufs[i].xfer = xfer;
2689 		tbuf = usbd_alloc_buffer(xfer, size);
2690 		if (tbuf == 0) {
2691 			i++;
2692 			goto bad;
2693 		}
2694 		ch->chanbufs[i].buffer = tbuf;
2695 		ch->chanbufs[i].chan = ch;
2696 	}
2697 
2698 	return USBD_NORMAL_COMPLETION;
2699 
2700 bad:
2701 	while (--i >= 0)
2702 		/* implicit buffer free */
2703 		usbd_free_xfer(ch->chanbufs[i].xfer);
2704 	return USBD_NOMEM;
2705 }
2706 
2707 Static void
2708 uaudio_chan_free_buffers(struct uaudio_softc *sc, struct chan *ch)
2709 {
2710 	int i;
2711 
2712 	for (i = 0; i < UAUDIO_NCHANBUFS; i++)
2713 		usbd_free_xfer(ch->chanbufs[i].xfer);
2714 }
2715 
2716 /* Called at splusb() */
2717 Static void
2718 uaudio_chan_ptransfer(struct chan *ch)
2719 {
2720 	struct chanbuf *cb;
2721 	int i, n, size, residue, total;
2722 
2723 	if (ch->sc->sc_dying)
2724 		return;
2725 
2726 	/* Pick the next channel buffer. */
2727 	cb = &ch->chanbufs[ch->curchanbuf];
2728 	if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
2729 		ch->curchanbuf = 0;
2730 
2731 	/* Compute the size of each frame in the next transfer. */
2732 	residue = ch->residue;
2733 	total = 0;
2734 	for (i = 0; i < UAUDIO_NFRAMES; i++) {
2735 		size = ch->bytes_per_frame;
2736 		residue += ch->fraction;
2737 		if (residue >= USB_FRAMES_PER_SECOND) {
2738 			if ((ch->sc->sc_altflags & UA_NOFRAC) == 0)
2739 				size += ch->sample_size;
2740 			residue -= USB_FRAMES_PER_SECOND;
2741 		}
2742 		cb->sizes[i] = size;
2743 		total += size;
2744 	}
2745 	ch->residue = residue;
2746 	cb->size = total;
2747 
2748 	/*
2749 	 * Transfer data from upper layer buffer to channel buffer, taking
2750 	 * care of wrapping the upper layer buffer.
2751 	 */
2752 	n = min(total, ch->end - ch->cur);
2753 	memcpy(cb->buffer, ch->cur, n);
2754 	ch->cur += n;
2755 	if (ch->cur >= ch->end)
2756 		ch->cur = ch->start;
2757 	if (total > n) {
2758 		total -= n;
2759 		memcpy(cb->buffer + n, ch->cur, total);
2760 		ch->cur += total;
2761 	}
2762 
2763 #ifdef UAUDIO_DEBUG
2764 	if (uaudiodebug > 8) {
2765 		DPRINTF(("uaudio_chan_ptransfer: buffer=%p, residue=0.%03d\n",
2766 			 cb->buffer, ch->residue));
2767 		for (i = 0; i < UAUDIO_NFRAMES; i++) {
2768 			DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
2769 		}
2770 	}
2771 #endif
2772 
2773 	DPRINTFN(5,("uaudio_chan_transfer: ptransfer xfer=%p\n", cb->xfer));
2774 	/* Fill the request */
2775 	usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
2776 			     UAUDIO_NFRAMES, USBD_NO_COPY,
2777 			     uaudio_chan_pintr);
2778 
2779 	(void)usbd_transfer(cb->xfer);
2780 }
2781 
2782 Static void
2783 uaudio_chan_pintr(usbd_xfer_handle xfer, usbd_private_handle priv,
2784 		  usbd_status status)
2785 {
2786 	struct chanbuf *cb;
2787 	struct chan *ch;
2788 	uint32_t count;
2789 	int s;
2790 
2791 	cb = priv;
2792 	ch = cb->chan;
2793 	/* Return if we are aborting. */
2794 	if (status == USBD_CANCELLED)
2795 		return;
2796 
2797 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
2798 	DPRINTFN(5,("uaudio_chan_pintr: count=%d, transferred=%d\n",
2799 		    count, ch->transferred));
2800 #ifdef DIAGNOSTIC
2801 	if (count != cb->size) {
2802 		aprint_error("uaudio_chan_pintr: count(%d) != size(%d)\n",
2803 		       count, cb->size);
2804 	}
2805 #endif
2806 
2807 	ch->transferred += cb->size;
2808 	s = splaudio();
2809 	/* Call back to upper layer */
2810 	while (ch->transferred >= ch->blksize) {
2811 		ch->transferred -= ch->blksize;
2812 		DPRINTFN(5,("uaudio_chan_pintr: call %p(%p)\n",
2813 			    ch->intr, ch->arg));
2814 		ch->intr(ch->arg);
2815 	}
2816 	splx(s);
2817 
2818 	/* start next transfer */
2819 	uaudio_chan_ptransfer(ch);
2820 }
2821 
2822 /* Called at splusb() */
2823 Static void
2824 uaudio_chan_rtransfer(struct chan *ch)
2825 {
2826 	struct chanbuf *cb;
2827 	int i, size, residue, total;
2828 
2829 	if (ch->sc->sc_dying)
2830 		return;
2831 
2832 	/* Pick the next channel buffer. */
2833 	cb = &ch->chanbufs[ch->curchanbuf];
2834 	if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
2835 		ch->curchanbuf = 0;
2836 
2837 	/* Compute the size of each frame in the next transfer. */
2838 	residue = ch->residue;
2839 	total = 0;
2840 	for (i = 0; i < UAUDIO_NFRAMES; i++) {
2841 		size = ch->bytes_per_frame;
2842 		cb->sizes[i] = size;
2843 		cb->offsets[i] = total;
2844 		total += size;
2845 	}
2846 	ch->residue = residue;
2847 	cb->size = total;
2848 
2849 #ifdef UAUDIO_DEBUG
2850 	if (uaudiodebug > 8) {
2851 		DPRINTF(("uaudio_chan_rtransfer: buffer=%p, residue=0.%03d\n",
2852 			 cb->buffer, ch->residue));
2853 		for (i = 0; i < UAUDIO_NFRAMES; i++) {
2854 			DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
2855 		}
2856 	}
2857 #endif
2858 
2859 	DPRINTFN(5,("uaudio_chan_rtransfer: transfer xfer=%p\n", cb->xfer));
2860 	/* Fill the request */
2861 	usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
2862 			     UAUDIO_NFRAMES, USBD_NO_COPY,
2863 			     uaudio_chan_rintr);
2864 
2865 	(void)usbd_transfer(cb->xfer);
2866 }
2867 
2868 Static void
2869 uaudio_chan_rintr(usbd_xfer_handle xfer, usbd_private_handle priv,
2870 		  usbd_status status)
2871 {
2872 	struct chanbuf *cb;
2873 	struct chan *ch;
2874 	uint32_t count;
2875 	int s, i, n, frsize;
2876 
2877 	cb = priv;
2878 	ch = cb->chan;
2879 	/* Return if we are aborting. */
2880 	if (status == USBD_CANCELLED)
2881 		return;
2882 
2883 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
2884 	DPRINTFN(5,("uaudio_chan_rintr: count=%d, transferred=%d\n",
2885 		    count, ch->transferred));
2886 
2887 	/* count < cb->size is normal for asynchronous source */
2888 #ifdef DIAGNOSTIC
2889 	if (count > cb->size) {
2890 		aprint_error("uaudio_chan_rintr: count(%d) > size(%d)\n",
2891 		       count, cb->size);
2892 	}
2893 #endif
2894 
2895 	/*
2896 	 * Transfer data from channel buffer to upper layer buffer, taking
2897 	 * care of wrapping the upper layer buffer.
2898 	 */
2899 	for(i = 0; i < UAUDIO_NFRAMES; i++) {
2900 		frsize = cb->sizes[i];
2901 		n = min(frsize, ch->end - ch->cur);
2902 		memcpy(ch->cur, cb->buffer + cb->offsets[i], n);
2903 		ch->cur += n;
2904 		if (ch->cur >= ch->end)
2905 			ch->cur = ch->start;
2906 		if (frsize > n) {
2907 			memcpy(ch->cur, cb->buffer + cb->offsets[i] + n,
2908 			    frsize - n);
2909 			ch->cur += frsize - n;
2910 		}
2911 	}
2912 
2913 	/* Call back to upper layer */
2914 	ch->transferred += count;
2915 	s = splaudio();
2916 	while (ch->transferred >= ch->blksize) {
2917 		ch->transferred -= ch->blksize;
2918 		DPRINTFN(5,("uaudio_chan_rintr: call %p(%p)\n",
2919 			    ch->intr, ch->arg));
2920 		ch->intr(ch->arg);
2921 	}
2922 	splx(s);
2923 
2924 	/* start next transfer */
2925 	uaudio_chan_rtransfer(ch);
2926 }
2927 
2928 Static void
2929 uaudio_chan_init(struct chan *ch, int altidx, const struct audio_params *param,
2930     int maxpktsize)
2931 {
2932 	int samples_per_frame, sample_size;
2933 
2934 	ch->altidx = altidx;
2935 	sample_size = param->precision * param->channels / 8;
2936 	samples_per_frame = param->sample_rate / USB_FRAMES_PER_SECOND;
2937 	ch->sample_size = sample_size;
2938 	ch->sample_rate = param->sample_rate;
2939 	if (maxpktsize == 0) {
2940 		ch->fraction = param->sample_rate % USB_FRAMES_PER_SECOND;
2941 		ch->bytes_per_frame = samples_per_frame * sample_size;
2942 	} else {
2943 		ch->fraction = 0;
2944 		ch->bytes_per_frame = maxpktsize;
2945 	}
2946 	ch->residue = 0;
2947 }
2948 
2949 Static void
2950 uaudio_chan_set_param(struct chan *ch, u_char *start, u_char *end, int blksize)
2951 {
2952 
2953 	ch->start = start;
2954 	ch->end = end;
2955 	ch->cur = start;
2956 	ch->blksize = blksize;
2957 	ch->transferred = 0;
2958 	ch->curchanbuf = 0;
2959 }
2960 
2961 Static int
2962 uaudio_set_params(void *addr, int setmode, int usemode,
2963 		  struct audio_params *play, struct audio_params *rec,
2964 		  stream_filter_list_t *pfil, stream_filter_list_t *rfil)
2965 {
2966 	struct uaudio_softc *sc;
2967 	int paltidx, raltidx;
2968 	struct audio_params *p;
2969 	stream_filter_list_t *fil;
2970 	int mode, i;
2971 
2972 	sc = addr;
2973 	paltidx = -1;
2974 	raltidx = -1;
2975 	if (sc->sc_dying)
2976 		return EIO;
2977 
2978 	if (((usemode & AUMODE_PLAY) && sc->sc_playchan.pipe != NULL) ||
2979 	    ((usemode & AUMODE_RECORD) && sc->sc_recchan.pipe != NULL))
2980 		return EBUSY;
2981 
2982 	if ((usemode & AUMODE_PLAY) && sc->sc_playchan.altidx != -1) {
2983 		sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 0;
2984 		AUFMT_VALIDATE(sc->sc_alts[sc->sc_playchan.altidx].aformat);
2985 	}
2986 	if ((usemode & AUMODE_RECORD) && sc->sc_recchan.altidx != -1) {
2987 		sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 0;
2988 		AUFMT_VALIDATE(sc->sc_alts[sc->sc_recchan.altidx].aformat);
2989 	}
2990 
2991 	/* Some uaudio devices are unidirectional.  Don't try to find a
2992 	   matching mode for the unsupported direction. */
2993 	setmode &= sc->sc_mode;
2994 
2995 	for (mode = AUMODE_RECORD; mode != -1;
2996 	     mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
2997 		if ((setmode & mode) == 0)
2998 			continue;
2999 
3000 		if (mode == AUMODE_PLAY) {
3001 			p = play;
3002 			fil = pfil;
3003 		} else {
3004 			p = rec;
3005 			fil = rfil;
3006 		}
3007 		i = auconv_set_converter(sc->sc_formats, sc->sc_nformats,
3008 					 mode, p, TRUE, fil);
3009 		if (i < 0)
3010 			return EINVAL;
3011 
3012 		if (mode == AUMODE_PLAY)
3013 			paltidx = i;
3014 		else
3015 			raltidx = i;
3016 	}
3017 
3018 	if ((setmode & AUMODE_PLAY)) {
3019 		p = pfil->req_size > 0 ? &pfil->filters[0].param : play;
3020 		/* XXX abort transfer if currently happening? */
3021 		uaudio_chan_init(&sc->sc_playchan, paltidx, p, 0);
3022 	}
3023 	if ((setmode & AUMODE_RECORD)) {
3024 		p = rfil->req_size > 0 ? &pfil->filters[0].param : rec;
3025 		/* XXX abort transfer if currently happening? */
3026 		uaudio_chan_init(&sc->sc_recchan, raltidx, p,
3027 		    UGETW(sc->sc_alts[raltidx].edesc->wMaxPacketSize));
3028 	}
3029 
3030 	if ((usemode & AUMODE_PLAY) && sc->sc_playchan.altidx != -1) {
3031 		sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 1;
3032 		AUFMT_INVALIDATE(sc->sc_alts[sc->sc_playchan.altidx].aformat);
3033 	}
3034 	if ((usemode & AUMODE_RECORD) && sc->sc_recchan.altidx != -1) {
3035 		sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 1;
3036 		AUFMT_INVALIDATE(sc->sc_alts[sc->sc_recchan.altidx].aformat);
3037 	}
3038 
3039 	DPRINTF(("uaudio_set_params: use altidx=p%d/r%d, altno=p%d/r%d\n",
3040 		 sc->sc_playchan.altidx, sc->sc_recchan.altidx,
3041 		 (sc->sc_playchan.altidx >= 0)
3042 		   ?sc->sc_alts[sc->sc_playchan.altidx].idesc->bAlternateSetting
3043 		   : -1,
3044 		 (sc->sc_recchan.altidx >= 0)
3045 		   ? sc->sc_alts[sc->sc_recchan.altidx].idesc->bAlternateSetting
3046 		   : -1));
3047 
3048 	return 0;
3049 }
3050 
3051 Static usbd_status
3052 uaudio_set_speed(struct uaudio_softc *sc, int endpt, u_int speed)
3053 {
3054 	usb_device_request_t req;
3055 	uint8_t data[3];
3056 
3057 	DPRINTFN(5,("uaudio_set_speed: endpt=%d speed=%u\n", endpt, speed));
3058 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
3059 	req.bRequest = SET_CUR;
3060 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
3061 	USETW(req.wIndex, endpt);
3062 	USETW(req.wLength, 3);
3063 	data[0] = speed;
3064 	data[1] = speed >> 8;
3065 	data[2] = speed >> 16;
3066 
3067 	return usbd_do_request(sc->sc_udev, &req, data);
3068 }
3069 
3070 #ifdef _MODULE
3071 
3072 MODULE(MODULE_CLASS_DRIVER, uaudio, NULL);
3073 
3074 static const struct cfiattrdata audiobuscf_iattrdata = {
3075 	"audiobus", 0, { { NULL, NULL, 0 }, }
3076 };
3077 static const struct cfiattrdata * const uaudio_attrs[] = {
3078 	&audiobuscf_iattrdata, NULL
3079 };
3080 CFDRIVER_DECL(uaudio, DV_DULL, uaudio_attrs);
3081 extern struct cfattach uaudio_ca;
3082 static int uaudioloc[6/*USBIFIFCF_NLOCS*/] = {
3083 	-1/*USBIFIFCF_PORT_DEFAULT*/,
3084 	-1/*USBIFIFCF_CONFIGURATION_DEFAULT*/,
3085 	-1/*USBIFIFCF_INTERFACE_DEFAULT*/,
3086 	-1/*USBIFIFCF_VENDOR_DEFAULT*/,
3087 	-1/*USBIFIFCF_PRODUCT_DEFAULT*/,
3088 	-1/*USBIFIFCF_RELEASE_DEFAULT*/};
3089 static struct cfparent uhubparent = {
3090 	"usbifif", NULL, DVUNIT_ANY
3091 };
3092 static struct cfdata uaudio_cfdata[] = {
3093 	{
3094 		.cf_name = "uaudio",
3095 		.cf_atname = "uaudio",
3096 		.cf_unit = 0,
3097 		.cf_fstate = FSTATE_STAR,
3098 		.cf_loc = uaudioloc,
3099 		.cf_flags = 0,
3100 		.cf_pspec = &uhubparent,
3101 	},
3102 	{ NULL }
3103 };
3104 
3105 static int
3106 uaudio_modcmd(modcmd_t cmd, void *arg)
3107 {
3108 	int err;
3109 
3110 	switch (cmd) {
3111 	case MODULE_CMD_INIT:
3112 		err = config_cfdriver_attach(&uaudio_cd);
3113 		if (err) {
3114 			return err;
3115 		}
3116 		err = config_cfattach_attach("uaudio", &uaudio_ca);
3117 		if (err) {
3118 			config_cfdriver_detach(&uaudio_cd);
3119 			return err;
3120 		}
3121 		err = config_cfdata_attach(uaudio_cfdata, 1);
3122 		if (err) {
3123 			config_cfattach_detach("uaudio", &uaudio_ca);
3124 			config_cfdriver_detach(&uaudio_cd);
3125 			return err;
3126 		}
3127 		return 0;
3128 	case MODULE_CMD_FINI:
3129 		err = config_cfdata_detach(uaudio_cfdata);
3130 		if (err)
3131 			return err;
3132 		config_cfattach_detach("uaudio", &uaudio_ca);
3133 		config_cfdriver_detach(&uaudio_cd);
3134 		return 0;
3135 	default:
3136 		return ENOTTY;
3137 	}
3138 }
3139 
3140 #endif
3141