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