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