xref: /freebsd/sys/dev/sound/pcm/channel.c (revision 9d18115ca0ab0ef3f34173d4e2bdabec916d0b60)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2005-2009 Ariff Abdullah <ariff@FreeBSD.org>
5  * Portions Copyright (c) Ryan Beasley <ryan.beasley@gmail.com> - GSoC 2006
6  * Copyright (c) 1999 Cameron Grant <cg@FreeBSD.org>
7  * Portions Copyright (c) Luigi Rizzo <luigi@FreeBSD.org> - 1997-99
8  * All rights reserved.
9  * Copyright (c) 2024-2025 The FreeBSD Foundation
10  *
11  * Portions of this software were developed by Christos Margiolis
12  * <christos@FreeBSD.org> under sponsorship from the FreeBSD Foundation.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifdef HAVE_KERNEL_OPTION_HEADERS
37 #include "opt_snd.h"
38 #endif
39 
40 #include <dev/sound/pcm/sound.h>
41 #include <dev/sound/pcm/vchan.h>
42 
43 #include "feeder_if.h"
44 
45 int report_soft_formats = 1;
46 SYSCTL_INT(_hw_snd, OID_AUTO, report_soft_formats, CTLFLAG_RW,
47 	&report_soft_formats, 0, "report software-emulated formats");
48 
49 int report_soft_matrix = 1;
50 SYSCTL_INT(_hw_snd, OID_AUTO, report_soft_matrix, CTLFLAG_RW,
51 	&report_soft_matrix, 0, "report software-emulated channel matrixing");
52 
53 int chn_latency = CHN_LATENCY_DEFAULT;
54 
55 static int
sysctl_hw_snd_latency(SYSCTL_HANDLER_ARGS)56 sysctl_hw_snd_latency(SYSCTL_HANDLER_ARGS)
57 {
58 	int err, val;
59 
60 	val = chn_latency;
61 	err = sysctl_handle_int(oidp, &val, 0, req);
62 	if (err != 0 || req->newptr == NULL)
63 		return err;
64 	if (val < CHN_LATENCY_MIN || val > CHN_LATENCY_MAX)
65 		err = EINVAL;
66 	else
67 		chn_latency = val;
68 
69 	return err;
70 }
71 SYSCTL_PROC(_hw_snd, OID_AUTO, latency,
72     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, sizeof(int),
73     sysctl_hw_snd_latency, "I",
74     "buffering latency (0=low ... 10=high)");
75 
76 int chn_latency_profile = CHN_LATENCY_PROFILE_DEFAULT;
77 
78 static int
sysctl_hw_snd_latency_profile(SYSCTL_HANDLER_ARGS)79 sysctl_hw_snd_latency_profile(SYSCTL_HANDLER_ARGS)
80 {
81 	int err, val;
82 
83 	val = chn_latency_profile;
84 	err = sysctl_handle_int(oidp, &val, 0, req);
85 	if (err != 0 || req->newptr == NULL)
86 		return err;
87 	if (val < CHN_LATENCY_PROFILE_MIN || val > CHN_LATENCY_PROFILE_MAX)
88 		err = EINVAL;
89 	else
90 		chn_latency_profile = val;
91 
92 	return err;
93 }
94 SYSCTL_PROC(_hw_snd, OID_AUTO, latency_profile,
95     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, sizeof(int),
96     sysctl_hw_snd_latency_profile, "I",
97     "buffering latency profile (0=aggressive 1=safe)");
98 
99 static int chn_timeout = CHN_TIMEOUT;
100 
101 static int
sysctl_hw_snd_timeout(SYSCTL_HANDLER_ARGS)102 sysctl_hw_snd_timeout(SYSCTL_HANDLER_ARGS)
103 {
104 	int err, val;
105 
106 	val = chn_timeout;
107 	err = sysctl_handle_int(oidp, &val, 0, req);
108 	if (err != 0 || req->newptr == NULL)
109 		return err;
110 	if (val < CHN_TIMEOUT_MIN || val > CHN_TIMEOUT_MAX)
111 		err = EINVAL;
112 	else
113 		chn_timeout = val;
114 
115 	return err;
116 }
117 SYSCTL_PROC(_hw_snd, OID_AUTO, timeout,
118     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, sizeof(int),
119     sysctl_hw_snd_timeout, "I",
120     "interrupt timeout (1 - 10) seconds");
121 
122 static int chn_vpc_autoreset = 1;
123 SYSCTL_INT(_hw_snd, OID_AUTO, vpc_autoreset, CTLFLAG_RWTUN,
124 	&chn_vpc_autoreset, 0, "automatically reset channels volume to 0db");
125 
126 static int chn_vol_0db_pcm = SND_VOL_0DB_PCM;
127 
128 static void
chn_vpc_proc(int reset,int db)129 chn_vpc_proc(int reset, int db)
130 {
131 	struct snddev_info *d;
132 	struct pcm_channel *c;
133 	int i;
134 
135 	bus_topo_lock();
136 	for (i = 0; pcm_devclass != NULL &&
137 	    i < devclass_get_maxunit(pcm_devclass); i++) {
138 		d = devclass_get_softc(pcm_devclass, i);
139 		if (!PCM_REGISTERED(d))
140 			continue;
141 		PCM_LOCK(d);
142 		PCM_WAIT(d);
143 		PCM_ACQUIRE(d);
144 		CHN_FOREACH(c, d, channels.pcm) {
145 			CHN_LOCK(c);
146 			CHN_SETVOLUME(c, SND_VOL_C_PCM, SND_CHN_T_VOL_0DB, db);
147 			if (reset != 0)
148 				chn_vpc_reset(c, SND_VOL_C_PCM, 1);
149 			CHN_UNLOCK(c);
150 		}
151 		PCM_RELEASE(d);
152 		PCM_UNLOCK(d);
153 	}
154 	bus_topo_unlock();
155 }
156 
157 static int
sysctl_hw_snd_vpc_0db(SYSCTL_HANDLER_ARGS)158 sysctl_hw_snd_vpc_0db(SYSCTL_HANDLER_ARGS)
159 {
160 	int err, val;
161 
162 	val = chn_vol_0db_pcm;
163 	err = sysctl_handle_int(oidp, &val, 0, req);
164 	if (err != 0 || req->newptr == NULL)
165 		return (err);
166 	if (val < SND_VOL_0DB_MIN || val > SND_VOL_0DB_MAX)
167 		return (EINVAL);
168 
169 	chn_vol_0db_pcm = val;
170 	chn_vpc_proc(0, val);
171 
172 	return (0);
173 }
174 SYSCTL_PROC(_hw_snd, OID_AUTO, vpc_0db,
175     CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, sizeof(int),
176     sysctl_hw_snd_vpc_0db, "I",
177     "0db relative level");
178 
179 static int
sysctl_hw_snd_vpc_reset(SYSCTL_HANDLER_ARGS)180 sysctl_hw_snd_vpc_reset(SYSCTL_HANDLER_ARGS)
181 {
182 	int err, val;
183 
184 	val = 0;
185 	err = sysctl_handle_int(oidp, &val, 0, req);
186 	if (err != 0 || req->newptr == NULL || val == 0)
187 		return (err);
188 
189 	chn_vol_0db_pcm = SND_VOL_0DB_PCM;
190 	chn_vpc_proc(1, SND_VOL_0DB_PCM);
191 
192 	return (0);
193 }
194 SYSCTL_PROC(_hw_snd, OID_AUTO, vpc_reset,
195     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, sizeof(int),
196     sysctl_hw_snd_vpc_reset, "I",
197     "reset volume on all channels");
198 
199 static int chn_usefrags = 0;
200 static int chn_syncdelay = -1;
201 
202 SYSCTL_INT(_hw_snd, OID_AUTO, usefrags, CTLFLAG_RWTUN,
203 	&chn_usefrags, 0, "prefer setfragments() over setblocksize()");
204 SYSCTL_INT(_hw_snd, OID_AUTO, syncdelay, CTLFLAG_RWTUN,
205 	&chn_syncdelay, 0,
206 	"append (0-1000) millisecond trailing buffer delay on each sync");
207 
208 /**
209  * @brief Channel sync group lock
210  *
211  * Clients should acquire this lock @b without holding any channel locks
212  * before touching syncgroups or the main syncgroup list.
213  */
214 struct mtx snd_pcm_syncgroups_mtx;
215 MTX_SYSINIT(pcm_syncgroup, &snd_pcm_syncgroups_mtx, "PCM channel sync group lock", MTX_DEF);
216 /**
217  * @brief syncgroups' master list
218  *
219  * Each time a channel syncgroup is created, it's added to this list.  This
220  * list should only be accessed with @sa snd_pcm_syncgroups_mtx held.
221  *
222  * See SNDCTL_DSP_SYNCGROUP for more information.
223  */
224 struct pcm_synclist snd_pcm_syncgroups = SLIST_HEAD_INITIALIZER(snd_pcm_syncgroups);
225 
226 static void
chn_lockinit(struct pcm_channel * c,int dir)227 chn_lockinit(struct pcm_channel *c, int dir)
228 {
229 	switch (dir) {
230 	case PCMDIR_PLAY:
231 		mtx_init(&c->lock, c->name, "pcm play channel", MTX_DEF);
232 		cv_init(&c->intr_cv, "pcmwr");
233 		break;
234 	case PCMDIR_PLAY_VIRTUAL:
235 		mtx_init(&c->lock, c->name, "pcm virtual play channel",
236 		    MTX_DEF);
237 		cv_init(&c->intr_cv, "pcmwrv");
238 		break;
239 	case PCMDIR_REC:
240 		mtx_init(&c->lock, c->name, "pcm record channel", MTX_DEF);
241 		cv_init(&c->intr_cv, "pcmrd");
242 		break;
243 	case PCMDIR_REC_VIRTUAL:
244 		mtx_init(&c->lock, c->name, "pcm virtual record channel",
245 		    MTX_DEF);
246 		cv_init(&c->intr_cv, "pcmrdv");
247 		break;
248 	default:
249 		panic("%s(): Invalid direction=%d", __func__, dir);
250 		break;
251 	}
252 
253 	cv_init(&c->cv, "pcmchn");
254 }
255 
256 static void
chn_lockdestroy(struct pcm_channel * c)257 chn_lockdestroy(struct pcm_channel *c)
258 {
259 	CHN_LOCKASSERT(c);
260 
261 	CHN_BROADCAST(&c->cv);
262 	CHN_BROADCAST(&c->intr_cv);
263 
264 	cv_destroy(&c->cv);
265 	cv_destroy(&c->intr_cv);
266 
267 	mtx_destroy(&c->lock);
268 }
269 
270 /**
271  * @brief Determine channel is ready for I/O
272  *
273  * @retval 1 = ready for I/O
274  * @retval 0 = not ready for I/O
275  */
276 int
chn_polltrigger(struct pcm_channel * c)277 chn_polltrigger(struct pcm_channel *c)
278 {
279 	struct snd_dbuf *bs = c->bufsoft;
280 	u_int delta;
281 
282 	CHN_LOCKASSERT(c);
283 
284 	if (c->flags & CHN_F_MMAP) {
285 		if (bs->prev_total < c->lw)
286 			delta = c->lw;
287 		else
288 			delta = bs->total - bs->prev_total;
289 	} else {
290 		if (c->direction == PCMDIR_PLAY)
291 			delta = sndbuf_getfree(bs);
292 		else
293 			delta = sndbuf_getready(bs);
294 	}
295 
296 	return ((delta < c->lw) ? 0 : 1);
297 }
298 
299 static void
chn_pollreset(struct pcm_channel * c)300 chn_pollreset(struct pcm_channel *c)
301 {
302 
303 	CHN_LOCKASSERT(c);
304 	c->bufsoft->prev_total = c->bufsoft->total;
305 }
306 
307 static void
chn_wakeup(struct pcm_channel * c)308 chn_wakeup(struct pcm_channel *c)
309 {
310 	struct snd_dbuf *bs;
311 	struct pcm_channel *ch;
312 
313 	CHN_LOCKASSERT(c);
314 
315 	bs = c->bufsoft;
316 
317 	if (CHN_EMPTY(c, children.busy)) {
318 		KNOTE_LOCKED(&bs->sel.si_note, 0);
319 		if (SEL_WAITING(&bs->sel) && chn_polltrigger(c))
320 			selwakeuppri(&bs->sel, PRIBIO);
321 		CHN_BROADCAST(&c->intr_cv);
322 	} else {
323 		CHN_FOREACH(ch, c, children.busy) {
324 			CHN_LOCK(ch);
325 			chn_wakeup(ch);
326 			CHN_UNLOCK(ch);
327 		}
328 	}
329 }
330 
331 static int
chn_sleep(struct pcm_channel * c,int timeout)332 chn_sleep(struct pcm_channel *c, int timeout)
333 {
334 	int ret;
335 
336 	CHN_LOCKASSERT(c);
337 
338 	if (c->flags & CHN_F_DEAD)
339 		return (EINVAL);
340 
341 	c->sleeping++;
342 	ret = cv_timedwait_sig(&c->intr_cv, &c->lock, timeout);
343 	c->sleeping--;
344 
345 	return ((c->flags & CHN_F_DEAD) ? EINVAL : ret);
346 }
347 
348 /*
349  * chn_dmaupdate() tracks the status of a dma transfer,
350  * updating pointers.
351  */
352 
353 static unsigned int
chn_dmaupdate(struct pcm_channel * c)354 chn_dmaupdate(struct pcm_channel *c)
355 {
356 	struct snd_dbuf *b = c->bufhard;
357 	unsigned int delta, old, hwptr, amt;
358 
359 	KASSERT(b->bufsize > 0, ("bufsize == 0"));
360 	CHN_LOCKASSERT(c);
361 
362 	old = b->hp;
363 	hwptr = chn_getptr(c);
364 	delta = (b->bufsize + hwptr - old) % b->bufsize;
365 	b->hp = hwptr;
366 
367 	if (c->direction == PCMDIR_PLAY) {
368 		amt = min(delta, sndbuf_getready(b));
369 		amt -= amt % b->align;
370 		if (amt > 0)
371 			sndbuf_dispose(b, NULL, amt);
372 	} else {
373 		amt = min(delta, sndbuf_getfree(b));
374 		amt -= amt % b->align;
375 		if (amt > 0)
376 		       sndbuf_acquire(b, NULL, amt);
377 	}
378 	if (snd_verbose > 3 && CHN_STARTED(c) && delta == 0) {
379 		device_printf(c->dev, "WARNING: %s DMA completion "
380 			"too fast/slow ! hwptr=%u, old=%u "
381 			"delta=%u amt=%u ready=%u free=%u\n",
382 			CHN_DIRSTR(c), hwptr, old, delta, amt,
383 			sndbuf_getready(b), sndbuf_getfree(b));
384 	}
385 
386 	return delta;
387 }
388 
389 static void
chn_wrfeed(struct pcm_channel * c)390 chn_wrfeed(struct pcm_channel *c)
391 {
392     	struct snd_dbuf *b = c->bufhard;
393     	struct snd_dbuf *bs = c->bufsoft;
394 	unsigned int amt, want, wasfree;
395 
396 	CHN_LOCKASSERT(c);
397 
398 	if ((c->flags & CHN_F_MMAP) && !(c->flags & CHN_F_CLOSING))
399 		sndbuf_acquire(bs, NULL, sndbuf_getfree(bs));
400 
401 	wasfree = sndbuf_getfree(b);
402 	want = min(b->bufsize, imax(0, sndbuf_xbytes(bs->bufsize, bs, b) -
403 	     sndbuf_getready(b)));
404 	amt = min(wasfree, want);
405 	if (amt > 0)
406 		sndbuf_feed(bs, b, c, c->feeder, amt);
407 
408 	/*
409 	 * Possible xruns. There should be no empty space left in buffer.
410 	 */
411 	if (sndbuf_getready(b) < want)
412 		c->xruns++;
413 
414 	if (sndbuf_getfree(b) < wasfree)
415 		chn_wakeup(c);
416 }
417 
418 static void
chn_wrintr(struct pcm_channel * c)419 chn_wrintr(struct pcm_channel *c)
420 {
421 
422 	CHN_LOCKASSERT(c);
423 	/* update pointers in primary buffer */
424 	chn_dmaupdate(c);
425 	/* ...and feed from secondary to primary */
426 	chn_wrfeed(c);
427 	/* tell the driver we've updated the primary buffer */
428 	chn_trigger(c, PCMTRIG_EMLDMAWR);
429 }
430 
431 /*
432  * user write routine - uiomove data into secondary buffer, trigger if necessary
433  * if blocking, sleep, rinse and repeat.
434  *
435  * called externally, so must handle locking
436  */
437 
438 int
chn_write(struct pcm_channel * c,struct uio * buf)439 chn_write(struct pcm_channel *c, struct uio *buf)
440 {
441 	struct snd_dbuf *bs = c->bufsoft;
442 	void *off;
443 	int ret, timeout, sz, p;
444 
445 	CHN_LOCKASSERT(c);
446 
447 	ret = 0;
448 	timeout = chn_timeout * hz;
449 
450 	while (ret == 0 && buf->uio_resid > 0) {
451 		p = sndbuf_getfreeptr(bs);
452 		sz = min(buf->uio_resid, sndbuf_getfree(bs));
453 		sz = min(sz, bs->bufsize - p);
454 		if (sz > 0) {
455 			off = sndbuf_getbufofs(bs, p);
456 			sndbuf_acquire(bs, NULL, sz);
457 			CHN_UNLOCK(c);
458 			ret = uiomove(off, sz, buf);
459 			CHN_LOCK(c);
460 			if (ret != 0)
461 				break;
462 			if (CHN_STOPPED(c) && !(c->flags & CHN_F_NOTRIGGER)) {
463 				ret = chn_start(c, 0);
464 				if (ret != 0)
465 					c->flags |= CHN_F_DEAD;
466 			}
467 		} else if (c->flags & (CHN_F_NBIO | CHN_F_NOTRIGGER)) {
468 			/**
469 			 * @todo Evaluate whether EAGAIN is truly desirable.
470 			 * 	 4Front drivers behave like this, but I'm
471 			 * 	 not sure if it at all violates the "write
472 			 * 	 should be allowed to block" model.
473 			 *
474 			 * 	 The idea is that, while set with CHN_F_NOTRIGGER,
475 			 * 	 a channel isn't playing, *but* without this we
476 			 * 	 end up with "interrupt timeout / channel dead".
477 			 */
478 			ret = EAGAIN;
479 		} else {
480    			ret = chn_sleep(c, timeout);
481 			if (ret == ERESTART || ret == EINTR)
482 				c->flags |= CHN_F_ABORTING;
483 		}
484 	}
485 
486 	return (ret);
487 }
488 
489 /*
490  * Feed new data from the read buffer. Can be called in the bottom half.
491  */
492 static void
chn_rdfeed(struct pcm_channel * c)493 chn_rdfeed(struct pcm_channel *c)
494 {
495     	struct snd_dbuf *b = c->bufhard;
496     	struct snd_dbuf *bs = c->bufsoft;
497 	unsigned int amt;
498 
499 	CHN_LOCKASSERT(c);
500 
501 	if (c->flags & CHN_F_MMAP)
502 		sndbuf_dispose(bs, NULL, sndbuf_getready(bs));
503 
504 	amt = sndbuf_getfree(bs);
505 	if (amt > 0)
506 		sndbuf_feed(b, bs, c, c->feeder, amt);
507 
508 	amt = sndbuf_getready(b);
509 	if (amt > 0) {
510 		c->xruns++;
511 		sndbuf_dispose(b, NULL, amt);
512 	}
513 
514 	if (sndbuf_getready(bs) > 0)
515 		chn_wakeup(c);
516 }
517 
518 /* read interrupt routine. Must be called with interrupts blocked. */
519 static void
chn_rdintr(struct pcm_channel * c)520 chn_rdintr(struct pcm_channel *c)
521 {
522 
523 	CHN_LOCKASSERT(c);
524 	/* tell the driver to update the primary buffer if non-dma */
525 	chn_trigger(c, PCMTRIG_EMLDMARD);
526 	/* update pointers in primary buffer */
527 	chn_dmaupdate(c);
528 	/* ...and feed from primary to secondary */
529 	chn_rdfeed(c);
530 }
531 
532 /*
533  * user read routine - trigger if necessary, uiomove data from secondary buffer
534  * if blocking, sleep, rinse and repeat.
535  *
536  * called externally, so must handle locking
537  */
538 
539 int
chn_read(struct pcm_channel * c,struct uio * buf)540 chn_read(struct pcm_channel *c, struct uio *buf)
541 {
542 	struct snd_dbuf *bs = c->bufsoft;
543 	void *off;
544 	int ret, timeout, sz, p;
545 
546 	CHN_LOCKASSERT(c);
547 
548 	if (CHN_STOPPED(c) && !(c->flags & CHN_F_NOTRIGGER)) {
549 		ret = chn_start(c, 0);
550 		if (ret != 0) {
551 			c->flags |= CHN_F_DEAD;
552 			return (ret);
553 		}
554 	}
555 
556 	ret = 0;
557 	timeout = chn_timeout * hz;
558 
559 	while (ret == 0 && buf->uio_resid > 0) {
560 		p = sndbuf_getreadyptr(bs);
561 		sz = min(buf->uio_resid, sndbuf_getready(bs));
562 		sz = min(sz, bs->bufsize - p);
563 		if (sz > 0) {
564 			off = sndbuf_getbufofs(bs, p);
565 			sndbuf_dispose(bs, NULL, sz);
566 			CHN_UNLOCK(c);
567 			ret = uiomove(off, sz, buf);
568 			CHN_LOCK(c);
569 			if (ret != 0)
570 				break;
571 		} else if (c->flags & (CHN_F_NBIO | CHN_F_NOTRIGGER))
572 			ret = EAGAIN;
573 		else {
574    			ret = chn_sleep(c, timeout);
575 			if (ret == ERESTART || ret == EINTR)
576 				c->flags |= CHN_F_ABORTING;
577 		}
578 	}
579 
580 	return (ret);
581 }
582 
583 void
chn_intr(struct pcm_channel * c)584 chn_intr(struct pcm_channel *c)
585 {
586 	CHN_LOCK(c);
587 	c->interrupts++;
588 	if (c->direction == PCMDIR_PLAY)
589 		chn_wrintr(c);
590 	else
591 		chn_rdintr(c);
592 	CHN_UNLOCK(c);
593 }
594 
595 u_int32_t
chn_start(struct pcm_channel * c,int force)596 chn_start(struct pcm_channel *c, int force)
597 {
598 	u_int32_t i, j;
599 	struct snd_dbuf *b = c->bufhard;
600 	struct snd_dbuf *bs = c->bufsoft;
601 	int err;
602 
603 	CHN_LOCKASSERT(c);
604 	/* if we're running, or if we're prevented from triggering, bail */
605 	if (CHN_STARTED(c) || ((c->flags & CHN_F_NOTRIGGER) && !force))
606 		return (EINVAL);
607 
608 	err = 0;
609 
610 	if (force) {
611 		i = 1;
612 		j = 0;
613 	} else {
614 		if (c->direction == PCMDIR_REC) {
615 			i = sndbuf_getfree(bs);
616 			j = (i > 0) ? 1 : sndbuf_getready(b);
617 		} else {
618 			if (sndbuf_getfree(bs) == 0) {
619 				i = 1;
620 				j = 0;
621 			} else {
622 				struct snd_dbuf *pb;
623 
624 				pb = CHN_BUF_PARENT(c, b);
625 				i = sndbuf_xbytes(sndbuf_getready(bs), bs, pb);
626 				j = pb->align;
627 			}
628 		}
629 		if (snd_verbose > 3 && CHN_EMPTY(c, children))
630 			device_printf(c->dev, "%s(): %s (%s) threshold "
631 			    "i=%d j=%d\n", __func__, CHN_DIRSTR(c),
632 			    (c->flags & CHN_F_VIRTUAL) ? "virtual" :
633 			    "hardware", i, j);
634 	}
635 
636 	if (i >= j) {
637 		c->flags |= CHN_F_TRIGGERED;
638 		sndbuf_setrun(b, 1);
639 		if (c->flags & CHN_F_CLOSING)
640 			c->feedcount = 2;
641 		else {
642 			c->feedcount = 0;
643 			c->interrupts = 0;
644 			c->xruns = 0;
645 		}
646 		if (c->parentchannel == NULL) {
647 			if (c->direction == PCMDIR_PLAY)
648 				sndbuf_fillsilence_rl(b,
649 				    sndbuf_xbytes(bs->bufsize, bs, b));
650 			if (snd_verbose > 3)
651 				device_printf(c->dev,
652 				    "%s(): %s starting! (%s/%s) "
653 				    "(ready=%d force=%d i=%d j=%d "
654 				    "intrtimeout=%u latency=%dms)\n",
655 				    __func__,
656 				    (c->flags & CHN_F_HAS_VCHAN) ?
657 				    "VCHAN PARENT" : "HW", CHN_DIRSTR(c),
658 				    (c->flags & CHN_F_CLOSING) ? "closing" :
659 				    "running",
660 				    sndbuf_getready(b),
661 				    force, i, j, c->timeout,
662 				    (b->bufsize * 1000) /
663 				    (b->align * b->spd));
664 		}
665 		err = chn_trigger(c, PCMTRIG_START);
666 	}
667 
668 	return (err);
669 }
670 
671 void
chn_resetbuf(struct pcm_channel * c)672 chn_resetbuf(struct pcm_channel *c)
673 {
674 	struct snd_dbuf *b = c->bufhard;
675 	struct snd_dbuf *bs = c->bufsoft;
676 
677 	c->blocks = 0;
678 	sndbuf_reset(b);
679 	sndbuf_reset(bs);
680 }
681 
682 /*
683  * chn_sync waits until the space in the given channel goes above
684  * a threshold. The threshold is checked against fl or rl respectively.
685  * Assume that the condition can become true, do not check here...
686  */
687 int
chn_sync(struct pcm_channel * c,int threshold)688 chn_sync(struct pcm_channel *c, int threshold)
689 {
690     	struct snd_dbuf *b, *bs;
691 	int ret, count, hcount, minflush, resid, residp, syncdelay, blksz;
692 	u_int32_t cflag;
693 
694 	CHN_LOCKASSERT(c);
695 
696 	if (c->direction != PCMDIR_PLAY)
697 		return (EINVAL);
698 
699 	bs = c->bufsoft;
700 
701 	if ((c->flags & (CHN_F_DEAD | CHN_F_ABORTING)) ||
702 	    (threshold < 1 && sndbuf_getready(bs) < 1))
703 		return (0);
704 
705 	/* if we haven't yet started and nothing is buffered, else start*/
706 	if (CHN_STOPPED(c)) {
707 		if (threshold > 0 || sndbuf_getready(bs) > 0) {
708 			ret = chn_start(c, 1);
709 			if (ret != 0)
710 				return (ret);
711 		} else
712 			return (0);
713 	}
714 
715 	b = CHN_BUF_PARENT(c, c->bufhard);
716 
717 	minflush = threshold + sndbuf_xbytes(sndbuf_getready(b), b, bs);
718 
719 	syncdelay = chn_syncdelay;
720 
721 	if (syncdelay < 0 && (threshold > 0 || sndbuf_getready(bs) > 0))
722 		minflush += sndbuf_xbytes(b->bufsize, b, bs);
723 
724 	/*
725 	 * Append (0-1000) millisecond trailing buffer (if needed)
726 	 * for slower / high latency hardwares (notably USB audio)
727 	 * to avoid audible truncation.
728 	 */
729 	if (syncdelay > 0)
730 		minflush += (bs->align * bs->spd *
731 		    ((syncdelay > 1000) ? 1000 : syncdelay)) / 1000;
732 
733 	minflush -= minflush % bs->align;
734 
735 	if (minflush > 0) {
736 		threshold = min(minflush, sndbuf_getfree(bs));
737 		sndbuf_clear(bs, threshold);
738 		sndbuf_acquire(bs, NULL, threshold);
739 		minflush -= threshold;
740 	}
741 
742 	resid = sndbuf_getready(bs);
743 	residp = resid;
744 	blksz = b->blksz;
745 	if (blksz < 1) {
746 		device_printf(c->dev,
747 		    "%s(): WARNING: blksz < 1 ! maxsize=%d [%d/%d/%d]\n",
748 		    __func__, b->maxsize, b->bufsize,
749 		    b->blksz, b->blkcnt);
750 		if (b->blkcnt > 0)
751 			blksz = b->bufsize / b->blkcnt;
752 		if (blksz < 1)
753 			blksz = 1;
754 	}
755 	count = sndbuf_xbytes(minflush + resid, bs, b) / blksz;
756 	hcount = count;
757 	ret = 0;
758 
759 	if (snd_verbose > 3)
760 		device_printf(c->dev, "%s(): [begin] timeout=%d count=%d "
761 		    "minflush=%d resid=%d\n", __func__, c->timeout, count,
762 		    minflush, resid);
763 
764 	cflag = c->flags & CHN_F_CLOSING;
765 	c->flags |= CHN_F_CLOSING;
766 	while (count > 0 && (resid > 0 || minflush > 0)) {
767 		ret = chn_sleep(c, c->timeout);
768     		if (ret == ERESTART || ret == EINTR) {
769 			c->flags |= CHN_F_ABORTING;
770 			break;
771 		} else if (ret == 0 || ret == EAGAIN) {
772 			resid = sndbuf_getready(bs);
773 			if (resid == residp) {
774 				--count;
775 				if (snd_verbose > 3)
776 					device_printf(c->dev,
777 					    "%s(): [stalled] timeout=%d "
778 					    "count=%d hcount=%d "
779 					    "resid=%d minflush=%d\n",
780 					    __func__, c->timeout, count,
781 					    hcount, resid, minflush);
782 			} else if (resid < residp && count < hcount) {
783 				++count;
784 				if (snd_verbose > 3)
785 					device_printf(c->dev,
786 					    "%s((): [resume] timeout=%d "
787 					    "count=%d hcount=%d "
788 					    "resid=%d minflush=%d\n",
789 					    __func__, c->timeout, count,
790 					    hcount, resid, minflush);
791 			}
792 			if (minflush > 0 && sndbuf_getfree(bs) > 0) {
793 				threshold = min(minflush,
794 				    sndbuf_getfree(bs));
795 				sndbuf_clear(bs, threshold);
796 				sndbuf_acquire(bs, NULL, threshold);
797 				resid = sndbuf_getready(bs);
798 				minflush -= threshold;
799 			}
800 			residp = resid;
801 		} else
802 			break;
803 	}
804 	c->flags &= ~CHN_F_CLOSING;
805 	c->flags |= cflag;
806 
807 	if (snd_verbose > 3)
808 		device_printf(c->dev,
809 		    "%s(): timeout=%d count=%d hcount=%d resid=%d residp=%d "
810 		    "minflush=%d ret=%d\n",
811 		    __func__, c->timeout, count, hcount, resid, residp,
812 		    minflush, ret);
813 
814     	return (0);
815 }
816 
817 /* called externally, handle locking */
818 int
chn_poll(struct pcm_channel * c,int ev,struct thread * td)819 chn_poll(struct pcm_channel *c, int ev, struct thread *td)
820 {
821 	struct snd_dbuf *bs = c->bufsoft;
822 	int ret;
823 
824 	CHN_LOCKASSERT(c);
825 
826     	if (!(c->flags & (CHN_F_MMAP | CHN_F_TRIGGERED))) {
827 		ret = chn_start(c, 1);
828 		if (ret != 0)
829 			return (0);
830 	}
831 
832 	ret = 0;
833 	if (chn_polltrigger(c)) {
834 		chn_pollreset(c);
835 		ret = ev;
836 	} else
837 		selrecord(td, &bs->sel);
838 
839 	return (ret);
840 }
841 
842 /*
843  * chn_abort terminates a running dma transfer.  it may sleep up to 200ms.
844  * it returns the number of bytes that have not been transferred.
845  *
846  * called from: dsp_close, dsp_ioctl, with channel locked
847  */
848 int
chn_abort(struct pcm_channel * c)849 chn_abort(struct pcm_channel *c)
850 {
851     	int missing = 0;
852     	struct snd_dbuf *b = c->bufhard;
853     	struct snd_dbuf *bs = c->bufsoft;
854 
855 	CHN_LOCKASSERT(c);
856 	if (CHN_STOPPED(c))
857 		return 0;
858 	c->flags |= CHN_F_ABORTING;
859 
860 	c->flags &= ~CHN_F_TRIGGERED;
861 	/* kill the channel */
862 	chn_trigger(c, PCMTRIG_ABORT);
863 	sndbuf_setrun(b, 0);
864 	if (!(c->flags & CHN_F_VIRTUAL))
865 		chn_dmaupdate(c);
866     	missing = sndbuf_getready(bs);
867 
868 	c->flags &= ~CHN_F_ABORTING;
869 	return missing;
870 }
871 
872 /*
873  * this routine tries to flush the dma transfer. It is called
874  * on a close of a playback channel.
875  * first, if there is data in the buffer, but the dma has not yet
876  * begun, we need to start it.
877  * next, we wait for the play buffer to drain
878  * finally, we stop the dma.
879  *
880  * called from: dsp_close, not valid for record channels.
881  */
882 
883 int
chn_flush(struct pcm_channel * c)884 chn_flush(struct pcm_channel *c)
885 {
886     	struct snd_dbuf *b = c->bufhard;
887 
888 	CHN_LOCKASSERT(c);
889 	KASSERT(c->direction == PCMDIR_PLAY, ("chn_flush on bad channel"));
890     	DEB(printf("chn_flush: c->flags 0x%08x\n", c->flags));
891 
892 	c->flags |= CHN_F_CLOSING;
893 	chn_sync(c, 0);
894 	c->flags &= ~CHN_F_TRIGGERED;
895 	/* kill the channel */
896 	chn_trigger(c, PCMTRIG_ABORT);
897 	sndbuf_setrun(b, 0);
898 
899     	c->flags &= ~CHN_F_CLOSING;
900     	return 0;
901 }
902 
903 int
snd_fmtvalid(uint32_t fmt,uint32_t * fmtlist)904 snd_fmtvalid(uint32_t fmt, uint32_t *fmtlist)
905 {
906 	int i;
907 
908 	for (i = 0; fmtlist[i] != 0; i++) {
909 		if (fmt == fmtlist[i] ||
910 		    ((fmt & AFMT_PASSTHROUGH) &&
911 		    (AFMT_ENCODING(fmt) & fmtlist[i])))
912 			return (1);
913 	}
914 
915 	return (0);
916 }
917 
918 static const struct {
919 	char *name, *alias1, *alias2;
920 	uint32_t afmt;
921 } afmt_tab[] = {
922 	{  "alaw",  NULL, NULL, AFMT_A_LAW  },
923 	{ "mulaw",  NULL, NULL, AFMT_MU_LAW },
924 	{    "u8",   "8", NULL, AFMT_U8     },
925 	{    "s8",  NULL, NULL, AFMT_S8     },
926 	{   "ac3",  NULL, NULL, AFMT_AC3    },
927 #if BYTE_ORDER == LITTLE_ENDIAN
928 	{ "s16le", "s16", "16", AFMT_S16_LE },
929 	{ "s16be",  NULL, NULL, AFMT_S16_BE },
930 	{ "s24le", "s24", "24", AFMT_S24_LE },
931 	{ "s24be",  NULL, NULL, AFMT_S24_BE },
932 	{ "s32le", "s32", "32", AFMT_S32_LE },
933 	{ "s32be",  NULL, NULL, AFMT_S32_BE },
934 	{ "f32le", "f32", NULL, AFMT_F32_LE },
935 	{ "f32be",  NULL, NULL, AFMT_F32_BE },
936 	{ "u16le", "u16", NULL, AFMT_U16_LE },
937 	{ "u16be",  NULL, NULL, AFMT_U16_BE },
938 	{ "u24le", "u24", NULL, AFMT_U24_LE },
939 	{ "u24be",  NULL, NULL, AFMT_U24_BE },
940 	{ "u32le", "u32", NULL, AFMT_U32_LE },
941 	{ "u32be",  NULL, NULL, AFMT_U32_BE },
942 #else
943 	{ "s16le",  NULL, NULL, AFMT_S16_LE },
944 	{ "s16be", "s16", "16", AFMT_S16_BE },
945 	{ "s24le",  NULL, NULL, AFMT_S24_LE },
946 	{ "s24be", "s24", "24", AFMT_S24_BE },
947 	{ "s32le",  NULL, NULL, AFMT_S32_LE },
948 	{ "s32be", "s32", "32", AFMT_S32_BE },
949 	{ "f32le",  NULL, NULL, AFMT_F32_LE },
950 	{ "f32be", "f32", NULL, AFMT_F32_BE },
951 	{ "u16le",  NULL, NULL, AFMT_U16_LE },
952 	{ "u16be", "u16", NULL, AFMT_U16_BE },
953 	{ "u24le",  NULL, NULL, AFMT_U24_LE },
954 	{ "u24be", "u24", NULL, AFMT_U24_BE },
955 	{ "u32le",  NULL, NULL, AFMT_U32_LE },
956 	{ "u32be", "u32", NULL, AFMT_U32_BE },
957 #endif
958 	{    NULL,  NULL, NULL, 0           }
959 };
960 
961 uint32_t
snd_str2afmt(const char * req)962 snd_str2afmt(const char *req)
963 {
964 	int ext;
965 	int ch;
966 	int i;
967 	char b1[8];
968 	char b2[8];
969 
970 	memset(b1, 0, sizeof(b1));
971 	memset(b2, 0, sizeof(b2));
972 
973 	i = sscanf(req, "%5[^:]:%6s", b1, b2);
974 
975 	if (i == 1) {
976 		if (strlen(req) != strlen(b1))
977 			return (0);
978 		strlcpy(b2, "2.0", sizeof(b2));
979 	} else if (i == 2) {
980 		if (strlen(req) != (strlen(b1) + 1 + strlen(b2)))
981 			return (0);
982 	} else
983 		return (0);
984 
985 	i = sscanf(b2, "%d.%d", &ch, &ext);
986 
987 	if (i == 0) {
988 		if (strcasecmp(b2, "mono") == 0) {
989 			ch = 1;
990 			ext = 0;
991 		} else if (strcasecmp(b2, "stereo") == 0) {
992 			ch = 2;
993 			ext = 0;
994 		} else if (strcasecmp(b2, "quad") == 0) {
995 			ch = 4;
996 			ext = 0;
997 		} else
998 			return (0);
999 	} else if (i == 1) {
1000 		if (ch < 1 || ch > AFMT_CHANNEL_MAX)
1001 			return (0);
1002 		ext = 0;
1003 	} else if (i == 2) {
1004 		if (ext < 0 || ext > AFMT_EXTCHANNEL_MAX)
1005 			return (0);
1006 		if (ch < 1 || (ch + ext) > AFMT_CHANNEL_MAX)
1007 			return (0);
1008 	} else
1009 		return (0);
1010 
1011 	for (i = 0; afmt_tab[i].name != NULL; i++) {
1012 		if (strcasecmp(afmt_tab[i].name, b1) != 0) {
1013 			if (afmt_tab[i].alias1 == NULL)
1014 				continue;
1015 			if (strcasecmp(afmt_tab[i].alias1, b1) != 0) {
1016 				if (afmt_tab[i].alias2 == NULL)
1017 					continue;
1018 				if (strcasecmp(afmt_tab[i].alias2, b1) != 0)
1019 					continue;
1020 			}
1021 		}
1022 		/* found a match */
1023 		return (SND_FORMAT(afmt_tab[i].afmt, ch + ext, ext));
1024 	}
1025 	/* not a valid format */
1026 	return (0);
1027 }
1028 
1029 uint32_t
snd_afmt2str(uint32_t afmt,char * buf,size_t len)1030 snd_afmt2str(uint32_t afmt, char *buf, size_t len)
1031 {
1032 	uint32_t enc;
1033 	uint32_t ext;
1034 	uint32_t ch;
1035 	int i;
1036 
1037 	if (buf == NULL || len < AFMTSTR_LEN)
1038 		return (0);
1039 
1040 	memset(buf, 0, len);
1041 
1042 	enc = AFMT_ENCODING(afmt);
1043 	ch = AFMT_CHANNEL(afmt);
1044 	ext = AFMT_EXTCHANNEL(afmt);
1045 	/* check there is at least one channel */
1046 	if (ch <= ext)
1047 		return (0);
1048 	for (i = 0; afmt_tab[i].name != NULL; i++) {
1049 		if (enc != afmt_tab[i].afmt)
1050 			continue;
1051 		/* found a match */
1052 		snprintf(buf, len, "%s:%d.%d",
1053 		    afmt_tab[i].name, ch - ext, ext);
1054 		return (SND_FORMAT(enc, ch, ext));
1055 	}
1056 	return (0);
1057 }
1058 
1059 int
chn_reset(struct pcm_channel * c,uint32_t fmt,uint32_t spd)1060 chn_reset(struct pcm_channel *c, uint32_t fmt, uint32_t spd)
1061 {
1062 	int r;
1063 
1064 	CHN_LOCKASSERT(c);
1065 	c->feedcount = 0;
1066 	c->flags &= CHN_F_RESET;
1067 	c->interrupts = 0;
1068 	c->timeout = 1;
1069 	c->xruns = 0;
1070 
1071 	c->flags |= (pcm_getflags(c->dev) & SD_F_BITPERFECT) ?
1072 	    CHN_F_BITPERFECT : 0;
1073 
1074 	r = CHANNEL_RESET(c->methods, c->devinfo);
1075 	if (r == 0 && fmt != 0 && spd != 0) {
1076 		r = chn_setparam(c, fmt, spd);
1077 		fmt = 0;
1078 		spd = 0;
1079 	}
1080 	if (r == 0 && fmt != 0)
1081 		r = chn_setformat(c, fmt);
1082 	if (r == 0 && spd != 0)
1083 		r = chn_setspeed(c, spd);
1084 	if (r == 0)
1085 		r = chn_setlatency(c, chn_latency);
1086 	if (r == 0) {
1087 		chn_resetbuf(c);
1088 		r = CHANNEL_RESETDONE(c->methods, c->devinfo);
1089 	}
1090 	return r;
1091 }
1092 
1093 static struct unrhdr *
chn_getunr(struct snddev_info * d,int type)1094 chn_getunr(struct snddev_info *d, int type)
1095 {
1096 	switch (type) {
1097 	case PCMDIR_PLAY:
1098 		return (d->p_unr);
1099 	case PCMDIR_PLAY_VIRTUAL:
1100 		return (d->vp_unr);
1101 	case PCMDIR_REC:
1102 		return (d->r_unr);
1103 	case PCMDIR_REC_VIRTUAL:
1104 		return (d->vr_unr);
1105 	default:
1106 		__assert_unreachable();
1107 	}
1108 
1109 }
1110 
1111 char *
chn_mkname(char * buf,size_t len,struct pcm_channel * c)1112 chn_mkname(char *buf, size_t len, struct pcm_channel *c)
1113 {
1114 	const char *str;
1115 
1116 	KASSERT(buf != NULL && len != 0,
1117 	    ("%s(): bogus buf=%p len=%zu", __func__, buf, len));
1118 
1119 	switch (c->type) {
1120 	case PCMDIR_PLAY:
1121 		str = "play";
1122 		break;
1123 	case PCMDIR_PLAY_VIRTUAL:
1124 		str = "virtual_play";
1125 		break;
1126 	case PCMDIR_REC:
1127 		str = "record";
1128 		break;
1129 	case PCMDIR_REC_VIRTUAL:
1130 		str = "virtual_record";
1131 		break;
1132 	default:
1133 		__assert_unreachable();
1134 	}
1135 
1136 	snprintf(buf, len, "dsp%d.%s.%d",
1137 	    device_get_unit(c->dev), str, c->unit);
1138 
1139 	return (buf);
1140 }
1141 
1142 struct pcm_channel *
chn_init(struct snddev_info * d,struct pcm_channel * parent,kobj_class_t cls,int dir,void * devinfo)1143 chn_init(struct snddev_info *d, struct pcm_channel *parent, kobj_class_t cls,
1144     int dir, void *devinfo)
1145 {
1146 	struct pcm_channel *c;
1147 	struct feeder_class *fc;
1148 	struct snd_dbuf *b, *bs;
1149 	char buf[CHN_NAMELEN];
1150 	int err, i, direction, *vchanrate, *vchanformat;
1151 
1152 	PCM_BUSYASSERT(d);
1153 	PCM_LOCKASSERT(d);
1154 
1155 	switch (dir) {
1156 	case PCMDIR_PLAY:
1157 		d->playcount++;
1158 		/* FALLTHROUGH */
1159 	case PCMDIR_PLAY_VIRTUAL:
1160 		if (dir == PCMDIR_PLAY_VIRTUAL)
1161 			d->pvchancount++;
1162 		direction = PCMDIR_PLAY;
1163 		vchanrate = &d->pvchanrate;
1164 		vchanformat = &d->pvchanformat;
1165 		break;
1166 	case PCMDIR_REC:
1167 		d->reccount++;
1168 		/* FALLTHROUGH */
1169 	case PCMDIR_REC_VIRTUAL:
1170 		if (dir == PCMDIR_REC_VIRTUAL)
1171 			d->rvchancount++;
1172 		direction = PCMDIR_REC;
1173 		vchanrate = &d->rvchanrate;
1174 		vchanformat = &d->rvchanformat;
1175 		break;
1176 	default:
1177 		device_printf(d->dev,
1178 		    "%s(): invalid channel direction: %d\n",
1179 		    __func__, dir);
1180 		return (NULL);
1181 	}
1182 
1183 	PCM_UNLOCK(d);
1184 	b = NULL;
1185 	bs = NULL;
1186 
1187 	c = malloc(sizeof(*c), M_DEVBUF, M_WAITOK | M_ZERO);
1188 	c->methods = kobj_create(cls, M_DEVBUF, M_WAITOK | M_ZERO);
1189 	chn_lockinit(c, dir);
1190 	CHN_INIT(c, children);
1191 	CHN_INIT(c, children.busy);
1192 	c->direction = direction;
1193 	c->type = dir;
1194 	c->unit = alloc_unr(chn_getunr(d, c->type));
1195 	c->format = SND_FORMAT(AFMT_S16_LE, 2, 0);
1196 	c->speed = 48000;
1197 	c->pid = -1;
1198 	c->latency = -1;
1199 	c->timeout = 1;
1200 	strlcpy(c->comm, CHN_COMM_UNUSED, sizeof(c->comm));
1201 	c->parentsnddev = d;
1202 	c->parentchannel = parent;
1203 	c->dev = d->dev;
1204 	c->trigger = PCMTRIG_STOP;
1205 	strlcpy(c->name, chn_mkname(buf, sizeof(buf), c), sizeof(c->name));
1206 
1207 	c->matrix = *feeder_matrix_id_map(SND_CHN_MATRIX_1_0);
1208 	c->matrix.id = SND_CHN_MATRIX_PCMCHANNEL;
1209 
1210 	for (i = 0; i < SND_CHN_T_MAX; i++)
1211 		c->volume[SND_VOL_C_MASTER][i] = SND_VOL_0DB_MASTER;
1212 
1213 	c->volume[SND_VOL_C_MASTER][SND_CHN_T_VOL_0DB] = SND_VOL_0DB_MASTER;
1214 	c->volume[SND_VOL_C_PCM][SND_CHN_T_VOL_0DB] = chn_vol_0db_pcm;
1215 
1216 	CHN_LOCK(c);
1217 	chn_vpc_reset(c, SND_VOL_C_PCM, 1);
1218 	CHN_UNLOCK(c);
1219 
1220 	fc = feeder_getclass(FEEDER_ROOT);
1221 	if (fc == NULL) {
1222 		device_printf(d->dev, "%s(): failed to get feeder class\n",
1223 		    __func__);
1224 		goto fail;
1225 	}
1226 	if (feeder_add(c, fc, NULL)) {
1227 		device_printf(d->dev, "%s(): failed to add feeder\n", __func__);
1228 		goto fail;
1229 	}
1230 
1231 	b = sndbuf_create(c, "primary");
1232 	bs = sndbuf_create(c, "secondary");
1233 	if (b == NULL || bs == NULL) {
1234 		device_printf(d->dev, "%s(): failed to create %s buffer\n",
1235 		    __func__, b == NULL ? "hardware" : "software");
1236 		goto fail;
1237 	}
1238 	c->bufhard = b;
1239 	c->bufsoft = bs;
1240 	knlist_init_mtx(&bs->sel.si_note, &c->lock);
1241 
1242 	c->devinfo = CHANNEL_INIT(c->methods, devinfo, b, c, direction);
1243 	if (c->devinfo == NULL) {
1244 		device_printf(d->dev, "%s(): CHANNEL_INIT() failed\n", __func__);
1245 		goto fail;
1246 	}
1247 
1248 	if (b->bufsize == 0 && ((c->flags & CHN_F_VIRTUAL) == 0)) {
1249 		device_printf(d->dev, "%s(): hardware buffer's size is 0\n",
1250 		    __func__);
1251 		goto fail;
1252 	}
1253 
1254 	sndbuf_setfmt(b, c->format);
1255 	sndbuf_setspd(b, c->speed);
1256 	sndbuf_setfmt(bs, c->format);
1257 	sndbuf_setspd(bs, c->speed);
1258 	sndbuf_setup(bs, NULL, 0);
1259 
1260 	/**
1261 	 * @todo Should this be moved somewhere else?  The primary buffer
1262 	 * 	 is allocated by the driver or via DMA map setup, and tmpbuf
1263 	 * 	 seems to only come into existence in sndbuf_resize().
1264 	 */
1265 	if (c->direction == PCMDIR_PLAY) {
1266 		bs->sl = bs->maxsize;
1267 		bs->shadbuf = malloc(bs->sl, M_DEVBUF, M_WAITOK);
1268 	}
1269 
1270 	if ((c->flags & CHN_F_VIRTUAL) == 0) {
1271 		CHN_LOCK(c);
1272 		err = chn_reset(c, c->format, c->speed);
1273 		CHN_UNLOCK(c);
1274 		if (err != 0)
1275 			goto fail;
1276 	}
1277 
1278 	PCM_LOCK(d);
1279 	CHN_INSERT_SORT_ASCEND(d, c, channels.pcm);
1280 	if ((c->flags & CHN_F_VIRTUAL) == 0) {
1281 		CHN_INSERT_SORT_ASCEND(d, c, channels.pcm.primary);
1282 		/* Initialize the *vchanrate/vchanformat parameters. */
1283 		*vchanrate = c->bufsoft->spd;
1284 		*vchanformat = c->bufsoft->fmt;
1285 	}
1286 
1287 	return (c);
1288 
1289 fail:
1290 	chn_kill(c);
1291 	PCM_LOCK(d);
1292 
1293 	return (NULL);
1294 }
1295 
1296 void
chn_kill(struct pcm_channel * c)1297 chn_kill(struct pcm_channel *c)
1298 {
1299 	struct snddev_info *d = c->parentsnddev;
1300 	struct snd_dbuf *b = c->bufhard;
1301 	struct snd_dbuf *bs = c->bufsoft;
1302 
1303 	PCM_BUSYASSERT(c->parentsnddev);
1304 
1305 	PCM_LOCK(d);
1306 	CHN_REMOVE(d, c, channels.pcm);
1307 	if ((c->flags & CHN_F_VIRTUAL) == 0)
1308 		CHN_REMOVE(d, c, channels.pcm.primary);
1309 
1310 	switch (c->type) {
1311 	case PCMDIR_PLAY:
1312 		d->playcount--;
1313 		break;
1314 	case PCMDIR_PLAY_VIRTUAL:
1315 		d->pvchancount--;
1316 		break;
1317 	case PCMDIR_REC:
1318 		d->reccount--;
1319 		break;
1320 	case PCMDIR_REC_VIRTUAL:
1321 		d->rvchancount--;
1322 		break;
1323 	default:
1324 		__assert_unreachable();
1325 	}
1326 	PCM_UNLOCK(d);
1327 
1328 	if (CHN_STARTED(c)) {
1329 		CHN_LOCK(c);
1330 		chn_trigger(c, PCMTRIG_ABORT);
1331 		CHN_UNLOCK(c);
1332 	}
1333 	free_unr(chn_getunr(d, c->type), c->unit);
1334 	feeder_remove(c);
1335 	if (c->devinfo)
1336 		CHANNEL_FREE(c->methods, c->devinfo);
1337 	if (bs) {
1338 		knlist_clear(&bs->sel.si_note, 0);
1339 		knlist_destroy(&bs->sel.si_note);
1340 		sndbuf_destroy(bs);
1341 	}
1342 	if (b)
1343 		sndbuf_destroy(b);
1344 	CHN_LOCK(c);
1345 	c->flags |= CHN_F_DEAD;
1346 	chn_lockdestroy(c);
1347 	kobj_delete(c->methods, M_DEVBUF);
1348 	free(c, M_DEVBUF);
1349 }
1350 
1351 void
chn_shutdown(struct pcm_channel * c)1352 chn_shutdown(struct pcm_channel *c)
1353 {
1354 	CHN_LOCKASSERT(c);
1355 
1356 	chn_wakeup(c);
1357 	c->flags |= CHN_F_DEAD;
1358 }
1359 
1360 /* release a locked channel and unlock it */
1361 int
chn_release(struct pcm_channel * c)1362 chn_release(struct pcm_channel *c)
1363 {
1364 	PCM_BUSYASSERT(c->parentsnddev);
1365 	CHN_LOCKASSERT(c);
1366 
1367 	c->flags &= ~CHN_F_BUSY;
1368 	c->pid = -1;
1369 	strlcpy(c->comm, CHN_COMM_UNUSED, sizeof(c->comm));
1370 	CHN_UNLOCK(c);
1371 
1372 	return (0);
1373 }
1374 
1375 int
chn_setvolume_multi(struct pcm_channel * c,int vc,int left,int right,int center)1376 chn_setvolume_multi(struct pcm_channel *c, int vc, int left, int right,
1377     int center)
1378 {
1379 	int i, ret;
1380 
1381 	ret = 0;
1382 
1383 	for (i = 0; i < SND_CHN_T_MAX; i++) {
1384 		if ((1 << i) & SND_CHN_LEFT_MASK)
1385 			ret |= chn_setvolume_matrix(c, vc, i, left);
1386 		else if ((1 << i) & SND_CHN_RIGHT_MASK)
1387 			ret |= chn_setvolume_matrix(c, vc, i, right) << 8;
1388 		else
1389 			ret |= chn_setvolume_matrix(c, vc, i, center) << 16;
1390 	}
1391 
1392 	return (ret);
1393 }
1394 
1395 int
chn_setvolume_matrix(struct pcm_channel * c,int vc,int vt,int val)1396 chn_setvolume_matrix(struct pcm_channel *c, int vc, int vt, int val)
1397 {
1398 	int i;
1399 
1400 	KASSERT(c != NULL && vc >= SND_VOL_C_MASTER && vc < SND_VOL_C_MAX &&
1401 	    (vc == SND_VOL_C_MASTER || (vc & 1)) &&
1402 	    (vt == SND_CHN_T_VOL_0DB || (vt >= SND_CHN_T_BEGIN &&
1403 	    vt <= SND_CHN_T_END)) && (vt != SND_CHN_T_VOL_0DB ||
1404 	    (val >= SND_VOL_0DB_MIN && val <= SND_VOL_0DB_MAX)),
1405 	    ("%s(): invalid volume matrix c=%p vc=%d vt=%d val=%d",
1406 	    __func__, c, vc, vt, val));
1407 	CHN_LOCKASSERT(c);
1408 
1409 	if (val < 0)
1410 		val = 0;
1411 	if (val > 100)
1412 		val = 100;
1413 
1414 	c->volume[vc][vt] = val;
1415 
1416 	/*
1417 	 * Do relative calculation here and store it into class + 1
1418 	 * to ease the job of feeder_volume.
1419 	 */
1420 	if (vc == SND_VOL_C_MASTER) {
1421 		for (vc = SND_VOL_C_BEGIN; vc <= SND_VOL_C_END;
1422 		    vc += SND_VOL_C_STEP)
1423 			c->volume[SND_VOL_C_VAL(vc)][vt] =
1424 			    SND_VOL_CALC_VAL(c->volume, vc, vt);
1425 	} else if (vc & 1) {
1426 		if (vt == SND_CHN_T_VOL_0DB)
1427 			for (i = SND_CHN_T_BEGIN; i <= SND_CHN_T_END;
1428 			    i += SND_CHN_T_STEP) {
1429 				c->volume[SND_VOL_C_VAL(vc)][i] =
1430 				    SND_VOL_CALC_VAL(c->volume, vc, i);
1431 			}
1432 		else
1433 			c->volume[SND_VOL_C_VAL(vc)][vt] =
1434 			    SND_VOL_CALC_VAL(c->volume, vc, vt);
1435 	}
1436 
1437 	return (val);
1438 }
1439 
1440 int
chn_getvolume_matrix(struct pcm_channel * c,int vc,int vt)1441 chn_getvolume_matrix(struct pcm_channel *c, int vc, int vt)
1442 {
1443 	KASSERT(c != NULL && vc >= SND_VOL_C_MASTER && vc < SND_VOL_C_MAX &&
1444 	    (vt == SND_CHN_T_VOL_0DB ||
1445 	    (vt >= SND_CHN_T_BEGIN && vt <= SND_CHN_T_END)),
1446 	    ("%s(): invalid volume matrix c=%p vc=%d vt=%d",
1447 	    __func__, c, vc, vt));
1448 	CHN_LOCKASSERT(c);
1449 
1450 	return (c->volume[vc][vt]);
1451 }
1452 
1453 int
chn_setmute_multi(struct pcm_channel * c,int vc,int mute)1454 chn_setmute_multi(struct pcm_channel *c, int vc, int mute)
1455 {
1456 	int i, ret;
1457 
1458 	ret = 0;
1459 
1460 	for (i = 0; i < SND_CHN_T_MAX; i++) {
1461 		if ((1 << i) & SND_CHN_LEFT_MASK)
1462 			ret |= chn_setmute_matrix(c, vc, i, mute);
1463 		else if ((1 << i) & SND_CHN_RIGHT_MASK)
1464 			ret |= chn_setmute_matrix(c, vc, i, mute) << 8;
1465 		else
1466 			ret |= chn_setmute_matrix(c, vc, i, mute) << 16;
1467 	}
1468 	return (ret);
1469 }
1470 
1471 int
chn_setmute_matrix(struct pcm_channel * c,int vc,int vt,int mute)1472 chn_setmute_matrix(struct pcm_channel *c, int vc, int vt, int mute)
1473 {
1474 	int i;
1475 
1476 	KASSERT(c != NULL && vc >= SND_VOL_C_MASTER && vc < SND_VOL_C_MAX &&
1477 	    (vc == SND_VOL_C_MASTER || (vc & 1)) &&
1478 	    (vt == SND_CHN_T_VOL_0DB || (vt >= SND_CHN_T_BEGIN && vt <= SND_CHN_T_END)),
1479 	    ("%s(): invalid mute matrix c=%p vc=%d vt=%d mute=%d",
1480 	    __func__, c, vc, vt, mute));
1481 
1482 	CHN_LOCKASSERT(c);
1483 
1484 	mute = (mute != 0);
1485 
1486 	c->muted[vc][vt] = mute;
1487 
1488 	/*
1489 	 * Do relative calculation here and store it into class + 1
1490 	 * to ease the job of feeder_volume.
1491 	 */
1492 	if (vc == SND_VOL_C_MASTER) {
1493 		for (vc = SND_VOL_C_BEGIN; vc <= SND_VOL_C_END;
1494 		    vc += SND_VOL_C_STEP)
1495 			c->muted[SND_VOL_C_VAL(vc)][vt] = mute;
1496 	} else if (vc & 1) {
1497 		if (vt == SND_CHN_T_VOL_0DB) {
1498 			for (i = SND_CHN_T_BEGIN; i <= SND_CHN_T_END;
1499 			    i += SND_CHN_T_STEP) {
1500 				c->muted[SND_VOL_C_VAL(vc)][i] = mute;
1501 			}
1502 		} else {
1503 			c->muted[SND_VOL_C_VAL(vc)][vt] = mute;
1504 		}
1505 	}
1506 	return (mute);
1507 }
1508 
1509 int
chn_getmute_matrix(struct pcm_channel * c,int vc,int vt)1510 chn_getmute_matrix(struct pcm_channel *c, int vc, int vt)
1511 {
1512 	KASSERT(c != NULL && vc >= SND_VOL_C_MASTER && vc < SND_VOL_C_MAX &&
1513 	    (vt == SND_CHN_T_VOL_0DB ||
1514 	    (vt >= SND_CHN_T_BEGIN && vt <= SND_CHN_T_END)),
1515 	    ("%s(): invalid mute matrix c=%p vc=%d vt=%d",
1516 	    __func__, c, vc, vt));
1517 	CHN_LOCKASSERT(c);
1518 
1519 	return (c->muted[vc][vt]);
1520 }
1521 
1522 struct pcmchan_matrix *
chn_getmatrix(struct pcm_channel * c)1523 chn_getmatrix(struct pcm_channel *c)
1524 {
1525 
1526 	KASSERT(c != NULL, ("%s(): NULL channel", __func__));
1527 	CHN_LOCKASSERT(c);
1528 
1529 	if (!(c->format & AFMT_CONVERTIBLE))
1530 		return (NULL);
1531 
1532 	return (&c->matrix);
1533 }
1534 
1535 int
chn_setmatrix(struct pcm_channel * c,struct pcmchan_matrix * m)1536 chn_setmatrix(struct pcm_channel *c, struct pcmchan_matrix *m)
1537 {
1538 
1539 	KASSERT(c != NULL && m != NULL,
1540 	    ("%s(): NULL channel or matrix", __func__));
1541 	CHN_LOCKASSERT(c);
1542 
1543 	if (!(c->format & AFMT_CONVERTIBLE))
1544 		return (EINVAL);
1545 
1546 	c->matrix = *m;
1547 	c->matrix.id = SND_CHN_MATRIX_PCMCHANNEL;
1548 
1549 	return (chn_setformat(c, SND_FORMAT(c->format, m->channels, m->ext)));
1550 }
1551 
1552 /*
1553  * XXX chn_oss_* exists for the sake of compatibility.
1554  */
1555 int
chn_oss_getorder(struct pcm_channel * c,unsigned long long * map)1556 chn_oss_getorder(struct pcm_channel *c, unsigned long long *map)
1557 {
1558 
1559 	KASSERT(c != NULL && map != NULL,
1560 	    ("%s(): NULL channel or map", __func__));
1561 	CHN_LOCKASSERT(c);
1562 
1563 	if (!(c->format & AFMT_CONVERTIBLE))
1564 		return (EINVAL);
1565 
1566 	return (feeder_matrix_oss_get_channel_order(&c->matrix, map));
1567 }
1568 
1569 int
chn_oss_setorder(struct pcm_channel * c,unsigned long long * map)1570 chn_oss_setorder(struct pcm_channel *c, unsigned long long *map)
1571 {
1572 	struct pcmchan_matrix m;
1573 	int ret;
1574 
1575 	KASSERT(c != NULL && map != NULL,
1576 	    ("%s(): NULL channel or map", __func__));
1577 	CHN_LOCKASSERT(c);
1578 
1579 	if (!(c->format & AFMT_CONVERTIBLE))
1580 		return (EINVAL);
1581 
1582 	m = c->matrix;
1583 	ret = feeder_matrix_oss_set_channel_order(&m, map);
1584 	if (ret != 0)
1585 		return (ret);
1586 
1587 	return (chn_setmatrix(c, &m));
1588 }
1589 
1590 #define SND_CHN_OSS_FRONT	(SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FR)
1591 #define SND_CHN_OSS_SURR	(SND_CHN_T_MASK_SL | SND_CHN_T_MASK_SR)
1592 #define SND_CHN_OSS_CENTER_LFE	(SND_CHN_T_MASK_FC | SND_CHN_T_MASK_LF)
1593 #define SND_CHN_OSS_REAR	(SND_CHN_T_MASK_BL | SND_CHN_T_MASK_BR)
1594 
1595 int
chn_oss_getmask(struct pcm_channel * c,uint32_t * retmask)1596 chn_oss_getmask(struct pcm_channel *c, uint32_t *retmask)
1597 {
1598 	struct pcmchan_matrix *m;
1599 	struct pcmchan_caps *caps;
1600 	uint32_t i, format;
1601 
1602 	KASSERT(c != NULL && retmask != NULL,
1603 	    ("%s(): NULL channel or retmask", __func__));
1604 	CHN_LOCKASSERT(c);
1605 
1606 	caps = chn_getcaps(c);
1607 	if (caps == NULL || caps->fmtlist == NULL)
1608 		return (ENODEV);
1609 
1610 	for (i = 0; caps->fmtlist[i] != 0; i++) {
1611 		format = caps->fmtlist[i];
1612 		if (!(format & AFMT_CONVERTIBLE)) {
1613 			*retmask |= DSP_BIND_SPDIF;
1614 			continue;
1615 		}
1616 		m = CHANNEL_GETMATRIX(c->methods, c->devinfo, format);
1617 		if (m == NULL)
1618 			continue;
1619 		if (m->mask & SND_CHN_OSS_FRONT)
1620 			*retmask |= DSP_BIND_FRONT;
1621 		if (m->mask & SND_CHN_OSS_SURR)
1622 			*retmask |= DSP_BIND_SURR;
1623 		if (m->mask & SND_CHN_OSS_CENTER_LFE)
1624 			*retmask |= DSP_BIND_CENTER_LFE;
1625 		if (m->mask & SND_CHN_OSS_REAR)
1626 			*retmask |= DSP_BIND_REAR;
1627 	}
1628 
1629 	/* report software-supported binding mask */
1630 	if (!CHN_BITPERFECT(c) && report_soft_matrix)
1631 		*retmask |= DSP_BIND_FRONT | DSP_BIND_SURR |
1632 		    DSP_BIND_CENTER_LFE | DSP_BIND_REAR;
1633 
1634 	return (0);
1635 }
1636 
1637 void
chn_vpc_reset(struct pcm_channel * c,int vc,int force)1638 chn_vpc_reset(struct pcm_channel *c, int vc, int force)
1639 {
1640 	int i;
1641 
1642 	KASSERT(c != NULL && vc >= SND_VOL_C_BEGIN && vc <= SND_VOL_C_END,
1643 	    ("%s(): invalid reset c=%p vc=%d", __func__, c, vc));
1644 	CHN_LOCKASSERT(c);
1645 
1646 	if (force == 0 && chn_vpc_autoreset == 0)
1647 		return;
1648 
1649 	for (i = SND_CHN_T_BEGIN; i <= SND_CHN_T_END; i += SND_CHN_T_STEP)
1650 		CHN_SETVOLUME(c, vc, i, c->volume[vc][SND_CHN_T_VOL_0DB]);
1651 }
1652 
1653 static u_int32_t
round_pow2(u_int32_t v)1654 round_pow2(u_int32_t v)
1655 {
1656 	u_int32_t ret;
1657 
1658 	if (v < 2)
1659 		v = 2;
1660 	ret = 0;
1661 	while (v >> ret)
1662 		ret++;
1663 	ret = 1 << (ret - 1);
1664 	while (ret < v)
1665 		ret <<= 1;
1666 	return ret;
1667 }
1668 
1669 static u_int32_t
round_blksz(u_int32_t v,int round)1670 round_blksz(u_int32_t v, int round)
1671 {
1672 	u_int32_t ret, tmp;
1673 
1674 	if (round < 1)
1675 		round = 1;
1676 
1677 	ret = min(round_pow2(v), CHN_2NDBUFMAXSIZE >> 1);
1678 
1679 	if (ret > v && (ret >> 1) > 0 && (ret >> 1) >= ((v * 3) >> 2))
1680 		ret >>= 1;
1681 
1682 	tmp = ret - (ret % round);
1683 	while (tmp < 16 || tmp < round) {
1684 		ret <<= 1;
1685 		tmp = ret - (ret % round);
1686 	}
1687 
1688 	return ret;
1689 }
1690 
1691 /*
1692  * 4Front call it DSP Policy, while we call it "Latency Profile". The idea
1693  * is to keep 2nd buffer short so that it doesn't cause long queue during
1694  * buffer transfer.
1695  *
1696  *    Latency reference table for 48khz stereo 16bit: (PLAY)
1697  *
1698  *      +---------+------------+-----------+------------+
1699  *      | Latency | Blockcount | Blocksize | Buffersize |
1700  *      +---------+------------+-----------+------------+
1701  *      |     0   |       2    |   64      |    128     |
1702  *      +---------+------------+-----------+------------+
1703  *      |     1   |       4    |   128     |    512     |
1704  *      +---------+------------+-----------+------------+
1705  *      |     2   |       8    |   512     |    4096    |
1706  *      +---------+------------+-----------+------------+
1707  *      |     3   |      16    |   512     |    8192    |
1708  *      +---------+------------+-----------+------------+
1709  *      |     4   |      32    |   512     |    16384   |
1710  *      +---------+------------+-----------+------------+
1711  *      |     5   |      32    |   1024    |    32768   |
1712  *      +---------+------------+-----------+------------+
1713  *      |     6   |      16    |   2048    |    32768   |
1714  *      +---------+------------+-----------+------------+
1715  *      |     7   |       8    |   4096    |    32768   |
1716  *      +---------+------------+-----------+------------+
1717  *      |     8   |       4    |   8192    |    32768   |
1718  *      +---------+------------+-----------+------------+
1719  *      |     9   |       2    |   16384   |    32768   |
1720  *      +---------+------------+-----------+------------+
1721  *      |    10   |       2    |   32768   |    65536   |
1722  *      +---------+------------+-----------+------------+
1723  *
1724  * Recording need a different reference table. All we care is
1725  * gobbling up everything within reasonable buffering threshold.
1726  *
1727  *    Latency reference table for 48khz stereo 16bit: (REC)
1728  *
1729  *      +---------+------------+-----------+------------+
1730  *      | Latency | Blockcount | Blocksize | Buffersize |
1731  *      +---------+------------+-----------+------------+
1732  *      |     0   |     512    |   32      |    16384   |
1733  *      +---------+------------+-----------+------------+
1734  *      |     1   |     256    |   64      |    16384   |
1735  *      +---------+------------+-----------+------------+
1736  *      |     2   |     128    |   128     |    16384   |
1737  *      +---------+------------+-----------+------------+
1738  *      |     3   |      64    |   256     |    16384   |
1739  *      +---------+------------+-----------+------------+
1740  *      |     4   |      32    |   512     |    16384   |
1741  *      +---------+------------+-----------+------------+
1742  *      |     5   |      32    |   1024    |    32768   |
1743  *      +---------+------------+-----------+------------+
1744  *      |     6   |      16    |   2048    |    32768   |
1745  *      +---------+------------+-----------+------------+
1746  *      |     7   |       8    |   4096    |    32768   |
1747  *      +---------+------------+-----------+------------+
1748  *      |     8   |       4    |   8192    |    32768   |
1749  *      +---------+------------+-----------+------------+
1750  *      |     9   |       2    |   16384   |    32768   |
1751  *      +---------+------------+-----------+------------+
1752  *      |    10   |       2    |   32768   |    65536   |
1753  *      +---------+------------+-----------+------------+
1754  *
1755  * Calculations for other data rate are entirely based on these reference
1756  * tables. For normal operation, Latency 5 seems give the best, well
1757  * balanced performance for typical workload. Anything below 5 will
1758  * eat up CPU to keep up with increasing context switches because of
1759  * shorter buffer space and usually require the application to handle it
1760  * aggressively through possibly real time programming technique.
1761  *
1762  */
1763 #define CHN_LATENCY_PBLKCNT_REF				\
1764 	{{1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1},		\
1765 	{1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1}}
1766 #define CHN_LATENCY_PBUFSZ_REF				\
1767 	{{7, 9, 12, 13, 14, 15, 15, 15, 15, 15, 16},	\
1768 	{11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 17}}
1769 
1770 #define CHN_LATENCY_RBLKCNT_REF				\
1771 	{{9, 8, 7, 6, 5, 5, 4, 3, 2, 1, 1},		\
1772 	{9, 8, 7, 6, 5, 5, 4, 3, 2, 1, 1}}
1773 #define CHN_LATENCY_RBUFSZ_REF				\
1774 	{{14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 16},	\
1775 	{15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 17}}
1776 
1777 #define CHN_LATENCY_DATA_REF	192000 /* 48khz stereo 16bit ~ 48000 x 2 x 2 */
1778 
1779 static int
chn_calclatency(int dir,int latency,int bps,u_int32_t datarate,u_int32_t max,int * rblksz,int * rblkcnt)1780 chn_calclatency(int dir, int latency, int bps, u_int32_t datarate,
1781 				u_int32_t max, int *rblksz, int *rblkcnt)
1782 {
1783 	static int pblkcnts[CHN_LATENCY_PROFILE_MAX + 1][CHN_LATENCY_MAX + 1] =
1784 	    CHN_LATENCY_PBLKCNT_REF;
1785 	static int  pbufszs[CHN_LATENCY_PROFILE_MAX + 1][CHN_LATENCY_MAX + 1] =
1786 	    CHN_LATENCY_PBUFSZ_REF;
1787 	static int rblkcnts[CHN_LATENCY_PROFILE_MAX + 1][CHN_LATENCY_MAX + 1] =
1788 	    CHN_LATENCY_RBLKCNT_REF;
1789 	static int  rbufszs[CHN_LATENCY_PROFILE_MAX + 1][CHN_LATENCY_MAX + 1] =
1790 	    CHN_LATENCY_RBUFSZ_REF;
1791 	u_int32_t bufsz;
1792 	int lprofile, blksz, blkcnt;
1793 
1794 	if (latency < CHN_LATENCY_MIN || latency > CHN_LATENCY_MAX ||
1795 	    bps < 1 || datarate < 1 ||
1796 	    !(dir == PCMDIR_PLAY || dir == PCMDIR_REC)) {
1797 		if (rblksz != NULL)
1798 			*rblksz = CHN_2NDBUFMAXSIZE >> 1;
1799 		if (rblkcnt != NULL)
1800 			*rblkcnt = 2;
1801 		printf("%s(): FAILED dir=%d latency=%d bps=%d "
1802 		    "datarate=%u max=%u\n",
1803 		    __func__, dir, latency, bps, datarate, max);
1804 		return CHN_2NDBUFMAXSIZE;
1805 	}
1806 
1807 	lprofile = chn_latency_profile;
1808 
1809 	if (dir == PCMDIR_PLAY) {
1810 		blkcnt = pblkcnts[lprofile][latency];
1811 		bufsz = pbufszs[lprofile][latency];
1812 	} else {
1813 		blkcnt = rblkcnts[lprofile][latency];
1814 		bufsz = rbufszs[lprofile][latency];
1815 	}
1816 
1817 	bufsz = round_pow2(snd_xbytes(1 << bufsz, CHN_LATENCY_DATA_REF,
1818 	    datarate));
1819 	if (bufsz > max)
1820 		bufsz = max;
1821 	blksz = round_blksz(bufsz >> blkcnt, bps);
1822 
1823 	if (rblksz != NULL)
1824 		*rblksz = blksz;
1825 	if (rblkcnt != NULL)
1826 		*rblkcnt = 1 << blkcnt;
1827 
1828 	return blksz << blkcnt;
1829 }
1830 
1831 static int
chn_resizebuf(struct pcm_channel * c,int latency,int blkcnt,int blksz)1832 chn_resizebuf(struct pcm_channel *c, int latency,
1833 					int blkcnt, int blksz)
1834 {
1835 	struct snd_dbuf *b, *bs, *pb;
1836 	int sblksz, sblkcnt, hblksz, hblkcnt, limit = 0, nsblksz, nsblkcnt;
1837 	int ret;
1838 
1839 	CHN_LOCKASSERT(c);
1840 
1841 	if ((c->flags & (CHN_F_MMAP | CHN_F_TRIGGERED)) ||
1842 	    !(c->direction == PCMDIR_PLAY || c->direction == PCMDIR_REC))
1843 		return EINVAL;
1844 
1845 	if (latency == -1) {
1846 		c->latency = -1;
1847 		latency = chn_latency;
1848 	} else if (latency == -2) {
1849 		latency = c->latency;
1850 		if (latency < CHN_LATENCY_MIN || latency > CHN_LATENCY_MAX)
1851 			latency = chn_latency;
1852 	} else if (latency < CHN_LATENCY_MIN || latency > CHN_LATENCY_MAX)
1853 		return EINVAL;
1854 	else {
1855 		c->latency = latency;
1856 	}
1857 
1858 	bs = c->bufsoft;
1859 	b = c->bufhard;
1860 
1861 	if (!(blksz == 0 || blkcnt == -1) &&
1862 	    (blksz < 16 || blksz < bs->align || blkcnt < 2 ||
1863 	    (blksz * blkcnt) > CHN_2NDBUFMAXSIZE))
1864 		return EINVAL;
1865 
1866 	chn_calclatency(c->direction, latency, bs->align,
1867 	    bs->align * bs->spd, CHN_2NDBUFMAXSIZE,
1868 	    &sblksz, &sblkcnt);
1869 
1870 	if (blksz == 0 || blkcnt == -1) {
1871 		if (blkcnt == -1)
1872 			c->flags &= ~CHN_F_HAS_SIZE;
1873 		if (c->flags & CHN_F_HAS_SIZE) {
1874 			blksz = bs->blksz;
1875 			blkcnt = bs->blkcnt;
1876 		}
1877 	} else
1878 		c->flags |= CHN_F_HAS_SIZE;
1879 
1880 	if (c->flags & CHN_F_HAS_SIZE) {
1881 		/*
1882 		 * The application has requested their own blksz/blkcnt.
1883 		 * Just obey with it, and let them toast alone. We can
1884 		 * clamp it to the nearest latency profile, but that would
1885 		 * defeat the purpose of having custom control. The least
1886 		 * we can do is round it to the nearest ^2 and align it.
1887 		 */
1888 		sblksz = round_blksz(blksz, bs->align);
1889 		sblkcnt = round_pow2(blkcnt);
1890 	}
1891 
1892 	if (c->parentchannel != NULL) {
1893 		pb = c->parentchannel->bufsoft;
1894 		CHN_UNLOCK(c);
1895 		CHN_LOCK(c->parentchannel);
1896 		chn_notify(c->parentchannel, CHN_N_BLOCKSIZE);
1897 		CHN_UNLOCK(c->parentchannel);
1898 		CHN_LOCK(c);
1899 		if (c->direction == PCMDIR_PLAY) {
1900 			limit = (pb != NULL) ?
1901 			    sndbuf_xbytes(pb->bufsize, pb, bs) : 0;
1902 		} else {
1903 			limit = (pb != NULL) ?
1904 			    sndbuf_xbytes(pb->blksz, pb, bs) * 2 : 0;
1905 		}
1906 	} else {
1907 		hblkcnt = 2;
1908 		if (c->flags & CHN_F_HAS_SIZE) {
1909 			hblksz = round_blksz(sndbuf_xbytes(sblksz, bs, b),
1910 			    b->align);
1911 			hblkcnt = round_pow2(bs->blkcnt);
1912 		} else
1913 			chn_calclatency(c->direction, latency,
1914 			    b->align, b->align * b->spd,
1915 			    CHN_2NDBUFMAXSIZE, &hblksz, &hblkcnt);
1916 
1917 		if ((hblksz << 1) > b->maxsize)
1918 			hblksz = round_blksz(b->maxsize >> 1, b->align);
1919 
1920 		while ((hblksz * hblkcnt) > b->maxsize) {
1921 			if (hblkcnt < 4)
1922 				hblksz >>= 1;
1923 			else
1924 				hblkcnt >>= 1;
1925 		}
1926 
1927 		hblksz -= hblksz % b->align;
1928 
1929 		CHN_UNLOCK(c);
1930 		if (chn_usefrags == 0 ||
1931 		    CHANNEL_SETFRAGMENTS(c->methods, c->devinfo,
1932 		    hblksz, hblkcnt) != 0)
1933 			b->blksz = CHANNEL_SETBLOCKSIZE(c->methods,
1934 			    c->devinfo, hblksz);
1935 		CHN_LOCK(c);
1936 
1937 		if (!CHN_EMPTY(c, children)) {
1938 			nsblksz = round_blksz(
1939 			    sndbuf_xbytes(b->blksz, b, bs), bs->align);
1940 			nsblkcnt = b->blkcnt;
1941 			if (c->direction == PCMDIR_PLAY) {
1942 				do {
1943 					nsblkcnt--;
1944 				} while (nsblkcnt >= 2 &&
1945 				    nsblksz * nsblkcnt >= sblksz * sblkcnt);
1946 				nsblkcnt++;
1947 			}
1948 			sblksz = nsblksz;
1949 			sblkcnt = nsblkcnt;
1950 			limit = 0;
1951 		} else
1952 			limit = sndbuf_xbytes(b->blksz, b, bs) * 2;
1953 	}
1954 
1955 	if (limit > CHN_2NDBUFMAXSIZE)
1956 		limit = CHN_2NDBUFMAXSIZE;
1957 
1958 	while ((sblksz * sblkcnt) < limit)
1959 		sblkcnt <<= 1;
1960 
1961 	while ((sblksz * sblkcnt) > CHN_2NDBUFMAXSIZE) {
1962 		if (sblkcnt < 4)
1963 			sblksz >>= 1;
1964 		else
1965 			sblkcnt >>= 1;
1966 	}
1967 
1968 	sblksz -= sblksz % bs->align;
1969 
1970 	if (bs->blkcnt != sblkcnt || bs->blksz != sblksz ||
1971 	    bs->bufsize != (sblkcnt * sblksz)) {
1972 		ret = sndbuf_remalloc(bs, sblkcnt, sblksz);
1973 		if (ret != 0) {
1974 			device_printf(c->dev, "%s(): Failed: %d %d\n",
1975 			    __func__, sblkcnt, sblksz);
1976 			return ret;
1977 		}
1978 	}
1979 
1980 	/*
1981 	 * Interrupt timeout
1982 	 */
1983 	c->timeout = ((u_int64_t)hz * bs->bufsize) /
1984 	    ((u_int64_t)bs->spd * bs->align);
1985 	if (c->parentchannel != NULL)
1986 		c->timeout = min(c->timeout, c->parentchannel->timeout);
1987 	if (c->timeout < 1)
1988 		c->timeout = 1;
1989 
1990 	/*
1991 	 * OSSv4 docs: "By default OSS will set the low water level equal
1992 	 * to the fragment size which is optimal in most cases."
1993 	 */
1994 	c->lw = bs->blksz;
1995 	chn_resetbuf(c);
1996 
1997 	if (snd_verbose > 3)
1998 		device_printf(c->dev, "%s(): %s (%s) timeout=%u "
1999 		    "b[%d/%d/%d] bs[%d/%d/%d] limit=%d\n",
2000 		    __func__, CHN_DIRSTR(c),
2001 		    (c->flags & CHN_F_VIRTUAL) ? "virtual" : "hardware",
2002 		    c->timeout,
2003 		    b->bufsize, b->blksz,
2004 		    b->blkcnt,
2005 		    bs->bufsize, bs->blksz,
2006 		    bs->blkcnt, limit);
2007 
2008 	return 0;
2009 }
2010 
2011 int
chn_setlatency(struct pcm_channel * c,int latency)2012 chn_setlatency(struct pcm_channel *c, int latency)
2013 {
2014 	CHN_LOCKASSERT(c);
2015 	/* Destroy blksz/blkcnt, enforce latency profile. */
2016 	return chn_resizebuf(c, latency, -1, 0);
2017 }
2018 
2019 int
chn_setblocksize(struct pcm_channel * c,int blkcnt,int blksz)2020 chn_setblocksize(struct pcm_channel *c, int blkcnt, int blksz)
2021 {
2022 	CHN_LOCKASSERT(c);
2023 	/* Destroy latency profile, enforce blksz/blkcnt */
2024 	return chn_resizebuf(c, -1, blkcnt, blksz);
2025 }
2026 
2027 int
chn_setparam(struct pcm_channel * c,uint32_t format,uint32_t speed)2028 chn_setparam(struct pcm_channel *c, uint32_t format, uint32_t speed)
2029 {
2030 	struct pcmchan_caps *caps;
2031 	uint32_t hwspeed, delta;
2032 	int ret;
2033 
2034 	CHN_LOCKASSERT(c);
2035 
2036 	if (speed < 1 || format == 0 || CHN_STARTED(c))
2037 		return (EINVAL);
2038 
2039 	c->format = format;
2040 	c->speed = speed;
2041 
2042 	caps = chn_getcaps(c);
2043 
2044 	hwspeed = speed;
2045 	RANGE(hwspeed, caps->minspeed, caps->maxspeed);
2046 
2047 	sndbuf_setspd(c->bufhard, CHANNEL_SETSPEED(c->methods, c->devinfo,
2048 	    hwspeed));
2049 	hwspeed = c->bufhard->spd;
2050 
2051 	delta = (hwspeed > speed) ? (hwspeed - speed) : (speed - hwspeed);
2052 
2053 	if (delta <= feeder_rate_round)
2054 		c->speed = hwspeed;
2055 
2056 	ret = feeder_chain(c);
2057 
2058 	if (ret == 0)
2059 		ret = CHANNEL_SETFORMAT(c->methods, c->devinfo, c->bufhard->fmt);
2060 
2061 	if (ret == 0)
2062 		ret = chn_resizebuf(c, -2, 0, 0);
2063 
2064 	return (ret);
2065 }
2066 
2067 int
chn_setspeed(struct pcm_channel * c,uint32_t speed)2068 chn_setspeed(struct pcm_channel *c, uint32_t speed)
2069 {
2070 	uint32_t oldformat, oldspeed;
2071 	int ret;
2072 
2073 	oldformat = c->format;
2074 	oldspeed = c->speed;
2075 
2076 	if (c->speed == speed)
2077 		return (0);
2078 
2079 	ret = chn_setparam(c, c->format, speed);
2080 	if (ret != 0) {
2081 		if (snd_verbose > 3)
2082 			device_printf(c->dev,
2083 			    "%s(): Setting speed %d failed, "
2084 			    "falling back to %d\n",
2085 			    __func__, speed, oldspeed);
2086 		chn_setparam(c, oldformat, oldspeed);
2087 	}
2088 
2089 	return (ret);
2090 }
2091 
2092 int
chn_setformat(struct pcm_channel * c,uint32_t format)2093 chn_setformat(struct pcm_channel *c, uint32_t format)
2094 {
2095 	uint32_t oldformat, oldspeed;
2096 	int ret;
2097 
2098 	/* XXX force stereo */
2099 	if ((format & AFMT_PASSTHROUGH) && AFMT_CHANNEL(format) < 2) {
2100 		format = SND_FORMAT(format, AFMT_PASSTHROUGH_CHANNEL,
2101 		    AFMT_PASSTHROUGH_EXTCHANNEL);
2102 	}
2103 
2104 	oldformat = c->format;
2105 	oldspeed = c->speed;
2106 
2107 	if (c->format == format)
2108 		return (0);
2109 
2110 	ret = chn_setparam(c, format, c->speed);
2111 	if (ret != 0) {
2112 		if (snd_verbose > 3)
2113 			device_printf(c->dev,
2114 			    "%s(): Format change 0x%08x failed, "
2115 			    "falling back to 0x%08x\n",
2116 			    __func__, format, oldformat);
2117 		chn_setparam(c, oldformat, oldspeed);
2118 	}
2119 
2120 	return (ret);
2121 }
2122 
2123 void
chn_syncstate(struct pcm_channel * c)2124 chn_syncstate(struct pcm_channel *c)
2125 {
2126 	struct snddev_info *d;
2127 	struct snd_mixer *m;
2128 
2129 	d = (c != NULL) ? c->parentsnddev : NULL;
2130 	m = (d != NULL && d->mixer_dev != NULL) ? d->mixer_dev->si_drv1 :
2131 	    NULL;
2132 
2133 	if (d == NULL || m == NULL)
2134 		return;
2135 
2136 	CHN_LOCKASSERT(c);
2137 
2138 	if (c->feederflags & (1 << FEEDER_VOLUME)) {
2139 		uint32_t parent;
2140 		int vol, pvol, left, right, center;
2141 
2142 		if (c->direction == PCMDIR_PLAY &&
2143 		    (d->flags & SD_F_SOFTPCMVOL)) {
2144 			/* CHN_UNLOCK(c); */
2145 			vol = mix_get(m, SOUND_MIXER_PCM);
2146 			parent = mix_getparent(m, SOUND_MIXER_PCM);
2147 			if (parent != SOUND_MIXER_NONE)
2148 				pvol = mix_get(m, parent);
2149 			else
2150 				pvol = 100 | (100 << 8);
2151 			/* CHN_LOCK(c); */
2152 		} else {
2153 			vol = 100 | (100 << 8);
2154 			pvol = vol;
2155 		}
2156 
2157 		if (vol == -1) {
2158 			device_printf(c->dev,
2159 			    "Soft PCM Volume: Failed to read pcm "
2160 			    "default value\n");
2161 			vol = 100 | (100 << 8);
2162 		}
2163 
2164 		if (pvol == -1) {
2165 			device_printf(c->dev,
2166 			    "Soft PCM Volume: Failed to read parent "
2167 			    "default value\n");
2168 			pvol = 100 | (100 << 8);
2169 		}
2170 
2171 		left = ((vol & 0x7f) * (pvol & 0x7f)) / 100;
2172 		right = (((vol >> 8) & 0x7f) * ((pvol >> 8) & 0x7f)) / 100;
2173 		center = (left + right) >> 1;
2174 
2175 		chn_setvolume_multi(c, SND_VOL_C_MASTER, left, right, center);
2176 	}
2177 
2178 	if (c->feederflags & (1 << FEEDER_EQ)) {
2179 		struct pcm_feeder *f;
2180 		int treble, bass, state;
2181 
2182 		/* CHN_UNLOCK(c); */
2183 		treble = mix_get(m, SOUND_MIXER_TREBLE);
2184 		bass = mix_get(m, SOUND_MIXER_BASS);
2185 		/* CHN_LOCK(c); */
2186 
2187 		if (treble == -1)
2188 			treble = 50;
2189 		else
2190 			treble = ((treble & 0x7f) +
2191 			    ((treble >> 8) & 0x7f)) >> 1;
2192 
2193 		if (bass == -1)
2194 			bass = 50;
2195 		else
2196 			bass = ((bass & 0x7f) + ((bass >> 8) & 0x7f)) >> 1;
2197 
2198 		f = feeder_find(c, FEEDER_EQ);
2199 		if (f != NULL) {
2200 			if (FEEDER_SET(f, FEEDEQ_TREBLE, treble) != 0)
2201 				device_printf(c->dev,
2202 				    "EQ: Failed to set treble -- %d\n",
2203 				    treble);
2204 			if (FEEDER_SET(f, FEEDEQ_BASS, bass) != 0)
2205 				device_printf(c->dev,
2206 				    "EQ: Failed to set bass -- %d\n",
2207 				    bass);
2208 			if (FEEDER_SET(f, FEEDEQ_PREAMP, d->eqpreamp) != 0)
2209 				device_printf(c->dev,
2210 				    "EQ: Failed to set preamp -- %d\n",
2211 				    d->eqpreamp);
2212 			if (d->flags & SD_F_EQ_BYPASSED)
2213 				state = FEEDEQ_BYPASS;
2214 			else if (d->flags & SD_F_EQ_ENABLED)
2215 				state = FEEDEQ_ENABLE;
2216 			else
2217 				state = FEEDEQ_DISABLE;
2218 			if (FEEDER_SET(f, FEEDEQ_STATE, state) != 0)
2219 				device_printf(c->dev,
2220 				    "EQ: Failed to set state -- %d\n", state);
2221 		}
2222 	}
2223 }
2224 
2225 int
chn_trigger(struct pcm_channel * c,int go)2226 chn_trigger(struct pcm_channel *c, int go)
2227 {
2228 	struct snddev_info *d = c->parentsnddev;
2229 	int ret;
2230 
2231 	CHN_LOCKASSERT(c);
2232 	if (!PCMTRIG_COMMON(go))
2233 		return (CHANNEL_TRIGGER(c->methods, c->devinfo, go));
2234 
2235 	if (go == c->trigger)
2236 		return (0);
2237 
2238 	if (snd_verbose > 3) {
2239 		device_printf(c->dev, "%s() %s: calling go=0x%08x , "
2240 		    "prev=0x%08x\n", __func__, c->name, go, c->trigger);
2241 	}
2242 
2243 	c->trigger = go;
2244 	ret = CHANNEL_TRIGGER(c->methods, c->devinfo, go);
2245 	if (ret != 0)
2246 		return (ret);
2247 
2248 	CHN_UNLOCK(c);
2249 	PCM_LOCK(d);
2250 	CHN_LOCK(c);
2251 
2252 	/*
2253 	 * Do nothing if another thread set a different trigger while we had
2254 	 * dropped the mutex.
2255 	 */
2256 	if (go != c->trigger) {
2257 		PCM_UNLOCK(d);
2258 		return (0);
2259 	}
2260 
2261 	/*
2262 	 * Use the SAFE variants to prevent inserting/removing an already
2263 	 * existing/missing element.
2264 	 */
2265 	switch (go) {
2266 	case PCMTRIG_START:
2267 		CHN_INSERT_HEAD_SAFE(d, c, channels.pcm.busy);
2268 		PCM_UNLOCK(d);
2269 		chn_syncstate(c);
2270 		break;
2271 	case PCMTRIG_STOP:
2272 	case PCMTRIG_ABORT:
2273 		CHN_REMOVE(d, c, channels.pcm.busy);
2274 		PCM_UNLOCK(d);
2275 		break;
2276 	default:
2277 		PCM_UNLOCK(d);
2278 		break;
2279 	}
2280 
2281 	return (0);
2282 }
2283 
2284 /**
2285  * @brief Queries sound driver for sample-aligned hardware buffer pointer index
2286  *
2287  * This function obtains the hardware pointer location, then aligns it to
2288  * the current bytes-per-sample value before returning.  (E.g., a channel
2289  * running in 16 bit stereo mode would require 4 bytes per sample, so a
2290  * hwptr value ranging from 32-35 would be returned as 32.)
2291  *
2292  * @param c	PCM channel context
2293  * @returns 	sample-aligned hardware buffer pointer index
2294  */
2295 int
chn_getptr(struct pcm_channel * c)2296 chn_getptr(struct pcm_channel *c)
2297 {
2298 	int hwptr;
2299 
2300 	CHN_LOCKASSERT(c);
2301 	hwptr = (CHN_STARTED(c)) ? CHANNEL_GETPTR(c->methods, c->devinfo) : 0;
2302 	return (hwptr - (hwptr % c->bufhard->align));
2303 }
2304 
2305 struct pcmchan_caps *
chn_getcaps(struct pcm_channel * c)2306 chn_getcaps(struct pcm_channel *c)
2307 {
2308 	CHN_LOCKASSERT(c);
2309 	return CHANNEL_GETCAPS(c->methods, c->devinfo);
2310 }
2311 
2312 u_int32_t
chn_getformats(struct pcm_channel * c)2313 chn_getformats(struct pcm_channel *c)
2314 {
2315 	u_int32_t *fmtlist, fmts;
2316 	int i;
2317 
2318 	fmtlist = chn_getcaps(c)->fmtlist;
2319 	fmts = 0;
2320 	for (i = 0; fmtlist[i]; i++)
2321 		fmts |= fmtlist[i];
2322 
2323 	/* report software-supported formats */
2324 	if (!CHN_BITPERFECT(c) && report_soft_formats)
2325 		fmts |= AFMT_CONVERTIBLE;
2326 
2327 	return (AFMT_ENCODING(fmts));
2328 }
2329 
2330 int
chn_notify(struct pcm_channel * c,u_int32_t flags)2331 chn_notify(struct pcm_channel *c, u_int32_t flags)
2332 {
2333 	struct pcm_channel *ch;
2334 	struct pcmchan_caps *caps;
2335 	uint32_t bestformat, bestspeed, besthwformat, *vchanformat, *vchanrate;
2336 	uint32_t vpflags;
2337 	int dirty, err, run, nrun;
2338 
2339 	CHN_LOCKASSERT(c);
2340 
2341 	if (CHN_EMPTY(c, children))
2342 		return (0);
2343 
2344 	err = 0;
2345 
2346 	/*
2347 	 * If the hwchan is running, we can't change its rate, format or
2348 	 * blocksize
2349 	 */
2350 	run = (CHN_STARTED(c)) ? 1 : 0;
2351 	if (run)
2352 		flags &= CHN_N_VOLUME | CHN_N_TRIGGER;
2353 
2354 	if (flags & CHN_N_RATE) {
2355 		/*
2356 		 * XXX I'll make good use of this someday.
2357 		 *     However this is currently being superseded by
2358 		 *     the availability of CHN_F_VCHAN_DYNAMIC.
2359 		 */
2360 	}
2361 
2362 	if (flags & CHN_N_FORMAT) {
2363 		/*
2364 		 * XXX I'll make good use of this someday.
2365 		 *     However this is currently being superseded by
2366 		 *     the availability of CHN_F_VCHAN_DYNAMIC.
2367 		 */
2368 	}
2369 
2370 	if (flags & CHN_N_VOLUME) {
2371 		/*
2372 		 * XXX I'll make good use of this someday, though
2373 		 *     soft volume control is currently pretty much
2374 		 *     integrated.
2375 		 */
2376 	}
2377 
2378 	if (flags & CHN_N_BLOCKSIZE) {
2379 		/*
2380 		 * Set to default latency profile
2381 		 */
2382 		chn_setlatency(c, chn_latency);
2383 	}
2384 
2385 	if ((flags & CHN_N_TRIGGER) && !(c->flags & CHN_F_VCHAN_DYNAMIC)) {
2386 		nrun = CHN_EMPTY(c, children.busy) ? 0 : 1;
2387 		if (nrun && !run)
2388 			err = chn_start(c, 1);
2389 		if (!nrun && run)
2390 			chn_abort(c);
2391 		flags &= ~CHN_N_TRIGGER;
2392 	}
2393 
2394 	if (flags & CHN_N_TRIGGER) {
2395 		if (c->direction == PCMDIR_PLAY) {
2396 			vchanformat = &c->parentsnddev->pvchanformat;
2397 			vchanrate = &c->parentsnddev->pvchanrate;
2398 		} else {
2399 			vchanformat = &c->parentsnddev->rvchanformat;
2400 			vchanrate = &c->parentsnddev->rvchanrate;
2401 		}
2402 
2403 		/* Dynamic Virtual Channel */
2404 		if (!(c->flags & CHN_F_VCHAN_ADAPTIVE)) {
2405 			bestformat = *vchanformat;
2406 			bestspeed = *vchanrate;
2407 		} else {
2408 			bestformat = 0;
2409 			bestspeed = 0;
2410 		}
2411 
2412 		besthwformat = 0;
2413 		nrun = 0;
2414 		caps = chn_getcaps(c);
2415 		dirty = 0;
2416 		vpflags = 0;
2417 
2418 		CHN_FOREACH(ch, c, children.busy) {
2419 			CHN_LOCK(ch);
2420 			if ((ch->format & AFMT_PASSTHROUGH) &&
2421 			    snd_fmtvalid(ch->format, caps->fmtlist)) {
2422 				bestformat = ch->format;
2423 				bestspeed = ch->speed;
2424 				CHN_UNLOCK(ch);
2425 				vpflags = CHN_F_PASSTHROUGH;
2426 				nrun++;
2427 				break;
2428 			}
2429 			if ((ch->flags & CHN_F_EXCLUSIVE) && vpflags == 0) {
2430 				if (c->flags & CHN_F_VCHAN_ADAPTIVE) {
2431 					bestspeed = ch->speed;
2432 					RANGE(bestspeed, caps->minspeed,
2433 					    caps->maxspeed);
2434 					besthwformat = snd_fmtbest(ch->format,
2435 					    caps->fmtlist);
2436 					if (besthwformat != 0)
2437 						bestformat = besthwformat;
2438 				}
2439 				CHN_UNLOCK(ch);
2440 				vpflags = CHN_F_EXCLUSIVE;
2441 				nrun++;
2442 				continue;
2443 			}
2444 			if (!(c->flags & CHN_F_VCHAN_ADAPTIVE) ||
2445 			    vpflags != 0) {
2446 				CHN_UNLOCK(ch);
2447 				nrun++;
2448 				continue;
2449 			}
2450 			if (ch->speed > bestspeed) {
2451 				bestspeed = ch->speed;
2452 				RANGE(bestspeed, caps->minspeed,
2453 				    caps->maxspeed);
2454 			}
2455 			besthwformat = snd_fmtbest(ch->format, caps->fmtlist);
2456 			if (!(besthwformat & AFMT_VCHAN)) {
2457 				CHN_UNLOCK(ch);
2458 				nrun++;
2459 				continue;
2460 			}
2461 			if (AFMT_CHANNEL(besthwformat) >
2462 			    AFMT_CHANNEL(bestformat))
2463 				bestformat = besthwformat;
2464 			else if (AFMT_CHANNEL(besthwformat) ==
2465 			    AFMT_CHANNEL(bestformat) &&
2466 			    AFMT_BIT(besthwformat) > AFMT_BIT(bestformat))
2467 				bestformat = besthwformat;
2468 			CHN_UNLOCK(ch);
2469 			nrun++;
2470 		}
2471 
2472 		if (bestformat == 0)
2473 			bestformat = c->format;
2474 		if (bestspeed == 0)
2475 			bestspeed = c->speed;
2476 
2477 		if (bestformat != c->format || bestspeed != c->speed)
2478 			dirty = 1;
2479 
2480 		c->flags &= ~(CHN_F_PASSTHROUGH | CHN_F_EXCLUSIVE);
2481 		c->flags |= vpflags;
2482 
2483 		if (nrun && !run) {
2484 			if (dirty) {
2485 				bestspeed = CHANNEL_SETSPEED(c->methods,
2486 				    c->devinfo, bestspeed);
2487 				err = chn_reset(c, bestformat, bestspeed);
2488 			}
2489 			if (err == 0 && dirty) {
2490 				CHN_FOREACH(ch, c, children.busy) {
2491 					CHN_LOCK(ch);
2492 					if (VCHAN_SYNC_REQUIRED(ch))
2493 						vchan_sync(ch);
2494 					CHN_UNLOCK(ch);
2495 				}
2496 			}
2497 			if (err == 0) {
2498 				if (dirty)
2499 					c->flags |= CHN_F_DIRTY;
2500 				err = chn_start(c, 1);
2501 			}
2502 		}
2503 
2504 		if (nrun && run && dirty) {
2505 			chn_abort(c);
2506 			bestspeed = CHANNEL_SETSPEED(c->methods, c->devinfo,
2507 			    bestspeed);
2508 			err = chn_reset(c, bestformat, bestspeed);
2509 			if (err == 0) {
2510 				CHN_FOREACH(ch, c, children.busy) {
2511 					CHN_LOCK(ch);
2512 					if (VCHAN_SYNC_REQUIRED(ch))
2513 						vchan_sync(ch);
2514 					CHN_UNLOCK(ch);
2515 				}
2516 			}
2517 			if (err == 0) {
2518 				c->flags |= CHN_F_DIRTY;
2519 				err = chn_start(c, 1);
2520 			}
2521 		}
2522 
2523 		if (err == 0 && !(bestformat & AFMT_PASSTHROUGH) &&
2524 		    (bestformat & AFMT_VCHAN)) {
2525 			*vchanformat = bestformat;
2526 			*vchanrate = bestspeed;
2527 		}
2528 
2529 		if (!nrun && run) {
2530 			c->flags &= ~(CHN_F_PASSTHROUGH | CHN_F_EXCLUSIVE);
2531 			bestformat = *vchanformat;
2532 			bestspeed = *vchanrate;
2533 			chn_abort(c);
2534 			if (c->format != bestformat || c->speed != bestspeed)
2535 				chn_reset(c, bestformat, bestspeed);
2536 		}
2537 	}
2538 
2539 	return (err);
2540 }
2541 
2542 /**
2543  * @brief Fetch array of supported discrete sample rates
2544  *
2545  * Wrapper for CHANNEL_GETRATES.  Please see channel_if.m:getrates() for
2546  * detailed information.
2547  *
2548  * @note If the operation isn't supported, this function will just return 0
2549  *       (no rates in the array), and *rates will be set to NULL.  Callers
2550  *       should examine rates @b only if this function returns non-zero.
2551  *
2552  * @param c	pcm channel to examine
2553  * @param rates	pointer to array of integers; rate table will be recorded here
2554  *
2555  * @return number of rates in the array pointed to be @c rates
2556  */
2557 int
chn_getrates(struct pcm_channel * c,int ** rates)2558 chn_getrates(struct pcm_channel *c, int **rates)
2559 {
2560 	KASSERT(rates != NULL, ("rates is null"));
2561 	CHN_LOCKASSERT(c);
2562 	return CHANNEL_GETRATES(c->methods, c->devinfo, rates);
2563 }
2564 
2565 /**
2566  * @brief Remove channel from a sync group, if there is one.
2567  *
2568  * This function is initially intended for the following conditions:
2569  *   - Starting a syncgroup (@c SNDCTL_DSP_SYNCSTART ioctl)
2570  *   - Closing a device.  (A channel can't be destroyed if it's still in use.)
2571  *
2572  * @note Before calling this function, the syncgroup list mutex must be
2573  * held.  (Consider pcm_channel::sm protected by the SG list mutex
2574  * whether @c c is locked or not.)
2575  *
2576  * @param c	channel device to be started or closed
2577  * @returns	If this channel was the only member of a group, the group ID
2578  * 		is returned to the caller so that the caller can release it
2579  * 		via free_unr() after giving up the syncgroup lock.  Else it
2580  * 		returns 0.
2581  */
2582 int
chn_syncdestroy(struct pcm_channel * c)2583 chn_syncdestroy(struct pcm_channel *c)
2584 {
2585 	struct pcmchan_syncmember *sm;
2586 	struct pcmchan_syncgroup *sg;
2587 	int sg_id;
2588 
2589 	sg_id = 0;
2590 
2591 	PCM_SG_LOCKASSERT(MA_OWNED);
2592 
2593 	if (c->sm != NULL) {
2594 		sm = c->sm;
2595 		sg = sm->parent;
2596 		c->sm = NULL;
2597 
2598 		KASSERT(sg != NULL, ("syncmember has null parent"));
2599 
2600 		SLIST_REMOVE(&sg->members, sm, pcmchan_syncmember, link);
2601 		free(sm, M_DEVBUF);
2602 
2603 		if (SLIST_EMPTY(&sg->members)) {
2604 			SLIST_REMOVE(&snd_pcm_syncgroups, sg, pcmchan_syncgroup, link);
2605 			sg_id = sg->id;
2606 			free(sg, M_DEVBUF);
2607 		}
2608 	}
2609 
2610 	return sg_id;
2611 }
2612 
2613 #ifdef OSSV4_EXPERIMENT
2614 int
chn_getpeaks(struct pcm_channel * c,int * lpeak,int * rpeak)2615 chn_getpeaks(struct pcm_channel *c, int *lpeak, int *rpeak)
2616 {
2617 	CHN_LOCKASSERT(c);
2618 	return CHANNEL_GETPEAKS(c->methods, c->devinfo, lpeak, rpeak);
2619 }
2620 #endif
2621