xref: /freebsd/sys/dev/sound/usb/uaudio.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
1 /*	$NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $	*/
2 /*	$FreeBSD$ */
3 
4 /*-
5  * Copyright (c) 1999 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *        This product includes software developed by the NetBSD
23  *        Foundation, Inc. and its contributors.
24  * 4. Neither the name of The NetBSD Foundation nor the names of its
25  *    contributors may be used to endorse or promote products derived
26  *    from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 /*
42  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
43  *                  http://www.usb.org/developers/devclass_docs/frmts10.pdf
44  *                  http://www.usb.org/developers/devclass_docs/termt10.pdf
45  */
46 
47 #include <sys/cdefs.h>
48 #if defined(__NetBSD__) || defined(__OpenBSD__)
49 __KERNEL_RCSID(0, "$NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $");
50 #endif
51 
52 /*
53  * Also merged:
54  *  $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $
55  *  $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $
56  *  $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $
57  *  $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $
58  *  $NetBSD: uaudio.c,v 1.102 2006/04/14 17:00:55 christos Exp $
59  *  $NetBSD: uaudio.c,v 1.103 2006/05/11 19:09:25 mrg Exp $
60  *  $NetBSD: uaudio.c,v 1.105 2006/10/04 16:00:15 christos Exp $
61  */
62 
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/kernel.h>
66 #include <sys/malloc.h>
67 #if defined(__NetBSD__) || defined(__OpenBSD__)
68 #include <sys/device.h>
69 #include <sys/ioctl.h>
70 #endif
71 #include <sys/tty.h>
72 #include <sys/file.h>
73 #include <sys/reboot.h>		/* for bootverbose */
74 #include <sys/select.h>
75 #include <sys/proc.h>
76 #if defined(__NetBSD__) || defined(__OpenBSD__)
77 #include <sys/device.h>
78 #elif defined(__FreeBSD__)
79 #include <sys/module.h>
80 #include <sys/bus.h>
81 #include <sys/conf.h>
82 #endif
83 #include <sys/poll.h>
84 #if defined(__FreeBSD__)
85 #include <sys/sysctl.h>
86 #include <sys/sbuf.h>
87 #endif
88 
89 #if defined(__NetBSD__) || defined(__OpenBSD__)
90 #include <sys/audioio.h>
91 #include <dev/audio_if.h>
92 #include <dev/audiovar.h>
93 #include <dev/mulaw.h>
94 #include <dev/auconv.h>
95 #elif defined(__FreeBSD__)
96 #include <dev/sound/pcm/sound.h>	/* XXXXX */
97 #include <dev/sound/chip.h>
98 #include "feeder_if.h"
99 #endif
100 
101 #include <dev/usb/usb_port.h>
102 #include <dev/usb/usb.h>
103 #include <dev/usb/usbdi.h>
104 #include <dev/usb/usbdi_util.h>
105 #include <dev/usb/usb_quirks.h>
106 
107 #if defined(__NetBSD__) || defined(__OpenBSD__)
108 #include <dev/usb/uaudioreg.h>
109 #elif defined(__FreeBSD__)
110 #include <dev/sound/usb/uaudioreg.h>
111 #include <dev/sound/usb/uaudio.h>
112 #endif
113 
114 #if defined(__NetBSD__) || defined(__OpenBSD__)
115 /* #define UAUDIO_DEBUG */
116 #else
117 /* #define USB_DEBUG */
118 #endif
119 /* #define UAUDIO_MULTIPLE_ENDPOINTS */
120 #ifdef USB_DEBUG
121 #define DPRINTF(x)	do { if (uaudiodebug) printf x; } while (0)
122 #define DPRINTFN(n,x)	do { if (uaudiodebug>(n)) printf x; } while (0)
123 int	uaudiodebug = 0;
124 #if defined(__FreeBSD__)
125 SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW, 0, "USB uaudio");
126 SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RW,
127 	   &uaudiodebug, 0, "uaudio debug level");
128 #endif
129 #else
130 #define DPRINTF(x)
131 #define DPRINTFN(n,x)
132 #endif
133 
134 #define UAUDIO_NCHANBUFS 6	/* number of outstanding request */
135 #if defined(__NetBSD__) || defined(__OpenBSD__)
136 #define UAUDIO_NFRAMES   10	/* ms of sound in each request */
137 #elif defined(__FreeBSD__)
138 #define UAUDIO_NFRAMES   20	/* ms of sound in each request */
139 #endif
140 
141 
142 #define MIX_MAX_CHAN 8
143 struct mixerctl {
144 	uint16_t	wValue[MIX_MAX_CHAN]; /* using nchan */
145 	uint16_t	wIndex;
146 	uint8_t		nchan;
147 	uint8_t		type;
148 #define MIX_ON_OFF	1
149 #define MIX_SIGNED_16	2
150 #define MIX_UNSIGNED_16	3
151 #define MIX_SIGNED_8	4
152 #define MIX_SELECTOR	5
153 #define MIX_SIZE(n) ((n) == MIX_SIGNED_16 || (n) == MIX_UNSIGNED_16 ? 2 : 1)
154 #define MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16)
155 	int		minval, maxval;
156 	u_int		delta;
157 	u_int		mul;
158 #if defined(__FreeBSD__) /* XXXXX */
159 	unsigned	ctl;
160 #define MAX_SELECTOR_INPUT_PIN 256
161 	uint8_t		slctrtype[MAX_SELECTOR_INPUT_PIN];
162 #endif
163 	uint8_t		class;
164 #if !defined(__FreeBSD__)
165 	char		ctlname[MAX_AUDIO_DEV_LEN];
166 	char		*ctlunit;
167 #endif
168 };
169 #define MAKE(h,l) (((h) << 8) | (l))
170 
171 struct as_info {
172 	uint8_t		alt;
173 	uint8_t		encoding;
174 	uint8_t		attributes; /* Copy of bmAttributes of
175 				     * usb_audio_streaming_endpoint_descriptor
176 				     */
177 	usbd_interface_handle	ifaceh;
178 	const usb_interface_descriptor_t *idesc;
179 	const usb_endpoint_descriptor_audio_t *edesc;
180 	const usb_endpoint_descriptor_audio_t *edesc1;
181 	const struct usb_audio_streaming_type1_descriptor *asf1desc;
182 	int		sc_busy;	/* currently used */
183 };
184 
185 struct chan {
186 #if defined(__NetBSD__) || defined(__OpenBSD__)
187 	void	(*intr)(void *);	/* DMA completion intr handler */
188 	void	*arg;		/* arg for intr() */
189 #else
190 	struct pcm_channel *pcm_ch;
191 #endif
192 	usbd_pipe_handle pipe;
193 	usbd_pipe_handle sync_pipe;
194 
195 	u_int	sample_size;
196 	u_int	sample_rate;
197 	u_int	bytes_per_frame;
198 	u_int	fraction;	/* fraction/1000 is the extra samples/frame */
199 	u_int	residue;	/* accumulates the fractional samples */
200 
201 	u_char	*start;		/* upper layer buffer start */
202 	u_char	*end;		/* upper layer buffer end */
203 	u_char	*cur;		/* current position in upper layer buffer */
204 	int	blksize;	/* chunk size to report up */
205 	int	transferred;	/* transferred bytes not reported up */
206 
207 	int	altidx;		/* currently used altidx */
208 
209 	int	curchanbuf;
210 	struct chanbuf {
211 		struct chan	*chan;
212 		usbd_xfer_handle xfer;
213 		u_char		*buffer;
214 		u_int16_t	sizes[UAUDIO_NFRAMES];
215 		u_int16_t	offsets[UAUDIO_NFRAMES];
216 		u_int16_t	size;
217 	} chanbufs[UAUDIO_NCHANBUFS];
218 
219 	struct uaudio_softc *sc; /* our softc */
220 #if defined(__FreeBSD__)
221 	u_int32_t format;
222 	int	precision;
223 	int	channels;
224 #endif
225 };
226 
227 struct uaudio_softc {
228 	device_t	sc_dev;		/* base device */
229 	usbd_device_handle sc_udev;	/* USB device */
230 	int		sc_ac_iface;	/* Audio Control interface */
231 	usbd_interface_handle	sc_ac_ifaceh;
232 	struct chan	sc_playchan;	/* play channel */
233 	struct chan	sc_recchan;	/* record channel */
234 	int		sc_nullalt;
235 	int		sc_audio_rev;
236 	struct as_info	*sc_alts;	/* alternate settings */
237 	int		sc_nalts;	/* # of alternate settings */
238 	int		sc_altflags;
239 #define HAS_8		0x01
240 #define HAS_16		0x02
241 #define HAS_8U		0x04
242 #define HAS_ALAW	0x08
243 #define HAS_MULAW	0x10
244 #define UA_NOFRAC	0x20		/* don't do sample rate adjustment */
245 #define HAS_24		0x40
246 #define HAS_32		0x80
247 	int		sc_mode;	/* play/record capability */
248 	struct mixerctl *sc_ctls;	/* mixer controls */
249 	int		sc_nctls;	/* # of mixer controls */
250 	device_t	sc_audiodev;
251 	char		sc_dying;
252 #if defined(__FreeBSD__)
253 	struct sbuf	uaudio_sndstat;
254 	int		uaudio_sndstat_flag;
255 	int		async;
256 #endif
257 	int		sc_vendor;
258 	int		sc_product;
259 	int		sc_release;
260 };
261 
262 struct terminal_list {
263 	int size;
264 	uint16_t terminals[1];
265 };
266 #define TERMINAL_LIST_SIZE(N)	(offsetof(struct terminal_list, terminals) \
267 				+ sizeof(uint16_t) * (N))
268 
269 struct io_terminal {
270 	union {
271 		const usb_descriptor_t *desc;
272 		const struct usb_audio_input_terminal *it;
273 		const struct usb_audio_output_terminal *ot;
274 		const struct usb_audio_mixer_unit *mu;
275 		const struct usb_audio_selector_unit *su;
276 		const struct usb_audio_feature_unit *fu;
277 		const struct usb_audio_processing_unit *pu;
278 		const struct usb_audio_extension_unit *eu;
279 	} d;
280 	int inputs_size;
281 	struct terminal_list **inputs; /* list of source input terminals */
282 	struct terminal_list *output; /* list of destination output terminals */
283 	int direct;		/* directly connected to an output terminal */
284 };
285 
286 #define UAC_OUTPUT	0
287 #define UAC_INPUT	1
288 #define UAC_EQUAL	2
289 #define UAC_RECORD	3
290 #define UAC_NCLASSES	4
291 #ifdef USB_DEBUG
292 #if defined(__FreeBSD__)
293 #define AudioCinputs	"inputs"
294 #define AudioCoutputs	"outputs"
295 #define AudioCrecord	"record"
296 #define AudioCequalization	"equalization"
297 #endif
298 static const char *uac_names[] = {
299 	AudioCoutputs, AudioCinputs, AudioCequalization, AudioCrecord,
300 };
301 #endif
302 
303 static usbd_status uaudio_identify_ac
304 	(struct uaudio_softc *, const usb_config_descriptor_t *);
305 static usbd_status uaudio_identify_as
306 	(struct uaudio_softc *, const usb_config_descriptor_t *);
307 static usbd_status uaudio_process_as
308 	(struct uaudio_softc *, const char *, int *, int,
309 	 const usb_interface_descriptor_t *);
310 
311 static void	uaudio_add_alt(struct uaudio_softc *, const struct as_info *);
312 
313 static const usb_interface_descriptor_t *uaudio_find_iface
314 	(const char *, int, int *, int);
315 
316 static void	uaudio_mixer_add_ctl(struct uaudio_softc *, struct mixerctl *);
317 
318 #if defined(__NetBSD__) || defined(__OpenBSD__)
319 static char	*uaudio_id_name
320 	(struct uaudio_softc *, const struct io_terminal *, int);
321 #endif
322 
323 #ifdef USB_DEBUG
324 static void	uaudio_dump_cluster(const struct usb_audio_cluster *);
325 #endif
326 static struct usb_audio_cluster uaudio_get_cluster
327 	(int, const struct io_terminal *);
328 static void	uaudio_add_input
329 	(struct uaudio_softc *, const struct io_terminal *, int);
330 static void	uaudio_add_output
331 	(struct uaudio_softc *, const struct io_terminal *, int);
332 static void	uaudio_add_mixer
333 	(struct uaudio_softc *, const struct io_terminal *, int);
334 static void	uaudio_add_selector
335 	(struct uaudio_softc *, const struct io_terminal *, int);
336 #ifdef USB_DEBUG
337 static const char *uaudio_get_terminal_name(int);
338 #endif
339 static int	uaudio_determine_class
340 	(const struct io_terminal *, struct mixerctl *);
341 #if defined(__FreeBSD__)
342 static int uaudio_feature_name(const struct io_terminal *,
343 	struct mixerctl *);
344 #else
345 static const char *uaudio_feature_name
346 	(const struct io_terminal *, struct mixerctl *);
347 #endif
348 static void	uaudio_add_feature
349 	(struct uaudio_softc *, const struct io_terminal *, int);
350 static void	uaudio_add_processing_updown
351 	(struct uaudio_softc *, const struct io_terminal *, int);
352 static void	uaudio_add_processing
353 	(struct uaudio_softc *, const struct io_terminal *, int);
354 static void	uaudio_add_extension
355 	(struct uaudio_softc *, const struct io_terminal *, int);
356 static struct terminal_list *uaudio_merge_terminal_list
357 	(const struct io_terminal *);
358 static struct terminal_list *uaudio_io_terminaltype
359 	(int, struct io_terminal *, int);
360 static usbd_status uaudio_identify
361 	(struct uaudio_softc *, const usb_config_descriptor_t *);
362 
363 static int	uaudio_signext(int, int);
364 #if defined(__NetBSD__) || defined(__OpenBSD__)
365 static int	uaudio_value2bsd(struct mixerctl *, int);
366 #endif
367 static int	uaudio_bsd2value(struct mixerctl *, int);
368 static int	uaudio_get(struct uaudio_softc *, int, int, int, int, int);
369 #if defined(__NetBSD__) || defined(__OpenBSD__)
370 static int	uaudio_ctl_get
371 	(struct uaudio_softc *, int, struct mixerctl *, int);
372 #endif
373 static void	uaudio_set
374 	(struct uaudio_softc *, int, int, int, int, int, int);
375 static void	uaudio_ctl_set
376 	(struct uaudio_softc *, int, struct mixerctl *, int, int);
377 
378 static usbd_status uaudio_set_speed(struct uaudio_softc *, int, u_int);
379 
380 static usbd_status uaudio_chan_open(struct uaudio_softc *, struct chan *);
381 static void	uaudio_chan_close(struct uaudio_softc *, struct chan *);
382 static usbd_status uaudio_chan_alloc_buffers
383 	(struct uaudio_softc *, struct chan *);
384 static void	uaudio_chan_free_buffers(struct uaudio_softc *, struct chan *);
385 
386 #if defined(__NetBSD__) || defined(__OpenBSD__)
387 static void	uaudio_chan_init
388 	(struct chan *, int, const struct audio_params *, int);
389 static void	uaudio_chan_set_param(struct chan *, u_char *, u_char *, int);
390 #endif
391 
392 static void	uaudio_chan_ptransfer(struct chan *);
393 static void	uaudio_chan_pintr
394 	(usbd_xfer_handle, usbd_private_handle, usbd_status);
395 
396 static void	uaudio_chan_rtransfer(struct chan *);
397 static void	uaudio_chan_rintr
398 	(usbd_xfer_handle, usbd_private_handle, usbd_status);
399 
400 #if defined(__NetBSD__) || defined(__OpenBSD__)
401 static int	uaudio_open(void *, int);
402 static void	uaudio_close(void *);
403 static int	uaudio_drain(void *);
404 static int	uaudio_query_encoding(void *, struct audio_encoding *);
405 static void	uaudio_get_minmax_rates
406 	(int, const struct as_info *, const struct audio_params *,
407 	 int, u_long *, u_long *);
408 static int	uaudio_match_alt_sub
409 	(int, const struct as_info *, const struct audio_params *, int, u_long);
410 static int	uaudio_match_alt_chan
411 	(int, const struct as_info *, struct audio_params *, int);
412 static int	uaudio_match_alt
413 	(int, const struct as_info *, struct audio_params *, int);
414 static int	uaudio_set_params
415 	(void *, int, int, struct audio_params *, struct audio_params *);
416 static int	uaudio_round_blocksize(void *, int);
417 static int	uaudio_trigger_output
418 	(void *, void *, void *, int, void (*)(void *), void *,
419 	 struct audio_params *);
420 static int	uaudio_trigger_input
421 	(void *, void *, void *, int, void (*)(void *), void *,
422 	 struct audio_params *);
423 static int	uaudio_halt_in_dma(void *);
424 static int	uaudio_halt_out_dma(void *);
425 static int	uaudio_getdev(void *, struct audio_device *);
426 static int	uaudio_mixer_set_port(void *, mixer_ctrl_t *);
427 static int	uaudio_mixer_get_port(void *, mixer_ctrl_t *);
428 static int	uaudio_query_devinfo(void *, mixer_devinfo_t *);
429 static int	uaudio_get_props(void *);
430 
431 static const struct audio_hw_if uaudio_hw_if = {
432 	uaudio_open,
433 	uaudio_close,
434 	uaudio_drain,
435 	uaudio_query_encoding,
436 	uaudio_set_params,
437 	uaudio_round_blocksize,
438 	NULL,
439 	NULL,
440 	NULL,
441 	NULL,
442 	NULL,
443 	uaudio_halt_out_dma,
444 	uaudio_halt_in_dma,
445 	NULL,
446 	uaudio_getdev,
447 	NULL,
448 	uaudio_mixer_set_port,
449 	uaudio_mixer_get_port,
450 	uaudio_query_devinfo,
451 	NULL,
452 	NULL,
453 	NULL,
454 	NULL,
455 	uaudio_get_props,
456 	uaudio_trigger_output,
457 	uaudio_trigger_input,
458 	NULL,
459 };
460 
461 static struct audio_device uaudio_device = {
462 	"USB audio",
463 	"",
464 	"uaudio"
465 };
466 
467 #elif defined(__FreeBSD__)
468 static int	audio_attach_mi(device_t);
469 static int	uaudio_init_params(struct uaudio_softc * sc, struct chan *ch, int mode);
470 static int 	uaudio_sndstat_prepare_pcm(struct sbuf *s, device_t dev, int verbose);
471 
472 /* for NetBSD compatibirity */
473 #define	AUMODE_PLAY	0x01
474 #define	AUMODE_RECORD	0x02
475 
476 #define	AUDIO_PROP_FULLDUPLEX	0x01
477 
478 #define	AUDIO_ENCODING_ULAW		1
479 #define	AUDIO_ENCODING_ALAW		2
480 #define	AUDIO_ENCODING_SLINEAR_LE	6
481 #define	AUDIO_ENCODING_SLINEAR_BE	7
482 #define	AUDIO_ENCODING_ULINEAR_LE	8
483 #define	AUDIO_ENCODING_ULINEAR_BE	9
484 
485 #endif	/* FreeBSD */
486 
487 
488 #if defined(__NetBSD__) || defined(__OpenBSD__)
489 
490 USB_DECLARE_DRIVER(uaudio);
491 
492 #elif defined(__FreeBSD__)
493 
494 USB_DECLARE_DRIVER_INIT(uaudio,
495 		DEVMETHOD(device_suspend, bus_generic_suspend),
496 		DEVMETHOD(device_resume, bus_generic_resume),
497 		DEVMETHOD(device_shutdown, bus_generic_shutdown),
498 		DEVMETHOD(bus_print_child, bus_generic_print_child)
499 		);
500 #endif
501 
502 
503 USB_MATCH(uaudio)
504 {
505 	USB_MATCH_START(uaudio, uaa);
506 	usb_interface_descriptor_t *id;
507 
508 	if (uaa->iface == NULL)
509 		return UMATCH_NONE;
510 
511 	id = usbd_get_interface_descriptor(uaa->iface);
512 	/* Trigger on the control interface. */
513 	if (id == NULL ||
514 	    id->bInterfaceClass != UICLASS_AUDIO ||
515 	    id->bInterfaceSubClass != UISUBCLASS_AUDIOCONTROL ||
516 	    (usbd_get_quirks(uaa->device)->uq_flags & UQ_BAD_AUDIO))
517 		return UMATCH_NONE;
518 
519 	return UMATCH_IFACECLASS_IFACESUBCLASS;
520 }
521 
522 USB_ATTACH(uaudio)
523 {
524 	USB_ATTACH_START(uaudio, sc, uaa);
525 	usb_interface_descriptor_t *id;
526 	usb_config_descriptor_t *cdesc;
527 #if !defined(__FreeBSD__)
528 	char devinfo[1024];
529 #endif
530 	usbd_status err;
531 	int i, j, found;
532 
533 #if defined(__FreeBSD__)
534 	sc->sc_dev = self;
535 #else
536 	usbd_devinfo(uaa->device, 0, devinfo, sizeof(devinfo));
537 	printf(": %s\n", devinfo);
538 #endif
539 
540 	sc->sc_udev = uaa->device;
541 	sc->sc_vendor = uaa->vendor;
542 	sc->sc_product = uaa->product;
543 	sc->sc_release = uaa->release;
544 #if defined(__FreeBSD__)
545 	if (resource_int_value(device_get_name(sc->sc_dev),
546 	    device_get_unit(sc->sc_dev), "async", &i) == 0 && i != 0)
547 		sc->async = 1;
548 	else
549 		sc->async = 0;
550 #endif
551 
552 	cdesc = usbd_get_config_descriptor(sc->sc_udev);
553 	if (cdesc == NULL) {
554 		printf("%s: failed to get configuration descriptor\n",
555 		       device_get_nameunit(sc->sc_dev));
556 		return ENXIO;
557 	}
558 
559 	err = uaudio_identify(sc, cdesc);
560 	if (err) {
561 		printf("%s: audio descriptors make no sense, error=%d\n",
562 		       device_get_nameunit(sc->sc_dev), err);
563 		return ENXIO;
564 	}
565 
566 	sc->sc_ac_ifaceh = uaa->iface;
567 	/* Pick up the AS interface. */
568 	for (i = 0; i < uaa->nifaces; i++) {
569 		if (uaa->ifaces[i] == NULL)
570 			continue;
571 		id = usbd_get_interface_descriptor(uaa->ifaces[i]);
572 		if (id == NULL)
573 			continue;
574 		found = 0;
575 		for (j = 0; j < sc->sc_nalts; j++) {
576 			if (id->bInterfaceNumber ==
577 			    sc->sc_alts[j].idesc->bInterfaceNumber) {
578 				sc->sc_alts[j].ifaceh = uaa->ifaces[i];
579 				found = 1;
580 			}
581 		}
582 		if (found)
583 			uaa->ifaces[i] = NULL;
584 	}
585 
586 	for (j = 0; j < sc->sc_nalts; j++) {
587 		if (sc->sc_alts[j].ifaceh == NULL) {
588 			printf("%s: alt %d missing AS interface(s)\n",
589 			    device_get_nameunit(sc->sc_dev), j);
590 			return ENXIO;
591 		}
592 	}
593 
594 	printf("%s: audio rev %d.%02x\n", device_get_nameunit(sc->sc_dev),
595 	       sc->sc_audio_rev >> 8, sc->sc_audio_rev & 0xff);
596 
597 	sc->sc_playchan.sc = sc->sc_recchan.sc = sc;
598 	sc->sc_playchan.altidx = -1;
599 	sc->sc_recchan.altidx = -1;
600 
601 	if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_FRAC)
602 		sc->sc_altflags |= UA_NOFRAC;
603 
604 #ifndef USB_DEBUG
605 	if (bootverbose)
606 #endif
607 		printf("%s: %d mixer controls\n", device_get_nameunit(sc->sc_dev),
608 		    sc->sc_nctls);
609 
610 #if !defined(__FreeBSD__)
611 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
612 			   USBDEV(sc->sc_dev));
613 #endif
614 
615 	DPRINTF(("uaudio_attach: doing audio_attach_mi\n"));
616 #if defined(__OpenBSD__)
617 	audio_attach_mi(&uaudio_hw_if, sc, &sc->sc_dev);
618 #elif defined(__NetBSD__)
619 	sc->sc_audiodev = audio_attach_mi(&uaudio_hw_if, sc, &sc->sc_dev);
620 #elif defined(__FreeBSD__)
621 	sc->sc_dying = 0;
622 	if (audio_attach_mi(sc->sc_dev)) {
623 		printf("audio_attach_mi failed\n");
624 		return ENXIO;
625 	}
626 #endif
627 
628 #if defined(__FreeBSD__)
629 	SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->sc_dev),
630 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->sc_dev)),
631 	    OID_AUTO, "async", CTLFLAG_RW, &sc->async, 0,
632 	    "Asynchronous USB request");
633 #endif
634 	return 0;
635 }
636 
637 #if defined(__NetBSD__) || defined(__OpenBSD__)
638 int
639 uaudio_activate(device_t self, enum devact act)
640 {
641 	struct uaudio_softc *sc;
642 	int rv;
643 
644 	sc = (struct uaudio_softc *)self;
645 	rv = 0;
646 	switch (act) {
647 	case DVACT_ACTIVATE:
648 		return EOPNOTSUPP;
649 
650 	case DVACT_DEACTIVATE:
651 		if (sc->sc_audiodev != NULL)
652 			rv = config_deactivate(sc->sc_audiodev);
653 		sc->sc_dying = 1;
654 		break;
655 	}
656 	return rv;
657 }
658 #endif
659 
660 #if defined(__NetBSD__) || defined(__OpenBSD__)
661 int
662 uaudio_detach(device_t self, int flags)
663 {
664 	struct uaudio_softc *sc;
665 	int rv;
666 
667 	sc = (struct uaudio_softc *)self;
668 	rv = 0;
669 	/* Wait for outstanding requests to complete. */
670 	usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
671 
672 	if (sc->sc_audiodev != NULL)
673 		rv = config_detach(sc->sc_audiodev, flags);
674 
675 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
676 			   USBDEV(sc->sc_dev));
677 
678 	return rv;
679 }
680 #elif defined(__FreeBSD__)
681 
682 USB_DETACH(uaudio)
683 {
684 	struct sndcard_func *func;
685 	device_t *devlist = NULL;
686 	int err, i, devcount;
687 
688 	USB_DETACH_START(uaudio, sc);
689 
690 	sbuf_delete(&(sc->uaudio_sndstat));
691 	sc->uaudio_sndstat_flag = 0;
692 
693 	sc->sc_dying = 1;
694 
695 #if 0 /* XXX */
696 	/* Wait for outstanding requests to complete. */
697 	usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
698 #endif
699 
700 	err = bus_generic_detach(sc->sc_dev);
701 
702 	if (err == 0) {
703 		device_get_children(sc->sc_dev, &devlist, &devcount);
704 		for (i = 0; devlist != NULL && i < devcount; i++) {
705 			func = device_get_ivars(devlist[i]);
706 			if (func != NULL && func->func == SCF_PCM &&
707 			    func->varinfo == NULL) {
708 				device_set_ivars(devlist[i], NULL);
709 				free(func, M_DEVBUF);
710 				device_delete_child(sc->sc_dev, devlist[i]);
711 			}
712 		}
713 		if (devlist != NULL)
714 			free(devlist, M_TEMP);
715 	}
716 
717 	return err;
718 }
719 #endif
720 
721 #if defined(__NetBSD__) || defined(__OpenBSD__)
722 static int
723 uaudio_query_encoding(void *addr, struct audio_encoding *fp)
724 {
725 	struct uaudio_softc *sc;
726 	int flags;
727 	int idx;
728 
729 	sc = addr;
730 	flags = sc->sc_altflags;
731 	if (sc->sc_dying)
732 		return EIO;
733 
734 	if (sc->sc_nalts == 0 || flags == 0)
735 		return ENXIO;
736 
737 	idx = fp->index;
738 	switch (idx) {
739 	case 0:
740 		strlcpy(fp->name, AudioEulinear, sizeof(fp->name));
741 		fp->encoding = AUDIO_ENCODING_ULINEAR;
742 		fp->precision = 8;
743 		fp->flags = flags&HAS_8U ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
744 		return (0);
745 	case 1:
746 		strlcpy(fp->name, AudioEmulaw, sizeof(fp->name));
747 		fp->encoding = AUDIO_ENCODING_ULAW;
748 		fp->precision = 8;
749 		fp->flags = flags&HAS_MULAW ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
750 		return (0);
751 	case 2:
752 		strlcpy(fp->name, AudioEalaw, sizeof(fp->name));
753 		fp->encoding = AUDIO_ENCODING_ALAW;
754 		fp->precision = 8;
755 		fp->flags = flags&HAS_ALAW ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
756 		return (0);
757 	case 3:
758 		strlcpy(fp->name, AudioEslinear, sizeof(fp->name));
759 		fp->encoding = AUDIO_ENCODING_SLINEAR;
760 		fp->precision = 8;
761 		fp->flags = flags&HAS_8 ? 0 : AUDIO_ENCODINGFLAG_EMULATED;
762 		return (0);
763 	case 4:
764 		strlcpy(fp->name, AudioEslinear_le, sizeof(fp->name));
765 		fp->encoding = AUDIO_ENCODING_SLINEAR_LE;
766 		fp->precision = 16;
767 		fp->flags = 0;
768 		return (0);
769 	case 5:
770 		strlcpy(fp->name, AudioEulinear_le, sizeof(fp->name));
771 		fp->encoding = AUDIO_ENCODING_ULINEAR_LE;
772 		fp->precision = 16;
773 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
774 		return (0);
775 	case 6:
776 		strlcpy(fp->name, AudioEslinear_be, sizeof(fp->name));
777 		fp->encoding = AUDIO_ENCODING_SLINEAR_BE;
778 		fp->precision = 16;
779 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
780 		return (0);
781 	case 7:
782 		strlcpy(fp->name, AudioEulinear_be, sizeof(fp->name));
783 		fp->encoding = AUDIO_ENCODING_ULINEAR_BE;
784 		fp->precision = 16;
785 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
786 		return (0);
787 	default:
788 		return (EINVAL);
789 	}
790 }
791 #endif
792 
793 static const usb_interface_descriptor_t *
794 uaudio_find_iface(const char *buf, int size, int *offsp, int subtype)
795 {
796 	const usb_interface_descriptor_t *d;
797 
798 	while (*offsp < size) {
799 		d = (const void *)(buf + *offsp);
800 		*offsp += d->bLength;
801 		if (d->bDescriptorType == UDESC_INTERFACE &&
802 		    d->bInterfaceClass == UICLASS_AUDIO &&
803 		    d->bInterfaceSubClass == subtype)
804 			return d;
805 	}
806 	return NULL;
807 }
808 
809 static void
810 uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct mixerctl *mc)
811 {
812 	int res;
813 	size_t len;
814 	struct mixerctl *nmc;
815 
816 #if defined(__FreeBSD__)
817 	if (mc->class < UAC_NCLASSES) {
818 		DPRINTF(("%s: adding %s.%d\n",
819 			 __func__, uac_names[mc->class], mc->ctl));
820 	} else {
821 		DPRINTF(("%s: adding %d\n", __func__, mc->ctl));
822 	}
823 #else
824 	if (mc->class < UAC_NCLASSES) {
825 		DPRINTF(("%s: adding %s.%s\n",
826 			 __func__, uac_names[mc->class], mc->ctlname));
827 	} else {
828 		DPRINTF(("%s: adding %s\n", __func__, mc->ctlname));
829 	}
830 #endif
831 	len = sizeof(*mc) * (sc->sc_nctls + 1);
832 	nmc = malloc(len, M_USBDEV, M_NOWAIT);
833 	if (nmc == NULL) {
834 		printf("uaudio_mixer_add_ctl: no memory\n");
835 		return;
836 	}
837 	/* Copy old data, if there was any */
838 	if (sc->sc_nctls != 0) {
839 		memcpy(nmc, sc->sc_ctls, sizeof(*mc) * (sc->sc_nctls));
840 		free(sc->sc_ctls, M_USBDEV);
841 	}
842 	sc->sc_ctls = nmc;
843 
844 	mc->delta = 0;
845 	if (mc->type == MIX_ON_OFF) {
846 		mc->minval = 0;
847 		mc->maxval = 1;
848 	} else if (mc->type == MIX_SELECTOR) {
849 		;
850 	} else {
851 		/* Determine min and max values. */
852 		mc->minval = uaudio_signext(mc->type,
853 			uaudio_get(sc, GET_MIN, UT_READ_CLASS_INTERFACE,
854 				   mc->wValue[0], mc->wIndex,
855 				   MIX_SIZE(mc->type)));
856 		mc->maxval = 1 + uaudio_signext(mc->type,
857 			uaudio_get(sc, GET_MAX, UT_READ_CLASS_INTERFACE,
858 				   mc->wValue[0], mc->wIndex,
859 				   MIX_SIZE(mc->type)));
860 		mc->mul = mc->maxval - mc->minval;
861 		if (mc->mul == 0)
862 			mc->mul = 1;
863 		res = uaudio_get(sc, GET_RES, UT_READ_CLASS_INTERFACE,
864 				 mc->wValue[0], mc->wIndex,
865 				 MIX_SIZE(mc->type));
866 		if (res > 0)
867 			mc->delta = (res * 255 + mc->mul/2) / mc->mul;
868 	}
869 
870 	sc->sc_ctls[sc->sc_nctls++] = *mc;
871 
872 #ifdef USB_DEBUG
873 	if (uaudiodebug > 2) {
874 		int i;
875 		DPRINTF(("uaudio_mixer_add_ctl: wValue=%04x",mc->wValue[0]));
876 		for (i = 1; i < mc->nchan; i++)
877 			DPRINTF((",%04x", mc->wValue[i]));
878 #if defined(__FreeBSD__)
879 		DPRINTF((" wIndex=%04x type=%d ctl='%d' "
880 			 "min=%d max=%d\n",
881 			 mc->wIndex, mc->type, mc->ctl,
882 			 mc->minval, mc->maxval));
883 #else
884 		DPRINTF((" wIndex=%04x type=%d name='%s' unit='%s' "
885 			 "min=%d max=%d\n",
886 			 mc->wIndex, mc->type, mc->ctlname, mc->ctlunit,
887 			 mc->minval, mc->maxval));
888 #endif
889 	}
890 #endif
891 }
892 
893 #if defined(__NetBSD__) || defined(__OpenBSD__)
894 static char *
895 uaudio_id_name(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
896 {
897 	static char buf[32];
898 
899 	snprintf(buf, sizeof(buf), "i%d", id);
900 	return buf;
901 }
902 #endif
903 
904 #ifdef USB_DEBUG
905 static void
906 uaudio_dump_cluster(const struct usb_audio_cluster *cl)
907 {
908 	static const char *channel_names[16] = {
909 		"LEFT", "RIGHT", "CENTER", "LFE",
910 		"LEFT_SURROUND", "RIGHT_SURROUND", "LEFT_CENTER", "RIGHT_CENTER",
911 		"SURROUND", "LEFT_SIDE", "RIGHT_SIDE", "TOP",
912 		"RESERVED12", "RESERVED13", "RESERVED14", "RESERVED15",
913 	};
914 	int cc, i, first;
915 
916 	cc = UGETW(cl->wChannelConfig);
917 	printf("cluster: bNrChannels=%u wChannelConfig=0x%.4x",
918 		  cl->bNrChannels, cc);
919 	first = TRUE;
920 	for (i = 0; cc != 0; i++) {
921 		if (cc & 1) {
922 			printf("%c%s", first ? '<' : ',', channel_names[i]);
923 			first = FALSE;
924 		}
925 		cc = cc >> 1;
926 	}
927 	printf("> iChannelNames=%u", cl->iChannelNames);
928 }
929 #endif
930 
931 static struct usb_audio_cluster
932 uaudio_get_cluster(int id, const struct io_terminal *iot)
933 {
934 	struct usb_audio_cluster r;
935 	const usb_descriptor_t *dp;
936 	int i;
937 
938 	for (i = 0; i < 25; i++) { /* avoid infinite loops */
939 		dp = iot[id].d.desc;
940 		if (dp == 0)
941 			goto bad;
942 		switch (dp->bDescriptorSubtype) {
943 		case UDESCSUB_AC_INPUT:
944 			r.bNrChannels = iot[id].d.it->bNrChannels;
945 			USETW(r.wChannelConfig, UGETW(iot[id].d.it->wChannelConfig));
946 			r.iChannelNames = iot[id].d.it->iChannelNames;
947 			return r;
948 		case UDESCSUB_AC_OUTPUT:
949 			id = iot[id].d.ot->bSourceId;
950 			break;
951 		case UDESCSUB_AC_MIXER:
952 			r = *(const struct usb_audio_cluster *)
953 				&iot[id].d.mu->baSourceId[iot[id].d.mu->bNrInPins];
954 			return r;
955 		case UDESCSUB_AC_SELECTOR:
956 			/* XXX This is not really right */
957 			id = iot[id].d.su->baSourceId[0];
958 			break;
959 		case UDESCSUB_AC_FEATURE:
960 			id = iot[id].d.fu->bSourceId;
961 			break;
962 		case UDESCSUB_AC_PROCESSING:
963 			r = *(const struct usb_audio_cluster *)
964 				&iot[id].d.pu->baSourceId[iot[id].d.pu->bNrInPins];
965 			return r;
966 		case UDESCSUB_AC_EXTENSION:
967 			r = *(const struct usb_audio_cluster *)
968 				&iot[id].d.eu->baSourceId[iot[id].d.eu->bNrInPins];
969 			return r;
970 		default:
971 			goto bad;
972 		}
973 	}
974  bad:
975 	printf("uaudio_get_cluster: bad data\n");
976 	memset(&r, 0, sizeof r);
977 	return r;
978 
979 }
980 
981 static void
982 uaudio_add_input(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
983 {
984 #ifdef USB_DEBUG
985 	const struct usb_audio_input_terminal *d = iot[id].d.it;
986 
987 	DPRINTFN(2,("uaudio_add_input: bTerminalId=%d wTerminalType=0x%04x "
988 		    "bAssocTerminal=%d bNrChannels=%d wChannelConfig=%d "
989 		    "iChannelNames=%d iTerminal=%d\n",
990 		    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
991 		    d->bNrChannels, UGETW(d->wChannelConfig),
992 		    d->iChannelNames, d->iTerminal));
993 #endif
994 }
995 
996 static void
997 uaudio_add_output(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
998 {
999 #ifdef USB_DEBUG
1000 	const struct usb_audio_output_terminal *d;
1001 
1002 	d = iot[id].d.ot;
1003 	DPRINTFN(2,("uaudio_add_output: bTerminalId=%d wTerminalType=0x%04x "
1004 		    "bAssocTerminal=%d bSourceId=%d iTerminal=%d\n",
1005 		    d->bTerminalId, UGETW(d->wTerminalType), d->bAssocTerminal,
1006 		    d->bSourceId, d->iTerminal));
1007 #endif
1008 }
1009 
1010 static void
1011 uaudio_add_mixer(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1012 {
1013 	const struct usb_audio_mixer_unit *d = iot[id].d.mu;
1014 	const struct usb_audio_mixer_unit_1 *d1;
1015 	int c, chs, ichs, ochs, i, o, bno, p, mo, mc, k;
1016 	const uByte *bm;
1017 	struct mixerctl mix;
1018 
1019 	DPRINTFN(2,("uaudio_add_mixer: bUnitId=%d bNrInPins=%d\n",
1020 		    d->bUnitId, d->bNrInPins));
1021 
1022 	/* Compute the number of input channels */
1023 	ichs = 0;
1024 	for (i = 0; i < d->bNrInPins; i++)
1025 		ichs += uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
1026 
1027 	/* and the number of output channels */
1028 	d1 = (const struct usb_audio_mixer_unit_1 *)&d->baSourceId[d->bNrInPins];
1029 	ochs = d1->bNrChannels;
1030 	DPRINTFN(2,("uaudio_add_mixer: ichs=%d ochs=%d\n", ichs, ochs));
1031 
1032 	bm = d1->bmControls;
1033 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1034 	uaudio_determine_class(&iot[id], &mix);
1035 	mix.type = MIX_SIGNED_16;
1036 #if !defined(__FreeBSD__)	/* XXXXX */
1037 	mix.ctlunit = AudioNvolume;
1038 #endif
1039 
1040 #define BIT(bno) ((bm[bno / 8] >> (7 - bno % 8)) & 1)
1041 	for (p = i = 0; i < d->bNrInPins; i++) {
1042 		chs = uaudio_get_cluster(d->baSourceId[i], iot).bNrChannels;
1043 		mc = 0;
1044 		for (c = 0; c < chs; c++) {
1045 			mo = 0;
1046 			for (o = 0; o < ochs; o++) {
1047 				bno = (p + c) * ochs + o;
1048 				if (BIT(bno))
1049 					mo++;
1050 			}
1051 			if (mo == 1)
1052 				mc++;
1053 		}
1054 		if (mc == chs && chs <= MIX_MAX_CHAN) {
1055 			k = 0;
1056 			for (c = 0; c < chs; c++)
1057 				for (o = 0; o < ochs; o++) {
1058 					bno = (p + c) * ochs + o;
1059 					if (BIT(bno))
1060 						mix.wValue[k++] =
1061 							MAKE(p+c+1, o+1);
1062 				}
1063 #if !defined(__FreeBSD__)
1064 			snprintf(mix.ctlname, sizeof(mix.ctlname), "mix%d-%s",
1065 			    d->bUnitId, uaudio_id_name(sc, iot,
1066 			    d->baSourceId[i]));
1067 #endif
1068 			mix.nchan = chs;
1069 			uaudio_mixer_add_ctl(sc, &mix);
1070 		} else {
1071 			/* XXX */
1072 		}
1073 #undef BIT
1074 		p += chs;
1075 	}
1076 
1077 }
1078 
1079 static void
1080 uaudio_add_selector(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1081 {
1082 	const struct usb_audio_selector_unit *d;
1083 	struct mixerctl mix;
1084 #if !defined(__FreeBSD__)
1085 	int i, wp;
1086 #else
1087 	int i;
1088 	struct mixerctl dummy;
1089 #endif
1090 
1091 	d = iot[id].d.su;
1092 	DPRINTFN(2,("uaudio_add_selector: bUnitId=%d bNrInPins=%d\n",
1093 		    d->bUnitId, d->bNrInPins));
1094 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1095 	mix.wValue[0] = MAKE(0, 0);
1096 	uaudio_determine_class(&iot[id], &mix);
1097 	mix.nchan = 1;
1098 	mix.type = MIX_SELECTOR;
1099 #if defined(__FreeBSD__)
1100 	mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1101 	mix.minval = 1;
1102 	mix.maxval = d->bNrInPins;
1103 	mix.mul = mix.maxval - mix.minval;
1104 	for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) {
1105 		mix.slctrtype[i] = SOUND_MIXER_NRDEVICES;
1106 	}
1107 	for (i = mix.minval; i <= mix.maxval; i++) {
1108 		mix.slctrtype[i - 1] = uaudio_feature_name(&iot[d->baSourceId[i - 1]], &dummy);
1109 	}
1110 #else
1111 	mix.ctlunit = "";
1112 	mix.minval = 1;
1113 	mix.maxval = d->bNrInPins;
1114 	mix.mul = mix.maxval - mix.minval;
1115 	wp = snprintf(mix.ctlname, MAX_AUDIO_DEV_LEN, "sel%d-", d->bUnitId);
1116 	for (i = 1; i <= d->bNrInPins; i++) {
1117 		wp += snprintf(mix.ctlname + wp, MAX_AUDIO_DEV_LEN - wp,
1118 			       "i%d", d->baSourceId[i - 1]);
1119 		if (wp > MAX_AUDIO_DEV_LEN - 1)
1120 			break;
1121 	}
1122 #endif
1123 	uaudio_mixer_add_ctl(sc, &mix);
1124 }
1125 
1126 #ifdef USB_DEBUG
1127 static const char *
1128 uaudio_get_terminal_name(int terminal_type)
1129 {
1130 	static char buf[100];
1131 
1132 	switch (terminal_type) {
1133 	/* USB terminal types */
1134 	case UAT_UNDEFINED:	return "UAT_UNDEFINED";
1135 	case UAT_STREAM:	return "UAT_STREAM";
1136 	case UAT_VENDOR:	return "UAT_VENDOR";
1137 	/* input terminal types */
1138 	case UATI_UNDEFINED:	return "UATI_UNDEFINED";
1139 	case UATI_MICROPHONE:	return "UATI_MICROPHONE";
1140 	case UATI_DESKMICROPHONE:	return "UATI_DESKMICROPHONE";
1141 	case UATI_PERSONALMICROPHONE:	return "UATI_PERSONALMICROPHONE";
1142 	case UATI_OMNIMICROPHONE:	return "UATI_OMNIMICROPHONE";
1143 	case UATI_MICROPHONEARRAY:	return "UATI_MICROPHONEARRAY";
1144 	case UATI_PROCMICROPHONEARR:	return "UATI_PROCMICROPHONEARR";
1145 	/* output terminal types */
1146 	case UATO_UNDEFINED:	return "UATO_UNDEFINED";
1147 	case UATO_SPEAKER:	return "UATO_SPEAKER";
1148 	case UATO_HEADPHONES:	return "UATO_HEADPHONES";
1149 	case UATO_DISPLAYAUDIO:	return "UATO_DISPLAYAUDIO";
1150 	case UATO_DESKTOPSPEAKER:	return "UATO_DESKTOPSPEAKER";
1151 	case UATO_ROOMSPEAKER:	return "UATO_ROOMSPEAKER";
1152 	case UATO_COMMSPEAKER:	return "UATO_COMMSPEAKER";
1153 	case UATO_SUBWOOFER:	return "UATO_SUBWOOFER";
1154 	/* bidir terminal types */
1155 	case UATB_UNDEFINED:	return "UATB_UNDEFINED";
1156 	case UATB_HANDSET:	return "UATB_HANDSET";
1157 	case UATB_HEADSET:	return "UATB_HEADSET";
1158 	case UATB_SPEAKERPHONE:	return "UATB_SPEAKERPHONE";
1159 	case UATB_SPEAKERPHONEESUP:	return "UATB_SPEAKERPHONEESUP";
1160 	case UATB_SPEAKERPHONEECANC:	return "UATB_SPEAKERPHONEECANC";
1161 	/* telephony terminal types */
1162 	case UATT_UNDEFINED:	return "UATT_UNDEFINED";
1163 	case UATT_PHONELINE:	return "UATT_PHONELINE";
1164 	case UATT_TELEPHONE:	return "UATT_TELEPHONE";
1165 	case UATT_DOWNLINEPHONE:	return "UATT_DOWNLINEPHONE";
1166 	/* external terminal types */
1167 	case UATE_UNDEFINED:	return "UATE_UNDEFINED";
1168 	case UATE_ANALOGCONN:	return "UATE_ANALOGCONN";
1169 	case UATE_LINECONN:	return "UATE_LINECONN";
1170 	case UATE_LEGACYCONN:	return "UATE_LEGACYCONN";
1171 	case UATE_DIGITALAUIFC:	return "UATE_DIGITALAUIFC";
1172 	case UATE_SPDIF:	return "UATE_SPDIF";
1173 	case UATE_1394DA:	return "UATE_1394DA";
1174 	case UATE_1394DV:	return "UATE_1394DV";
1175 	/* embedded function terminal types */
1176 	case UATF_UNDEFINED:	return "UATF_UNDEFINED";
1177 	case UATF_CALIBNOISE:	return "UATF_CALIBNOISE";
1178 	case UATF_EQUNOISE:	return "UATF_EQUNOISE";
1179 	case UATF_CDPLAYER:	return "UATF_CDPLAYER";
1180 	case UATF_DAT:	return "UATF_DAT";
1181 	case UATF_DCC:	return "UATF_DCC";
1182 	case UATF_MINIDISK:	return "UATF_MINIDISK";
1183 	case UATF_ANALOGTAPE:	return "UATF_ANALOGTAPE";
1184 	case UATF_PHONOGRAPH:	return "UATF_PHONOGRAPH";
1185 	case UATF_VCRAUDIO:	return "UATF_VCRAUDIO";
1186 	case UATF_VIDEODISCAUDIO:	return "UATF_VIDEODISCAUDIO";
1187 	case UATF_DVDAUDIO:	return "UATF_DVDAUDIO";
1188 	case UATF_TVTUNERAUDIO:	return "UATF_TVTUNERAUDIO";
1189 	case UATF_SATELLITE:	return "UATF_SATELLITE";
1190 	case UATF_CABLETUNER:	return "UATF_CABLETUNER";
1191 	case UATF_DSS:	return "UATF_DSS";
1192 	case UATF_RADIORECV:	return "UATF_RADIORECV";
1193 	case UATF_RADIOXMIT:	return "UATF_RADIOXMIT";
1194 	case UATF_MULTITRACK:	return "UATF_MULTITRACK";
1195 	case UATF_SYNTHESIZER:	return "UATF_SYNTHESIZER";
1196 	default:
1197 		snprintf(buf, sizeof(buf), "unknown type (0x%.4x)", terminal_type);
1198 		return buf;
1199 	}
1200 }
1201 #endif
1202 
1203 static int
1204 uaudio_determine_class(const struct io_terminal *iot, struct mixerctl *mix)
1205 {
1206 	int terminal_type;
1207 
1208 	if (iot == NULL || iot->output == NULL) {
1209 		mix->class = UAC_OUTPUT;
1210 		return 0;
1211 	}
1212 	terminal_type = 0;
1213 	if (iot->output->size == 1)
1214 		terminal_type = iot->output->terminals[0];
1215 	/*
1216 	 * If the only output terminal is USB,
1217 	 * the class is UAC_RECORD.
1218 	 */
1219 	if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) {
1220 		mix->class = UAC_RECORD;
1221 		if (iot->inputs_size == 1
1222 		    && iot->inputs[0] != NULL
1223 		    && iot->inputs[0]->size == 1)
1224 			return iot->inputs[0]->terminals[0];
1225 		else
1226 			return 0;
1227 	}
1228 	/*
1229 	 * If the ultimate destination of the unit is just one output
1230 	 * terminal and the unit is connected to the output terminal
1231 	 * directly, the class is UAC_OUTPUT.
1232 	 */
1233 	if (terminal_type != 0 && iot->direct) {
1234 		mix->class = UAC_OUTPUT;
1235 		return terminal_type;
1236 	}
1237 	/*
1238 	 * If the unit is connected to just one input terminal,
1239 	 * the class is UAC_INPUT.
1240 	 */
1241 	if (iot->inputs_size == 1 && iot->inputs[0] != NULL
1242 	    && iot->inputs[0]->size == 1) {
1243 		mix->class = UAC_INPUT;
1244 		return iot->inputs[0]->terminals[0];
1245 	}
1246 	/*
1247 	 * Otherwise, the class is UAC_OUTPUT.
1248 	 */
1249 	mix->class = UAC_OUTPUT;
1250 	return terminal_type;
1251 }
1252 
1253 #if defined(__FreeBSD__)
1254 static int
1255 uaudio_feature_name(const struct io_terminal *iot, struct mixerctl *mix)
1256 {
1257 	int terminal_type;
1258 
1259 	terminal_type = uaudio_determine_class(iot, mix);
1260 	if (mix->class == UAC_RECORD && terminal_type == 0)
1261 		return SOUND_MIXER_IMIX;
1262 	DPRINTF(("%s: terminal_type=%s\n", __func__,
1263 		 uaudio_get_terminal_name(terminal_type)));
1264 	switch (terminal_type) {
1265 	case UAT_STREAM:
1266 		return SOUND_MIXER_PCM;
1267 
1268 	case UATI_MICROPHONE:
1269 	case UATI_DESKMICROPHONE:
1270 	case UATI_PERSONALMICROPHONE:
1271 	case UATI_OMNIMICROPHONE:
1272 	case UATI_MICROPHONEARRAY:
1273 	case UATI_PROCMICROPHONEARR:
1274 		return SOUND_MIXER_MIC;
1275 
1276 	case UATO_SPEAKER:
1277 	case UATO_DESKTOPSPEAKER:
1278 	case UATO_ROOMSPEAKER:
1279 	case UATO_COMMSPEAKER:
1280 		return SOUND_MIXER_SPEAKER;
1281 
1282 	case UATE_ANALOGCONN:
1283 	case UATE_LINECONN:
1284 	case UATE_LEGACYCONN:
1285 		return SOUND_MIXER_LINE;
1286 
1287 	case UATE_DIGITALAUIFC:
1288 	case UATE_SPDIF:
1289 	case UATE_1394DA:
1290 	case UATE_1394DV:
1291 		return SOUND_MIXER_ALTPCM;
1292 
1293 	case UATF_CDPLAYER:
1294 		return SOUND_MIXER_CD;
1295 
1296 	case UATF_SYNTHESIZER:
1297 		return SOUND_MIXER_SYNTH;
1298 
1299 	case UATF_VIDEODISCAUDIO:
1300 	case UATF_DVDAUDIO:
1301 	case UATF_TVTUNERAUDIO:
1302 		return SOUND_MIXER_VIDEO;
1303 
1304 /* telephony terminal types */
1305 	case UATT_UNDEFINED:
1306 	case UATT_PHONELINE:
1307 	case UATT_TELEPHONE:
1308 	case UATT_DOWNLINEPHONE:
1309 		return SOUND_MIXER_PHONEIN;
1310 /*		return SOUND_MIXER_PHONEOUT;*/
1311 
1312 	case UATF_RADIORECV:
1313 	case UATF_RADIOXMIT:
1314 		return SOUND_MIXER_RADIO;
1315 
1316 	case UAT_UNDEFINED:
1317 	case UAT_VENDOR:
1318 	case UATI_UNDEFINED:
1319 /* output terminal types */
1320 	case UATO_UNDEFINED:
1321 	case UATO_DISPLAYAUDIO:
1322 	case UATO_SUBWOOFER:
1323 	case UATO_HEADPHONES:
1324 /* bidir terminal types */
1325 	case UATB_UNDEFINED:
1326 	case UATB_HANDSET:
1327 	case UATB_HEADSET:
1328 	case UATB_SPEAKERPHONE:
1329 	case UATB_SPEAKERPHONEESUP:
1330 	case UATB_SPEAKERPHONEECANC:
1331 /* external terminal types */
1332 	case UATE_UNDEFINED:
1333 /* embedded function terminal types */
1334 	case UATF_UNDEFINED:
1335 	case UATF_CALIBNOISE:
1336 	case UATF_EQUNOISE:
1337 	case UATF_DAT:
1338 	case UATF_DCC:
1339 	case UATF_MINIDISK:
1340 	case UATF_ANALOGTAPE:
1341 	case UATF_PHONOGRAPH:
1342 	case UATF_VCRAUDIO:
1343 	case UATF_SATELLITE:
1344 	case UATF_CABLETUNER:
1345 	case UATF_DSS:
1346 	case UATF_MULTITRACK:
1347 	case 0xffff:
1348 	default:
1349 		DPRINTF(("%s: 'master' for 0x%.4x\n", __func__, terminal_type));
1350 		return SOUND_MIXER_VOLUME;
1351 	}
1352 	return SOUND_MIXER_VOLUME;
1353 }
1354 #else
1355 static const char *
1356 uaudio_feature_name(const struct io_terminal *iot, struct mixerctl *mix)
1357 {
1358 	int terminal_type;
1359 
1360 	terminal_type = uaudio_determine_class(iot, mix);
1361 	if (mix->class == UAC_RECORD && terminal_type == 0)
1362 		return AudioNmixerout;
1363 	DPRINTF(("%s: terminal_type=%s\n", __func__,
1364 		 uaudio_get_terminal_name(terminal_type)));
1365 	switch (terminal_type) {
1366 	case UAT_STREAM:
1367 		return AudioNdac;
1368 
1369 	case UATI_MICROPHONE:
1370 	case UATI_DESKMICROPHONE:
1371 	case UATI_PERSONALMICROPHONE:
1372 	case UATI_OMNIMICROPHONE:
1373 	case UATI_MICROPHONEARRAY:
1374 	case UATI_PROCMICROPHONEARR:
1375 		return AudioNmicrophone;
1376 
1377 	case UATO_SPEAKER:
1378 	case UATO_DESKTOPSPEAKER:
1379 	case UATO_ROOMSPEAKER:
1380 	case UATO_COMMSPEAKER:
1381 		return AudioNspeaker;
1382 
1383 	case UATO_HEADPHONES:
1384 		return AudioNheadphone;
1385 
1386 	case UATO_SUBWOOFER:
1387 		return AudioNlfe;
1388 
1389 	/* telephony terminal types */
1390 	case UATT_UNDEFINED:
1391 	case UATT_PHONELINE:
1392 	case UATT_TELEPHONE:
1393 	case UATT_DOWNLINEPHONE:
1394 		return "phone";
1395 
1396 	case UATE_ANALOGCONN:
1397 	case UATE_LINECONN:
1398 	case UATE_LEGACYCONN:
1399 		return AudioNline;
1400 
1401 	case UATE_DIGITALAUIFC:
1402 	case UATE_SPDIF:
1403 	case UATE_1394DA:
1404 	case UATE_1394DV:
1405 		return AudioNaux;
1406 
1407 	case UATF_CDPLAYER:
1408 		return AudioNcd;
1409 
1410 	case UATF_SYNTHESIZER:
1411 		return AudioNfmsynth;
1412 
1413 	case UATF_VIDEODISCAUDIO:
1414 	case UATF_DVDAUDIO:
1415 	case UATF_TVTUNERAUDIO:
1416 		return AudioNvideo;
1417 
1418 	case UAT_UNDEFINED:
1419 	case UAT_VENDOR:
1420 	case UATI_UNDEFINED:
1421 /* output terminal types */
1422 	case UATO_UNDEFINED:
1423 	case UATO_DISPLAYAUDIO:
1424 /* bidir terminal types */
1425 	case UATB_UNDEFINED:
1426 	case UATB_HANDSET:
1427 	case UATB_HEADSET:
1428 	case UATB_SPEAKERPHONE:
1429 	case UATB_SPEAKERPHONEESUP:
1430 	case UATB_SPEAKERPHONEECANC:
1431 /* external terminal types */
1432 	case UATE_UNDEFINED:
1433 /* embedded function terminal types */
1434 	case UATF_UNDEFINED:
1435 	case UATF_CALIBNOISE:
1436 	case UATF_EQUNOISE:
1437 	case UATF_DAT:
1438 	case UATF_DCC:
1439 	case UATF_MINIDISK:
1440 	case UATF_ANALOGTAPE:
1441 	case UATF_PHONOGRAPH:
1442 	case UATF_VCRAUDIO:
1443 	case UATF_SATELLITE:
1444 	case UATF_CABLETUNER:
1445 	case UATF_DSS:
1446 	case UATF_RADIORECV:
1447 	case UATF_RADIOXMIT:
1448 	case UATF_MULTITRACK:
1449 	case 0xffff:
1450 	default:
1451 		DPRINTF(("%s: 'master' for 0x%.4x\n", __func__, terminal_type));
1452 		return AudioNmaster;
1453 	}
1454 	return AudioNmaster;
1455 }
1456 #endif
1457 
1458 static void
1459 uaudio_add_feature(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1460 {
1461 	const struct usb_audio_feature_unit *d;
1462 	const uByte *ctls;
1463 	int ctlsize;
1464 	int nchan;
1465 	u_int fumask, mmask, cmask;
1466 	struct mixerctl mix;
1467 	int chan, ctl, i, unit;
1468 #if defined(__FreeBSD__)
1469 	int mixernumber;
1470 #else
1471 	const char *mixername;
1472 #endif
1473 
1474 #define GET(i) (ctls[(i)*ctlsize] | \
1475 		(ctlsize > 1 ? ctls[(i)*ctlsize+1] << 8 : 0))
1476 	d = iot[id].d.fu;
1477 	ctls = d->bmaControls;
1478 	ctlsize = d->bControlSize;
1479 	nchan = (d->bLength - 7) / ctlsize;
1480 	mmask = GET(0);
1481 	/* Figure out what we can control */
1482 	for (cmask = 0, chan = 1; chan < nchan; chan++) {
1483 		DPRINTFN(9,("uaudio_add_feature: chan=%d mask=%x\n",
1484 			    chan, GET(chan)));
1485 		cmask |= GET(chan);
1486 	}
1487 
1488 #if !defined(__FreeBSD__)
1489 	DPRINTFN(1,("uaudio_add_feature: bUnitId=%d, "
1490 		    "%d channels, mmask=0x%04x, cmask=0x%04x\n",
1491 		    d->bUnitId, nchan, mmask, cmask));
1492 #endif
1493 
1494 	if (nchan > MIX_MAX_CHAN)
1495 		nchan = MIX_MAX_CHAN;
1496 	unit = d->bUnitId;
1497 	mix.wIndex = MAKE(unit, sc->sc_ac_iface);
1498 	for (ctl = MUTE_CONTROL; ctl < LOUDNESS_CONTROL; ctl++) {
1499 		fumask = FU_MASK(ctl);
1500 		DPRINTFN(4,("uaudio_add_feature: ctl=%d fumask=0x%04x\n",
1501 			    ctl, fumask));
1502 		if (mmask & fumask) {
1503 			mix.nchan = 1;
1504 			mix.wValue[0] = MAKE(ctl, 0);
1505 		} else if (cmask & fumask) {
1506 			mix.nchan = nchan - 1;
1507 			for (i = 1; i < nchan; i++) {
1508 				if (GET(i) & fumask)
1509 					mix.wValue[i-1] = MAKE(ctl, i);
1510 				else
1511 					mix.wValue[i-1] = -1;
1512 			}
1513 		} else {
1514 			continue;
1515 		}
1516 #undef GET
1517 
1518 #if defined(__FreeBSD__)
1519 		mixernumber = uaudio_feature_name(&iot[id], &mix);
1520 #else
1521 		mixername = uaudio_feature_name(&iot[id], &mix);
1522 #endif
1523 		switch (ctl) {
1524 		case MUTE_CONTROL:
1525 			mix.type = MIX_ON_OFF;
1526 #if defined(__FreeBSD__)
1527 			mix.ctl = SOUND_MIXER_NRDEVICES;
1528 #else
1529 			mix.ctlunit = "";
1530 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1531 				 "%s.%s", mixername, AudioNmute);
1532 #endif
1533 			break;
1534 		case VOLUME_CONTROL:
1535 			mix.type = MIX_SIGNED_16;
1536 #if defined(__FreeBSD__)
1537 			mix.ctl = mixernumber;
1538 #else
1539 			mix.ctlunit = AudioNvolume;
1540 			strlcpy(mix.ctlname, mixername, sizeof(mix.ctlname));
1541 #endif
1542 			break;
1543 		case BASS_CONTROL:
1544 			mix.type = MIX_SIGNED_8;
1545 #if defined(__FreeBSD__)
1546 			mix.ctl = SOUND_MIXER_BASS;
1547 #else
1548 			mix.ctlunit = AudioNbass;
1549 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1550 				 "%s.%s", mixername, AudioNbass);
1551 #endif
1552 			break;
1553 		case MID_CONTROL:
1554 			mix.type = MIX_SIGNED_8;
1555 #if defined(__FreeBSD__)
1556 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1557 #else
1558 			mix.ctlunit = AudioNmid;
1559 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1560 				 "%s.%s", mixername, AudioNmid);
1561 #endif
1562 			break;
1563 		case TREBLE_CONTROL:
1564 			mix.type = MIX_SIGNED_8;
1565 #if defined(__FreeBSD__)
1566 			mix.ctl = SOUND_MIXER_TREBLE;
1567 #else
1568 			mix.ctlunit = AudioNtreble;
1569 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1570 				 "%s.%s", mixername, AudioNtreble);
1571 #endif
1572 			break;
1573 		case GRAPHIC_EQUALIZER_CONTROL:
1574 			continue; /* XXX don't add anything */
1575 			break;
1576 		case AGC_CONTROL:
1577 			mix.type = MIX_ON_OFF;
1578 #if defined(__FreeBSD__)
1579 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1580 #else
1581 			mix.ctlunit = "";
1582 			snprintf(mix.ctlname, sizeof(mix.ctlname), "%s.%s",
1583 				 mixername, AudioNagc);
1584 #endif
1585 			break;
1586 		case DELAY_CONTROL:
1587 			mix.type = MIX_UNSIGNED_16;
1588 #if defined(__FreeBSD__)
1589 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1590 #else
1591 			mix.ctlunit = "4 ms";
1592 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1593 				 "%s.%s", mixername, AudioNdelay);
1594 #endif
1595 			break;
1596 		case BASS_BOOST_CONTROL:
1597 			mix.type = MIX_ON_OFF;
1598 #if defined(__FreeBSD__)
1599 			mix.ctl = SOUND_MIXER_NRDEVICES;	/* XXXXX */
1600 #else
1601 			mix.ctlunit = "";
1602 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1603 				 "%s.%s", mixername, AudioNbassboost);
1604 #endif
1605 			break;
1606 		case LOUDNESS_CONTROL:
1607 			mix.type = MIX_ON_OFF;
1608 #if defined(__FreeBSD__)
1609 			mix.ctl = SOUND_MIXER_LOUD;	/* Is this correct ? */
1610 #else
1611 			mix.ctlunit = "";
1612 			snprintf(mix.ctlname, sizeof(mix.ctlname),
1613 				 "%s.%s", mixername, AudioNloudness);
1614 #endif
1615 			break;
1616 		}
1617 		uaudio_mixer_add_ctl(sc, &mix);
1618 	}
1619 }
1620 
1621 static void
1622 uaudio_add_processing_updown(struct uaudio_softc *sc,
1623 			     const struct io_terminal *iot, int id)
1624 {
1625 	const struct usb_audio_processing_unit *d;
1626 	const struct usb_audio_processing_unit_1 *d1;
1627 	const struct usb_audio_processing_unit_updown *ud;
1628 	struct mixerctl mix;
1629 	int i;
1630 
1631 	d = iot[id].d.pu;
1632 	d1 = (const struct usb_audio_processing_unit_1 *)
1633 		&d->baSourceId[d->bNrInPins];
1634 	ud = (const struct usb_audio_processing_unit_updown *)
1635 		&d1->bmControls[d1->bControlSize];
1636 	DPRINTFN(2,("uaudio_add_processing_updown: bUnitId=%d bNrModes=%d\n",
1637 		    d->bUnitId, ud->bNrModes));
1638 
1639 	if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) {
1640 		DPRINTF(("uaudio_add_processing_updown: no mode select\n"));
1641 		return;
1642 	}
1643 
1644 	mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1645 	mix.nchan = 1;
1646 	mix.wValue[0] = MAKE(UD_MODE_SELECT_CONTROL, 0);
1647 	uaudio_determine_class(&iot[id], &mix);
1648 	mix.type = MIX_ON_OFF;	/* XXX */
1649 #if !defined(__FreeBSD__)
1650 	mix.ctlunit = "";
1651 	snprintf(mix.ctlname, sizeof(mix.ctlname), "pro%d-mode", d->bUnitId);
1652 #endif
1653 
1654 	for (i = 0; i < ud->bNrModes; i++) {
1655 		DPRINTFN(2,("uaudio_add_processing_updown: i=%d bm=0x%x\n",
1656 			    i, UGETW(ud->waModes[i])));
1657 		/* XXX */
1658 	}
1659 	uaudio_mixer_add_ctl(sc, &mix);
1660 }
1661 
1662 static void
1663 uaudio_add_processing(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1664 {
1665 	const struct usb_audio_processing_unit *d;
1666 	const struct usb_audio_processing_unit_1 *d1;
1667 	int ptype;
1668 	struct mixerctl mix;
1669 
1670 	d = iot[id].d.pu;
1671 	d1 = (const struct usb_audio_processing_unit_1 *)
1672 		&d->baSourceId[d->bNrInPins];
1673 	ptype = UGETW(d->wProcessType);
1674 	DPRINTFN(2,("uaudio_add_processing: wProcessType=%d bUnitId=%d "
1675 		    "bNrInPins=%d\n", ptype, d->bUnitId, d->bNrInPins));
1676 
1677 	if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) {
1678 		mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1679 		mix.nchan = 1;
1680 		mix.wValue[0] = MAKE(XX_ENABLE_CONTROL, 0);
1681 		uaudio_determine_class(&iot[id], &mix);
1682 		mix.type = MIX_ON_OFF;
1683 #if !defined(__FreeBSD__)
1684 		mix.ctlunit = "";
1685 		snprintf(mix.ctlname, sizeof(mix.ctlname), "pro%d.%d-enable",
1686 		    d->bUnitId, ptype);
1687 #endif
1688 		uaudio_mixer_add_ctl(sc, &mix);
1689 	}
1690 
1691 	switch(ptype) {
1692 	case UPDOWNMIX_PROCESS:
1693 		uaudio_add_processing_updown(sc, iot, id);
1694 		break;
1695 	case DOLBY_PROLOGIC_PROCESS:
1696 	case P3D_STEREO_EXTENDER_PROCESS:
1697 	case REVERBATION_PROCESS:
1698 	case CHORUS_PROCESS:
1699 	case DYN_RANGE_COMP_PROCESS:
1700 	default:
1701 #ifdef USB_DEBUG
1702 		printf("uaudio_add_processing: unit %d, type=%d not impl.\n",
1703 		       d->bUnitId, ptype);
1704 #endif
1705 		break;
1706 	}
1707 }
1708 
1709 static void
1710 uaudio_add_extension(struct uaudio_softc *sc, const struct io_terminal *iot, int id)
1711 {
1712 	const struct usb_audio_extension_unit *d;
1713 	const struct usb_audio_extension_unit_1 *d1;
1714 	struct mixerctl mix;
1715 
1716 	d = iot[id].d.eu;
1717 	d1 = (const struct usb_audio_extension_unit_1 *)
1718 		&d->baSourceId[d->bNrInPins];
1719 	DPRINTFN(2,("uaudio_add_extension: bUnitId=%d bNrInPins=%d\n",
1720 		    d->bUnitId, d->bNrInPins));
1721 
1722 	if (usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_NO_XU)
1723 		return;
1724 
1725 	if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) {
1726 		mix.wIndex = MAKE(d->bUnitId, sc->sc_ac_iface);
1727 		mix.nchan = 1;
1728 		mix.wValue[0] = MAKE(UA_EXT_ENABLE, 0);
1729 		uaudio_determine_class(&iot[id], &mix);
1730 		mix.type = MIX_ON_OFF;
1731 #if !defined(__FreeBSD__)
1732 		mix.ctlunit = "";
1733 		snprintf(mix.ctlname, sizeof(mix.ctlname), "ext%d-enable",
1734 		    d->bUnitId);
1735 #endif
1736 		uaudio_mixer_add_ctl(sc, &mix);
1737 	}
1738 }
1739 
1740 static struct terminal_list*
1741 uaudio_merge_terminal_list(const struct io_terminal *iot)
1742 {
1743 	struct terminal_list *tml;
1744 	uint16_t *ptm;
1745 	int i, len;
1746 
1747 	len = 0;
1748 	if (iot->inputs == NULL)
1749 		return NULL;
1750 	for (i = 0; i < iot->inputs_size; i++) {
1751 		if (iot->inputs[i] != NULL)
1752 			len += iot->inputs[i]->size;
1753 	}
1754 	tml = malloc(TERMINAL_LIST_SIZE(len), M_TEMP, M_NOWAIT);
1755 	if (tml == NULL) {
1756 		printf("uaudio_merge_terminal_list: no memory\n");
1757 		return NULL;
1758 	}
1759 	tml->size = 0;
1760 	ptm = tml->terminals;
1761 	for (i = 0; i < iot->inputs_size; i++) {
1762 		if (iot->inputs[i] == NULL)
1763 			continue;
1764 		if (iot->inputs[i]->size > len)
1765 			break;
1766 		memcpy(ptm, iot->inputs[i]->terminals,
1767 		       iot->inputs[i]->size * sizeof(uint16_t));
1768 		tml->size += iot->inputs[i]->size;
1769 		ptm += iot->inputs[i]->size;
1770 		len -= iot->inputs[i]->size;
1771 	}
1772 	return tml;
1773 }
1774 
1775 static struct terminal_list *
1776 uaudio_io_terminaltype(int outtype, struct io_terminal *iot, int id)
1777 {
1778 	struct terminal_list *tml;
1779 	struct io_terminal *it;
1780 	int src_id, i;
1781 
1782 	it = &iot[id];
1783 	if (it->output != NULL) {
1784 		/* already has outtype? */
1785 		for (i = 0; i < it->output->size; i++)
1786 			if (it->output->terminals[i] == outtype)
1787 				return uaudio_merge_terminal_list(it);
1788 		tml = malloc(TERMINAL_LIST_SIZE(it->output->size + 1),
1789 			     M_TEMP, M_NOWAIT);
1790 		if (tml == NULL) {
1791 			printf("uaudio_io_terminaltype: no memory\n");
1792 			return uaudio_merge_terminal_list(it);
1793 		}
1794 		memcpy(tml, it->output, TERMINAL_LIST_SIZE(it->output->size));
1795 		tml->terminals[it->output->size] = outtype;
1796 		tml->size++;
1797 		free(it->output, M_TEMP);
1798 		it->output = tml;
1799 		if (it->inputs != NULL) {
1800 			for (i = 0; i < it->inputs_size; i++)
1801 				if (it->inputs[i] != NULL)
1802 					free(it->inputs[i], M_TEMP);
1803 			free(it->inputs, M_TEMP);
1804 		}
1805 		it->inputs_size = 0;
1806 		it->inputs = NULL;
1807 	} else {		/* end `iot[id] != NULL' */
1808 		it->inputs_size = 0;
1809 		it->inputs = NULL;
1810 		it->output = malloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
1811 		if (it->output == NULL) {
1812 			printf("uaudio_io_terminaltype: no memory\n");
1813 			return NULL;
1814 		}
1815 		it->output->terminals[0] = outtype;
1816 		it->output->size = 1;
1817 		it->direct = FALSE;
1818 	}
1819 
1820 	switch (it->d.desc->bDescriptorSubtype) {
1821 	case UDESCSUB_AC_INPUT:
1822 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1823 		if (it->inputs == NULL) {
1824 			printf("uaudio_io_terminaltype: no memory\n");
1825 			return NULL;
1826 		}
1827 		tml = malloc(TERMINAL_LIST_SIZE(1), M_TEMP, M_NOWAIT);
1828 		if (tml == NULL) {
1829 			printf("uaudio_io_terminaltype: no memory\n");
1830 			free(it->inputs, M_TEMP);
1831 			it->inputs = NULL;
1832 			return NULL;
1833 		}
1834 		it->inputs[0] = tml;
1835 		tml->terminals[0] = UGETW(it->d.it->wTerminalType);
1836 		tml->size = 1;
1837 		it->inputs_size = 1;
1838 		return uaudio_merge_terminal_list(it);
1839 	case UDESCSUB_AC_FEATURE:
1840 		src_id = it->d.fu->bSourceId;
1841 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1842 		if (it->inputs == NULL) {
1843 			printf("uaudio_io_terminaltype: no memory\n");
1844 			return uaudio_io_terminaltype(outtype, iot, src_id);
1845 		}
1846 		it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
1847 		it->inputs_size = 1;
1848 		return uaudio_merge_terminal_list(it);
1849 	case UDESCSUB_AC_OUTPUT:
1850 		it->inputs = malloc(sizeof(struct terminal_list *), M_TEMP, M_NOWAIT);
1851 		if (it->inputs == NULL) {
1852 			printf("uaudio_io_terminaltype: no memory\n");
1853 			return NULL;
1854 		}
1855 		src_id = it->d.ot->bSourceId;
1856 		it->inputs[0] = uaudio_io_terminaltype(outtype, iot, src_id);
1857 		it->inputs_size = 1;
1858 		iot[src_id].direct = TRUE;
1859 		return NULL;
1860 	case UDESCSUB_AC_MIXER:
1861 		it->inputs_size = 0;
1862 		it->inputs = malloc(sizeof(struct terminal_list *)
1863 				    * it->d.mu->bNrInPins, M_TEMP, M_NOWAIT);
1864 		if (it->inputs == NULL) {
1865 			printf("uaudio_io_terminaltype: no memory\n");
1866 			return NULL;
1867 		}
1868 		for (i = 0; i < it->d.mu->bNrInPins; i++) {
1869 			src_id = it->d.mu->baSourceId[i];
1870 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1871 							       src_id);
1872 			it->inputs_size++;
1873 		}
1874 		return uaudio_merge_terminal_list(it);
1875 	case UDESCSUB_AC_SELECTOR:
1876 		it->inputs_size = 0;
1877 		it->inputs = malloc(sizeof(struct terminal_list *)
1878 				    * it->d.su->bNrInPins, M_TEMP, M_NOWAIT);
1879 		if (it->inputs == NULL) {
1880 			printf("uaudio_io_terminaltype: no memory\n");
1881 			return NULL;
1882 		}
1883 		for (i = 0; i < it->d.su->bNrInPins; i++) {
1884 			src_id = it->d.su->baSourceId[i];
1885 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1886 							       src_id);
1887 			it->inputs_size++;
1888 		}
1889 		return uaudio_merge_terminal_list(it);
1890 	case UDESCSUB_AC_PROCESSING:
1891 		it->inputs_size = 0;
1892 		it->inputs = malloc(sizeof(struct terminal_list *)
1893 				    * it->d.pu->bNrInPins, M_TEMP, M_NOWAIT);
1894 		if (it->inputs == NULL) {
1895 			printf("uaudio_io_terminaltype: no memory\n");
1896 			return NULL;
1897 		}
1898 		for (i = 0; i < it->d.pu->bNrInPins; i++) {
1899 			src_id = it->d.pu->baSourceId[i];
1900 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1901 							       src_id);
1902 			it->inputs_size++;
1903 		}
1904 		return uaudio_merge_terminal_list(it);
1905 	case UDESCSUB_AC_EXTENSION:
1906 		it->inputs_size = 0;
1907 		it->inputs = malloc(sizeof(struct terminal_list *)
1908 				    * it->d.eu->bNrInPins, M_TEMP, M_NOWAIT);
1909 		if (it->inputs == NULL) {
1910 			printf("uaudio_io_terminaltype: no memory\n");
1911 			return NULL;
1912 		}
1913 		for (i = 0; i < it->d.eu->bNrInPins; i++) {
1914 			src_id = it->d.eu->baSourceId[i];
1915 			it->inputs[i] = uaudio_io_terminaltype(outtype, iot,
1916 							       src_id);
1917 			it->inputs_size++;
1918 		}
1919 		return uaudio_merge_terminal_list(it);
1920 	case UDESCSUB_AC_HEADER:
1921 	default:
1922 		return NULL;
1923 	}
1924 }
1925 
1926 static usbd_status
1927 uaudio_identify(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
1928 {
1929 	usbd_status err;
1930 
1931 	err = uaudio_identify_ac(sc, cdesc);
1932 	if (err)
1933 		return err;
1934 	return uaudio_identify_as(sc, cdesc);
1935 }
1936 
1937 static void
1938 uaudio_add_alt(struct uaudio_softc *sc, const struct as_info *ai)
1939 {
1940 	size_t len;
1941 	struct as_info *nai;
1942 
1943 	len = sizeof(*ai) * (sc->sc_nalts + 1);
1944 	nai = malloc(len, M_USBDEV, M_NOWAIT);
1945 	if (nai == NULL) {
1946 		printf("uaudio_add_alt: no memory\n");
1947 		return;
1948 	}
1949 	/* Copy old data, if there was any */
1950 	if (sc->sc_nalts != 0) {
1951 		memcpy(nai, sc->sc_alts, sizeof(*ai) * (sc->sc_nalts));
1952 		free(sc->sc_alts, M_USBDEV);
1953 	}
1954 	sc->sc_alts = nai;
1955 	DPRINTFN(2,("uaudio_add_alt: adding alt=%d, enc=%d\n",
1956 		    ai->alt, ai->encoding));
1957 	sc->sc_alts[sc->sc_nalts++] = *ai;
1958 }
1959 
1960 static usbd_status
1961 uaudio_process_as(struct uaudio_softc *sc, const char *buf, int *offsp,
1962 		  int size, const usb_interface_descriptor_t *id)
1963 #define offs (*offsp)
1964 {
1965 	const struct usb_audio_streaming_interface_descriptor *asid;
1966 	const struct usb_audio_streaming_type1_descriptor *asf1d;
1967 	const usb_endpoint_descriptor_audio_t *ed;
1968 	const usb_endpoint_descriptor_audio_t *epdesc1;
1969 	const struct usb_audio_streaming_endpoint_descriptor *sed;
1970 	int format, chan, prec, enc;
1971 	int dir, type, sync;
1972 	struct as_info ai;
1973 	const char *format_str;
1974 
1975 	asid = (const void *)(buf + offs);
1976 
1977 	if (asid->bDescriptorType != UDESC_CS_INTERFACE ||
1978 	    asid->bDescriptorSubtype != AS_GENERAL)
1979 		return USBD_INVAL;
1980 	DPRINTF(("uaudio_process_as: asid: bTerminakLink=%d wFormatTag=%d\n",
1981 		 asid->bTerminalLink, UGETW(asid->wFormatTag)));
1982 	offs += asid->bLength;
1983 	if (offs > size)
1984 		return USBD_INVAL;
1985 
1986 	asf1d = (const void *)(buf + offs);
1987 	if (asf1d->bDescriptorType != UDESC_CS_INTERFACE ||
1988 	    asf1d->bDescriptorSubtype != FORMAT_TYPE)
1989 		return USBD_INVAL;
1990 	offs += asf1d->bLength;
1991 	if (offs > size)
1992 		return USBD_INVAL;
1993 
1994 	if (asf1d->bFormatType != FORMAT_TYPE_I) {
1995 		printf("%s: ignored setting with type %d format\n",
1996 		       device_get_nameunit(sc->sc_dev), UGETW(asid->wFormatTag));
1997 		return USBD_NORMAL_COMPLETION;
1998 	}
1999 
2000 	ed = (const void *)(buf + offs);
2001 	if (ed->bDescriptorType != UDESC_ENDPOINT)
2002 		return USBD_INVAL;
2003 	DPRINTF(("uaudio_process_as: endpoint[0] bLength=%d bDescriptorType=%d "
2004 		 "bEndpointAddress=%d bmAttributes=0x%x wMaxPacketSize=%d "
2005 		 "bInterval=%d bRefresh=%d bSynchAddress=%d\n",
2006 		 ed->bLength, ed->bDescriptorType, ed->bEndpointAddress,
2007 		 ed->bmAttributes, UGETW(ed->wMaxPacketSize),
2008 		 ed->bInterval, ed->bRefresh, ed->bSynchAddress));
2009 	offs += ed->bLength;
2010 	if (offs > size)
2011 		return USBD_INVAL;
2012 	if (UE_GET_XFERTYPE(ed->bmAttributes) != UE_ISOCHRONOUS)
2013 		return USBD_INVAL;
2014 
2015 	dir = UE_GET_DIR(ed->bEndpointAddress);
2016 	type = UE_GET_ISO_TYPE(ed->bmAttributes);
2017 	if ((usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_AU_INP_ASYNC) &&
2018 	    dir == UE_DIR_IN && type == UE_ISO_ADAPT)
2019 		type = UE_ISO_ASYNC;
2020 
2021 	/* We can't handle endpoints that need a sync pipe yet. */
2022 	sync = FALSE;
2023 	if (dir == UE_DIR_IN && type == UE_ISO_ADAPT) {
2024 		sync = TRUE;
2025 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
2026 		printf("%s: ignored input endpoint of type adaptive\n",
2027 		       device_get_nameunit(sc->sc_dev));
2028 		return USBD_NORMAL_COMPLETION;
2029 #endif
2030 	}
2031 	if (dir != UE_DIR_IN && type == UE_ISO_ASYNC) {
2032 		sync = TRUE;
2033 #ifndef UAUDIO_MULTIPLE_ENDPOINTS
2034 		printf("%s: ignored output endpoint of type async\n",
2035 		       device_get_nameunit(sc->sc_dev));
2036 		return USBD_NORMAL_COMPLETION;
2037 #endif
2038 	}
2039 
2040 	sed = (const void *)(buf + offs);
2041 	if (sed->bDescriptorType != UDESC_CS_ENDPOINT ||
2042 	    sed->bDescriptorSubtype != AS_GENERAL)
2043 		return USBD_INVAL;
2044 	DPRINTF((" streadming_endpoint: offset=%d bLength=%d\n", offs, sed->bLength));
2045 	offs += sed->bLength;
2046 	if (offs > size)
2047 		return USBD_INVAL;
2048 
2049 #ifdef UAUDIO_MULTIPLE_ENDPOINTS
2050 	if (sync && id->bNumEndpoints <= 1) {
2051 		printf("%s: a sync-pipe endpoint but no other endpoint\n",
2052 		       device_get_nameunit(sc->sc_dev));
2053 		return USBD_INVAL;
2054 	}
2055 #endif
2056 	if (!sync && id->bNumEndpoints > 1) {
2057 		printf("%s: non sync-pipe endpoint but multiple endpoints\n",
2058 		       device_get_nameunit(sc->sc_dev));
2059 		return USBD_INVAL;
2060 	}
2061 	epdesc1 = NULL;
2062 	if (id->bNumEndpoints > 1) {
2063 		epdesc1 = (const void*)(buf + offs);
2064 		if (epdesc1->bDescriptorType != UDESC_ENDPOINT)
2065 			return USBD_INVAL;
2066 		DPRINTF(("uaudio_process_as: endpoint[1] bLength=%d "
2067 			 "bDescriptorType=%d bEndpointAddress=%d "
2068 			 "bmAttributes=0x%x wMaxPacketSize=%d bInterval=%d "
2069 			 "bRefresh=%d bSynchAddress=%d\n",
2070 			 epdesc1->bLength, epdesc1->bDescriptorType,
2071 			 epdesc1->bEndpointAddress, epdesc1->bmAttributes,
2072 			 UGETW(epdesc1->wMaxPacketSize), epdesc1->bInterval,
2073 			 epdesc1->bRefresh, epdesc1->bSynchAddress));
2074 		offs += epdesc1->bLength;
2075 		if (offs > size)
2076 			return USBD_INVAL;
2077 		if (epdesc1->bSynchAddress != 0) {
2078 			printf("%s: invalid endpoint: bSynchAddress=0\n",
2079 			       device_get_nameunit(sc->sc_dev));
2080 			return USBD_INVAL;
2081 		}
2082 		if (UE_GET_XFERTYPE(epdesc1->bmAttributes) != UE_ISOCHRONOUS) {
2083 			printf("%s: invalid endpoint: bmAttributes=0x%x\n",
2084 			       device_get_nameunit(sc->sc_dev), epdesc1->bmAttributes);
2085 			return USBD_INVAL;
2086 		}
2087 		if (epdesc1->bEndpointAddress != ed->bSynchAddress) {
2088 			printf("%s: invalid endpoint addresses: "
2089 			       "ep[0]->bSynchAddress=0x%x "
2090 			       "ep[1]->bEndpointAddress=0x%x\n",
2091 			       device_get_nameunit(sc->sc_dev), ed->bSynchAddress,
2092 			       epdesc1->bEndpointAddress);
2093 			return USBD_INVAL;
2094 		}
2095 		/* UE_GET_ADDR(epdesc1->bEndpointAddress), and epdesc1->bRefresh */
2096 	}
2097 
2098 	format = UGETW(asid->wFormatTag);
2099 	chan = asf1d->bNrChannels;
2100 	prec = asf1d->bBitResolution;
2101 	if (prec != 8 && prec != 16 && prec != 24 && prec != 32) {
2102 		printf("%s: ignored setting with precision %d\n",
2103 		       device_get_nameunit(sc->sc_dev), prec);
2104 		return USBD_NORMAL_COMPLETION;
2105 	}
2106 	switch (format) {
2107 	case UA_FMT_PCM:
2108 		if (prec == 8) {
2109 			sc->sc_altflags |= HAS_8;
2110 		} else if (prec == 16) {
2111 			sc->sc_altflags |= HAS_16;
2112 		} else if (prec == 24) {
2113 			sc->sc_altflags |= HAS_24;
2114 		} else if (prec == 32) {
2115 			sc->sc_altflags |= HAS_32;
2116 		}
2117 		enc = AUDIO_ENCODING_SLINEAR_LE;
2118 		format_str = "pcm";
2119 		break;
2120 	case UA_FMT_PCM8:
2121 		enc = AUDIO_ENCODING_ULINEAR_LE;
2122 		sc->sc_altflags |= HAS_8U;
2123 		format_str = "pcm8";
2124 		break;
2125 	case UA_FMT_ALAW:
2126 		enc = AUDIO_ENCODING_ALAW;
2127 		sc->sc_altflags |= HAS_ALAW;
2128 		format_str = "alaw";
2129 		break;
2130 	case UA_FMT_MULAW:
2131 		enc = AUDIO_ENCODING_ULAW;
2132 		sc->sc_altflags |= HAS_MULAW;
2133 		format_str = "mulaw";
2134 		break;
2135 	case UA_FMT_IEEE_FLOAT:
2136 	default:
2137 		printf("%s: ignored setting with format %d\n",
2138 		       device_get_nameunit(sc->sc_dev), format);
2139 		return USBD_NORMAL_COMPLETION;
2140 	}
2141 #ifdef USB_DEBUG
2142 	printf("%s: %s: %dch, %d/%dbit, %s,", device_get_nameunit(sc->sc_dev),
2143 	       dir == UE_DIR_IN ? "recording" : "playback",
2144 	       chan, prec, asf1d->bSubFrameSize * 8, format_str);
2145 	if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
2146 		printf(" %d-%dHz\n", UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
2147 	} else {
2148 		int r;
2149 		printf(" %d", UA_GETSAMP(asf1d, 0));
2150 		for (r = 1; r < asf1d->bSamFreqType; r++)
2151 			printf(",%d", UA_GETSAMP(asf1d, r));
2152 		printf("Hz\n");
2153 	}
2154 #endif
2155 #if defined(__FreeBSD__)
2156 	if (sc->uaudio_sndstat_flag != 0) {
2157 		sbuf_printf(&(sc->uaudio_sndstat), "\n\t");
2158 		sbuf_printf(&(sc->uaudio_sndstat),
2159 		    "mode %d:(%s) %dch, %d/%dbit, %s,",
2160 		    id->bAlternateSetting,
2161 		    dir == UE_DIR_IN ? "input" : "output",
2162 		    chan, prec, asf1d->bSubFrameSize * 8, format_str);
2163 		if (asf1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
2164 			sbuf_printf(&(sc->uaudio_sndstat), " %d-%dHz",
2165 			    UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
2166 		} else {
2167 			int r;
2168 			sbuf_printf(&(sc->uaudio_sndstat),
2169 			    " %d", UA_GETSAMP(asf1d, 0));
2170 			for (r = 1; r < asf1d->bSamFreqType; r++)
2171 				sbuf_printf(&(sc->uaudio_sndstat),
2172 				    ",%d", UA_GETSAMP(asf1d, r));
2173 			sbuf_printf(&(sc->uaudio_sndstat), "Hz");
2174 		}
2175 	}
2176 #endif
2177 	ai.alt = id->bAlternateSetting;
2178 	ai.encoding = enc;
2179 	ai.attributes = sed->bmAttributes;
2180 	ai.idesc = id;
2181 	ai.edesc = ed;
2182 	ai.edesc1 = epdesc1;
2183 	ai.asf1desc = asf1d;
2184 	ai.sc_busy = 0;
2185 	ai.ifaceh = NULL;
2186 	uaudio_add_alt(sc, &ai);
2187 #ifdef USB_DEBUG
2188 	if (ai.attributes & UA_SED_FREQ_CONTROL)
2189 		DPRINTFN(1, ("uaudio_process_as:  FREQ_CONTROL\n"));
2190 	if (ai.attributes & UA_SED_PITCH_CONTROL)
2191 		DPRINTFN(1, ("uaudio_process_as:  PITCH_CONTROL\n"));
2192 #endif
2193 	sc->sc_mode |= (dir == UE_DIR_OUT) ? AUMODE_PLAY : AUMODE_RECORD;
2194 
2195 	return USBD_NORMAL_COMPLETION;
2196 }
2197 #undef offs
2198 
2199 static usbd_status
2200 uaudio_identify_as(struct uaudio_softc *sc,
2201 		   const usb_config_descriptor_t *cdesc)
2202 {
2203 	const usb_interface_descriptor_t *id;
2204 	const char *buf;
2205 	int size, offs;
2206 
2207 	size = UGETW(cdesc->wTotalLength);
2208 	buf = (const char *)cdesc;
2209 
2210 	/* Locate the AudioStreaming interface descriptor. */
2211 	offs = 0;
2212 	id = uaudio_find_iface(buf, size, &offs, UISUBCLASS_AUDIOSTREAM);
2213 	if (id == NULL)
2214 		return USBD_INVAL;
2215 
2216 #if defined(__FreeBSD__)
2217 	sc->uaudio_sndstat_flag = 0;
2218 	if (sbuf_new(&(sc->uaudio_sndstat), NULL, 4096, SBUF_AUTOEXTEND) != NULL)
2219 		sc->uaudio_sndstat_flag = 1;
2220 #endif
2221 	/* Loop through all the alternate settings. */
2222 	while (offs <= size) {
2223 		DPRINTFN(2, ("uaudio_identify: interface=%d offset=%d\n",
2224 		    id->bInterfaceNumber, offs));
2225 		switch (id->bNumEndpoints) {
2226 		case 0:
2227 			DPRINTFN(2, ("uaudio_identify: AS null alt=%d\n",
2228 				     id->bAlternateSetting));
2229 			sc->sc_nullalt = id->bAlternateSetting;
2230 			break;
2231 		case 1:
2232 #ifdef UAUDIO_MULTIPLE_ENDPOINTS
2233 		case 2:
2234 #endif
2235 			uaudio_process_as(sc, buf, &offs, size, id);
2236 			break;
2237 		default:
2238 			printf("%s: ignored audio interface with %d "
2239 			       "endpoints\n",
2240 			       device_get_nameunit(sc->sc_dev), id->bNumEndpoints);
2241 			break;
2242 		}
2243 		id = uaudio_find_iface(buf, size, &offs,UISUBCLASS_AUDIOSTREAM);
2244 		if (id == NULL)
2245 			break;
2246 	}
2247 #if defined(__FreeBSD__)
2248 	sbuf_finish(&(sc->uaudio_sndstat));
2249 #endif
2250 	if (offs > size)
2251 		return USBD_INVAL;
2252 	DPRINTF(("uaudio_identify_as: %d alts available\n", sc->sc_nalts));
2253 
2254 	if (sc->sc_mode == 0) {
2255 		printf("%s: no usable endpoint found\n",
2256 		       device_get_nameunit(sc->sc_dev));
2257 		return USBD_INVAL;
2258 	}
2259 
2260 	return USBD_NORMAL_COMPLETION;
2261 }
2262 
2263 static usbd_status
2264 uaudio_identify_ac(struct uaudio_softc *sc, const usb_config_descriptor_t *cdesc)
2265 {
2266 	struct io_terminal* iot;
2267 	const usb_interface_descriptor_t *id;
2268 	const struct usb_audio_control_descriptor *acdp;
2269 	const usb_descriptor_t *dp;
2270 	const struct usb_audio_output_terminal *pot;
2271 	struct terminal_list *tml;
2272 	const char *buf, *ibuf, *ibufend;
2273 	int size, offs, aclen, ndps, i, j;
2274 
2275 	size = UGETW(cdesc->wTotalLength);
2276 	buf = (const char *)cdesc;
2277 
2278 	/* Locate the AudioControl interface descriptor. */
2279 	offs = 0;
2280 	id = uaudio_find_iface(buf, size, &offs, UISUBCLASS_AUDIOCONTROL);
2281 	if (id == NULL)
2282 		return USBD_INVAL;
2283 	if (offs + sizeof *acdp > size)
2284 		return USBD_INVAL;
2285 	sc->sc_ac_iface = id->bInterfaceNumber;
2286 	DPRINTFN(2,("uaudio_identify_ac: AC interface is %d\n", sc->sc_ac_iface));
2287 
2288 	/* A class-specific AC interface header should follow. */
2289 	ibuf = buf + offs;
2290 	acdp = (const struct usb_audio_control_descriptor *)ibuf;
2291 	if (acdp->bDescriptorType != UDESC_CS_INTERFACE ||
2292 	    acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)
2293 		return USBD_INVAL;
2294 	aclen = UGETW(acdp->wTotalLength);
2295 	if (offs + aclen > size)
2296 		return USBD_INVAL;
2297 
2298 	if (!(usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_BAD_ADC) &&
2299 	     UGETW(acdp->bcdADC) != UAUDIO_VERSION)
2300 		return USBD_INVAL;
2301 
2302 	sc->sc_audio_rev = UGETW(acdp->bcdADC);
2303 	DPRINTFN(2,("uaudio_identify_ac: found AC header, vers=%03x, len=%d\n",
2304 		 sc->sc_audio_rev, aclen));
2305 
2306 	sc->sc_nullalt = -1;
2307 
2308 	/* Scan through all the AC specific descriptors */
2309 	ibufend = ibuf + aclen;
2310 	dp = (const usb_descriptor_t *)ibuf;
2311 	ndps = 0;
2312 	iot = malloc(sizeof(struct io_terminal) * 256, M_TEMP, M_NOWAIT | M_ZERO);
2313 	if (iot == NULL) {
2314 		printf("%s: no memory\n", __func__);
2315 		return USBD_NOMEM;
2316 	}
2317 	for (;;) {
2318 		ibuf += dp->bLength;
2319 		if (ibuf >= ibufend)
2320 			break;
2321 		dp = (const usb_descriptor_t *)ibuf;
2322 		if (ibuf + dp->bLength > ibufend) {
2323 			free(iot, M_TEMP);
2324 			return USBD_INVAL;
2325 		}
2326 		if (dp->bDescriptorType != UDESC_CS_INTERFACE) {
2327 			printf("uaudio_identify_ac: skip desc type=0x%02x\n",
2328 			       dp->bDescriptorType);
2329 			continue;
2330 		}
2331 		i = ((const struct usb_audio_input_terminal *)dp)->bTerminalId;
2332 		iot[i].d.desc = dp;
2333 		if (i > ndps)
2334 			ndps = i;
2335 	}
2336 	ndps++;
2337 
2338 	/* construct io_terminal */
2339 	for (i = 0; i < ndps; i++) {
2340 		dp = iot[i].d.desc;
2341 		if (dp == NULL)
2342 			continue;
2343 		if (dp->bDescriptorSubtype != UDESCSUB_AC_OUTPUT)
2344 			continue;
2345 		pot = iot[i].d.ot;
2346 		tml = uaudio_io_terminaltype(UGETW(pot->wTerminalType), iot, i);
2347 		if (tml != NULL)
2348 			free(tml, M_TEMP);
2349 	}
2350 
2351 #ifdef USB_DEBUG
2352 	for (i = 0; i < 256; i++) {
2353 		struct usb_audio_cluster cluster;
2354 
2355 		if (iot[i].d.desc == NULL)
2356 			continue;
2357 		printf("id %d:\t", i);
2358 		switch (iot[i].d.desc->bDescriptorSubtype) {
2359 		case UDESCSUB_AC_INPUT:
2360 			printf("AC_INPUT type=%s\n", uaudio_get_terminal_name
2361 				  (UGETW(iot[i].d.it->wTerminalType)));
2362 			printf("\t");
2363 			cluster = uaudio_get_cluster(i, iot);
2364 			uaudio_dump_cluster(&cluster);
2365 			printf("\n");
2366 			break;
2367 		case UDESCSUB_AC_OUTPUT:
2368 			printf("AC_OUTPUT type=%s ", uaudio_get_terminal_name
2369 				  (UGETW(iot[i].d.ot->wTerminalType)));
2370 			printf("src=%d\n", iot[i].d.ot->bSourceId);
2371 			break;
2372 		case UDESCSUB_AC_MIXER:
2373 			printf("AC_MIXER src=");
2374 			for (j = 0; j < iot[i].d.mu->bNrInPins; j++)
2375 				printf("%d ", iot[i].d.mu->baSourceId[j]);
2376 			printf("\n\t");
2377 			cluster = uaudio_get_cluster(i, iot);
2378 			uaudio_dump_cluster(&cluster);
2379 			printf("\n");
2380 			break;
2381 		case UDESCSUB_AC_SELECTOR:
2382 			printf("AC_SELECTOR src=");
2383 			for (j = 0; j < iot[i].d.su->bNrInPins; j++)
2384 				printf("%d ", iot[i].d.su->baSourceId[j]);
2385 			printf("\n");
2386 			break;
2387 		case UDESCSUB_AC_FEATURE:
2388 			printf("AC_FEATURE src=%d\n", iot[i].d.fu->bSourceId);
2389 			break;
2390 		case UDESCSUB_AC_PROCESSING:
2391 			printf("AC_PROCESSING src=");
2392 			for (j = 0; j < iot[i].d.pu->bNrInPins; j++)
2393 				printf("%d ", iot[i].d.pu->baSourceId[j]);
2394 			printf("\n\t");
2395 			cluster = uaudio_get_cluster(i, iot);
2396 			uaudio_dump_cluster(&cluster);
2397 			printf("\n");
2398 			break;
2399 		case UDESCSUB_AC_EXTENSION:
2400 			printf("AC_EXTENSION src=");
2401 			for (j = 0; j < iot[i].d.eu->bNrInPins; j++)
2402 				printf("%d ", iot[i].d.eu->baSourceId[j]);
2403 			printf("\n\t");
2404 			cluster = uaudio_get_cluster(i, iot);
2405 			uaudio_dump_cluster(&cluster);
2406 			printf("\n");
2407 			break;
2408 		default:
2409 			printf("unknown audio control (subtype=%d)\n",
2410 				  iot[i].d.desc->bDescriptorSubtype);
2411 		}
2412 		for (j = 0; j < iot[i].inputs_size; j++) {
2413 			int k;
2414 			printf("\tinput%d: ", j);
2415 			tml = iot[i].inputs[j];
2416 			if (tml == NULL) {
2417 				printf("NULL\n");
2418 				continue;
2419 			}
2420 			for (k = 0; k < tml->size; k++)
2421 				printf("%s ", uaudio_get_terminal_name
2422 					  (tml->terminals[k]));
2423 			printf("\n");
2424 		}
2425 		printf("\toutput: ");
2426 		tml = iot[i].output;
2427 		for (j = 0; j < tml->size; j++)
2428 			printf("%s ", uaudio_get_terminal_name(tml->terminals[j]));
2429 		printf("\n");
2430 	}
2431 #endif
2432 
2433 	for (i = 0; i < ndps; i++) {
2434 		dp = iot[i].d.desc;
2435 		if (dp == NULL)
2436 			continue;
2437 		DPRINTF(("uaudio_identify_ac: id=%d subtype=%d\n",
2438 			 i, dp->bDescriptorSubtype));
2439 		switch (dp->bDescriptorSubtype) {
2440 		case UDESCSUB_AC_HEADER:
2441 			printf("uaudio_identify_ac: unexpected AC header\n");
2442 			break;
2443 		case UDESCSUB_AC_INPUT:
2444 			uaudio_add_input(sc, iot, i);
2445 			break;
2446 		case UDESCSUB_AC_OUTPUT:
2447 			uaudio_add_output(sc, iot, i);
2448 			break;
2449 		case UDESCSUB_AC_MIXER:
2450 			uaudio_add_mixer(sc, iot, i);
2451 			break;
2452 		case UDESCSUB_AC_SELECTOR:
2453 			uaudio_add_selector(sc, iot, i);
2454 			break;
2455 		case UDESCSUB_AC_FEATURE:
2456 			uaudio_add_feature(sc, iot, i);
2457 			break;
2458 		case UDESCSUB_AC_PROCESSING:
2459 			uaudio_add_processing(sc, iot, i);
2460 			break;
2461 		case UDESCSUB_AC_EXTENSION:
2462 			uaudio_add_extension(sc, iot, i);
2463 			break;
2464 		default:
2465 			printf("uaudio_identify_ac: bad AC desc subtype=0x%02x\n",
2466 			       dp->bDescriptorSubtype);
2467 			break;
2468 		}
2469 	}
2470 
2471 	/* delete io_terminal */
2472 	for (i = 0; i < 256; i++) {
2473 		if (iot[i].d.desc == NULL)
2474 			continue;
2475 		if (iot[i].inputs != NULL) {
2476 			for (j = 0; j < iot[i].inputs_size; j++) {
2477 				if (iot[i].inputs[j] != NULL)
2478 					free(iot[i].inputs[j], M_TEMP);
2479 			}
2480 			free(iot[i].inputs, M_TEMP);
2481 		}
2482 		if (iot[i].output != NULL)
2483 			free(iot[i].output, M_TEMP);
2484 		iot[i].d.desc = NULL;
2485 	}
2486 	free(iot, M_TEMP);
2487 
2488 	return USBD_NORMAL_COMPLETION;
2489 }
2490 
2491 #if defined(__NetBSD__) || defined(__OpenBSD__)
2492 static int
2493 uaudio_query_devinfo(void *addr, mixer_devinfo_t *mi)
2494 {
2495 	struct uaudio_softc *sc;
2496 	struct mixerctl *mc;
2497 	int n, nctls, i;
2498 
2499 	sc = addr;
2500 	DPRINTFN(2,("uaudio_query_devinfo: index=%d\n", mi->index));
2501 	if (sc->sc_dying)
2502 		return EIO;
2503 
2504 	n = mi->index;
2505 	nctls = sc->sc_nctls;
2506 
2507 	switch (n) {
2508 	case UAC_OUTPUT:
2509 		mi->type = AUDIO_MIXER_CLASS;
2510 		mi->mixer_class = UAC_OUTPUT;
2511 		mi->next = mi->prev = AUDIO_MIXER_LAST;
2512 		strlcpy(mi->label.name, AudioCoutputs, sizeof(mi->label.name));
2513 		return 0;
2514 	case UAC_INPUT:
2515 		mi->type = AUDIO_MIXER_CLASS;
2516 		mi->mixer_class = UAC_INPUT;
2517 		mi->next = mi->prev = AUDIO_MIXER_LAST;
2518 		strlcpy(mi->label.name, AudioCinputs, sizeof(mi->label.name));
2519 		return 0;
2520 	case UAC_EQUAL:
2521 		mi->type = AUDIO_MIXER_CLASS;
2522 		mi->mixer_class = UAC_EQUAL;
2523 		mi->next = mi->prev = AUDIO_MIXER_LAST;
2524 		strlcpy(mi->label.name, AudioCequalization,
2525 		    sizeof(mi->label.name));
2526 		return 0;
2527 	case UAC_RECORD:
2528 		mi->type = AUDIO_MIXER_CLASS;
2529 		mi->mixer_class = UAC_RECORD;
2530 		mi->next = mi->prev = AUDIO_MIXER_LAST;
2531 		strlcpy(mi->label.name, AudioCrecord, sizeof(mi->label.name));
2532 		return 0;
2533 	default:
2534 		break;
2535 	}
2536 
2537 	n -= UAC_NCLASSES;
2538 	if (n < 0 || n >= nctls)
2539 		return ENXIO;
2540 
2541 	mc = &sc->sc_ctls[n];
2542 	strlcpy(mi->label.name, mc->ctlname, sizeof(mi->label.name));
2543 	mi->mixer_class = mc->class;
2544 	mi->next = mi->prev = AUDIO_MIXER_LAST;	/* XXX */
2545 	switch (mc->type) {
2546 	case MIX_ON_OFF:
2547 		mi->type = AUDIO_MIXER_ENUM;
2548 		mi->un.e.num_mem = 2;
2549 		strlcpy(mi->un.e.member[0].label.name, AudioNoff,
2550 		    sizeof(mi->un.e.member[0].label.name));
2551 		mi->un.e.member[0].ord = 0;
2552 		strlcpy(mi->un.e.member[1].label.name, AudioNon,
2553 		    sizeof(mi->un.e.member[1].label.name));
2554 		mi->un.e.member[1].ord = 1;
2555 		break;
2556 	case MIX_SELECTOR:
2557 		mi->type = AUDIO_MIXER_ENUM;
2558 		mi->un.e.num_mem = mc->maxval - mc->minval + 1;
2559 		for (i = 0; i <= mc->maxval - mc->minval; i++) {
2560 			snprintf(mi->un.e.member[i].label.name,
2561 				 sizeof(mi->un.e.member[i].label.name),
2562 				 "%d", i + mc->minval);
2563 			mi->un.e.member[i].ord = i + mc->minval;
2564 		}
2565 		break;
2566 	default:
2567 		mi->type = AUDIO_MIXER_VALUE;
2568 		strlcpy(mi->un.v.units.name, mc->ctlunit, MAX_AUDIO_DEV_LEN);
2569 		mi->un.v.num_channels = mc->nchan;
2570 		mi->un.v.delta = mc->delta;
2571 		break;
2572 	}
2573 	return 0;
2574 }
2575 
2576 static int
2577 uaudio_open(void *addr, int flags)
2578 {
2579 	struct uaudio_softc *sc;
2580 
2581 	sc = addr;
2582 	DPRINTF(("uaudio_open: sc=%p\n", sc));
2583 	if (sc->sc_dying)
2584 		return EIO;
2585 
2586 	if ((flags & FWRITE) && !(sc->sc_mode & AUMODE_PLAY))
2587 		return EACCES;
2588 	if ((flags & FREAD) && !(sc->sc_mode & AUMODE_RECORD))
2589 		return EACCES;
2590 
2591 	return 0;
2592 }
2593 
2594 /*
2595  * Close function is called at splaudio().
2596  */
2597 static void
2598 uaudio_close(void *addr)
2599 {
2600 }
2601 
2602 static int
2603 uaudio_drain(void *addr)
2604 {
2605 	struct uaudio_softc *sc;
2606 
2607 	sc = addr;
2608 	usbd_delay_ms(sc->sc_udev, UAUDIO_NCHANBUFS * UAUDIO_NFRAMES);
2609 
2610 	return 0;
2611 }
2612 
2613 static int
2614 uaudio_halt_out_dma(void *addr)
2615 {
2616 	struct uaudio_softc *sc;
2617 
2618 	sc = addr;
2619 	if (sc->sc_dying)
2620 		return EIO;
2621 
2622 	DPRINTF(("uaudio_halt_out_dma: enter\n"));
2623 	if (sc->sc_playchan.pipe != NULL) {
2624 		uaudio_chan_close(sc, &sc->sc_playchan);
2625 		sc->sc_playchan.pipe = NULL;
2626 		uaudio_chan_free_buffers(sc, &sc->sc_playchan);
2627 		sc->sc_playchan.intr = NULL;
2628 	}
2629 	return 0;
2630 }
2631 
2632 static int
2633 uaudio_halt_in_dma(void *addr)
2634 {
2635 	struct uaudio_softc *sc;
2636 
2637 	DPRINTF(("uaudio_halt_in_dma: enter\n"));
2638 	sc = addr;
2639 	if (sc->sc_recchan.pipe != NULL) {
2640 		uaudio_chan_close(sc, &sc->sc_recchan);
2641 		sc->sc_recchan.pipe = NULL;
2642 		uaudio_chan_free_buffers(sc, &sc->sc_recchan);
2643 		sc->sc_recchan.intr = NULL;
2644 	}
2645 	return 0;
2646 }
2647 
2648 static int
2649 uaudio_getdev(void *addr, struct audio_device *retp)
2650 {
2651 	struct uaudio_softc *sc;
2652 
2653 	DPRINTF(("uaudio_mixer_getdev:\n"));
2654 	sc = addr;
2655 	if (sc->sc_dying)
2656 		return EIO;
2657 
2658 	*retp = uaudio_device;
2659 	return 0;
2660 }
2661 
2662 /*
2663  * Make sure the block size is large enough to hold all outstanding transfers.
2664  */
2665 static int
2666 uaudio_round_blocksize(void *addr, int blk)
2667 {
2668 	struct uaudio_softc *sc;
2669 	int b;
2670 
2671 	sc = addr;
2672 	DPRINTF(("uaudio_round_blocksize: blk=%d mode=%s\n", blk,
2673 		mode == AUMODE_PLAY ? "AUMODE_PLAY" : "AUMODE_RECORD"));
2674 
2675 	/* chan.bytes_per_frame can be 0. */
2676 	if (mode == AUMODE_PLAY || sc->sc_recchan.bytes_per_frame <= 0) {
2677 		b = param->sample_rate * UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
2678 
2679 		/*
2680 		 * This does not make accurate value in the case
2681 		 * of b % USB_FRAMES_PER_SECOND != 0
2682 		 */
2683 		b /= USB_FRAMES_PER_SECOND;
2684 
2685 		b *= param->precision / 8 * param->channels;
2686 	} else {
2687 		/*
2688 		 * use wMaxPacketSize in bytes_per_frame.
2689 		 * See uaudio_set_params() and uaudio_chan_init()
2690 		 */
2691 		b = sc->sc_recchan.bytes_per_frame
2692 			* UAUDIO_NFRAMES * UAUDIO_NCHANBUFS;
2693 	}
2694 
2695 	if (b <= 0)
2696 		b = 1;
2697 	blk = blk <= b ? b : blk / b * b;
2698 
2699 #ifdef DIAGNOSTIC
2700 	if (blk <= 0) {
2701 		printf("uaudio_round_blocksize: blk=%d\n", blk);
2702 		blk = 512;
2703 	}
2704 #endif
2705 
2706 	DPRINTF(("uaudio_round_blocksize: resultant blk=%d\n", blk));
2707 	return blk;
2708 }
2709 
2710 static int
2711 uaudio_get_props(void *addr)
2712 {
2713 	return AUDIO_PROP_FULLDUPLEX | AUDIO_PROP_INDEPENDENT;
2714 
2715 }
2716 #endif	/* NetBSD or OpenBSD */
2717 
2718 static int
2719 uaudio_get(struct uaudio_softc *sc, int which, int type, int wValue,
2720 	   int wIndex, int len)
2721 {
2722 	usb_device_request_t req;
2723 	uint8_t data[4];
2724 	usbd_status err;
2725 	int val;
2726 
2727 #if defined(__FreeBSD__)
2728 	if (sc->sc_dying)
2729 		return EIO;
2730 #endif
2731 
2732 	if (wValue == -1)
2733 		return 0;
2734 
2735 	req.bmRequestType = type;
2736 	req.bRequest = which;
2737 	USETW(req.wValue, wValue);
2738 	USETW(req.wIndex, wIndex);
2739 	USETW(req.wLength, len);
2740 	DPRINTFN(2,("uaudio_get: type=0x%02x req=0x%02x wValue=0x%04x "
2741 		    "wIndex=0x%04x len=%d\n",
2742 		    type, which, wValue, wIndex, len));
2743 #if defined(__FreeBSD__)
2744 	if (sc->async != 0)
2745 		err = usbd_do_request_async(sc->sc_udev, &req, data);
2746 	else
2747 #endif
2748 		err = usbd_do_request(sc->sc_udev, &req, data);
2749 	if (err) {
2750 		DPRINTF(("uaudio_get: err=%s\n", usbd_errstr(err)));
2751 		return -1;
2752 	}
2753 	switch (len) {
2754 	case 1:
2755 		val = data[0];
2756 		break;
2757 	case 2:
2758 		val = data[0] | (data[1] << 8);
2759 		break;
2760 	default:
2761 		DPRINTF(("uaudio_get: bad length=%d\n", len));
2762 		return -1;
2763 	}
2764 	DPRINTFN(2,("uaudio_get: val=%d\n", val));
2765 	return val;
2766 }
2767 
2768 static void
2769 uaudio_set(struct uaudio_softc *sc, int which, int type, int wValue,
2770 	   int wIndex, int len, int val)
2771 {
2772 	usb_device_request_t req;
2773 	uint8_t data[4];
2774 	usbd_status err;
2775 
2776 #if defined(__FreeBSD__)
2777 	if (sc->sc_dying)
2778 		return;
2779 #endif
2780 
2781 	if (wValue == -1)
2782 		return;
2783 
2784 	req.bmRequestType = type;
2785 	req.bRequest = which;
2786 	USETW(req.wValue, wValue);
2787 	USETW(req.wIndex, wIndex);
2788 	USETW(req.wLength, len);
2789 	switch (len) {
2790 	case 1:
2791 		data[0] = val;
2792 		break;
2793 	case 2:
2794 		data[0] = val;
2795 		data[1] = val >> 8;
2796 		break;
2797 	default:
2798 		return;
2799 	}
2800 	DPRINTFN(2,("uaudio_set: type=0x%02x req=0x%02x wValue=0x%04x "
2801 		    "wIndex=0x%04x len=%d, val=%d\n",
2802 		    type, which, wValue, wIndex, len, val & 0xffff));
2803 #if defined(__FreeBSD__)
2804 	if (sc->async != 0)
2805 		err = usbd_do_request_async(sc->sc_udev, &req, data);
2806 	else
2807 #endif
2808 		err = usbd_do_request(sc->sc_udev, &req, data);
2809 #ifdef USB_DEBUG
2810 	if (err)
2811 		DPRINTF(("uaudio_set: err=%d\n", err));
2812 #endif
2813 }
2814 
2815 static int
2816 uaudio_signext(int type, int val)
2817 {
2818 	if (!MIX_UNSIGNED(type)) {
2819 		if (MIX_SIZE(type) == 2)
2820 			val = (int16_t)val;
2821 		else
2822 			val = (int8_t)val;
2823 	}
2824 	return val;
2825 }
2826 
2827 #if defined(__NetBSD__) || defined(__OpenBSD__)
2828 static int
2829 uaudio_value2bsd(struct mixerctl *mc, int val)
2830 {
2831 	DPRINTFN(5, ("uaudio_value2bsd: type=%03x val=%d min=%d max=%d ",
2832 		     mc->type, val, mc->minval, mc->maxval));
2833 	if (mc->type == MIX_ON_OFF) {
2834 		val = (val != 0);
2835 	} else if (mc->type == MIX_SELECTOR) {
2836 		if (val < mc->minval || val > mc->maxval)
2837 			val = mc->minval;
2838 	} else
2839 		val = ((uaudio_signext(mc->type, val) - mc->minval) * 255
2840 			+ mc->mul/2) / mc->mul;
2841 	DPRINTFN(5, ("val'=%d\n", val));
2842 	return val;
2843 }
2844 #endif
2845 
2846 int
2847 uaudio_bsd2value(struct mixerctl *mc, int val)
2848 {
2849 	DPRINTFN(5,("uaudio_bsd2value: type=%03x val=%d min=%d max=%d ",
2850 		    mc->type, val, mc->minval, mc->maxval));
2851 	if (mc->type == MIX_ON_OFF) {
2852 		val = (val != 0);
2853 	} else if (mc->type == MIX_SELECTOR) {
2854 		if (val < mc->minval || val > mc->maxval)
2855 			val = mc->minval;
2856 	} else
2857 		val = (val + mc->delta/2) * mc->mul / 255 + mc->minval;
2858 	DPRINTFN(5, ("val'=%d\n", val));
2859 	return val;
2860 }
2861 
2862 #if defined(__NetBSD__) || defined(__OpenBSD__)
2863 static int
2864 uaudio_ctl_get(struct uaudio_softc *sc, int which, struct mixerctl *mc,
2865 	       int chan)
2866 {
2867 	int val;
2868 
2869 	DPRINTFN(5,("uaudio_ctl_get: which=%d chan=%d\n", which, chan));
2870 	val = uaudio_get(sc, which, UT_READ_CLASS_INTERFACE, mc->wValue[chan],
2871 			 mc->wIndex, MIX_SIZE(mc->type));
2872 	return uaudio_value2bsd(mc, val);
2873 }
2874 #endif
2875 
2876 static void
2877 uaudio_ctl_set(struct uaudio_softc *sc, int which, struct mixerctl *mc,
2878 	       int chan, int val)
2879 {
2880 	val = uaudio_bsd2value(mc, val);
2881 	uaudio_set(sc, which, UT_WRITE_CLASS_INTERFACE, mc->wValue[chan],
2882 		   mc->wIndex, MIX_SIZE(mc->type), val);
2883 }
2884 
2885 #if defined(__NetBSD__) || defined(__OpenBSD__)
2886 static int
2887 uaudio_mixer_get_port(void *addr, mixer_ctrl_t *cp)
2888 {
2889 	struct uaudio_softc *sc;
2890 	struct mixerctl *mc;
2891 	int i, n, vals[MIX_MAX_CHAN], val;
2892 
2893 	DPRINTFN(2,("uaudio_mixer_get_port: index=%d\n", cp->dev));
2894 	sc = addr;
2895 	if (sc->sc_dying)
2896 		return EIO;
2897 
2898 	n = cp->dev - UAC_NCLASSES;
2899 	if (n < 0 || n >= sc->sc_nctls)
2900 		return ENXIO;
2901 	mc = &sc->sc_ctls[n];
2902 
2903 	if (mc->type == MIX_ON_OFF) {
2904 		if (cp->type != AUDIO_MIXER_ENUM)
2905 			return EINVAL;
2906 		cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
2907 	} else if (mc->type == MIX_SELECTOR) {
2908 		if (cp->type != AUDIO_MIXER_ENUM)
2909 			return EINVAL;
2910 		cp->un.ord = uaudio_ctl_get(sc, GET_CUR, mc, 0);
2911 	} else {
2912 		if (cp->type != AUDIO_MIXER_VALUE)
2913 			return (EINVAL);
2914 		if (cp->un.value.num_channels != 1 &&
2915 		    cp->un.value.num_channels != mc->nchan)
2916 			return EINVAL;
2917 		for (i = 0; i < mc->nchan; i++)
2918 			vals[i] = uaudio_ctl_get(sc, GET_CUR, mc, i);
2919 		if (cp->un.value.num_channels == 1 && mc->nchan != 1) {
2920 			for (val = 0, i = 0; i < mc->nchan; i++)
2921 				val += vals[i];
2922 			vals[0] = val / mc->nchan;
2923 		}
2924 		for (i = 0; i < cp->un.value.num_channels; i++)
2925 			cp->un.value.level[i] = vals[i];
2926 	}
2927 
2928 	return 0;
2929 }
2930 
2931 static int
2932 uaudio_mixer_set_port(void *addr, mixer_ctrl_t *cp)
2933 {
2934 	struct uaudio_softc *sc;
2935 	struct mixerctl *mc;
2936 	int i, n, vals[MIX_MAX_CHAN];
2937 
2938 	DPRINTFN(2,("uaudio_mixer_set_port: index = %d\n", cp->dev));
2939 	sc = addr;
2940 	if (sc->sc_dying)
2941 		return EIO;
2942 
2943 	n = cp->dev - UAC_NCLASSES;
2944 	if (n < 0 || n >= sc->sc_nctls)
2945 		return ENXIO;
2946 	mc = &sc->sc_ctls[n];
2947 
2948 	if (mc->type == MIX_ON_OFF) {
2949 		if (cp->type != AUDIO_MIXER_ENUM)
2950 			return EINVAL;
2951 		uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
2952 	} else if (mc->type == MIX_SELECTOR) {
2953 		if (cp->type != AUDIO_MIXER_ENUM)
2954 			return EINVAL;
2955 		uaudio_ctl_set(sc, SET_CUR, mc, 0, cp->un.ord);
2956 	} else {
2957 		if (cp->type != AUDIO_MIXER_VALUE)
2958 			return EINVAL;
2959 		if (cp->un.value.num_channels == 1)
2960 			for (i = 0; i < mc->nchan; i++)
2961 				vals[i] = cp->un.value.level[0];
2962 		else if (cp->un.value.num_channels == mc->nchan)
2963 			for (i = 0; i < mc->nchan; i++)
2964 				vals[i] = cp->un.value.level[i];
2965 		else
2966 			return EINVAL;
2967 		for (i = 0; i < mc->nchan; i++)
2968 			uaudio_ctl_set(sc, SET_CUR, mc, i, vals[i]);
2969 	}
2970 	return 0;
2971 }
2972 
2973 static int
2974 uaudio_trigger_input(void *addr, void *start, void *end, int blksize,
2975 		     void (*intr)(void *), void *arg,
2976 		     struct audio_params *param)
2977 {
2978 	struct uaudio_softc *sc;
2979 	struct chan *ch;
2980 	usbd_status err;
2981 	int i, s;
2982 
2983 	sc = addr;
2984 	if (sc->sc_dying)
2985 		return EIO;
2986 
2987 	DPRINTFN(3,("uaudio_trigger_input: sc=%p start=%p end=%p "
2988 		    "blksize=%d\n", sc, start, end, blksize));
2989 	ch = &sc->sc_recchan;
2990 	uaudio_chan_set_param(ch, start, end, blksize);
2991 	DPRINTFN(3,("uaudio_trigger_input: sample_size=%d bytes/frame=%d "
2992 		    "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
2993 		    ch->fraction));
2994 
2995 	err = uaudio_chan_alloc_buffers(sc, ch);
2996 	if (err)
2997 		return EIO;
2998 
2999 	err = uaudio_chan_open(sc, ch);
3000 	if (err) {
3001 		uaudio_chan_free_buffers(sc, ch);
3002 		return EIO;
3003 	}
3004 
3005 	ch->intr = intr;
3006 	ch->arg = arg;
3007 
3008 	s = splusb();
3009 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX -1 shouldn't be needed */
3010 		uaudio_chan_rtransfer(ch);
3011 	splx(s);
3012 
3013 	return 0;
3014 }
3015 
3016 static int
3017 uaudio_trigger_output(void *addr, void *start, void *end, int blksize,
3018 		      void (*intr)(void *), void *arg,
3019 		      struct audio_params *param)
3020 {
3021 	struct uaudio_softc *sc;
3022 	struct chan *ch;
3023 	usbd_status err;
3024 	int i, s;
3025 
3026 	sc = addr;
3027 	if (sc->sc_dying)
3028 		return EIO;
3029 
3030 	DPRINTFN(3,("uaudio_trigger_output: sc=%p start=%p end=%p "
3031 		    "blksize=%d\n", sc, start, end, blksize));
3032 	ch = &sc->sc_playchan;
3033 	uaudio_chan_set_param(ch, start, end, blksize);
3034 	DPRINTFN(3,("uaudio_trigger_output: sample_size=%d bytes/frame=%d "
3035 		    "fraction=0.%03d\n", ch->sample_size, ch->bytes_per_frame,
3036 		    ch->fraction));
3037 
3038 	err = uaudio_chan_alloc_buffers(sc, ch);
3039 	if (err)
3040 		return EIO;
3041 
3042 	err = uaudio_chan_open(sc, ch);
3043 	if (err) {
3044 		uaudio_chan_free_buffers(sc, ch);
3045 		return EIO;
3046 	}
3047 
3048 	ch->intr = intr;
3049 	ch->arg = arg;
3050 
3051 	s = splusb();
3052 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX */
3053 		uaudio_chan_ptransfer(ch);
3054 	splx(s);
3055 
3056 	return 0;
3057 }
3058 #endif	/* NetBSD or OpenBSD */
3059 
3060 /* Set up a pipe for a channel. */
3061 static usbd_status
3062 uaudio_chan_open(struct uaudio_softc *sc, struct chan *ch)
3063 {
3064 	struct as_info *as;
3065 	int endpt;
3066 #if defined(__FreeBSD__)
3067 	int locked;
3068 #endif
3069 	usbd_status err;
3070 
3071 #if defined(__FreeBSD__)
3072 	if (sc->sc_dying)
3073 		return EIO;
3074 #endif
3075 
3076 	as = &sc->sc_alts[ch->altidx];
3077 	endpt = as->edesc->bEndpointAddress;
3078 	DPRINTF(("uaudio_chan_open: endpt=0x%02x, speed=%d, alt=%d\n",
3079 		 endpt, ch->sample_rate, as->alt));
3080 
3081 #if defined(__FreeBSD__)
3082 	locked = (ch->pcm_ch != NULL && mtx_owned(ch->pcm_ch->lock)) ? 1 : 0;
3083 	if (locked)
3084 		CHN_UNLOCK(ch->pcm_ch);
3085 #endif
3086 	/* Set alternate interface corresponding to the mode. */
3087 	err = usbd_set_interface(as->ifaceh, as->alt);
3088 #if defined(__FreeBSD__)
3089 	if (locked)
3090 		CHN_LOCK(ch->pcm_ch);
3091 #endif
3092 	if (err)
3093 		return err;
3094 
3095 	/*
3096 	 * If just one sampling rate is supported,
3097 	 * no need to call uaudio_set_speed().
3098 	 * Roland SD-90 freezes by a SAMPLING_FREQ_CONTROL request.
3099 	 */
3100 	if (as->asf1desc->bSamFreqType != 1) {
3101 		err = uaudio_set_speed(sc, endpt, ch->sample_rate);
3102 		if (err) {
3103 			DPRINTF(("uaudio_chan_open: set_speed failed err=%s\n",
3104 				 usbd_errstr(err)));
3105 		}
3106 	}
3107 
3108 	ch->pipe = 0;
3109 	ch->sync_pipe = 0;
3110 	DPRINTF(("uaudio_chan_open: create pipe to 0x%02x\n", endpt));
3111 	err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->pipe);
3112 	if (err)
3113 		return err;
3114 	if (as->edesc1 != NULL) {
3115 		endpt = as->edesc1->bEndpointAddress;
3116 		DPRINTF(("uaudio_chan_open: create sync-pipe to 0x%02x\n", endpt));
3117 		err = usbd_open_pipe(as->ifaceh, endpt, 0, &ch->sync_pipe);
3118 	}
3119 	return err;
3120 }
3121 
3122 static void
3123 uaudio_chan_close(struct uaudio_softc *sc, struct chan *ch)
3124 {
3125 	struct as_info *as;
3126 #if defined(__FreeBSD__)
3127 	int locked;
3128 
3129 	if (sc->sc_dying)
3130 		return ;
3131 #endif
3132 
3133 	as = &sc->sc_alts[ch->altidx];
3134 	as->sc_busy = 0;
3135 #if defined(__FreeBSD__)
3136 	locked = (ch->pcm_ch != NULL && mtx_owned(ch->pcm_ch->lock)) ? 1 : 0;
3137 	if (locked)
3138 		CHN_UNLOCK(ch->pcm_ch);
3139 #endif
3140 	if (sc->sc_nullalt >= 0) {
3141 		DPRINTF(("uaudio_chan_close: set null alt=%d\n",
3142 			 sc->sc_nullalt));
3143 		/*
3144 		 * The interface will be initialized later again, so an
3145 		 * error does not hurt.
3146 		 */
3147 		(void)usbd_set_interface(as->ifaceh, sc->sc_nullalt);
3148 	}
3149 	if (ch->pipe) {
3150 		usbd_abort_pipe(ch->pipe);
3151 		usbd_close_pipe(ch->pipe);
3152 	}
3153 	if (ch->sync_pipe) {
3154 		usbd_abort_pipe(ch->sync_pipe);
3155 		usbd_close_pipe(ch->sync_pipe);
3156 	}
3157 #if defined(__FreeBSD__)
3158 	if (locked)
3159 		CHN_LOCK(ch->pcm_ch);
3160 #endif
3161 }
3162 
3163 static usbd_status
3164 uaudio_chan_alloc_buffers(struct uaudio_softc *sc, struct chan *ch)
3165 {
3166 	usbd_xfer_handle xfer;
3167 	void *buf;
3168 	int i, size;
3169 
3170 	size = (ch->bytes_per_frame + ch->sample_size) * UAUDIO_NFRAMES;
3171 	for (i = 0; i < UAUDIO_NCHANBUFS; i++) {
3172 		xfer = usbd_alloc_xfer(sc->sc_udev);
3173 		if (xfer == 0)
3174 			goto bad;
3175 		ch->chanbufs[i].xfer = xfer;
3176 		buf = usbd_alloc_buffer(xfer, size);
3177 		if (buf == 0) {
3178 			i++;
3179 			goto bad;
3180 		}
3181 		ch->chanbufs[i].buffer = buf;
3182 		ch->chanbufs[i].chan = ch;
3183 	}
3184 
3185 	return USBD_NORMAL_COMPLETION;
3186 
3187 bad:
3188 	while (--i >= 0)
3189 		/* implicit buffer free */
3190 		usbd_free_xfer(ch->chanbufs[i].xfer);
3191 	return USBD_NOMEM;
3192 }
3193 
3194 static void
3195 uaudio_chan_free_buffers(struct uaudio_softc *sc, struct chan *ch)
3196 {
3197 	int i;
3198 
3199 	for (i = 0; i < UAUDIO_NCHANBUFS; i++)
3200 		usbd_free_xfer(ch->chanbufs[i].xfer);
3201 }
3202 
3203 /* Called at splusb() */
3204 static void
3205 uaudio_chan_ptransfer(struct chan *ch)
3206 {
3207 	struct chanbuf *cb;
3208 	int i, n, size, residue, total;
3209 
3210 	if (ch->sc->sc_dying)
3211 		return;
3212 
3213 	/* Pick the next channel buffer. */
3214 	cb = &ch->chanbufs[ch->curchanbuf];
3215 	if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
3216 		ch->curchanbuf = 0;
3217 
3218 	/* Compute the size of each frame in the next transfer. */
3219 	residue = ch->residue;
3220 	total = 0;
3221 	for (i = 0; i < UAUDIO_NFRAMES; i++) {
3222 		size = ch->bytes_per_frame;
3223 		residue += ch->fraction;
3224 		if (residue >= USB_FRAMES_PER_SECOND) {
3225 			if ((ch->sc->sc_altflags & UA_NOFRAC) == 0)
3226 				size += ch->sample_size;
3227 			residue -= USB_FRAMES_PER_SECOND;
3228 		}
3229 		cb->sizes[i] = size;
3230 		total += size;
3231 	}
3232 	ch->residue = residue;
3233 	cb->size = total;
3234 
3235 	/*
3236 	 * Transfer data from upper layer buffer to channel buffer, taking
3237 	 * care of wrapping the upper layer buffer.
3238 	 */
3239 	n = min(total, ch->end - ch->cur);
3240 	memcpy(cb->buffer, ch->cur, n);
3241 	ch->cur += n;
3242 	if (ch->cur >= ch->end)
3243 		ch->cur = ch->start;
3244 	if (total > n) {
3245 		total -= n;
3246 		memcpy(cb->buffer + n, ch->cur, total);
3247 		ch->cur += total;
3248 	}
3249 
3250 #ifdef USB_DEBUG
3251 	if (uaudiodebug > 8) {
3252 		DPRINTF(("uaudio_chan_ptransfer: buffer=%p, residue=0.%03d\n",
3253 			 cb->buffer, ch->residue));
3254 		for (i = 0; i < UAUDIO_NFRAMES; i++) {
3255 			DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
3256 		}
3257 	}
3258 #endif
3259 
3260 	DPRINTFN(5,("uaudio_chan_transfer: ptransfer xfer=%p\n", cb->xfer));
3261 	/* Fill the request */
3262 	usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
3263 			     UAUDIO_NFRAMES, USBD_NO_COPY,
3264 			     uaudio_chan_pintr);
3265 
3266 	(void)usbd_transfer(cb->xfer);
3267 }
3268 
3269 static void
3270 uaudio_chan_pintr(usbd_xfer_handle xfer, usbd_private_handle priv,
3271 		  usbd_status status)
3272 {
3273 	struct chanbuf *cb;
3274 	struct chan *ch;
3275 	u_int32_t count;
3276 	int s;
3277 
3278 	cb = priv;
3279 	ch = cb->chan;
3280 	/* Return if we are aborting. */
3281 	if (status == USBD_CANCELLED)
3282 		return;
3283 
3284 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
3285 	DPRINTFN(5,("uaudio_chan_pintr: count=%d, transferred=%d\n",
3286 		    count, ch->transferred));
3287 #ifdef DIAGNOSTIC
3288 	if (count != cb->size) {
3289 		printf("uaudio_chan_pintr: count(%d) != size(%d)\n",
3290 		       count, cb->size);
3291 	}
3292 #endif
3293 
3294 	ch->transferred += cb->size;
3295 #if defined(__FreeBSD__)
3296 	/* s = spltty(); */
3297 	s = splhigh();
3298 	chn_intr(ch->pcm_ch);
3299 	splx(s);
3300 #else
3301 	s = splaudio();
3302 	/* Call back to upper layer */
3303 	while (ch->transferred >= ch->blksize) {
3304 		ch->transferred -= ch->blksize;
3305 		DPRINTFN(5,("uaudio_chan_pintr: call %p(%p)\n",
3306 			    ch->intr, ch->arg));
3307 		ch->intr(ch->arg);
3308 	}
3309 	splx(s);
3310 #endif
3311 
3312 	/* start next transfer */
3313 	uaudio_chan_ptransfer(ch);
3314 }
3315 
3316 /* Called at splusb() */
3317 static void
3318 uaudio_chan_rtransfer(struct chan *ch)
3319 {
3320 	struct chanbuf *cb;
3321 	int i, size, residue, total;
3322 
3323 	if (ch->sc->sc_dying)
3324 		return;
3325 
3326 	/* Pick the next channel buffer. */
3327 	cb = &ch->chanbufs[ch->curchanbuf];
3328 	if (++ch->curchanbuf >= UAUDIO_NCHANBUFS)
3329 		ch->curchanbuf = 0;
3330 
3331 	/* Compute the size of each frame in the next transfer. */
3332 	residue = ch->residue;
3333 	total = 0;
3334 	for (i = 0; i < UAUDIO_NFRAMES; i++) {
3335 		size = ch->bytes_per_frame;
3336 		cb->sizes[i] = size;
3337 		cb->offsets[i] = total;
3338 		total += size;
3339 	}
3340 	ch->residue = residue;
3341 	cb->size = total;
3342 
3343 #ifdef USB_DEBUG
3344 	if (uaudiodebug > 8) {
3345 		DPRINTF(("uaudio_chan_rtransfer: buffer=%p, residue=0.%03d\n",
3346 			 cb->buffer, ch->residue));
3347 		for (i = 0; i < UAUDIO_NFRAMES; i++) {
3348 			DPRINTF(("   [%d] length %d\n", i, cb->sizes[i]));
3349 		}
3350 	}
3351 #endif
3352 
3353 	DPRINTFN(5,("uaudio_chan_rtransfer: transfer xfer=%p\n", cb->xfer));
3354 	/* Fill the request */
3355 	usbd_setup_isoc_xfer(cb->xfer, ch->pipe, cb, cb->sizes,
3356 			     UAUDIO_NFRAMES, USBD_NO_COPY,
3357 			     uaudio_chan_rintr);
3358 
3359 	(void)usbd_transfer(cb->xfer);
3360 }
3361 
3362 static void
3363 uaudio_chan_rintr(usbd_xfer_handle xfer, usbd_private_handle priv,
3364 		  usbd_status status)
3365 {
3366 	struct chanbuf *cb = priv;
3367 	struct chan *ch = cb->chan;
3368 	u_int32_t count;
3369 	int s, i, n, frsize;
3370 
3371 	/* Return if we are aborting. */
3372 	if (status == USBD_CANCELLED)
3373 		return;
3374 
3375 	usbd_get_xfer_status(xfer, NULL, NULL, &count, NULL);
3376 	DPRINTFN(5,("uaudio_chan_rintr: count=%d, transferred=%d\n",
3377 		    count, ch->transferred));
3378 
3379 	/* count < cb->size is normal for asynchronous source */
3380 #ifdef DIAGNOSTIC
3381 	if (count > cb->size) {
3382 		printf("uaudio_chan_rintr: count(%d) > size(%d)\n",
3383 		       count, cb->size);
3384 	}
3385 #endif
3386 
3387 	/*
3388 	 * Transfer data from channel buffer to upper layer buffer, taking
3389 	 * care of wrapping the upper layer buffer.
3390 	 */
3391 	for(i = 0; i < UAUDIO_NFRAMES; i++) {
3392 		frsize = cb->sizes[i];
3393 		n = min(frsize, ch->end - ch->cur);
3394 		memcpy(ch->cur, cb->buffer + cb->offsets[i], n);
3395 		ch->cur += n;
3396 		if (ch->cur >= ch->end)
3397 			ch->cur = ch->start;
3398 		if (frsize > n) {
3399 			memcpy(ch->cur, cb->buffer + cb->offsets[i] + n,
3400 			    frsize - n);
3401 			ch->cur += frsize - n;
3402 		}
3403 	}
3404 
3405 	/* Call back to upper layer */
3406 	ch->transferred += count;
3407 #if defined(__FreeBSD__)
3408 	s = spltty();
3409 	chn_intr(ch->pcm_ch);
3410 	splx(s);
3411 #else
3412 	s = splaudio();
3413 	while (ch->transferred >= ch->blksize) {
3414 		ch->transferred -= ch->blksize;
3415 		DPRINTFN(5,("uaudio_chan_rintr: call %p(%p)\n",
3416 			    ch->intr, ch->arg));
3417 		ch->intr(ch->arg);
3418 	}
3419 	splx(s);
3420 #endif
3421 
3422 	/* start next transfer */
3423 	uaudio_chan_rtransfer(ch);
3424 }
3425 
3426 #if defined(__NetBSD__) || defined(__OpenBSD__)
3427 static void
3428 uaudio_chan_init(struct chan *ch, int altidx, const struct audio_params *param,
3429     int maxpktsize)
3430 {
3431 	int samples_per_frame, sample_size;
3432 
3433 	ch->altidx = altidx;
3434 	sample_size = param->precision * param->factor * param->hw_channels / 8;
3435 	samples_per_frame = param->hw_sample_rate / USB_FRAMES_PER_SECOND;
3436 	ch->sample_size = sample_size;
3437 	ch->sample_rate = param->hw_sample_rate;
3438 	if (maxpktsize == 0) {
3439 		ch->fraction = param->hw_sample_rate % USB_FRAMES_PER_SECOND;
3440 		ch->bytes_per_frame = samples_per_frame * sample_size;
3441 	} else {
3442 		ch->fraction = 0;
3443 		ch->bytes_per_frame = maxpktsize;
3444 	}
3445 	ch->residue = 0;
3446 }
3447 
3448 static void
3449 uaudio_chan_set_param(struct chan *ch, u_char *start, u_char *end, int blksize)
3450 {
3451 	ch->start = start;
3452 	ch->end = end;
3453 	ch->cur = start;
3454 	ch->blksize = blksize;
3455 	ch->transferred = 0;
3456 	ch->curchanbuf = 0;
3457 }
3458 
3459 static void
3460 uaudio_get_minmax_rates(int nalts, const struct as_info *alts,
3461 			const struct audio_params *p, int mode,
3462 			u_long *min, u_long *max)
3463 {
3464 	const struct usb_audio_streaming_type1_descriptor *a1d;
3465 	int i, j;
3466 
3467 	*min = ULONG_MAX;
3468 	*max = 0;
3469 	for (i = 0; i < nalts; i++) {
3470 		a1d = alts[i].asf1desc;
3471 		if (alts[i].sc_busy)
3472 			continue;
3473 		if (p->hw_channels != a1d->bNrChannels)
3474 			continue;
3475 		if (p->hw_precision != a1d->bBitResolution)
3476 			continue;
3477 		if (p->hw_encoding != alts[i].encoding)
3478 			continue;
3479 		if (mode != UE_GET_DIR(alts[i].edesc->bEndpointAddress))
3480 			continue;
3481 		if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
3482 			DPRINTFN(2,("uaudio_get_minmax_rates: cont %d-%d\n",
3483 				    UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
3484 			if (UA_SAMP_LO(a1d) < *min)
3485 				*min = UA_SAMP_LO(a1d);
3486 			if (UA_SAMP_HI(a1d) > *max)
3487 				*max = UA_SAMP_HI(a1d);
3488 		} else {
3489 			for (j = 0; j < a1d->bSamFreqType; j++) {
3490 				DPRINTFN(2,("uaudio_get_minmax_rates: disc #%d: %d\n",
3491 					    j, UA_GETSAMP(a1d, j)));
3492 				if (UA_GETSAMP(a1d, j) < *min)
3493 					*min = UA_GETSAMP(a1d, j);
3494 				if (UA_GETSAMP(a1d, j) > *max)
3495 					*max = UA_GETSAMP(a1d, j);
3496 			}
3497 		}
3498 	}
3499 }
3500 
3501 static int
3502 uaudio_match_alt_sub(int nalts, const struct as_info *alts,
3503 		     const struct audio_params *p, int mode, u_long rate)
3504 {
3505 	const struct usb_audio_streaming_type1_descriptor *a1d;
3506 	int i, j;
3507 
3508 	DPRINTF(("uaudio_match_alt_sub: search for %luHz %dch\n",
3509 		 rate, p->hw_channels));
3510 	for (i = 0; i < nalts; i++) {
3511 		a1d = alts[i].asf1desc;
3512 		if (alts[i].sc_busy)
3513 			continue;
3514 		if (p->hw_channels != a1d->bNrChannels)
3515 			continue;
3516 		if (p->hw_precision != a1d->bBitResolution)
3517 			continue;
3518 		if (p->hw_encoding != alts[i].encoding)
3519 			continue;
3520 		if (mode != UE_GET_DIR(alts[i].edesc->bEndpointAddress))
3521 			continue;
3522 		if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
3523 			DPRINTFN(3,("uaudio_match_alt_sub: cont %d-%d\n",
3524 				    UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
3525 			if (UA_SAMP_LO(a1d) <= rate && rate <= UA_SAMP_HI(a1d))
3526 				return i;
3527 		} else {
3528 			for (j = 0; j < a1d->bSamFreqType; j++) {
3529 				DPRINTFN(3,("uaudio_match_alt_sub: disc #%d: %d\n",
3530 					    j, UA_GETSAMP(a1d, j)));
3531 				/* XXX allow for some slack */
3532 				if (UA_GETSAMP(a1d, j) == rate)
3533 					return i;
3534 			}
3535 		}
3536 	}
3537 	return -1;
3538 }
3539 
3540 static int
3541 uaudio_match_alt_chan(int nalts, const struct as_info *alts,
3542 		      struct audio_params *p, int mode)
3543 {
3544 	int i, n;
3545 	u_long min, max;
3546 	u_long rate;
3547 
3548 	/* Exact match */
3549 	DPRINTF(("uaudio_match_alt_chan: examine %ldHz %dch %dbit.\n",
3550 		 p->sample_rate, p->hw_channels, p->hw_precision));
3551 	i = uaudio_match_alt_sub(nalts, alts, p, mode, p->sample_rate);
3552 	if (i >= 0)
3553 		return i;
3554 
3555 	uaudio_get_minmax_rates(nalts, alts, p, mode, &min, &max);
3556 	DPRINTF(("uaudio_match_alt_chan: min=%lu max=%lu\n", min, max));
3557 	if (max <= 0)
3558 		return -1;
3559 	/* Search for biggers */
3560 	n = 2;
3561 	while ((rate = p->sample_rate * n++) <= max) {
3562 		i = uaudio_match_alt_sub(nalts, alts, p, mode, rate);
3563 		if (i >= 0) {
3564 			p->hw_sample_rate = rate;
3565 			return i;
3566 		}
3567 	}
3568 	if (p->sample_rate >= min) {
3569 		i = uaudio_match_alt_sub(nalts, alts, p, mode, max);
3570 		if (i >= 0) {
3571 			p->hw_sample_rate = max;
3572 			return i;
3573 		}
3574 	} else {
3575 		i = uaudio_match_alt_sub(nalts, alts, p, mode, min);
3576 		if (i >= 0) {
3577 			p->hw_sample_rate = min;
3578 			return i;
3579 		}
3580 	}
3581 	return -1;
3582 }
3583 
3584 static int
3585 uaudio_match_alt(int nalts, const struct as_info *alts,
3586 		 struct audio_params *p, int mode)
3587 {
3588 	int i, n;
3589 
3590 	mode = mode == AUMODE_PLAY ? UE_DIR_OUT : UE_DIR_IN;
3591 	i = uaudio_match_alt_chan(nalts, alts, p, mode);
3592 	if (i >= 0)
3593 		return i;
3594 
3595 	for (n = p->channels + 1; n <= AUDIO_MAX_CHANNELS; n++) {
3596 		p->hw_channels = n;
3597 		i = uaudio_match_alt_chan(nalts, alts, p, mode);
3598 		if (i >= 0)
3599 			return i;
3600 	}
3601 
3602 	if (p->channels != 2)
3603 		return -1;
3604 	p->hw_channels = 1;
3605 	return uaudio_match_alt_chan(nalts, alts, p, mode);
3606 }
3607 
3608 static int
3609 uaudio_set_params(void *addr, int setmode, int usemode,
3610 		  struct audio_params *play, struct audio_params *rec)
3611 {
3612 	struct uaudio_softc *sc;
3613 	int flags;
3614 	int factor;
3615 	int enc, i;
3616 	int paltidx, raltidx;
3617 	void (*swcode)(void *, u_char *buf, int cnt);
3618 	struct audio_params *p;
3619 	int mode;
3620 
3621 	sc = addr;
3622 	flags = sc->sc_altflags;
3623 	paltidx = -1;
3624 	raltidx = -1;
3625 	if (sc->sc_dying)
3626 		return EIO;
3627 
3628 	if (((usemode & AUMODE_PLAY) && sc->sc_playchan.pipe != NULL) ||
3629 	    ((usemode & AUMODE_RECORD) && sc->sc_recchan.pipe != NULL))
3630 		return EBUSY;
3631 
3632 	if ((usemode & AUMODE_PLAY) && sc->sc_playchan.altidx != -1)
3633 		sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 0;
3634 	if ((usemode & AUMODE_RECORD) && sc->sc_recchan.altidx != -1)
3635 		sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 0;
3636 
3637 	/* Some uaudio devices are unidirectional.  Don't try to find a
3638 	   matching mode for the unsupported direction. */
3639 	setmode &= sc->sc_mode;
3640 
3641 	for (mode = AUMODE_RECORD; mode != -1;
3642 	     mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
3643 		if ((setmode & mode) == 0)
3644 			continue;
3645 
3646 		p = (mode == AUMODE_PLAY) ? play : rec;
3647 
3648 		factor = 1;
3649 		swcode = 0;
3650 		enc = p->encoding;
3651 		switch (enc) {
3652 		case AUDIO_ENCODING_SLINEAR_BE:
3653 			/* FALLTHROUGH */
3654 		case AUDIO_ENCODING_SLINEAR_LE:
3655 			if (enc == AUDIO_ENCODING_SLINEAR_BE
3656 			    && p->precision == 16 && (flags & HAS_16)) {
3657 				swcode = swap_bytes;
3658 				enc = AUDIO_ENCODING_SLINEAR_LE;
3659 			} else if (p->precision == 8) {
3660 				if (flags & HAS_8) {
3661 					/* No conversion */
3662 				} else if (flags & HAS_8U) {
3663 					swcode = change_sign8;
3664 					enc = AUDIO_ENCODING_ULINEAR_LE;
3665 				} else if (flags & HAS_16) {
3666 					factor = 2;
3667 					p->hw_precision = 16;
3668 					if (mode == AUMODE_PLAY)
3669 						swcode = linear8_to_linear16_le;
3670 					else
3671 						swcode = linear16_to_linear8_le;
3672 				}
3673 			}
3674 			break;
3675 		case AUDIO_ENCODING_ULINEAR_BE:
3676 			/* FALLTHROUGH */
3677 		case AUDIO_ENCODING_ULINEAR_LE:
3678 			if (p->precision == 16) {
3679 				if (enc == AUDIO_ENCODING_ULINEAR_LE)
3680 					swcode = change_sign16_le;
3681 				else if (mode == AUMODE_PLAY)
3682 					swcode = swap_bytes_change_sign16_le;
3683 				else
3684 					swcode = change_sign16_swap_bytes_le;
3685 				enc = AUDIO_ENCODING_SLINEAR_LE;
3686 			} else if (p->precision == 8) {
3687 				if (flags & HAS_8U) {
3688 					/* No conversion */
3689 				} else if (flags & HAS_8) {
3690 					swcode = change_sign8;
3691 					enc = AUDIO_ENCODING_SLINEAR_LE;
3692 				} else if (flags & HAS_16) {
3693 					factor = 2;
3694 					p->hw_precision = 16;
3695 					enc = AUDIO_ENCODING_SLINEAR_LE;
3696 					if (mode == AUMODE_PLAY)
3697 						swcode = ulinear8_to_slinear16_le;
3698 					else
3699 						swcode = slinear16_to_ulinear8_le;
3700 				}
3701 			}
3702 			break;
3703 		case AUDIO_ENCODING_ULAW:
3704 			if (flags & HAS_MULAW)
3705 				break;
3706 			if (flags & HAS_16) {
3707 				if (mode == AUMODE_PLAY)
3708 					swcode = mulaw_to_slinear16_le;
3709 				else
3710 					swcode = slinear16_to_mulaw_le;
3711 				factor = 2;
3712 				enc = AUDIO_ENCODING_SLINEAR_LE;
3713 				p->hw_precision = 16;
3714 			} else if (flags & HAS_8U) {
3715 				if (mode == AUMODE_PLAY)
3716 					swcode = mulaw_to_ulinear8;
3717 				else
3718 					swcode = ulinear8_to_mulaw;
3719 				enc = AUDIO_ENCODING_ULINEAR_LE;
3720 			} else if (flags & HAS_8) {
3721 				if (mode == AUMODE_PLAY)
3722 					swcode = mulaw_to_slinear8;
3723 				else
3724 					swcode = slinear8_to_mulaw;
3725 				enc = AUDIO_ENCODING_SLINEAR_LE;
3726 			} else
3727 				return (EINVAL);
3728 			break;
3729 		case AUDIO_ENCODING_ALAW:
3730 			if (flags & HAS_ALAW)
3731 				break;
3732 			if (mode == AUMODE_PLAY && (flags & HAS_16)) {
3733 				swcode = alaw_to_slinear16_le;
3734 				factor = 2;
3735 				enc = AUDIO_ENCODING_SLINEAR_LE;
3736 				p->hw_precision = 16;
3737 			} else if (flags & HAS_8U) {
3738 				if (mode == AUMODE_PLAY)
3739 					swcode = alaw_to_ulinear8;
3740 				else
3741 					swcode = ulinear8_to_alaw;
3742 				enc = AUDIO_ENCODING_ULINEAR_LE;
3743 			} else if (flags & HAS_8) {
3744 				if (mode == AUMODE_PLAY)
3745 					swcode = alaw_to_slinear8;
3746 				else
3747 					swcode = slinear8_to_alaw;
3748 				enc = AUDIO_ENCODING_SLINEAR_LE;
3749 			} else
3750 				return (EINVAL);
3751 			break;
3752 		default:
3753 			return (EINVAL);
3754 		}
3755 		/* XXX do some other conversions... */
3756 
3757 		DPRINTF(("uaudio_set_params: chan=%d prec=%d enc=%d rate=%ld\n",
3758 			 p->channels, p->hw_precision, enc, p->sample_rate));
3759 
3760 		p->hw_encoding = enc;
3761 		i = uaudio_match_alt(sc->sc_nalts, sc->sc_alts, p, mode);
3762 		if (i < 0)
3763 			return (EINVAL);
3764 
3765 		p->sw_code = swcode;
3766 		p->factor  = factor;
3767 
3768 		if (mode == AUMODE_PLAY)
3769 			paltidx = i;
3770 		else
3771 			raltidx = i;
3772 	}
3773 
3774 	if ((setmode & AUMODE_PLAY)) {
3775 		/* XXX abort transfer if currently happening? */
3776 		uaudio_chan_init(&sc->sc_playchan, paltidx, play, 0);
3777 	}
3778 	if ((setmode & AUMODE_RECORD)) {
3779 		/* XXX abort transfer if currently happening? */
3780 		uaudio_chan_init(&sc->sc_recchan, raltidx, rec,
3781 		    UGETW(sc->sc_alts[raltidx].edesc->wMaxPacketSize));
3782 	}
3783 
3784 	if ((usemode & AUMODE_PLAY) && sc->sc_playchan.altidx != -1)
3785 		sc->sc_alts[sc->sc_playchan.altidx].sc_busy = 1;
3786 	if ((usemode & AUMODE_RECORD) && sc->sc_recchan.altidx != -1)
3787 		sc->sc_alts[sc->sc_recchan.altidx].sc_busy = 1;
3788 
3789 	DPRINTF(("uaudio_set_params: use altidx=p%d/r%d, altno=p%d/r%d\n",
3790 		 sc->sc_playchan.altidx, sc->sc_recchan.altidx,
3791 		 (sc->sc_playchan.altidx >= 0)
3792 		   ?sc->sc_alts[sc->sc_playchan.altidx].idesc->bAlternateSetting
3793 		   : -1,
3794 		 (sc->sc_recchan.altidx >= 0)
3795 		   ? sc->sc_alts[sc->sc_recchan.altidx].idesc->bAlternateSetting
3796 		   : -1));
3797 
3798 	return 0;
3799 }
3800 #endif /* NetBSD or OpenBSD */
3801 
3802 static usbd_status
3803 uaudio_set_speed(struct uaudio_softc *sc, int endpt, u_int speed)
3804 {
3805 	usb_device_request_t req;
3806 	uint8_t data[3];
3807 
3808 	DPRINTFN(5,("uaudio_set_speed: endpt=%d speed=%u\n", endpt, speed));
3809 	req.bmRequestType = UT_WRITE_CLASS_ENDPOINT;
3810 	req.bRequest = SET_CUR;
3811 	USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0);
3812 	USETW(req.wIndex, endpt);
3813 	USETW(req.wLength, 3);
3814 	data[0] = speed;
3815 	data[1] = speed >> 8;
3816 	data[2] = speed >> 16;
3817 
3818 #if defined(__FreeBSD__)
3819 	if (sc->async != 0)
3820 		return usbd_do_request_async(sc->sc_udev, &req, data);
3821 #endif
3822 	return usbd_do_request(sc->sc_udev, &req, data);
3823 }
3824 
3825 
3826 #if defined(__FreeBSD__)
3827 /************************************************************/
3828 int
3829 uaudio_init_params(struct uaudio_softc *sc, struct chan *ch, int mode)
3830 {
3831 	int i, j, enc;
3832 	int samples_per_frame, sample_size;
3833 
3834 	if ((sc->sc_playchan.pipe != NULL) || (sc->sc_recchan.pipe != NULL))
3835 		return (-1);
3836 
3837 	switch(ch->format & 0x000FFFFF) {
3838 	case AFMT_U8:
3839 		enc = AUDIO_ENCODING_ULINEAR_LE;
3840 		ch->precision = 8;
3841 		break;
3842 	case AFMT_S8:
3843 		enc = AUDIO_ENCODING_SLINEAR_LE;
3844 		ch->precision = 8;
3845 		break;
3846 	case AFMT_A_LAW:	/* ? */
3847 		enc = AUDIO_ENCODING_ALAW;
3848 		ch->precision = 8;
3849 		break;
3850 	case AFMT_MU_LAW:	/* ? */
3851 		enc = AUDIO_ENCODING_ULAW;
3852 		ch->precision = 8;
3853 		break;
3854 	case AFMT_S16_LE:
3855 		enc = AUDIO_ENCODING_SLINEAR_LE;
3856 		ch->precision = 16;
3857 		break;
3858 	case AFMT_S16_BE:
3859 		enc = AUDIO_ENCODING_SLINEAR_BE;
3860 		ch->precision = 16;
3861 		break;
3862 	case AFMT_U16_LE:
3863 		enc = AUDIO_ENCODING_ULINEAR_LE;
3864 		ch->precision = 16;
3865 		break;
3866 	case AFMT_U16_BE:
3867 		enc = AUDIO_ENCODING_ULINEAR_BE;
3868 		ch->precision = 16;
3869 		break;
3870 	case AFMT_S24_LE:
3871 		enc = AUDIO_ENCODING_SLINEAR_LE;
3872 		ch->precision = 24;
3873 		break;
3874 	case AFMT_S24_BE:
3875 		enc = AUDIO_ENCODING_SLINEAR_BE;
3876 		ch->precision = 24;
3877 		break;
3878 	case AFMT_U24_LE:
3879 		enc = AUDIO_ENCODING_ULINEAR_LE;
3880 		ch->precision = 24;
3881 		break;
3882 	case AFMT_U24_BE:
3883 		enc = AUDIO_ENCODING_ULINEAR_BE;
3884 		ch->precision = 24;
3885 		break;
3886 	case AFMT_S32_LE:
3887 		enc = AUDIO_ENCODING_SLINEAR_LE;
3888 		ch->precision = 32;
3889 		break;
3890 	case AFMT_S32_BE:
3891 		enc = AUDIO_ENCODING_SLINEAR_BE;
3892 		ch->precision = 32;
3893 		break;
3894 	case AFMT_U32_LE:
3895 		enc = AUDIO_ENCODING_ULINEAR_LE;
3896 		ch->precision = 32;
3897 		break;
3898 	case AFMT_U32_BE:
3899 		enc = AUDIO_ENCODING_ULINEAR_BE;
3900 		ch->precision = 32;
3901 		break;
3902 	default:
3903 		enc = 0;
3904 		ch->precision = 16;
3905 		printf("Unknown format %x\n", ch->format);
3906 	}
3907 
3908 	if (ch->format & AFMT_STEREO) {
3909 		ch->channels = 2;
3910 	} else {
3911 		ch->channels = 1;
3912 	}
3913 
3914 /*	for (mode =  ......	 */
3915 		for (i = 0; i < sc->sc_nalts; i++) {
3916 			const struct usb_audio_streaming_type1_descriptor *a1d =
3917 				sc->sc_alts[i].asf1desc;
3918 			if (ch->channels == a1d->bNrChannels &&
3919 			    ch->precision == a1d->bBitResolution &&
3920 #if 0
3921 			    enc == sc->sc_alts[i].encoding) {
3922 #else
3923 			    enc == sc->sc_alts[i].encoding &&
3924 			    (mode == AUMODE_PLAY ? UE_DIR_OUT : UE_DIR_IN) ==
3925 			    UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress)) {
3926 #endif
3927 				if (a1d->bSamFreqType == UA_SAMP_CONTNUOUS) {
3928 					DPRINTFN(2,("uaudio_set_params: cont %d-%d\n",
3929 					    UA_SAMP_LO(a1d), UA_SAMP_HI(a1d)));
3930 					if (UA_SAMP_LO(a1d) <= ch->sample_rate &&
3931 					    ch->sample_rate <= UA_SAMP_HI(a1d)) {
3932 						if (mode == AUMODE_PLAY)
3933 							sc->sc_playchan.altidx = i;
3934 						else
3935 							sc->sc_recchan.altidx = i;
3936 						goto found;
3937 					}
3938 				} else {
3939 					for (j = 0; j < a1d->bSamFreqType; j++) {
3940 						DPRINTFN(2,("uaudio_set_params: disc #"
3941 						    "%d: %d\n", j, UA_GETSAMP(a1d, j)));
3942 						/* XXX allow for some slack */
3943 						if (UA_GETSAMP(a1d, j) ==
3944 						    ch->sample_rate) {
3945 							if (mode == AUMODE_PLAY)
3946 								sc->sc_playchan.altidx = i;
3947 							else
3948 								sc->sc_recchan.altidx = i;
3949 							goto found;
3950 						}
3951 					}
3952 				}
3953 			}
3954 		}
3955 		/* return (EINVAL); */
3956 		if (mode == AUMODE_PLAY)
3957 			printf("uaudio: This device can't play in rate=%d.\n", ch->sample_rate);
3958 		else
3959 			printf("uaudio: This device can't record in rate=%d.\n", ch->sample_rate);
3960 		return (-1);
3961 
3962 	found:
3963 #if 0 /* XXX */
3964 		p->sw_code = swcode;
3965 		p->factor  = factor;
3966 		if (usemode == mode)
3967 			sc->sc_curaltidx = i;
3968 #endif
3969 /*	} */
3970 
3971 	sample_size = ch->precision * ch->channels / 8;
3972 	samples_per_frame = ch->sample_rate / USB_FRAMES_PER_SECOND;
3973 	ch->fraction = ch->sample_rate % USB_FRAMES_PER_SECOND;
3974 	ch->sample_size = sample_size;
3975 	ch->bytes_per_frame = samples_per_frame * sample_size;
3976 	ch->residue = 0;
3977 
3978 	ch->cur = ch->start;
3979 	ch->transferred = 0;
3980 	ch->curchanbuf = 0;
3981 	return (0);
3982 }
3983 
3984 struct uaudio_conversion {
3985 	uint8_t uaudio_fmt;
3986 	uint8_t uaudio_prec;
3987 	uint32_t freebsd_fmt;
3988 };
3989 
3990 const struct uaudio_conversion const accepted_conversion[] = {
3991 	{AUDIO_ENCODING_ULINEAR_LE, 8, AFMT_U8},
3992 	{AUDIO_ENCODING_ULINEAR_LE, 16, AFMT_U16_LE},
3993 	{AUDIO_ENCODING_ULINEAR_LE, 24, AFMT_U24_LE},
3994 	{AUDIO_ENCODING_ULINEAR_LE, 32, AFMT_U32_LE},
3995 	{AUDIO_ENCODING_ULINEAR_BE, 16, AFMT_U16_BE},
3996 	{AUDIO_ENCODING_ULINEAR_BE, 24, AFMT_U24_BE},
3997 	{AUDIO_ENCODING_ULINEAR_BE, 32, AFMT_U32_BE},
3998 	{AUDIO_ENCODING_SLINEAR_LE, 8, AFMT_S8},
3999 	{AUDIO_ENCODING_SLINEAR_LE, 16, AFMT_S16_LE},
4000 	{AUDIO_ENCODING_SLINEAR_LE, 24, AFMT_S24_LE},
4001 	{AUDIO_ENCODING_SLINEAR_LE, 32, AFMT_S32_LE},
4002 	{AUDIO_ENCODING_SLINEAR_BE, 16, AFMT_S16_BE},
4003 	{AUDIO_ENCODING_SLINEAR_BE, 24, AFMT_S24_BE},
4004 	{AUDIO_ENCODING_SLINEAR_BE, 32, AFMT_S32_BE},
4005 	{AUDIO_ENCODING_ALAW, 8, AFMT_A_LAW},
4006 	{AUDIO_ENCODING_ULAW, 8, AFMT_MU_LAW},
4007 	{0,0,0}
4008 };
4009 
4010 unsigned
4011 uaudio_query_formats(device_t dev, int reqdir, unsigned maxfmt, struct pcmchan_caps *cap)
4012 {
4013 	struct uaudio_softc *sc;
4014 	const struct usb_audio_streaming_type1_descriptor *asf1d;
4015 	const struct uaudio_conversion *iterator;
4016 	unsigned fmtcount, foundcount;
4017 	u_int32_t fmt;
4018 	uint8_t format, numchan, subframesize, prec, dir, iscontinuous;
4019 	int freq, freq_min, freq_max;
4020 	char *numchannel_descr;
4021 	char freq_descr[64];
4022 	int i,r;
4023 
4024 	sc = device_get_softc(dev);
4025 	if (sc == NULL)
4026 		return 0;
4027 
4028 	cap->minspeed = cap->maxspeed = 0;
4029 	foundcount = fmtcount = 0;
4030 
4031 	for (i = 0; i < sc->sc_nalts; i++) {
4032 		dir = UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress);
4033 
4034 		if ((dir == UE_DIR_OUT) != (reqdir == PCMDIR_PLAY))
4035 			continue;
4036 
4037 		asf1d = sc->sc_alts[i].asf1desc;
4038 		format = sc->sc_alts[i].encoding;
4039 
4040 		numchan = asf1d->bNrChannels;
4041 		subframesize = asf1d->bSubFrameSize;
4042 		prec = asf1d->bBitResolution;	/* precision */
4043 		iscontinuous = asf1d->bSamFreqType == UA_SAMP_CONTNUOUS;
4044 
4045 		if (iscontinuous)
4046 			snprintf(freq_descr, sizeof(freq_descr), "continous min %d max %d", UA_SAMP_LO(asf1d), UA_SAMP_HI(asf1d));
4047 		else
4048 			snprintf(freq_descr, sizeof(freq_descr), "fixed frequency (%d listed formats)", asf1d->bSamFreqType);
4049 
4050 		if (numchan == 1)
4051 			numchannel_descr = " (mono)";
4052 		else if (numchan == 2)
4053 			numchannel_descr = " (stereo)";
4054 		else
4055 			numchannel_descr = "";
4056 
4057 		if (bootverbose) {
4058 			device_printf(dev, "uaudio_query_formats: found a native %s channel%s %s %dbit %dbytes/subframe X %d channels = %d bytes per sample\n",
4059 					(dir==UE_DIR_OUT)?"playback":"record",
4060 					numchannel_descr, freq_descr,
4061 					prec, subframesize, numchan, subframesize*numchan);
4062 		}
4063 		/*
4064 		 * Now start rejecting the ones that don't map to FreeBSD
4065 		 */
4066 
4067 		if (numchan != 1 && numchan != 2)
4068 			continue;
4069 
4070 		for (iterator = accepted_conversion ; iterator->uaudio_fmt != 0 ; iterator++)
4071 			if (iterator->uaudio_fmt == format && iterator->uaudio_prec == prec)
4072 				break;
4073 
4074 		if (iterator->uaudio_fmt == 0)
4075 			continue;
4076 
4077 		fmt = iterator->freebsd_fmt;
4078 
4079 		if (numchan == 2)
4080 			fmt |= AFMT_STEREO;
4081 
4082 		foundcount++;
4083 
4084 		if (fmtcount >= maxfmt)
4085 			continue;
4086 
4087 		cap->fmtlist[fmtcount++] = fmt;
4088 
4089 		if (iscontinuous) {
4090 			freq_min = UA_SAMP_LO(asf1d);
4091 			freq_max = UA_SAMP_HI(asf1d);
4092 
4093 			if (cap->minspeed == 0 || freq_min < cap->minspeed)
4094 				cap->minspeed = freq_min;
4095 			if (cap->maxspeed == 0)
4096 				cap->maxspeed = cap->minspeed;
4097 			if (freq_max > cap->maxspeed)
4098 				cap->maxspeed = freq_max;
4099 		} else {
4100 			for (r = 0; r < asf1d->bSamFreqType; r++) {
4101 				freq = UA_GETSAMP(asf1d, r);
4102 				if (cap->minspeed == 0 || freq < cap->minspeed)
4103 					cap->minspeed = freq;
4104 				if (cap->maxspeed == 0)
4105 					cap->maxspeed = cap->minspeed;
4106 				if (freq > cap->maxspeed)
4107 					cap->maxspeed = freq;
4108 			}
4109 		}
4110 	}
4111 	cap->fmtlist[fmtcount] = 0;
4112 	return foundcount;
4113 }
4114 
4115 void
4116 uaudio_chan_set_param_pcm_dma_buff(device_t dev, u_char *start, u_char *end,
4117 		struct pcm_channel *pc, int dir)
4118 {
4119 	struct uaudio_softc *sc;
4120 	struct chan *ch;
4121 
4122 	sc = device_get_softc(dev);
4123 #ifndef NO_RECORDING
4124 	if (dir == PCMDIR_PLAY)
4125 		ch = &sc->sc_playchan;
4126 	else
4127 		ch = &sc->sc_recchan;
4128 #else
4129 	ch = &sc->sc_playchan;
4130 #endif
4131 
4132 	ch->start = start;
4133 	ch->end = end;
4134 
4135 	ch->pcm_ch = pc;
4136 
4137 	return;
4138 }
4139 
4140 void
4141 uaudio_chan_set_param_blocksize(device_t dev, u_int32_t blocksize, int dir)
4142 {
4143 	struct uaudio_softc *sc;
4144 	struct chan *ch;
4145 
4146 	sc = device_get_softc(dev);
4147 #ifndef NO_RECORDING
4148 	if (dir == PCMDIR_PLAY)
4149 		ch = &sc->sc_playchan;
4150 	else
4151 		ch = &sc->sc_recchan;
4152 #else
4153 	ch = &sc->sc_playchan;
4154 #endif
4155 
4156 	ch->blksize = blocksize;
4157 
4158 	return;
4159 }
4160 
4161 int
4162 uaudio_chan_set_param_speed(device_t dev, u_int32_t speed, int reqdir)
4163 {
4164 	const struct uaudio_conversion *iterator;
4165 	struct uaudio_softc *sc;
4166 	struct chan *ch;
4167 	int i, r, score, hiscore, bestspeed;
4168 
4169 	sc = device_get_softc(dev);
4170 #ifndef NO_RECORDING
4171 	if (reqdir == PCMDIR_PLAY)
4172 		ch = &sc->sc_playchan;
4173 	else
4174 		ch = &sc->sc_recchan;
4175 #else
4176 	ch = &sc->sc_playchan;
4177 #endif
4178 	/*
4179 	 * We are successful if we find an endpoint that matches our selected format and it
4180 	 * supports the requested speed.
4181 	 */
4182 	hiscore = 0;
4183 	bestspeed = 1;
4184 	for (i = 0; i < sc->sc_nalts; i++) {
4185 		int dir = UE_GET_DIR(sc->sc_alts[i].edesc->bEndpointAddress);
4186 		int format = sc->sc_alts[i].encoding;
4187 		const struct usb_audio_streaming_type1_descriptor *asf1d = sc->sc_alts[i].asf1desc;
4188 		int iscontinuous = asf1d->bSamFreqType == UA_SAMP_CONTNUOUS;
4189 
4190 		if ((dir == UE_DIR_OUT) != (reqdir == PCMDIR_PLAY))
4191 			continue;
4192 
4193 		for (iterator = accepted_conversion ; iterator->uaudio_fmt != 0 ; iterator++)
4194 			if (iterator->uaudio_fmt != format || iterator->freebsd_fmt != (ch->format&0xfffffff))
4195 				continue;
4196 			if (iscontinuous) {
4197 				if (speed >= UA_SAMP_LO(asf1d) && speed <= UA_SAMP_HI(asf1d)) {
4198 					ch->sample_rate = speed;
4199 					return speed;
4200 				} else if (speed < UA_SAMP_LO(asf1d)) {
4201 					score = 0xfff * speed / UA_SAMP_LO(asf1d);
4202 					if (score > hiscore) {
4203 						bestspeed = UA_SAMP_LO(asf1d);
4204 						hiscore = score;
4205 					}
4206 				} else if (speed > UA_SAMP_HI(asf1d)) {
4207 					score = 0xfff * UA_SAMP_HI(asf1d) / speed;
4208 					if (score > hiscore) {
4209 						bestspeed = UA_SAMP_HI(asf1d);
4210 						hiscore = score;
4211 					}
4212 				}
4213 				continue;
4214 			}
4215 			for (r = 0; r < asf1d->bSamFreqType; r++) {
4216 				if (speed == UA_GETSAMP(asf1d, r)) {
4217 					ch->sample_rate = speed;
4218 					return speed;
4219 				}
4220 				if (speed > UA_GETSAMP(asf1d, r))
4221 					score = 0xfff * UA_GETSAMP(asf1d, r) / speed;
4222 				else
4223 					score = 0xfff * speed / UA_GETSAMP(asf1d, r);
4224 				if (score > hiscore) {
4225 					bestspeed = UA_GETSAMP(asf1d, r);
4226 					hiscore = score;
4227 				}
4228 			}
4229 	}
4230 	if (bestspeed != 1) {
4231 		ch->sample_rate = bestspeed;
4232 		return bestspeed;
4233 	}
4234 
4235 	return 0;
4236 }
4237 
4238 int
4239 uaudio_chan_getptr(device_t dev, int dir)
4240 {
4241 	struct uaudio_softc *sc;
4242 	struct chan *ch;
4243 	int ptr;
4244 
4245 	sc = device_get_softc(dev);
4246 #ifndef NO_RECORDING
4247 	if (dir == PCMDIR_PLAY)
4248 		ch = &sc->sc_playchan;
4249 	else
4250 		ch = &sc->sc_recchan;
4251 #else
4252 	ch = &sc->sc_playchan;
4253 #endif
4254 
4255 	ptr = ch->cur - ch->start;
4256 
4257 	return ptr;
4258 }
4259 
4260 void
4261 uaudio_chan_set_param_format(device_t dev, u_int32_t format, int dir)
4262 {
4263 	struct uaudio_softc *sc;
4264 	struct chan *ch;
4265 
4266 	sc = device_get_softc(dev);
4267 #ifndef NO_RECORDING
4268 	if (dir == PCMDIR_PLAY)
4269 		ch = &sc->sc_playchan;
4270 	else
4271 		ch = &sc->sc_recchan;
4272 #else
4273 	ch = &sc->sc_playchan;
4274 #endif
4275 
4276 	ch->format = format;
4277 
4278 	return;
4279 }
4280 
4281 int
4282 uaudio_halt_out_dma(device_t dev)
4283 {
4284 	struct uaudio_softc *sc;
4285 
4286 	sc = device_get_softc(dev);
4287 
4288 	DPRINTF(("uaudio_halt_out_dma: enter\n"));
4289 	if (sc->sc_playchan.pipe != NULL) {
4290 		uaudio_chan_close(sc, &sc->sc_playchan);
4291 		sc->sc_playchan.pipe = 0;
4292 		uaudio_chan_free_buffers(sc, &sc->sc_playchan);
4293 	}
4294         return (0);
4295 }
4296 
4297 int
4298 uaudio_halt_in_dma(device_t dev)
4299 {
4300 	struct uaudio_softc *sc;
4301 
4302 	sc = device_get_softc(dev);
4303 
4304 	if (sc->sc_dying)
4305 		return (EIO);
4306 
4307 	DPRINTF(("uaudio_halt_in_dma: enter\n"));
4308 	if (sc->sc_recchan.pipe != NULL) {
4309 		uaudio_chan_close(sc, &sc->sc_recchan);
4310 		sc->sc_recchan.pipe = NULL;
4311 		uaudio_chan_free_buffers(sc, &sc->sc_recchan);
4312 /*		sc->sc_recchan.intr = NULL; */
4313 	}
4314 	return (0);
4315 }
4316 
4317 int
4318 uaudio_trigger_input(device_t dev)
4319 {
4320 	struct uaudio_softc *sc;
4321 	struct chan *ch;
4322 	usbd_status err;
4323 	int i, s;
4324 
4325 	sc = device_get_softc(dev);
4326 	ch = &sc->sc_recchan;
4327 
4328 	if (sc->sc_dying)
4329 		return (EIO);
4330 
4331 /*	uaudio_chan_set_param(ch, start, end, blksize) */
4332 	if (uaudio_init_params(sc, ch, AUMODE_RECORD))
4333 		return (EIO);
4334 
4335 	err = uaudio_chan_alloc_buffers(sc, ch);
4336 	if (err)
4337 		return (EIO);
4338 
4339 	err = uaudio_chan_open(sc, ch);
4340 	if (err) {
4341 		uaudio_chan_free_buffers(sc, ch);
4342 		return (EIO);
4343 	}
4344 
4345 /*	ch->intr = intr;
4346 	ch->arg = arg; */
4347 
4348 	s = splusb();
4349 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX -1 shouldn't be needed */
4350 		uaudio_chan_rtransfer(ch);
4351 	splx(s);
4352 
4353 	return (0);
4354 }
4355 
4356 int
4357 uaudio_trigger_output(device_t dev)
4358 {
4359 	struct uaudio_softc *sc;
4360 	struct chan *ch;
4361 	usbd_status err;
4362 	int i, s;
4363 
4364 	sc = device_get_softc(dev);
4365 	ch = &sc->sc_playchan;
4366 
4367 	if (sc->sc_dying)
4368 		return (EIO);
4369 
4370 	if (uaudio_init_params(sc, ch, AUMODE_PLAY))
4371 		return (EIO);
4372 
4373 	err = uaudio_chan_alloc_buffers(sc, ch);
4374 	if (err)
4375 		return (EIO);
4376 
4377 	err = uaudio_chan_open(sc, ch);
4378 	if (err) {
4379 		uaudio_chan_free_buffers(sc, ch);
4380 		return (EIO);
4381 	}
4382 
4383 	s = splusb();
4384 	for (i = 0; i < UAUDIO_NCHANBUFS-1; i++) /* XXX */
4385 		uaudio_chan_ptransfer(ch);
4386 	splx(s);
4387 
4388         return (0);
4389 }
4390 
4391 u_int32_t
4392 uaudio_query_mix_info(device_t dev)
4393 {
4394 	int i;
4395 	u_int32_t mask = 0;
4396 	struct uaudio_softc *sc;
4397 	struct mixerctl *mc;
4398 
4399 	sc = device_get_softc(dev);
4400 	for (i=0; i < sc->sc_nctls; i++) {
4401 		mc = &sc->sc_ctls[i];
4402 		if (mc->ctl != SOUND_MIXER_NRDEVICES) {
4403 			/* Set device mask bits.
4404 			   See /usr/include/machine/soundcard.h */
4405 			mask |= (1 << mc->ctl);
4406 		}
4407 	}
4408 	return mask;
4409 }
4410 
4411 u_int32_t
4412 uaudio_query_recsrc_info(device_t dev)
4413 {
4414 	int i, rec_selector_id;
4415 	u_int32_t mask = 0;
4416 	struct uaudio_softc *sc;
4417 	struct mixerctl *mc;
4418 
4419 	sc = device_get_softc(dev);
4420 	rec_selector_id = -1;
4421 	for (i=0; i < sc->sc_nctls; i++) {
4422 		mc = &sc->sc_ctls[i];
4423 		if (mc->ctl == SOUND_MIXER_NRDEVICES &&
4424 		    mc->type == MIX_SELECTOR && mc->class == UAC_RECORD) {
4425 			if (rec_selector_id == -1) {
4426 				rec_selector_id = i;
4427 			} else {
4428 				printf("There are many selectors.  Can't recognize which selector is a record source selector.\n");
4429 				return mask;
4430 			}
4431 		}
4432 	}
4433 	if (rec_selector_id == -1)
4434 		return mask;
4435 	mc = &sc->sc_ctls[rec_selector_id];
4436 	for (i = mc->minval; i <= mc->maxval; i++) {
4437 		if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES)
4438 			continue;
4439 		mask |= 1 << mc->slctrtype[i - 1];
4440 	}
4441 	return mask;
4442 }
4443 
4444 void
4445 uaudio_mixer_set(device_t dev, unsigned type, unsigned left, unsigned right)
4446 {
4447 	int i;
4448 	struct uaudio_softc *sc;
4449 	struct mixerctl *mc;
4450 
4451 	sc = device_get_softc(dev);
4452 	for (i=0; i < sc->sc_nctls; i++) {
4453 		mc = &sc->sc_ctls[i];
4454 		if (mc->ctl == type) {
4455 			if (mc->nchan == 2) {
4456 				/* set Right */
4457 				uaudio_ctl_set(sc, SET_CUR, mc, 1, (int)(right*255)/100);
4458 			}
4459 			/* set Left or Mono */
4460 			uaudio_ctl_set(sc, SET_CUR, mc, 0, (int)(left*255)/100);
4461 		}
4462 	}
4463 	return;
4464 }
4465 
4466 u_int32_t
4467 uaudio_mixer_setrecsrc(device_t dev, u_int32_t src)
4468 {
4469 	int i, rec_selector_id;
4470 	struct uaudio_softc *sc;
4471 	struct mixerctl *mc;
4472 
4473 	sc = device_get_softc(dev);
4474 	rec_selector_id = -1;
4475 	for (i=0; i < sc->sc_nctls; i++) {
4476 		mc = &sc->sc_ctls[i];
4477 		if (mc->ctl == SOUND_MIXER_NRDEVICES &&
4478 		    mc->type == MIX_SELECTOR && mc->class == UAC_RECORD) {
4479 			if (rec_selector_id == -1) {
4480 				rec_selector_id = i;
4481 			} else {
4482 				return src; /* Can't recognize which selector is record source selector */
4483 			}
4484 		}
4485 	}
4486 	if (rec_selector_id == -1)
4487 		return src;
4488 	mc = &sc->sc_ctls[rec_selector_id];
4489 	for (i = mc->minval; i <= mc->maxval; i++) {
4490 		if (src != (1 << mc->slctrtype[i - 1]))
4491 			continue;
4492 		uaudio_ctl_set(sc, SET_CUR, mc, 0, i);
4493 		return (1 << mc->slctrtype[i - 1]);
4494 	}
4495 	uaudio_ctl_set(sc, SET_CUR, mc, 0, mc->minval);
4496 	return (1 << mc->slctrtype[mc->minval - 1]);
4497 }
4498 
4499 static int
4500 uaudio_sndstat_prepare_pcm(struct sbuf *s, device_t dev, int verbose)
4501 {
4502 	struct snddev_info *d;
4503 	struct pcm_channel *c;
4504 	struct pcm_feeder *f;
4505 	device_t pa_dev = device_get_parent(dev);
4506 	struct uaudio_softc *sc = device_get_softc(pa_dev);
4507 
4508 	if (verbose < 1)
4509 		return 0;
4510 
4511 	d = device_get_softc(dev);
4512 	if (!d)
4513 		return ENXIO;
4514 
4515 	PCM_BUSYASSERT(d);
4516 
4517 	if (CHN_EMPTY(d, channels.pcm)) {
4518 		sbuf_printf(s, " (mixer only)");
4519 		return 0;
4520 	}
4521 
4522 	sbuf_printf(s, " (%dp:%dv/%dr:%dv channels%s%s)",
4523 			d->playcount, d->pvchancount,
4524 			d->reccount, d->rvchancount,
4525 			(d->flags & SD_F_SIMPLEX)? "" : " duplex",
4526 #ifdef USING_DEVFS
4527 			(device_get_unit(dev) == snd_unit)? " default" : ""
4528 #else
4529 			""
4530 #endif
4531 			);
4532 
4533 	if (sc->uaudio_sndstat_flag != 0) {
4534 		sbuf_cat(s, sbuf_data(&(sc->uaudio_sndstat)));
4535 	}
4536 
4537 	if (verbose <= 1)
4538 		return 0;
4539 
4540 	CHN_FOREACH(c, d, channels.pcm) {
4541 
4542 		KASSERT(c->bufhard != NULL && c->bufsoft != NULL,
4543 			("hosed pcm channel setup"));
4544 
4545 		sbuf_printf(s, "\n\t");
4546 
4547 		/* it would be better to indent child channels */
4548 		sbuf_printf(s, "%s[%s]: ", c->parentchannel? c->parentchannel->name : "", c->name);
4549 		sbuf_printf(s, "spd %d", c->speed);
4550 		if (c->speed != sndbuf_getspd(c->bufhard))
4551 			sbuf_printf(s, "/%d", sndbuf_getspd(c->bufhard));
4552 		sbuf_printf(s, ", fmt 0x%08x", c->format);
4553 		if (c->format != sndbuf_getfmt(c->bufhard))
4554 			sbuf_printf(s, "/0x%08x", sndbuf_getfmt(c->bufhard));
4555 		sbuf_printf(s, ", flags 0x%08x, 0x%08x", c->flags, c->feederflags);
4556 		if (c->pid != -1)
4557 			sbuf_printf(s, ", pid %d", c->pid);
4558 		sbuf_printf(s, "\n\t");
4559 
4560 		sbuf_printf(s, "interrupts %d, ", c->interrupts);
4561 		if (c->direction == PCMDIR_REC)
4562 			sbuf_printf(s, "overruns %d, feed %u, hfree %d, sfree %d [b:%d/%d/%d|bs:%d/%d/%d]",
4563 			    c->xruns, c->feedcount, sndbuf_getfree(c->bufhard), sndbuf_getfree(c->bufsoft),
4564 			    sndbuf_getsize(c->bufhard), sndbuf_getblksz(c->bufhard),
4565 			    sndbuf_getblkcnt(c->bufhard),
4566 			    sndbuf_getsize(c->bufsoft), sndbuf_getblksz(c->bufsoft),
4567 			    sndbuf_getblkcnt(c->bufsoft));
4568 		else
4569 			sbuf_printf(s, "underruns %d, feed %u, ready %d [b:%d/%d/%d|bs:%d/%d/%d]",
4570 			    c->xruns, c->feedcount, sndbuf_getready(c->bufsoft),
4571 			    sndbuf_getsize(c->bufhard), sndbuf_getblksz(c->bufhard),
4572 			    sndbuf_getblkcnt(c->bufhard),
4573 			    sndbuf_getsize(c->bufsoft), sndbuf_getblksz(c->bufsoft),
4574 			    sndbuf_getblkcnt(c->bufsoft));
4575 		sbuf_printf(s, "\n\t");
4576 
4577 		sbuf_printf(s, "{%s}", (c->direction == PCMDIR_REC)? "hardware" : "userland");
4578 		sbuf_printf(s, " -> ");
4579 		f = c->feeder;
4580 		while (f->source != NULL)
4581 			f = f->source;
4582 		while (f != NULL) {
4583 			sbuf_printf(s, "%s", f->class->name);
4584 			if (f->desc->type == FEEDER_FMT)
4585 				sbuf_printf(s, "(0x%08x -> 0x%08x)", f->desc->in, f->desc->out);
4586 			if (f->desc->type == FEEDER_RATE)
4587 				sbuf_printf(s, "(%d -> %d)", FEEDER_GET(f, FEEDRATE_SRC), FEEDER_GET(f, FEEDRATE_DST));
4588 			if (f->desc->type == FEEDER_ROOT || f->desc->type == FEEDER_MIXER ||
4589 					f->desc->type == FEEDER_VOLUME)
4590 				sbuf_printf(s, "(0x%08x)", f->desc->out);
4591 			sbuf_printf(s, " -> ");
4592 			f = f->parent;
4593 		}
4594 		sbuf_printf(s, "{%s}", (c->direction == PCMDIR_REC)? "userland" : "hardware");
4595 	}
4596 
4597 	return 0;
4598 }
4599 
4600 void
4601 uaudio_sndstat_register(device_t dev)
4602 {
4603 	struct snddev_info *d = device_get_softc(dev);
4604 	sndstat_register(dev, d->status, uaudio_sndstat_prepare_pcm);
4605 }
4606 
4607 int
4608 uaudio_get_vendor(device_t dev)
4609 {
4610 	struct uaudio_softc *sc = device_get_softc(dev);
4611 
4612 	if (sc == NULL)
4613 		return 0;
4614 
4615 	return sc->sc_vendor;
4616 }
4617 
4618 int
4619 uaudio_get_product(device_t dev)
4620 {
4621 	struct uaudio_softc *sc = device_get_softc(dev);
4622 
4623 	if (sc == NULL)
4624 		return 0;
4625 
4626 	return sc->sc_product;
4627 }
4628 
4629 int
4630 uaudio_get_release(device_t dev)
4631 {
4632 	struct uaudio_softc *sc = device_get_softc(dev);
4633 
4634 	if (sc == NULL)
4635 		return 0;
4636 
4637 	return sc->sc_release;
4638 }
4639 
4640 static int
4641 audio_attach_mi(device_t dev)
4642 {
4643 	device_t child;
4644 	struct sndcard_func *func;
4645 
4646 	/* Attach the children. */
4647 	/* PCM Audio */
4648 	func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO);
4649 	if (func == NULL)
4650 		return (ENOMEM);
4651 	func->func = SCF_PCM;
4652 	child = device_add_child(dev, "pcm", -1);
4653 	device_set_ivars(child, func);
4654 
4655 	bus_generic_attach(dev);
4656 
4657 	return 0; /* XXXXX */
4658 }
4659 
4660 DRIVER_MODULE(uaudio, uhub, uaudio_driver, uaudio_devclass, usbd_driver_load, 0);
4661 MODULE_VERSION(uaudio, 1);
4662 
4663 #endif
4664