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