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