xref: /openbsd-src/sys/dev/usb/uaudio.c (revision fc405d53b73a2d73393cb97f684863d17b583e38)
1 /*	$OpenBSD: uaudio.c,v 1.172 2022/10/26 20:19:09 kn Exp $	*/
2 /*
3  * Copyright (c) 2018 Alexandre Ratchov <alex@caoua.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 /*
18  * The USB Audio Class (UAC) defines what is an audio device and how
19  * to use it. There are two versions of the UAC: v1.0 and v2.0. They
20  * are not compatible with each other but they are close enough to
21  * attempt to have the same driver for both.
22  *
23  */
24 #include <sys/param.h>
25 #include <sys/types.h>
26 #include <sys/device.h>
27 #include <sys/errno.h>
28 #include <sys/fcntl.h>
29 #include <sys/malloc.h>
30 #include <sys/systm.h>
31 #include <sys/time.h>
32 #include <sys/audioio.h>
33 #include <machine/bus.h>
34 #include <dev/audio_if.h>
35 #include <dev/usb/usb.h>
36 #include <dev/usb/usbdi.h>
37 #include <dev/usb/usbdivar.h>
38 #include <dev/usb/usb_mem.h>
39 
40 #ifdef UAUDIO_DEBUG
41 #define DPRINTF(...)				\
42 	do {					\
43 		if (uaudio_debug)		\
44 			printf(__VA_ARGS__);	\
45 	} while (0)
46 #else
47 #define DPRINTF(...) do {} while(0)
48 #endif
49 
50 #define DEVNAME(sc) ((sc)->dev.dv_xname)
51 
52 /*
53  * Isochronous endpoint usage (XXX: these belong to dev/usb/usb.h).
54  */
55 #define UE_ISO_USAGE			0x30
56 #define  UE_ISO_USAGE_DATA		0x00
57 #define  UE_ISO_USAGE_FEEDBACK		0x10
58 #define  UE_ISO_USAGE_IMPL		0x20
59 #define UE_GET_ISO_USAGE(a)		((a) & UE_ISO_USAGE)
60 
61 /*
62  * Max length of unit names
63  */
64 #define UAUDIO_NAMEMAX			MAX_AUDIO_DEV_LEN
65 
66 /*
67  * USB audio class versions
68  */
69 #define UAUDIO_V1			0x100
70 #define UAUDIO_V2			0x200
71 
72 /*
73  * AC class-specific descriptor interface sub-type
74  */
75 #define UAUDIO_AC_HEADER		0x1
76 #define UAUDIO_AC_INPUT			0x2
77 #define UAUDIO_AC_OUTPUT		0x3
78 #define UAUDIO_AC_MIXER			0x4
79 #define UAUDIO_AC_SELECTOR		0x5
80 #define UAUDIO_AC_FEATURE		0x6
81 #define UAUDIO_AC_EFFECT		0x7
82 #define UAUDIO_AC_PROCESSING		0x8
83 #define UAUDIO_AC_EXTENSION		0x9
84 #define UAUDIO_AC_CLKSRC		0xa
85 #define UAUDIO_AC_CLKSEL		0xb
86 #define UAUDIO_AC_CLKMULT		0xc
87 #define UAUDIO_AC_RATECONV		0xd
88 
89 /*
90  * AS class-specific interface sub-types
91  */
92 #define UAUDIO_AS_GENERAL		0x1
93 #define UAUDIO_AS_FORMAT		0x2
94 
95 /*
96  * AS class-specific endpoint sub-type
97  */
98 #define UAUDIO_EP_GENERAL		0x1
99 
100 /*
101  * UAC v1 formats, wFormatTag is an enum
102  */
103 #define UAUDIO_V1_FMT_PCM		0x1
104 #define UAUDIO_V1_FMT_PCM8		0x2
105 #define UAUDIO_V1_FMT_FLOAT		0x3
106 #define UAUDIO_V1_FMT_ALAW		0x4
107 #define UAUDIO_V1_FMT_MULAW		0x5
108 
109 /*
110  * UAC v2 formats, bmFormats is a bitmap
111  */
112 #define UAUDIO_V2_FMT_PCM		0x01
113 #define UAUDIO_V2_FMT_PCM8		0x02
114 #define UAUDIO_V2_FMT_FLOAT		0x04
115 #define UAUDIO_V2_FMT_ALAW		0x08
116 #define UAUDIO_V2_FMT_MULAW		0x10
117 
118 /*
119  * AC requests
120  */
121 #define UAUDIO_V1_REQ_SET_CUR		0x01
122 #define UAUDIO_V1_REQ_SET_MIN		0x02
123 #define UAUDIO_V1_REQ_SET_MAX		0x03
124 #define UAUDIO_V1_REQ_SET_RES		0x04
125 #define UAUDIO_V1_REQ_GET_CUR		0x81
126 #define UAUDIO_V1_REQ_GET_MIN		0x82
127 #define UAUDIO_V1_REQ_GET_MAX		0x83
128 #define UAUDIO_V1_REQ_GET_RES		0x84
129 #define UAUDIO_V2_REQ_CUR		1
130 #define UAUDIO_V2_REQ_RANGES		2
131 
132 /*
133  * AC request "selector control"
134  */
135 #define UAUDIO_V2_REQSEL_CLKFREQ	1
136 #define UAUDIO_V2_REQSEL_CLKSEL		1
137 
138 /*
139  * AS class-specific endpoint attributes
140  */
141 #define UAUDIO_EP_FREQCTL		0x01
142 
143 /*
144  * AC feature control selectors (aka wValue in the request)
145  */
146 #define UAUDIO_REQSEL_MUTE		0x01
147 #define UAUDIO_REQSEL_VOLUME		0x02
148 #define UAUDIO_REQSEL_BASS		0x03
149 #define UAUDIO_REQSEL_MID		0x04
150 #define UAUDIO_REQSEL_TREBLE		0x05
151 #define UAUDIO_REQSEL_EQ		0x06
152 #define UAUDIO_REQSEL_AGC		0x07
153 #define UAUDIO_REQSEL_DELAY		0x08
154 #define UAUDIO_REQSEL_BASSBOOST		0x09
155 #define UAUDIO_REQSEL_LOUDNESS		0x0a
156 #define UAUDIO_REQSEL_GAIN		0x0b
157 #define UAUDIO_REQSEL_GAINPAD		0x0c
158 #define UAUDIO_REQSEL_PHASEINV		0x0d
159 
160 /*
161  * Endpoint (UAC v1) or clock-source unit (UAC v2) sample rate control
162  */
163 #define UAUDIO_REQSEL_RATE		0x01
164 
165 /*
166  * Samples-per-frame are fractions. UAC v2.0 requires the denominator to
167  * be multiple of 2^16, as used in the sync pipe. On the other hand, to
168  * represent sample-per-frame of all rates we support, we need the
169  * denominator to be such that (rate / 1000) can be represented exactly,
170  * 80 works. So we use the least common multiplier of both.
171  */
172 #define UAUDIO_SPF_DIV			327680
173 
174 /*
175  * names of DAC and ADC unit names
176  */
177 #define UAUDIO_NAME_PLAY	"dac"
178 #define UAUDIO_NAME_REC		"record"
179 
180 /*
181  * read/write pointers for secure sequential access of binary data,
182  * ex. usb descriptors, tables and alike. Bytes are read using the
183  * read pointer up to the write pointer.
184  */
185 struct uaudio_blob {
186 	unsigned char *rptr, *wptr;
187 };
188 
189 /*
190  * Ranges of integer values used to represent controls values and
191  * sample frequencies.
192  */
193 struct uaudio_ranges {
194 	unsigned int nval;
195 	struct uaudio_ranges_el {
196 		struct uaudio_ranges_el *next;
197 		int min, max, res;
198 	} *el;
199 };
200 
201 struct uaudio_softc {
202 	struct device dev;
203 	struct usbd_device *udev;
204 	int version;
205 
206 	/*
207 	 * UAC exposes the device as a circuit of units. Input and
208 	 * output jacks are known as terminal units, others are
209 	 * processing units. The purpose of this driver is to give
210 	 * them reasonable names and expose them as mixer(1)
211 	 * controls. Control names are derived from the type of the
212 	 * unit and its role in the circuit.
213 	 *
214 	 * UAC v2.0 exposes also the clock circuitry using units, so
215 	 * selecting the sample rate also involves units usage.
216 	 */
217 	struct uaudio_unit {
218 		struct uaudio_unit *unit_next, *src_next, *dst_next;
219 		struct uaudio_unit *src_list, *dst_list;
220 		char name[UAUDIO_NAMEMAX];
221 		unsigned int nch;
222 		int type, id;
223 
224 		/* terminal or clock type */
225 		unsigned int term;
226 
227 		/* clock source, if a terminal or selector */
228 		struct uaudio_unit *clock;
229 
230 		/* sample rates, if this is a clock source */
231 		struct uaudio_ranges rates;
232 
233 		/* mixer(4) bits */
234 #define UAUDIO_CLASS_OUT	0
235 #define UAUDIO_CLASS_IN		1
236 #define UAUDIO_CLASS_COUNT	2
237 		int mixer_class;
238 		struct uaudio_mixent {
239 			struct uaudio_mixent *next;
240 			char *fname;
241 #define UAUDIO_MIX_SW	0
242 #define UAUDIO_MIX_NUM	1
243 #define UAUDIO_MIX_ENUM	2
244 			int type;
245 			int chan;
246 			int req_sel;
247 			struct uaudio_ranges ranges;
248 		} *mixent_list;
249 	} *unit_list;
250 
251 	/*
252 	 * Current clock, UAC v2.0 only
253 	 */
254 	struct uaudio_unit *clock;
255 
256 	/*
257 	 * Number of input and output terminals
258 	 */
259 	unsigned int nin, nout;
260 
261 	/*
262 	 * When unique names are needed, they are generated using a
263 	 * base string suffixed with a number. Ex. "spkr5". The
264 	 * following structure is used to keep track of strings we
265 	 * allocated.
266 	 */
267 	struct uaudio_name {
268 		struct uaudio_name *next;
269 		char *templ;
270 		unsigned int unit;
271 	} *names;
272 
273 	/*
274 	 * Audio streaming (AS) alternate settings, i.e. stream format
275 	 * and USB-related parameters to use it.
276 	 */
277 	struct uaudio_alt {
278 		struct uaudio_alt *next;
279 		int ifnum, altnum;
280 		int mode;		/* one of AUMODE_{RECORD,PLAY} */
281 		int data_addr;		/* data endpoint address */
282 		int sync_addr;		/* feedback endpoint address */
283 		int maxpkt;		/* max supported bytes per frame */
284 		int fps;		/* USB (micro-)frames per second */
285 		int bps, bits, nch;	/* audio encoding */
286 		int v1_rates;		/* if UAC 1.0, bitmap of rates */
287 	} *alts;
288 
289 	/*
290 	 * Audio parameters: play and record stream formats usable
291 	 * together.
292 	 */
293 	struct uaudio_params {
294 		struct uaudio_params *next;
295 		struct uaudio_alt *palt, *ralt;
296 		int v1_rates;
297 	} *params_list, *params;
298 
299 	/*
300 	 * One direction audio stream, aka "DMA" in progress
301 	 */
302 	struct uaudio_stream {
303 #define UAUDIO_NXFERS_MIN	2
304 #define UAUDIO_NXFERS_MAX	8
305 		struct uaudio_xfer {
306 			struct usbd_xfer *usb_xfer;
307 			unsigned char *buf;
308 			uint16_t *sizes;
309 			unsigned int size;	/* bytes requested */
310 			unsigned int nframes;	/* frames requested */
311 		} data_xfers[UAUDIO_NXFERS_MAX], sync_xfers[UAUDIO_NXFERS_MAX];
312 
313 		/*
314 		 * We don't use all the data_xfers[] entries because
315 		 * we can't schedule too many frames in the usb
316 		 * controller.
317 		 */
318 		unsigned int nxfers;
319 
320 		unsigned int spf_remain;	/* frac sample left */
321 		unsigned int spf;		/* avg samples per frame */
322 		unsigned int spf_min, spf_max;	/* allowed boundaries */
323 
324 		/*
325 		 * The max frame size we'll need (which may be lower
326 		 * than the maxpkt the usb pipe supports).
327 		 */
328 		unsigned int maxpkt;
329 
330 		/*
331 		 * max number of frames per xfer we'll need
332 		 */
333 		unsigned int nframes_max;
334 
335 		/*
336 		 * At usb2.0 speed, the number of (micro-)frames per
337 		 * transfer must correspond to 1ms, which is the usb1.1
338 		 * frame duration. This is required by lower level usb
339 		 * drivers.
340 		 *
341 		 * The nframes_mask variable is used to test if the
342 		 * number of frames per transfer is usable (by checking
343 		 * that least significant bits are zero). For instance,
344 		 * nframes_mask will be set to 0x0 on usb1.1 device and
345 		 * 0x7 on usb2.0 devices running at 8000 fps.
346 		 */
347 		unsigned int nframes_mask;
348 
349 		unsigned int data_nextxfer, sync_nextxfer;
350 		struct usbd_pipe *data_pipe;
351 		struct usbd_pipe *sync_pipe;
352 		void (*intr)(void *);
353 		void *arg;
354 
355 		/* audio ring extents, passed to trigger() methods */
356 		unsigned char *ring_start, *ring_end;
357 
358 		/* pointer to first byte available */
359 		unsigned char *ring_pos;
360 
361 		/* audio(9) block size in bytes */
362 		int ring_blksz;
363 
364 		/* xfer position relative to block boundary */
365 		int ring_offs;
366 
367 		/*
368 		 * As USB sample-per-frame is not constant, we must
369 		 * schedule transfers slightly larger that one audio
370 		 * block. This is the "safe" block size, that ensures
371 		 * the transfer will cross the audio block boundary.
372 		 */
373 		int safe_blksz;
374 
375 		/*
376 		 * Number of bytes completed, when it reaches a
377 		 * block size, we fire an audio(9) interrupt.
378 		 */
379 		int ring_icnt;
380 
381 		/*
382 		 * USB transfers are used as a FIFO which is the
383 		 * concatenation of all transfers. This is the write
384 		 * (read) position of the play (rec) stream
385 		 */
386 		unsigned int ubuf_xfer;		/* xfer index */
387 		unsigned int ubuf_pos;		/* offset in bytes */
388 	} pstream, rstream;
389 
390 	int ctl_ifnum;			/* aka AC interface */
391 
392 	int mode;			/* open() mode */
393 	int trigger_mode;		/* trigger() mode */
394 
395 	unsigned int rate;		/* current sample rate */
396 	unsigned int ufps;		/* USB frames per second */
397 	unsigned int sync_pktsz;	/* size of sync packet */
398 	unsigned int host_nframes;	/* max frames we can schedule */
399 
400 	int diff_nsamp;			/* samples play is ahead of rec */
401 	int diff_nframes;		/* frames play is ahead of rec */
402 	unsigned int adjspf_age;	/* frames since last uaudio_adjspf */
403 
404 	/*
405 	 * bytes pending to be copied to transfer buffer. This is play
406 	 * only, as recorded frames are copied as soon they are
407 	 * received.
408 	 */
409 	size_t copy_todo;
410 };
411 
412 int uaudio_match(struct device *, void *, void *);
413 void uaudio_attach(struct device *, struct device *, void *);
414 int uaudio_detach(struct device *, int);
415 
416 int uaudio_open(void *, int);
417 void uaudio_close(void *);
418 int uaudio_set_params(void *, int, int, struct audio_params *,
419     struct audio_params *);
420 unsigned int uaudio_set_blksz(void *, int,
421     struct audio_params *, struct audio_params *, unsigned int);
422 int uaudio_trigger_output(void *, void *, void *, int,
423     void (*)(void *), void *, struct audio_params *);
424 int uaudio_trigger_input(void *, void *, void *, int,
425     void (*)(void *), void *, struct audio_params *);
426 void uaudio_copy_output(void *, size_t);
427 void uaudio_underrun(void *);
428 int uaudio_halt_output(void *);
429 int uaudio_halt_input(void *);
430 int uaudio_query_devinfo(void *, struct mixer_devinfo *);
431 int uaudio_get_port(void *, struct mixer_ctrl *);
432 int uaudio_set_port(void *, struct mixer_ctrl *);
433 
434 int uaudio_process_unit(struct uaudio_softc *,
435     struct uaudio_unit *, int,
436     struct uaudio_blob,
437     struct uaudio_unit **);
438 
439 void uaudio_pdata_intr(struct usbd_xfer *, void *, usbd_status);
440 void uaudio_rdata_intr(struct usbd_xfer *, void *, usbd_status);
441 void uaudio_psync_intr(struct usbd_xfer *, void *, usbd_status);
442 
443 #ifdef UAUDIO_DEBUG
444 char *uaudio_isoname(int isotype);
445 char *uaudio_modename(int mode);
446 char *uaudio_usagename(int usage);
447 void uaudio_rates_print(int rates);
448 void uaudio_ranges_print(struct uaudio_ranges *r);
449 void uaudio_print_unit(struct uaudio_softc *sc, struct uaudio_unit *u);
450 void uaudio_mixer_print(struct uaudio_softc *sc);
451 void uaudio_conf_print(struct uaudio_softc *sc);
452 
453 /*
454  * 0 - nothing, same as if UAUDIO_DEBUG isn't defined
455  * 1 - initialisations & setup
456  * 2 - audio(4) calls
457  * 3 - transfers
458  */
459 int uaudio_debug = 1;
460 #endif
461 
462 struct cfdriver uaudio_cd = {
463 	NULL, "uaudio", DV_DULL
464 };
465 
466 const struct cfattach uaudio_ca = {
467 	sizeof(struct uaudio_softc), uaudio_match, uaudio_attach, uaudio_detach
468 };
469 
470 const struct audio_hw_if uaudio_hw_if = {
471 	.open = uaudio_open,
472 	.close = uaudio_close,
473 	.set_params = uaudio_set_params,
474 	.halt_output = uaudio_halt_output,
475 	.halt_input = uaudio_halt_input,
476 	.set_port = uaudio_set_port,
477 	.get_port = uaudio_get_port,
478 	.query_devinfo = uaudio_query_devinfo,
479 	.trigger_output = uaudio_trigger_output,
480 	.trigger_input = uaudio_trigger_input,
481 	.copy_output = uaudio_copy_output,
482 	.underrun = uaudio_underrun,
483 	.set_blksz = uaudio_set_blksz,
484 };
485 
486 /*
487  * To keep things simple, we support only the following rates, we
488  * don't care about continuous sample rates or other "advanced"
489  * features which complicate implementation.
490  */
491 const int uaudio_rates[] = {
492 	8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000,
493 	64000, 88200, 96000, 128000, 176400, 192000
494 };
495 
496 /*
497  * Convert 8, 16, or 24-bit signed value to an int by expanding the
498  * sign bit.
499  */
500 int
501 uaudio_sign_expand(unsigned int val, int opsize)
502 {
503 	unsigned int s;
504 
505 	s = 1 << (8 * opsize - 1);
506 	return (val ^ s) - s;
507 }
508 
509 int
510 uaudio_req(struct uaudio_softc *sc,
511     unsigned int type,
512     unsigned int req,
513     unsigned int sel,
514     unsigned int chan,
515     unsigned int ifnum,
516     unsigned int id,
517     unsigned char *buf,
518     size_t size)
519 {
520 	struct usb_device_request r;
521 	int err;
522 
523 	r.bmRequestType = type;
524 	r.bRequest = req;
525 	USETW(r.wValue, sel << 8 | chan);
526 	USETW(r.wIndex, id << 8 | ifnum);
527 	USETW(r.wLength, size);
528 
529 	DPRINTF("%s: type = 0x%x, req = 0x%x, val = 0x%x, "
530 	    "index = 0x%x, size = %d\n", __func__,
531 	    type, req, UGETW(r.wValue), UGETW(r.wIndex), UGETW(r.wLength));
532 
533 	err = usbd_do_request(sc->udev, &r, buf);
534 	if (err) {
535 		DPRINTF("%s: failed: %s\n", __func__, usbd_errstr(err));
536 		return 0;
537 	}
538 	return 1;
539 }
540 
541 /*
542  * Read a number of the given size (in bytes) from the given
543  * blob. Return 0 on error.
544  */
545 int
546 uaudio_getnum(struct uaudio_blob *p, unsigned int size, unsigned int *ret)
547 {
548 	unsigned int i, num = 0;
549 
550 	if (p->wptr - p->rptr < size) {
551 		DPRINTF("%s: %d: too small\n", __func__, size);
552 		return 0;
553 	}
554 
555 	for (i = 0; i < size; i++)
556 		num |= *p->rptr++ << (8 * i);
557 
558 	if (ret)
559 		*ret = num;
560 	return 1;
561 }
562 
563 /*
564  * Read a USB descriptor from the given blob. Return 0 on error.
565  */
566 int
567 uaudio_getdesc(struct uaudio_blob *p, struct uaudio_blob *ret)
568 {
569 	unsigned int size;
570 
571 	if (!uaudio_getnum(p, 1, &size))
572 		return 0;
573 	if (size-- == 0) {
574 		DPRINTF("%s: zero sized desc\n", __func__);
575 		return 0;
576 	}
577 	if (p->wptr - p->rptr < size) {
578 		DPRINTF("%s: too small\n", __func__);
579 		return 0;
580 	}
581 	ret->rptr = p->rptr;
582 	ret->wptr = p->rptr + size;
583 	p->rptr += size;
584 	return 1;
585 }
586 
587 /*
588  * Find the unit with the given id, return NULL if not found.
589  */
590 struct uaudio_unit *
591 uaudio_unit_byid(struct uaudio_softc *sc, unsigned int id)
592 {
593 	struct uaudio_unit *u;
594 
595 	for (u = sc->unit_list; u != NULL; u = u->unit_next) {
596 		if (u->id == id)
597 			break;
598 	}
599 	return u;
600 }
601 
602 /*
603  * Return a terminal name for the given terminal type.
604  */
605 char *
606 uaudio_tname(struct uaudio_softc *sc, unsigned int type, int isout)
607 {
608 	unsigned int hi, lo;
609 	char *name;
610 
611 	hi = type >> 8;
612 	lo = type & 0xff;
613 
614 	/* usb data stream */
615 	if (hi == 1)
616 		return isout ? UAUDIO_NAME_REC : UAUDIO_NAME_PLAY;
617 
618 	/* if there is only one input (output) use "input" ("output") */
619 	if (isout) {
620 		if (sc->nout == 1)
621 			return "output";
622 	} else {
623 		if (sc->nin == 1)
624 			return "input";
625 	}
626 
627 	/* determine name from USB terminal type */
628 	switch (hi) {
629 	case 2:
630 		/* embedded inputs */
631 		name = isout ? "mic-out" : "mic";
632 		break;
633 	case 3:
634 		/* embedded outputs, mostly speakers, except 0x302 */
635 		switch (lo) {
636 		case 0x02:
637 			name = isout ? "hp" : "hp-in";
638 			break;
639 		default:
640 			name = isout ? "spkr" : "spkr-in";
641 			break;
642 		}
643 		break;
644 	case 4:
645 		/* handsets and headset */
646 		name = isout ? "spkr" : "mic";
647 		break;
648 	case 5:
649 		/* phone line */
650 		name = isout ? "phone-in" : "phone-out";
651 		break;
652 	case 6:
653 		/* external sources/sinks */
654 		switch (lo) {
655 		case 0x02:
656 		case 0x05:
657 		case 0x06:
658 		case 0x07:
659 		case 0x09:
660 		case 0x0a:
661 			name = isout ? "dig-out" : "dig-in";
662 			break;
663 		default:
664 			name = isout ? "line-out" : "line-in";
665 			break;
666 		}
667 		break;
668 	case 7:
669 		/* internal devices */
670 		name = isout ? "int-out" : "int-in";
671 		break;
672 	default:
673 		name = isout ? "unk-out" : "unk-in";
674 	}
675 	return name;
676 }
677 
678 /*
679  * Return a clock name for the given clock type.
680  */
681 char *
682 uaudio_clkname(unsigned int attr)
683 {
684 	static char *names[] = {"ext", "fixed", "var", "prog"};
685 
686 	return names[attr & 3];
687 }
688 
689 /*
690  * Return an unique name for the given template.
691  */
692 void
693 uaudio_mkname(struct uaudio_softc *sc, char *templ, char *res)
694 {
695 	struct uaudio_name *n;
696 	char *sep;
697 
698 	/*
699 	 * if this is not a terminal name (i.e. there's a underscore
700 	 * in the name, like in "spkr2_mic3"), then use underscore as
701 	 * separator to avoid concatenating two numbers
702 	 */
703 	sep = strchr(templ, '_') != NULL ? "_" : "";
704 
705 	n = sc->names;
706 	while (1) {
707 		if (n == NULL) {
708 			n = malloc(sizeof(struct uaudio_name),
709 			    M_USBDEV, M_WAITOK);
710 			n->templ = templ;
711 			n->unit = 0;
712 			n->next = sc->names;
713 			sc->names = n;
714 		}
715 		if (strcmp(n->templ, templ) == 0)
716 			break;
717 		n = n->next;
718 	}
719 	if (n->unit == 0)
720 		snprintf(res, UAUDIO_NAMEMAX, "%s", templ);
721 	else
722 		snprintf(res, UAUDIO_NAMEMAX, "%s%s%u", templ, sep, n->unit);
723 	n->unit++;
724 }
725 
726 /*
727  * Convert UAC v1.0 feature bitmap to UAC v2.0 feature bitmap.
728  */
729 unsigned int
730 uaudio_feature_fixup(struct uaudio_softc *sc, unsigned int ctl)
731 {
732 	int i;
733 	unsigned int bits, n;
734 
735 	switch (sc->version) {
736 	case UAUDIO_V1:
737 		n = 0;
738 		for (i = 0; i < 16; i++) {
739 			bits = (ctl >> i) & 1;
740 			if (bits)
741 				bits |= 2;
742 			n |= bits << (2 * i);
743 		}
744 		return n;
745 	case UAUDIO_V2:
746 		break;
747 	}
748 	return ctl;
749 }
750 
751 /*
752  * Initialize a uaudio_ranges to the empty set
753  */
754 void
755 uaudio_ranges_init(struct uaudio_ranges *r)
756 {
757 	r->el = NULL;
758 	r->nval = 0;
759 }
760 
761 /*
762  * Add the given range to the uaudio_ranges structures. Ranges are
763  * not supposed to overlap (required by USB spec). If they do we just
764  * return.
765  */
766 void
767 uaudio_ranges_add(struct uaudio_ranges *r, int min, int max, int res)
768 {
769 	struct uaudio_ranges_el *e, **pe;
770 
771 	if (min > max) {
772 		DPRINTF("%s: [%d:%d]/%d: bad range\n", __func__,
773 		    min, max, res);
774 		return;
775 	}
776 
777 	for (pe = &r->el; (e = *pe) != NULL; pe = &e->next) {
778 		if (min <= e->max && max >= e->min) {
779 			DPRINTF("%s: overlapping ranges\n", __func__);
780 			return;
781 		}
782 		if (min < e->max)
783 			break;
784 	}
785 
786 	/* XXX: use 'res' here */
787 	r->nval += max - min + 1;
788 
789 	e = malloc(sizeof(struct uaudio_ranges_el), M_USBDEV, M_WAITOK);
790 	e->min = min;
791 	e->max = max;
792 	e->res = res;
793 	e->next = *pe;
794 	*pe = e;
795 }
796 
797 /*
798  * Free all ranges making the uaudio_ranges the empty set
799  */
800 void
801 uaudio_ranges_clear(struct uaudio_ranges *r)
802 {
803 	struct uaudio_ranges_el *e;
804 
805 	while ((e = r->el) != NULL) {
806 		r->el = e->next;
807 		free(e, M_USBDEV, sizeof(struct uaudio_ranges_el));
808 	}
809 	r->nval = 0;
810 }
811 
812 /*
813  * Convert a value in the given uaudio_ranges, into a 0..255 integer
814  * suitable for mixer usage
815  */
816 int
817 uaudio_ranges_decode(struct uaudio_ranges *r, int val)
818 {
819 	struct uaudio_ranges_el *e;
820 	int diff, pos;
821 
822 	pos = 0;
823 
824 	for (e = r->el; e != NULL; e = e->next) {
825 		if (val >= e->min && val <= e->max) {
826 			pos += val - e->min;
827 			return (r->nval == 1) ? 0 :
828 			    (pos * 255 + (r->nval - 1) / 2) / (r->nval - 1);
829 		}
830 		diff = e->max - e->min + 1;
831 		pos += diff;
832 	}
833 	return 0;
834 }
835 
836 /*
837  * Convert a 0..255 to a value in the uaudio_ranges suitable for a USB
838  * request.
839  */
840 unsigned int
841 uaudio_ranges_encode(struct uaudio_ranges *r, int val)
842 {
843 	struct uaudio_ranges_el *e;
844 	int diff, pos;
845 
846 	pos = (val * (r->nval - 1) + 127) / 255;
847 
848 	for (e = r->el; e != NULL; e = e->next) {
849 		diff = e->max - e->min + 1;
850 		if (pos < diff)
851 			return e->min + pos;
852 		pos -= diff;
853 	}
854 	return 0;
855 }
856 
857 /*
858  * Return the bitmap of supported rates included in the given ranges.
859  * This is not a mixer thing, UAC v2.0 uses ranges to report sample
860  * rates.
861  */
862 int
863 uaudio_ranges_getrates(struct uaudio_ranges *r,
864     unsigned int mult, unsigned int div)
865 {
866 	struct uaudio_ranges_el *e;
867 	int rates, i, v;
868 
869 	rates = 0;
870 
871 	for (e = r->el; e != NULL; e = e->next) {
872 		for (i = 0; i < nitems(uaudio_rates); i++) {
873 			v = (unsigned long long)uaudio_rates[i] * mult / div;
874 			if (v < e->min || v > e->max)
875 				continue;
876 			if (e->res == 0 || v - e->min % e->res == 0)
877 				rates |= 1 << i;
878 		}
879 	}
880 
881 	return rates;
882 }
883 
884 /*
885  * Return the index in the uaudio_rates[] array of rate closest to the
886  * given rate in Hz.
887  */
888 int
889 uaudio_rates_indexof(int mask, int rate)
890 {
891 	int i, diff, best_index, best_diff;
892 
893 	best_index = -1;
894 	best_diff = INT_MAX;
895 	for (i = 0; i < nitems(uaudio_rates); i++) {
896 		if ((mask & (1 << i)) == 0)
897 			continue;
898 		diff = uaudio_rates[i] - rate;
899 		if (diff < 0)
900 			diff = -diff;
901 		if (diff < best_diff) {
902 			best_index = i;
903 			best_diff = diff;
904 		}
905 	}
906 	return best_index;
907 }
908 
909 /*
910  * Do a request that results in a uaudio_ranges. On UAC v1.0, this is
911  * simply a min/max/res triplet. On UAC v2.0, this is an array of
912  * min/max/res triplets.
913  */
914 int
915 uaudio_req_ranges(struct uaudio_softc *sc,
916     unsigned int opsize,
917     unsigned int sel,
918     unsigned int chan,
919     unsigned int ifnum,
920     unsigned int id,
921     struct uaudio_ranges *r)
922 {
923 	unsigned char req_buf[16], *req = NULL;
924 	size_t req_size;
925 	struct uaudio_blob p;
926 	unsigned int count, min, max, res;
927 	int i;
928 
929 	switch (sc->version) {
930 	case UAUDIO_V1:
931 		count = 1;
932 		req = req_buf;
933 		p.rptr = p.wptr = req;
934 		if (!uaudio_req(sc, UT_READ_CLASS_INTERFACE,
935 			UAUDIO_V1_REQ_GET_MIN, sel, chan,
936 			ifnum, id, p.wptr, opsize))
937 			return 0;
938 		p.wptr += opsize;
939 		if (!uaudio_req(sc, UT_READ_CLASS_INTERFACE,
940 			UAUDIO_V1_REQ_GET_MAX, sel, chan,
941 			ifnum, id, p.wptr, opsize))
942 			return 0;
943 		p.wptr += opsize;
944 		if (!uaudio_req(sc, UT_READ_CLASS_INTERFACE,
945 			UAUDIO_V1_REQ_GET_RES, sel, chan,
946 			ifnum, id, p.wptr, opsize))
947 			return 0;
948 		p.wptr += opsize;
949 		break;
950 	case UAUDIO_V2:
951 		/* fetch the ranges count only (first 2 bytes) */
952 		if (!uaudio_req(sc, UT_READ_CLASS_INTERFACE,
953 			UAUDIO_V2_REQ_RANGES, sel, chan,
954 			ifnum, id, req_buf, 2))
955 			return 0;
956 
957 		/* count is at most 65535 */
958 		count = req_buf[0] | req_buf[1] << 8;
959 
960 		/* restart the request on a large enough buffer */
961 		req_size = 2 + 3 * opsize * count;
962 		if (sizeof(req_buf) >= req_size)
963 			req = req_buf;
964 		else
965 			req = malloc(req_size, M_USBDEV, M_WAITOK);
966 
967 		p.rptr = p.wptr = req;
968 		if (!uaudio_req(sc, UT_READ_CLASS_INTERFACE,
969 			UAUDIO_V2_REQ_RANGES, sel, chan,
970 			ifnum, id, p.wptr, req_size))
971 			return 0;
972 		p.wptr += req_size;
973 
974 		/* skip initial 2 bytes of count */
975 		p.rptr += 2;
976 		break;
977 	}
978 
979 	for (i = 0; i < count; i++) {
980 		if (!uaudio_getnum(&p, opsize, &min))
981 			return 0;
982 		if (!uaudio_getnum(&p, opsize, &max))
983 			return 0;
984 		if (!uaudio_getnum(&p, opsize, &res))
985 			return 0;
986 		uaudio_ranges_add(r,
987 		    uaudio_sign_expand(min, opsize),
988 		    uaudio_sign_expand(max, opsize),
989 		    uaudio_sign_expand(res, opsize));
990 	}
991 
992 	if (req != req_buf)
993 		free(req, M_USBDEV, req_size);
994 
995 	return 1;
996 }
997 
998 /*
999  * Return the rates bitmap of the given interface alt setting
1000  */
1001 int
1002 uaudio_alt_getrates(struct uaudio_softc *sc, struct uaudio_alt *p)
1003 {
1004 	struct uaudio_unit *u;
1005 	unsigned int mult = 1, div = 1;
1006 
1007 	switch (sc->version) {
1008 	case UAUDIO_V1:
1009 		return p->v1_rates;
1010 	case UAUDIO_V2:
1011 		u = sc->clock;
1012 		while (1) {
1013 			switch (u->type) {
1014 			case UAUDIO_AC_CLKSRC:
1015 				return uaudio_ranges_getrates(&u->rates,
1016 				    mult, div);
1017 			case UAUDIO_AC_CLKSEL:
1018 				u = u->clock;
1019 				break;
1020 			case UAUDIO_AC_CLKMULT:
1021 			case UAUDIO_AC_RATECONV:
1022 				/* XXX: adjust rate with multiplier */
1023 				u = u->src_list;
1024 				break;
1025 			default:
1026 				DPRINTF("%s: no clock\n", __func__);
1027 				return 0;
1028 			}
1029 		}
1030 	}
1031 	return 0;
1032 }
1033 
1034 /*
1035  * return the clock unit of the given terminal unit (v2 only)
1036  */
1037 int
1038 uaudio_clock_id(struct uaudio_softc *sc)
1039 {
1040 	struct uaudio_unit *u;
1041 
1042 	u = sc->clock;
1043 	while (1) {
1044 		if (u == NULL) {
1045 			DPRINTF("%s: NULL clock pointer\n", __func__);
1046 			return -1;
1047 		}
1048 		switch (u->type) {
1049 		case UAUDIO_AC_CLKSRC:
1050 			return u->id;
1051 		case UAUDIO_AC_CLKSEL:
1052 			u = u->clock;
1053 			break;
1054 		case UAUDIO_AC_CLKMULT:
1055 		case UAUDIO_AC_RATECONV:
1056 			u = u->src_list;
1057 			break;
1058 		default:
1059 			DPRINTF("%s: no clock\n", __func__);
1060 			return -1;
1061 		}
1062 	}
1063 }
1064 
1065 /*
1066  * Return the rates bitmap of the given parameters setting
1067  */
1068 int
1069 uaudio_getrates(struct uaudio_softc *sc, struct uaudio_params *p)
1070 {
1071 	switch (sc->version) {
1072 	case UAUDIO_V1:
1073 		return p->v1_rates;
1074 	case UAUDIO_V2:
1075 		return uaudio_alt_getrates(sc, p->palt ? p->palt : p->ralt);
1076 	}
1077 	return 0;
1078 }
1079 
1080 /*
1081  * Add the given feature (aka mixer control) to the given unit.
1082  */
1083 void
1084 uaudio_feature_addent(struct uaudio_softc *sc,
1085     struct uaudio_unit *u, int uac_type, int chan)
1086 {
1087 	static struct {
1088 		char *name;
1089 		int mix_type;
1090 		int req_sel;
1091 	} features[] = {
1092 		{"mute", UAUDIO_MIX_SW, UAUDIO_REQSEL_MUTE},
1093 		{"level", UAUDIO_MIX_NUM, UAUDIO_REQSEL_VOLUME},
1094 		{"bass", UAUDIO_MIX_NUM, UAUDIO_REQSEL_BASS},
1095 		{"mid", UAUDIO_MIX_NUM, UAUDIO_REQSEL_MID},
1096 		{"treble", UAUDIO_MIX_NUM, UAUDIO_REQSEL_TREBLE},
1097 		{"eq", UAUDIO_MIX_NUM, UAUDIO_REQSEL_EQ},
1098 		{"agc", UAUDIO_MIX_SW, UAUDIO_REQSEL_AGC},
1099 		{NULL, -1, -1},			/* delay */
1100 		{"bassboost", UAUDIO_MIX_SW, UAUDIO_REQSEL_BASSBOOST},
1101 		{"loud", UAUDIO_MIX_SW, UAUDIO_REQSEL_LOUDNESS},
1102 		{"gain", UAUDIO_MIX_NUM, UAUDIO_REQSEL_GAIN},
1103 		{"gainpad", UAUDIO_MIX_SW, UAUDIO_REQSEL_GAINPAD},
1104 		{"phase", UAUDIO_MIX_SW, UAUDIO_REQSEL_PHASEINV},
1105 		{NULL, -1, -1},			/* underflow */
1106 		{NULL, -1, -1}			/* overflow */
1107 	};
1108 	struct uaudio_mixent *m, *i, **pi;
1109 	int cmp;
1110 
1111 	if (uac_type >= sizeof(features) / sizeof(features[0])) {
1112 		printf("%s: skipped unknown feature\n", DEVNAME(sc));
1113 		return;
1114 	}
1115 
1116 	m = malloc(sizeof(struct uaudio_mixent), M_USBDEV, M_WAITOK);
1117 	m->chan = chan;
1118 	m->fname = features[uac_type].name;
1119 	m->type = features[uac_type].mix_type;
1120 	m->req_sel = features[uac_type].req_sel;
1121 	uaudio_ranges_init(&m->ranges);
1122 
1123 	if (m->type == UAUDIO_MIX_NUM) {
1124 		if (!uaudio_req_ranges(sc, 2,
1125 			m->req_sel, chan < 0 ? 0 : chan + 1,
1126 			sc->ctl_ifnum, u->id,
1127 			&m->ranges)) {
1128 			printf("%s: failed to get ranges for %s control\n",
1129 			    DEVNAME(sc), m->fname);
1130 			free(m, M_USBDEV, sizeof(struct uaudio_mixent));
1131 			return;
1132 		}
1133 		if (m->ranges.el == NULL) {
1134 			printf("%s: skipped %s control with empty range\n",
1135 			    DEVNAME(sc), m->fname);
1136 			free(m, M_USBDEV, sizeof(struct uaudio_mixent));
1137 			return;
1138 		}
1139 #ifdef UAUDIO_DEBUG
1140 		if (uaudio_debug)
1141 			uaudio_ranges_print(&m->ranges);
1142 #endif
1143 	}
1144 
1145 	/*
1146 	 * Add to unit's mixer controls list, sorting entries by name
1147 	 * and increasing channel number.
1148 	 */
1149 	for (pi = &u->mixent_list; (i = *pi) != NULL; pi = &i->next) {
1150 		cmp = strcmp(i->fname, m->fname);
1151 		if (cmp == 0)
1152 			cmp = i->chan - m->chan;
1153 		if (cmp == 0) {
1154 			DPRINTF("%02u: %s.%s: duplicate feature for chan %d\n",
1155 			    u->id, u->name, m->fname, m->chan);
1156 			free(m, M_USBDEV, sizeof(struct uaudio_mixent));
1157 			return;
1158 		}
1159 		if (cmp > 0)
1160 			break;
1161 	}
1162 	m->next = *pi;
1163 	*pi = m;
1164 
1165 	DPRINTF("\t%s[%d]\n", m->fname, m->chan);
1166 }
1167 
1168 /*
1169  * For the given unit, parse the list of its sources and recursively
1170  * call uaudio_process_unit() for each.
1171  */
1172 int
1173 uaudio_process_srcs(struct uaudio_softc *sc,
1174 	struct uaudio_unit *u, struct uaudio_blob units,
1175 	struct uaudio_blob *p)
1176 {
1177 	struct uaudio_unit *s, **ps;
1178 	unsigned int i, npin, sid;
1179 
1180 	if (!uaudio_getnum(p, 1, &npin))
1181 		return 0;
1182 	ps = &u->src_list;
1183 	for (i = 0; i < npin; i++) {
1184 		if (!uaudio_getnum(p, 1, &sid))
1185 			return 0;
1186 		if (!uaudio_process_unit(sc, u, sid, units, &s))
1187 			return 0;
1188 		s->src_next = NULL;
1189 		*ps = s;
1190 		ps = &s->src_next;
1191 	}
1192 	return 1;
1193 }
1194 
1195 /*
1196  * Parse the number of channels.
1197  */
1198 int
1199 uaudio_process_nch(struct uaudio_softc *sc,
1200 	struct uaudio_unit *u, struct uaudio_blob *p)
1201 {
1202 	if (!uaudio_getnum(p, 1, &u->nch))
1203 		return 0;
1204 	/* skip junk */
1205 	switch (sc->version) {
1206 	case UAUDIO_V1:
1207 		if (!uaudio_getnum(p, 2, NULL)) /* bmChannelConfig */
1208 			return 0;
1209 		break;
1210 	case UAUDIO_V2:
1211 		if (!uaudio_getnum(p, 4, NULL)) /* wChannelConfig */
1212 			return 0;
1213 		break;
1214 	}
1215 	if (!uaudio_getnum(p, 1, NULL)) /* iChannelNames */
1216 		return 0;
1217 	return 1;
1218 }
1219 
1220 /*
1221  * Find the AC class-specific descriptor for this unit id.
1222  */
1223 int
1224 uaudio_unit_getdesc(struct uaudio_softc *sc, int id,
1225 	struct uaudio_blob units,
1226 	struct uaudio_blob *p,
1227 	unsigned int *rtype)
1228 {
1229 	unsigned int i, type, subtype;
1230 
1231 	/*
1232 	 * Find the usb descriptor for this id.
1233 	 */
1234 	while (1) {
1235 		if (units.rptr == units.wptr) {
1236 			DPRINTF("%s: %02u: not found\n", __func__, id);
1237 			return 0;
1238 		}
1239 		if (!uaudio_getdesc(&units, p))
1240 			return 0;
1241 		if (!uaudio_getnum(p, 1, &type))
1242 			return 0;
1243 		if (!uaudio_getnum(p, 1, &subtype))
1244 			return 0;
1245 		if (!uaudio_getnum(p, 1, &i))
1246 			return 0;
1247 		if (i == id)
1248 			break;
1249 	}
1250 	*rtype = subtype;
1251 	return 1;
1252 }
1253 
1254 /*
1255  * Parse a unit, possibly calling uaudio_process_unit() for each of
1256  * its sources.
1257  */
1258 int
1259 uaudio_process_unit(struct uaudio_softc *sc,
1260 	struct uaudio_unit *dest, int id,
1261 	struct uaudio_blob units,
1262 	struct uaudio_unit **rchild)
1263 {
1264 	struct uaudio_blob p;
1265 	struct uaudio_unit *u, *s;
1266 	unsigned int i, j, size, ctl, type, subtype, assoc, clk;
1267 #ifdef UAUDIO_DEBUG
1268 	unsigned int bit;
1269 #endif
1270 
1271 	if (!uaudio_unit_getdesc(sc, id, units, &p, &subtype))
1272 		return 0;
1273 
1274 	/*
1275 	 * find this unit on the list as it may be already processed as
1276 	 * the source of another destination
1277 	 */
1278 	u = uaudio_unit_byid(sc, id);
1279 	if (u == NULL) {
1280 		u = malloc(sizeof(struct uaudio_unit), M_USBDEV, M_WAITOK);
1281 		u->id = id;
1282 		u->type = subtype;
1283 		u->term = 0;
1284 		u->src_list = NULL;
1285 		u->dst_list = NULL;
1286 		u->clock = NULL;
1287 		u->mixent_list = NULL;
1288 		u->nch = 0;
1289 		u->name[0] = 0;
1290 		uaudio_ranges_init(&u->rates);
1291 		u->unit_next = sc->unit_list;
1292 		sc->unit_list = u;
1293 	} else {
1294 		switch (u->type) {
1295 		case UAUDIO_AC_CLKSRC:
1296 		case UAUDIO_AC_CLKSEL:
1297 		case UAUDIO_AC_CLKMULT:
1298 		case UAUDIO_AC_RATECONV:
1299 			/* not using 'dest' list */
1300 			*rchild = u;
1301 			return 1;
1302 		}
1303 	}
1304 
1305 	if (dest) {
1306 		dest->dst_next = u->dst_list;
1307 		u->dst_list = dest;
1308 		if (dest->dst_next != NULL) {
1309 			/* already seen */
1310 			*rchild = u;
1311 			return 1;
1312 		}
1313 	}
1314 
1315 	switch (u->type) {
1316 	case UAUDIO_AC_INPUT:
1317 		if (!uaudio_getnum(&p, 2, &u->term))
1318 			return 0;
1319 		if (!uaudio_getnum(&p, 1, &assoc))
1320 			return 0;
1321 		if (u->term >> 8 != 1)
1322 			sc->nin++;
1323 		switch (sc->version) {
1324 		case UAUDIO_V1:
1325 			break;
1326 		case UAUDIO_V2:
1327 			if (!uaudio_getnum(&p, 1, &clk))
1328 				return 0;
1329 			if (!uaudio_process_unit(sc, NULL,
1330 				clk, units, &u->clock))
1331 				return 0;
1332 			break;
1333 		}
1334 		if (!uaudio_getnum(&p, 1, &u->nch))
1335 			return 0;
1336 		DPRINTF("%02u: "
1337 		    "in, nch = %d, term = 0x%x, assoc = %d\n",
1338 		    u->id, u->nch, u->term, assoc);
1339 		break;
1340 	case UAUDIO_AC_OUTPUT:
1341 		if (!uaudio_getnum(&p, 2, &u->term))
1342 			return 0;
1343 		if (!uaudio_getnum(&p, 1, &assoc))
1344 			return 0;
1345 		if (!uaudio_getnum(&p, 1, &id))
1346 			return 0;
1347 		if (!uaudio_process_unit(sc, u, id, units, &s))
1348 			return 0;
1349 		if (u->term >> 8 != 1)
1350 			sc->nout++;
1351 		switch (sc->version) {
1352 		case UAUDIO_V1:
1353 			break;
1354 		case UAUDIO_V2:
1355 			if (!uaudio_getnum(&p, 1, &clk))
1356 				return 0;
1357 			if (!uaudio_process_unit(sc, NULL,
1358 				clk, units, &u->clock))
1359 				return 0;
1360 			break;
1361 		}
1362 		u->src_list = s;
1363 		s->src_next = NULL;
1364 		u->nch = s->nch;
1365 		DPRINTF("%02u: "
1366 		    "out, id = %d, nch = %d, term = 0x%x, assoc = %d\n",
1367 		    u->id, id, u->nch, u->term, assoc);
1368 		break;
1369 	case UAUDIO_AC_MIXER:
1370 		if (!uaudio_process_srcs(sc, u, units, &p))
1371 			return 0;
1372 		if (!uaudio_process_nch(sc, u, &p))
1373 			return 0;
1374 		DPRINTF("%02u: mixer, nch = %u:\n", u->id, u->nch);
1375 
1376 #ifdef UAUDIO_DEBUG
1377 		/*
1378 		 * Print the list of available mixer's unit knobs (a bit
1379 		 * matrix). Matrix mixers are rare because levels are
1380 		 * already controlled by feature units, making the mixer
1381 		 * knobs redundant with the feature's knobs. So, for
1382 		 * now, we don't add clutter to the mixer(4) interface
1383 		 * and ignore all knobs. Other popular OSes doesn't
1384 		 * seem to expose them either.
1385 		 */
1386 		bit = 0;
1387 		for (s = u->src_list; s != NULL; s = s->src_next) {
1388 			for (i = 0; i < s->nch; i++) {
1389 				for (j = 0; j < u->nch; j++) {
1390 					if ((bit++ & 7) == 0) {
1391 						if (!uaudio_getnum(&p, 1, &ctl))
1392 							return 0;
1393 					}
1394 					if (ctl & 0x80)
1395 						DPRINTF("\t%02u[%d] -> [%d]\n",
1396 						    s->id, i, j);
1397 					ctl <<= 1;
1398 				}
1399 			}
1400 		}
1401 #endif
1402 		break;
1403 	case UAUDIO_AC_SELECTOR:
1404 		/*
1405 		 * Selectors are extremely rare, so not supported yet.
1406 		 */
1407 		if (!uaudio_process_srcs(sc, u, units, &p))
1408 			return 0;
1409 		if (u->src_list == NULL) {
1410 			printf("%s: selector %02u has no sources\n",
1411 			    DEVNAME(sc), u->id);
1412 			return 0;
1413 		}
1414 		u->nch = u->src_list->nch;
1415 		DPRINTF("%02u: selector, nch = %u\n", u->id, u->nch);
1416 		break;
1417 	case UAUDIO_AC_FEATURE:
1418 		if (!uaudio_getnum(&p, 1, &id))
1419 			return 0;
1420 		if (!uaudio_process_unit(sc, u, id, units, &s))
1421 			return 0;
1422 		s->src_next = u->src_list;
1423 		u->src_list = s;
1424 		u->nch = s->nch;
1425 		switch (sc->version) {
1426 		case UAUDIO_V1:
1427 			if (!uaudio_getnum(&p, 1, &size))
1428 				return 0;
1429 			break;
1430 		case UAUDIO_V2:
1431 			size = 4;
1432 			break;
1433 		}
1434 		DPRINTF("%02d: feature id = %d, nch = %d, size = %d\n",
1435 		    u->id, id, u->nch, size);
1436 
1437 		if (!uaudio_getnum(&p, size, &ctl))
1438 			return 0;
1439 		ctl = uaudio_feature_fixup(sc, ctl);
1440 		for (i = 0; i < 16; i++) {
1441 			if ((ctl & 3) == 3)
1442 				uaudio_feature_addent(sc, u, i, -1);
1443 			ctl >>= 2;
1444 		}
1445 
1446 		/*
1447 		 * certain devices provide no per-channel control descriptors
1448 		 */
1449 		if (p.wptr - p.rptr == 1)
1450 			break;
1451 
1452 		for (j = 0; j < u->nch; j++) {
1453 			if (!uaudio_getnum(&p, size, &ctl))
1454 				return 0;
1455 			ctl = uaudio_feature_fixup(sc, ctl);
1456 			for (i = 0; i < 16; i++) {
1457 				if ((ctl & 3) == 3)
1458 					uaudio_feature_addent(sc, u, i, j);
1459 				ctl >>= 2;
1460 			}
1461 		}
1462 		break;
1463 	case UAUDIO_AC_EFFECT:
1464 		if (!uaudio_getnum(&p, 2, &type))
1465 			return 0;
1466 		if (!uaudio_getnum(&p, 1, &id))
1467 			return 0;
1468 		if (!uaudio_process_unit(sc, u, id, units, &s))
1469 			return 0;
1470 		s->src_next = u->src_list;
1471 		u->src_list = s;
1472 		u->nch = s->nch;
1473 		DPRINTF("%02d: effect, type = %u, id = %d, nch = %d\n",
1474 		    u->id, type, id, u->nch);
1475 		break;
1476 	case UAUDIO_AC_PROCESSING:
1477 	case UAUDIO_AC_EXTENSION:
1478 		if (!uaudio_getnum(&p, 2, &type))
1479 			return 0;
1480 		if (!uaudio_process_srcs(sc, u, units, &p))
1481 			return 0;
1482 		if (!uaudio_process_nch(sc, u, &p))
1483 			return 0;
1484 		DPRINTF("%02u: proc/ext, type = 0x%x, nch = %u\n",
1485 		    u->id, type, u->nch);
1486 		for (s = u->src_list; s != NULL; s = s->src_next) {
1487 			DPRINTF("%u:\tpin %u:\n", u->id, s->id);
1488 		}
1489 		break;
1490 	case UAUDIO_AC_CLKSRC:
1491 		if (!uaudio_getnum(&p, 1, &u->term))
1492 			return 0;
1493 		if (!uaudio_getnum(&p, 1, &ctl))
1494 			return 0;
1495 		DPRINTF("%02u: clock source, attr = 0x%x, ctl = 0x%x\n",
1496 		    u->id, u->term, ctl);
1497 		break;
1498 	case UAUDIO_AC_CLKSEL:
1499 		DPRINTF("%02u: clock sel\n", u->id);
1500 		if (!uaudio_process_srcs(sc, u, units, &p))
1501 			return 0;
1502 		if (u->src_list == NULL) {
1503 			printf("%s: clock selector %02u with no srcs\n",
1504 			    DEVNAME(sc), u->id);
1505 			return 0;
1506 		}
1507 		break;
1508 	case UAUDIO_AC_CLKMULT:
1509 		DPRINTF("%02u: clock mult\n", u->id);
1510 
1511 		/* XXX: fetch multiplier */
1512 		printf("%s: clock multiplier not supported\n", DEVNAME(sc));
1513 		break;
1514 	case UAUDIO_AC_RATECONV:
1515 		DPRINTF("%02u: rate conv\n", u->id);
1516 
1517 		/* XXX: fetch multiplier */
1518 		printf("%s: rate converter not supported\n", DEVNAME(sc));
1519 		break;
1520 	}
1521 	if (rchild)
1522 		*rchild = u;
1523 	return 1;
1524 }
1525 
1526 /*
1527  * Try to set the unit name to the name of its destination terminal. If
1528  * the name is ambiguous (already given to another source unit or having
1529  * multiple destinations) then return 0.
1530  */
1531 int
1532 uaudio_setname_dsts(struct uaudio_softc *sc, struct uaudio_unit *u, char *name)
1533 {
1534 	struct uaudio_unit *d = u;
1535 
1536 	while (d != NULL) {
1537 		if (d->dst_list == NULL || d->dst_list->dst_next != NULL)
1538 			break;
1539 		d = d->dst_list;
1540 		if (d->src_list == NULL || d->src_list->src_next != NULL)
1541 			break;
1542 		if (d->name[0] != '\0') {
1543 			if (name != NULL && strcmp(name, d->name) != 0)
1544 				break;
1545 			strlcpy(u->name, d->name, UAUDIO_NAMEMAX);
1546 			return 1;
1547 		}
1548 	}
1549 	return 0;
1550 }
1551 
1552 /*
1553  * Try to set the unit name to the name of its source terminal. If the
1554  * name is ambiguous (already given to another destination unit or
1555  * having multiple sources) then return 0.
1556  */
1557 int
1558 uaudio_setname_srcs(struct uaudio_softc *sc, struct uaudio_unit *u, char *name)
1559 {
1560 	struct uaudio_unit *s = u;
1561 
1562 	while (s != NULL) {
1563 		if (s->src_list == NULL || s->src_list->src_next != NULL)
1564 			break;
1565 		s = s->src_list;
1566 		if (s->dst_list == NULL || s->dst_list->dst_next != NULL)
1567 			break;
1568 		if (s->name[0] != '\0') {
1569 			if (name != NULL && strcmp(name, s->name) != 0)
1570 				break;
1571 			strlcpy(u->name, s->name, UAUDIO_NAMEMAX);
1572 			return 1;
1573 		}
1574 	}
1575 	return 0;
1576 }
1577 
1578 /*
1579  * Set the name of the given unit by using both its source and
1580  * destination units. This is naming scheme is only useful to units
1581  * that would have ambiguous names if only sources or only destination
1582  * were used.
1583  */
1584 void
1585 uaudio_setname_middle(struct uaudio_softc *sc, struct uaudio_unit *u)
1586 {
1587 	struct uaudio_unit *s, *d;
1588 	char name[UAUDIO_NAMEMAX];
1589 
1590 	s = u->src_list;
1591 	while (1) {
1592 		if (s == NULL) {
1593 			DPRINTF("%s: %02u: has no srcs\n",
1594 			    __func__, u->id);
1595 			return;
1596 		}
1597 		if (s->name[0] != '\0')
1598 			break;
1599 		s = s->src_list;
1600 	}
1601 
1602 	d = u->dst_list;
1603 	while (1) {
1604 		if (d == NULL) {
1605 			DPRINTF("%s: %02u: has no dests\n",
1606 			    __func__, u->id);
1607 			return;
1608 		}
1609 		if (d->name[0] != '\0')
1610 			break;
1611 		d = d->dst_list;
1612 	}
1613 
1614 	snprintf(name, UAUDIO_NAMEMAX, "%s_%s", d->name, s->name);
1615 	uaudio_mkname(sc, name, u->name);
1616 }
1617 
1618 #ifdef UAUDIO_DEBUG
1619 /*
1620  * Return the synchronization type name, for debug purposes only.
1621  */
1622 char *
1623 uaudio_isoname(int isotype)
1624 {
1625 	switch (isotype) {
1626 	case UE_ISO_ASYNC:
1627 		return "async";
1628 	case UE_ISO_ADAPT:
1629 		return "adapt";
1630 	case UE_ISO_SYNC:
1631 		return "sync";
1632 	default:
1633 		return "unk";
1634 	}
1635 }
1636 
1637 /*
1638  * Return the name of the given mode, debug only
1639  */
1640 char *
1641 uaudio_modename(int mode)
1642 {
1643 	switch (mode) {
1644 	case 0:
1645 		return "none";
1646 	case AUMODE_PLAY:
1647 		return "play";
1648 	case AUMODE_RECORD:
1649 		return "rec";
1650 	case AUMODE_PLAY | AUMODE_RECORD:
1651 		return "duplex";
1652 	default:
1653 		return "unk";
1654 	}
1655 }
1656 
1657 /*
1658  * Return UAC v2.0 endpoint usage, debug only
1659  */
1660 char *
1661 uaudio_usagename(int usage)
1662 {
1663 	switch (usage) {
1664 	case UE_ISO_USAGE_DATA:
1665 		return "data";
1666 	case UE_ISO_USAGE_FEEDBACK:
1667 		return "feed";
1668 	case UE_ISO_USAGE_IMPL:
1669 		return "impl";
1670 	default:
1671 		return "unk";
1672 	}
1673 }
1674 
1675 /*
1676  * Print a bitmap of rates on the console.
1677  */
1678 void
1679 uaudio_rates_print(int rates)
1680 {
1681 	unsigned int i;
1682 
1683 	for (i = 0; i < nitems(uaudio_rates); i++) {
1684 		if (rates & (1 << i))
1685 			printf(" %d", uaudio_rates[i]);
1686 	}
1687 	printf("\n");
1688 }
1689 
1690 
1691 /*
1692  * Print uaudio_ranges to console.
1693  */
1694 void
1695 uaudio_ranges_print(struct uaudio_ranges *r)
1696 {
1697 	struct uaudio_ranges_el *e;
1698 	int more = 0;
1699 
1700 	for (e = r->el; e != NULL; e = e->next) {
1701 		if (more)
1702 			printf(", ");
1703 		if (e->min == e->max)
1704 			printf("%d", e->min);
1705 		else
1706 			printf("[%d:%d]/%d", e->min, e->max, e->res);
1707 		more = 1;
1708 	}
1709 	printf(" (%d vals)\n", r->nval);
1710 }
1711 
1712 /*
1713  * Print unit to the console.
1714  */
1715 void
1716 uaudio_print_unit(struct uaudio_softc *sc, struct uaudio_unit *u)
1717 {
1718 	struct uaudio_unit *s;
1719 
1720 	switch (u->type) {
1721 	case UAUDIO_AC_INPUT:
1722 		printf("%02u: input <%s>, dest = %02u <%s>\n",
1723 		    u->id, u->name, u->dst_list->id, u->dst_list->name);
1724 		break;
1725 	case UAUDIO_AC_OUTPUT:
1726 		printf("%02u: output <%s>, source = %02u <%s>\n",
1727 		    u->id, u->name, u->src_list->id, u->src_list->name);
1728 		break;
1729 	case UAUDIO_AC_MIXER:
1730 		printf("%02u: mixer <%s>:\n", u->id, u->name);
1731 		for (s = u->src_list; s != NULL; s = s->src_next)
1732 			printf("%02u:\tsource %u <%s>:\n",
1733 			    u->id, s->id, s->name);
1734 		break;
1735 	case UAUDIO_AC_SELECTOR:
1736 		printf("%02u: selector <%s>:\n", u->id, u->name);
1737 		for (s = u->src_list; s != NULL; s = s->src_next)
1738 			printf("%02u:\tsource %u <%s>:\n",
1739 			    u->id, s->id, s->name);
1740 		break;
1741 	case UAUDIO_AC_FEATURE:
1742 		printf("%02u: feature <%s>, "
1743 		    "src = %02u <%s>, dst = %02u <%s>, cls = %d\n",
1744 		    u->id, u->name,
1745 		    u->src_list->id, u->src_list->name,
1746 		    u->dst_list->id, u->dst_list->name, u->mixer_class);
1747 		break;
1748 	case UAUDIO_AC_EFFECT:
1749 		printf("%02u: effect <%s>, "
1750 		    "src = %02u <%s>, dst = %02u <%s>\n",
1751 		    u->id, u->name,
1752 		    u->src_list->id, u->src_list->name,
1753 		    u->dst_list->id, u->dst_list->name);
1754 		break;
1755 	case UAUDIO_AC_PROCESSING:
1756 	case UAUDIO_AC_EXTENSION:
1757 		printf("%02u: proc/ext <%s>:\n", u->id, u->name);
1758 		for (s = u->src_list; s != NULL; s = s->src_next)
1759 			printf("%02u:\tsource %u <%s>:\n",
1760 			    u->id, s->id, s->name);
1761 		break;
1762 	case UAUDIO_AC_CLKSRC:
1763 		printf("%02u: clock source <%s>\n", u->id, u->name);
1764 		break;
1765 	case UAUDIO_AC_CLKSEL:
1766 		printf("%02u: clock sel <%s>\n", u->id, u->name);
1767 		break;
1768 	case UAUDIO_AC_CLKMULT:
1769 		printf("%02u: clock mult\n", u->id);
1770 		break;
1771 	case UAUDIO_AC_RATECONV:
1772 		printf("%02u: rate conv\n", u->id);
1773 		break;
1774 	}
1775 }
1776 
1777 /*
1778  * Print the full mixer on the console.
1779  */
1780 void
1781 uaudio_mixer_print(struct uaudio_softc *sc)
1782 {
1783 	struct uaudio_mixent *m;
1784 	struct uaudio_unit *u;
1785 
1786 	for (u = sc->unit_list; u != NULL; u = u->unit_next) {
1787 		for (m = u->mixent_list; m != NULL; m = m->next) {
1788 			printf("%02u:\t%s.%s",
1789 			    u->id, u->name, m->fname);
1790 			if (m->chan >= 0)
1791 				printf("[%u]", m->chan);
1792 			printf("\n");
1793 		}
1794 	}
1795 }
1796 
1797 /*
1798  * Print the full device configuration on the console.
1799  */
1800 void
1801 uaudio_conf_print(struct uaudio_softc *sc)
1802 {
1803 	struct uaudio_alt *a;
1804 	struct uaudio_params *p;
1805 	struct mixer_devinfo mi;
1806 	struct mixer_ctrl ctl;
1807 	int i, rates;
1808 
1809 	mi.index = 0;
1810 	while (1) {
1811 		if (uaudio_query_devinfo(sc, &mi) != 0)
1812 			break;
1813 
1814 		if (mi.type != AUDIO_MIXER_CLASS) {
1815 			ctl.dev = mi.index;
1816 			if (uaudio_get_port(sc, &ctl) != 0) {
1817 				printf("%02u: failed to get port\n", mi.index);
1818 				memset(&ctl.un, 0, sizeof(ctl.un));
1819 			}
1820 		}
1821 
1822 		printf("%02u: <%s>, next = %d, prev = %d, class = %d",
1823 		    mi.index, mi.label.name, mi.next, mi.prev, mi.mixer_class);
1824 
1825 		switch (mi.type) {
1826 		case AUDIO_MIXER_CLASS:
1827 			break;
1828 		case AUDIO_MIXER_VALUE:
1829 			printf(", nch = %d, delta = %d",
1830 			    mi.un.v.num_channels, mi.un.v.delta);
1831 			printf(", val =");
1832 			for (i = 0; i < mi.un.v.num_channels; i++)
1833 				printf(" %d", ctl.un.value.level[i]);
1834 			break;
1835 		case AUDIO_MIXER_ENUM:
1836 			printf(", members:");
1837 			for (i = 0; i != mi.un.e.num_mem; i++) {
1838 				printf(" %s(=%d)",
1839 				    mi.un.e.member[i].label.name,
1840 				    mi.un.e.member[i].ord);
1841 			}
1842 			printf(", val = %d", ctl.un.ord);
1843 			break;
1844 		}
1845 
1846 		printf("\n");
1847 		mi.index++;
1848 	}
1849 
1850 	printf("%d controls\n", mi.index);
1851 
1852 	printf("alts:\n");
1853 	for (a = sc->alts; a != NULL; a = a->next) {
1854 		rates = uaudio_alt_getrates(sc, a);
1855 		printf("mode = %s, ifnum = %d, altnum = %d, "
1856 		    "addr = 0x%x, maxpkt = %d, sync = 0x%x, "
1857 		    "nch = %d, fmt = s%dle%d, rates:",
1858 		    uaudio_modename(a->mode),
1859 		    a->ifnum, a->altnum,
1860 		    a->data_addr, a->maxpkt,
1861 		    a->sync_addr,
1862 		    a->nch, a->bits, a->bps);
1863 		uaudio_rates_print(rates);
1864 	}
1865 
1866 	printf("parameters:\n");
1867 	for (p = sc->params_list; p != NULL; p = p->next) {
1868 		switch (sc->version) {
1869 		case UAUDIO_V1:
1870 			rates = p->v1_rates;
1871 			break;
1872 		case UAUDIO_V2:
1873 			rates = uaudio_getrates(sc, p);
1874 			break;
1875 		}
1876 		printf("pchan = %d, s%dle%d, rchan = %d, s%dle%d, rates:",
1877 		    p->palt ? p->palt->nch : 0,
1878 		    p->palt ? p->palt->bits : 0,
1879 		    p->palt ? p->palt->bps : 0,
1880 		    p->ralt ? p->ralt->nch : 0,
1881 		    p->ralt ? p->ralt->bits : 0,
1882 		    p->ralt ? p->ralt->bps : 0);
1883 		uaudio_rates_print(rates);
1884 	}
1885 }
1886 #endif
1887 
1888 /*
1889  * Return the number of mixer controls that have the same name but
1890  * control different channels of the same stream.
1891  */
1892 int
1893 uaudio_mixer_nchan(struct uaudio_mixent *m, struct uaudio_mixent **rnext)
1894 {
1895 	char *name;
1896 	int i;
1897 
1898 	i = 0;
1899 	name = m->fname;
1900 	while (m != NULL && strcmp(name, m->fname) == 0) {
1901 		m = m->next;
1902 		i++;
1903 	}
1904 	if (rnext)
1905 		*rnext = m;
1906 	return i;
1907 }
1908 
1909 /*
1910  * Skip redundant mixer entries that we don't want to expose to userland.
1911  * For instance if there is a mute-all-channels control and per-channel
1912  * mute controls, we don't want both (we expose the per-channel mute)
1913  */
1914 void
1915 uaudio_mixer_skip(struct uaudio_mixent **pm)
1916 {
1917 	struct uaudio_mixent *m = *pm;
1918 
1919 	if (m != NULL &&
1920 	    m->chan == -1 &&
1921 	    m->next != NULL &&
1922 	    strcmp(m->fname, m->next->fname) == 0)
1923 		m = m->next;
1924 
1925 	*pm = m;
1926 }
1927 
1928 /*
1929  * Return pointer to the unit and mixer entry which have the given
1930  * index exposed by the mixer(4) API.
1931  */
1932 int
1933 uaudio_mixer_byindex(struct uaudio_softc *sc, int index,
1934     struct uaudio_unit **ru, struct uaudio_mixent **rm)
1935 {
1936 	struct uaudio_unit *u;
1937 	struct uaudio_mixent *m;
1938 	char *name;
1939 	int i;
1940 
1941 	i = UAUDIO_CLASS_COUNT;
1942 	for (u = sc->unit_list; u != NULL; u = u->unit_next) {
1943 		m = u->mixent_list;
1944 		while (1) {
1945 			uaudio_mixer_skip(&m);
1946 			if (m == NULL)
1947 				break;
1948 			if (index == i) {
1949 				*ru = u;
1950 				*rm = m;
1951 				return 1;
1952 			}
1953 			if (m->type == UAUDIO_MIX_NUM) {
1954 				name = m->fname;
1955 				while (m != NULL &&
1956 				    strcmp(name, m->fname) == 0)
1957 					m = m->next;
1958 			} else
1959 				m = m->next;
1960 			i++;
1961 		}
1962 	}
1963 	return 0;
1964 }
1965 
1966 /*
1967  * Parse AC header descriptor, we use it only to determine UAC
1968  * version. Other properties (like wTotalLength) can be determined
1969  * using other descriptors, so we try to no rely on them to avoid
1970  * inconsistencies and the need for certain quirks.
1971  */
1972 int
1973 uaudio_process_header(struct uaudio_softc *sc, struct uaudio_blob *p)
1974 {
1975 	struct uaudio_blob ph;
1976 	unsigned int type, subtype;
1977 
1978 	if (!uaudio_getdesc(p, &ph))
1979 		return 0;
1980 	if (!uaudio_getnum(&ph, 1, &type))
1981 		return 0;
1982 	if (type != UDESC_CS_INTERFACE) {
1983 		DPRINTF("%s: expected cs iface desc\n", __func__);
1984 		return 0;
1985 	}
1986 	if (!uaudio_getnum(&ph, 1, &subtype))
1987 		return 0;
1988 	if (subtype != UAUDIO_AC_HEADER) {
1989 		DPRINTF("%s: expected header desc\n", __func__);
1990 		return 0;
1991 	}
1992 	if (!uaudio_getnum(&ph, 2, &sc->version))
1993 		return 0;
1994 
1995 	DPRINTF("%s: version 0x%x\n", __func__, sc->version);
1996 	return 1;
1997 }
1998 
1999 /*
2000  * Process AC interrupt endpoint descriptor, this is mainly to skip
2001  * the descriptor as we use neither of its properties. Our mixer
2002  * interface doesn't support unsolicitated state changes, so we've no
2003  * use of it yet.
2004  */
2005 int
2006 uaudio_process_ac_ep(struct uaudio_softc *sc, struct uaudio_blob *p)
2007 {
2008 #ifdef UAUDIO_DEBUG
2009 	static const char *xfer[] = {
2010 		"ctl", "iso", "bulk", "intr"
2011 	};
2012 #endif
2013 	struct uaudio_blob dp;
2014 	unsigned int type, addr, attr, maxpkt, ival;
2015 	unsigned char *savepos;
2016 
2017 	/*
2018 	 * parse optional interrupt endpoint descriptor
2019 	 */
2020 	if (p->rptr == p->wptr)
2021 		return 1;
2022 	savepos = p->rptr;
2023 	if (!uaudio_getdesc(p, &dp))
2024 		return 0;
2025 	if (!uaudio_getnum(&dp, 1, &type))
2026 		return 0;
2027 	if (type != UDESC_ENDPOINT) {
2028 		p->rptr = savepos;
2029 		return 1;
2030 	}
2031 
2032 	if (!uaudio_getnum(&dp, 1, &addr))
2033 		return 0;
2034 	if (!uaudio_getnum(&dp, 1, &attr))
2035 		return 0;
2036 	if (!uaudio_getnum(&dp, 2, &maxpkt))
2037 		return 0;
2038 	if (!uaudio_getnum(&dp, 1, &ival))
2039 		return 0;
2040 
2041 	DPRINTF("%s: addr = 0x%x, type = %s, maxpkt = %d, ival = %d\n",
2042 	    __func__, addr, xfer[UE_GET_XFERTYPE(attr)],
2043 	    UE_GET_SIZE(maxpkt), ival);
2044 
2045 	return 1;
2046 }
2047 
2048 /*
2049  * Process the AC interface descriptors: mainly build the mixer and,
2050  * for UAC v2.0, find the clock source.
2051  *
2052  * The audio device exposes an audio control (AC) interface with a big
2053  * set of USB descriptors which expose the complete circuit the
2054  * device. The circuit describes how the signal flows between the USB
2055  * streaming interfaces to the terminal connectors (jacks, speakers,
2056  * mics, ...). The circuit is build of mixers, source selectors, gain
2057  * controls, mutters, processors, and alike; each comes with its own
2058  * set of controls. Most of the boring driver work is to parse the
2059  * circuit and build a human-usable set of controls that could be
2060  * exposed through the mixer(4) interface.
2061  */
2062 int
2063 uaudio_process_ac(struct uaudio_softc *sc, struct uaudio_blob *p, int ifnum)
2064 {
2065 	struct uaudio_blob units, pu;
2066 	struct uaudio_unit *u, *v;
2067 	unsigned char *savepos;
2068 	unsigned int type, subtype, id;
2069 	char *name, val;
2070 
2071 	DPRINTF("%s: ifnum = %d, %zd bytes to process\n", __func__,
2072 	    ifnum, p->wptr - p->rptr);
2073 
2074 	sc->ctl_ifnum = ifnum;
2075 
2076 	/* The first AC class-specific descriptor is the AC header */
2077 	if (!uaudio_process_header(sc, p))
2078 		return 0;
2079 
2080 	/*
2081 	 * Determine the size of the AC descriptors array: scan
2082 	 * descriptors until we get the first non-class-specific
2083 	 * descriptor. This avoids relying on the wTotalLength field.
2084 	 */
2085 	savepos = p->rptr;
2086 	units.rptr = units.wptr = p->rptr;
2087 	while (p->rptr != p->wptr) {
2088 		if (!uaudio_getdesc(p, &pu))
2089 			return 0;
2090 		if (!uaudio_getnum(&pu, 1, &type))
2091 			return 0;
2092 		if (type != UDESC_CS_INTERFACE)
2093 			break;
2094 		units.wptr = p->rptr;
2095 	}
2096 	p->rptr = savepos;
2097 
2098 	/*
2099 	 * Load units, walking from outputs to inputs, as
2100 	 * the usb audio class spec requires.
2101 	 */
2102 	while (p->rptr != units.wptr) {
2103 		if (!uaudio_getdesc(p, &pu))
2104 			return 0;
2105 		if (!uaudio_getnum(&pu, 1, &type))
2106 			return 0;
2107 		if (!uaudio_getnum(&pu, 1, &subtype))
2108 			return 0;
2109 		if (subtype == UAUDIO_AC_OUTPUT) {
2110 			if (!uaudio_getnum(&pu, 1, &id))
2111 				return 0;
2112 			if (!uaudio_process_unit(sc, NULL, id, units, NULL))
2113 				return 0;
2114 		}
2115 	}
2116 
2117 	/*
2118 	 * set terminal, effect, and processor unit names
2119 	 */
2120 	for (u = sc->unit_list; u != NULL; u = u->unit_next) {
2121 		switch (u->type) {
2122 		case UAUDIO_AC_INPUT:
2123 			uaudio_mkname(sc, uaudio_tname(sc, u->term, 0), u->name);
2124 			break;
2125 		case UAUDIO_AC_OUTPUT:
2126 			uaudio_mkname(sc, uaudio_tname(sc, u->term, 1), u->name);
2127 			break;
2128 		case UAUDIO_AC_CLKSRC:
2129 			uaudio_mkname(sc, uaudio_clkname(u->term), u->name);
2130 			break;
2131 		case UAUDIO_AC_CLKSEL:
2132 			uaudio_mkname(sc, "clksel", u->name);
2133 			break;
2134 		case UAUDIO_AC_EFFECT:
2135 			uaudio_mkname(sc, "fx", u->name);
2136 			break;
2137 		case UAUDIO_AC_PROCESSING:
2138 			uaudio_mkname(sc, "proc", u->name);
2139 			break;
2140 		case UAUDIO_AC_EXTENSION:
2141 			uaudio_mkname(sc, "ext", u->name);
2142 			break;
2143 		}
2144 	}
2145 
2146 	/*
2147 	 * set mixer/selector unit names
2148 	 */
2149 	for (u = sc->unit_list; u != NULL; u = u->unit_next) {
2150 		if (u->type != UAUDIO_AC_MIXER &&
2151 		    u->type != UAUDIO_AC_SELECTOR)
2152 			continue;
2153 		if (!uaudio_setname_dsts(sc, u, NULL)) {
2154 			switch (u->type) {
2155 			case UAUDIO_AC_MIXER:
2156 				name = "mix";
2157 				break;
2158 			case UAUDIO_AC_SELECTOR:
2159 				name = "sel";
2160 				break;
2161 			}
2162 			uaudio_mkname(sc, name, u->name);
2163 		}
2164 	}
2165 
2166 	/*
2167 	 * set feature unit names and classes
2168 	 */
2169 	for (u = sc->unit_list; u != NULL; u = u->unit_next) {
2170 		if (u->type != UAUDIO_AC_FEATURE)
2171 			continue;
2172 		if (uaudio_setname_dsts(sc, u, UAUDIO_NAME_REC)) {
2173 			u->mixer_class = UAUDIO_CLASS_IN;
2174 			continue;
2175 		}
2176 		if (uaudio_setname_srcs(sc, u, UAUDIO_NAME_PLAY)) {
2177 			u->mixer_class = UAUDIO_CLASS_OUT;
2178 			continue;
2179 		}
2180 		if (uaudio_setname_dsts(sc, u, NULL)) {
2181 			u->mixer_class = UAUDIO_CLASS_OUT;
2182 			continue;
2183 		}
2184 		if (uaudio_setname_srcs(sc, u, NULL)) {
2185 			u->mixer_class = UAUDIO_CLASS_IN;
2186 			continue;
2187 		}
2188 		uaudio_setname_middle(sc, u);
2189 		u->mixer_class = UAUDIO_CLASS_IN;
2190 	}
2191 
2192 #ifdef UAUDIO_DEBUG
2193 	if (uaudio_debug) {
2194 		printf("%s: units list:\n", DEVNAME(sc));
2195 		for (u = sc->unit_list; u != NULL; u = u->unit_next)
2196 			uaudio_print_unit(sc, u);
2197 
2198 		printf("%s: mixer controls:\n", DEVNAME(sc));
2199 		uaudio_mixer_print(sc);
2200 	}
2201 #endif
2202 
2203 	/* follows optional interrupt endpoint descriptor */
2204 	if (!uaudio_process_ac_ep(sc, p))
2205 		return 0;
2206 
2207 	/* fetch clock source rates */
2208 	for (u = sc->unit_list; u != NULL; u = u->unit_next) {
2209 		switch (u->type) {
2210 		case UAUDIO_AC_CLKSRC:
2211 			if (!uaudio_req_ranges(sc, 4,
2212 				UAUDIO_V2_REQSEL_CLKFREQ,
2213 				0, /* channel (not used) */
2214 				sc->ctl_ifnum,
2215 				u->id,
2216 				&u->rates)) {
2217 				printf("%s: failed to read clock rates\n",
2218 				    DEVNAME(sc));
2219 				return 1;
2220 			}
2221 #ifdef UAUDIO_DEBUG
2222 			if (uaudio_debug) {
2223 				printf("%02u: clock rates: ", u->id);
2224 				uaudio_ranges_print(&u->rates);
2225 			}
2226 #endif
2227 			break;
2228 		case UAUDIO_AC_CLKSEL:
2229 			if (!uaudio_req(sc, UT_READ_CLASS_INTERFACE,
2230 				UAUDIO_V2_REQ_CUR,
2231 				UAUDIO_V2_REQSEL_CLKSEL, 0,
2232 				sc->ctl_ifnum, u->id,
2233 				&val, 1)) {
2234 				printf("%s: failed to read clock selector\n",
2235 				    DEVNAME(sc));
2236 				return 0;
2237 			}
2238 			for (v = u->src_list; v != NULL; v = v->src_next) {
2239 				if (--val == 0)
2240 					break;
2241 			}
2242 			u->clock = v;
2243 			break;
2244 		}
2245 	}
2246 
2247 	if (sc->version == UAUDIO_V2) {
2248 		/*
2249 		 * Find common clock unit. We assume all terminals
2250 		 * belong to the same clock domain (ie are connected
2251 		 * to the same source)
2252 		 */
2253 		sc->clock = NULL;
2254 		for (u = sc->unit_list; u != NULL; u = u->unit_next) {
2255 			if (u->type != UAUDIO_AC_INPUT &&
2256 			    u->type != UAUDIO_AC_OUTPUT)
2257 				continue;
2258 			if (sc->clock == NULL) {
2259 				if (u->clock == NULL) {
2260 					printf("%s: terminal with no clock\n",
2261 					    DEVNAME(sc));
2262 					return 0;
2263 				}
2264 				sc->clock = u->clock;
2265 			} else if (u->clock != sc->clock) {
2266 				printf("%s: only one clock domain supported\n",
2267 				    DEVNAME(sc));
2268 				return 0;
2269 			}
2270 		}
2271 
2272 		if (sc->clock == NULL) {
2273 			printf("%s: no clock found\n", DEVNAME(sc));
2274 			return 0;
2275 		}
2276 	}
2277 	return 1;
2278 }
2279 
2280 /*
2281  * Parse endpoint descriptor with the following format:
2282  *
2283  * For playback there's a output data endpoint, of the
2284  * following types:
2285  *
2286  *  type	sync	descr
2287  *  -------------------------------------------------------
2288  *  async:	Yes	the device uses its own clock but
2289  *			sends feedback on a (input) sync endpoint
2290  *			for the host to adjust next packet size
2291  *
2292  *  sync:	-	data rate is constant, and device
2293  *			is clocked to the usb bus.
2294  *
2295  *  adapt:	-	the device adapts to data rate of the
2296  *			host. If fixed packet size is used,
2297  *			data rate is equivalent to the usb clock
2298  *			so this mode is the same as the
2299  *			sync mode.
2300  *
2301  * For recording there's and input data endpoint, of
2302  * the following types:
2303  *
2304  *  type	sync	descr
2305  *  -------------------------------------------------------
2306  *  async:	-	the device uses its own clock and
2307  *			adjusts packet sizes.
2308  *
2309  *  sync:	-	the device uses usb clock rate
2310  *
2311  *  adapt:	Yes	the device uses host's feedback (on
2312  *			on a dedicated (output) sync endpoint
2313  *			to adapt to software's desired rate
2314  *
2315  *
2316  * For usb1.1 ival is cardcoded to 1 for isochronous
2317  * transfers, which means one transfer every ms. I.e one
2318  * transfer every frame period.
2319  *
2320  * For usb2, ival the poll interval is:
2321  *
2322  *	frame_period * 2^(ival - 1)
2323  *
2324  * so, if we use this formula, we get something working in all
2325  * cases.
2326  *
2327  * The MaxPacketsOnly attribute is used only by "Type II" encodings,
2328  * so we don't care about it.
2329  */
2330 int
2331 uaudio_process_as_ep(struct uaudio_softc *sc,
2332 	struct uaudio_blob *p, struct uaudio_alt *a, int nep)
2333 {
2334 	unsigned int addr, attr, maxpkt, isotype, ival;
2335 
2336 	if (!uaudio_getnum(p, 1, &addr))
2337 		return 0;
2338 	if (!uaudio_getnum(p, 1, &attr))
2339 		return 0;
2340 	if (!uaudio_getnum(p, 2, &maxpkt))
2341 		return 0;
2342 	if (!uaudio_getnum(p, 1, &ival)) /* bInterval */
2343 		return 0;
2344 
2345 	DPRINTF("%s: addr = 0x%x, %s/%s, "
2346 	    "maxpktsz = %d, ival = %d\n",
2347 	    __func__, addr,
2348 	    uaudio_isoname(UE_GET_ISO_TYPE(attr)),
2349 	    uaudio_usagename(UE_GET_ISO_USAGE(attr)),
2350 	    maxpkt, ival);
2351 
2352 	if (UE_GET_XFERTYPE(attr) != UE_ISOCHRONOUS) {
2353 		printf("%s: skipped non-isoc endpt.\n", DEVNAME(sc));
2354 		return 1;
2355 	}
2356 
2357 	/*
2358 	 * For each AS interface setting, there's a single data
2359 	 * endpoint and an optional feedback endpoint. The
2360 	 * synchronization type is non-zero and must be set in the data
2361 	 * endpoints.
2362 	 *
2363 	 * However, the isoc sync type field of the attribute can't be
2364 	 * trusted: a lot of devices have it wrong. If the isoc sync
2365 	 * type is set it's necessarily a data endpoint, if it's not,
2366 	 * then if it is the only endpoint, it necessarily the data
2367 	 * endpoint.
2368 	 */
2369 	isotype = UE_GET_ISO_TYPE(attr);
2370 	if (isotype || nep == 1) {
2371 		/* this is the data endpoint */
2372 
2373 		if (a->data_addr && addr != a->data_addr) {
2374 			printf("%s: skipped extra data endpt.\n", DEVNAME(sc));
2375 			return 1;
2376 		}
2377 
2378 		a->mode = (UE_GET_DIR(addr) == UE_DIR_IN) ?
2379 		    AUMODE_RECORD : AUMODE_PLAY;
2380 		a->data_addr = addr;
2381 		a->fps = sc->ufps / (1 << (ival - 1));
2382 		a->maxpkt = UE_GET_SIZE(maxpkt);
2383 	} else {
2384 		/* this is the sync endpoint */
2385 
2386 		if (a->sync_addr && addr != a->sync_addr) {
2387 			printf("%s: skipped extra sync endpt.\n", DEVNAME(sc));
2388 			return 1;
2389 		}
2390 		a->sync_addr = addr;
2391 	}
2392 
2393 	return 1;
2394 }
2395 
2396 /*
2397  * Parse AS general descriptor. Non-PCM interfaces are skipped. UAC
2398  * v2.0 report the number of channels. For UAC v1.0 we set the number
2399  * of channels to zero, it will be determined later from the format
2400  * descriptor.
2401  */
2402 int
2403 uaudio_process_as_general(struct uaudio_softc *sc,
2404 	struct uaudio_blob *p, int *rispcm, struct uaudio_alt *a)
2405 {
2406 	unsigned int term, fmt, ctl, fmt_type, fmt_map, nch;
2407 
2408 	if (!uaudio_getnum(p, 1, &term))
2409 		return 0;
2410 	switch (sc->version) {
2411 	case UAUDIO_V1:
2412 		if (!uaudio_getnum(p, 1, NULL))	/* bDelay */
2413 			return 0;
2414 		if (!uaudio_getnum(p, 1, &fmt))
2415 			return 0;
2416 		*rispcm = (fmt == UAUDIO_V1_FMT_PCM);
2417 		break;
2418 	case UAUDIO_V2:
2419 		/* XXX: should we check if alt setting control is valid ? */
2420 		if (!uaudio_getnum(p, 1, &ctl))
2421 			return 0;
2422 		if (!uaudio_getnum(p, 1, &fmt_type))
2423 			return 0;
2424 		if (!uaudio_getnum(p, 4, &fmt_map))
2425 			return 0;
2426 		if (!uaudio_getnum(p, 1, &nch))
2427 			return 0;
2428 		a->nch = nch;
2429 		*rispcm = (fmt_type == 1) && (fmt_map & UAUDIO_V2_FMT_PCM);
2430 	}
2431 	return 1;
2432 }
2433 
2434 /*
2435  * Parse AS format descriptor: we support only "Type 1" formats, aka
2436  * PCM. Other formats are not really audio, they are data-only
2437  * interfaces that we don't want to support: ethernet is much better
2438  * for raw data transfers.
2439  *
2440  * XXX: handle ieee 754 32-bit floating point formats.
2441  */
2442 int
2443 uaudio_process_as_format(struct uaudio_softc *sc,
2444 	struct uaudio_blob *p, struct uaudio_alt *a, int *ispcm)
2445 {
2446 	unsigned int type, bps, bits, nch, nrates, rate_min, rate_max, rates;
2447 	int i, j;
2448 
2449 	switch (sc->version) {
2450 	case UAUDIO_V1:
2451 		if (!uaudio_getnum(p, 1, &type))
2452 			return 0;
2453 		if (type != 1) {
2454 			DPRINTF("%s: class v1: "
2455 			    "skipped unsupported type = %d\n", __func__, type);
2456 			*ispcm = 0;
2457 			return 1;
2458 		}
2459 		if (!uaudio_getnum(p, 1, &nch))
2460 			return 0;
2461 		if (!uaudio_getnum(p, 1, &bps))
2462 			return 0;
2463 		if (!uaudio_getnum(p, 1, &bits))
2464 			return 0;
2465 		if (!uaudio_getnum(p, 1, &nrates))
2466 			return 0;
2467 		rates = 0;
2468 		if (nrates == 0) {
2469 			if (!uaudio_getnum(p, 3, &rate_min))
2470 				return 0;
2471 			if (!uaudio_getnum(p, 3, &rate_max))
2472 				return 0;
2473 			for (i = 0; i < nitems(uaudio_rates); i++) {
2474 				if (uaudio_rates[i] >= rate_min &&
2475 				    uaudio_rates[i] <= rate_max)
2476 					rates |= 1 << i;
2477 			}
2478 		} else {
2479 			for (j = 0; j < nrates; j++) {
2480 				if (!uaudio_getnum(p, 3, &rate_min))
2481 					return 0;
2482 				for (i = 0; i < nitems(uaudio_rates); i++) {
2483 					if (uaudio_rates[i] == rate_min)
2484 						rates |= 1 << i;
2485 				}
2486 			}
2487 		}
2488 		a->v1_rates = rates;
2489 		a->nch = nch;
2490 		break;
2491 	case UAUDIO_V2:
2492 		/*
2493 		 * sample rate ranges are obtained with requests to
2494 		 * the clock source, as defined by the clock source
2495 		 * descriptor
2496 		 *
2497 		 * the number of channels is in the GENERAL descriptor
2498 		 */
2499 		if (!uaudio_getnum(p, 1, &type))
2500 			return 0;
2501 		if (type != 1) {
2502 			DPRINTF("%s: class v2: "
2503 			    "skipped unsupported type = %d\n", __func__, type);
2504 			*ispcm = 0;
2505 			return 1;
2506 		}
2507 		if (!uaudio_getnum(p, 1, &bps))
2508 			return 0;
2509 		if (!uaudio_getnum(p, 1, &bits))
2510 			return 0;
2511 
2512 		/*
2513 		 * nch is in the v2 general desc, rates come from the
2514 		 * clock source, so we're done.
2515 		 */
2516 		break;
2517 	}
2518 	a->bps = bps;
2519 	a->bits = bits;
2520 	*ispcm = 1;
2521 	return 1;
2522 }
2523 
2524 /*
2525  * Parse AS descriptors.
2526  *
2527  * The audio streaming (AS) interfaces are used to move data between
2528  * the host and the device. On the one hand, the device has
2529  * analog-to-digital (ADC) and digital-to-analog (DAC) converters
2530  * which have their own low-jitter clock source. On other hand, the
2531  * USB host runs a bus clock using another clock source. So both
2532  * drift. That's why, the device sends feedback to the driver for the
2533  * host to adjust continuously its data rate, hence the need for sync
2534  * endpoints.
2535  */
2536 int
2537 uaudio_process_as(struct uaudio_softc *sc,
2538     struct uaudio_blob *p, int ifnum, int altnum, int nep)
2539 {
2540 	struct uaudio_alt *a, *anext, **pa;
2541 	struct uaudio_blob dp;
2542 	unsigned char *savep;
2543 	unsigned int type, subtype;
2544 	int ispcm = 0;
2545 
2546 	a = malloc(sizeof(struct uaudio_alt), M_USBDEV, M_WAITOK);
2547 	a->mode = 0;
2548 	a->nch = 0;
2549 	a->v1_rates = 0;
2550 	a->data_addr = 0;
2551 	a->sync_addr = 0;
2552 	a->ifnum = ifnum;
2553 	a->altnum = altnum;
2554 
2555 	while (p->rptr != p->wptr) {
2556 		savep = p->rptr;
2557 		if (!uaudio_getdesc(p, &dp))
2558 			goto failed;
2559 		if (!uaudio_getnum(&dp, 1, &type))
2560 			goto failed;
2561 		if (type != UDESC_CS_INTERFACE) {
2562 			p->rptr = savep;
2563 			break;
2564 		}
2565 		if (!uaudio_getnum(&dp, 1, &subtype))
2566 			goto failed;
2567 		switch (subtype) {
2568 		case UAUDIO_AS_GENERAL:
2569 			if (!uaudio_process_as_general(sc, &dp, &ispcm, a))
2570 				goto failed;
2571 			break;
2572 		case UAUDIO_AS_FORMAT:
2573 			if (!uaudio_process_as_format(sc, &dp, a, &ispcm))
2574 				goto failed;
2575 			break;
2576 		default:
2577 			DPRINTF("%s: unknown desc\n", __func__);
2578 			continue;
2579 		}
2580 		if (!ispcm) {
2581 			DPRINTF("%s: non-pcm iface\n", __func__);
2582 			free(a, M_USBDEV, sizeof(struct uaudio_alt));
2583 			return 1;
2584 		}
2585 	}
2586 
2587 
2588 	while (p->rptr != p->wptr) {
2589 		savep = p->rptr;
2590 		if (!uaudio_getdesc(p, &dp))
2591 			goto failed;
2592 		if (!uaudio_getnum(&dp, 1, &type))
2593 			goto failed;
2594 		if (type == UDESC_CS_ENDPOINT)
2595 			continue;
2596 		if (type != UDESC_ENDPOINT) {
2597 			p->rptr = savep;
2598 			break;
2599 		}
2600 		if (!uaudio_process_as_ep(sc, &dp, a, nep))
2601 			goto failed;
2602 	}
2603 
2604 	if (a->mode == 0) {
2605 		printf("%s: no data endpoints found\n", DEVNAME(sc));
2606 		free(a, M_USBDEV, sizeof(struct uaudio_alt));
2607 		return 1;
2608 	}
2609 
2610 	/*
2611 	 * Append to list of alts, but keep the list sorted by number
2612 	 * of channels, bits and rate. From the most capable to the
2613 	 * less capable.
2614 	 */
2615 	pa = &sc->alts;
2616 	while (1) {
2617 		if ((anext = *pa) == NULL)
2618 			break;
2619 		if (a->nch > anext->nch)
2620 			break;
2621 		else if (a->nch == anext->nch) {
2622 			if (a->bits > anext->bits)
2623 				break;
2624 			else if (sc->version == UAUDIO_V1 &&
2625 				a->v1_rates > anext->v1_rates)
2626 				break;
2627 		}
2628 		pa = &anext->next;
2629 	}
2630 	a->next = *pa;
2631 	*pa = a;
2632 	return 1;
2633 failed:
2634 	free(a, M_USBDEV, sizeof(struct uaudio_alt));
2635 	return 0;
2636 }
2637 
2638 /*
2639  * Populate the sc->params_list with combinations of play and rec alt
2640  * settings that work together in full-duplex.
2641  */
2642 void
2643 uaudio_fixup_params(struct uaudio_softc *sc)
2644 {
2645 	struct uaudio_alt *ap, *ar, *a;
2646 	struct uaudio_params *p, **pp;
2647 	int rates;
2648 
2649 	/*
2650 	 * Add full-duplex parameter combinations.
2651 	 */
2652 	pp = &sc->params_list;
2653 	for (ap = sc->alts; ap != NULL; ap = ap->next) {
2654 		if (ap->mode != AUMODE_PLAY)
2655 			continue;
2656 		for (ar = sc->alts; ar != NULL; ar = ar->next) {
2657 			if (ar->mode != AUMODE_RECORD)
2658 				continue;
2659 			if (ar->bps != ap->bps || ar->bits != ap->bits)
2660 				continue;
2661 			switch (sc->version) {
2662 			case UAUDIO_V1:
2663 				rates = ap->v1_rates & ar->v1_rates;
2664 				if (rates == 0)
2665 					continue;
2666 				break;
2667 			case UAUDIO_V2:
2668 				/* UAC v2.0 common rates */
2669 				rates = 0;
2670 				break;
2671 			}
2672 			p = malloc(sizeof(struct uaudio_params),
2673 			    M_USBDEV, M_WAITOK);
2674 			p->palt = ap;
2675 			p->ralt = ar;
2676 			p->v1_rates = rates;
2677 			p->next = NULL;
2678 			*pp = p;
2679 			pp = &p->next;
2680 		}
2681 	}
2682 
2683 	/*
2684 	 * For unidirectional devices, add play-only and or rec-only
2685 	 * parameters.
2686 	 */
2687 	if (sc->params_list == NULL) {
2688 		for (a = sc->alts; a != NULL; a = a->next) {
2689 			p = malloc(sizeof(struct uaudio_params),
2690 			    M_USBDEV, M_WAITOK);
2691 			if (a->mode == AUMODE_PLAY) {
2692 				p->palt = a;
2693 				p->ralt = NULL;
2694 			} else {
2695 				p->palt = NULL;
2696 				p->ralt = a;
2697 			}
2698 			p->v1_rates = a->v1_rates;
2699 			p->next = NULL;
2700 			*pp = p;
2701 			pp = &p->next;
2702 		}
2703 	}
2704 }
2705 
2706 /*
2707  * Parse all descriptors and build configuration of the device.
2708  */
2709 int
2710 uaudio_process_conf(struct uaudio_softc *sc, struct uaudio_blob *p)
2711 {
2712 	struct uaudio_blob dp;
2713 	unsigned int type, ifnum, altnum, nep, class, subclass;
2714 
2715 	while (p->rptr != p->wptr) {
2716 		if (!uaudio_getdesc(p, &dp))
2717 			return 0;
2718 		if (!uaudio_getnum(&dp, 1, &type))
2719 			return 0;
2720 		if (type != UDESC_INTERFACE)
2721 			continue;
2722 		if (!uaudio_getnum(&dp, 1, &ifnum))
2723 			return 0;
2724 		if (!uaudio_getnum(&dp, 1, &altnum))
2725 			return 0;
2726 		if (!uaudio_getnum(&dp, 1, &nep))
2727 			return 0;
2728 		if (!uaudio_getnum(&dp, 1, &class))
2729 			return 0;
2730 		if (!uaudio_getnum(&dp, 1, &subclass))
2731 			return 0;
2732 		if (class != UICLASS_AUDIO) {
2733 			DPRINTF("%s: skipped iface\n", __func__);
2734 			continue;
2735 		}
2736 
2737 		switch (subclass) {
2738 		case UISUBCLASS_AUDIOCONTROL:
2739 			usbd_claim_iface(sc->udev, ifnum);
2740 			if (sc->unit_list != NULL) {
2741 				DPRINTF("%s: >1 AC ifaces\n", __func__);
2742 				goto done;
2743 			}
2744 			if (!uaudio_process_ac(sc, p, ifnum))
2745 				return 0;
2746 			break;
2747 		case UISUBCLASS_AUDIOSTREAM:
2748 			usbd_claim_iface(sc->udev, ifnum);
2749 			if (nep == 0) {
2750 				DPRINTF("%s: "
2751 				    "stop altnum %d\n", __func__, altnum);
2752 				break;	/* 0 is "stop sound", skip it */
2753 			}
2754 			if (!uaudio_process_as(sc, p, ifnum, altnum, nep))
2755 				return 0;
2756 		}
2757 	}
2758 done:
2759 	uaudio_fixup_params(sc);
2760 
2761 	return 1;
2762 }
2763 
2764 /*
2765  * Allocate a isochronous transfer and its bounce-buffers with the
2766  * given maximum framesize and maximum frames per transfer.
2767  */
2768 int
2769 uaudio_xfer_alloc(struct uaudio_softc *sc, struct uaudio_xfer *xfer,
2770 	unsigned int framesize, unsigned int count)
2771 {
2772 	xfer->usb_xfer = usbd_alloc_xfer(sc->udev);
2773 	if (xfer->usb_xfer == NULL)
2774 		return ENOMEM;
2775 
2776 	xfer->buf = usbd_alloc_buffer(xfer->usb_xfer, framesize * count);
2777 	if (xfer->buf == NULL)
2778 		return ENOMEM;
2779 
2780 	xfer->sizes = mallocarray(count,
2781 	    sizeof(xfer->sizes[0]), M_USBDEV, M_WAITOK);
2782 	if (xfer->sizes == NULL)
2783 		return ENOMEM;
2784 
2785 	return 0;
2786 }
2787 
2788 /*
2789  * Free a isochronous transfer and its bounce-buffers.
2790  */
2791 void
2792 uaudio_xfer_free(struct uaudio_softc *sc, struct uaudio_xfer *xfer,
2793 	unsigned int count)
2794 {
2795 	if (xfer->usb_xfer != NULL) {
2796 		/* frees request buffer as well */
2797 		usbd_free_xfer(xfer->usb_xfer);
2798 		xfer->usb_xfer = NULL;
2799 	}
2800 	if (xfer->sizes != NULL) {
2801 		free(xfer->sizes, M_USBDEV,
2802 		    sizeof(xfer->sizes[0]) * count);
2803 		xfer->sizes = NULL;
2804 	}
2805 }
2806 
2807 /*
2808  * Close a stream and free all associated resources
2809  */
2810 void
2811 uaudio_stream_close(struct uaudio_softc *sc, int dir)
2812 {
2813 	struct uaudio_stream *s = &sc->pstream;
2814 	struct uaudio_alt *a = sc->params->palt;
2815 	struct usbd_interface *iface;
2816 	int err, i;
2817 
2818 	if (dir == AUMODE_PLAY) {
2819 		s = &sc->pstream;
2820 		a = sc->params->palt;
2821 	} else {
2822 		s = &sc->rstream;
2823 		a = sc->params->ralt;
2824 	}
2825 
2826 	if (s->data_pipe) {
2827 		usbd_close_pipe(s->data_pipe);
2828 		s->data_pipe = NULL;
2829 	}
2830 
2831 	if (s->sync_pipe) {
2832 		usbd_close_pipe(s->sync_pipe);
2833 		s->sync_pipe = NULL;
2834 	}
2835 
2836 	err = usbd_device2interface_handle(sc->udev, a->ifnum, &iface);
2837 	if (err)
2838 		printf("%s: can't get iface handle\n", DEVNAME(sc));
2839 	else {
2840 		err = usbd_set_interface(iface, 0);
2841 		if (err)
2842 			printf("%s: can't reset interface\n", DEVNAME(sc));
2843 	}
2844 
2845 	for (i = 0; i < UAUDIO_NXFERS_MAX; i++) {
2846 		uaudio_xfer_free(sc, s->data_xfers + i, s->nframes_max);
2847 		uaudio_xfer_free(sc, s->sync_xfers + i, 1);
2848 	}
2849 }
2850 
2851 /*
2852  * Open a stream with the given buffer settings and set the current
2853  * interface alt setting.
2854  */
2855 int
2856 uaudio_stream_open(struct uaudio_softc *sc, int dir,
2857     void *start, void *end, size_t blksz, void (*intr)(void *), void *arg)
2858 {
2859 	struct uaudio_stream *s;
2860 	struct uaudio_alt *a;
2861 	struct usbd_interface *iface;
2862 	unsigned char req_buf[4];
2863 	unsigned int bpa, spf_max, min_blksz;
2864 	int err, clock_id, i;
2865 
2866 	if (dir == AUMODE_PLAY) {
2867 		s = &sc->pstream;
2868 		a = sc->params->palt;
2869 	} else {
2870 		s = &sc->rstream;
2871 		a = sc->params->ralt;
2872 	}
2873 
2874 	for (i = 0; i < UAUDIO_NXFERS_MAX; i++) {
2875 		s->data_xfers[i].usb_xfer = NULL;
2876 		s->data_xfers[i].sizes = NULL;
2877 		s->sync_xfers[i].usb_xfer = NULL;
2878 		s->sync_xfers[i].sizes = NULL;
2879 	}
2880 	s->data_pipe = NULL;
2881 	s->sync_pipe = NULL;
2882 
2883 	s->nframes_mask = 0;
2884 	i = a->fps;
2885 	while (i > 1000) {
2886 		s->nframes_mask = (s->nframes_mask << 1) | 1;
2887 		i >>= 1;
2888 	}
2889 
2890 	/* bytes per audio frame */
2891 	bpa = a->bps * a->nch;
2892 
2893 	/* ideal samples per usb frame, fixed-point */
2894 	s->spf = (uint64_t)sc->rate * UAUDIO_SPF_DIV / a->fps;
2895 
2896 	/*
2897 	 * UAC2.0 spec allows 1000PPM tolerance in sample frequency,
2898 	 * while USB1.1 requires 1Hz, which is 125PPM at 8kHz. We
2899 	 * accept as much as 1/256, which is 2500PPM.
2900 	 */
2901 	s->spf_min = (uint64_t)s->spf * 255 / 256;
2902 	s->spf_max = (uint64_t)s->spf * 257 / 256;
2903 
2904 	/* max spf can't exceed the device usb packet size */
2905 	spf_max = (a->maxpkt / bpa) * UAUDIO_SPF_DIV;
2906 	if (s->spf > spf_max) {
2907 		printf("%s: samples per frame too large\n", DEVNAME(sc));
2908 		return EIO;
2909 	}
2910 	if (s->spf_max > spf_max)
2911 		s->spf_max = spf_max;
2912 
2913 	/*
2914 	 * Upon transfer completion the device must reach the audio
2915 	 * block boundary, which is propagated to upper layers. In the
2916 	 * worst case, we schedule only frames of spf_max samples, but
2917 	 * the device returns only frames of spf_min samples; in this
2918 	 * case the amount actually transferred is at least:
2919 	 *
2920 	 *		min_blksz = blksz / spf_max * spf_min
2921 	 *
2922 	 * As we've UAUDIO_NXFERS outstanding blocks, worst-case
2923 	 * remaining bytes is at most:
2924 	 *
2925 	 *		UAUDIO_NXFERS * (blksz - min_blksz)
2926 	 */
2927 	min_blksz = (((uint64_t)blksz << 32) / s->spf_max * s->spf_min) >> 32;
2928 
2929 	/* round to sample size */
2930 	min_blksz -= min_blksz % bpa;
2931 
2932 	/* finally this is what ensures we cross block boundary */
2933 	s->safe_blksz = blksz + UAUDIO_NXFERS_MAX * (blksz - min_blksz);
2934 
2935 	/* max number of (micro-)frames we'll ever use */
2936 	s->nframes_max = (uint64_t)(s->safe_blksz / bpa) *
2937 	    UAUDIO_SPF_DIV / s->spf_min + 1;
2938 
2939 	/* round to next usb1.1 frame */
2940 	s->nframes_max = (s->nframes_max + s->nframes_mask) &
2941 	    ~s->nframes_mask;
2942 
2943 	/* this is the max packet size we'll ever need */
2944 	s->maxpkt = bpa *
2945 	    ((s->spf_max + UAUDIO_SPF_DIV - 1) / UAUDIO_SPF_DIV);
2946 
2947 	/* how many xfers we need to fill sc->host_nframes */
2948 	s->nxfers = sc->host_nframes / s->nframes_max;
2949 	if (s->nxfers > UAUDIO_NXFERS_MAX)
2950 		s->nxfers = UAUDIO_NXFERS_MAX;
2951 
2952 	DPRINTF("%s: %s: blksz = %zu, rate = %u, fps = %u\n", __func__,
2953 	    dir == AUMODE_PLAY ? "play" : "rec", blksz, sc->rate, a->fps);
2954 	DPRINTF("%s: spf = 0x%x in [0x%x:0x%x]\n", __func__,
2955 	    s->spf, s->spf_min, s->spf_max);
2956 	DPRINTF("%s: nframes_max = %u, nframes_mask = %u, maxpkt = %u\n",
2957 	    __func__, s->nframes_max, s->nframes_mask, s->maxpkt);
2958 	DPRINTF("%s: safe_blksz = %d, nxfers = %d\n", __func__,
2959 	    s->safe_blksz, s->nxfers);
2960 
2961 	if (s->nxfers < UAUDIO_NXFERS_MIN) {
2962 		printf("%s: block size too large\n", DEVNAME(sc));
2963 		return EIO;
2964 	}
2965 
2966 	/*
2967 	 * Require at least 2ms block size to ensure no
2968 	 * transfer exceeds two blocks.
2969 	 *
2970 	 * XXX: use s->nframes_mask instead of 1000
2971 	 */
2972 	if (1000 * blksz < 2 * sc->rate * bpa) {
2973 		printf("%s: audio block too small\n", DEVNAME(sc));
2974 		return EIO;
2975 	}
2976 
2977 	for (i = 0; i < s->nxfers; i++) {
2978 		err = uaudio_xfer_alloc(sc, s->data_xfers + i,
2979 		    s->maxpkt, s->nframes_max);
2980 		if (err)
2981 			goto failed;
2982 		if (a->sync_addr) {
2983 			err = uaudio_xfer_alloc(sc, s->sync_xfers + i,
2984 			    sc->sync_pktsz, 1);
2985 			if (err)
2986 				goto failed;
2987 		}
2988 	}
2989 
2990 	err = usbd_device2interface_handle(sc->udev, a->ifnum, &iface);
2991 	if (err) {
2992 		printf("%s: can't get iface handle\n", DEVNAME(sc));
2993 		goto failed;
2994 	}
2995 
2996 	err = usbd_set_interface(iface, a->altnum);
2997 	if (err) {
2998 		printf("%s: can't set interface\n", DEVNAME(sc));
2999 		goto failed;
3000 	}
3001 
3002 	/*
3003 	 * Set the sample rate.
3004 	 *
3005 	 * Certain devices are able to lock their clock to the data
3006 	 * rate and expose no frequency control. In this case, the
3007 	 * request to set the frequency will fail, but this error is
3008 	 * safe to ignore.
3009 	 *
3010 	 * Such devices expose this capability in the class-specific
3011 	 * endpoint descriptor (UAC v1.0) or in the clock unit
3012 	 * descriptor (UAC v2.0) but we don't want to use them for now
3013 	 * as certain devices have them wrong, missing or misplaced.
3014 	 */
3015 	switch (sc->version) {
3016 	case UAUDIO_V1:
3017 		req_buf[0] = sc->rate;
3018 		req_buf[1] = sc->rate >> 8;
3019 		req_buf[2] = sc->rate >> 16;
3020 		if (!uaudio_req(sc, UT_WRITE_CLASS_ENDPOINT,
3021 			UAUDIO_V1_REQ_SET_CUR, UAUDIO_REQSEL_RATE, 0,
3022 			a->data_addr, 0, req_buf, 3)) {
3023 			DPRINTF("%s: not setting endpoint rate\n", __func__);
3024 		}
3025 		break;
3026 	case UAUDIO_V2:
3027 		req_buf[0] = sc->rate;
3028 		req_buf[1] = sc->rate >> 8;
3029 		req_buf[2] = sc->rate >> 16;
3030 		req_buf[3] = sc->rate >> 24;
3031 		clock_id = uaudio_clock_id(sc);
3032 		if (clock_id < 0) {
3033 			printf("%s: can't get clock id\n", DEVNAME(sc));
3034 			goto failed;
3035 		}
3036 		if (!uaudio_req(sc, UT_WRITE_CLASS_INTERFACE,
3037 			UAUDIO_V2_REQ_CUR, UAUDIO_REQSEL_RATE, 0,
3038 			sc->ctl_ifnum, clock_id, req_buf, 4)) {
3039 			DPRINTF("%s: not setting clock rate\n", __func__);
3040 		}
3041 		break;
3042 	}
3043 
3044 	err = usbd_open_pipe(iface, a->data_addr, 0, &s->data_pipe);
3045 	if (err) {
3046 		printf("%s: can't open data pipe\n", DEVNAME(sc));
3047 		goto failed;
3048 	}
3049 
3050 	if (a->sync_addr) {
3051 		err = usbd_open_pipe(iface, a->sync_addr, 0, &s->sync_pipe);
3052 		if (err) {
3053 			printf("%s: can't open sync pipe\n", DEVNAME(sc));
3054 			goto failed;
3055 		}
3056 	}
3057 
3058 	s->data_nextxfer = 0;
3059 	s->sync_nextxfer = 0;
3060 	s->spf_remain = 0;
3061 
3062 	s->intr = intr;
3063 	s->arg = arg;
3064 	s->ring_start = start;
3065 	s->ring_end = end;
3066 	s->ring_blksz = blksz;
3067 
3068 	s->ring_pos = s->ring_start;
3069 	s->ring_offs = 0;
3070 	s->ring_icnt = 0;
3071 
3072 	s->ubuf_xfer = 0;
3073 	s->ubuf_pos = 0;
3074 	return 0;
3075 
3076 failed:
3077 	uaudio_stream_close(sc, dir);
3078 	return ENOMEM;
3079 }
3080 
3081 /*
3082  * Adjust play samples-per-frame to keep play and rec streams in sync.
3083  */
3084 void
3085 uaudio_adjspf(struct uaudio_softc *sc)
3086 {
3087 	struct uaudio_stream *s = &sc->pstream;
3088 	int diff;
3089 
3090 	if (sc->mode != (AUMODE_RECORD | AUMODE_PLAY))
3091 		return;
3092 	if (s->sync_pipe != NULL)
3093 		return;
3094 
3095 	/*
3096 	 * number of samples play stream is ahead of record stream.
3097 	 */
3098 	diff = sc->diff_nsamp;
3099 	if (sc->diff_nframes > 0) {
3100 		diff -= (uint64_t)sc->pstream.spf *
3101 		    sc->diff_nframes / UAUDIO_SPF_DIV;
3102 	} else {
3103 		diff += (uint64_t)sc->rstream.spf *
3104 		    -sc->diff_nframes / UAUDIO_SPF_DIV;
3105 	}
3106 
3107 	/*
3108 	 * adjust samples-per-frames to resync within the next second
3109 	 */
3110 	s->spf = (uint64_t)(sc->rate - diff) * UAUDIO_SPF_DIV / sc->ufps;
3111 	if (s->spf > s->spf_max)
3112 		s->spf = s->spf_max;
3113 	else if (s->spf < s->spf_min)
3114 		s->spf = s->spf_min;
3115 #ifdef UAUDIO_DEBUG
3116 	if (uaudio_debug >= 2)
3117 		printf("%s: diff = %d, spf = 0x%x\n", __func__, diff, s->spf);
3118 #endif
3119 }
3120 
3121 /*
3122  * Copy one audio block to the xfer buffer.
3123  */
3124 void
3125 uaudio_pdata_copy(struct uaudio_softc *sc)
3126 {
3127 	struct uaudio_stream *s = &sc->pstream;
3128 	struct uaudio_xfer *xfer;
3129 	size_t count, avail;
3130 	int index;
3131 #ifdef UAUDIO_DEBUG
3132 	struct timeval tv;
3133 
3134 	getmicrotime(&tv);
3135 #endif
3136 	while (sc->copy_todo > 0 && s->ubuf_xfer < s->nxfers) {
3137 		index = s->data_nextxfer + s->ubuf_xfer;
3138 		if (index >= s->nxfers)
3139 			index -= s->nxfers;
3140 		xfer = s->data_xfers + index;
3141 		avail = s->ring_end - s->ring_pos;
3142 		count = xfer->size - s->ubuf_pos;
3143 		if (count > avail)
3144 			count = avail;
3145 		if (count > sc->copy_todo)
3146 			count = sc->copy_todo;
3147 #ifdef UAUDIO_DEBUG
3148 		if (uaudio_debug >= 2) {
3149 			printf("%s: %llu.%06lu: %zd..%zd -> %u:%u..%zu\n",
3150 			    __func__, tv.tv_sec, tv.tv_usec,
3151 			    s->ring_pos - s->ring_start,
3152 			    s->ring_pos - s->ring_start + count,
3153 			    s->ubuf_xfer, s->ubuf_pos, s->ubuf_pos + count);
3154 		}
3155 #endif
3156 		memcpy(xfer->buf + s->ubuf_pos, s->ring_pos, count);
3157 		sc->copy_todo -= count;
3158 		s->ring_pos += count;
3159 		if (s->ring_pos == s->ring_end) {
3160 			s->ring_pos = s->ring_start;
3161 		}
3162 		s->ubuf_pos += count;
3163 		if (s->ubuf_pos == xfer->size) {
3164 			usb_syncmem(&xfer->usb_xfer->dmabuf, 0, xfer->size,
3165 			    BUS_DMASYNC_PREWRITE);
3166 			s->ubuf_pos = 0;
3167 #ifdef DIAGNOSTIC
3168 			if (s->ubuf_xfer == s->nxfers) {
3169 				printf("%s: overflow\n", __func__);
3170 				return;
3171 			}
3172 #endif
3173 			s->ubuf_xfer++;
3174 		}
3175 	}
3176 }
3177 
3178 /*
3179  * Calculate and fill xfer frames sizes.
3180  */
3181 void
3182 uaudio_pdata_calcsizes(struct uaudio_softc *sc, struct uaudio_xfer *xfer)
3183 {
3184 #ifdef UAUDIO_DEBUG
3185 	struct timeval tv;
3186 #endif
3187 	struct uaudio_stream *s = &sc->pstream;
3188 	struct uaudio_alt *a = sc->params->palt;
3189 	unsigned int fsize, bpf;
3190 	int done;
3191 
3192 	bpf = a->bps * a->nch;
3193 	done = s->ring_offs;
3194 	xfer->nframes = 0;
3195 
3196 	while (1) {
3197 		/*
3198 		 * if we crossed the next block boundary, we're done
3199 		 */
3200 		if ((xfer->nframes & s->nframes_mask) == 0 &&
3201 		    done > s->safe_blksz)
3202 			break;
3203 
3204 		/*
3205 		 * this can't happen, debug only
3206 		 */
3207 		if (xfer->nframes == s->nframes_max) {
3208 			printf("%s: too many frames for play xfer: "
3209 			    "done = %u, blksz = %d\n",
3210 			    DEVNAME(sc), done, s->ring_blksz);
3211 			break;
3212 		}
3213 
3214 		/*
3215 		 * calculate frame size and adjust state
3216 		 */
3217 		s->spf_remain += s->spf;
3218 		fsize = s->spf_remain / UAUDIO_SPF_DIV * bpf;
3219 		s->spf_remain %= UAUDIO_SPF_DIV;
3220 		done += fsize;
3221 		xfer->sizes[xfer->nframes] = fsize;
3222 		xfer->nframes++;
3223 	}
3224 
3225 	xfer->size = done - s->ring_offs;
3226 	s->ring_offs = done - s->ring_blksz;
3227 
3228 #ifdef UAUDIO_DEBUG
3229 	if (uaudio_debug >= 3) {
3230 		getmicrotime(&tv);
3231 		printf("%s: size = %d, offs -> %d\n", __func__,
3232 		    xfer->size, s->ring_offs);
3233 	}
3234 #endif
3235 	memset(xfer->buf, 0, xfer->size);
3236 }
3237 
3238 /*
3239  * Submit a play data transfer to the USB driver.
3240  */
3241 void
3242 uaudio_pdata_xfer(struct uaudio_softc *sc)
3243 {
3244 #ifdef UAUDIO_DEBUG
3245 	struct timeval tv;
3246 #endif
3247 	struct uaudio_stream *s = &sc->pstream;
3248 	struct uaudio_xfer *xfer;
3249 	int err;
3250 
3251 	xfer = s->data_xfers + s->data_nextxfer;
3252 
3253 #ifdef UAUDIO_DEBUG
3254 	if (uaudio_debug >= 3) {
3255 		getmicrotime(&tv);
3256 		printf("%s: %llu.%06lu: "
3257 		    "%d bytes, %u frames, remain = 0x%x, offs = %d\n",
3258 		    __func__, tv.tv_sec, tv.tv_usec,
3259 		    xfer->size, xfer->nframes,
3260 		    s->spf_remain, s->ring_offs);
3261 	}
3262 #endif
3263 
3264 	/* this can't happen, debug only */
3265 	if (xfer->nframes == 0) {
3266 		printf("%s: zero frame play xfer\n", DEVNAME(sc));
3267 		return;
3268 	}
3269 
3270 	/*
3271 	 * We accept short transfers because in case of babble/stale frames
3272 	 * the transfer will be short
3273 	 */
3274 	usbd_setup_isoc_xfer(xfer->usb_xfer, s->data_pipe, sc,
3275 	    xfer->sizes, xfer->nframes,
3276 	    USBD_NO_COPY | USBD_SHORT_XFER_OK,
3277 	    uaudio_pdata_intr);
3278 
3279 	err = usbd_transfer(xfer->usb_xfer);
3280 	if (err != 0 && err != USBD_IN_PROGRESS)
3281 		printf("%s: play xfer, err = %d\n", DEVNAME(sc), err);
3282 
3283 	if (++s->data_nextxfer == s->nxfers)
3284 		s->data_nextxfer = 0;
3285 }
3286 
3287 /*
3288  * Callback called by the USB driver upon completion of play data transfer.
3289  */
3290 void
3291 uaudio_pdata_intr(struct usbd_xfer *usb_xfer, void *arg, usbd_status status)
3292 {
3293 #ifdef UAUDIO_DEBUG
3294 	struct timeval tv;
3295 #endif
3296 	struct uaudio_softc *sc = arg;
3297 	struct uaudio_stream *s = &sc->pstream;
3298 	struct uaudio_xfer *xfer;
3299 	uint32_t size;
3300 	int nintr;
3301 
3302 	if (status != 0 && status != USBD_IOERROR) {
3303 		DPRINTF("%s: xfer status = %d\n", __func__, status);
3304 		return;
3305 	}
3306 
3307 	xfer = s->data_xfers + s->data_nextxfer;
3308 	if (xfer->usb_xfer != usb_xfer) {
3309 		DPRINTF("%s: wrong xfer\n", __func__);
3310 		return;
3311 	}
3312 
3313 	sc->diff_nsamp += xfer->size /
3314 	    (sc->params->palt->nch * sc->params->palt->bps);
3315 	sc->diff_nframes += xfer->nframes;
3316 
3317 #ifdef UAUDIO_DEBUG
3318 	if (uaudio_debug >= 2) {
3319 		getmicrotime(&tv);
3320 		printf("%s: %llu.%06lu: %u: %u bytes\n",
3321 		    __func__, tv.tv_sec, tv.tv_usec,
3322 		    s->data_nextxfer, xfer->size);
3323 	}
3324 #endif
3325 	usbd_get_xfer_status(usb_xfer, NULL, NULL, &size, NULL);
3326 	if (size != xfer->size) {
3327 		DPRINTF("%s: %u bytes out of %u: incomplete play xfer\n",
3328 		    DEVNAME(sc), size, xfer->size);
3329 	}
3330 
3331 	/*
3332 	 * Upper layer call-back may call uaudio_underrun(), which
3333 	 * needs the current size of this transfer. So, don't
3334 	 * recalculate the sizes and don't schedule the transfer yet.
3335 	 */
3336 	s->ring_icnt += xfer->size;
3337 	nintr = 0;
3338 	mtx_enter(&audio_lock);
3339 	while (s->ring_icnt >= s->ring_blksz) {
3340 		s->intr(s->arg);
3341 		s->ring_icnt -= s->ring_blksz;
3342 		nintr++;
3343 	}
3344 	mtx_leave(&audio_lock);
3345 	if (nintr != 1)
3346 		printf("%s: %d: bad play intr count\n", __func__, nintr);
3347 
3348 	uaudio_pdata_calcsizes(sc, xfer);
3349 	uaudio_pdata_xfer(sc);
3350 #ifdef DIAGNOSTIC
3351 	if (s->ubuf_xfer == 0) {
3352 		printf("%s: underflow\n", __func__);
3353 		return;
3354 	}
3355 #endif
3356 	s->ubuf_xfer--;
3357 	uaudio_pdata_copy(sc);
3358 }
3359 
3360 /*
3361  * Submit a play sync transfer to the USB driver.
3362  */
3363 void
3364 uaudio_psync_xfer(struct uaudio_softc *sc)
3365 {
3366 #ifdef UAUDIO_DEBUG
3367 	struct timeval tv;
3368 #endif
3369 	struct uaudio_stream *s = &sc->pstream;
3370 	struct uaudio_xfer *xfer;
3371 	unsigned int i;
3372 	int err;
3373 
3374 	xfer = s->sync_xfers + s->sync_nextxfer;
3375 	xfer->nframes = 1;
3376 
3377 	for (i = 0; i < xfer->nframes; i++)
3378 		xfer->sizes[i] = sc->sync_pktsz;
3379 
3380 	xfer->size = xfer->nframes * sc->sync_pktsz;
3381 
3382 #ifdef UAUDIO_DEBUG
3383 	memset(xfer->buf, 0xd0, sc->sync_pktsz * xfer->nframes);
3384 #endif
3385 
3386 	usbd_setup_isoc_xfer(xfer->usb_xfer, s->sync_pipe, sc,
3387 	    xfer->sizes, xfer->nframes,
3388 	    USBD_NO_COPY | USBD_SHORT_XFER_OK,
3389 	    uaudio_psync_intr);
3390 
3391 	err = usbd_transfer(xfer->usb_xfer);
3392 	if (err != 0 && err != USBD_IN_PROGRESS)
3393 		printf("%s: sync play xfer, err = %d\n", DEVNAME(sc), err);
3394 
3395 	if (++s->sync_nextxfer == s->nxfers)
3396 		s->sync_nextxfer = 0;
3397 
3398 #ifdef UAUDIO_DEBUG
3399 	if (uaudio_debug >= 3) {
3400 		getmicrotime(&tv);
3401 		printf("%s: %llu.%06lu: %dB, %d fr\n", __func__,
3402 		    tv.tv_sec, tv.tv_usec, sc->sync_pktsz, xfer->nframes);
3403 	}
3404 #endif
3405 }
3406 
3407 /*
3408  * Callback called by the USB driver upon completion of play sync transfer.
3409  */
3410 void
3411 uaudio_psync_intr(struct usbd_xfer *usb_xfer, void *arg, usbd_status status)
3412 {
3413 #ifdef UAUDIO_DEBUG
3414 	struct timeval tv;
3415 #endif
3416 	struct uaudio_softc *sc = arg;
3417 	struct uaudio_stream *s = &sc->pstream;
3418 	struct uaudio_xfer *xfer;
3419 	unsigned char *buf;
3420 	unsigned int i;
3421 	int32_t val;
3422 
3423 	if (status != 0) {
3424 		DPRINTF("%s: xfer status = %d\n", __func__, status);
3425 		return;
3426 	}
3427 
3428 	xfer = s->sync_xfers + s->sync_nextxfer;
3429 	if (xfer->usb_xfer != usb_xfer) {
3430 		DPRINTF("%s: wrong xfer\n", __func__);
3431 		return;
3432 	}
3433 
3434 	/* XXX: there's only one frame, the loop is not necessary */
3435 
3436 	buf = xfer->buf;
3437 	for (i = 0; i < xfer->nframes; i++) {
3438 		if (xfer->sizes[i] == sc->sync_pktsz) {
3439 			val = buf[0] | buf[1] << 8 | buf[2] << 16;
3440 			if (sc->sync_pktsz == 4)
3441 				val |= xfer->buf[3] << 24;
3442 			else
3443 				val <<= 2;
3444 			val *= UAUDIO_SPF_DIV / (1 << 16);
3445 #ifdef UAUDIO_DEBUG
3446 			if (uaudio_debug >= 2) {
3447 				getmicrotime(&tv);
3448 				printf("%s: %llu.%06lu: spf: %08x\n",
3449 				    __func__, tv.tv_sec, tv.tv_usec, val);
3450 			}
3451 #endif
3452 			if (val > s->spf_max)
3453 				s->spf = s->spf_max;
3454 			else if (val < s->spf_min)
3455 				s->spf = s->spf_min;
3456 			else
3457 				s->spf = val;
3458 		}
3459 		buf += sc->sync_pktsz;
3460 	}
3461 
3462 	uaudio_psync_xfer(sc);
3463 }
3464 
3465 /*
3466  * Submit a rec data transfer to the USB driver.
3467  */
3468 void
3469 uaudio_rdata_xfer(struct uaudio_softc *sc)
3470 {
3471 #ifdef UAUDIO_DEBUG
3472 	struct timeval tv;
3473 #endif
3474 	struct uaudio_stream *s = &sc->rstream;
3475 	struct uaudio_alt *a = sc->params->ralt;
3476 	struct uaudio_xfer *xfer;
3477 	unsigned int fsize, bpf;
3478 	int done;
3479 	int err;
3480 
3481 	xfer = s->data_xfers + s->data_nextxfer;
3482 	bpf = a->bps * a->nch;
3483 	xfer->nframes = 0;
3484 	done = s->ring_offs;
3485 
3486 	while (1) {
3487 		/*
3488 		 * if we crossed the next block boundary, we're done
3489 		 */
3490 		if ((xfer->nframes & s->nframes_mask) == 0 &&
3491 		    done > s->safe_blksz) {
3492 		done:
3493 			xfer->size = done - s->ring_offs;
3494 			s->ring_offs = done - s->ring_blksz;
3495 			break;
3496 		}
3497 
3498 		/*
3499 		 * this can't happen, debug only
3500 		 */
3501 		if (xfer->nframes == s->nframes_max) {
3502 			printf("%s: too many frames for rec xfer: "
3503 			    "done = %d, blksz = %d\n",
3504 			    DEVNAME(sc), done, s->ring_blksz);
3505 			goto done;
3506 		}
3507 
3508 		/*
3509 		 * estimate next block using s->spf, but allow
3510 		 * transfers up to maxpkt
3511 		 */
3512 		s->spf_remain += s->spf;
3513 		fsize = s->spf_remain / UAUDIO_SPF_DIV * bpf;
3514 		s->spf_remain %= UAUDIO_SPF_DIV;
3515 		done += fsize;
3516 		xfer->sizes[xfer->nframes] = s->maxpkt;
3517 		xfer->nframes++;
3518 	}
3519 
3520 #ifdef UAUDIO_DEBUG
3521 	if (uaudio_debug >= 3) {
3522 		getmicrotime(&tv);
3523 		printf("%s: %llu.%06lu: "
3524 		    "%u fr, %d bytes (max %d), offs = %d\n",
3525 		    __func__, tv.tv_sec, tv.tv_usec,
3526 		    xfer->nframes, xfer->size,
3527 		    s->maxpkt * xfer->nframes, s->ring_offs);
3528 	}
3529 #endif
3530 
3531 	/* this can't happen, debug only */
3532 	if (xfer->nframes == 0) {
3533 		printf("%s: zero frame rec xfer\n", DEVNAME(sc));
3534 		return;
3535 	}
3536 
3537 #ifdef UAUDIO_DEBUG
3538 	memset(xfer->buf, 0xd0, s->maxpkt * xfer->nframes);
3539 #endif
3540 	usbd_setup_isoc_xfer(xfer->usb_xfer, s->data_pipe, sc,
3541 	    xfer->sizes, xfer->nframes, USBD_NO_COPY | USBD_SHORT_XFER_OK,
3542 	    uaudio_rdata_intr);
3543 
3544 	err = usbd_transfer(xfer->usb_xfer);
3545 	if (err != 0 && err != USBD_IN_PROGRESS)
3546 		printf("%s: rec xfer, err = %d\n", DEVNAME(sc), err);
3547 
3548 	if (++s->data_nextxfer == s->nxfers)
3549 		s->data_nextxfer = 0;
3550 }
3551 
3552 /*
3553  * Callback called by the USB driver upon completion of rec data transfer.
3554  */
3555 void
3556 uaudio_rdata_intr(struct usbd_xfer *usb_xfer, void *arg, usbd_status status)
3557 {
3558 #ifdef UAUDIO_DEBUG
3559 	struct timeval tv;
3560 #endif
3561 	struct uaudio_softc *sc = arg;
3562 	struct uaudio_stream *s = &sc->rstream;
3563 	struct uaudio_alt *a = sc->params->ralt;
3564 	struct uaudio_xfer *xfer;
3565 	unsigned char *buf, *framebuf;
3566 	unsigned int count, fsize, fsize_min, nframes, bpf;
3567 	unsigned int data_size, null_count;
3568 	unsigned int nintr;
3569 
3570 	if (status != 0) {
3571 		DPRINTF("%s: xfer status = %d\n", __func__, status);
3572 		return;
3573 	}
3574 
3575 	xfer = s->data_xfers + s->data_nextxfer;
3576 	if (xfer->usb_xfer != usb_xfer) {
3577 		DPRINTF("%s: wrong xfer\n", __func__);
3578 		return;
3579 	}
3580 
3581 	bpf = a->bps * a->nch;
3582 	framebuf = xfer->buf;
3583 	nframes = 0;
3584 	null_count = 0;
3585 	data_size = 0;
3586 	fsize_min = s->spf_min / UAUDIO_SPF_DIV;
3587 	for (nframes = 0; nframes < xfer->nframes; nframes++) {
3588 
3589 		/*
3590 		 * Device clock may take some time to lock during which
3591 		 * we'd receive empty or incomplete packets for which we
3592 		 * need to generate silence.
3593 		 */
3594 		fsize = xfer->sizes[nframes];
3595 		if (fsize < fsize_min) {
3596 			s->spf_remain += s->spf;
3597 			fsize = s->spf_remain / UAUDIO_SPF_DIV * bpf;
3598 			s->spf_remain %= UAUDIO_SPF_DIV;
3599 			memset(framebuf, 0, fsize);
3600 			null_count++;
3601 		}
3602 		data_size += fsize;
3603 
3604 		/*
3605 		 * fill ring from frame buffer, handling
3606 		 * boundary conditions
3607 		 */
3608 		buf = framebuf;
3609 		while (fsize > 0) {
3610 			count = s->ring_end - s->ring_pos;
3611 			if (count > fsize)
3612 				count = fsize;
3613 			memcpy(s->ring_pos, buf, count);
3614 			s->ring_pos += count;
3615 			if (s->ring_pos == s->ring_end)
3616 				s->ring_pos = s->ring_start;
3617 			buf += count;
3618 			fsize -= count;
3619 		}
3620 
3621 		framebuf += s->maxpkt;
3622 	}
3623 
3624 	s->ring_offs += data_size - xfer->size;
3625 	s->ring_icnt += data_size;
3626 
3627 	sc->diff_nsamp -= data_size /
3628 	    (sc->params->ralt->nch * sc->params->ralt->bps);
3629 	sc->diff_nframes -= xfer->nframes;
3630 
3631 	sc->adjspf_age += xfer->nframes;
3632 	if (sc->adjspf_age >= sc->ufps / 8) {
3633 		sc->adjspf_age -= sc->ufps / 8;
3634 		uaudio_adjspf(sc);
3635 	}
3636 
3637 #ifdef UAUDIO_DEBUG
3638 	if (uaudio_debug >= 2) {
3639 		getmicrotime(&tv);
3640 		printf("%s: %llu.%06lu: %u: "
3641 		    "%u bytes of %u, offs -> %d\n",
3642 		    __func__, tv.tv_sec, tv.tv_usec,
3643 		    s->data_nextxfer, data_size, xfer->size, s->ring_offs);
3644 	}
3645 	if (null_count > 0) {
3646 		DPRINTF("%s: %u null frames out of %u: incomplete record xfer\n",
3647 		    DEVNAME(sc), null_count, xfer->nframes);
3648 	}
3649 #endif
3650 	uaudio_rdata_xfer(sc);
3651 
3652 	nintr = 0;
3653 	mtx_enter(&audio_lock);
3654 	while (s->ring_icnt >= s->ring_blksz) {
3655 		s->intr(s->arg);
3656 		s->ring_icnt -= s->ring_blksz;
3657 		nintr++;
3658 	}
3659 	mtx_leave(&audio_lock);
3660 	if (nintr != 1)
3661 		printf("%s: %u: bad rec intr count\n", DEVNAME(sc), nintr);
3662 }
3663 
3664 /*
3665  * Start simultaneously playback and recording, unless trigger_input()
3666  * and trigger_output() were not both called yet.
3667  */
3668 void
3669 uaudio_trigger(struct uaudio_softc *sc)
3670 {
3671 	int i, s;
3672 
3673 	if (sc->mode != sc->trigger_mode)
3674 		return;
3675 
3676 	DPRINTF("%s: preparing\n", __func__);
3677 	if (sc->mode & AUMODE_PLAY) {
3678 		for (i = 0; i < sc->pstream.nxfers; i++)
3679 			uaudio_pdata_calcsizes(sc, sc->pstream.data_xfers + i);
3680 
3681 		uaudio_pdata_copy(sc);
3682 	}
3683 
3684 	sc->diff_nsamp = 0;
3685 	sc->diff_nframes = 0;
3686 	sc->adjspf_age = 0;
3687 
3688 	DPRINTF("%s: starting\n", __func__);
3689 	s = splusb();
3690 	for (i = 0; i < UAUDIO_NXFERS_MAX; i++) {
3691 		if ((sc->mode & AUMODE_PLAY) && i < sc->pstream.nxfers) {
3692 			if (sc->pstream.sync_pipe)
3693 				uaudio_psync_xfer(sc);
3694 			uaudio_pdata_xfer(sc);
3695 		}
3696 		if ((sc->mode & AUMODE_RECORD) && i < sc->rstream.nxfers)
3697 			uaudio_rdata_xfer(sc);
3698 	}
3699 	splx(s);
3700 }
3701 
3702 void
3703 uaudio_print(struct uaudio_softc *sc)
3704 {
3705 	struct uaudio_unit *u;
3706 	struct uaudio_mixent *m;
3707 	struct uaudio_params *p;
3708 	int pchan = 0, rchan = 0, async = 0;
3709 	int nctl = 0;
3710 
3711 	for (u = sc->unit_list; u != NULL; u = u->unit_next) {
3712 		m = u->mixent_list;
3713 		while (1) {
3714 			uaudio_mixer_skip(&m);
3715 			if (m == NULL)
3716 				break;
3717 			m = m->next;
3718 			nctl++;
3719 		}
3720 	}
3721 
3722 	for (p = sc->params_list; p != NULL; p = p->next) {
3723 		if (p->palt && p->palt->nch > pchan)
3724 			pchan = p->palt->nch;
3725 		if (p->ralt && p->ralt->nch > rchan)
3726 			rchan = p->ralt->nch;
3727 		if (p->palt && p->palt->sync_addr)
3728 			async = 1;
3729 		if (p->ralt && p->ralt->sync_addr)
3730 			async = 1;
3731 	}
3732 
3733 	printf("%s: class v%d, %s, %s, channels: %d play, %d rec, %d ctls\n",
3734 	    DEVNAME(sc),
3735 	    sc->version >> 8,
3736 	    sc->ufps == 1000 ? "full-speed" : "high-speed",
3737 	    async ? "async" : "sync",
3738 	    pchan, rchan, nctl);
3739 }
3740 
3741 int
3742 uaudio_match(struct device *parent, void *match, void *aux)
3743 {
3744 	struct usb_attach_arg *arg = aux;
3745 	struct usb_interface_descriptor *idesc;
3746 
3747 	if (arg->iface == NULL || arg->device == NULL)
3748 		return UMATCH_NONE;
3749 
3750 	idesc = usbd_get_interface_descriptor(arg->iface);
3751 	if (idesc == NULL) {
3752 		DPRINTF("%s: couldn't get idesc\n", __func__);
3753 		return UMATCH_NONE;
3754 	}
3755 
3756 	if (idesc->bInterfaceClass != UICLASS_AUDIO ||
3757 	    idesc->bInterfaceSubClass != UISUBCLASS_AUDIOSTREAM)
3758 		return UMATCH_NONE;
3759 
3760 	return UMATCH_VENDOR_PRODUCT_CONF_IFACE;
3761 }
3762 
3763 void
3764 uaudio_attach(struct device *parent, struct device *self, void *aux)
3765 {
3766 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
3767 	struct usb_attach_arg *arg = aux;
3768 	struct usb_config_descriptor *cdesc;
3769 	struct uaudio_blob desc;
3770 
3771 	/*
3772 	 * this device has audio AC or AS or MS interface, get the
3773 	 * full config descriptor and attach audio devices
3774 	 */
3775 
3776 	cdesc = usbd_get_config_descriptor(arg->device);
3777 	if (cdesc == NULL)
3778 		return;
3779 
3780 	desc.rptr = (unsigned char *)cdesc;
3781 	desc.wptr = desc.rptr + UGETW(cdesc->wTotalLength);
3782 
3783 	sc->udev = arg->device;
3784 	sc->unit_list = NULL;
3785 	sc->names = NULL;
3786 	sc->alts = NULL;
3787 	sc->params_list = NULL;
3788 	sc->clock = NULL;
3789 	sc->params = NULL;
3790 	sc->rate = 0;
3791 	sc->mode = 0;
3792 	sc->trigger_mode = 0;
3793 	sc->copy_todo = 0;
3794 
3795 	/*
3796 	 * Ideally the USB host controller should expose the number of
3797 	 * frames we're allowed to schedule, but there's no such
3798 	 * interface. The uhci(4) driver can buffer up to 128 frames
3799 	 * (or it crashes), ehci(4) starts recording null frames if we
3800 	 * exceed 256 (micro-)frames, ohci(4) works with at most 50
3801 	 * frames.
3802 	 */
3803 	switch (sc->udev->speed) {
3804 	case USB_SPEED_LOW:
3805 	case USB_SPEED_FULL:
3806 		sc->ufps = 1000;
3807 		sc->sync_pktsz = 3;
3808 		sc->host_nframes = 50;
3809 		break;
3810 	case USB_SPEED_HIGH:
3811 	case USB_SPEED_SUPER:
3812 		sc->ufps = 8000;
3813 		sc->sync_pktsz = 4;
3814 		sc->host_nframes = 240;
3815 		break;
3816 	default:
3817 		printf("%s: unsupported bus speed\n", DEVNAME(sc));
3818 		return;
3819 	}
3820 
3821 	if (!uaudio_process_conf(sc, &desc))
3822 		return;
3823 
3824 #ifdef UAUDIO_DEBUG
3825 	if (uaudio_debug)
3826 		uaudio_conf_print(sc);
3827 #endif
3828 	/* print a nice uaudio attach line */
3829 	uaudio_print(sc);
3830 
3831 	audio_attach_mi(&uaudio_hw_if, sc, arg->cookie, &sc->dev);
3832 }
3833 
3834 int
3835 uaudio_detach(struct device *self, int flags)
3836 {
3837 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
3838 	struct uaudio_unit *unit;
3839 	struct uaudio_params *params;
3840 	struct uaudio_alt *alt;
3841 	struct uaudio_name *name;
3842 	struct uaudio_mixent *mixent;
3843 	int rv;
3844 
3845 	rv = config_detach_children(self, flags);
3846 
3847 	usbd_ref_wait(sc->udev);
3848 
3849 	while ((alt = sc->alts) != NULL) {
3850 		sc->alts = alt->next;
3851 		free(alt, M_USBDEV, sizeof(struct uaudio_alt));
3852 	}
3853 
3854 	while ((params = sc->params_list) != NULL) {
3855 		sc->params_list = params->next;
3856 		free(params, M_USBDEV, sizeof(struct uaudio_params));
3857 	}
3858 
3859 	while ((unit = sc->unit_list) != NULL) {
3860 		sc->unit_list = unit->unit_next;
3861 		while ((mixent = unit->mixent_list) != NULL) {
3862 			unit->mixent_list = mixent->next;
3863 			uaudio_ranges_clear(&mixent->ranges);
3864 			free(mixent, M_USBDEV, sizeof(struct uaudio_mixent));
3865 		}
3866 		uaudio_ranges_clear(&unit->rates);
3867 		free(unit, M_USBDEV, sizeof(struct uaudio_unit));
3868 	}
3869 
3870 	while ((name = sc->names)) {
3871 		sc->names = name->next;
3872 		free(name, M_USBDEV, sizeof(struct uaudio_name));
3873 	}
3874 
3875 	return rv;
3876 }
3877 
3878 int
3879 uaudio_open(void *self, int flags)
3880 {
3881 	struct uaudio_softc *sc = self;
3882 	struct uaudio_params *p;
3883 
3884 	if (usbd_is_dying(sc->udev))
3885 		return EIO;
3886 
3887 	usbd_ref_incr(sc->udev);
3888 
3889 	flags &= (FREAD | FWRITE);
3890 
3891 	for (p = sc->params_list; p != NULL; p = p->next) {
3892 		switch (flags) {
3893 		case FWRITE:
3894 			if (!p->palt)
3895 				break;
3896 			sc->mode = AUMODE_PLAY;
3897 			return 0;
3898 		case FREAD:
3899 			if (!p->ralt)
3900 				break;
3901 			sc->mode = AUMODE_RECORD;
3902 			return 0;
3903 		case FREAD | FWRITE:
3904 			if (!(p->ralt && p->palt))
3905 				break;
3906 			sc->mode = AUMODE_RECORD | AUMODE_PLAY;
3907 			return 0;
3908 		}
3909 	}
3910 
3911 	usbd_ref_decr(sc->udev);
3912 	return ENXIO;
3913 }
3914 
3915 void
3916 uaudio_close(void *self)
3917 {
3918 	struct uaudio_softc *sc = self;
3919 
3920 	sc->mode = 0;
3921 	usbd_ref_decr(sc->udev);
3922 }
3923 
3924 int
3925 uaudio_set_params(void *self, int setmode, int usemode,
3926     struct audio_params *ap, struct audio_params *ar)
3927 {
3928 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
3929 	struct uaudio_params *p, *best_mode, *best_rate, *best_nch;
3930 	int rate, rateindex;
3931 
3932 #ifdef DIAGNOSTIC
3933 	if (setmode != usemode || setmode != sc->mode) {
3934 		printf("%s: bad call to uaudio_set_params()\n", DEVNAME(sc));
3935 		return EINVAL;
3936 	}
3937 	if (sc->mode == 0) {
3938 		printf("%s: uaudio_set_params(): not open\n", DEVNAME(sc));
3939 		return EINVAL;
3940 	}
3941 #endif
3942 	/*
3943 	 * audio(4) layer requests equal play and record rates
3944 	 */
3945 	rate = (sc->mode & AUMODE_PLAY) ? ap->sample_rate : ar->sample_rate;
3946 	rateindex = uaudio_rates_indexof(~0, rate);
3947 
3948 	DPRINTF("%s: rate %d -> %d (index %d)\n", __func__,
3949 	    rate, uaudio_rates[rateindex], rateindex);
3950 
3951 	best_mode = best_rate = best_nch = NULL;
3952 
3953 	for (p = sc->params_list; p != NULL; p = p->next) {
3954 
3955 		/* test if params match the requested mode */
3956 		if (sc->mode & AUMODE_PLAY) {
3957 			if (p->palt == NULL)
3958 				continue;
3959 		}
3960 		if (sc->mode & AUMODE_RECORD) {
3961 			if (p->ralt == NULL)
3962 				continue;
3963 		}
3964 		if (best_mode == NULL)
3965 			best_mode = p;
3966 
3967 		/* test if params match the requested rate */
3968 		if ((uaudio_getrates(sc, p) & (1 << rateindex)) == 0)
3969 			continue;
3970 		if (best_rate == NULL)
3971 			best_rate = p;
3972 
3973 		/* test if params match the requested channel counts */
3974 		if (sc->mode & AUMODE_PLAY) {
3975 			if (p->palt->nch != ap->channels)
3976 				continue;
3977 		}
3978 		if (sc->mode & AUMODE_RECORD) {
3979 			if (p->ralt->nch != ar->channels)
3980 				continue;
3981 		}
3982 		if (best_nch == NULL)
3983 			best_nch = p;
3984 
3985 		/* test if params match the requested precision */
3986 		if (sc->mode & AUMODE_PLAY) {
3987 			if (p->palt->bits != ap->precision)
3988 				continue;
3989 		}
3990 		if (sc->mode & AUMODE_RECORD) {
3991 			if (p->ralt->bits != ar->precision)
3992 				continue;
3993 		}
3994 
3995 		/* everything matched, we're done */
3996 		break;
3997 	}
3998 
3999 	if (p == NULL) {
4000 		if (best_nch)
4001 			p = best_nch;
4002 		else if (best_rate)
4003 			p = best_rate;
4004 		else if (best_mode)
4005 			p = best_mode;
4006 		else
4007 			return ENOTTY;
4008 	}
4009 
4010 	/*
4011 	 * Recalculate rate index, because the chosen parameters
4012 	 * may not support the requested one
4013 	 */
4014 	rateindex = uaudio_rates_indexof(uaudio_getrates(sc, p), rate);
4015 	if (rateindex < 0)
4016 		return ENOTTY;
4017 
4018 	sc->params = p;
4019 	sc->rate = uaudio_rates[rateindex];
4020 
4021 	DPRINTF("%s: rate = %u\n", __func__, sc->rate);
4022 
4023 	if (sc->mode & AUMODE_PLAY) {
4024 		ap->sample_rate = sc->rate;
4025 		ap->precision = p->palt->bits;
4026 		ap->encoding = AUDIO_ENCODING_SLINEAR_LE;
4027 		ap->bps = p->palt->bps;
4028 		ap->msb = 1;
4029 		ap->channels = p->palt->nch;
4030 	}
4031 	if (sc->mode & AUMODE_RECORD) {
4032 		ar->sample_rate = sc->rate;
4033 		ar->precision = p->ralt->bits;
4034 		ar->encoding = AUDIO_ENCODING_SLINEAR_LE;
4035 		ar->bps = p->ralt->bps;
4036 		ar->msb = 1;
4037 		ar->channels = p->ralt->nch;
4038 	}
4039 
4040 	return 0;
4041 }
4042 
4043 unsigned int
4044 uaudio_set_blksz(void *self, int mode,
4045     struct audio_params *p, struct audio_params *r, unsigned int blksz)
4046 {
4047 	struct uaudio_softc *sc = self;
4048 	unsigned int fps, fps_min;
4049 	unsigned int blksz_max, blksz_min;
4050 
4051 	/*
4052 	 * minimum block size is two transfers, see uaudio_stream_open()
4053 	 */
4054 	fps_min = sc->ufps;
4055 	if (mode & AUMODE_PLAY) {
4056 		fps = sc->params->palt->fps;
4057 		if (fps_min > fps)
4058 			fps_min = fps;
4059 	}
4060 	if (mode & AUMODE_RECORD) {
4061 		fps = sc->params->ralt->fps;
4062 		if (fps_min > fps)
4063 			fps_min = fps;
4064 	}
4065 	blksz_min = (sc->rate * 2 + fps_min - 1) / fps_min;
4066 
4067 	/*
4068 	 * max block size is only limited by the number of frames the
4069 	 * host can schedule
4070 	 */
4071 	blksz_max = sc->rate * (sc->host_nframes / UAUDIO_NXFERS_MIN) /
4072 	    sc->ufps * 85 / 100;
4073 
4074 	if (blksz > blksz_max)
4075 		blksz = blksz_max;
4076 	else if (blksz < blksz_min)
4077 		blksz = blksz_min;
4078 
4079 	return blksz;
4080 }
4081 
4082 int
4083 uaudio_trigger_output(void *self, void *start, void *end, int blksz,
4084     void (*intr)(void *), void *arg, struct audio_params *param)
4085 {
4086 	struct uaudio_softc *sc = self;
4087 	int err;
4088 
4089 	err = uaudio_stream_open(sc,
4090 	    AUMODE_PLAY, start, end, blksz, intr, arg);
4091 	if (err)
4092 		return err;
4093 
4094 	sc->trigger_mode |= AUMODE_PLAY;
4095 	uaudio_trigger(sc);
4096 	return 0;
4097 }
4098 
4099 int
4100 uaudio_trigger_input(void *self, void *start, void *end, int blksz,
4101     void (*intr)(void *), void *arg, struct audio_params *param)
4102 {
4103 	struct uaudio_softc *sc = self;
4104 	int err;
4105 
4106 	err = uaudio_stream_open(sc,
4107 	    AUMODE_RECORD, start, end, blksz, intr, arg);
4108 	if (err)
4109 		return err;
4110 
4111 	sc->trigger_mode |= AUMODE_RECORD;
4112 	uaudio_trigger(sc);
4113 	return 0;
4114 }
4115 
4116 void
4117 uaudio_copy_output(void *self, size_t todo)
4118 {
4119 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
4120 	int s;
4121 
4122 	s = splusb();
4123 	sc->copy_todo += todo;
4124 
4125 #ifdef UAUDIO_DEBUG
4126 	if (uaudio_debug >= 3) {
4127 		printf("%s: copy_todo -> %zd (+%zd)\n", __func__,
4128 		    sc->copy_todo, todo);
4129 	}
4130 #endif
4131 
4132 	if (sc->mode == sc->trigger_mode)
4133 		uaudio_pdata_copy(sc);
4134 	splx(s);
4135 }
4136 
4137 void
4138 uaudio_underrun(void *self)
4139 {
4140 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
4141 	struct uaudio_stream *s = &sc->pstream;
4142 
4143 	sc->copy_todo += s->ring_blksz;
4144 
4145 #ifdef UAUDIO_DEBUG
4146 	if (uaudio_debug >= 3)
4147 		printf("%s: copy_todo -> %zd\n", __func__, sc->copy_todo);
4148 #endif
4149 
4150 	/* copy data (actually silence) produced by the audio(4) layer */
4151 	uaudio_pdata_copy(sc);
4152 }
4153 
4154 int
4155 uaudio_halt_output(void *self)
4156 {
4157 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
4158 
4159 	uaudio_stream_close(sc, AUMODE_PLAY);
4160 	sc->trigger_mode &= ~AUMODE_PLAY;
4161 	sc->copy_todo = 0;
4162 	return 0;
4163 }
4164 
4165 int
4166 uaudio_halt_input(void *self)
4167 {
4168 	struct uaudio_softc *sc = (struct uaudio_softc *)self;
4169 
4170 	uaudio_stream_close(sc, AUMODE_RECORD);
4171 	sc->trigger_mode &= ~AUMODE_RECORD;
4172 	return 0;
4173 }
4174 
4175 int
4176 uaudio_get_port_do(struct uaudio_softc *sc, struct mixer_ctrl *ctl)
4177 {
4178 	struct uaudio_unit *u;
4179 	struct uaudio_mixent *m;
4180 	unsigned char req_buf[4];
4181 	struct uaudio_blob p;
4182 	int i, nch, val, req_num;
4183 
4184 	if (!uaudio_mixer_byindex(sc, ctl->dev, &u, &m))
4185 		return ENOENT;
4186 
4187 	switch (sc->version) {
4188 	case UAUDIO_V1:
4189 		req_num = UAUDIO_V1_REQ_GET_CUR;
4190 		break;
4191 	case UAUDIO_V2:
4192 		req_num = UAUDIO_V2_REQ_CUR;
4193 	}
4194 
4195 	switch (m->type) {
4196 	case UAUDIO_MIX_SW:
4197 		p.rptr = p.wptr = req_buf;
4198 		if (!uaudio_req(sc,
4199 			UT_READ_CLASS_INTERFACE,
4200 			req_num,
4201 			m->req_sel,
4202 			m->chan < 0 ? 0 : m->chan,
4203 			sc->ctl_ifnum,
4204 			u->id,
4205 			req_buf,
4206 			1))
4207 			return EIO;
4208 		p.wptr++;
4209 		if (!uaudio_getnum(&p, 1, &val))
4210 			return EIO;
4211 		ctl->un.ord = !!val;
4212 		break;
4213 	case UAUDIO_MIX_NUM:
4214 		nch = uaudio_mixer_nchan(m, NULL);
4215 		ctl->un.value.num_channels = nch;
4216 		for (i = 0; i < nch; i++) {
4217 			p.rptr = p.wptr = req_buf;
4218 			if (!uaudio_req(sc,
4219 				UT_READ_CLASS_INTERFACE,
4220 				req_num,
4221 				m->req_sel,
4222 				m->chan < 0 ? 0 : i + 1,
4223 				sc->ctl_ifnum,
4224 				u->id,
4225 				req_buf,
4226 				2))
4227 				return EIO;
4228 			p.wptr += 2;
4229 			if (!uaudio_getnum(&p, 2, &val))
4230 				return EIO;
4231 			ctl->un.value.level[i] =
4232 			    uaudio_ranges_decode(&m->ranges,
4233 				uaudio_sign_expand(val, 2));
4234 			m = m->next;
4235 		}
4236 		break;
4237 	case UAUDIO_MIX_ENUM:
4238 		/* XXX: not used yet */
4239 		break;
4240 	}
4241 	return 0;
4242 }
4243 
4244 int
4245 uaudio_set_port_do(struct uaudio_softc *sc, struct mixer_ctrl *ctl)
4246 {
4247 	struct uaudio_unit *u;
4248 	struct uaudio_mixent *m;
4249 	unsigned char req_buf[4];
4250 	unsigned int val;
4251 	int i, nch;
4252 
4253 	if (!uaudio_mixer_byindex(sc, ctl->dev, &u, &m))
4254 		return ENOENT;
4255 
4256 	switch (m->type) {
4257 	case UAUDIO_MIX_SW:
4258 		if (ctl->un.ord < 0 || ctl->un.ord > 1)
4259 			return EINVAL;
4260 		req_buf[0] = ctl->un.ord;
4261 		if (!uaudio_req(sc,
4262 			UT_WRITE_CLASS_INTERFACE,
4263 			UAUDIO_V1_REQ_SET_CUR,
4264 			m->req_sel,
4265 			m->chan < 0 ? 0 : m->chan,
4266 			sc->ctl_ifnum,
4267 			u->id,
4268 			req_buf,
4269 			1))
4270 			return EIO;
4271 		break;
4272 	case UAUDIO_MIX_NUM:
4273 		nch = uaudio_mixer_nchan(m, NULL);
4274 		ctl->un.value.num_channels = nch;
4275 		for (i = 0; i < nch; i++) {
4276 			val = uaudio_ranges_encode(&m->ranges,
4277 			    ctl->un.value.level[i]);
4278 			DPRINTF("%s: ch %d, ctl %d, num val %d\n", __func__,
4279 			    i, ctl->un.value.level[i], val);
4280 			req_buf[0] = val;
4281 			req_buf[1] = val >> 8;
4282 			if (!uaudio_req(sc,
4283 				UT_WRITE_CLASS_INTERFACE,
4284 				UAUDIO_V1_REQ_SET_CUR,
4285 				m->req_sel,
4286 				m->chan < 0 ? 0 : i + 1,
4287 				sc->ctl_ifnum,
4288 				u->id,
4289 				req_buf,
4290 				2))
4291 				return EIO;
4292 			m = m->next;
4293 		}
4294 		break;
4295 	case UAUDIO_MIX_ENUM:
4296 		/* XXX: not used yet */
4297 		break;
4298 	}
4299 	return 0;
4300 }
4301 
4302 int
4303 uaudio_query_devinfo_do(struct uaudio_softc *sc, struct mixer_devinfo *devinfo)
4304 {
4305 	struct uaudio_unit *u;
4306 	struct uaudio_mixent *m;
4307 
4308 	devinfo->next = -1;
4309 	devinfo->prev = -1;
4310 	switch (devinfo->index) {
4311 	case UAUDIO_CLASS_IN:
4312 		strlcpy(devinfo->label.name, AudioCinputs, MAX_AUDIO_DEV_LEN);
4313 		devinfo->type = AUDIO_MIXER_CLASS;
4314 		devinfo->mixer_class = -1;
4315 		return 0;
4316 	case UAUDIO_CLASS_OUT:
4317 		strlcpy(devinfo->label.name, AudioCoutputs, MAX_AUDIO_DEV_LEN);
4318 		devinfo->type = AUDIO_MIXER_CLASS;
4319 		devinfo->mixer_class = -1;
4320 		return 0;
4321 	}
4322 
4323 	/*
4324 	 * find the unit & mixent structure for the given index
4325 	 */
4326 	if (!uaudio_mixer_byindex(sc, devinfo->index, &u, &m))
4327 		return ENOENT;
4328 
4329 	if (strcmp(m->fname, "level") == 0) {
4330 		/*
4331 		 * mixer(4) interface doesn't give a names to level
4332 		 * controls
4333 		 */
4334 		strlcpy(devinfo->label.name, u->name, MAX_AUDIO_DEV_LEN);
4335 	} else {
4336 		if (m->chan == -1) {
4337 			snprintf(devinfo->label.name, MAX_AUDIO_DEV_LEN,
4338 			    "%s_%s", u->name, m->fname);
4339 		} else {
4340 			snprintf(devinfo->label.name, MAX_AUDIO_DEV_LEN,
4341 			    "%s_%s%u", u->name, m->fname, m->chan);
4342 		}
4343 	}
4344 
4345 	devinfo->mixer_class = u->mixer_class;
4346 	switch (m->type) {
4347 	case UAUDIO_MIX_SW:
4348 		devinfo->type = AUDIO_MIXER_ENUM;
4349 		devinfo->un.e.num_mem = 2;
4350 		devinfo->un.e.member[0].ord = 0;
4351 		strlcpy(devinfo->un.e.member[0].label.name, "off",
4352 		    MAX_AUDIO_DEV_LEN);
4353 		devinfo->un.e.member[1].ord = 1;
4354 		strlcpy(devinfo->un.e.member[1].label.name, "on",
4355 		    MAX_AUDIO_DEV_LEN);
4356 		break;
4357 	case UAUDIO_MIX_NUM:
4358 		devinfo->type = AUDIO_MIXER_VALUE;
4359 		devinfo->un.v.num_channels = uaudio_mixer_nchan(m, NULL);
4360 		devinfo->un.v.delta = 1;
4361 		break;
4362 	case UAUDIO_MIX_ENUM:
4363 		/* XXX: not used yet */
4364 		devinfo->type = AUDIO_MIXER_ENUM;
4365 		devinfo->un.e.num_mem = 0;
4366 		break;
4367 	}
4368 	return 0;
4369 }
4370 
4371 int
4372 uaudio_get_port(void *arg, struct mixer_ctrl *ctl)
4373 {
4374 	struct uaudio_softc *sc = arg;
4375 	int rc;
4376 
4377 	usbd_ref_incr(sc->udev);
4378 	rc = uaudio_get_port_do(sc, ctl);
4379 	usbd_ref_decr(sc->udev);
4380 	return rc;
4381 }
4382 
4383 int
4384 uaudio_set_port(void *arg, struct mixer_ctrl *ctl)
4385 {
4386 	struct uaudio_softc *sc = arg;
4387 	int rc;
4388 
4389 	usbd_ref_incr(sc->udev);
4390 	rc = uaudio_set_port_do(sc, ctl);
4391 	usbd_ref_decr(sc->udev);
4392 	return rc;
4393 }
4394 
4395 int
4396 uaudio_query_devinfo(void *arg, struct mixer_devinfo *devinfo)
4397 {
4398 	struct uaudio_softc *sc = arg;
4399 	int rc;
4400 
4401 	usbd_ref_incr(sc->udev);
4402 	rc = uaudio_query_devinfo_do(sc, devinfo);
4403 	usbd_ref_decr(sc->udev);
4404 	return rc;
4405 }
4406