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