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