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