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