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