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