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