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