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