audio.c revision 1.74
1/*	$NetBSD: audio.c,v 1.74 2020/05/26 15:20:16 nia Exp $	*/
2
3/*-
4 * Copyright (c) 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32/*
33 * Copyright (c) 1991-1993 Regents of the University of California.
34 * All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 * 1. Redistributions of source code must retain the above copyright
40 *    notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 *    notice, this list of conditions and the following disclaimer in the
43 *    documentation and/or other materials provided with the distribution.
44 * 3. All advertising materials mentioning features or use of this software
45 *    must display the following acknowledgement:
46 *	This product includes software developed by the Computer Systems
47 *	Engineering Group at Lawrence Berkeley Laboratory.
48 * 4. Neither the name of the University nor of the Laboratory may be used
49 *    to endorse or promote products derived from this software without
50 *    specific prior written permission.
51 *
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * SUCH DAMAGE.
63 */
64
65/*
66 * Locking: there are three locks per device.
67 *
68 * - sc_lock, provided by the underlying driver.  This is an adaptive lock,
69 *   returned in the second parameter to hw_if->get_locks().  It is known
70 *   as the "thread lock".
71 *
72 *   It serializes access to state in all places except the
73 *   driver's interrupt service routine.  This lock is taken from process
74 *   context (example: access to /dev/audio).  It is also taken from soft
75 *   interrupt handlers in this module, primarily to serialize delivery of
76 *   wakeups.  This lock may be used/provided by modules external to the
77 *   audio subsystem, so take care not to introduce a lock order problem.
78 *   LONG TERM SLEEPS MUST NOT OCCUR WITH THIS LOCK HELD.
79 *
80 * - sc_intr_lock, provided by the underlying driver.  This may be either a
81 *   spinlock (at IPL_SCHED or IPL_VM) or an adaptive lock (IPL_NONE or
82 *   IPL_SOFT*), returned in the first parameter to hw_if->get_locks().  It
83 *   is known as the "interrupt lock".
84 *
85 *   It provides atomic access to the device's hardware state, and to audio
86 *   channel data that may be accessed by the hardware driver's ISR.
87 *   In all places outside the ISR, sc_lock must be held before taking
88 *   sc_intr_lock.  This is to ensure that groups of hardware operations are
89 *   made atomically.  SLEEPS CANNOT OCCUR WITH THIS LOCK HELD.
90 *
91 * - sc_exlock, private to this module.  This is a variable protected by
92 *   sc_lock.  It is known as the "critical section".
93 *   Some operations release sc_lock in order to allocate memory, to wait
94 *   for in-flight I/O to complete, to copy to/from user context, etc.
95 *   sc_exlock provides a critical section even under the circumstance.
96 *   "+" in following list indicates the interfaces which necessary to be
97 *   protected by sc_exlock.
98 *
99 * List of hardware interface methods, and which locks are held when each
100 * is called by this module:
101 *
102 *	METHOD			INTR	THREAD  NOTES
103 *	----------------------- ------- -------	-------------------------
104 *	open 			x	x +
105 *	close 			x	x +
106 *	query_format		-	x
107 *	set_format		-	x
108 *	round_blocksize		-	x
109 *	commit_settings		-	x
110 *	init_output 		x	x
111 *	init_input 		x	x
112 *	start_output 		x	x +
113 *	start_input 		x	x +
114 *	halt_output 		x	x +
115 *	halt_input 		x	x +
116 *	speaker_ctl 		x	x
117 *	getdev 			-	x
118 *	set_port 		-	x +
119 *	get_port 		-	x +
120 *	query_devinfo 		-	x
121 *	allocm 			-	- +
122 *	freem 			-	- +
123 *	round_buffersize 	-	x
124 *	get_props 		-	-	Called at attach time
125 *	trigger_output 		x	x +
126 *	trigger_input 		x	x +
127 *	dev_ioctl 		-	x
128 *	get_locks 		-	-	Called at attach time
129 *
130 * In addition, there is an additional lock.
131 *
132 * - track->lock.  This is an atomic variable and is similar to the
133 *   "interrupt lock".  This is one for each track.  If any thread context
134 *   (and software interrupt context) and hardware interrupt context who
135 *   want to access some variables on this track, they must acquire this
136 *   lock before.  It protects track's consistency between hardware
137 *   interrupt context and others.
138 */
139
140#include <sys/cdefs.h>
141__KERNEL_RCSID(0, "$NetBSD: audio.c,v 1.74 2020/05/26 15:20:16 nia Exp $");
142
143#ifdef _KERNEL_OPT
144#include "audio.h"
145#include "midi.h"
146#endif
147
148#if NAUDIO > 0
149
150#include <sys/types.h>
151#include <sys/param.h>
152#include <sys/atomic.h>
153#include <sys/audioio.h>
154#include <sys/conf.h>
155#include <sys/cpu.h>
156#include <sys/device.h>
157#include <sys/fcntl.h>
158#include <sys/file.h>
159#include <sys/filedesc.h>
160#include <sys/intr.h>
161#include <sys/ioctl.h>
162#include <sys/kauth.h>
163#include <sys/kernel.h>
164#include <sys/kmem.h>
165#include <sys/malloc.h>
166#include <sys/mman.h>
167#include <sys/module.h>
168#include <sys/poll.h>
169#include <sys/proc.h>
170#include <sys/queue.h>
171#include <sys/select.h>
172#include <sys/signalvar.h>
173#include <sys/stat.h>
174#include <sys/sysctl.h>
175#include <sys/systm.h>
176#include <sys/syslog.h>
177#include <sys/vnode.h>
178
179#include <dev/audio/audio_if.h>
180#include <dev/audio/audiovar.h>
181#include <dev/audio/audiodef.h>
182#include <dev/audio/linear.h>
183#include <dev/audio/mulaw.h>
184
185#include <machine/endian.h>
186
187#include <uvm/uvm_extern.h>
188
189#include "ioconf.h"
190
191/*
192 * 0: No debug logs
193 * 1: action changes like open/close/set_format...
194 * 2: + normal operations like read/write/ioctl...
195 * 3: + TRACEs except interrupt
196 * 4: + TRACEs including interrupt
197 */
198//#define AUDIO_DEBUG 1
199
200#if defined(AUDIO_DEBUG)
201
202int audiodebug = AUDIO_DEBUG;
203static void audio_vtrace(struct audio_softc *sc, const char *, const char *,
204	const char *, va_list);
205static void audio_trace(struct audio_softc *sc, const char *, const char *, ...)
206	__printflike(3, 4);
207static void audio_tracet(const char *, audio_track_t *, const char *, ...)
208	__printflike(3, 4);
209static void audio_tracef(const char *, audio_file_t *, const char *, ...)
210	__printflike(3, 4);
211
212/* XXX sloppy memory logger */
213static void audio_mlog_init(void);
214static void audio_mlog_free(void);
215static void audio_mlog_softintr(void *);
216extern void audio_mlog_flush(void);
217extern void audio_mlog_printf(const char *, ...);
218
219static int mlog_refs;		/* reference counter */
220static char *mlog_buf[2];	/* double buffer */
221static int mlog_buflen;		/* buffer length */
222static int mlog_used;		/* used length */
223static int mlog_full;		/* number of dropped lines by buffer full */
224static int mlog_drop;		/* number of dropped lines by busy */
225static volatile uint32_t mlog_inuse;	/* in-use */
226static int mlog_wpage;		/* active page */
227static void *mlog_sih;		/* softint handle */
228
229static void
230audio_mlog_init(void)
231{
232	mlog_refs++;
233	if (mlog_refs > 1)
234		return;
235	mlog_buflen = 4096;
236	mlog_buf[0] = kmem_zalloc(mlog_buflen, KM_SLEEP);
237	mlog_buf[1] = kmem_zalloc(mlog_buflen, KM_SLEEP);
238	mlog_used = 0;
239	mlog_full = 0;
240	mlog_drop = 0;
241	mlog_inuse = 0;
242	mlog_wpage = 0;
243	mlog_sih = softint_establish(SOFTINT_SERIAL, audio_mlog_softintr, NULL);
244	if (mlog_sih == NULL)
245		printf("%s: softint_establish failed\n", __func__);
246}
247
248static void
249audio_mlog_free(void)
250{
251	mlog_refs--;
252	if (mlog_refs > 0)
253		return;
254
255	audio_mlog_flush();
256	if (mlog_sih)
257		softint_disestablish(mlog_sih);
258	kmem_free(mlog_buf[0], mlog_buflen);
259	kmem_free(mlog_buf[1], mlog_buflen);
260}
261
262/*
263 * Flush memory buffer.
264 * It must not be called from hardware interrupt context.
265 */
266void
267audio_mlog_flush(void)
268{
269	if (mlog_refs == 0)
270		return;
271
272	/* Nothing to do if already in use ? */
273	if (atomic_swap_32(&mlog_inuse, 1) == 1)
274		return;
275
276	int rpage = mlog_wpage;
277	mlog_wpage ^= 1;
278	mlog_buf[mlog_wpage][0] = '\0';
279	mlog_used = 0;
280
281	atomic_swap_32(&mlog_inuse, 0);
282
283	if (mlog_buf[rpage][0] != '\0') {
284		printf("%s", mlog_buf[rpage]);
285		if (mlog_drop > 0)
286			printf("mlog_drop %d\n", mlog_drop);
287		if (mlog_full > 0)
288			printf("mlog_full %d\n", mlog_full);
289	}
290	mlog_full = 0;
291	mlog_drop = 0;
292}
293
294static void
295audio_mlog_softintr(void *cookie)
296{
297	audio_mlog_flush();
298}
299
300void
301audio_mlog_printf(const char *fmt, ...)
302{
303	int len;
304	va_list ap;
305
306	if (atomic_swap_32(&mlog_inuse, 1) == 1) {
307		/* already inuse */
308		mlog_drop++;
309		return;
310	}
311
312	va_start(ap, fmt);
313	len = vsnprintf(
314	    mlog_buf[mlog_wpage] + mlog_used,
315	    mlog_buflen - mlog_used,
316	    fmt, ap);
317	va_end(ap);
318
319	mlog_used += len;
320	if (mlog_buflen - mlog_used <= 1) {
321		mlog_full++;
322	}
323
324	atomic_swap_32(&mlog_inuse, 0);
325
326	if (mlog_sih)
327		softint_schedule(mlog_sih);
328}
329
330/* trace functions */
331static void
332audio_vtrace(struct audio_softc *sc, const char *funcname, const char *header,
333	const char *fmt, va_list ap)
334{
335	char buf[256];
336	int n;
337
338	n = 0;
339	buf[0] = '\0';
340	n += snprintf(buf + n, sizeof(buf) - n, "%s@%d %s",
341	    funcname, device_unit(sc->sc_dev), header);
342	n += vsnprintf(buf + n, sizeof(buf) - n, fmt, ap);
343
344	if (cpu_intr_p()) {
345		audio_mlog_printf("%s\n", buf);
346	} else {
347		audio_mlog_flush();
348		printf("%s\n", buf);
349	}
350}
351
352static void
353audio_trace(struct audio_softc *sc, const char *funcname, const char *fmt, ...)
354{
355	va_list ap;
356
357	va_start(ap, fmt);
358	audio_vtrace(sc, funcname, "", fmt, ap);
359	va_end(ap);
360}
361
362static void
363audio_tracet(const char *funcname, audio_track_t *track, const char *fmt, ...)
364{
365	char hdr[16];
366	va_list ap;
367
368	snprintf(hdr, sizeof(hdr), "#%d ", track->id);
369	va_start(ap, fmt);
370	audio_vtrace(track->mixer->sc, funcname, hdr, fmt, ap);
371	va_end(ap);
372}
373
374static void
375audio_tracef(const char *funcname, audio_file_t *file, const char *fmt, ...)
376{
377	char hdr[32];
378	char phdr[16], rhdr[16];
379	va_list ap;
380
381	phdr[0] = '\0';
382	rhdr[0] = '\0';
383	if (file->ptrack)
384		snprintf(phdr, sizeof(phdr), "#%d", file->ptrack->id);
385	if (file->rtrack)
386		snprintf(rhdr, sizeof(rhdr), "#%d", file->rtrack->id);
387	snprintf(hdr, sizeof(hdr), "{%s,%s} ", phdr, rhdr);
388
389	va_start(ap, fmt);
390	audio_vtrace(file->sc, funcname, hdr, fmt, ap);
391	va_end(ap);
392}
393
394#define DPRINTF(n, fmt...)	do {	\
395	if (audiodebug >= (n)) {	\
396		audio_mlog_flush();	\
397		printf(fmt);		\
398	}				\
399} while (0)
400#define TRACE(n, fmt...)	do { \
401	if (audiodebug >= (n)) audio_trace(sc, __func__, fmt); \
402} while (0)
403#define TRACET(n, t, fmt...)	do { \
404	if (audiodebug >= (n)) audio_tracet(__func__, t, fmt); \
405} while (0)
406#define TRACEF(n, f, fmt...)	do { \
407	if (audiodebug >= (n)) audio_tracef(__func__, f, fmt); \
408} while (0)
409
410struct audio_track_debugbuf {
411	char usrbuf[32];
412	char codec[32];
413	char chvol[32];
414	char chmix[32];
415	char freq[32];
416	char outbuf[32];
417};
418
419static void
420audio_track_bufstat(audio_track_t *track, struct audio_track_debugbuf *buf)
421{
422
423	memset(buf, 0, sizeof(*buf));
424
425	snprintf(buf->outbuf, sizeof(buf->outbuf), " out=%d/%d/%d",
426	    track->outbuf.head, track->outbuf.used, track->outbuf.capacity);
427	if (track->freq.filter)
428		snprintf(buf->freq, sizeof(buf->freq), " f=%d/%d/%d",
429		    track->freq.srcbuf.head,
430		    track->freq.srcbuf.used,
431		    track->freq.srcbuf.capacity);
432	if (track->chmix.filter)
433		snprintf(buf->chmix, sizeof(buf->chmix), " m=%d",
434		    track->chmix.srcbuf.used);
435	if (track->chvol.filter)
436		snprintf(buf->chvol, sizeof(buf->chvol), " v=%d",
437		    track->chvol.srcbuf.used);
438	if (track->codec.filter)
439		snprintf(buf->codec, sizeof(buf->codec), " e=%d",
440		    track->codec.srcbuf.used);
441	snprintf(buf->usrbuf, sizeof(buf->usrbuf), " usr=%d/%d/H%d",
442	    track->usrbuf.head, track->usrbuf.used, track->usrbuf_usedhigh);
443}
444#else
445#define DPRINTF(n, fmt...)	do { } while (0)
446#define TRACE(n, fmt, ...)	do { } while (0)
447#define TRACET(n, t, fmt, ...)	do { } while (0)
448#define TRACEF(n, f, fmt, ...)	do { } while (0)
449#endif
450
451#define SPECIFIED(x)	((x) != ~0)
452#define SPECIFIED_CH(x)	((x) != (u_char)~0)
453
454/*
455 * Default hardware blocksize in msec.
456 *
457 * We use 10 msec for most modern platforms.  This period is good enough to
458 * play audio and video synchronizely.
459 * In contrast, for very old platforms, this is usually too short and too
460 * severe.  Also such platforms usually can not play video confortably, so
461 * it's not so important to make the blocksize shorter.  If the platform
462 * defines its own value as __AUDIO_BLK_MS in its <machine/param.h>, it
463 * uses this instead.
464 *
465 * In either case, you can overwrite AUDIO_BLK_MS by your kernel
466 * configuration file if you wish.
467 */
468#if !defined(AUDIO_BLK_MS)
469# if defined(__AUDIO_BLK_MS)
470#  define AUDIO_BLK_MS __AUDIO_BLK_MS
471# else
472#  define AUDIO_BLK_MS (10)
473# endif
474#endif
475
476/* Device timeout in msec */
477#define AUDIO_TIMEOUT	(3000)
478
479/* #define AUDIO_PM_IDLE */
480#ifdef AUDIO_PM_IDLE
481int audio_idle_timeout = 30;
482#endif
483
484/* Number of elements of async mixer's pid */
485#define AM_CAPACITY	(4)
486
487struct portname {
488	const char *name;
489	int mask;
490};
491
492static int audiomatch(device_t, cfdata_t, void *);
493static void audioattach(device_t, device_t, void *);
494static int audiodetach(device_t, int);
495static int audioactivate(device_t, enum devact);
496static void audiochilddet(device_t, device_t);
497static int audiorescan(device_t, const char *, const int *);
498
499static int audio_modcmd(modcmd_t, void *);
500
501#ifdef AUDIO_PM_IDLE
502static void audio_idle(void *);
503static void audio_activity(device_t, devactive_t);
504#endif
505
506static bool audio_suspend(device_t dv, const pmf_qual_t *);
507static bool audio_resume(device_t dv, const pmf_qual_t *);
508static void audio_volume_down(device_t);
509static void audio_volume_up(device_t);
510static void audio_volume_toggle(device_t);
511
512static void audio_mixer_capture(struct audio_softc *);
513static void audio_mixer_restore(struct audio_softc *);
514
515static void audio_softintr_rd(void *);
516static void audio_softintr_wr(void *);
517
518static int audio_exlock_mutex_enter(struct audio_softc *);
519static void audio_exlock_mutex_exit(struct audio_softc *);
520static int audio_exlock_enter(struct audio_softc *);
521static void audio_exlock_exit(struct audio_softc *);
522static struct audio_softc *audio_file_enter(audio_file_t *, struct psref *);
523static void audio_file_exit(struct audio_softc *, struct psref *);
524static int audio_track_waitio(struct audio_softc *, audio_track_t *);
525
526static int audioclose(struct file *);
527static int audioread(struct file *, off_t *, struct uio *, kauth_cred_t, int);
528static int audiowrite(struct file *, off_t *, struct uio *, kauth_cred_t, int);
529static int audioioctl(struct file *, u_long, void *);
530static int audiopoll(struct file *, int);
531static int audiokqfilter(struct file *, struct knote *);
532static int audiommap(struct file *, off_t *, size_t, int, int *, int *,
533	struct uvm_object **, int *);
534static int audiostat(struct file *, struct stat *);
535
536static void filt_audiowrite_detach(struct knote *);
537static int  filt_audiowrite_event(struct knote *, long);
538static void filt_audioread_detach(struct knote *);
539static int  filt_audioread_event(struct knote *, long);
540
541static int audio_open(dev_t, struct audio_softc *, int, int, struct lwp *,
542	audio_file_t **);
543static int audio_close(struct audio_softc *, audio_file_t *);
544static int audio_unlink(struct audio_softc *, audio_file_t *);
545static int audio_read(struct audio_softc *, struct uio *, int, audio_file_t *);
546static int audio_write(struct audio_softc *, struct uio *, int, audio_file_t *);
547static void audio_file_clear(struct audio_softc *, audio_file_t *);
548static int audio_ioctl(dev_t, struct audio_softc *, u_long, void *, int,
549	struct lwp *, audio_file_t *);
550static int audio_poll(struct audio_softc *, int, struct lwp *, audio_file_t *);
551static int audio_kqfilter(struct audio_softc *, audio_file_t *, struct knote *);
552static int audio_mmap(struct audio_softc *, off_t *, size_t, int, int *, int *,
553	struct uvm_object **, int *, audio_file_t *);
554
555static int audioctl_open(dev_t, struct audio_softc *, int, int, struct lwp *);
556
557static void audio_pintr(void *);
558static void audio_rintr(void *);
559
560static int audio_query_devinfo(struct audio_softc *, mixer_devinfo_t *);
561
562static __inline int audio_track_readablebytes(const audio_track_t *);
563static int audio_file_setinfo(struct audio_softc *, audio_file_t *,
564	const struct audio_info *);
565static int audio_track_setinfo_check(audio_track_t *,
566	audio_format2_t *, const struct audio_prinfo *);
567static void audio_track_setinfo_water(audio_track_t *,
568	const struct audio_info *);
569static int audio_hw_setinfo(struct audio_softc *, const struct audio_info *,
570	struct audio_info *);
571static int audio_hw_set_format(struct audio_softc *, int,
572	const audio_format2_t *, const audio_format2_t *,
573	audio_filter_reg_t *, audio_filter_reg_t *);
574static int audiogetinfo(struct audio_softc *, struct audio_info *, int,
575	audio_file_t *);
576static bool audio_can_playback(struct audio_softc *);
577static bool audio_can_capture(struct audio_softc *);
578static int audio_check_params(audio_format2_t *);
579static int audio_mixers_init(struct audio_softc *sc, int,
580	const audio_format2_t *, const audio_format2_t *,
581	const audio_filter_reg_t *, const audio_filter_reg_t *);
582static int audio_select_freq(const struct audio_format *);
583static int audio_hw_probe(struct audio_softc *, audio_format2_t *, int);
584static int audio_hw_validate_format(struct audio_softc *, int,
585	const audio_format2_t *);
586static int audio_mixers_set_format(struct audio_softc *,
587	const struct audio_info *);
588static void audio_mixers_get_format(struct audio_softc *, struct audio_info *);
589static int audio_sysctl_blk_ms(SYSCTLFN_PROTO);
590static int audio_sysctl_multiuser(SYSCTLFN_PROTO);
591#if defined(AUDIO_DEBUG)
592static int audio_sysctl_debug(SYSCTLFN_PROTO);
593static void audio_format2_tostr(char *, size_t, const audio_format2_t *);
594static void audio_print_format2(const char *, const audio_format2_t *) __unused;
595#endif
596
597static void *audio_realloc(void *, size_t);
598static int audio_realloc_usrbuf(audio_track_t *, int);
599static void audio_free_usrbuf(audio_track_t *);
600
601static audio_track_t *audio_track_create(struct audio_softc *,
602	audio_trackmixer_t *);
603static void audio_track_destroy(audio_track_t *);
604static audio_filter_t audio_track_get_codec(audio_track_t *,
605	const audio_format2_t *, const audio_format2_t *);
606static int audio_track_set_format(audio_track_t *, audio_format2_t *);
607static void audio_track_play(audio_track_t *);
608static int audio_track_drain(struct audio_softc *, audio_track_t *);
609static void audio_track_record(audio_track_t *);
610static void audio_track_clear(struct audio_softc *, audio_track_t *);
611
612static int audio_mixer_init(struct audio_softc *, int,
613	const audio_format2_t *, const audio_filter_reg_t *);
614static void audio_mixer_destroy(struct audio_softc *, audio_trackmixer_t *);
615static void audio_pmixer_start(struct audio_softc *, bool);
616static void audio_pmixer_process(struct audio_softc *);
617static void audio_pmixer_agc(audio_trackmixer_t *, int);
618static int  audio_pmixer_mix_track(audio_trackmixer_t *, audio_track_t *, int);
619static void audio_pmixer_output(struct audio_softc *);
620static int  audio_pmixer_halt(struct audio_softc *);
621static void audio_rmixer_start(struct audio_softc *);
622static void audio_rmixer_process(struct audio_softc *);
623static void audio_rmixer_input(struct audio_softc *);
624static int  audio_rmixer_halt(struct audio_softc *);
625
626static void mixer_init(struct audio_softc *);
627static int mixer_open(dev_t, struct audio_softc *, int, int, struct lwp *);
628static int mixer_close(struct audio_softc *, audio_file_t *);
629static int mixer_ioctl(struct audio_softc *, u_long, void *, int, struct lwp *);
630static void mixer_async_add(struct audio_softc *, pid_t);
631static void mixer_async_remove(struct audio_softc *, pid_t);
632static void mixer_signal(struct audio_softc *);
633
634static int au_portof(struct audio_softc *, char *, int);
635
636static void au_setup_ports(struct audio_softc *, struct au_mixer_ports *,
637	mixer_devinfo_t *, const struct portname *);
638static int au_set_lr_value(struct audio_softc *, mixer_ctrl_t *, int, int);
639static int au_get_lr_value(struct audio_softc *, mixer_ctrl_t *, int *, int *);
640static int au_set_gain(struct audio_softc *, struct au_mixer_ports *, int, int);
641static void au_get_gain(struct audio_softc *, struct au_mixer_ports *,
642	u_int *, u_char *);
643static int au_set_port(struct audio_softc *, struct au_mixer_ports *, u_int);
644static int au_get_port(struct audio_softc *, struct au_mixer_ports *);
645static int au_set_monitor_gain(struct audio_softc *, int);
646static int au_get_monitor_gain(struct audio_softc *);
647static int audio_get_port(struct audio_softc *, mixer_ctrl_t *);
648static int audio_set_port(struct audio_softc *, mixer_ctrl_t *);
649
650static __inline struct audio_params
651format2_to_params(const audio_format2_t *f2)
652{
653	audio_params_t p;
654
655	/* validbits/precision <-> precision/stride */
656	p.sample_rate = f2->sample_rate;
657	p.channels    = f2->channels;
658	p.encoding    = f2->encoding;
659	p.validbits   = f2->precision;
660	p.precision   = f2->stride;
661	return p;
662}
663
664static __inline audio_format2_t
665params_to_format2(const struct audio_params *p)
666{
667	audio_format2_t f2;
668
669	/* precision/stride <-> validbits/precision */
670	f2.sample_rate = p->sample_rate;
671	f2.channels    = p->channels;
672	f2.encoding    = p->encoding;
673	f2.precision   = p->validbits;
674	f2.stride      = p->precision;
675	return f2;
676}
677
678/* Return true if this track is a playback track. */
679static __inline bool
680audio_track_is_playback(const audio_track_t *track)
681{
682
683	return ((track->mode & AUMODE_PLAY) != 0);
684}
685
686/* Return true if this track is a recording track. */
687static __inline bool
688audio_track_is_record(const audio_track_t *track)
689{
690
691	return ((track->mode & AUMODE_RECORD) != 0);
692}
693
694#if 0 /* XXX Not used yet */
695/*
696 * Convert 0..255 volume used in userland to internal presentation 0..256.
697 */
698static __inline u_int
699audio_volume_to_inner(u_int v)
700{
701
702	return v < 127 ? v : v + 1;
703}
704
705/*
706 * Convert 0..256 internal presentation to 0..255 volume used in userland.
707 */
708static __inline u_int
709audio_volume_to_outer(u_int v)
710{
711
712	return v < 127 ? v : v - 1;
713}
714#endif /* 0 */
715
716static dev_type_open(audioopen);
717/* XXXMRG use more dev_type_xxx */
718
719const struct cdevsw audio_cdevsw = {
720	.d_open = audioopen,
721	.d_close = noclose,
722	.d_read = noread,
723	.d_write = nowrite,
724	.d_ioctl = noioctl,
725	.d_stop = nostop,
726	.d_tty = notty,
727	.d_poll = nopoll,
728	.d_mmap = nommap,
729	.d_kqfilter = nokqfilter,
730	.d_discard = nodiscard,
731	.d_flag = D_OTHER | D_MPSAFE
732};
733
734const struct fileops audio_fileops = {
735	.fo_name = "audio",
736	.fo_read = audioread,
737	.fo_write = audiowrite,
738	.fo_ioctl = audioioctl,
739	.fo_fcntl = fnullop_fcntl,
740	.fo_stat = audiostat,
741	.fo_poll = audiopoll,
742	.fo_close = audioclose,
743	.fo_mmap = audiommap,
744	.fo_kqfilter = audiokqfilter,
745	.fo_restart = fnullop_restart
746};
747
748/* The default audio mode: 8 kHz mono mu-law */
749static const struct audio_params audio_default = {
750	.sample_rate = 8000,
751	.encoding = AUDIO_ENCODING_ULAW,
752	.precision = 8,
753	.validbits = 8,
754	.channels = 1,
755};
756
757static const char *encoding_names[] = {
758	"none",
759	AudioEmulaw,
760	AudioEalaw,
761	"pcm16",
762	"pcm8",
763	AudioEadpcm,
764	AudioEslinear_le,
765	AudioEslinear_be,
766	AudioEulinear_le,
767	AudioEulinear_be,
768	AudioEslinear,
769	AudioEulinear,
770	AudioEmpeg_l1_stream,
771	AudioEmpeg_l1_packets,
772	AudioEmpeg_l1_system,
773	AudioEmpeg_l2_stream,
774	AudioEmpeg_l2_packets,
775	AudioEmpeg_l2_system,
776	AudioEac3,
777};
778
779/*
780 * Returns encoding name corresponding to AUDIO_ENCODING_*.
781 * Note that it may return a local buffer because it is mainly for debugging.
782 */
783const char *
784audio_encoding_name(int encoding)
785{
786	static char buf[16];
787
788	if (0 <= encoding && encoding < __arraycount(encoding_names)) {
789		return encoding_names[encoding];
790	} else {
791		snprintf(buf, sizeof(buf), "enc=%d", encoding);
792		return buf;
793	}
794}
795
796/*
797 * Supported encodings used by AUDIO_GETENC.
798 * index and flags are set by code.
799 * XXX is there any needs for SLINEAR_OE:>=16/ULINEAR_OE:>=16 ?
800 */
801static const audio_encoding_t audio_encodings[] = {
802	{ 0, AudioEmulaw,	AUDIO_ENCODING_ULAW,		8,  0 },
803	{ 0, AudioEalaw,	AUDIO_ENCODING_ALAW,		8,  0 },
804	{ 0, AudioEslinear,	AUDIO_ENCODING_SLINEAR,		8,  0 },
805	{ 0, AudioEulinear,	AUDIO_ENCODING_ULINEAR,		8,  0 },
806	{ 0, AudioEslinear_le,	AUDIO_ENCODING_SLINEAR_LE,	16, 0 },
807	{ 0, AudioEulinear_le,	AUDIO_ENCODING_ULINEAR_LE,	16, 0 },
808	{ 0, AudioEslinear_be,	AUDIO_ENCODING_SLINEAR_BE,	16, 0 },
809	{ 0, AudioEulinear_be,	AUDIO_ENCODING_ULINEAR_BE,	16, 0 },
810#if defined(AUDIO_SUPPORT_LINEAR24)
811	{ 0, AudioEslinear_le,	AUDIO_ENCODING_SLINEAR_LE,	24, 0 },
812	{ 0, AudioEulinear_le,	AUDIO_ENCODING_ULINEAR_LE,	24, 0 },
813	{ 0, AudioEslinear_be,	AUDIO_ENCODING_SLINEAR_BE,	24, 0 },
814	{ 0, AudioEulinear_be,	AUDIO_ENCODING_ULINEAR_BE,	24, 0 },
815#endif
816	{ 0, AudioEslinear_le,	AUDIO_ENCODING_SLINEAR_LE,	32, 0 },
817	{ 0, AudioEulinear_le,	AUDIO_ENCODING_ULINEAR_LE,	32, 0 },
818	{ 0, AudioEslinear_be,	AUDIO_ENCODING_SLINEAR_BE,	32, 0 },
819	{ 0, AudioEulinear_be,	AUDIO_ENCODING_ULINEAR_BE,	32, 0 },
820};
821
822static const struct portname itable[] = {
823	{ AudioNmicrophone,	AUDIO_MICROPHONE },
824	{ AudioNline,		AUDIO_LINE_IN },
825	{ AudioNcd,		AUDIO_CD },
826	{ 0, 0 }
827};
828static const struct portname otable[] = {
829	{ AudioNspeaker,	AUDIO_SPEAKER },
830	{ AudioNheadphone,	AUDIO_HEADPHONE },
831	{ AudioNline,		AUDIO_LINE_OUT },
832	{ 0, 0 }
833};
834
835static struct psref_class *audio_psref_class __read_mostly;
836
837CFATTACH_DECL3_NEW(audio, sizeof(struct audio_softc),
838    audiomatch, audioattach, audiodetach, audioactivate, audiorescan,
839    audiochilddet, DVF_DETACH_SHUTDOWN);
840
841static int
842audiomatch(device_t parent, cfdata_t match, void *aux)
843{
844	struct audio_attach_args *sa;
845
846	sa = aux;
847	DPRINTF(1, "%s: type=%d sa=%p hw=%p\n",
848	     __func__, sa->type, sa, sa->hwif);
849	return (sa->type == AUDIODEV_TYPE_AUDIO) ? 1 : 0;
850}
851
852static void
853audioattach(device_t parent, device_t self, void *aux)
854{
855	struct audio_softc *sc;
856	struct audio_attach_args *sa;
857	const struct audio_hw_if *hw_if;
858	audio_format2_t phwfmt;
859	audio_format2_t rhwfmt;
860	audio_filter_reg_t pfil;
861	audio_filter_reg_t rfil;
862	const struct sysctlnode *node;
863	void *hdlp;
864	bool has_playback;
865	bool has_capture;
866	bool has_indep;
867	bool has_fulldup;
868	int mode;
869	int error;
870
871	sc = device_private(self);
872	sc->sc_dev = self;
873	sa = (struct audio_attach_args *)aux;
874	hw_if = sa->hwif;
875	hdlp = sa->hdl;
876
877	if (hw_if == NULL) {
878		panic("audioattach: missing hw_if method");
879	}
880	if (hw_if->get_locks == NULL || hw_if->get_props == NULL) {
881		aprint_error(": missing mandatory method\n");
882		return;
883	}
884
885	hw_if->get_locks(hdlp, &sc->sc_intr_lock, &sc->sc_lock);
886	sc->sc_props = hw_if->get_props(hdlp);
887
888	has_playback = (sc->sc_props & AUDIO_PROP_PLAYBACK);
889	has_capture  = (sc->sc_props & AUDIO_PROP_CAPTURE);
890	has_indep    = (sc->sc_props & AUDIO_PROP_INDEPENDENT);
891	has_fulldup  = (sc->sc_props & AUDIO_PROP_FULLDUPLEX);
892
893#ifdef DIAGNOSTIC
894	if (hw_if->query_format == NULL ||
895	    hw_if->set_format == NULL ||
896	    hw_if->getdev == NULL ||
897	    hw_if->set_port == NULL ||
898	    hw_if->get_port == NULL ||
899	    hw_if->query_devinfo == NULL) {
900		aprint_error(": missing mandatory method\n");
901		return;
902	}
903	if (has_playback) {
904		if ((hw_if->start_output == NULL && hw_if->trigger_output == NULL) ||
905		    hw_if->halt_output == NULL) {
906			aprint_error(": missing playback method\n");
907		}
908	}
909	if (has_capture) {
910		if ((hw_if->start_input == NULL && hw_if->trigger_input == NULL) ||
911		    hw_if->halt_input == NULL) {
912			aprint_error(": missing capture method\n");
913		}
914	}
915#endif
916
917	sc->hw_if = hw_if;
918	sc->hw_hdl = hdlp;
919	sc->hw_dev = parent;
920
921	sc->sc_exlock = 1;
922	sc->sc_blk_ms = AUDIO_BLK_MS;
923	SLIST_INIT(&sc->sc_files);
924	cv_init(&sc->sc_exlockcv, "audiolk");
925	sc->sc_am_capacity = 0;
926	sc->sc_am_used = 0;
927	sc->sc_am = NULL;
928
929	/* MMAP is now supported by upper layer.  */
930	sc->sc_props |= AUDIO_PROP_MMAP;
931
932	KASSERT(has_playback || has_capture);
933	/* Unidirectional device must have neither FULLDUP nor INDEPENDENT. */
934	if (!has_playback || !has_capture) {
935		KASSERT(!has_indep);
936		KASSERT(!has_fulldup);
937	}
938
939	mode = 0;
940	if (has_playback) {
941		aprint_normal(": playback");
942		mode |= AUMODE_PLAY;
943	}
944	if (has_capture) {
945		aprint_normal("%c capture", has_playback ? ',' : ':');
946		mode |= AUMODE_RECORD;
947	}
948	if (has_playback && has_capture) {
949		if (has_fulldup)
950			aprint_normal(", full duplex");
951		else
952			aprint_normal(", half duplex");
953
954		if (has_indep)
955			aprint_normal(", independent");
956	}
957
958	aprint_naive("\n");
959	aprint_normal("\n");
960
961	/* probe hw params */
962	memset(&phwfmt, 0, sizeof(phwfmt));
963	memset(&rhwfmt, 0, sizeof(rhwfmt));
964	memset(&pfil, 0, sizeof(pfil));
965	memset(&rfil, 0, sizeof(rfil));
966	if (has_indep) {
967		int perror, rerror;
968
969		/* On independent devices, probe separately. */
970		perror = audio_hw_probe(sc, &phwfmt, AUMODE_PLAY);
971		rerror = audio_hw_probe(sc, &rhwfmt, AUMODE_RECORD);
972		if (perror && rerror) {
973			aprint_error_dev(self, "audio_hw_probe failed, "
974			    "perror = %d, rerror = %d\n", perror, rerror);
975			goto bad;
976		}
977		if (perror) {
978			mode &= ~AUMODE_PLAY;
979			aprint_error_dev(self, "audio_hw_probe failed with "
980			    "%d, playback disabled\n", perror);
981		}
982		if (rerror) {
983			mode &= ~AUMODE_RECORD;
984			aprint_error_dev(self, "audio_hw_probe failed with "
985			    "%d, capture disabled\n", rerror);
986		}
987	} else {
988		/*
989		 * On non independent devices or uni-directional devices,
990		 * probe once (simultaneously).
991		 */
992		audio_format2_t *fmt = has_playback ? &phwfmt : &rhwfmt;
993		error = audio_hw_probe(sc, fmt, mode);
994		if (error) {
995			aprint_error_dev(self, "audio_hw_probe failed, "
996			    "error = %d\n", error);
997			goto bad;
998		}
999		if (has_playback && has_capture)
1000			rhwfmt = phwfmt;
1001	}
1002
1003	/* Init hardware. */
1004	/* hw_probe() also validates [pr]hwfmt.  */
1005	error = audio_hw_set_format(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
1006	if (error) {
1007		aprint_error_dev(self, "audio_hw_set_format failed, "
1008		    "error = %d\n", error);
1009		goto bad;
1010	}
1011
1012	/*
1013	 * Init track mixers.  If at least one direction is available on
1014	 * attach time, we assume a success.
1015	 */
1016	error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
1017	if (sc->sc_pmixer == NULL && sc->sc_rmixer == NULL) {
1018		aprint_error_dev(self, "audio_mixers_init failed, "
1019		    "error = %d\n", error);
1020		goto bad;
1021	}
1022
1023	sc->sc_psz = pserialize_create();
1024	psref_target_init(&sc->sc_psref, audio_psref_class);
1025
1026	selinit(&sc->sc_wsel);
1027	selinit(&sc->sc_rsel);
1028
1029	/* Initial parameter of /dev/sound */
1030	sc->sc_sound_pparams = params_to_format2(&audio_default);
1031	sc->sc_sound_rparams = params_to_format2(&audio_default);
1032	sc->sc_sound_ppause = false;
1033	sc->sc_sound_rpause = false;
1034
1035	/* XXX TODO: consider about sc_ai */
1036
1037	mixer_init(sc);
1038	TRACE(2, "inputs ports=0x%x, input master=%d, "
1039	    "output ports=0x%x, output master=%d",
1040	    sc->sc_inports.allports, sc->sc_inports.master,
1041	    sc->sc_outports.allports, sc->sc_outports.master);
1042
1043	sysctl_createv(&sc->sc_log, 0, NULL, &node,
1044	    0,
1045	    CTLTYPE_NODE, device_xname(sc->sc_dev),
1046	    SYSCTL_DESCR("audio test"),
1047	    NULL, 0,
1048	    NULL, 0,
1049	    CTL_HW,
1050	    CTL_CREATE, CTL_EOL);
1051
1052	if (node != NULL) {
1053		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
1054		    CTLFLAG_READWRITE,
1055		    CTLTYPE_INT, "blk_ms",
1056		    SYSCTL_DESCR("blocksize in msec"),
1057		    audio_sysctl_blk_ms, 0, (void *)sc, 0,
1058		    CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL);
1059
1060		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
1061		    CTLFLAG_READWRITE,
1062		    CTLTYPE_BOOL, "multiuser",
1063		    SYSCTL_DESCR("allow multiple user access"),
1064		    audio_sysctl_multiuser, 0, (void *)sc, 0,
1065		    CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL);
1066
1067#if defined(AUDIO_DEBUG)
1068		sysctl_createv(&sc->sc_log, 0, NULL, NULL,
1069		    CTLFLAG_READWRITE,
1070		    CTLTYPE_INT, "debug",
1071		    SYSCTL_DESCR("debug level (0..4)"),
1072		    audio_sysctl_debug, 0, (void *)sc, 0,
1073		    CTL_HW, node->sysctl_num, CTL_CREATE, CTL_EOL);
1074#endif
1075	}
1076
1077#ifdef AUDIO_PM_IDLE
1078	callout_init(&sc->sc_idle_counter, 0);
1079	callout_setfunc(&sc->sc_idle_counter, audio_idle, self);
1080#endif
1081
1082	if (!pmf_device_register(self, audio_suspend, audio_resume))
1083		aprint_error_dev(self, "couldn't establish power handler\n");
1084#ifdef AUDIO_PM_IDLE
1085	if (!device_active_register(self, audio_activity))
1086		aprint_error_dev(self, "couldn't register activity handler\n");
1087#endif
1088
1089	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_DOWN,
1090	    audio_volume_down, true))
1091		aprint_error_dev(self, "couldn't add volume down handler\n");
1092	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_UP,
1093	    audio_volume_up, true))
1094		aprint_error_dev(self, "couldn't add volume up handler\n");
1095	if (!pmf_event_register(self, PMFE_AUDIO_VOLUME_TOGGLE,
1096	    audio_volume_toggle, true))
1097		aprint_error_dev(self, "couldn't add volume toggle handler\n");
1098
1099#ifdef AUDIO_PM_IDLE
1100	callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
1101#endif
1102
1103#if defined(AUDIO_DEBUG)
1104	audio_mlog_init();
1105#endif
1106
1107	audiorescan(self, "audio", NULL);
1108	sc->sc_exlock = 0;
1109	return;
1110
1111bad:
1112	/* Clearing hw_if means that device is attached but disabled. */
1113	sc->hw_if = NULL;
1114	sc->sc_exlock = 0;
1115	aprint_error_dev(sc->sc_dev, "disabled\n");
1116	return;
1117}
1118
1119/*
1120 * Initialize hardware mixer.
1121 * This function is called from audioattach().
1122 */
1123static void
1124mixer_init(struct audio_softc *sc)
1125{
1126	mixer_devinfo_t mi;
1127	int iclass, mclass, oclass, rclass;
1128	int record_master_found, record_source_found;
1129
1130	iclass = mclass = oclass = rclass = -1;
1131	sc->sc_inports.index = -1;
1132	sc->sc_inports.master = -1;
1133	sc->sc_inports.nports = 0;
1134	sc->sc_inports.isenum = false;
1135	sc->sc_inports.allports = 0;
1136	sc->sc_inports.isdual = false;
1137	sc->sc_inports.mixerout = -1;
1138	sc->sc_inports.cur_port = -1;
1139	sc->sc_outports.index = -1;
1140	sc->sc_outports.master = -1;
1141	sc->sc_outports.nports = 0;
1142	sc->sc_outports.isenum = false;
1143	sc->sc_outports.allports = 0;
1144	sc->sc_outports.isdual = false;
1145	sc->sc_outports.mixerout = -1;
1146	sc->sc_outports.cur_port = -1;
1147	sc->sc_monitor_port = -1;
1148	/*
1149	 * Read through the underlying driver's list, picking out the class
1150	 * names from the mixer descriptions. We'll need them to decode the
1151	 * mixer descriptions on the next pass through the loop.
1152	 */
1153	mutex_enter(sc->sc_lock);
1154	for(mi.index = 0; ; mi.index++) {
1155		if (audio_query_devinfo(sc, &mi) != 0)
1156			break;
1157		 /*
1158		  * The type of AUDIO_MIXER_CLASS merely introduces a class.
1159		  * All the other types describe an actual mixer.
1160		  */
1161		if (mi.type == AUDIO_MIXER_CLASS) {
1162			if (strcmp(mi.label.name, AudioCinputs) == 0)
1163				iclass = mi.mixer_class;
1164			if (strcmp(mi.label.name, AudioCmonitor) == 0)
1165				mclass = mi.mixer_class;
1166			if (strcmp(mi.label.name, AudioCoutputs) == 0)
1167				oclass = mi.mixer_class;
1168			if (strcmp(mi.label.name, AudioCrecord) == 0)
1169				rclass = mi.mixer_class;
1170		}
1171	}
1172	mutex_exit(sc->sc_lock);
1173
1174	/* Allocate save area.  Ensure non-zero allocation. */
1175	sc->sc_nmixer_states = mi.index;
1176	sc->sc_mixer_state = kmem_zalloc(sizeof(mixer_ctrl_t) *
1177	    (sc->sc_nmixer_states + 1), KM_SLEEP);
1178
1179	/*
1180	 * This is where we assign each control in the "audio" model, to the
1181	 * underlying "mixer" control.  We walk through the whole list once,
1182	 * assigning likely candidates as we come across them.
1183	 */
1184	record_master_found = 0;
1185	record_source_found = 0;
1186	mutex_enter(sc->sc_lock);
1187	for(mi.index = 0; ; mi.index++) {
1188		if (audio_query_devinfo(sc, &mi) != 0)
1189			break;
1190		KASSERT(mi.index < sc->sc_nmixer_states);
1191		if (mi.type == AUDIO_MIXER_CLASS)
1192			continue;
1193		if (mi.mixer_class == iclass) {
1194			/*
1195			 * AudioCinputs is only a fallback, when we don't
1196			 * find what we're looking for in AudioCrecord, so
1197			 * check the flags before accepting one of these.
1198			 */
1199			if (strcmp(mi.label.name, AudioNmaster) == 0
1200			    && record_master_found == 0)
1201				sc->sc_inports.master = mi.index;
1202			if (strcmp(mi.label.name, AudioNsource) == 0
1203			    && record_source_found == 0) {
1204				if (mi.type == AUDIO_MIXER_ENUM) {
1205				    int i;
1206				    for(i = 0; i < mi.un.e.num_mem; i++)
1207					if (strcmp(mi.un.e.member[i].label.name,
1208						    AudioNmixerout) == 0)
1209						sc->sc_inports.mixerout =
1210						    mi.un.e.member[i].ord;
1211				}
1212				au_setup_ports(sc, &sc->sc_inports, &mi,
1213				    itable);
1214			}
1215			if (strcmp(mi.label.name, AudioNdac) == 0 &&
1216			    sc->sc_outports.master == -1)
1217				sc->sc_outports.master = mi.index;
1218		} else if (mi.mixer_class == mclass) {
1219			if (strcmp(mi.label.name, AudioNmonitor) == 0)
1220				sc->sc_monitor_port = mi.index;
1221		} else if (mi.mixer_class == oclass) {
1222			if (strcmp(mi.label.name, AudioNmaster) == 0)
1223				sc->sc_outports.master = mi.index;
1224			if (strcmp(mi.label.name, AudioNselect) == 0)
1225				au_setup_ports(sc, &sc->sc_outports, &mi,
1226				    otable);
1227		} else if (mi.mixer_class == rclass) {
1228			/*
1229			 * These are the preferred mixers for the audio record
1230			 * controls, so set the flags here, but don't check.
1231			 */
1232			if (strcmp(mi.label.name, AudioNmaster) == 0) {
1233				sc->sc_inports.master = mi.index;
1234				record_master_found = 1;
1235			}
1236#if 1	/* Deprecated. Use AudioNmaster. */
1237			if (strcmp(mi.label.name, AudioNrecord) == 0) {
1238				sc->sc_inports.master = mi.index;
1239				record_master_found = 1;
1240			}
1241			if (strcmp(mi.label.name, AudioNvolume) == 0) {
1242				sc->sc_inports.master = mi.index;
1243				record_master_found = 1;
1244			}
1245#endif
1246			if (strcmp(mi.label.name, AudioNsource) == 0) {
1247				if (mi.type == AUDIO_MIXER_ENUM) {
1248				    int i;
1249				    for(i = 0; i < mi.un.e.num_mem; i++)
1250					if (strcmp(mi.un.e.member[i].label.name,
1251						    AudioNmixerout) == 0)
1252						sc->sc_inports.mixerout =
1253						    mi.un.e.member[i].ord;
1254				}
1255				au_setup_ports(sc, &sc->sc_inports, &mi,
1256				    itable);
1257				record_source_found = 1;
1258			}
1259		}
1260	}
1261	mutex_exit(sc->sc_lock);
1262}
1263
1264static int
1265audioactivate(device_t self, enum devact act)
1266{
1267	struct audio_softc *sc = device_private(self);
1268
1269	switch (act) {
1270	case DVACT_DEACTIVATE:
1271		mutex_enter(sc->sc_lock);
1272		sc->sc_dying = true;
1273		cv_broadcast(&sc->sc_exlockcv);
1274		mutex_exit(sc->sc_lock);
1275		return 0;
1276	default:
1277		return EOPNOTSUPP;
1278	}
1279}
1280
1281static int
1282audiodetach(device_t self, int flags)
1283{
1284	struct audio_softc *sc;
1285	struct audio_file *file;
1286	int error;
1287
1288	sc = device_private(self);
1289	TRACE(2, "flags=%d", flags);
1290
1291	/* device is not initialized */
1292	if (sc->hw_if == NULL)
1293		return 0;
1294
1295	/* Start draining existing accessors of the device. */
1296	error = config_detach_children(self, flags);
1297	if (error)
1298		return error;
1299
1300	/* delete sysctl nodes */
1301	sysctl_teardown(&sc->sc_log);
1302
1303	mutex_enter(sc->sc_lock);
1304	sc->sc_dying = true;
1305	cv_broadcast(&sc->sc_exlockcv);
1306	if (sc->sc_pmixer)
1307		cv_broadcast(&sc->sc_pmixer->outcv);
1308	if (sc->sc_rmixer)
1309		cv_broadcast(&sc->sc_rmixer->outcv);
1310
1311	/* Prevent new users */
1312	SLIST_FOREACH(file, &sc->sc_files, entry) {
1313		atomic_store_relaxed(&file->dying, true);
1314	}
1315
1316	/*
1317	 * Wait for existing users to drain.
1318	 * - pserialize_perform waits for all pserialize_read sections on
1319	 *   all CPUs; after this, no more new psref_acquire can happen.
1320	 * - psref_target_destroy waits for all extant acquired psrefs to
1321	 *   be psref_released.
1322	 */
1323	pserialize_perform(sc->sc_psz);
1324	mutex_exit(sc->sc_lock);
1325	psref_target_destroy(&sc->sc_psref, audio_psref_class);
1326
1327	/*
1328	 * We are now guaranteed that there are no calls to audio fileops
1329	 * that hold sc, and any new calls with files that were for sc will
1330	 * fail.  Thus, we now have exclusive access to the softc.
1331	 */
1332	sc->sc_exlock = 1;
1333
1334	/*
1335	 * Nuke all open instances.
1336	 * Here, we no longer need any locks to traverse sc_files.
1337	 */
1338	while ((file = SLIST_FIRST(&sc->sc_files)) != NULL) {
1339		audio_unlink(sc, file);
1340	}
1341
1342	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_DOWN,
1343	    audio_volume_down, true);
1344	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_UP,
1345	    audio_volume_up, true);
1346	pmf_event_deregister(self, PMFE_AUDIO_VOLUME_TOGGLE,
1347	    audio_volume_toggle, true);
1348
1349#ifdef AUDIO_PM_IDLE
1350	callout_halt(&sc->sc_idle_counter, sc->sc_lock);
1351
1352	device_active_deregister(self, audio_activity);
1353#endif
1354
1355	pmf_device_deregister(self);
1356
1357	/* Free resources */
1358	if (sc->sc_pmixer) {
1359		audio_mixer_destroy(sc, sc->sc_pmixer);
1360		kmem_free(sc->sc_pmixer, sizeof(*sc->sc_pmixer));
1361	}
1362	if (sc->sc_rmixer) {
1363		audio_mixer_destroy(sc, sc->sc_rmixer);
1364		kmem_free(sc->sc_rmixer, sizeof(*sc->sc_rmixer));
1365	}
1366	if (sc->sc_am)
1367		kern_free(sc->sc_am);
1368
1369	seldestroy(&sc->sc_wsel);
1370	seldestroy(&sc->sc_rsel);
1371
1372#ifdef AUDIO_PM_IDLE
1373	callout_destroy(&sc->sc_idle_counter);
1374#endif
1375
1376	cv_destroy(&sc->sc_exlockcv);
1377
1378#if defined(AUDIO_DEBUG)
1379	audio_mlog_free();
1380#endif
1381
1382	return 0;
1383}
1384
1385static void
1386audiochilddet(device_t self, device_t child)
1387{
1388
1389	/* we hold no child references, so do nothing */
1390}
1391
1392static int
1393audiosearch(device_t parent, cfdata_t cf, const int *locs, void *aux)
1394{
1395
1396	if (config_match(parent, cf, aux))
1397		config_attach_loc(parent, cf, locs, aux, NULL);
1398
1399	return 0;
1400}
1401
1402static int
1403audiorescan(device_t self, const char *ifattr, const int *flags)
1404{
1405	struct audio_softc *sc = device_private(self);
1406
1407	if (!ifattr_match(ifattr, "audio"))
1408		return 0;
1409
1410	config_search_loc(audiosearch, sc->sc_dev, "audio", NULL, NULL);
1411
1412	return 0;
1413}
1414
1415/*
1416 * Called from hardware driver.  This is where the MI audio driver gets
1417 * probed/attached to the hardware driver.
1418 */
1419device_t
1420audio_attach_mi(const struct audio_hw_if *ahwp, void *hdlp, device_t dev)
1421{
1422	struct audio_attach_args arg;
1423
1424#ifdef DIAGNOSTIC
1425	if (ahwp == NULL) {
1426		aprint_error("audio_attach_mi: NULL\n");
1427		return 0;
1428	}
1429#endif
1430	arg.type = AUDIODEV_TYPE_AUDIO;
1431	arg.hwif = ahwp;
1432	arg.hdl = hdlp;
1433	return config_found(dev, &arg, audioprint);
1434}
1435
1436/*
1437 * Enter critical section and also keep sc_lock.
1438 * If successful, returns 0 with sc_lock held.  Otherwise returns errno.
1439 * Must be called without sc_lock held.
1440 */
1441static int
1442audio_exlock_mutex_enter(struct audio_softc *sc)
1443{
1444	int error;
1445
1446	mutex_enter(sc->sc_lock);
1447	if (sc->sc_dying) {
1448		mutex_exit(sc->sc_lock);
1449		return EIO;
1450	}
1451
1452	while (__predict_false(sc->sc_exlock != 0)) {
1453		error = cv_wait_sig(&sc->sc_exlockcv, sc->sc_lock);
1454		if (sc->sc_dying)
1455			error = EIO;
1456		if (error) {
1457			mutex_exit(sc->sc_lock);
1458			return error;
1459		}
1460	}
1461
1462	/* Acquire */
1463	sc->sc_exlock = 1;
1464	return 0;
1465}
1466
1467/*
1468 * Exit critical section and exit sc_lock.
1469 * Must be called with sc_lock held.
1470 */
1471static void
1472audio_exlock_mutex_exit(struct audio_softc *sc)
1473{
1474
1475	KASSERT(mutex_owned(sc->sc_lock));
1476
1477	sc->sc_exlock = 0;
1478	cv_broadcast(&sc->sc_exlockcv);
1479	mutex_exit(sc->sc_lock);
1480}
1481
1482/*
1483 * Enter critical section.
1484 * If successful, it returns 0.  Otherwise returns errno.
1485 * Must be called without sc_lock held.
1486 * This function returns without sc_lock held.
1487 */
1488static int
1489audio_exlock_enter(struct audio_softc *sc)
1490{
1491	int error;
1492
1493	error = audio_exlock_mutex_enter(sc);
1494	if (error)
1495		return error;
1496	mutex_exit(sc->sc_lock);
1497	return 0;
1498}
1499
1500/*
1501 * Exit critical section.
1502 * Must be called without sc_lock held.
1503 */
1504static void
1505audio_exlock_exit(struct audio_softc *sc)
1506{
1507
1508	mutex_enter(sc->sc_lock);
1509	audio_exlock_mutex_exit(sc);
1510}
1511
1512/*
1513 * Acquire sc from file, and increment the psref count.
1514 * If successful, returns sc.  Otherwise returns NULL.
1515 */
1516struct audio_softc *
1517audio_file_enter(audio_file_t *file, struct psref *refp)
1518{
1519	int s;
1520	bool dying;
1521
1522	/* psref(9) forbids to migrate CPUs */
1523	curlwp_bind();
1524
1525	/* Block audiodetach while we acquire a reference */
1526	s = pserialize_read_enter();
1527
1528	/* If close or audiodetach already ran, tough -- no more audio */
1529	dying = atomic_load_relaxed(&file->dying);
1530	if (dying) {
1531		pserialize_read_exit(s);
1532		return NULL;
1533	}
1534
1535	/* Acquire a reference */
1536	psref_acquire(refp, &file->sc->sc_psref, audio_psref_class);
1537
1538	/* Now sc won't go away until we drop the reference count */
1539	pserialize_read_exit(s);
1540
1541	return file->sc;
1542}
1543
1544/*
1545 * Decrement the psref count.
1546 */
1547void
1548audio_file_exit(struct audio_softc *sc, struct psref *refp)
1549{
1550
1551	psref_release(refp, &sc->sc_psref, audio_psref_class);
1552}
1553
1554/*
1555 * Wait for I/O to complete, releasing sc_lock.
1556 * Must be called with sc_lock held.
1557 */
1558static int
1559audio_track_waitio(struct audio_softc *sc, audio_track_t *track)
1560{
1561	int error;
1562
1563	KASSERT(track);
1564	KASSERT(mutex_owned(sc->sc_lock));
1565
1566	/* Wait for pending I/O to complete. */
1567	error = cv_timedwait_sig(&track->mixer->outcv, sc->sc_lock,
1568	    mstohz(AUDIO_TIMEOUT));
1569	if (sc->sc_dying) {
1570		error = EIO;
1571	}
1572	if (error) {
1573		TRACET(2, track, "cv_timedwait_sig failed %d", error);
1574		if (error == EWOULDBLOCK)
1575			device_printf(sc->sc_dev, "device timeout\n");
1576	} else {
1577		TRACET(3, track, "wakeup");
1578	}
1579	return error;
1580}
1581
1582/*
1583 * Try to acquire track lock.
1584 * It doesn't block if the track lock is already aquired.
1585 * Returns true if the track lock was acquired, or false if the track
1586 * lock was already acquired.
1587 */
1588static __inline bool
1589audio_track_lock_tryenter(audio_track_t *track)
1590{
1591	return (atomic_cas_uint(&track->lock, 0, 1) == 0);
1592}
1593
1594/*
1595 * Acquire track lock.
1596 */
1597static __inline void
1598audio_track_lock_enter(audio_track_t *track)
1599{
1600	/* Don't sleep here. */
1601	while (audio_track_lock_tryenter(track) == false)
1602		;
1603}
1604
1605/*
1606 * Release track lock.
1607 */
1608static __inline void
1609audio_track_lock_exit(audio_track_t *track)
1610{
1611	atomic_swap_uint(&track->lock, 0);
1612}
1613
1614
1615static int
1616audioopen(dev_t dev, int flags, int ifmt, struct lwp *l)
1617{
1618	struct audio_softc *sc;
1619	int error;
1620
1621	/* Find the device */
1622	sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
1623	if (sc == NULL || sc->hw_if == NULL)
1624		return ENXIO;
1625
1626	error = audio_exlock_enter(sc);
1627	if (error)
1628		return error;
1629
1630	device_active(sc->sc_dev, DVA_SYSTEM);
1631	switch (AUDIODEV(dev)) {
1632	case SOUND_DEVICE:
1633	case AUDIO_DEVICE:
1634		error = audio_open(dev, sc, flags, ifmt, l, NULL);
1635		break;
1636	case AUDIOCTL_DEVICE:
1637		error = audioctl_open(dev, sc, flags, ifmt, l);
1638		break;
1639	case MIXER_DEVICE:
1640		error = mixer_open(dev, sc, flags, ifmt, l);
1641		break;
1642	default:
1643		error = ENXIO;
1644		break;
1645	}
1646	audio_exlock_exit(sc);
1647
1648	return error;
1649}
1650
1651static int
1652audioclose(struct file *fp)
1653{
1654	struct audio_softc *sc;
1655	struct psref sc_ref;
1656	audio_file_t *file;
1657	int error;
1658	dev_t dev;
1659
1660	KASSERT(fp->f_audioctx);
1661	file = fp->f_audioctx;
1662	dev = file->dev;
1663	error = 0;
1664
1665	/*
1666	 * audioclose() must
1667	 * - unplug track from the trackmixer (and unplug anything from softc),
1668	 *   if sc exists.
1669	 * - free all memory objects, regardless of sc.
1670	 */
1671
1672	sc = audio_file_enter(file, &sc_ref);
1673	if (sc) {
1674		switch (AUDIODEV(dev)) {
1675		case SOUND_DEVICE:
1676		case AUDIO_DEVICE:
1677			error = audio_close(sc, file);
1678			break;
1679		case AUDIOCTL_DEVICE:
1680			error = 0;
1681			break;
1682		case MIXER_DEVICE:
1683			error = mixer_close(sc, file);
1684			break;
1685		default:
1686			error = ENXIO;
1687			break;
1688		}
1689
1690		audio_file_exit(sc, &sc_ref);
1691	}
1692
1693	/* Free memory objects anyway */
1694	TRACEF(2, file, "free memory");
1695	if (file->ptrack)
1696		audio_track_destroy(file->ptrack);
1697	if (file->rtrack)
1698		audio_track_destroy(file->rtrack);
1699	kmem_free(file, sizeof(*file));
1700	fp->f_audioctx = NULL;
1701
1702	return error;
1703}
1704
1705static int
1706audioread(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
1707	int ioflag)
1708{
1709	struct audio_softc *sc;
1710	struct psref sc_ref;
1711	audio_file_t *file;
1712	int error;
1713	dev_t dev;
1714
1715	KASSERT(fp->f_audioctx);
1716	file = fp->f_audioctx;
1717	dev = file->dev;
1718
1719	sc = audio_file_enter(file, &sc_ref);
1720	if (sc == NULL)
1721		return EIO;
1722
1723	if (fp->f_flag & O_NONBLOCK)
1724		ioflag |= IO_NDELAY;
1725
1726	switch (AUDIODEV(dev)) {
1727	case SOUND_DEVICE:
1728	case AUDIO_DEVICE:
1729		error = audio_read(sc, uio, ioflag, file);
1730		break;
1731	case AUDIOCTL_DEVICE:
1732	case MIXER_DEVICE:
1733		error = ENODEV;
1734		break;
1735	default:
1736		error = ENXIO;
1737		break;
1738	}
1739
1740	audio_file_exit(sc, &sc_ref);
1741	return error;
1742}
1743
1744static int
1745audiowrite(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
1746	int ioflag)
1747{
1748	struct audio_softc *sc;
1749	struct psref sc_ref;
1750	audio_file_t *file;
1751	int error;
1752	dev_t dev;
1753
1754	KASSERT(fp->f_audioctx);
1755	file = fp->f_audioctx;
1756	dev = file->dev;
1757
1758	sc = audio_file_enter(file, &sc_ref);
1759	if (sc == NULL)
1760		return EIO;
1761
1762	if (fp->f_flag & O_NONBLOCK)
1763		ioflag |= IO_NDELAY;
1764
1765	switch (AUDIODEV(dev)) {
1766	case SOUND_DEVICE:
1767	case AUDIO_DEVICE:
1768		error = audio_write(sc, uio, ioflag, file);
1769		break;
1770	case AUDIOCTL_DEVICE:
1771	case MIXER_DEVICE:
1772		error = ENODEV;
1773		break;
1774	default:
1775		error = ENXIO;
1776		break;
1777	}
1778
1779	audio_file_exit(sc, &sc_ref);
1780	return error;
1781}
1782
1783static int
1784audioioctl(struct file *fp, u_long cmd, void *addr)
1785{
1786	struct audio_softc *sc;
1787	struct psref sc_ref;
1788	audio_file_t *file;
1789	struct lwp *l = curlwp;
1790	int error;
1791	dev_t dev;
1792
1793	KASSERT(fp->f_audioctx);
1794	file = fp->f_audioctx;
1795	dev = file->dev;
1796
1797	sc = audio_file_enter(file, &sc_ref);
1798	if (sc == NULL)
1799		return EIO;
1800
1801	switch (AUDIODEV(dev)) {
1802	case SOUND_DEVICE:
1803	case AUDIO_DEVICE:
1804	case AUDIOCTL_DEVICE:
1805		mutex_enter(sc->sc_lock);
1806		device_active(sc->sc_dev, DVA_SYSTEM);
1807		mutex_exit(sc->sc_lock);
1808		if (IOCGROUP(cmd) == IOCGROUP(AUDIO_MIXER_READ))
1809			error = mixer_ioctl(sc, cmd, addr, fp->f_flag, l);
1810		else
1811			error = audio_ioctl(dev, sc, cmd, addr, fp->f_flag, l,
1812			    file);
1813		break;
1814	case MIXER_DEVICE:
1815		error = mixer_ioctl(sc, cmd, addr, fp->f_flag, l);
1816		break;
1817	default:
1818		error = ENXIO;
1819		break;
1820	}
1821
1822	audio_file_exit(sc, &sc_ref);
1823	return error;
1824}
1825
1826static int
1827audiostat(struct file *fp, struct stat *st)
1828{
1829	struct audio_softc *sc;
1830	struct psref sc_ref;
1831	audio_file_t *file;
1832
1833	KASSERT(fp->f_audioctx);
1834	file = fp->f_audioctx;
1835
1836	sc = audio_file_enter(file, &sc_ref);
1837	if (sc == NULL)
1838		return EIO;
1839
1840	memset(st, 0, sizeof(*st));
1841
1842	st->st_dev = file->dev;
1843	st->st_uid = kauth_cred_geteuid(fp->f_cred);
1844	st->st_gid = kauth_cred_getegid(fp->f_cred);
1845	st->st_mode = S_IFCHR;
1846
1847	audio_file_exit(sc, &sc_ref);
1848	return 0;
1849}
1850
1851static int
1852audiopoll(struct file *fp, int events)
1853{
1854	struct audio_softc *sc;
1855	struct psref sc_ref;
1856	audio_file_t *file;
1857	struct lwp *l = curlwp;
1858	int revents;
1859	dev_t dev;
1860
1861	KASSERT(fp->f_audioctx);
1862	file = fp->f_audioctx;
1863	dev = file->dev;
1864
1865	sc = audio_file_enter(file, &sc_ref);
1866	if (sc == NULL)
1867		return EIO;
1868
1869	switch (AUDIODEV(dev)) {
1870	case SOUND_DEVICE:
1871	case AUDIO_DEVICE:
1872		revents = audio_poll(sc, events, l, file);
1873		break;
1874	case AUDIOCTL_DEVICE:
1875	case MIXER_DEVICE:
1876		revents = 0;
1877		break;
1878	default:
1879		revents = POLLERR;
1880		break;
1881	}
1882
1883	audio_file_exit(sc, &sc_ref);
1884	return revents;
1885}
1886
1887static int
1888audiokqfilter(struct file *fp, struct knote *kn)
1889{
1890	struct audio_softc *sc;
1891	struct psref sc_ref;
1892	audio_file_t *file;
1893	dev_t dev;
1894	int error;
1895
1896	KASSERT(fp->f_audioctx);
1897	file = fp->f_audioctx;
1898	dev = file->dev;
1899
1900	sc = audio_file_enter(file, &sc_ref);
1901	if (sc == NULL)
1902		return EIO;
1903
1904	switch (AUDIODEV(dev)) {
1905	case SOUND_DEVICE:
1906	case AUDIO_DEVICE:
1907		error = audio_kqfilter(sc, file, kn);
1908		break;
1909	case AUDIOCTL_DEVICE:
1910	case MIXER_DEVICE:
1911		error = ENODEV;
1912		break;
1913	default:
1914		error = ENXIO;
1915		break;
1916	}
1917
1918	audio_file_exit(sc, &sc_ref);
1919	return error;
1920}
1921
1922static int
1923audiommap(struct file *fp, off_t *offp, size_t len, int prot, int *flagsp,
1924	int *advicep, struct uvm_object **uobjp, int *maxprotp)
1925{
1926	struct audio_softc *sc;
1927	struct psref sc_ref;
1928	audio_file_t *file;
1929	dev_t dev;
1930	int error;
1931
1932	KASSERT(fp->f_audioctx);
1933	file = fp->f_audioctx;
1934	dev = file->dev;
1935
1936	sc = audio_file_enter(file, &sc_ref);
1937	if (sc == NULL)
1938		return EIO;
1939
1940	mutex_enter(sc->sc_lock);
1941	device_active(sc->sc_dev, DVA_SYSTEM); /* XXXJDM */
1942	mutex_exit(sc->sc_lock);
1943
1944	switch (AUDIODEV(dev)) {
1945	case SOUND_DEVICE:
1946	case AUDIO_DEVICE:
1947		error = audio_mmap(sc, offp, len, prot, flagsp, advicep,
1948		    uobjp, maxprotp, file);
1949		break;
1950	case AUDIOCTL_DEVICE:
1951	case MIXER_DEVICE:
1952	default:
1953		error = ENOTSUP;
1954		break;
1955	}
1956
1957	audio_file_exit(sc, &sc_ref);
1958	return error;
1959}
1960
1961
1962/* Exported interfaces for audiobell. */
1963
1964/*
1965 * Open for audiobell.
1966 * It stores allocated file to *filep.
1967 * If successful returns 0, otherwise errno.
1968 */
1969int
1970audiobellopen(dev_t dev, audio_file_t **filep)
1971{
1972	struct audio_softc *sc;
1973	int error;
1974
1975	/* Find the device */
1976	sc = device_lookup_private(&audio_cd, AUDIOUNIT(dev));
1977	if (sc == NULL || sc->hw_if == NULL)
1978		return ENXIO;
1979
1980	error = audio_exlock_enter(sc);
1981	if (error)
1982		return error;
1983
1984	device_active(sc->sc_dev, DVA_SYSTEM);
1985	error = audio_open(dev, sc, FWRITE, 0, curlwp, filep);
1986
1987	audio_exlock_exit(sc);
1988	return error;
1989}
1990
1991/* Close for audiobell */
1992int
1993audiobellclose(audio_file_t *file)
1994{
1995	struct audio_softc *sc;
1996	struct psref sc_ref;
1997	int error;
1998
1999	sc = audio_file_enter(file, &sc_ref);
2000	if (sc == NULL)
2001		return EIO;
2002
2003	error = audio_close(sc, file);
2004
2005	audio_file_exit(sc, &sc_ref);
2006
2007	KASSERT(file->ptrack);
2008	audio_track_destroy(file->ptrack);
2009	KASSERT(file->rtrack == NULL);
2010	kmem_free(file, sizeof(*file));
2011	return error;
2012}
2013
2014/* Set sample rate for audiobell */
2015int
2016audiobellsetrate(audio_file_t *file, u_int sample_rate)
2017{
2018	struct audio_softc *sc;
2019	struct psref sc_ref;
2020	struct audio_info ai;
2021	int error;
2022
2023	sc = audio_file_enter(file, &sc_ref);
2024	if (sc == NULL)
2025		return EIO;
2026
2027	AUDIO_INITINFO(&ai);
2028	ai.play.sample_rate = sample_rate;
2029
2030	error = audio_exlock_enter(sc);
2031	if (error)
2032		goto done;
2033	error = audio_file_setinfo(sc, file, &ai);
2034	audio_exlock_exit(sc);
2035
2036done:
2037	audio_file_exit(sc, &sc_ref);
2038	return error;
2039}
2040
2041/* Playback for audiobell */
2042int
2043audiobellwrite(audio_file_t *file, struct uio *uio)
2044{
2045	struct audio_softc *sc;
2046	struct psref sc_ref;
2047	int error;
2048
2049	sc = audio_file_enter(file, &sc_ref);
2050	if (sc == NULL)
2051		return EIO;
2052
2053	error = audio_write(sc, uio, 0, file);
2054
2055	audio_file_exit(sc, &sc_ref);
2056	return error;
2057}
2058
2059
2060/*
2061 * Audio driver
2062 */
2063
2064/*
2065 * Must be called with sc_exlock held and without sc_lock held.
2066 */
2067int
2068audio_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
2069	struct lwp *l, audio_file_t **bellfile)
2070{
2071	struct audio_info ai;
2072	struct file *fp;
2073	audio_file_t *af;
2074	audio_ring_t *hwbuf;
2075	bool fullduplex;
2076	int fd;
2077	int error;
2078
2079	KASSERT(sc->sc_exlock);
2080
2081	TRACE(1, "%sdev=%s flags=0x%x po=%d ro=%d",
2082	    (audiodebug >= 3) ? "start " : "",
2083	    ISDEVSOUND(dev) ? "sound" : "audio",
2084	    flags, sc->sc_popens, sc->sc_ropens);
2085
2086	af = kmem_zalloc(sizeof(audio_file_t), KM_SLEEP);
2087	af->sc = sc;
2088	af->dev = dev;
2089	if ((flags & FWRITE) != 0 && audio_can_playback(sc))
2090		af->mode |= AUMODE_PLAY | AUMODE_PLAY_ALL;
2091	if ((flags & FREAD) != 0 && audio_can_capture(sc))
2092		af->mode |= AUMODE_RECORD;
2093	if (af->mode == 0) {
2094		error = ENXIO;
2095		goto bad1;
2096	}
2097
2098	fullduplex = (sc->sc_props & AUDIO_PROP_FULLDUPLEX);
2099
2100	/*
2101	 * On half duplex hardware,
2102	 * 1. if mode is (PLAY | REC), let mode PLAY.
2103	 * 2. if mode is PLAY, let mode PLAY if no rec tracks, otherwise error.
2104	 * 3. if mode is REC, let mode REC if no play tracks, otherwise error.
2105	 */
2106	if (fullduplex == false) {
2107		if ((af->mode & AUMODE_PLAY)) {
2108			if (sc->sc_ropens != 0) {
2109				TRACE(1, "record track already exists");
2110				error = ENODEV;
2111				goto bad1;
2112			}
2113			/* Play takes precedence */
2114			af->mode &= ~AUMODE_RECORD;
2115		}
2116		if ((af->mode & AUMODE_RECORD)) {
2117			if (sc->sc_popens != 0) {
2118				TRACE(1, "play track already exists");
2119				error = ENODEV;
2120				goto bad1;
2121			}
2122		}
2123	}
2124
2125	/* Create tracks */
2126	if ((af->mode & AUMODE_PLAY))
2127		af->ptrack = audio_track_create(sc, sc->sc_pmixer);
2128	if ((af->mode & AUMODE_RECORD))
2129		af->rtrack = audio_track_create(sc, sc->sc_rmixer);
2130
2131	/* Set parameters */
2132	AUDIO_INITINFO(&ai);
2133	if (bellfile) {
2134		/* If audiobell, only sample_rate will be set later. */
2135		ai.play.sample_rate   = audio_default.sample_rate;
2136		ai.play.encoding      = AUDIO_ENCODING_SLINEAR_NE;
2137		ai.play.channels      = 1;
2138		ai.play.precision     = 16;
2139		ai.play.pause         = 0;
2140	} else if (ISDEVAUDIO(dev)) {
2141		/* If /dev/audio, initialize everytime. */
2142		ai.play.sample_rate   = audio_default.sample_rate;
2143		ai.play.encoding      = audio_default.encoding;
2144		ai.play.channels      = audio_default.channels;
2145		ai.play.precision     = audio_default.precision;
2146		ai.play.pause         = 0;
2147		ai.record.sample_rate = audio_default.sample_rate;
2148		ai.record.encoding    = audio_default.encoding;
2149		ai.record.channels    = audio_default.channels;
2150		ai.record.precision   = audio_default.precision;
2151		ai.record.pause       = 0;
2152	} else {
2153		/* If /dev/sound, take over the previous parameters. */
2154		ai.play.sample_rate   = sc->sc_sound_pparams.sample_rate;
2155		ai.play.encoding      = sc->sc_sound_pparams.encoding;
2156		ai.play.channels      = sc->sc_sound_pparams.channels;
2157		ai.play.precision     = sc->sc_sound_pparams.precision;
2158		ai.play.pause         = sc->sc_sound_ppause;
2159		ai.record.sample_rate = sc->sc_sound_rparams.sample_rate;
2160		ai.record.encoding    = sc->sc_sound_rparams.encoding;
2161		ai.record.channels    = sc->sc_sound_rparams.channels;
2162		ai.record.precision   = sc->sc_sound_rparams.precision;
2163		ai.record.pause       = sc->sc_sound_rpause;
2164	}
2165	error = audio_file_setinfo(sc, af, &ai);
2166	if (error)
2167		goto bad2;
2168
2169	if (sc->sc_popens + sc->sc_ropens == 0) {
2170		/* First open */
2171
2172		sc->sc_cred = kauth_cred_get();
2173		kauth_cred_hold(sc->sc_cred);
2174
2175		if (sc->hw_if->open) {
2176			int hwflags;
2177
2178			/*
2179			 * Call hw_if->open() only at first open of
2180			 * combination of playback and recording.
2181			 * On full duplex hardware, the flags passed to
2182			 * hw_if->open() is always (FREAD | FWRITE)
2183			 * regardless of this open()'s flags.
2184			 * see also dev/isa/aria.c
2185			 * On half duplex hardware, the flags passed to
2186			 * hw_if->open() is either FREAD or FWRITE.
2187			 * see also arch/evbarm/mini2440/audio_mini2440.c
2188			 */
2189			if (fullduplex) {
2190				hwflags = FREAD | FWRITE;
2191			} else {
2192				/* Construct hwflags from af->mode. */
2193				hwflags = 0;
2194				if ((af->mode & AUMODE_PLAY) != 0)
2195					hwflags |= FWRITE;
2196				if ((af->mode & AUMODE_RECORD) != 0)
2197					hwflags |= FREAD;
2198			}
2199
2200			mutex_enter(sc->sc_lock);
2201			mutex_enter(sc->sc_intr_lock);
2202			error = sc->hw_if->open(sc->hw_hdl, hwflags);
2203			mutex_exit(sc->sc_intr_lock);
2204			mutex_exit(sc->sc_lock);
2205			if (error)
2206				goto bad2;
2207		}
2208
2209		/*
2210		 * Set speaker mode when a half duplex.
2211		 * XXX I'm not sure this is correct.
2212		 */
2213		if (1/*XXX*/) {
2214			if (sc->hw_if->speaker_ctl) {
2215				int on;
2216				if (af->ptrack) {
2217					on = 1;
2218				} else {
2219					on = 0;
2220				}
2221				mutex_enter(sc->sc_lock);
2222				mutex_enter(sc->sc_intr_lock);
2223				error = sc->hw_if->speaker_ctl(sc->hw_hdl, on);
2224				mutex_exit(sc->sc_intr_lock);
2225				mutex_exit(sc->sc_lock);
2226				if (error)
2227					goto bad3;
2228			}
2229		}
2230	} else if (sc->sc_multiuser == false) {
2231		uid_t euid = kauth_cred_geteuid(kauth_cred_get());
2232		if (euid != 0 && euid != kauth_cred_geteuid(sc->sc_cred)) {
2233			error = EPERM;
2234			goto bad2;
2235		}
2236	}
2237
2238	/* Call init_output if this is the first playback open. */
2239	if (af->ptrack && sc->sc_popens == 0) {
2240		if (sc->hw_if->init_output) {
2241			hwbuf = &sc->sc_pmixer->hwbuf;
2242			mutex_enter(sc->sc_lock);
2243			mutex_enter(sc->sc_intr_lock);
2244			error = sc->hw_if->init_output(sc->hw_hdl,
2245			    hwbuf->mem,
2246			    hwbuf->capacity *
2247			    hwbuf->fmt.channels * hwbuf->fmt.stride / NBBY);
2248			mutex_exit(sc->sc_intr_lock);
2249			mutex_exit(sc->sc_lock);
2250			if (error)
2251				goto bad3;
2252		}
2253	}
2254	/*
2255	 * Call init_input and start rmixer, if this is the first recording
2256	 * open.  See pause consideration notes.
2257	 */
2258	if (af->rtrack && sc->sc_ropens == 0) {
2259		if (sc->hw_if->init_input) {
2260			hwbuf = &sc->sc_rmixer->hwbuf;
2261			mutex_enter(sc->sc_lock);
2262			mutex_enter(sc->sc_intr_lock);
2263			error = sc->hw_if->init_input(sc->hw_hdl,
2264			    hwbuf->mem,
2265			    hwbuf->capacity *
2266			    hwbuf->fmt.channels * hwbuf->fmt.stride / NBBY);
2267			mutex_exit(sc->sc_intr_lock);
2268			mutex_exit(sc->sc_lock);
2269			if (error)
2270				goto bad3;
2271		}
2272
2273		mutex_enter(sc->sc_lock);
2274		audio_rmixer_start(sc);
2275		mutex_exit(sc->sc_lock);
2276	}
2277
2278	if (bellfile == NULL) {
2279		error = fd_allocfile(&fp, &fd);
2280		if (error)
2281			goto bad3;
2282	}
2283
2284	/*
2285	 * Count up finally.
2286	 * Don't fail from here.
2287	 */
2288	mutex_enter(sc->sc_lock);
2289	if (af->ptrack)
2290		sc->sc_popens++;
2291	if (af->rtrack)
2292		sc->sc_ropens++;
2293	mutex_enter(sc->sc_intr_lock);
2294	SLIST_INSERT_HEAD(&sc->sc_files, af, entry);
2295	mutex_exit(sc->sc_intr_lock);
2296	mutex_exit(sc->sc_lock);
2297
2298	if (bellfile) {
2299		*bellfile = af;
2300	} else {
2301		error = fd_clone(fp, fd, flags, &audio_fileops, af);
2302		KASSERTMSG(error == EMOVEFD, "error=%d", error);
2303	}
2304
2305	TRACEF(3, af, "done");
2306	return error;
2307
2308	/*
2309	 * Since track here is not yet linked to sc_files,
2310	 * you can call track_destroy() without sc_intr_lock.
2311	 */
2312bad3:
2313	if (sc->sc_popens + sc->sc_ropens == 0) {
2314		if (sc->hw_if->close) {
2315			mutex_enter(sc->sc_lock);
2316			mutex_enter(sc->sc_intr_lock);
2317			sc->hw_if->close(sc->hw_hdl);
2318			mutex_exit(sc->sc_intr_lock);
2319			mutex_exit(sc->sc_lock);
2320		}
2321	}
2322bad2:
2323	if (af->rtrack) {
2324		audio_track_destroy(af->rtrack);
2325		af->rtrack = NULL;
2326	}
2327	if (af->ptrack) {
2328		audio_track_destroy(af->ptrack);
2329		af->ptrack = NULL;
2330	}
2331bad1:
2332	kmem_free(af, sizeof(*af));
2333	return error;
2334}
2335
2336/*
2337 * Must be called without sc_lock nor sc_exlock held.
2338 */
2339int
2340audio_close(struct audio_softc *sc, audio_file_t *file)
2341{
2342
2343	/* Protect entering new fileops to this file */
2344	atomic_store_relaxed(&file->dying, true);
2345
2346	/*
2347	 * Drain first.
2348	 * It must be done before unlinking(acquiring exlock).
2349	 */
2350	if (file->ptrack) {
2351		mutex_enter(sc->sc_lock);
2352		audio_track_drain(sc, file->ptrack);
2353		mutex_exit(sc->sc_lock);
2354	}
2355
2356	return audio_unlink(sc, file);
2357}
2358
2359/*
2360 * Unlink this file, but not freeing memory here.
2361 * Must be called without sc_lock nor sc_exlock held.
2362 */
2363int
2364audio_unlink(struct audio_softc *sc, audio_file_t *file)
2365{
2366	int error;
2367
2368	mutex_enter(sc->sc_lock);
2369
2370	TRACEF(1, file, "%spid=%d.%d po=%d ro=%d",
2371	    (audiodebug >= 3) ? "start " : "",
2372	    (int)curproc->p_pid, (int)curlwp->l_lid,
2373	    sc->sc_popens, sc->sc_ropens);
2374	KASSERTMSG(sc->sc_popens + sc->sc_ropens > 0,
2375	    "sc->sc_popens=%d, sc->sc_ropens=%d",
2376	    sc->sc_popens, sc->sc_ropens);
2377
2378	/*
2379	 * Acquire exlock to protect counters.
2380	 * Does not use audio_exlock_enter() due to sc_dying.
2381	 */
2382	while (__predict_false(sc->sc_exlock != 0)) {
2383		error = cv_timedwait_sig(&sc->sc_exlockcv, sc->sc_lock,
2384		    mstohz(AUDIO_TIMEOUT));
2385		/* XXX what should I do on error? */
2386		if (error == EWOULDBLOCK) {
2387			mutex_exit(sc->sc_lock);
2388			device_printf(sc->sc_dev,
2389			    "%s: cv_timedwait_sig failed %d", __func__, error);
2390			return error;
2391		}
2392	}
2393	sc->sc_exlock = 1;
2394
2395	device_active(sc->sc_dev, DVA_SYSTEM);
2396
2397	mutex_enter(sc->sc_intr_lock);
2398	SLIST_REMOVE(&sc->sc_files, file, audio_file, entry);
2399	mutex_exit(sc->sc_intr_lock);
2400
2401	if (file->ptrack) {
2402		TRACET(3, file->ptrack, "dropframes=%" PRIu64,
2403		    file->ptrack->dropframes);
2404
2405		KASSERT(sc->sc_popens > 0);
2406		sc->sc_popens--;
2407
2408		/* Call hw halt_output if this is the last playback track. */
2409		if (sc->sc_popens == 0 && sc->sc_pbusy) {
2410			error = audio_pmixer_halt(sc);
2411			if (error) {
2412				device_printf(sc->sc_dev,
2413				    "halt_output failed with %d (ignored)\n",
2414				    error);
2415			}
2416		}
2417
2418		/* Restore mixing volume if all tracks are gone. */
2419		if (sc->sc_popens == 0) {
2420			/* intr_lock is not necessary, but just manners. */
2421			mutex_enter(sc->sc_intr_lock);
2422			sc->sc_pmixer->volume = 256;
2423			sc->sc_pmixer->voltimer = 0;
2424			mutex_exit(sc->sc_intr_lock);
2425		}
2426	}
2427	if (file->rtrack) {
2428		TRACET(3, file->rtrack, "dropframes=%" PRIu64,
2429		    file->rtrack->dropframes);
2430
2431		KASSERT(sc->sc_ropens > 0);
2432		sc->sc_ropens--;
2433
2434		/* Call hw halt_input if this is the last recording track. */
2435		if (sc->sc_ropens == 0 && sc->sc_rbusy) {
2436			error = audio_rmixer_halt(sc);
2437			if (error) {
2438				device_printf(sc->sc_dev,
2439				    "halt_input failed with %d (ignored)\n",
2440				    error);
2441			}
2442		}
2443
2444	}
2445
2446	/* Call hw close if this is the last track. */
2447	if (sc->sc_popens + sc->sc_ropens == 0) {
2448		if (sc->hw_if->close) {
2449			TRACE(2, "hw_if close");
2450			mutex_enter(sc->sc_intr_lock);
2451			sc->hw_if->close(sc->hw_hdl);
2452			mutex_exit(sc->sc_intr_lock);
2453		}
2454	}
2455
2456	mutex_exit(sc->sc_lock);
2457	if (sc->sc_popens + sc->sc_ropens == 0)
2458		kauth_cred_free(sc->sc_cred);
2459
2460	TRACE(3, "done");
2461	audio_exlock_exit(sc);
2462
2463	return 0;
2464}
2465
2466/*
2467 * Must be called without sc_lock nor sc_exlock held.
2468 */
2469int
2470audio_read(struct audio_softc *sc, struct uio *uio, int ioflag,
2471	audio_file_t *file)
2472{
2473	audio_track_t *track;
2474	audio_ring_t *usrbuf;
2475	audio_ring_t *input;
2476	int error;
2477
2478	/*
2479	 * On half-duplex hardware, O_RDWR is treated as O_WRONLY.
2480	 * However read() system call itself can be called because it's
2481	 * opened with O_RDWR.  So in this case, deny this read().
2482	 */
2483	track = file->rtrack;
2484	if (track == NULL) {
2485		return EBADF;
2486	}
2487
2488	/* I think it's better than EINVAL. */
2489	if (track->mmapped)
2490		return EPERM;
2491
2492	TRACET(2, track, "resid=%zd", uio->uio_resid);
2493
2494#ifdef AUDIO_PM_IDLE
2495	error = audio_exlock_mutex_enter(sc);
2496	if (error)
2497		return error;
2498
2499	if (device_is_active(&sc->sc_dev) || sc->sc_idle)
2500		device_active(&sc->sc_dev, DVA_SYSTEM);
2501
2502	/* In recording, unlike playback, read() never operates rmixer. */
2503
2504	audio_exlock_mutex_exit(sc);
2505#endif
2506
2507	usrbuf = &track->usrbuf;
2508	input = track->input;
2509	error = 0;
2510
2511	while (uio->uio_resid > 0 && error == 0) {
2512		int bytes;
2513
2514		TRACET(3, track,
2515		    "while resid=%zd input=%d/%d/%d usrbuf=%d/%d/H%d",
2516		    uio->uio_resid,
2517		    input->head, input->used, input->capacity,
2518		    usrbuf->head, usrbuf->used, track->usrbuf_usedhigh);
2519
2520		/* Wait when buffers are empty. */
2521		mutex_enter(sc->sc_lock);
2522		for (;;) {
2523			bool empty;
2524			audio_track_lock_enter(track);
2525			empty = (input->used == 0 && usrbuf->used == 0);
2526			audio_track_lock_exit(track);
2527			if (!empty)
2528				break;
2529
2530			if ((ioflag & IO_NDELAY)) {
2531				mutex_exit(sc->sc_lock);
2532				return EWOULDBLOCK;
2533			}
2534
2535			TRACET(3, track, "sleep");
2536			error = audio_track_waitio(sc, track);
2537			if (error) {
2538				mutex_exit(sc->sc_lock);
2539				return error;
2540			}
2541		}
2542		mutex_exit(sc->sc_lock);
2543
2544		audio_track_lock_enter(track);
2545		audio_track_record(track);
2546
2547		/* uiomove from usrbuf as much as possible. */
2548		bytes = uimin(usrbuf->used, uio->uio_resid);
2549		while (bytes > 0) {
2550			int head = usrbuf->head;
2551			int len = uimin(bytes, usrbuf->capacity - head);
2552			error = uiomove((uint8_t *)usrbuf->mem + head, len,
2553			    uio);
2554			if (error) {
2555				audio_track_lock_exit(track);
2556				device_printf(sc->sc_dev,
2557				    "uiomove(len=%d) failed with %d\n",
2558				    len, error);
2559				goto abort;
2560			}
2561			auring_take(usrbuf, len);
2562			track->useriobytes += len;
2563			TRACET(3, track, "uiomove(len=%d) usrbuf=%d/%d/C%d",
2564			    len,
2565			    usrbuf->head, usrbuf->used, usrbuf->capacity);
2566			bytes -= len;
2567		}
2568
2569		audio_track_lock_exit(track);
2570	}
2571
2572abort:
2573	return error;
2574}
2575
2576
2577/*
2578 * Clear file's playback and/or record track buffer immediately.
2579 */
2580static void
2581audio_file_clear(struct audio_softc *sc, audio_file_t *file)
2582{
2583
2584	if (file->ptrack)
2585		audio_track_clear(sc, file->ptrack);
2586	if (file->rtrack)
2587		audio_track_clear(sc, file->rtrack);
2588}
2589
2590/*
2591 * Must be called without sc_lock nor sc_exlock held.
2592 */
2593int
2594audio_write(struct audio_softc *sc, struct uio *uio, int ioflag,
2595	audio_file_t *file)
2596{
2597	audio_track_t *track;
2598	audio_ring_t *usrbuf;
2599	audio_ring_t *outbuf;
2600	int error;
2601
2602	track = file->ptrack;
2603	KASSERT(track);
2604
2605	/* I think it's better than EINVAL. */
2606	if (track->mmapped)
2607		return EPERM;
2608
2609	TRACET(2, track, "%sresid=%zd pid=%d.%d ioflag=0x%x",
2610	    audiodebug >= 3 ? "begin " : "",
2611	    uio->uio_resid, (int)curproc->p_pid, (int)curlwp->l_lid, ioflag);
2612
2613	if (uio->uio_resid == 0) {
2614		track->eofcounter++;
2615		return 0;
2616	}
2617
2618	error = audio_exlock_mutex_enter(sc);
2619	if (error)
2620		return error;
2621
2622#ifdef AUDIO_PM_IDLE
2623	if (device_is_active(&sc->sc_dev) || sc->sc_idle)
2624		device_active(&sc->sc_dev, DVA_SYSTEM);
2625#endif
2626
2627	/*
2628	 * The first write starts pmixer.
2629	 */
2630	if (sc->sc_pbusy == false)
2631		audio_pmixer_start(sc, false);
2632	audio_exlock_mutex_exit(sc);
2633
2634	usrbuf = &track->usrbuf;
2635	outbuf = &track->outbuf;
2636	track->pstate = AUDIO_STATE_RUNNING;
2637	error = 0;
2638
2639	while (uio->uio_resid > 0 && error == 0) {
2640		int bytes;
2641
2642		TRACET(3, track, "while resid=%zd usrbuf=%d/%d/H%d",
2643		    uio->uio_resid,
2644		    usrbuf->head, usrbuf->used, track->usrbuf_usedhigh);
2645
2646		/* Wait when buffers are full. */
2647		mutex_enter(sc->sc_lock);
2648		for (;;) {
2649			bool full;
2650			audio_track_lock_enter(track);
2651			full = (usrbuf->used >= track->usrbuf_usedhigh &&
2652			    outbuf->used >= outbuf->capacity);
2653			audio_track_lock_exit(track);
2654			if (!full)
2655				break;
2656
2657			if ((ioflag & IO_NDELAY)) {
2658				error = EWOULDBLOCK;
2659				mutex_exit(sc->sc_lock);
2660				goto abort;
2661			}
2662
2663			TRACET(3, track, "sleep usrbuf=%d/H%d",
2664			    usrbuf->used, track->usrbuf_usedhigh);
2665			error = audio_track_waitio(sc, track);
2666			if (error) {
2667				mutex_exit(sc->sc_lock);
2668				goto abort;
2669			}
2670		}
2671		mutex_exit(sc->sc_lock);
2672
2673		audio_track_lock_enter(track);
2674
2675		/* uiomove to usrbuf as much as possible. */
2676		bytes = uimin(track->usrbuf_usedhigh - usrbuf->used,
2677		    uio->uio_resid);
2678		while (bytes > 0) {
2679			int tail = auring_tail(usrbuf);
2680			int len = uimin(bytes, usrbuf->capacity - tail);
2681			error = uiomove((uint8_t *)usrbuf->mem + tail, len,
2682			    uio);
2683			if (error) {
2684				audio_track_lock_exit(track);
2685				device_printf(sc->sc_dev,
2686				    "uiomove(len=%d) failed with %d\n",
2687				    len, error);
2688				goto abort;
2689			}
2690			auring_push(usrbuf, len);
2691			track->useriobytes += len;
2692			TRACET(3, track, "uiomove(len=%d) usrbuf=%d/%d/C%d",
2693			    len,
2694			    usrbuf->head, usrbuf->used, usrbuf->capacity);
2695			bytes -= len;
2696		}
2697
2698		/* Convert them as much as possible. */
2699		while (usrbuf->used >= track->usrbuf_blksize &&
2700		    outbuf->used < outbuf->capacity) {
2701			audio_track_play(track);
2702		}
2703
2704		audio_track_lock_exit(track);
2705	}
2706
2707abort:
2708	TRACET(3, track, "done error=%d", error);
2709	return error;
2710}
2711
2712/*
2713 * Must be called without sc_lock nor sc_exlock held.
2714 */
2715int
2716audio_ioctl(dev_t dev, struct audio_softc *sc, u_long cmd, void *addr, int flag,
2717	struct lwp *l, audio_file_t *file)
2718{
2719	struct audio_offset *ao;
2720	struct audio_info ai;
2721	audio_track_t *track;
2722	audio_encoding_t *ae;
2723	audio_format_query_t *query;
2724	u_int stamp;
2725	u_int offs;
2726	int fd;
2727	int index;
2728	int error;
2729
2730#if defined(AUDIO_DEBUG)
2731	const char *ioctlnames[] = {
2732		" AUDIO_GETINFO",	/* 21 */
2733		" AUDIO_SETINFO",	/* 22 */
2734		" AUDIO_DRAIN",		/* 23 */
2735		" AUDIO_FLUSH",		/* 24 */
2736		" AUDIO_WSEEK",		/* 25 */
2737		" AUDIO_RERROR",	/* 26 */
2738		" AUDIO_GETDEV",	/* 27 */
2739		" AUDIO_GETENC",	/* 28 */
2740		" AUDIO_GETFD",		/* 29 */
2741		" AUDIO_SETFD",		/* 30 */
2742		" AUDIO_PERROR",	/* 31 */
2743		" AUDIO_GETIOFFS",	/* 32 */
2744		" AUDIO_GETOOFFS",	/* 33 */
2745		" AUDIO_GETPROPS",	/* 34 */
2746		" AUDIO_GETBUFINFO",	/* 35 */
2747		" AUDIO_SETCHAN",	/* 36 */
2748		" AUDIO_GETCHAN",	/* 37 */
2749		" AUDIO_QUERYFORMAT",	/* 38 */
2750		" AUDIO_GETFORMAT",	/* 39 */
2751		" AUDIO_SETFORMAT",	/* 40 */
2752	};
2753	int nameidx = (cmd & 0xff);
2754	const char *ioctlname = "";
2755	if (21 <= nameidx && nameidx <= 21 + __arraycount(ioctlnames))
2756		ioctlname = ioctlnames[nameidx - 21];
2757	TRACEF(2, file, "(%lu,'%c',%lu)%s pid=%d.%d",
2758	    IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff, ioctlname,
2759	    (int)curproc->p_pid, (int)l->l_lid);
2760#endif
2761
2762	error = 0;
2763	switch (cmd) {
2764	case FIONBIO:
2765		/* All handled in the upper FS layer. */
2766		break;
2767
2768	case FIONREAD:
2769		/* Get the number of bytes that can be read. */
2770		if (file->rtrack) {
2771			*(int *)addr = audio_track_readablebytes(file->rtrack);
2772		} else {
2773			*(int *)addr = 0;
2774		}
2775		break;
2776
2777	case FIOASYNC:
2778		/* Set/Clear ASYNC I/O. */
2779		if (*(int *)addr) {
2780			file->async_audio = curproc->p_pid;
2781			TRACEF(2, file, "FIOASYNC pid %d", file->async_audio);
2782		} else {
2783			file->async_audio = 0;
2784			TRACEF(2, file, "FIOASYNC off");
2785		}
2786		break;
2787
2788	case AUDIO_FLUSH:
2789		/* XXX TODO: clear errors and restart? */
2790		audio_file_clear(sc, file);
2791		break;
2792
2793	case AUDIO_RERROR:
2794		/*
2795		 * Number of read bytes dropped.  We don't know where
2796		 * or when they were dropped (including conversion stage).
2797		 * Therefore, the number of accurate bytes or samples is
2798		 * also unknown.
2799		 */
2800		track = file->rtrack;
2801		if (track) {
2802			*(int *)addr = frametobyte(&track->usrbuf.fmt,
2803			    track->dropframes);
2804		}
2805		break;
2806
2807	case AUDIO_PERROR:
2808		/*
2809		 * Number of write bytes dropped.  We don't know where
2810		 * or when they were dropped (including conversion stage).
2811		 * Therefore, the number of accurate bytes or samples is
2812		 * also unknown.
2813		 */
2814		track = file->ptrack;
2815		if (track) {
2816			*(int *)addr = frametobyte(&track->usrbuf.fmt,
2817			    track->dropframes);
2818		}
2819		break;
2820
2821	case AUDIO_GETIOFFS:
2822		/* XXX TODO */
2823		ao = (struct audio_offset *)addr;
2824		ao->samples = 0;
2825		ao->deltablks = 0;
2826		ao->offset = 0;
2827		break;
2828
2829	case AUDIO_GETOOFFS:
2830		ao = (struct audio_offset *)addr;
2831		track = file->ptrack;
2832		if (track == NULL) {
2833			ao->samples = 0;
2834			ao->deltablks = 0;
2835			ao->offset = 0;
2836			break;
2837		}
2838		mutex_enter(sc->sc_lock);
2839		mutex_enter(sc->sc_intr_lock);
2840		/* figure out where next DMA will start */
2841		stamp = track->usrbuf_stamp;
2842		offs = track->usrbuf.head;
2843		mutex_exit(sc->sc_intr_lock);
2844		mutex_exit(sc->sc_lock);
2845
2846		ao->samples = stamp;
2847		ao->deltablks = (stamp / track->usrbuf_blksize) -
2848		    (track->usrbuf_stamp_last / track->usrbuf_blksize);
2849		track->usrbuf_stamp_last = stamp;
2850		offs = rounddown(offs, track->usrbuf_blksize)
2851		    + track->usrbuf_blksize;
2852		if (offs >= track->usrbuf.capacity)
2853			offs -= track->usrbuf.capacity;
2854		ao->offset = offs;
2855
2856		TRACET(3, track, "GETOOFFS: samples=%u deltablks=%u offset=%u",
2857		    ao->samples, ao->deltablks, ao->offset);
2858		break;
2859
2860	case AUDIO_WSEEK:
2861		/* XXX return value does not include outbuf one. */
2862		if (file->ptrack)
2863			*(u_long *)addr = file->ptrack->usrbuf.used;
2864		break;
2865
2866	case AUDIO_SETINFO:
2867		error = audio_exlock_enter(sc);
2868		if (error)
2869			break;
2870		error = audio_file_setinfo(sc, file, (struct audio_info *)addr);
2871		if (error) {
2872			audio_exlock_exit(sc);
2873			break;
2874		}
2875		/* XXX TODO: update last_ai if /dev/sound ? */
2876		if (ISDEVSOUND(dev))
2877			error = audiogetinfo(sc, &sc->sc_ai, 0, file);
2878		audio_exlock_exit(sc);
2879		break;
2880
2881	case AUDIO_GETINFO:
2882		error = audio_exlock_enter(sc);
2883		if (error)
2884			break;
2885		error = audiogetinfo(sc, (struct audio_info *)addr, 1, file);
2886		audio_exlock_exit(sc);
2887		break;
2888
2889	case AUDIO_GETBUFINFO:
2890		error = audio_exlock_enter(sc);
2891		if (error)
2892			break;
2893		error = audiogetinfo(sc, (struct audio_info *)addr, 0, file);
2894		audio_exlock_exit(sc);
2895		break;
2896
2897	case AUDIO_DRAIN:
2898		if (file->ptrack) {
2899			mutex_enter(sc->sc_lock);
2900			error = audio_track_drain(sc, file->ptrack);
2901			mutex_exit(sc->sc_lock);
2902		}
2903		break;
2904
2905	case AUDIO_GETDEV:
2906		mutex_enter(sc->sc_lock);
2907		error = sc->hw_if->getdev(sc->hw_hdl, (audio_device_t *)addr);
2908		mutex_exit(sc->sc_lock);
2909		break;
2910
2911	case AUDIO_GETENC:
2912		ae = (audio_encoding_t *)addr;
2913		index = ae->index;
2914		if (index < 0 || index >= __arraycount(audio_encodings)) {
2915			error = EINVAL;
2916			break;
2917		}
2918		*ae = audio_encodings[index];
2919		ae->index = index;
2920		/*
2921		 * EMULATED always.
2922		 * EMULATED flag at that time used to mean that it could
2923		 * not be passed directly to the hardware as-is.  But
2924		 * currently, all formats including hardware native is not
2925		 * passed directly to the hardware.  So I set EMULATED
2926		 * flag for all formats.
2927		 */
2928		ae->flags = AUDIO_ENCODINGFLAG_EMULATED;
2929		break;
2930
2931	case AUDIO_GETFD:
2932		/*
2933		 * Returns the current setting of full duplex mode.
2934		 * If HW has full duplex mode and there are two mixers,
2935		 * it is full duplex.  Otherwise half duplex.
2936		 */
2937		error = audio_exlock_enter(sc);
2938		if (error)
2939			break;
2940		fd = (sc->sc_props & AUDIO_PROP_FULLDUPLEX)
2941		    && (sc->sc_pmixer && sc->sc_rmixer);
2942		audio_exlock_exit(sc);
2943		*(int *)addr = fd;
2944		break;
2945
2946	case AUDIO_GETPROPS:
2947		*(int *)addr = sc->sc_props;
2948		break;
2949
2950	case AUDIO_QUERYFORMAT:
2951		query = (audio_format_query_t *)addr;
2952		mutex_enter(sc->sc_lock);
2953		error = sc->hw_if->query_format(sc->hw_hdl, query);
2954		mutex_exit(sc->sc_lock);
2955		/* Hide internal infomations */
2956		query->fmt.driver_data = NULL;
2957		break;
2958
2959	case AUDIO_GETFORMAT:
2960		error = audio_exlock_enter(sc);
2961		if (error)
2962			break;
2963		audio_mixers_get_format(sc, (struct audio_info *)addr);
2964		audio_exlock_exit(sc);
2965		break;
2966
2967	case AUDIO_SETFORMAT:
2968		error = audio_exlock_enter(sc);
2969		audio_mixers_get_format(sc, &ai);
2970		error = audio_mixers_set_format(sc, (struct audio_info *)addr);
2971		if (error) {
2972			/* Rollback */
2973			audio_mixers_set_format(sc, &ai);
2974		}
2975		audio_exlock_exit(sc);
2976		break;
2977
2978	case AUDIO_SETFD:
2979	case AUDIO_SETCHAN:
2980	case AUDIO_GETCHAN:
2981		/* Obsoleted */
2982		break;
2983
2984	default:
2985		if (sc->hw_if->dev_ioctl) {
2986			mutex_enter(sc->sc_lock);
2987			error = sc->hw_if->dev_ioctl(sc->hw_hdl,
2988			    cmd, addr, flag, l);
2989			mutex_exit(sc->sc_lock);
2990		} else {
2991			TRACEF(2, file, "unknown ioctl");
2992			error = EINVAL;
2993		}
2994		break;
2995	}
2996	TRACEF(2, file, "(%lu,'%c',%lu)%s result %d",
2997	    IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xff, ioctlname,
2998	    error);
2999	return error;
3000}
3001
3002/*
3003 * Returns the number of bytes that can be read on recording buffer.
3004 */
3005static __inline int
3006audio_track_readablebytes(const audio_track_t *track)
3007{
3008	int bytes;
3009
3010	KASSERT(track);
3011	KASSERT(track->mode == AUMODE_RECORD);
3012
3013	/*
3014	 * Although usrbuf is primarily readable data, recorded data
3015	 * also stays in track->input until reading.  So it is necessary
3016	 * to add it.  track->input is in frame, usrbuf is in byte.
3017	 */
3018	bytes = track->usrbuf.used +
3019	    track->input->used * frametobyte(&track->usrbuf.fmt, 1);
3020	return bytes;
3021}
3022
3023/*
3024 * Must be called without sc_lock nor sc_exlock held.
3025 */
3026int
3027audio_poll(struct audio_softc *sc, int events, struct lwp *l,
3028	audio_file_t *file)
3029{
3030	audio_track_t *track;
3031	int revents;
3032	bool in_is_valid;
3033	bool out_is_valid;
3034
3035#if defined(AUDIO_DEBUG)
3036#define POLLEV_BITMAP "\177\020" \
3037	    "b\10WRBAND\0" \
3038	    "b\7RDBAND\0" "b\6RDNORM\0" "b\5NVAL\0" "b\4HUP\0" \
3039	    "b\3ERR\0" "b\2OUT\0" "b\1PRI\0" "b\0IN\0"
3040	char evbuf[64];
3041	snprintb(evbuf, sizeof(evbuf), POLLEV_BITMAP, events);
3042	TRACEF(2, file, "pid=%d.%d events=%s",
3043	    (int)curproc->p_pid, (int)l->l_lid, evbuf);
3044#endif
3045
3046	revents = 0;
3047	in_is_valid = false;
3048	out_is_valid = false;
3049	if (events & (POLLIN | POLLRDNORM)) {
3050		track = file->rtrack;
3051		if (track) {
3052			int used;
3053			in_is_valid = true;
3054			used = audio_track_readablebytes(track);
3055			if (used > 0)
3056				revents |= events & (POLLIN | POLLRDNORM);
3057		}
3058	}
3059	if (events & (POLLOUT | POLLWRNORM)) {
3060		track = file->ptrack;
3061		if (track) {
3062			out_is_valid = true;
3063			if (track->usrbuf.used <= track->usrbuf_usedlow)
3064				revents |= events & (POLLOUT | POLLWRNORM);
3065		}
3066	}
3067
3068	if (revents == 0) {
3069		mutex_enter(sc->sc_lock);
3070		if (in_is_valid) {
3071			TRACEF(3, file, "selrecord rsel");
3072			selrecord(l, &sc->sc_rsel);
3073		}
3074		if (out_is_valid) {
3075			TRACEF(3, file, "selrecord wsel");
3076			selrecord(l, &sc->sc_wsel);
3077		}
3078		mutex_exit(sc->sc_lock);
3079	}
3080
3081#if defined(AUDIO_DEBUG)
3082	snprintb(evbuf, sizeof(evbuf), POLLEV_BITMAP, revents);
3083	TRACEF(2, file, "revents=%s", evbuf);
3084#endif
3085	return revents;
3086}
3087
3088static const struct filterops audioread_filtops = {
3089	.f_isfd = 1,
3090	.f_attach = NULL,
3091	.f_detach = filt_audioread_detach,
3092	.f_event = filt_audioread_event,
3093};
3094
3095static void
3096filt_audioread_detach(struct knote *kn)
3097{
3098	struct audio_softc *sc;
3099	audio_file_t *file;
3100
3101	file = kn->kn_hook;
3102	sc = file->sc;
3103	TRACEF(3, file, "");
3104
3105	mutex_enter(sc->sc_lock);
3106	SLIST_REMOVE(&sc->sc_rsel.sel_klist, kn, knote, kn_selnext);
3107	mutex_exit(sc->sc_lock);
3108}
3109
3110static int
3111filt_audioread_event(struct knote *kn, long hint)
3112{
3113	audio_file_t *file;
3114	audio_track_t *track;
3115
3116	file = kn->kn_hook;
3117	track = file->rtrack;
3118
3119	/*
3120	 * kn_data must contain the number of bytes can be read.
3121	 * The return value indicates whether the event occurs or not.
3122	 */
3123
3124	if (track == NULL) {
3125		/* can not read with this descriptor. */
3126		kn->kn_data = 0;
3127		return 0;
3128	}
3129
3130	kn->kn_data = audio_track_readablebytes(track);
3131	TRACEF(3, file, "data=%" PRId64, kn->kn_data);
3132	return kn->kn_data > 0;
3133}
3134
3135static const struct filterops audiowrite_filtops = {
3136	.f_isfd = 1,
3137	.f_attach = NULL,
3138	.f_detach = filt_audiowrite_detach,
3139	.f_event = filt_audiowrite_event,
3140};
3141
3142static void
3143filt_audiowrite_detach(struct knote *kn)
3144{
3145	struct audio_softc *sc;
3146	audio_file_t *file;
3147
3148	file = kn->kn_hook;
3149	sc = file->sc;
3150	TRACEF(3, file, "");
3151
3152	mutex_enter(sc->sc_lock);
3153	SLIST_REMOVE(&sc->sc_wsel.sel_klist, kn, knote, kn_selnext);
3154	mutex_exit(sc->sc_lock);
3155}
3156
3157static int
3158filt_audiowrite_event(struct knote *kn, long hint)
3159{
3160	audio_file_t *file;
3161	audio_track_t *track;
3162
3163	file = kn->kn_hook;
3164	track = file->ptrack;
3165
3166	/*
3167	 * kn_data must contain the number of bytes can be write.
3168	 * The return value indicates whether the event occurs or not.
3169	 */
3170
3171	if (track == NULL) {
3172		/* can not write with this descriptor. */
3173		kn->kn_data = 0;
3174		return 0;
3175	}
3176
3177	kn->kn_data = track->usrbuf_usedhigh - track->usrbuf.used;
3178	TRACEF(3, file, "data=%" PRId64, kn->kn_data);
3179	return (track->usrbuf.used < track->usrbuf_usedlow);
3180}
3181
3182/*
3183 * Must be called without sc_lock nor sc_exlock held.
3184 */
3185int
3186audio_kqfilter(struct audio_softc *sc, audio_file_t *file, struct knote *kn)
3187{
3188	struct klist *klist;
3189
3190	TRACEF(3, file, "kn=%p kn_filter=%x", kn, (int)kn->kn_filter);
3191
3192	mutex_enter(sc->sc_lock);
3193	switch (kn->kn_filter) {
3194	case EVFILT_READ:
3195		klist = &sc->sc_rsel.sel_klist;
3196		kn->kn_fop = &audioread_filtops;
3197		break;
3198
3199	case EVFILT_WRITE:
3200		klist = &sc->sc_wsel.sel_klist;
3201		kn->kn_fop = &audiowrite_filtops;
3202		break;
3203
3204	default:
3205		mutex_exit(sc->sc_lock);
3206		return EINVAL;
3207	}
3208
3209	kn->kn_hook = file;
3210
3211	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
3212	mutex_exit(sc->sc_lock);
3213
3214	return 0;
3215}
3216
3217/*
3218 * Must be called without sc_lock nor sc_exlock held.
3219 */
3220int
3221audio_mmap(struct audio_softc *sc, off_t *offp, size_t len, int prot,
3222	int *flagsp, int *advicep, struct uvm_object **uobjp, int *maxprotp,
3223	audio_file_t *file)
3224{
3225	audio_track_t *track;
3226	vsize_t vsize;
3227	int error;
3228
3229	TRACEF(2, file, "off=%lld, prot=%d", (long long)(*offp), prot);
3230
3231	if (*offp < 0)
3232		return EINVAL;
3233
3234#if 0
3235	/* XXX
3236	 * The idea here was to use the protection to determine if
3237	 * we are mapping the read or write buffer, but it fails.
3238	 * The VM system is broken in (at least) two ways.
3239	 * 1) If you map memory VM_PROT_WRITE you SIGSEGV
3240	 *    when writing to it, so VM_PROT_READ|VM_PROT_WRITE
3241	 *    has to be used for mmapping the play buffer.
3242	 * 2) Even if calling mmap() with VM_PROT_READ|VM_PROT_WRITE
3243	 *    audio_mmap will get called at some point with VM_PROT_READ
3244	 *    only.
3245	 * So, alas, we always map the play buffer for now.
3246	 */
3247	if (prot == (VM_PROT_READ|VM_PROT_WRITE) ||
3248	    prot == VM_PROT_WRITE)
3249		track = file->ptrack;
3250	else if (prot == VM_PROT_READ)
3251		track = file->rtrack;
3252	else
3253		return EINVAL;
3254#else
3255	track = file->ptrack;
3256#endif
3257	if (track == NULL)
3258		return EACCES;
3259
3260	vsize = roundup2(MAX(track->usrbuf.capacity, PAGE_SIZE), PAGE_SIZE);
3261	if (len > vsize)
3262		return EOVERFLOW;
3263	if (*offp > (uint)(vsize - len))
3264		return EOVERFLOW;
3265
3266	/* XXX TODO: what happens when mmap twice. */
3267	if (!track->mmapped) {
3268		track->mmapped = true;
3269
3270		if (!track->is_pause) {
3271			error = audio_exlock_mutex_enter(sc);
3272			if (error)
3273				return error;
3274			if (sc->sc_pbusy == false)
3275				audio_pmixer_start(sc, true);
3276			audio_exlock_mutex_exit(sc);
3277		}
3278		/* XXX mmapping record buffer is not supported */
3279	}
3280
3281	/* get ringbuffer */
3282	*uobjp = track->uobj;
3283
3284	/* Acquire a reference for the mmap.  munmap will release. */
3285	uao_reference(*uobjp);
3286	*maxprotp = prot;
3287	*advicep = UVM_ADV_RANDOM;
3288	*flagsp = MAP_SHARED;
3289	return 0;
3290}
3291
3292/*
3293 * /dev/audioctl has to be able to open at any time without interference
3294 * with any /dev/audio or /dev/sound.
3295 * Must be called with sc_exlock held and without sc_lock held.
3296 */
3297static int
3298audioctl_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
3299	struct lwp *l)
3300{
3301	struct file *fp;
3302	audio_file_t *af;
3303	int fd;
3304	int error;
3305
3306	KASSERT(sc->sc_exlock);
3307
3308	TRACE(1, "");
3309
3310	error = fd_allocfile(&fp, &fd);
3311	if (error)
3312		return error;
3313
3314	af = kmem_zalloc(sizeof(audio_file_t), KM_SLEEP);
3315	af->sc = sc;
3316	af->dev = dev;
3317
3318	/* Not necessary to insert sc_files. */
3319
3320	error = fd_clone(fp, fd, flags, &audio_fileops, af);
3321	KASSERTMSG(error == EMOVEFD, "error=%d", error);
3322
3323	return error;
3324}
3325
3326/*
3327 * Free 'mem' if available, and initialize the pointer.
3328 * For this reason, this is implemented as macro.
3329 */
3330#define audio_free(mem)	do {	\
3331	if (mem != NULL) {	\
3332		kern_free(mem);	\
3333		mem = NULL;	\
3334	}	\
3335} while (0)
3336
3337/*
3338 * (Re)allocate 'memblock' with specified 'bytes'.
3339 * bytes must not be 0.
3340 * This function never returns NULL.
3341 */
3342static void *
3343audio_realloc(void *memblock, size_t bytes)
3344{
3345
3346	KASSERT(bytes != 0);
3347	audio_free(memblock);
3348	return kern_malloc(bytes, M_WAITOK);
3349}
3350
3351/*
3352 * (Re)allocate usrbuf with 'newbufsize' bytes.
3353 * Use this function for usrbuf because only usrbuf can be mmapped.
3354 * If successful, it updates track->usrbuf.mem, track->usrbuf.capacity and
3355 * returns 0.  Otherwise, it clears track->usrbuf.mem, track->usrbuf.capacity
3356 * and returns errno.
3357 * It must be called before updating usrbuf.capacity.
3358 */
3359static int
3360audio_realloc_usrbuf(audio_track_t *track, int newbufsize)
3361{
3362	struct audio_softc *sc;
3363	vaddr_t vstart;
3364	vsize_t oldvsize;
3365	vsize_t newvsize;
3366	int error;
3367
3368	KASSERT(newbufsize > 0);
3369	sc = track->mixer->sc;
3370
3371	/* Get a nonzero multiple of PAGE_SIZE */
3372	newvsize = roundup2(MAX(newbufsize, PAGE_SIZE), PAGE_SIZE);
3373
3374	if (track->usrbuf.mem != NULL) {
3375		oldvsize = roundup2(MAX(track->usrbuf.capacity, PAGE_SIZE),
3376		    PAGE_SIZE);
3377		if (oldvsize == newvsize) {
3378			track->usrbuf.capacity = newbufsize;
3379			return 0;
3380		}
3381		vstart = (vaddr_t)track->usrbuf.mem;
3382		uvm_unmap(kernel_map, vstart, vstart + oldvsize);
3383		/* uvm_unmap also detach uobj */
3384		track->uobj = NULL;		/* paranoia */
3385		track->usrbuf.mem = NULL;
3386	}
3387
3388	/* Create a uvm anonymous object */
3389	track->uobj = uao_create(newvsize, 0);
3390
3391	/* Map it into the kernel virtual address space */
3392	vstart = 0;
3393	error = uvm_map(kernel_map, &vstart, newvsize, track->uobj, 0, 0,
3394	    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW, UVM_INH_NONE,
3395	    UVM_ADV_RANDOM, 0));
3396	if (error) {
3397		device_printf(sc->sc_dev, "uvm_map failed with %d\n", error);
3398		uao_detach(track->uobj);	/* release reference */
3399		goto abort;
3400	}
3401
3402	error = uvm_map_pageable(kernel_map, vstart, vstart + newvsize,
3403	    false, 0);
3404	if (error) {
3405		device_printf(sc->sc_dev, "uvm_map_pageable failed with %d\n",
3406		    error);
3407		uvm_unmap(kernel_map, vstart, vstart + newvsize);
3408		/* uvm_unmap also detach uobj */
3409		goto abort;
3410	}
3411
3412	track->usrbuf.mem = (void *)vstart;
3413	track->usrbuf.capacity = newbufsize;
3414	memset(track->usrbuf.mem, 0, newvsize);
3415	return 0;
3416
3417	/* failure */
3418abort:
3419	track->uobj = NULL;		/* paranoia */
3420	track->usrbuf.mem = NULL;
3421	track->usrbuf.capacity = 0;
3422	return error;
3423}
3424
3425/*
3426 * Free usrbuf (if available).
3427 */
3428static void
3429audio_free_usrbuf(audio_track_t *track)
3430{
3431	vaddr_t vstart;
3432	vsize_t vsize;
3433
3434	vstart = (vaddr_t)track->usrbuf.mem;
3435	vsize = roundup2(MAX(track->usrbuf.capacity, PAGE_SIZE), PAGE_SIZE);
3436	if (track->usrbuf.mem != NULL) {
3437		/*
3438		 * Unmap the kernel mapping.  uvm_unmap releases the
3439		 * reference to the uvm object, and this should be the
3440		 * last virtual mapping of the uvm object, so no need
3441		 * to explicitly release (`detach') the object.
3442		 */
3443		uvm_unmap(kernel_map, vstart, vstart + vsize);
3444
3445		track->uobj = NULL;
3446		track->usrbuf.mem = NULL;
3447		track->usrbuf.capacity = 0;
3448	}
3449}
3450
3451/*
3452 * This filter changes the volume for each channel.
3453 * arg->context points track->ch_volume[].
3454 */
3455static void
3456audio_track_chvol(audio_filter_arg_t *arg)
3457{
3458	int16_t *ch_volume;
3459	const aint_t *s;
3460	aint_t *d;
3461	u_int i;
3462	u_int ch;
3463	u_int channels;
3464
3465	DIAGNOSTIC_filter_arg(arg);
3466	KASSERTMSG(arg->srcfmt->channels == arg->dstfmt->channels,
3467	    "arg->srcfmt->channels=%d, arg->dstfmt->channels=%d",
3468	    arg->srcfmt->channels, arg->dstfmt->channels);
3469	KASSERT(arg->context != NULL);
3470	KASSERTMSG(arg->srcfmt->channels <= AUDIO_MAX_CHANNELS,
3471	    "arg->srcfmt->channels=%d", arg->srcfmt->channels);
3472
3473	s = arg->src;
3474	d = arg->dst;
3475	ch_volume = arg->context;
3476
3477	channels = arg->srcfmt->channels;
3478	for (i = 0; i < arg->count; i++) {
3479		for (ch = 0; ch < channels; ch++) {
3480			aint2_t val;
3481			val = *s++;
3482			val = AUDIO_SCALEDOWN(val * ch_volume[ch], 8);
3483			*d++ = (aint_t)val;
3484		}
3485	}
3486}
3487
3488/*
3489 * This filter performs conversion from stereo (or more channels) to mono.
3490 */
3491static void
3492audio_track_chmix_mixLR(audio_filter_arg_t *arg)
3493{
3494	const aint_t *s;
3495	aint_t *d;
3496	u_int i;
3497
3498	DIAGNOSTIC_filter_arg(arg);
3499
3500	s = arg->src;
3501	d = arg->dst;
3502
3503	for (i = 0; i < arg->count; i++) {
3504		*d++ = AUDIO_SCALEDOWN(s[0], 1) + AUDIO_SCALEDOWN(s[1], 1);
3505		s += arg->srcfmt->channels;
3506	}
3507}
3508
3509/*
3510 * This filter performs conversion from mono to stereo (or more channels).
3511 */
3512static void
3513audio_track_chmix_dupLR(audio_filter_arg_t *arg)
3514{
3515	const aint_t *s;
3516	aint_t *d;
3517	u_int i;
3518	u_int ch;
3519	u_int dstchannels;
3520
3521	DIAGNOSTIC_filter_arg(arg);
3522
3523	s = arg->src;
3524	d = arg->dst;
3525	dstchannels = arg->dstfmt->channels;
3526
3527	for (i = 0; i < arg->count; i++) {
3528		d[0] = s[0];
3529		d[1] = s[0];
3530		s++;
3531		d += dstchannels;
3532	}
3533	if (dstchannels > 2) {
3534		d = arg->dst;
3535		for (i = 0; i < arg->count; i++) {
3536			for (ch = 2; ch < dstchannels; ch++) {
3537				d[ch] = 0;
3538			}
3539			d += dstchannels;
3540		}
3541	}
3542}
3543
3544/*
3545 * This filter shrinks M channels into N channels.
3546 * Extra channels are discarded.
3547 */
3548static void
3549audio_track_chmix_shrink(audio_filter_arg_t *arg)
3550{
3551	const aint_t *s;
3552	aint_t *d;
3553	u_int i;
3554	u_int ch;
3555
3556	DIAGNOSTIC_filter_arg(arg);
3557
3558	s = arg->src;
3559	d = arg->dst;
3560
3561	for (i = 0; i < arg->count; i++) {
3562		for (ch = 0; ch < arg->dstfmt->channels; ch++) {
3563			*d++ = s[ch];
3564		}
3565		s += arg->srcfmt->channels;
3566	}
3567}
3568
3569/*
3570 * This filter expands M channels into N channels.
3571 * Silence is inserted for missing channels.
3572 */
3573static void
3574audio_track_chmix_expand(audio_filter_arg_t *arg)
3575{
3576	const aint_t *s;
3577	aint_t *d;
3578	u_int i;
3579	u_int ch;
3580	u_int srcchannels;
3581	u_int dstchannels;
3582
3583	DIAGNOSTIC_filter_arg(arg);
3584
3585	s = arg->src;
3586	d = arg->dst;
3587
3588	srcchannels = arg->srcfmt->channels;
3589	dstchannels = arg->dstfmt->channels;
3590	for (i = 0; i < arg->count; i++) {
3591		for (ch = 0; ch < srcchannels; ch++) {
3592			*d++ = *s++;
3593		}
3594		for (; ch < dstchannels; ch++) {
3595			*d++ = 0;
3596		}
3597	}
3598}
3599
3600/*
3601 * This filter performs frequency conversion (up sampling).
3602 * It uses linear interpolation.
3603 */
3604static void
3605audio_track_freq_up(audio_filter_arg_t *arg)
3606{
3607	audio_track_t *track;
3608	audio_ring_t *src;
3609	audio_ring_t *dst;
3610	const aint_t *s;
3611	aint_t *d;
3612	aint_t prev[AUDIO_MAX_CHANNELS];
3613	aint_t curr[AUDIO_MAX_CHANNELS];
3614	aint_t grad[AUDIO_MAX_CHANNELS];
3615	u_int i;
3616	u_int t;
3617	u_int step;
3618	u_int channels;
3619	u_int ch;
3620	int srcused;
3621
3622	track = arg->context;
3623	KASSERT(track);
3624	src = &track->freq.srcbuf;
3625	dst = track->freq.dst;
3626	DIAGNOSTIC_ring(dst);
3627	DIAGNOSTIC_ring(src);
3628	KASSERT(src->used > 0);
3629	KASSERTMSG(src->fmt.channels == dst->fmt.channels,
3630	    "src->fmt.channels=%d dst->fmt.channels=%d",
3631	    src->fmt.channels, dst->fmt.channels);
3632	KASSERTMSG(src->head % track->mixer->frames_per_block == 0,
3633	    "src->head=%d track->mixer->frames_per_block=%d",
3634	    src->head, track->mixer->frames_per_block);
3635
3636	s = arg->src;
3637	d = arg->dst;
3638
3639	/*
3640	 * In order to faciliate interpolation for each block, slide (delay)
3641	 * input by one sample.  As a result, strictly speaking, the output
3642	 * phase is delayed by 1/dstfreq.  However, I believe there is no
3643	 * observable impact.
3644	 *
3645	 * Example)
3646	 * srcfreq:dstfreq = 1:3
3647	 *
3648	 *  A - -
3649	 *  |
3650	 *  |
3651	 *  |     B - -
3652	 *  +-----+-----> input timeframe
3653	 *  0     1
3654	 *
3655	 *  0     1
3656	 *  +-----+-----> input timeframe
3657	 *  |     A
3658	 *  |   x   x
3659	 *  | x       x
3660	 *  x          (B)
3661	 *  +-+-+-+-+-+-> output timeframe
3662	 *  0 1 2 3 4 5
3663	 */
3664
3665	/* Last samples in previous block */
3666	channels = src->fmt.channels;
3667	for (ch = 0; ch < channels; ch++) {
3668		prev[ch] = track->freq_prev[ch];
3669		curr[ch] = track->freq_curr[ch];
3670		grad[ch] = curr[ch] - prev[ch];
3671	}
3672
3673	step = track->freq_step;
3674	t = track->freq_current;
3675//#define FREQ_DEBUG
3676#if defined(FREQ_DEBUG)
3677#define PRINTF(fmt...)	printf(fmt)
3678#else
3679#define PRINTF(fmt...)	do { } while (0)
3680#endif
3681	srcused = src->used;
3682	PRINTF("upstart step=%d leap=%d", step, track->freq_leap);
3683	PRINTF(" srcused=%d arg->count=%u", src->used, arg->count);
3684	PRINTF(" prev=%d curr=%d grad=%d", prev[0], curr[0], grad[0]);
3685	PRINTF(" t=%d\n", t);
3686
3687	for (i = 0; i < arg->count; i++) {
3688		PRINTF("i=%d t=%5d", i, t);
3689		if (t >= 65536) {
3690			for (ch = 0; ch < channels; ch++) {
3691				prev[ch] = curr[ch];
3692				curr[ch] = *s++;
3693				grad[ch] = curr[ch] - prev[ch];
3694			}
3695			PRINTF(" prev=%d s[%d]=%d",
3696			    prev[0], src->used - srcused, curr[0]);
3697
3698			/* Update */
3699			t -= 65536;
3700			srcused--;
3701			if (srcused < 0) {
3702				PRINTF(" break\n");
3703				break;
3704			}
3705		}
3706
3707		for (ch = 0; ch < channels; ch++) {
3708			*d++ = prev[ch] + (aint2_t)grad[ch] * t / 65536;
3709#if defined(FREQ_DEBUG)
3710			if (ch == 0)
3711				printf(" t=%5d *d=%d", t, d[-1]);
3712#endif
3713		}
3714		t += step;
3715
3716		PRINTF("\n");
3717	}
3718	PRINTF("end prev=%d curr=%d\n", prev[0], curr[0]);
3719
3720	auring_take(src, src->used);
3721	auring_push(dst, i);
3722
3723	/* Adjust */
3724	t += track->freq_leap;
3725
3726	track->freq_current = t;
3727	for (ch = 0; ch < channels; ch++) {
3728		track->freq_prev[ch] = prev[ch];
3729		track->freq_curr[ch] = curr[ch];
3730	}
3731}
3732
3733/*
3734 * This filter performs frequency conversion (down sampling).
3735 * It uses simple thinning.
3736 */
3737static void
3738audio_track_freq_down(audio_filter_arg_t *arg)
3739{
3740	audio_track_t *track;
3741	audio_ring_t *src;
3742	audio_ring_t *dst;
3743	const aint_t *s0;
3744	aint_t *d;
3745	u_int i;
3746	u_int t;
3747	u_int step;
3748	u_int ch;
3749	u_int channels;
3750
3751	track = arg->context;
3752	KASSERT(track);
3753	src = &track->freq.srcbuf;
3754	dst = track->freq.dst;
3755
3756	DIAGNOSTIC_ring(dst);
3757	DIAGNOSTIC_ring(src);
3758	KASSERT(src->used > 0);
3759	KASSERTMSG(src->fmt.channels == dst->fmt.channels,
3760	    "src->fmt.channels=%d dst->fmt.channels=%d",
3761	    src->fmt.channels, dst->fmt.channels);
3762	KASSERTMSG(src->head % track->mixer->frames_per_block == 0,
3763	    "src->head=%d track->mixer->frames_per_block=%d",
3764	    src->head, track->mixer->frames_per_block);
3765
3766	s0 = arg->src;
3767	d = arg->dst;
3768	t = track->freq_current;
3769	step = track->freq_step;
3770	channels = dst->fmt.channels;
3771	PRINTF("downstart step=%d leap=%d", step, track->freq_leap);
3772	PRINTF(" srcused=%d arg->count=%u", src->used, arg->count);
3773	PRINTF(" t=%d\n", t);
3774
3775	for (i = 0; i < arg->count && t / 65536 < src->used; i++) {
3776		const aint_t *s;
3777		PRINTF("i=%4d t=%10d", i, t);
3778		s = s0 + (t / 65536) * channels;
3779		PRINTF(" s=%5ld", (s - s0) / channels);
3780		for (ch = 0; ch < channels; ch++) {
3781			if (ch == 0) PRINTF(" *s=%d", s[ch]);
3782			*d++ = s[ch];
3783		}
3784		PRINTF("\n");
3785		t += step;
3786	}
3787	t += track->freq_leap;
3788	PRINTF("end t=%d\n", t);
3789	auring_take(src, src->used);
3790	auring_push(dst, i);
3791	track->freq_current = t % 65536;
3792}
3793
3794/*
3795 * Creates track and returns it.
3796 * Must be called without sc_lock held.
3797 */
3798audio_track_t *
3799audio_track_create(struct audio_softc *sc, audio_trackmixer_t *mixer)
3800{
3801	audio_track_t *track;
3802	static int newid = 0;
3803
3804	track = kmem_zalloc(sizeof(*track), KM_SLEEP);
3805
3806	track->id = newid++;
3807	track->mixer = mixer;
3808	track->mode = mixer->mode;
3809
3810	/* Do TRACE after id is assigned. */
3811	TRACET(3, track, "for %s",
3812	    mixer->mode == AUMODE_PLAY ? "playback" : "recording");
3813
3814#if defined(AUDIO_SUPPORT_TRACK_VOLUME)
3815	track->volume = 256;
3816#endif
3817	for (int i = 0; i < AUDIO_MAX_CHANNELS; i++) {
3818		track->ch_volume[i] = 256;
3819	}
3820
3821	return track;
3822}
3823
3824/*
3825 * Release all resources of the track and track itself.
3826 * track must not be NULL.  Don't specify the track within the file
3827 * structure linked from sc->sc_files.
3828 */
3829static void
3830audio_track_destroy(audio_track_t *track)
3831{
3832
3833	KASSERT(track);
3834
3835	audio_free_usrbuf(track);
3836	audio_free(track->codec.srcbuf.mem);
3837	audio_free(track->chvol.srcbuf.mem);
3838	audio_free(track->chmix.srcbuf.mem);
3839	audio_free(track->freq.srcbuf.mem);
3840	audio_free(track->outbuf.mem);
3841
3842	kmem_free(track, sizeof(*track));
3843}
3844
3845/*
3846 * It returns encoding conversion filter according to src and dst format.
3847 * If it is not a convertible pair, it returns NULL.  Either src or dst
3848 * must be internal format.
3849 */
3850static audio_filter_t
3851audio_track_get_codec(audio_track_t *track, const audio_format2_t *src,
3852	const audio_format2_t *dst)
3853{
3854
3855	if (audio_format2_is_internal(src)) {
3856		if (dst->encoding == AUDIO_ENCODING_ULAW) {
3857			return audio_internal_to_mulaw;
3858		} else if (dst->encoding == AUDIO_ENCODING_ALAW) {
3859			return audio_internal_to_alaw;
3860		} else if (audio_format2_is_linear(dst)) {
3861			switch (dst->stride) {
3862			case 8:
3863				return audio_internal_to_linear8;
3864			case 16:
3865				return audio_internal_to_linear16;
3866#if defined(AUDIO_SUPPORT_LINEAR24)
3867			case 24:
3868				return audio_internal_to_linear24;
3869#endif
3870			case 32:
3871				return audio_internal_to_linear32;
3872			default:
3873				TRACET(1, track, "unsupported %s stride %d",
3874				    "dst", dst->stride);
3875				goto abort;
3876			}
3877		}
3878	} else if (audio_format2_is_internal(dst)) {
3879		if (src->encoding == AUDIO_ENCODING_ULAW) {
3880			return audio_mulaw_to_internal;
3881		} else if (src->encoding == AUDIO_ENCODING_ALAW) {
3882			return audio_alaw_to_internal;
3883		} else if (audio_format2_is_linear(src)) {
3884			switch (src->stride) {
3885			case 8:
3886				return audio_linear8_to_internal;
3887			case 16:
3888				return audio_linear16_to_internal;
3889#if defined(AUDIO_SUPPORT_LINEAR24)
3890			case 24:
3891				return audio_linear24_to_internal;
3892#endif
3893			case 32:
3894				return audio_linear32_to_internal;
3895			default:
3896				TRACET(1, track, "unsupported %s stride %d",
3897				    "src", src->stride);
3898				goto abort;
3899			}
3900		}
3901	}
3902
3903	TRACET(1, track, "unsupported encoding");
3904abort:
3905#if defined(AUDIO_DEBUG)
3906	if (audiodebug >= 2) {
3907		char buf[100];
3908		audio_format2_tostr(buf, sizeof(buf), src);
3909		TRACET(2, track, "src %s", buf);
3910		audio_format2_tostr(buf, sizeof(buf), dst);
3911		TRACET(2, track, "dst %s", buf);
3912	}
3913#endif
3914	return NULL;
3915}
3916
3917/*
3918 * Initialize the codec stage of this track as necessary.
3919 * If successful, it initializes the codec stage as necessary, stores updated
3920 * last_dst in *last_dstp in any case, and returns 0.
3921 * Otherwise, it returns errno without modifying *last_dstp.
3922 */
3923static int
3924audio_track_init_codec(audio_track_t *track, audio_ring_t **last_dstp)
3925{
3926	audio_ring_t *last_dst;
3927	audio_ring_t *srcbuf;
3928	audio_format2_t *srcfmt;
3929	audio_format2_t *dstfmt;
3930	audio_filter_arg_t *arg;
3931	u_int len;
3932	int error;
3933
3934	KASSERT(track);
3935
3936	last_dst = *last_dstp;
3937	dstfmt = &last_dst->fmt;
3938	srcfmt = &track->inputfmt;
3939	srcbuf = &track->codec.srcbuf;
3940	error = 0;
3941
3942	if (srcfmt->encoding != dstfmt->encoding
3943	 || srcfmt->precision != dstfmt->precision
3944	 || srcfmt->stride != dstfmt->stride) {
3945		track->codec.dst = last_dst;
3946
3947		srcbuf->fmt = *dstfmt;
3948		srcbuf->fmt.encoding = srcfmt->encoding;
3949		srcbuf->fmt.precision = srcfmt->precision;
3950		srcbuf->fmt.stride = srcfmt->stride;
3951
3952		track->codec.filter = audio_track_get_codec(track,
3953		    &srcbuf->fmt, dstfmt);
3954		if (track->codec.filter == NULL) {
3955			error = EINVAL;
3956			goto abort;
3957		}
3958
3959		srcbuf->head = 0;
3960		srcbuf->used = 0;
3961		srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
3962		len = auring_bytelen(srcbuf);
3963		srcbuf->mem = audio_realloc(srcbuf->mem, len);
3964
3965		arg = &track->codec.arg;
3966		arg->srcfmt = &srcbuf->fmt;
3967		arg->dstfmt = dstfmt;
3968		arg->context = NULL;
3969
3970		*last_dstp = srcbuf;
3971		return 0;
3972	}
3973
3974abort:
3975	track->codec.filter = NULL;
3976	audio_free(srcbuf->mem);
3977	return error;
3978}
3979
3980/*
3981 * Initialize the chvol stage of this track as necessary.
3982 * If successful, it initializes the chvol stage as necessary, stores updated
3983 * last_dst in *last_dstp in any case, and returns 0.
3984 * Otherwise, it returns errno without modifying *last_dstp.
3985 */
3986static int
3987audio_track_init_chvol(audio_track_t *track, audio_ring_t **last_dstp)
3988{
3989	audio_ring_t *last_dst;
3990	audio_ring_t *srcbuf;
3991	audio_format2_t *srcfmt;
3992	audio_format2_t *dstfmt;
3993	audio_filter_arg_t *arg;
3994	u_int len;
3995	int error;
3996
3997	KASSERT(track);
3998
3999	last_dst = *last_dstp;
4000	dstfmt = &last_dst->fmt;
4001	srcfmt = &track->inputfmt;
4002	srcbuf = &track->chvol.srcbuf;
4003	error = 0;
4004
4005	/* Check whether channel volume conversion is necessary. */
4006	bool use_chvol = false;
4007	for (int ch = 0; ch < srcfmt->channels; ch++) {
4008		if (track->ch_volume[ch] != 256) {
4009			use_chvol = true;
4010			break;
4011		}
4012	}
4013
4014	if (use_chvol == true) {
4015		track->chvol.dst = last_dst;
4016		track->chvol.filter = audio_track_chvol;
4017
4018		srcbuf->fmt = *dstfmt;
4019		/* no format conversion occurs */
4020
4021		srcbuf->head = 0;
4022		srcbuf->used = 0;
4023		srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
4024		len = auring_bytelen(srcbuf);
4025		srcbuf->mem = audio_realloc(srcbuf->mem, len);
4026
4027		arg = &track->chvol.arg;
4028		arg->srcfmt = &srcbuf->fmt;
4029		arg->dstfmt = dstfmt;
4030		arg->context = track->ch_volume;
4031
4032		*last_dstp = srcbuf;
4033		return 0;
4034	}
4035
4036	track->chvol.filter = NULL;
4037	audio_free(srcbuf->mem);
4038	return error;
4039}
4040
4041/*
4042 * Initialize the chmix stage of this track as necessary.
4043 * If successful, it initializes the chmix stage as necessary, stores updated
4044 * last_dst in *last_dstp in any case, and returns 0.
4045 * Otherwise, it returns errno without modifying *last_dstp.
4046 */
4047static int
4048audio_track_init_chmix(audio_track_t *track, audio_ring_t **last_dstp)
4049{
4050	audio_ring_t *last_dst;
4051	audio_ring_t *srcbuf;
4052	audio_format2_t *srcfmt;
4053	audio_format2_t *dstfmt;
4054	audio_filter_arg_t *arg;
4055	u_int srcch;
4056	u_int dstch;
4057	u_int len;
4058	int error;
4059
4060	KASSERT(track);
4061
4062	last_dst = *last_dstp;
4063	dstfmt = &last_dst->fmt;
4064	srcfmt = &track->inputfmt;
4065	srcbuf = &track->chmix.srcbuf;
4066	error = 0;
4067
4068	srcch = srcfmt->channels;
4069	dstch = dstfmt->channels;
4070	if (srcch != dstch) {
4071		track->chmix.dst = last_dst;
4072
4073		if (srcch >= 2 && dstch == 1) {
4074			track->chmix.filter = audio_track_chmix_mixLR;
4075		} else if (srcch == 1 && dstch >= 2) {
4076			track->chmix.filter = audio_track_chmix_dupLR;
4077		} else if (srcch > dstch) {
4078			track->chmix.filter = audio_track_chmix_shrink;
4079		} else {
4080			track->chmix.filter = audio_track_chmix_expand;
4081		}
4082
4083		srcbuf->fmt = *dstfmt;
4084		srcbuf->fmt.channels = srcch;
4085
4086		srcbuf->head = 0;
4087		srcbuf->used = 0;
4088		/* XXX The buffer size should be able to calculate. */
4089		srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
4090		len = auring_bytelen(srcbuf);
4091		srcbuf->mem = audio_realloc(srcbuf->mem, len);
4092
4093		arg = &track->chmix.arg;
4094		arg->srcfmt = &srcbuf->fmt;
4095		arg->dstfmt = dstfmt;
4096		arg->context = NULL;
4097
4098		*last_dstp = srcbuf;
4099		return 0;
4100	}
4101
4102	track->chmix.filter = NULL;
4103	audio_free(srcbuf->mem);
4104	return error;
4105}
4106
4107/*
4108 * Initialize the freq stage of this track as necessary.
4109 * If successful, it initializes the freq stage as necessary, stores updated
4110 * last_dst in *last_dstp in any case, and returns 0.
4111 * Otherwise, it returns errno without modifying *last_dstp.
4112 */
4113static int
4114audio_track_init_freq(audio_track_t *track, audio_ring_t **last_dstp)
4115{
4116	audio_ring_t *last_dst;
4117	audio_ring_t *srcbuf;
4118	audio_format2_t *srcfmt;
4119	audio_format2_t *dstfmt;
4120	audio_filter_arg_t *arg;
4121	uint32_t srcfreq;
4122	uint32_t dstfreq;
4123	u_int dst_capacity;
4124	u_int mod;
4125	u_int len;
4126	int error;
4127
4128	KASSERT(track);
4129
4130	last_dst = *last_dstp;
4131	dstfmt = &last_dst->fmt;
4132	srcfmt = &track->inputfmt;
4133	srcbuf = &track->freq.srcbuf;
4134	error = 0;
4135
4136	srcfreq = srcfmt->sample_rate;
4137	dstfreq = dstfmt->sample_rate;
4138	if (srcfreq != dstfreq) {
4139		track->freq.dst = last_dst;
4140
4141		memset(track->freq_prev, 0, sizeof(track->freq_prev));
4142		memset(track->freq_curr, 0, sizeof(track->freq_curr));
4143
4144		/* freq_step is the ratio of src/dst when let dst 65536. */
4145		track->freq_step = (uint64_t)srcfreq * 65536 / dstfreq;
4146
4147		dst_capacity = frame_per_block(track->mixer, dstfmt);
4148		mod = (uint64_t)srcfreq * 65536 % dstfreq;
4149		track->freq_leap = (mod * dst_capacity + dstfreq / 2) / dstfreq;
4150
4151		if (track->freq_step < 65536) {
4152			track->freq.filter = audio_track_freq_up;
4153			/* In order to carry at the first time. */
4154			track->freq_current = 65536;
4155		} else {
4156			track->freq.filter = audio_track_freq_down;
4157			track->freq_current = 0;
4158		}
4159
4160		srcbuf->fmt = *dstfmt;
4161		srcbuf->fmt.sample_rate = srcfreq;
4162
4163		srcbuf->head = 0;
4164		srcbuf->used = 0;
4165		srcbuf->capacity = frame_per_block(track->mixer, &srcbuf->fmt);
4166		len = auring_bytelen(srcbuf);
4167		srcbuf->mem = audio_realloc(srcbuf->mem, len);
4168
4169		arg = &track->freq.arg;
4170		arg->srcfmt = &srcbuf->fmt;
4171		arg->dstfmt = dstfmt;/*&last_dst->fmt;*/
4172		arg->context = track;
4173
4174		*last_dstp = srcbuf;
4175		return 0;
4176	}
4177
4178	track->freq.filter = NULL;
4179	audio_free(srcbuf->mem);
4180	return error;
4181}
4182
4183/*
4184 * When playing back: (e.g. if codec and freq stage are valid)
4185 *
4186 *               write
4187 *                | uiomove
4188 *                v
4189 *  usrbuf      [...............]  byte ring buffer (mmap-able)
4190 *                | memcpy
4191 *                v
4192 *  codec.srcbuf[....]             1 block (ring) buffer   <-- stage input
4193 *       .dst ----+
4194 *                | convert
4195 *                v
4196 *  freq.srcbuf [....]             1 block (ring) buffer
4197 *      .dst  ----+
4198 *                | convert
4199 *                v
4200 *  outbuf      [...............]  NBLKOUT blocks ring buffer
4201 *
4202 *
4203 * When recording:
4204 *
4205 *  freq.srcbuf [...............]  NBLKOUT blocks ring buffer <-- stage input
4206 *      .dst  ----+
4207 *                | convert
4208 *                v
4209 *  codec.srcbuf[.....]            1 block (ring) buffer
4210 *       .dst ----+
4211 *                | convert
4212 *                v
4213 *  outbuf      [.....]            1 block (ring) buffer
4214 *                | memcpy
4215 *                v
4216 *  usrbuf      [...............]  byte ring buffer (mmap-able *)
4217 *                | uiomove
4218 *                v
4219 *               read
4220 *
4221 *    *: usrbuf for recording is also mmap-able due to symmetry with
4222 *       playback buffer, but for now mmap will never happen for recording.
4223 */
4224
4225/*
4226 * Set the userland format of this track.
4227 * usrfmt argument should be parameter verified with audio_check_params().
4228 * It will release and reallocate all internal conversion buffers.
4229 * It returns 0 if successful.  Otherwise it returns errno with clearing all
4230 * internal buffers.
4231 * It must be called without sc_intr_lock since uvm_* routines require non
4232 * intr_lock state.
4233 * It must be called with track lock held since it may release and reallocate
4234 * outbuf.
4235 */
4236static int
4237audio_track_set_format(audio_track_t *track, audio_format2_t *usrfmt)
4238{
4239	struct audio_softc *sc;
4240	u_int newbufsize;
4241	u_int oldblksize;
4242	u_int len;
4243	int error;
4244
4245	KASSERT(track);
4246	sc = track->mixer->sc;
4247
4248	/* usrbuf is the closest buffer to the userland. */
4249	track->usrbuf.fmt = *usrfmt;
4250
4251	/*
4252	 * For references, one block size (in 40msec) is:
4253	 *  320 bytes    = 204 blocks/64KB for mulaw/8kHz/1ch
4254	 *  7680 bytes   = 8 blocks/64KB for s16/48kHz/2ch
4255	 *  30720 bytes  = 90 KB/3blocks for s16/48kHz/8ch
4256	 *  61440 bytes  = 180 KB/3blocks for s16/96kHz/8ch
4257	 *  245760 bytes = 720 KB/3blocks for s32/192kHz/8ch
4258	 *
4259	 * For example,
4260	 * 1) If usrbuf_blksize = 7056 (s16/44.1k/2ch) and PAGE_SIZE = 8192,
4261	 *     newbufsize = rounddown(65536 / 7056) = 63504
4262	 *     newvsize = roundup2(63504, PAGE_SIZE) = 65536
4263	 *    Therefore it maps 8 * 8K pages and usrbuf->capacity = 63504.
4264	 *
4265	 * 2) If usrbuf_blksize = 7680 (s16/48k/2ch) and PAGE_SIZE = 4096,
4266	 *     newbufsize = rounddown(65536 / 7680) = 61440
4267	 *     newvsize = roundup2(61440, PAGE_SIZE) = 61440 (= 15 pages)
4268	 *    Therefore it maps 15 * 4K pages and usrbuf->capacity = 61440.
4269	 */
4270	oldblksize = track->usrbuf_blksize;
4271	track->usrbuf_blksize = frametobyte(&track->usrbuf.fmt,
4272	    frame_per_block(track->mixer, &track->usrbuf.fmt));
4273	track->usrbuf.head = 0;
4274	track->usrbuf.used = 0;
4275	newbufsize = MAX(track->usrbuf_blksize * AUMINNOBLK, 65536);
4276	newbufsize = rounddown(newbufsize, track->usrbuf_blksize);
4277	error = audio_realloc_usrbuf(track, newbufsize);
4278	if (error) {
4279		device_printf(sc->sc_dev, "malloc usrbuf(%d) failed\n",
4280		    newbufsize);
4281		goto error;
4282	}
4283
4284	/* Recalc water mark. */
4285	if (track->usrbuf_blksize != oldblksize) {
4286		if (audio_track_is_playback(track)) {
4287			/* Set high at 100%, low at 75%.  */
4288			track->usrbuf_usedhigh = track->usrbuf.capacity;
4289			track->usrbuf_usedlow = track->usrbuf.capacity * 3 / 4;
4290		} else {
4291			/* Set high at 100% minus 1block(?), low at 0% */
4292			track->usrbuf_usedhigh = track->usrbuf.capacity -
4293			    track->usrbuf_blksize;
4294			track->usrbuf_usedlow = 0;
4295		}
4296	}
4297
4298	/* Stage buffer */
4299	audio_ring_t *last_dst = &track->outbuf;
4300	if (audio_track_is_playback(track)) {
4301		/* On playback, initialize from the mixer side in order. */
4302		track->inputfmt = *usrfmt;
4303		track->outbuf.fmt =  track->mixer->track_fmt;
4304
4305		if ((error = audio_track_init_freq(track, &last_dst)) != 0)
4306			goto error;
4307		if ((error = audio_track_init_chmix(track, &last_dst)) != 0)
4308			goto error;
4309		if ((error = audio_track_init_chvol(track, &last_dst)) != 0)
4310			goto error;
4311		if ((error = audio_track_init_codec(track, &last_dst)) != 0)
4312			goto error;
4313	} else {
4314		/* On recording, initialize from userland side in order. */
4315		track->inputfmt = track->mixer->track_fmt;
4316		track->outbuf.fmt = *usrfmt;
4317
4318		if ((error = audio_track_init_codec(track, &last_dst)) != 0)
4319			goto error;
4320		if ((error = audio_track_init_chvol(track, &last_dst)) != 0)
4321			goto error;
4322		if ((error = audio_track_init_chmix(track, &last_dst)) != 0)
4323			goto error;
4324		if ((error = audio_track_init_freq(track, &last_dst)) != 0)
4325			goto error;
4326	}
4327#if 0
4328	/* debug */
4329	if (track->freq.filter) {
4330		audio_print_format2("freq src", &track->freq.srcbuf.fmt);
4331		audio_print_format2("freq dst", &track->freq.dst->fmt);
4332	}
4333	if (track->chmix.filter) {
4334		audio_print_format2("chmix src", &track->chmix.srcbuf.fmt);
4335		audio_print_format2("chmix dst", &track->chmix.dst->fmt);
4336	}
4337	if (track->chvol.filter) {
4338		audio_print_format2("chvol src", &track->chvol.srcbuf.fmt);
4339		audio_print_format2("chvol dst", &track->chvol.dst->fmt);
4340	}
4341	if (track->codec.filter) {
4342		audio_print_format2("codec src", &track->codec.srcbuf.fmt);
4343		audio_print_format2("codec dst", &track->codec.dst->fmt);
4344	}
4345#endif
4346
4347	/* Stage input buffer */
4348	track->input = last_dst;
4349
4350	/*
4351	 * On the recording track, make the first stage a ring buffer.
4352	 * XXX is there a better way?
4353	 */
4354	if (audio_track_is_record(track)) {
4355		track->input->capacity = NBLKOUT *
4356		    frame_per_block(track->mixer, &track->input->fmt);
4357		len = auring_bytelen(track->input);
4358		track->input->mem = audio_realloc(track->input->mem, len);
4359	}
4360
4361	/*
4362	 * Output buffer.
4363	 * On the playback track, its capacity is NBLKOUT blocks.
4364	 * On the recording track, its capacity is 1 block.
4365	 */
4366	track->outbuf.head = 0;
4367	track->outbuf.used = 0;
4368	track->outbuf.capacity = frame_per_block(track->mixer,
4369	    &track->outbuf.fmt);
4370	if (audio_track_is_playback(track))
4371		track->outbuf.capacity *= NBLKOUT;
4372	len = auring_bytelen(&track->outbuf);
4373	track->outbuf.mem = audio_realloc(track->outbuf.mem, len);
4374	if (track->outbuf.mem == NULL) {
4375		device_printf(sc->sc_dev, "malloc outbuf(%d) failed\n", len);
4376		error = ENOMEM;
4377		goto error;
4378	}
4379
4380#if defined(AUDIO_DEBUG)
4381	if (audiodebug >= 3) {
4382		struct audio_track_debugbuf m;
4383
4384		memset(&m, 0, sizeof(m));
4385		snprintf(m.outbuf, sizeof(m.outbuf), " out=%d",
4386		    track->outbuf.capacity * frametobyte(&track->outbuf.fmt,1));
4387		if (track->freq.filter)
4388			snprintf(m.freq, sizeof(m.freq), " freq=%d",
4389			    track->freq.srcbuf.capacity *
4390			    frametobyte(&track->freq.srcbuf.fmt, 1));
4391		if (track->chmix.filter)
4392			snprintf(m.chmix, sizeof(m.chmix), " chmix=%d",
4393			    track->chmix.srcbuf.capacity *
4394			    frametobyte(&track->chmix.srcbuf.fmt, 1));
4395		if (track->chvol.filter)
4396			snprintf(m.chvol, sizeof(m.chvol), " chvol=%d",
4397			    track->chvol.srcbuf.capacity *
4398			    frametobyte(&track->chvol.srcbuf.fmt, 1));
4399		if (track->codec.filter)
4400			snprintf(m.codec, sizeof(m.codec), " codec=%d",
4401			    track->codec.srcbuf.capacity *
4402			    frametobyte(&track->codec.srcbuf.fmt, 1));
4403		snprintf(m.usrbuf, sizeof(m.usrbuf),
4404		    " usr=%d", track->usrbuf.capacity);
4405
4406		if (audio_track_is_playback(track)) {
4407			TRACET(0, track, "bufsize%s%s%s%s%s%s",
4408			    m.outbuf, m.freq, m.chmix,
4409			    m.chvol, m.codec, m.usrbuf);
4410		} else {
4411			TRACET(0, track, "bufsize%s%s%s%s%s%s",
4412			    m.freq, m.chmix, m.chvol,
4413			    m.codec, m.outbuf, m.usrbuf);
4414		}
4415	}
4416#endif
4417	return 0;
4418
4419error:
4420	audio_free_usrbuf(track);
4421	audio_free(track->codec.srcbuf.mem);
4422	audio_free(track->chvol.srcbuf.mem);
4423	audio_free(track->chmix.srcbuf.mem);
4424	audio_free(track->freq.srcbuf.mem);
4425	audio_free(track->outbuf.mem);
4426	return error;
4427}
4428
4429/*
4430 * Fill silence frames (as the internal format) up to 1 block
4431 * if the ring is not empty and less than 1 block.
4432 * It returns the number of appended frames.
4433 */
4434static int
4435audio_append_silence(audio_track_t *track, audio_ring_t *ring)
4436{
4437	int fpb;
4438	int n;
4439
4440	KASSERT(track);
4441	KASSERT(audio_format2_is_internal(&ring->fmt));
4442
4443	/* XXX is n correct? */
4444	/* XXX memset uses frametobyte()? */
4445
4446	if (ring->used == 0)
4447		return 0;
4448
4449	fpb = frame_per_block(track->mixer, &ring->fmt);
4450	if (ring->used >= fpb)
4451		return 0;
4452
4453	n = (ring->capacity - ring->used) % fpb;
4454
4455	KASSERTMSG(auring_get_contig_free(ring) >= n,
4456	    "auring_get_contig_free(ring)=%d n=%d",
4457	    auring_get_contig_free(ring), n);
4458
4459	memset(auring_tailptr_aint(ring), 0,
4460	    n * ring->fmt.channels * sizeof(aint_t));
4461	auring_push(ring, n);
4462	return n;
4463}
4464
4465/*
4466 * Execute the conversion stage.
4467 * It prepares arg from this stage and executes stage->filter.
4468 * It must be called only if stage->filter is not NULL.
4469 *
4470 * For stages other than frequency conversion, the function increments
4471 * src and dst counters here.  For frequency conversion stage, on the
4472 * other hand, the function does not touch src and dst counters and
4473 * filter side has to increment them.
4474 */
4475static void
4476audio_apply_stage(audio_track_t *track, audio_stage_t *stage, bool isfreq)
4477{
4478	audio_filter_arg_t *arg;
4479	int srccount;
4480	int dstcount;
4481	int count;
4482
4483	KASSERT(track);
4484	KASSERT(stage->filter);
4485
4486	srccount = auring_get_contig_used(&stage->srcbuf);
4487	dstcount = auring_get_contig_free(stage->dst);
4488
4489	if (isfreq) {
4490		KASSERTMSG(srccount > 0, "freq but srccount=%d", srccount);
4491		count = uimin(dstcount, track->mixer->frames_per_block);
4492	} else {
4493		count = uimin(srccount, dstcount);
4494	}
4495
4496	if (count > 0) {
4497		arg = &stage->arg;
4498		arg->src = auring_headptr(&stage->srcbuf);
4499		arg->dst = auring_tailptr(stage->dst);
4500		arg->count = count;
4501
4502		stage->filter(arg);
4503
4504		if (!isfreq) {
4505			auring_take(&stage->srcbuf, count);
4506			auring_push(stage->dst, count);
4507		}
4508	}
4509}
4510
4511/*
4512 * Produce output buffer for playback from user input buffer.
4513 * It must be called only if usrbuf is not empty and outbuf is
4514 * available at least one free block.
4515 */
4516static void
4517audio_track_play(audio_track_t *track)
4518{
4519	audio_ring_t *usrbuf;
4520	audio_ring_t *input;
4521	int count;
4522	int framesize;
4523	int bytes;
4524
4525	KASSERT(track);
4526	KASSERT(track->lock);
4527	TRACET(4, track, "start pstate=%d", track->pstate);
4528
4529	/* At this point usrbuf must not be empty. */
4530	KASSERT(track->usrbuf.used > 0);
4531	/* Also, outbuf must be available at least one block. */
4532	count = auring_get_contig_free(&track->outbuf);
4533	KASSERTMSG(count >= frame_per_block(track->mixer, &track->outbuf.fmt),
4534	    "count=%d fpb=%d",
4535	    count, frame_per_block(track->mixer, &track->outbuf.fmt));
4536
4537	/* XXX TODO: is this necessary for now? */
4538	int track_count_0 = track->outbuf.used;
4539
4540	usrbuf = &track->usrbuf;
4541	input = track->input;
4542
4543	/*
4544	 * framesize is always 1 byte or more since all formats supported as
4545	 * usrfmt(=input) have 8bit or more stride.
4546	 */
4547	framesize = frametobyte(&input->fmt, 1);
4548	KASSERT(framesize >= 1);
4549
4550	/* The next stage of usrbuf (=input) must be available. */
4551	KASSERT(auring_get_contig_free(input) > 0);
4552
4553	/*
4554	 * Copy usrbuf up to 1block to input buffer.
4555	 * count is the number of frames to copy from usrbuf.
4556	 * bytes is the number of bytes to copy from usrbuf.  However it is
4557	 * not copied less than one frame.
4558	 */
4559	count = uimin(usrbuf->used, track->usrbuf_blksize) / framesize;
4560	bytes = count * framesize;
4561
4562	track->usrbuf_stamp += bytes;
4563
4564	if (usrbuf->head + bytes < usrbuf->capacity) {
4565		memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
4566		    (uint8_t *)usrbuf->mem + usrbuf->head,
4567		    bytes);
4568		auring_push(input, count);
4569		auring_take(usrbuf, bytes);
4570	} else {
4571		int bytes1;
4572		int bytes2;
4573
4574		bytes1 = auring_get_contig_used(usrbuf);
4575		KASSERTMSG(bytes1 % framesize == 0,
4576		    "bytes1=%d framesize=%d", bytes1, framesize);
4577		memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
4578		    (uint8_t *)usrbuf->mem + usrbuf->head,
4579		    bytes1);
4580		auring_push(input, bytes1 / framesize);
4581		auring_take(usrbuf, bytes1);
4582
4583		bytes2 = bytes - bytes1;
4584		memcpy((uint8_t *)input->mem + auring_tail(input) * framesize,
4585		    (uint8_t *)usrbuf->mem + usrbuf->head,
4586		    bytes2);
4587		auring_push(input, bytes2 / framesize);
4588		auring_take(usrbuf, bytes2);
4589	}
4590
4591	/* Encoding conversion */
4592	if (track->codec.filter)
4593		audio_apply_stage(track, &track->codec, false);
4594
4595	/* Channel volume */
4596	if (track->chvol.filter)
4597		audio_apply_stage(track, &track->chvol, false);
4598
4599	/* Channel mix */
4600	if (track->chmix.filter)
4601		audio_apply_stage(track, &track->chmix, false);
4602
4603	/* Frequency conversion */
4604	/*
4605	 * Since the frequency conversion needs correction for each block,
4606	 * it rounds up to 1 block.
4607	 */
4608	if (track->freq.filter) {
4609		int n;
4610		n = audio_append_silence(track, &track->freq.srcbuf);
4611		if (n > 0) {
4612			TRACET(4, track,
4613			    "freq.srcbuf add silence %d -> %d/%d/%d",
4614			    n,
4615			    track->freq.srcbuf.head,
4616			    track->freq.srcbuf.used,
4617			    track->freq.srcbuf.capacity);
4618		}
4619		if (track->freq.srcbuf.used > 0) {
4620			audio_apply_stage(track, &track->freq, true);
4621		}
4622	}
4623
4624	if (bytes < track->usrbuf_blksize) {
4625		/*
4626		 * Clear all conversion buffer pointer if the conversion was
4627		 * not exactly one block.  These conversion stage buffers are
4628		 * certainly circular buffers because of symmetry with the
4629		 * previous and next stage buffer.  However, since they are
4630		 * treated as simple contiguous buffers in operation, so head
4631		 * always should point 0.  This may happen during drain-age.
4632		 */
4633		TRACET(4, track, "reset stage");
4634		if (track->codec.filter) {
4635			KASSERT(track->codec.srcbuf.used == 0);
4636			track->codec.srcbuf.head = 0;
4637		}
4638		if (track->chvol.filter) {
4639			KASSERT(track->chvol.srcbuf.used == 0);
4640			track->chvol.srcbuf.head = 0;
4641		}
4642		if (track->chmix.filter) {
4643			KASSERT(track->chmix.srcbuf.used == 0);
4644			track->chmix.srcbuf.head = 0;
4645		}
4646		if (track->freq.filter) {
4647			KASSERT(track->freq.srcbuf.used == 0);
4648			track->freq.srcbuf.head = 0;
4649		}
4650	}
4651
4652	if (track->input == &track->outbuf) {
4653		track->outputcounter = track->inputcounter;
4654	} else {
4655		track->outputcounter += track->outbuf.used - track_count_0;
4656	}
4657
4658#if defined(AUDIO_DEBUG)
4659	if (audiodebug >= 3) {
4660		struct audio_track_debugbuf m;
4661		audio_track_bufstat(track, &m);
4662		TRACET(0, track, "end%s%s%s%s%s%s",
4663		    m.outbuf, m.freq, m.chvol, m.chmix, m.codec, m.usrbuf);
4664	}
4665#endif
4666}
4667
4668/*
4669 * Produce user output buffer for recording from input buffer.
4670 */
4671static void
4672audio_track_record(audio_track_t *track)
4673{
4674	audio_ring_t *outbuf;
4675	audio_ring_t *usrbuf;
4676	int count;
4677	int bytes;
4678	int framesize;
4679
4680	KASSERT(track);
4681	KASSERT(track->lock);
4682
4683	/* Number of frames to process */
4684	count = auring_get_contig_used(track->input);
4685	count = uimin(count, track->mixer->frames_per_block);
4686	if (count == 0) {
4687		TRACET(4, track, "count == 0");
4688		return;
4689	}
4690
4691	/* Frequency conversion */
4692	if (track->freq.filter) {
4693		if (track->freq.srcbuf.used > 0) {
4694			audio_apply_stage(track, &track->freq, true);
4695			/* XXX should input of freq be from beginning of buf? */
4696		}
4697	}
4698
4699	/* Channel mix */
4700	if (track->chmix.filter)
4701		audio_apply_stage(track, &track->chmix, false);
4702
4703	/* Channel volume */
4704	if (track->chvol.filter)
4705		audio_apply_stage(track, &track->chvol, false);
4706
4707	/* Encoding conversion */
4708	if (track->codec.filter)
4709		audio_apply_stage(track, &track->codec, false);
4710
4711	/* Copy outbuf to usrbuf */
4712	outbuf = &track->outbuf;
4713	usrbuf = &track->usrbuf;
4714	/*
4715	 * framesize is always 1 byte or more since all formats supported
4716	 * as usrfmt(=output) have 8bit or more stride.
4717	 */
4718	framesize = frametobyte(&outbuf->fmt, 1);
4719	KASSERT(framesize >= 1);
4720	/*
4721	 * count is the number of frames to copy to usrbuf.
4722	 * bytes is the number of bytes to copy to usrbuf.
4723	 */
4724	count = outbuf->used;
4725	count = uimin(count,
4726	    (track->usrbuf_usedhigh - usrbuf->used) / framesize);
4727	bytes = count * framesize;
4728	if (auring_tail(usrbuf) + bytes < usrbuf->capacity) {
4729		memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
4730		    (uint8_t *)outbuf->mem + outbuf->head * framesize,
4731		    bytes);
4732		auring_push(usrbuf, bytes);
4733		auring_take(outbuf, count);
4734	} else {
4735		int bytes1;
4736		int bytes2;
4737
4738		bytes1 = auring_get_contig_free(usrbuf);
4739		KASSERTMSG(bytes1 % framesize == 0,
4740		    "bytes1=%d framesize=%d", bytes1, framesize);
4741		memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
4742		    (uint8_t *)outbuf->mem + outbuf->head * framesize,
4743		    bytes1);
4744		auring_push(usrbuf, bytes1);
4745		auring_take(outbuf, bytes1 / framesize);
4746
4747		bytes2 = bytes - bytes1;
4748		memcpy((uint8_t *)usrbuf->mem + auring_tail(usrbuf),
4749		    (uint8_t *)outbuf->mem + outbuf->head * framesize,
4750		    bytes2);
4751		auring_push(usrbuf, bytes2);
4752		auring_take(outbuf, bytes2 / framesize);
4753	}
4754
4755	/* XXX TODO: any counters here? */
4756
4757#if defined(AUDIO_DEBUG)
4758	if (audiodebug >= 3) {
4759		struct audio_track_debugbuf m;
4760		audio_track_bufstat(track, &m);
4761		TRACET(0, track, "end%s%s%s%s%s%s",
4762		    m.freq, m.chvol, m.chmix, m.codec, m.outbuf, m.usrbuf);
4763	}
4764#endif
4765}
4766
4767/*
4768 * Calcurate blktime [msec] from mixer(.hwbuf.fmt).
4769 * Must be called with sc_exlock held.
4770 */
4771static u_int
4772audio_mixer_calc_blktime(struct audio_softc *sc, audio_trackmixer_t *mixer)
4773{
4774	audio_format2_t *fmt;
4775	u_int blktime;
4776	u_int frames_per_block;
4777
4778	KASSERT(sc->sc_exlock);
4779
4780	fmt = &mixer->hwbuf.fmt;
4781	blktime = sc->sc_blk_ms;
4782
4783	/*
4784	 * If stride is not multiples of 8, special treatment is necessary.
4785	 * For now, it is only x68k's vs(4), 4 bit/sample ADPCM.
4786	 */
4787	if (fmt->stride == 4) {
4788		frames_per_block = fmt->sample_rate * blktime / 1000;
4789		if ((frames_per_block & 1) != 0)
4790			blktime *= 2;
4791	}
4792#ifdef DIAGNOSTIC
4793	else if (fmt->stride % NBBY != 0) {
4794		panic("unsupported HW stride %d", fmt->stride);
4795	}
4796#endif
4797
4798	return blktime;
4799}
4800
4801/*
4802 * Initialize the mixer corresponding to the mode.
4803 * Set AUMODE_PLAY to the 'mode' for playback or AUMODE_RECORD for recording.
4804 * sc->sc_[pr]mixer (corresponding to the 'mode') must be zero-filled.
4805 * This function returns 0 on successful.  Otherwise returns errno.
4806 * Must be called with sc_exlock held and without sc_lock held.
4807 */
4808static int
4809audio_mixer_init(struct audio_softc *sc, int mode,
4810	const audio_format2_t *hwfmt, const audio_filter_reg_t *reg)
4811{
4812	char codecbuf[64];
4813	char blkdmsbuf[8];
4814	audio_trackmixer_t *mixer;
4815	void (*softint_handler)(void *);
4816	int len;
4817	int blksize;
4818	int capacity;
4819	size_t bufsize;
4820	int hwblks;
4821	int blkms;
4822	int blkdms;
4823	int error;
4824
4825	KASSERT(hwfmt != NULL);
4826	KASSERT(reg != NULL);
4827	KASSERT(sc->sc_exlock);
4828
4829	error = 0;
4830	if (mode == AUMODE_PLAY)
4831		mixer = sc->sc_pmixer;
4832	else
4833		mixer = sc->sc_rmixer;
4834
4835	mixer->sc = sc;
4836	mixer->mode = mode;
4837
4838	mixer->hwbuf.fmt = *hwfmt;
4839	mixer->volume = 256;
4840	mixer->blktime_d = 1000;
4841	mixer->blktime_n = audio_mixer_calc_blktime(sc, mixer);
4842	sc->sc_blk_ms = mixer->blktime_n;
4843	hwblks = NBLKHW;
4844
4845	mixer->frames_per_block = frame_per_block(mixer, &mixer->hwbuf.fmt);
4846	blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
4847	if (sc->hw_if->round_blocksize) {
4848		int rounded;
4849		audio_params_t p = format2_to_params(&mixer->hwbuf.fmt);
4850		mutex_enter(sc->sc_lock);
4851		rounded = sc->hw_if->round_blocksize(sc->hw_hdl, blksize,
4852		    mode, &p);
4853		mutex_exit(sc->sc_lock);
4854		TRACE(1, "round_blocksize %d -> %d", blksize, rounded);
4855		if (rounded != blksize) {
4856			if ((rounded * NBBY) % (mixer->hwbuf.fmt.stride *
4857			    mixer->hwbuf.fmt.channels) != 0) {
4858				device_printf(sc->sc_dev,
4859				    "round_blocksize must return blocksize "
4860				    "divisible by framesize: "
4861				    "blksize=%d rounded=%d "
4862				    "stride=%ubit channels=%u\n",
4863				    blksize, rounded,
4864				    mixer->hwbuf.fmt.stride,
4865				    mixer->hwbuf.fmt.channels);
4866				return EINVAL;
4867			}
4868			/* Recalculation */
4869			blksize = rounded;
4870			mixer->frames_per_block = blksize * NBBY /
4871			    (mixer->hwbuf.fmt.stride *
4872			     mixer->hwbuf.fmt.channels);
4873		}
4874	}
4875	mixer->blktime_n = mixer->frames_per_block;
4876	mixer->blktime_d = mixer->hwbuf.fmt.sample_rate;
4877
4878	capacity = mixer->frames_per_block * hwblks;
4879	bufsize = frametobyte(&mixer->hwbuf.fmt, capacity);
4880	if (sc->hw_if->round_buffersize) {
4881		size_t rounded;
4882		mutex_enter(sc->sc_lock);
4883		rounded = sc->hw_if->round_buffersize(sc->hw_hdl, mode,
4884		    bufsize);
4885		mutex_exit(sc->sc_lock);
4886		TRACE(1, "round_buffersize %zd -> %zd", bufsize, rounded);
4887		if (rounded < bufsize) {
4888			/* buffersize needs NBLKHW blocks at least. */
4889			device_printf(sc->sc_dev,
4890			    "buffersize too small: buffersize=%zd blksize=%d\n",
4891			    rounded, blksize);
4892			return EINVAL;
4893		}
4894		if (rounded % blksize != 0) {
4895			/* buffersize/blksize constraint mismatch? */
4896			device_printf(sc->sc_dev,
4897			    "buffersize must be multiple of blksize: "
4898			    "buffersize=%zu blksize=%d\n",
4899			    rounded, blksize);
4900			return EINVAL;
4901		}
4902		if (rounded != bufsize) {
4903			/* Recalcuration */
4904			bufsize = rounded;
4905			hwblks = bufsize / blksize;
4906			capacity = mixer->frames_per_block * hwblks;
4907		}
4908	}
4909	TRACE(1, "buffersize for %s = %zu",
4910	    (mode == AUMODE_PLAY) ? "playback" : "recording",
4911	    bufsize);
4912	mixer->hwbuf.capacity = capacity;
4913
4914	if (sc->hw_if->allocm) {
4915		/* sc_lock is not necessary for allocm */
4916		mixer->hwbuf.mem = sc->hw_if->allocm(sc->hw_hdl, mode, bufsize);
4917		if (mixer->hwbuf.mem == NULL) {
4918			device_printf(sc->sc_dev, "%s: allocm(%zu) failed\n",
4919			    __func__, bufsize);
4920			return ENOMEM;
4921		}
4922	} else {
4923		mixer->hwbuf.mem = kmem_alloc(bufsize, KM_SLEEP);
4924	}
4925
4926	/* From here, audio_mixer_destroy is necessary to exit. */
4927	if (mode == AUMODE_PLAY) {
4928		cv_init(&mixer->outcv, "audiowr");
4929	} else {
4930		cv_init(&mixer->outcv, "audiord");
4931	}
4932
4933	if (mode == AUMODE_PLAY) {
4934		softint_handler = audio_softintr_wr;
4935	} else {
4936		softint_handler = audio_softintr_rd;
4937	}
4938	mixer->sih = softint_establish(SOFTINT_SERIAL | SOFTINT_MPSAFE,
4939	    softint_handler, sc);
4940	if (mixer->sih == NULL) {
4941		device_printf(sc->sc_dev, "softint_establish failed\n");
4942		goto abort;
4943	}
4944
4945	mixer->track_fmt.encoding = AUDIO_ENCODING_SLINEAR_NE;
4946	mixer->track_fmt.precision = AUDIO_INTERNAL_BITS;
4947	mixer->track_fmt.stride = AUDIO_INTERNAL_BITS;
4948	mixer->track_fmt.channels = mixer->hwbuf.fmt.channels;
4949	mixer->track_fmt.sample_rate = mixer->hwbuf.fmt.sample_rate;
4950
4951	if (mixer->hwbuf.fmt.encoding == AUDIO_ENCODING_SLINEAR_OE &&
4952	    mixer->hwbuf.fmt.precision == AUDIO_INTERNAL_BITS) {
4953		mixer->swap_endian = true;
4954		TRACE(1, "swap_endian");
4955	}
4956
4957	if (mode == AUMODE_PLAY) {
4958		/* Mixing buffer */
4959		mixer->mixfmt = mixer->track_fmt;
4960		mixer->mixfmt.precision *= 2;
4961		mixer->mixfmt.stride *= 2;
4962		/* XXX TODO: use some macros? */
4963		len = mixer->frames_per_block * mixer->mixfmt.channels *
4964		    mixer->mixfmt.stride / NBBY;
4965		mixer->mixsample = audio_realloc(mixer->mixsample, len);
4966	} else {
4967		/* No mixing buffer for recording */
4968	}
4969
4970	if (reg->codec) {
4971		mixer->codec = reg->codec;
4972		mixer->codecarg.context = reg->context;
4973		if (mode == AUMODE_PLAY) {
4974			mixer->codecarg.srcfmt = &mixer->track_fmt;
4975			mixer->codecarg.dstfmt = &mixer->hwbuf.fmt;
4976		} else {
4977			mixer->codecarg.srcfmt = &mixer->hwbuf.fmt;
4978			mixer->codecarg.dstfmt = &mixer->track_fmt;
4979		}
4980		mixer->codecbuf.fmt = mixer->track_fmt;
4981		mixer->codecbuf.capacity = mixer->frames_per_block;
4982		len = auring_bytelen(&mixer->codecbuf);
4983		mixer->codecbuf.mem = audio_realloc(mixer->codecbuf.mem, len);
4984		if (mixer->codecbuf.mem == NULL) {
4985			device_printf(sc->sc_dev,
4986			    "%s: malloc codecbuf(%d) failed\n",
4987			    __func__, len);
4988			error = ENOMEM;
4989			goto abort;
4990		}
4991	}
4992
4993	/* Succeeded so display it. */
4994	codecbuf[0] = '\0';
4995	if (mixer->codec || mixer->swap_endian) {
4996		snprintf(codecbuf, sizeof(codecbuf), " %s %s:%d",
4997		    (mode == AUMODE_PLAY) ? "->" : "<-",
4998		    audio_encoding_name(mixer->hwbuf.fmt.encoding),
4999		    mixer->hwbuf.fmt.precision);
5000	}
5001	blkms = mixer->blktime_n * 1000 / mixer->blktime_d;
5002	blkdms = (mixer->blktime_n * 10000 / mixer->blktime_d) % 10;
5003	blkdmsbuf[0] = '\0';
5004	if (blkdms != 0) {
5005		snprintf(blkdmsbuf, sizeof(blkdmsbuf), ".%1d", blkdms);
5006	}
5007	aprint_normal_dev(sc->sc_dev,
5008	    "%s:%d%s %dch %dHz, blk %d bytes (%d%sms) for %s\n",
5009	    audio_encoding_name(mixer->track_fmt.encoding),
5010	    mixer->track_fmt.precision,
5011	    codecbuf,
5012	    mixer->track_fmt.channels,
5013	    mixer->track_fmt.sample_rate,
5014	    blksize,
5015	    blkms, blkdmsbuf,
5016	    (mode == AUMODE_PLAY) ? "playback" : "recording");
5017
5018	return 0;
5019
5020abort:
5021	audio_mixer_destroy(sc, mixer);
5022	return error;
5023}
5024
5025/*
5026 * Releases all resources of 'mixer'.
5027 * Note that it does not release the memory area of 'mixer' itself.
5028 * Must be called with sc_exlock held and without sc_lock held.
5029 */
5030static void
5031audio_mixer_destroy(struct audio_softc *sc, audio_trackmixer_t *mixer)
5032{
5033	int bufsize;
5034
5035	KASSERT(sc->sc_exlock == 1);
5036
5037	bufsize = frametobyte(&mixer->hwbuf.fmt, mixer->hwbuf.capacity);
5038
5039	if (mixer->hwbuf.mem != NULL) {
5040		if (sc->hw_if->freem) {
5041			/* sc_lock is not necessary for freem */
5042			sc->hw_if->freem(sc->hw_hdl, mixer->hwbuf.mem, bufsize);
5043		} else {
5044			kmem_free(mixer->hwbuf.mem, bufsize);
5045		}
5046		mixer->hwbuf.mem = NULL;
5047	}
5048
5049	audio_free(mixer->codecbuf.mem);
5050	audio_free(mixer->mixsample);
5051
5052	cv_destroy(&mixer->outcv);
5053
5054	if (mixer->sih) {
5055		softint_disestablish(mixer->sih);
5056		mixer->sih = NULL;
5057	}
5058}
5059
5060/*
5061 * Starts playback mixer.
5062 * Must be called only if sc_pbusy is false.
5063 * Must be called with sc_lock && sc_exlock held.
5064 * Must not be called from the interrupt context.
5065 */
5066static void
5067audio_pmixer_start(struct audio_softc *sc, bool force)
5068{
5069	audio_trackmixer_t *mixer;
5070	int minimum;
5071
5072	KASSERT(mutex_owned(sc->sc_lock));
5073	KASSERT(sc->sc_exlock);
5074	KASSERT(sc->sc_pbusy == false);
5075
5076	mutex_enter(sc->sc_intr_lock);
5077
5078	mixer = sc->sc_pmixer;
5079	TRACE(2, "%smixseq=%d hwseq=%d hwbuf=%d/%d/%d%s",
5080	    (audiodebug >= 3) ? "begin " : "",
5081	    (int)mixer->mixseq, (int)mixer->hwseq,
5082	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity,
5083	    force ? " force" : "");
5084
5085	/* Need two blocks to start normally. */
5086	minimum = (force) ? 1 : 2;
5087	while (mixer->hwbuf.used < mixer->frames_per_block * minimum) {
5088		audio_pmixer_process(sc);
5089	}
5090
5091	/* Start output */
5092	audio_pmixer_output(sc);
5093	sc->sc_pbusy = true;
5094
5095	TRACE(3, "end   mixseq=%d hwseq=%d hwbuf=%d/%d/%d",
5096	    (int)mixer->mixseq, (int)mixer->hwseq,
5097	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
5098
5099	mutex_exit(sc->sc_intr_lock);
5100}
5101
5102/*
5103 * When playing back with MD filter:
5104 *
5105 *           track track ...
5106 *               v v
5107 *                +  mix (with aint2_t)
5108 *                |  master volume (with aint2_t)
5109 *                v
5110 *    mixsample [::::]                  wide-int 1 block (ring) buffer
5111 *                |
5112 *                |  convert aint2_t -> aint_t
5113 *                v
5114 *    codecbuf  [....]                  1 block (ring) buffer
5115 *                |
5116 *                |  convert to hw format
5117 *                v
5118 *    hwbuf     [............]          NBLKHW blocks ring buffer
5119 *
5120 * When playing back without MD filter:
5121 *
5122 *    mixsample [::::]                  wide-int 1 block (ring) buffer
5123 *                |
5124 *                |  convert aint2_t -> aint_t
5125 *                |  (with byte swap if necessary)
5126 *                v
5127 *    hwbuf     [............]          NBLKHW blocks ring buffer
5128 *
5129 * mixsample: slinear_NE, wide internal precision, HW ch, HW freq.
5130 * codecbuf:  slinear_NE, internal precision,      HW ch, HW freq.
5131 * hwbuf:     HW encoding, HW precision,           HW ch, HW freq.
5132 */
5133
5134/*
5135 * Performs track mixing and converts it to hwbuf.
5136 * Note that this function doesn't transfer hwbuf to hardware.
5137 * Must be called with sc_intr_lock held.
5138 */
5139static void
5140audio_pmixer_process(struct audio_softc *sc)
5141{
5142	audio_trackmixer_t *mixer;
5143	audio_file_t *f;
5144	int frame_count;
5145	int sample_count;
5146	int mixed;
5147	int i;
5148	aint2_t *m;
5149	aint_t *h;
5150
5151	mixer = sc->sc_pmixer;
5152
5153	frame_count = mixer->frames_per_block;
5154	KASSERTMSG(auring_get_contig_free(&mixer->hwbuf) >= frame_count,
5155	    "auring_get_contig_free()=%d frame_count=%d",
5156	    auring_get_contig_free(&mixer->hwbuf), frame_count);
5157	sample_count = frame_count * mixer->mixfmt.channels;
5158
5159	mixer->mixseq++;
5160
5161	/* Mix all tracks */
5162	mixed = 0;
5163	SLIST_FOREACH(f, &sc->sc_files, entry) {
5164		audio_track_t *track = f->ptrack;
5165
5166		if (track == NULL)
5167			continue;
5168
5169		if (track->is_pause) {
5170			TRACET(4, track, "skip; paused");
5171			continue;
5172		}
5173
5174		/* Skip if the track is used by process context. */
5175		if (audio_track_lock_tryenter(track) == false) {
5176			TRACET(4, track, "skip; in use");
5177			continue;
5178		}
5179
5180		/* Emulate mmap'ped track */
5181		if (track->mmapped) {
5182			auring_push(&track->usrbuf, track->usrbuf_blksize);
5183			TRACET(4, track, "mmap; usr=%d/%d/C%d",
5184			    track->usrbuf.head,
5185			    track->usrbuf.used,
5186			    track->usrbuf.capacity);
5187		}
5188
5189		if (track->outbuf.used < mixer->frames_per_block &&
5190		    track->usrbuf.used > 0) {
5191			TRACET(4, track, "process");
5192			audio_track_play(track);
5193		}
5194
5195		if (track->outbuf.used > 0) {
5196			mixed = audio_pmixer_mix_track(mixer, track, mixed);
5197		} else {
5198			TRACET(4, track, "skip; empty");
5199		}
5200
5201		audio_track_lock_exit(track);
5202	}
5203
5204	if (mixed == 0) {
5205		/* Silence */
5206		memset(mixer->mixsample, 0,
5207		    frametobyte(&mixer->mixfmt, frame_count));
5208	} else {
5209		if (mixed > 1) {
5210			/* If there are multiple tracks, do auto gain control */
5211			audio_pmixer_agc(mixer, sample_count);
5212		}
5213
5214		/* Apply master volume */
5215		if (mixer->volume < 256) {
5216			m = mixer->mixsample;
5217			for (i = 0; i < sample_count; i++) {
5218				*m = AUDIO_SCALEDOWN(*m * mixer->volume, 8);
5219				m++;
5220			}
5221
5222			/*
5223			 * Recover the volume gradually at the pace of
5224			 * several times per second.  If it's too fast, you
5225			 * can recognize that the volume changes up and down
5226			 * quickly and it's not so comfortable.
5227			 */
5228			mixer->voltimer += mixer->blktime_n;
5229			if (mixer->voltimer * 4 >= mixer->blktime_d) {
5230				mixer->volume++;
5231				mixer->voltimer = 0;
5232#if defined(AUDIO_DEBUG_AGC)
5233				TRACE(1, "volume recover: %d", mixer->volume);
5234#endif
5235			}
5236		}
5237	}
5238
5239	/*
5240	 * The rest is the hardware part.
5241	 */
5242
5243	if (mixer->codec) {
5244		h = auring_tailptr_aint(&mixer->codecbuf);
5245	} else {
5246		h = auring_tailptr_aint(&mixer->hwbuf);
5247	}
5248
5249	m = mixer->mixsample;
5250	if (mixer->swap_endian) {
5251		for (i = 0; i < sample_count; i++) {
5252			*h++ = bswap16(*m++);
5253		}
5254	} else {
5255		for (i = 0; i < sample_count; i++) {
5256			*h++ = *m++;
5257		}
5258	}
5259
5260	/* Hardware driver's codec */
5261	if (mixer->codec) {
5262		auring_push(&mixer->codecbuf, frame_count);
5263		mixer->codecarg.src = auring_headptr(&mixer->codecbuf);
5264		mixer->codecarg.dst = auring_tailptr(&mixer->hwbuf);
5265		mixer->codecarg.count = frame_count;
5266		mixer->codec(&mixer->codecarg);
5267		auring_take(&mixer->codecbuf, mixer->codecarg.count);
5268	}
5269
5270	auring_push(&mixer->hwbuf, frame_count);
5271
5272	TRACE(4, "done mixseq=%d hwbuf=%d/%d/%d%s",
5273	    (int)mixer->mixseq,
5274	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity,
5275	    (mixed == 0) ? " silent" : "");
5276}
5277
5278/*
5279 * Do auto gain control.
5280 * Must be called sc_intr_lock held.
5281 */
5282static void
5283audio_pmixer_agc(audio_trackmixer_t *mixer, int sample_count)
5284{
5285	struct audio_softc *sc __unused;
5286	aint2_t val;
5287	aint2_t maxval;
5288	aint2_t minval;
5289	aint2_t over_plus;
5290	aint2_t over_minus;
5291	aint2_t *m;
5292	int newvol;
5293	int i;
5294
5295	sc = mixer->sc;
5296
5297	/* Overflow detection */
5298	maxval = AINT_T_MAX;
5299	minval = AINT_T_MIN;
5300	m = mixer->mixsample;
5301	for (i = 0; i < sample_count; i++) {
5302		val = *m++;
5303		if (val > maxval)
5304			maxval = val;
5305		else if (val < minval)
5306			minval = val;
5307	}
5308
5309	/* Absolute value of overflowed amount */
5310	over_plus = maxval - AINT_T_MAX;
5311	over_minus = AINT_T_MIN - minval;
5312
5313	if (over_plus > 0 || over_minus > 0) {
5314		if (over_plus > over_minus) {
5315			newvol = (int)((aint2_t)AINT_T_MAX * 256 / maxval);
5316		} else {
5317			newvol = (int)((aint2_t)AINT_T_MIN * 256 / minval);
5318		}
5319
5320		/*
5321		 * Change the volume only if new one is smaller.
5322		 * Reset the timer even if the volume isn't changed.
5323		 */
5324		if (newvol <= mixer->volume) {
5325			mixer->volume = newvol;
5326			mixer->voltimer = 0;
5327#if defined(AUDIO_DEBUG_AGC)
5328			TRACE(1, "auto volume adjust: %d", mixer->volume);
5329#endif
5330		}
5331	}
5332}
5333
5334/*
5335 * Mix one track.
5336 * 'mixed' specifies the number of tracks mixed so far.
5337 * It returns the number of tracks mixed.  In other words, it returns
5338 * mixed + 1 if this track is mixed.
5339 */
5340static int
5341audio_pmixer_mix_track(audio_trackmixer_t *mixer, audio_track_t *track,
5342	int mixed)
5343{
5344	int count;
5345	int sample_count;
5346	int remain;
5347	int i;
5348	const aint_t *s;
5349	aint2_t *d;
5350
5351	/* XXX TODO: Is this necessary for now? */
5352	if (mixer->mixseq < track->seq)
5353		return mixed;
5354
5355	count = auring_get_contig_used(&track->outbuf);
5356	count = uimin(count, mixer->frames_per_block);
5357
5358	s = auring_headptr_aint(&track->outbuf);
5359	d = mixer->mixsample;
5360
5361	/*
5362	 * Apply track volume with double-sized integer and perform
5363	 * additive synthesis.
5364	 *
5365	 * XXX If you limit the track volume to 1.0 or less (<= 256),
5366	 *     it would be better to do this in the track conversion stage
5367	 *     rather than here.  However, if you accept the volume to
5368	 *     be greater than 1.0 (> 256), it's better to do it here.
5369	 *     Because the operation here is done by double-sized integer.
5370	 */
5371	sample_count = count * mixer->mixfmt.channels;
5372	if (mixed == 0) {
5373		/* If this is the first track, assignment can be used. */
5374#if defined(AUDIO_SUPPORT_TRACK_VOLUME)
5375		if (track->volume != 256) {
5376			for (i = 0; i < sample_count; i++) {
5377				aint2_t v;
5378				v = *s++;
5379				*d++ = AUDIO_SCALEDOWN(v * track->volume, 8)
5380			}
5381		} else
5382#endif
5383		{
5384			for (i = 0; i < sample_count; i++) {
5385				*d++ = ((aint2_t)*s++);
5386			}
5387		}
5388		/* Fill silence if the first track is not filled. */
5389		for (; i < mixer->frames_per_block * mixer->mixfmt.channels; i++)
5390			*d++ = 0;
5391	} else {
5392		/* If this is the second or later, add it. */
5393#if defined(AUDIO_SUPPORT_TRACK_VOLUME)
5394		if (track->volume != 256) {
5395			for (i = 0; i < sample_count; i++) {
5396				aint2_t v;
5397				v = *s++;
5398				*d++ += AUDIO_SCALEDOWN(v * track->volume, 8);
5399			}
5400		} else
5401#endif
5402		{
5403			for (i = 0; i < sample_count; i++) {
5404				*d++ += ((aint2_t)*s++);
5405			}
5406		}
5407	}
5408
5409	auring_take(&track->outbuf, count);
5410	/*
5411	 * The counters have to align block even if outbuf is less than
5412	 * one block. XXX Is this still necessary?
5413	 */
5414	remain = mixer->frames_per_block - count;
5415	if (__predict_false(remain != 0)) {
5416		auring_push(&track->outbuf, remain);
5417		auring_take(&track->outbuf, remain);
5418	}
5419
5420	/*
5421	 * Update track sequence.
5422	 * mixseq has previous value yet at this point.
5423	 */
5424	track->seq = mixer->mixseq + 1;
5425
5426	return mixed + 1;
5427}
5428
5429/*
5430 * Output one block from hwbuf to HW.
5431 * Must be called with sc_intr_lock held.
5432 */
5433static void
5434audio_pmixer_output(struct audio_softc *sc)
5435{
5436	audio_trackmixer_t *mixer;
5437	audio_params_t params;
5438	void *start;
5439	void *end;
5440	int blksize;
5441	int error;
5442
5443	mixer = sc->sc_pmixer;
5444	TRACE(4, "pbusy=%d hwbuf=%d/%d/%d",
5445	    sc->sc_pbusy,
5446	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
5447	KASSERTMSG(mixer->hwbuf.used >= mixer->frames_per_block,
5448	    "mixer->hwbuf.used=%d mixer->frames_per_block=%d",
5449	    mixer->hwbuf.used, mixer->frames_per_block);
5450
5451	blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
5452
5453	if (sc->hw_if->trigger_output) {
5454		/* trigger (at once) */
5455		if (!sc->sc_pbusy) {
5456			start = mixer->hwbuf.mem;
5457			end = (uint8_t *)start + auring_bytelen(&mixer->hwbuf);
5458			params = format2_to_params(&mixer->hwbuf.fmt);
5459
5460			error = sc->hw_if->trigger_output(sc->hw_hdl,
5461			    start, end, blksize, audio_pintr, sc, &params);
5462			if (error) {
5463				device_printf(sc->sc_dev,
5464				    "trigger_output failed with %d\n", error);
5465				return;
5466			}
5467		}
5468	} else {
5469		/* start (everytime) */
5470		start = auring_headptr(&mixer->hwbuf);
5471
5472		error = sc->hw_if->start_output(sc->hw_hdl,
5473		    start, blksize, audio_pintr, sc);
5474		if (error) {
5475			device_printf(sc->sc_dev,
5476			    "start_output failed with %d\n", error);
5477			return;
5478		}
5479	}
5480}
5481
5482/*
5483 * This is an interrupt handler for playback.
5484 * It is called with sc_intr_lock held.
5485 *
5486 * It is usually called from hardware interrupt.  However, note that
5487 * for some drivers (e.g. uaudio) it is called from software interrupt.
5488 */
5489static void
5490audio_pintr(void *arg)
5491{
5492	struct audio_softc *sc;
5493	audio_trackmixer_t *mixer;
5494
5495	sc = arg;
5496	KASSERT(mutex_owned(sc->sc_intr_lock));
5497
5498	if (sc->sc_dying)
5499		return;
5500	if (sc->sc_pbusy == false) {
5501#if defined(DIAGNOSTIC)
5502		device_printf(sc->sc_dev,
5503		    "DIAGNOSTIC: %s raised stray interrupt\n",
5504		    device_xname(sc->hw_dev));
5505#endif
5506		return;
5507	}
5508
5509	mixer = sc->sc_pmixer;
5510	mixer->hw_complete_counter += mixer->frames_per_block;
5511	mixer->hwseq++;
5512
5513	auring_take(&mixer->hwbuf, mixer->frames_per_block);
5514
5515	TRACE(4,
5516	    "HW_INT ++hwseq=%" PRIu64 " cmplcnt=%" PRIu64 " hwbuf=%d/%d/%d",
5517	    mixer->hwseq, mixer->hw_complete_counter,
5518	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
5519
5520#if defined(AUDIO_HW_SINGLE_BUFFER)
5521	/*
5522	 * Create a new block here and output it immediately.
5523	 * It makes a latency lower but needs machine power.
5524	 */
5525	audio_pmixer_process(sc);
5526	audio_pmixer_output(sc);
5527#else
5528	/*
5529	 * It is called when block N output is done.
5530	 * Output immediately block N+1 created by the last interrupt.
5531	 * And then create block N+2 for the next interrupt.
5532	 * This method makes playback robust even on slower machines.
5533	 * Instead the latency is increased by one block.
5534	 */
5535
5536	/* At first, output ready block. */
5537	if (mixer->hwbuf.used >= mixer->frames_per_block) {
5538		audio_pmixer_output(sc);
5539	}
5540
5541	bool later = false;
5542
5543	if (mixer->hwbuf.used < mixer->frames_per_block) {
5544		later = true;
5545	}
5546
5547	/* Then, process next block. */
5548	audio_pmixer_process(sc);
5549
5550	if (later) {
5551		audio_pmixer_output(sc);
5552	}
5553#endif
5554
5555	/*
5556	 * When this interrupt is the real hardware interrupt, disabling
5557	 * preemption here is not necessary.  But some drivers (e.g. uaudio)
5558	 * emulate it by software interrupt, so kpreempt_disable is necessary.
5559	 */
5560	kpreempt_disable();
5561	softint_schedule(mixer->sih);
5562	kpreempt_enable();
5563}
5564
5565/*
5566 * Starts record mixer.
5567 * Must be called only if sc_rbusy is false.
5568 * Must be called with sc_lock && sc_exlock held.
5569 * Must not be called from the interrupt context.
5570 */
5571static void
5572audio_rmixer_start(struct audio_softc *sc)
5573{
5574
5575	KASSERT(mutex_owned(sc->sc_lock));
5576	KASSERT(sc->sc_exlock);
5577	KASSERT(sc->sc_rbusy == false);
5578
5579	mutex_enter(sc->sc_intr_lock);
5580
5581	TRACE(2, "%s", (audiodebug >= 3) ? "begin" : "");
5582	audio_rmixer_input(sc);
5583	sc->sc_rbusy = true;
5584	TRACE(3, "end");
5585
5586	mutex_exit(sc->sc_intr_lock);
5587}
5588
5589/*
5590 * When recording with MD filter:
5591 *
5592 *    hwbuf     [............]          NBLKHW blocks ring buffer
5593 *                |
5594 *                | convert from hw format
5595 *                v
5596 *    codecbuf  [....]                  1 block (ring) buffer
5597 *               |  |
5598 *               v  v
5599 *            track track ...
5600 *
5601 * When recording without MD filter:
5602 *
5603 *    hwbuf     [............]          NBLKHW blocks ring buffer
5604 *               |  |
5605 *               v  v
5606 *            track track ...
5607 *
5608 * hwbuf:     HW encoding, HW precision, HW ch, HW freq.
5609 * codecbuf:  slinear_NE, internal precision, HW ch, HW freq.
5610 */
5611
5612/*
5613 * Distribute a recorded block to all recording tracks.
5614 */
5615static void
5616audio_rmixer_process(struct audio_softc *sc)
5617{
5618	audio_trackmixer_t *mixer;
5619	audio_ring_t *mixersrc;
5620	audio_file_t *f;
5621	aint_t *p;
5622	int count;
5623	int bytes;
5624	int i;
5625
5626	mixer = sc->sc_rmixer;
5627
5628	/*
5629	 * count is the number of frames to be retrieved this time.
5630	 * count should be one block.
5631	 */
5632	count = auring_get_contig_used(&mixer->hwbuf);
5633	count = uimin(count, mixer->frames_per_block);
5634	if (count <= 0) {
5635		TRACE(4, "count %d: too short", count);
5636		return;
5637	}
5638	bytes = frametobyte(&mixer->track_fmt, count);
5639
5640	/* Hardware driver's codec */
5641	if (mixer->codec) {
5642		mixer->codecarg.src = auring_headptr(&mixer->hwbuf);
5643		mixer->codecarg.dst = auring_tailptr(&mixer->codecbuf);
5644		mixer->codecarg.count = count;
5645		mixer->codec(&mixer->codecarg);
5646		auring_take(&mixer->hwbuf, mixer->codecarg.count);
5647		auring_push(&mixer->codecbuf, mixer->codecarg.count);
5648		mixersrc = &mixer->codecbuf;
5649	} else {
5650		mixersrc = &mixer->hwbuf;
5651	}
5652
5653	if (mixer->swap_endian) {
5654		/* inplace conversion */
5655		p = auring_headptr_aint(mixersrc);
5656		for (i = 0; i < count * mixer->track_fmt.channels; i++, p++) {
5657			*p = bswap16(*p);
5658		}
5659	}
5660
5661	/* Distribute to all tracks. */
5662	SLIST_FOREACH(f, &sc->sc_files, entry) {
5663		audio_track_t *track = f->rtrack;
5664		audio_ring_t *input;
5665
5666		if (track == NULL)
5667			continue;
5668
5669		if (track->is_pause) {
5670			TRACET(4, track, "skip; paused");
5671			continue;
5672		}
5673
5674		if (audio_track_lock_tryenter(track) == false) {
5675			TRACET(4, track, "skip; in use");
5676			continue;
5677		}
5678
5679		/* If the track buffer is full, discard the oldest one? */
5680		input = track->input;
5681		if (input->capacity - input->used < mixer->frames_per_block) {
5682			int drops = mixer->frames_per_block -
5683			    (input->capacity - input->used);
5684			track->dropframes += drops;
5685			TRACET(4, track, "drop %d frames: inp=%d/%d/%d",
5686			    drops,
5687			    input->head, input->used, input->capacity);
5688			auring_take(input, drops);
5689		}
5690		KASSERTMSG(input->used % mixer->frames_per_block == 0,
5691		    "input->used=%d mixer->frames_per_block=%d",
5692		    input->used, mixer->frames_per_block);
5693
5694		memcpy(auring_tailptr_aint(input),
5695		    auring_headptr_aint(mixersrc),
5696		    bytes);
5697		auring_push(input, count);
5698
5699		/* XXX sequence counter? */
5700
5701		audio_track_lock_exit(track);
5702	}
5703
5704	auring_take(mixersrc, count);
5705}
5706
5707/*
5708 * Input one block from HW to hwbuf.
5709 * Must be called with sc_intr_lock held.
5710 */
5711static void
5712audio_rmixer_input(struct audio_softc *sc)
5713{
5714	audio_trackmixer_t *mixer;
5715	audio_params_t params;
5716	void *start;
5717	void *end;
5718	int blksize;
5719	int error;
5720
5721	mixer = sc->sc_rmixer;
5722	blksize = frametobyte(&mixer->hwbuf.fmt, mixer->frames_per_block);
5723
5724	if (sc->hw_if->trigger_input) {
5725		/* trigger (at once) */
5726		if (!sc->sc_rbusy) {
5727			start = mixer->hwbuf.mem;
5728			end = (uint8_t *)start + auring_bytelen(&mixer->hwbuf);
5729			params = format2_to_params(&mixer->hwbuf.fmt);
5730
5731			error = sc->hw_if->trigger_input(sc->hw_hdl,
5732			    start, end, blksize, audio_rintr, sc, &params);
5733			if (error) {
5734				device_printf(sc->sc_dev,
5735				    "trigger_input failed with %d\n", error);
5736				return;
5737			}
5738		}
5739	} else {
5740		/* start (everytime) */
5741		start = auring_tailptr(&mixer->hwbuf);
5742
5743		error = sc->hw_if->start_input(sc->hw_hdl,
5744		    start, blksize, audio_rintr, sc);
5745		if (error) {
5746			device_printf(sc->sc_dev,
5747			    "start_input failed with %d\n", error);
5748			return;
5749		}
5750	}
5751}
5752
5753/*
5754 * This is an interrupt handler for recording.
5755 * It is called with sc_intr_lock.
5756 *
5757 * It is usually called from hardware interrupt.  However, note that
5758 * for some drivers (e.g. uaudio) it is called from software interrupt.
5759 */
5760static void
5761audio_rintr(void *arg)
5762{
5763	struct audio_softc *sc;
5764	audio_trackmixer_t *mixer;
5765
5766	sc = arg;
5767	KASSERT(mutex_owned(sc->sc_intr_lock));
5768
5769	if (sc->sc_dying)
5770		return;
5771	if (sc->sc_rbusy == false) {
5772#if defined(DIAGNOSTIC)
5773		device_printf(sc->sc_dev,
5774		    "DIAGNOSTIC: %s raised stray interrupt\n",
5775		    device_xname(sc->hw_dev));
5776#endif
5777		return;
5778	}
5779
5780	mixer = sc->sc_rmixer;
5781	mixer->hw_complete_counter += mixer->frames_per_block;
5782	mixer->hwseq++;
5783
5784	auring_push(&mixer->hwbuf, mixer->frames_per_block);
5785
5786	TRACE(4,
5787	    "HW_INT ++hwseq=%" PRIu64 " cmplcnt=%" PRIu64 " hwbuf=%d/%d/%d",
5788	    mixer->hwseq, mixer->hw_complete_counter,
5789	    mixer->hwbuf.head, mixer->hwbuf.used, mixer->hwbuf.capacity);
5790
5791	/* Distrubute recorded block */
5792	audio_rmixer_process(sc);
5793
5794	/* Request next block */
5795	audio_rmixer_input(sc);
5796
5797	/*
5798	 * When this interrupt is the real hardware interrupt, disabling
5799	 * preemption here is not necessary.  But some drivers (e.g. uaudio)
5800	 * emulate it by software interrupt, so kpreempt_disable is necessary.
5801	 */
5802	kpreempt_disable();
5803	softint_schedule(mixer->sih);
5804	kpreempt_enable();
5805}
5806
5807/*
5808 * Halts playback mixer.
5809 * This function also clears related parameters, so call this function
5810 * instead of calling halt_output directly.
5811 * Must be called only if sc_pbusy is true.
5812 * Must be called with sc_lock && sc_exlock held.
5813 */
5814static int
5815audio_pmixer_halt(struct audio_softc *sc)
5816{
5817	int error;
5818
5819	TRACE(2, "");
5820	KASSERT(mutex_owned(sc->sc_lock));
5821	KASSERT(sc->sc_exlock);
5822
5823	mutex_enter(sc->sc_intr_lock);
5824	error = sc->hw_if->halt_output(sc->hw_hdl);
5825
5826	/* Halts anyway even if some error has occurred. */
5827	sc->sc_pbusy = false;
5828	sc->sc_pmixer->hwbuf.head = 0;
5829	sc->sc_pmixer->hwbuf.used = 0;
5830	sc->sc_pmixer->mixseq = 0;
5831	sc->sc_pmixer->hwseq = 0;
5832	mutex_exit(sc->sc_intr_lock);
5833
5834	return error;
5835}
5836
5837/*
5838 * Halts recording mixer.
5839 * This function also clears related parameters, so call this function
5840 * instead of calling halt_input directly.
5841 * Must be called only if sc_rbusy is true.
5842 * Must be called with sc_lock && sc_exlock held.
5843 */
5844static int
5845audio_rmixer_halt(struct audio_softc *sc)
5846{
5847	int error;
5848
5849	TRACE(2, "");
5850	KASSERT(mutex_owned(sc->sc_lock));
5851	KASSERT(sc->sc_exlock);
5852
5853	mutex_enter(sc->sc_intr_lock);
5854	error = sc->hw_if->halt_input(sc->hw_hdl);
5855
5856	/* Halts anyway even if some error has occurred. */
5857	sc->sc_rbusy = false;
5858	sc->sc_rmixer->hwbuf.head = 0;
5859	sc->sc_rmixer->hwbuf.used = 0;
5860	sc->sc_rmixer->mixseq = 0;
5861	sc->sc_rmixer->hwseq = 0;
5862	mutex_exit(sc->sc_intr_lock);
5863
5864	return error;
5865}
5866
5867/*
5868 * Flush this track.
5869 * Halts all operations, clears all buffers, reset error counters.
5870 * XXX I'm not sure...
5871 */
5872static void
5873audio_track_clear(struct audio_softc *sc, audio_track_t *track)
5874{
5875
5876	KASSERT(track);
5877	TRACET(3, track, "clear");
5878
5879	audio_track_lock_enter(track);
5880
5881	track->usrbuf.used = 0;
5882	/* Clear all internal parameters. */
5883	if (track->codec.filter) {
5884		track->codec.srcbuf.used = 0;
5885		track->codec.srcbuf.head = 0;
5886	}
5887	if (track->chvol.filter) {
5888		track->chvol.srcbuf.used = 0;
5889		track->chvol.srcbuf.head = 0;
5890	}
5891	if (track->chmix.filter) {
5892		track->chmix.srcbuf.used = 0;
5893		track->chmix.srcbuf.head = 0;
5894	}
5895	if (track->freq.filter) {
5896		track->freq.srcbuf.used = 0;
5897		track->freq.srcbuf.head = 0;
5898		if (track->freq_step < 65536)
5899			track->freq_current = 65536;
5900		else
5901			track->freq_current = 0;
5902		memset(track->freq_prev, 0, sizeof(track->freq_prev));
5903		memset(track->freq_curr, 0, sizeof(track->freq_curr));
5904	}
5905	/* Clear buffer, then operation halts naturally. */
5906	track->outbuf.used = 0;
5907
5908	/* Clear counters. */
5909	track->dropframes = 0;
5910
5911	audio_track_lock_exit(track);
5912}
5913
5914/*
5915 * Drain the track.
5916 * track must be present and for playback.
5917 * If successful, it returns 0.  Otherwise returns errno.
5918 * Must be called with sc_lock held.
5919 */
5920static int
5921audio_track_drain(struct audio_softc *sc, audio_track_t *track)
5922{
5923	audio_trackmixer_t *mixer;
5924	int done;
5925	int error;
5926
5927	KASSERT(track);
5928	TRACET(3, track, "start");
5929	mixer = track->mixer;
5930	KASSERT(mutex_owned(sc->sc_lock));
5931
5932	/* Ignore them if pause. */
5933	if (track->is_pause) {
5934		TRACET(3, track, "pause -> clear");
5935		track->pstate = AUDIO_STATE_CLEAR;
5936	}
5937	/* Terminate early here if there is no data in the track. */
5938	if (track->pstate == AUDIO_STATE_CLEAR) {
5939		TRACET(3, track, "no need to drain");
5940		return 0;
5941	}
5942	track->pstate = AUDIO_STATE_DRAINING;
5943
5944	for (;;) {
5945		/* I want to display it before condition evaluation. */
5946		TRACET(3, track, "pid=%d.%d trkseq=%d hwseq=%d out=%d/%d/%d",
5947		    (int)curproc->p_pid, (int)curlwp->l_lid,
5948		    (int)track->seq, (int)mixer->hwseq,
5949		    track->outbuf.head, track->outbuf.used,
5950		    track->outbuf.capacity);
5951
5952		/* Condition to terminate */
5953		audio_track_lock_enter(track);
5954		done = (track->usrbuf.used < frametobyte(&track->inputfmt, 1) &&
5955		    track->outbuf.used == 0 &&
5956		    track->seq <= mixer->hwseq);
5957		audio_track_lock_exit(track);
5958		if (done)
5959			break;
5960
5961		TRACET(3, track, "sleep");
5962		error = audio_track_waitio(sc, track);
5963		if (error)
5964			return error;
5965
5966		/* XXX call audio_track_play here ? */
5967	}
5968
5969	track->pstate = AUDIO_STATE_CLEAR;
5970	TRACET(3, track, "done trk_inp=%d trk_out=%d",
5971		(int)track->inputcounter, (int)track->outputcounter);
5972	return 0;
5973}
5974
5975/*
5976 * Send signal to process.
5977 * This is intended to be called only from audio_softintr_{rd,wr}.
5978 * Must be called without sc_intr_lock held.
5979 */
5980static inline void
5981audio_psignal(struct audio_softc *sc, pid_t pid, int signum)
5982{
5983	proc_t *p;
5984
5985	KASSERT(pid != 0);
5986
5987	/*
5988	 * psignal() must be called without spin lock held.
5989	 */
5990
5991	mutex_enter(&proc_lock);
5992	p = proc_find(pid);
5993	if (p)
5994		psignal(p, signum);
5995	mutex_exit(&proc_lock);
5996}
5997
5998/*
5999 * This is software interrupt handler for record.
6000 * It is called from recording hardware interrupt everytime.
6001 * It does:
6002 * - Deliver SIGIO for all async processes.
6003 * - Notify to audio_read() that data has arrived.
6004 * - selnotify() for select/poll-ing processes.
6005 */
6006/*
6007 * XXX If a process issues FIOASYNC between hardware interrupt and
6008 *     software interrupt, (stray) SIGIO will be sent to the process
6009 *     despite the fact that it has not receive recorded data yet.
6010 */
6011static void
6012audio_softintr_rd(void *cookie)
6013{
6014	struct audio_softc *sc = cookie;
6015	audio_file_t *f;
6016	pid_t pid;
6017
6018	mutex_enter(sc->sc_lock);
6019
6020	SLIST_FOREACH(f, &sc->sc_files, entry) {
6021		audio_track_t *track = f->rtrack;
6022
6023		if (track == NULL)
6024			continue;
6025
6026		TRACET(4, track, "broadcast; inp=%d/%d/%d",
6027		    track->input->head,
6028		    track->input->used,
6029		    track->input->capacity);
6030
6031		pid = f->async_audio;
6032		if (pid != 0) {
6033			TRACEF(4, f, "sending SIGIO %d", pid);
6034			audio_psignal(sc, pid, SIGIO);
6035		}
6036	}
6037
6038	/* Notify that data has arrived. */
6039	selnotify(&sc->sc_rsel, 0, NOTE_SUBMIT);
6040	KNOTE(&sc->sc_rsel.sel_klist, 0);
6041	cv_broadcast(&sc->sc_rmixer->outcv);
6042
6043	mutex_exit(sc->sc_lock);
6044}
6045
6046/*
6047 * This is software interrupt handler for playback.
6048 * It is called from playback hardware interrupt everytime.
6049 * It does:
6050 * - Deliver SIGIO for all async and writable (used < lowat) processes.
6051 * - Notify to audio_write() that outbuf block available.
6052 * - selnotify() for select/poll-ing processes if there are any writable
6053 *   (used < lowat) processes.  Checking each descriptor will be done by
6054 *   filt_audiowrite_event().
6055 */
6056static void
6057audio_softintr_wr(void *cookie)
6058{
6059	struct audio_softc *sc = cookie;
6060	audio_file_t *f;
6061	bool found;
6062	pid_t pid;
6063
6064	TRACE(4, "called");
6065	found = false;
6066
6067	mutex_enter(sc->sc_lock);
6068
6069	SLIST_FOREACH(f, &sc->sc_files, entry) {
6070		audio_track_t *track = f->ptrack;
6071
6072		if (track == NULL)
6073			continue;
6074
6075		TRACET(4, track, "broadcast; trseq=%d out=%d/%d/%d",
6076		    (int)track->seq,
6077		    track->outbuf.head,
6078		    track->outbuf.used,
6079		    track->outbuf.capacity);
6080
6081		/*
6082		 * Send a signal if the process is async mode and
6083		 * used is lower than lowat.
6084		 */
6085		if (track->usrbuf.used <= track->usrbuf_usedlow &&
6086		    !track->is_pause) {
6087			/* For selnotify */
6088			found = true;
6089			/* For SIGIO */
6090			pid = f->async_audio;
6091			if (pid != 0) {
6092				TRACEF(4, f, "sending SIGIO %d", pid);
6093				audio_psignal(sc, pid, SIGIO);
6094			}
6095		}
6096	}
6097
6098	/*
6099	 * Notify for select/poll when someone become writable.
6100	 * It needs sc_lock (and not sc_intr_lock).
6101	 */
6102	if (found) {
6103		TRACE(4, "selnotify");
6104		selnotify(&sc->sc_wsel, 0, NOTE_SUBMIT);
6105		KNOTE(&sc->sc_wsel.sel_klist, 0);
6106	}
6107
6108	/* Notify to audio_write() that outbuf available. */
6109	cv_broadcast(&sc->sc_pmixer->outcv);
6110
6111	mutex_exit(sc->sc_lock);
6112}
6113
6114/*
6115 * Check (and convert) the format *p came from userland.
6116 * If successful, it writes back the converted format to *p if necessary
6117 * and returns 0.  Otherwise returns errno (*p may change even this case).
6118 */
6119static int
6120audio_check_params(audio_format2_t *p)
6121{
6122
6123	/*
6124	 * Convert obsolete AUDIO_ENCODING_PCM encodings.
6125	 *
6126	 * AUDIO_ENCODING_PCM16 == AUDIO_ENCODING_LINEAR
6127	 * So, it's always signed, as in SunOS.
6128	 *
6129	 * AUDIO_ENCODING_PCM8 == AUDIO_ENCODING_LINEAR8
6130	 * So, it's always unsigned, as in SunOS.
6131	 */
6132	if (p->encoding == AUDIO_ENCODING_PCM16) {
6133		p->encoding = AUDIO_ENCODING_SLINEAR;
6134	} else if (p->encoding == AUDIO_ENCODING_PCM8) {
6135		if (p->precision == 8)
6136			p->encoding = AUDIO_ENCODING_ULINEAR;
6137		else
6138			return EINVAL;
6139	}
6140
6141	/*
6142	 * Convert obsoleted AUDIO_ENCODING_[SU]LINEAR without endianness
6143	 * suffix.
6144	 */
6145	if (p->encoding == AUDIO_ENCODING_SLINEAR)
6146		p->encoding = AUDIO_ENCODING_SLINEAR_NE;
6147	if (p->encoding == AUDIO_ENCODING_ULINEAR)
6148		p->encoding = AUDIO_ENCODING_ULINEAR_NE;
6149
6150	switch (p->encoding) {
6151	case AUDIO_ENCODING_ULAW:
6152	case AUDIO_ENCODING_ALAW:
6153		if (p->precision != 8)
6154			return EINVAL;
6155		break;
6156	case AUDIO_ENCODING_ADPCM:
6157		if (p->precision != 4 && p->precision != 8)
6158			return EINVAL;
6159		break;
6160	case AUDIO_ENCODING_SLINEAR_LE:
6161	case AUDIO_ENCODING_SLINEAR_BE:
6162	case AUDIO_ENCODING_ULINEAR_LE:
6163	case AUDIO_ENCODING_ULINEAR_BE:
6164		if (p->precision !=  8 && p->precision != 16 &&
6165		    p->precision != 24 && p->precision != 32)
6166			return EINVAL;
6167
6168		/* 8bit format does not have endianness. */
6169		if (p->precision == 8) {
6170			if (p->encoding == AUDIO_ENCODING_SLINEAR_OE)
6171				p->encoding = AUDIO_ENCODING_SLINEAR_NE;
6172			if (p->encoding == AUDIO_ENCODING_ULINEAR_OE)
6173				p->encoding = AUDIO_ENCODING_ULINEAR_NE;
6174		}
6175
6176		if (p->precision > p->stride)
6177			return EINVAL;
6178		break;
6179	case AUDIO_ENCODING_MPEG_L1_STREAM:
6180	case AUDIO_ENCODING_MPEG_L1_PACKETS:
6181	case AUDIO_ENCODING_MPEG_L1_SYSTEM:
6182	case AUDIO_ENCODING_MPEG_L2_STREAM:
6183	case AUDIO_ENCODING_MPEG_L2_PACKETS:
6184	case AUDIO_ENCODING_MPEG_L2_SYSTEM:
6185	case AUDIO_ENCODING_AC3:
6186		break;
6187	default:
6188		return EINVAL;
6189	}
6190
6191	/* sanity check # of channels*/
6192	if (p->channels < 1 || p->channels > AUDIO_MAX_CHANNELS)
6193		return EINVAL;
6194
6195	return 0;
6196}
6197
6198/*
6199 * Initialize playback and record mixers.
6200 * mode (AUMODE_{PLAY,RECORD}) indicates the mixer to be initialized.
6201 * phwfmt and rhwfmt indicate the hardware format.  pfil and rfil indicate
6202 * the filter registration information.  These four must not be NULL.
6203 * If successful returns 0.  Otherwise returns errno.
6204 * Must be called with sc_exlock held and without sc_lock held.
6205 * Must not be called if there are any tracks.
6206 * Caller should check that the initialization succeed by whether
6207 * sc_[pr]mixer is not NULL.
6208 */
6209static int
6210audio_mixers_init(struct audio_softc *sc, int mode,
6211	const audio_format2_t *phwfmt, const audio_format2_t *rhwfmt,
6212	const audio_filter_reg_t *pfil, const audio_filter_reg_t *rfil)
6213{
6214	int error;
6215
6216	KASSERT(phwfmt != NULL);
6217	KASSERT(rhwfmt != NULL);
6218	KASSERT(pfil != NULL);
6219	KASSERT(rfil != NULL);
6220	KASSERT(sc->sc_exlock);
6221
6222	if ((mode & AUMODE_PLAY)) {
6223		if (sc->sc_pmixer == NULL) {
6224			sc->sc_pmixer = kmem_zalloc(sizeof(*sc->sc_pmixer),
6225			    KM_SLEEP);
6226		} else {
6227			/* destroy() doesn't free memory. */
6228			audio_mixer_destroy(sc, sc->sc_pmixer);
6229			memset(sc->sc_pmixer, 0, sizeof(*sc->sc_pmixer));
6230		}
6231		error = audio_mixer_init(sc, AUMODE_PLAY, phwfmt, pfil);
6232		if (error) {
6233			device_printf(sc->sc_dev,
6234			    "configuring playback mode failed with %d\n",
6235			    error);
6236			kmem_free(sc->sc_pmixer, sizeof(*sc->sc_pmixer));
6237			sc->sc_pmixer = NULL;
6238			return error;
6239		}
6240	}
6241	if ((mode & AUMODE_RECORD)) {
6242		if (sc->sc_rmixer == NULL) {
6243			sc->sc_rmixer = kmem_zalloc(sizeof(*sc->sc_rmixer),
6244			    KM_SLEEP);
6245		} else {
6246			/* destroy() doesn't free memory. */
6247			audio_mixer_destroy(sc, sc->sc_rmixer);
6248			memset(sc->sc_rmixer, 0, sizeof(*sc->sc_rmixer));
6249		}
6250		error = audio_mixer_init(sc, AUMODE_RECORD, rhwfmt, rfil);
6251		if (error) {
6252			device_printf(sc->sc_dev,
6253			    "configuring record mode failed with %d\n",
6254			    error);
6255			kmem_free(sc->sc_rmixer, sizeof(*sc->sc_rmixer));
6256			sc->sc_rmixer = NULL;
6257			return error;
6258		}
6259	}
6260
6261	return 0;
6262}
6263
6264/*
6265 * Select a frequency.
6266 * Prioritize 48kHz and 44.1kHz.  Otherwise choose the highest one.
6267 * XXX Better algorithm?
6268 */
6269static int
6270audio_select_freq(const struct audio_format *fmt)
6271{
6272	int freq;
6273	int high;
6274	int low;
6275	int j;
6276
6277	if (fmt->frequency_type == 0) {
6278		low = fmt->frequency[0];
6279		high = fmt->frequency[1];
6280		freq = 48000;
6281		if (low <= freq && freq <= high) {
6282			return freq;
6283		}
6284		freq = 44100;
6285		if (low <= freq && freq <= high) {
6286			return freq;
6287		}
6288		return high;
6289	} else {
6290		for (j = 0; j < fmt->frequency_type; j++) {
6291			if (fmt->frequency[j] == 48000) {
6292				return fmt->frequency[j];
6293			}
6294		}
6295		high = 0;
6296		for (j = 0; j < fmt->frequency_type; j++) {
6297			if (fmt->frequency[j] == 44100) {
6298				return fmt->frequency[j];
6299			}
6300			if (fmt->frequency[j] > high) {
6301				high = fmt->frequency[j];
6302			}
6303		}
6304		return high;
6305	}
6306}
6307
6308/*
6309 * Choose the most preferred hardware format.
6310 * If successful, it will store the chosen format into *cand and return 0.
6311 * Otherwise, return errno.
6312 * Must be called without sc_lock held.
6313 */
6314static int
6315audio_hw_probe(struct audio_softc *sc, audio_format2_t *cand, int mode)
6316{
6317	audio_format_query_t query;
6318	int cand_score;
6319	int score;
6320	int i;
6321	int error;
6322
6323	/*
6324	 * Score each formats and choose the highest one.
6325	 *
6326	 *                 +---- priority(0-3)
6327	 *                 |+--- encoding/precision
6328	 *                 ||+-- channels
6329	 * score = 0x000000PEC
6330	 */
6331
6332	cand_score = 0;
6333	for (i = 0; ; i++) {
6334		memset(&query, 0, sizeof(query));
6335		query.index = i;
6336
6337		mutex_enter(sc->sc_lock);
6338		error = sc->hw_if->query_format(sc->hw_hdl, &query);
6339		mutex_exit(sc->sc_lock);
6340		if (error == EINVAL)
6341			break;
6342		if (error)
6343			return error;
6344
6345#if defined(AUDIO_DEBUG)
6346		DPRINTF(1, "fmt[%d] %c%c pri=%d %s,%d/%dbit,%dch,", i,
6347		    (query.fmt.mode & AUMODE_PLAY)   ? 'P' : '-',
6348		    (query.fmt.mode & AUMODE_RECORD) ? 'R' : '-',
6349		    query.fmt.priority,
6350		    audio_encoding_name(query.fmt.encoding),
6351		    query.fmt.validbits,
6352		    query.fmt.precision,
6353		    query.fmt.channels);
6354		if (query.fmt.frequency_type == 0) {
6355			DPRINTF(1, "{%d-%d",
6356			    query.fmt.frequency[0], query.fmt.frequency[1]);
6357		} else {
6358			int j;
6359			for (j = 0; j < query.fmt.frequency_type; j++) {
6360				DPRINTF(1, "%c%d",
6361				    (j == 0) ? '{' : ',',
6362				    query.fmt.frequency[j]);
6363			}
6364		}
6365		DPRINTF(1, "}\n");
6366#endif
6367
6368		if ((query.fmt.mode & mode) == 0) {
6369			DPRINTF(1, "fmt[%d] skip; mode not match %d\n", i,
6370			    mode);
6371			continue;
6372		}
6373
6374		if (query.fmt.priority < 0) {
6375			DPRINTF(1, "fmt[%d] skip; unsupported encoding\n", i);
6376			continue;
6377		}
6378
6379		/* Score */
6380		score = (query.fmt.priority & 3) * 0x100;
6381		if (query.fmt.encoding == AUDIO_ENCODING_SLINEAR_NE &&
6382		    query.fmt.validbits == AUDIO_INTERNAL_BITS &&
6383		    query.fmt.precision == AUDIO_INTERNAL_BITS) {
6384			score += 0x20;
6385		} else if (query.fmt.encoding == AUDIO_ENCODING_SLINEAR_OE &&
6386		    query.fmt.validbits == AUDIO_INTERNAL_BITS &&
6387		    query.fmt.precision == AUDIO_INTERNAL_BITS) {
6388			score += 0x10;
6389		}
6390		score += query.fmt.channels;
6391
6392		if (score < cand_score) {
6393			DPRINTF(1, "fmt[%d] skip; score 0x%x < 0x%x\n", i,
6394			    score, cand_score);
6395			continue;
6396		}
6397
6398		/* Update candidate */
6399		cand_score = score;
6400		cand->encoding    = query.fmt.encoding;
6401		cand->precision   = query.fmt.validbits;
6402		cand->stride      = query.fmt.precision;
6403		cand->channels    = query.fmt.channels;
6404		cand->sample_rate = audio_select_freq(&query.fmt);
6405		DPRINTF(1, "fmt[%d] candidate (score=0x%x)"
6406		    " pri=%d %s,%d/%d,%dch,%dHz\n", i,
6407		    cand_score, query.fmt.priority,
6408		    audio_encoding_name(query.fmt.encoding),
6409		    cand->precision, cand->stride,
6410		    cand->channels, cand->sample_rate);
6411	}
6412
6413	if (cand_score == 0) {
6414		DPRINTF(1, "%s no fmt\n", __func__);
6415		return ENXIO;
6416	}
6417	DPRINTF(1, "%s selected: %s,%d/%d,%dch,%dHz\n", __func__,
6418	    audio_encoding_name(cand->encoding),
6419	    cand->precision, cand->stride, cand->channels, cand->sample_rate);
6420	return 0;
6421}
6422
6423/*
6424 * Validate fmt with query_format.
6425 * If fmt is included in the result of query_format, returns 0.
6426 * Otherwise returns EINVAL.
6427 * Must be called without sc_lock held.
6428 */
6429static int
6430audio_hw_validate_format(struct audio_softc *sc, int mode,
6431	const audio_format2_t *fmt)
6432{
6433	audio_format_query_t query;
6434	struct audio_format *q;
6435	int index;
6436	int error;
6437	int j;
6438
6439	for (index = 0; ; index++) {
6440		query.index = index;
6441		mutex_enter(sc->sc_lock);
6442		error = sc->hw_if->query_format(sc->hw_hdl, &query);
6443		mutex_exit(sc->sc_lock);
6444		if (error == EINVAL)
6445			break;
6446		if (error)
6447			return error;
6448
6449		q = &query.fmt;
6450		/*
6451		 * Note that fmt is audio_format2_t (precision/stride) but
6452		 * q is audio_format_t (validbits/precision).
6453		 */
6454		if ((q->mode & mode) == 0) {
6455			continue;
6456		}
6457		if (fmt->encoding != q->encoding) {
6458			continue;
6459		}
6460		if (fmt->precision != q->validbits) {
6461			continue;
6462		}
6463		if (fmt->stride != q->precision) {
6464			continue;
6465		}
6466		if (fmt->channels != q->channels) {
6467			continue;
6468		}
6469		if (q->frequency_type == 0) {
6470			if (fmt->sample_rate < q->frequency[0] ||
6471			    fmt->sample_rate > q->frequency[1]) {
6472				continue;
6473			}
6474		} else {
6475			for (j = 0; j < q->frequency_type; j++) {
6476				if (fmt->sample_rate == q->frequency[j])
6477					break;
6478			}
6479			if (j == query.fmt.frequency_type) {
6480				continue;
6481			}
6482		}
6483
6484		/* Matched. */
6485		return 0;
6486	}
6487
6488	return EINVAL;
6489}
6490
6491/*
6492 * Set track mixer's format depending on ai->mode.
6493 * If AUMODE_PLAY is set in ai->mode, it set up the playback mixer
6494 * with ai.play.*.
6495 * If AUMODE_RECORD is set in ai->mode, it set up the recording mixer
6496 * with ai.record.*.
6497 * All other fields in ai are ignored.
6498 * If successful returns 0.  Otherwise returns errno.
6499 * This function does not roll back even if it fails.
6500 * Must be called with sc_exlock held and without sc_lock held.
6501 */
6502static int
6503audio_mixers_set_format(struct audio_softc *sc, const struct audio_info *ai)
6504{
6505	audio_format2_t phwfmt;
6506	audio_format2_t rhwfmt;
6507	audio_filter_reg_t pfil;
6508	audio_filter_reg_t rfil;
6509	int mode;
6510	int error;
6511
6512	KASSERT(sc->sc_exlock);
6513
6514	/*
6515	 * Even when setting either one of playback and recording,
6516	 * both must be halted.
6517	 */
6518	if (sc->sc_popens + sc->sc_ropens > 0)
6519		return EBUSY;
6520
6521	if (!SPECIFIED(ai->mode) || ai->mode == 0)
6522		return ENOTTY;
6523
6524	mode = ai->mode;
6525	if ((mode & AUMODE_PLAY)) {
6526		phwfmt.encoding    = ai->play.encoding;
6527		phwfmt.precision   = ai->play.precision;
6528		phwfmt.stride      = ai->play.precision;
6529		phwfmt.channels    = ai->play.channels;
6530		phwfmt.sample_rate = ai->play.sample_rate;
6531	}
6532	if ((mode & AUMODE_RECORD)) {
6533		rhwfmt.encoding    = ai->record.encoding;
6534		rhwfmt.precision   = ai->record.precision;
6535		rhwfmt.stride      = ai->record.precision;
6536		rhwfmt.channels    = ai->record.channels;
6537		rhwfmt.sample_rate = ai->record.sample_rate;
6538	}
6539
6540	/* On non-independent devices, use the same format for both. */
6541	if ((sc->sc_props & AUDIO_PROP_INDEPENDENT) == 0) {
6542		if (mode == AUMODE_RECORD) {
6543			phwfmt = rhwfmt;
6544		} else {
6545			rhwfmt = phwfmt;
6546		}
6547		mode = AUMODE_PLAY | AUMODE_RECORD;
6548	}
6549
6550	/* Then, unset the direction not exist on the hardware. */
6551	if ((sc->sc_props & AUDIO_PROP_PLAYBACK) == 0)
6552		mode &= ~AUMODE_PLAY;
6553	if ((sc->sc_props & AUDIO_PROP_CAPTURE) == 0)
6554		mode &= ~AUMODE_RECORD;
6555
6556	/* debug */
6557	if ((mode & AUMODE_PLAY)) {
6558		TRACE(1, "play=%s/%d/%d/%dch/%dHz",
6559		    audio_encoding_name(phwfmt.encoding),
6560		    phwfmt.precision,
6561		    phwfmt.stride,
6562		    phwfmt.channels,
6563		    phwfmt.sample_rate);
6564	}
6565	if ((mode & AUMODE_RECORD)) {
6566		TRACE(1, "rec =%s/%d/%d/%dch/%dHz",
6567		    audio_encoding_name(rhwfmt.encoding),
6568		    rhwfmt.precision,
6569		    rhwfmt.stride,
6570		    rhwfmt.channels,
6571		    rhwfmt.sample_rate);
6572	}
6573
6574	/* Check the format */
6575	if ((mode & AUMODE_PLAY)) {
6576		if (audio_hw_validate_format(sc, AUMODE_PLAY, &phwfmt)) {
6577			TRACE(1, "invalid format");
6578			return EINVAL;
6579		}
6580	}
6581	if ((mode & AUMODE_RECORD)) {
6582		if (audio_hw_validate_format(sc, AUMODE_RECORD, &rhwfmt)) {
6583			TRACE(1, "invalid format");
6584			return EINVAL;
6585		}
6586	}
6587
6588	/* Configure the mixers. */
6589	memset(&pfil, 0, sizeof(pfil));
6590	memset(&rfil, 0, sizeof(rfil));
6591	error = audio_hw_set_format(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
6592	if (error)
6593		return error;
6594
6595	error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
6596	if (error)
6597		return error;
6598
6599	/*
6600	 * Reinitialize the sticky parameters for /dev/sound.
6601	 * If the number of the hardware channels becomes less than the number
6602	 * of channels that sticky parameters remember, subsequent /dev/sound
6603	 * open will fail.  To prevent this, reinitialize the sticky
6604	 * parameters whenever the hardware format is changed.
6605	 */
6606	sc->sc_sound_pparams = params_to_format2(&audio_default);
6607	sc->sc_sound_rparams = params_to_format2(&audio_default);
6608	sc->sc_sound_ppause = false;
6609	sc->sc_sound_rpause = false;
6610
6611	return 0;
6612}
6613
6614/*
6615 * Store current mixers format into *ai.
6616 * Must be called with sc_exlock held.
6617 */
6618static void
6619audio_mixers_get_format(struct audio_softc *sc, struct audio_info *ai)
6620{
6621
6622	KASSERT(sc->sc_exlock);
6623
6624	/*
6625	 * There is no stride information in audio_info but it doesn't matter.
6626	 * trackmixer always treats stride and precision as the same.
6627	 */
6628	AUDIO_INITINFO(ai);
6629	ai->mode = 0;
6630	if (sc->sc_pmixer) {
6631		audio_format2_t *fmt = &sc->sc_pmixer->track_fmt;
6632		ai->play.encoding    = fmt->encoding;
6633		ai->play.precision   = fmt->precision;
6634		ai->play.channels    = fmt->channels;
6635		ai->play.sample_rate = fmt->sample_rate;
6636		ai->mode |= AUMODE_PLAY;
6637	}
6638	if (sc->sc_rmixer) {
6639		audio_format2_t *fmt = &sc->sc_rmixer->track_fmt;
6640		ai->record.encoding    = fmt->encoding;
6641		ai->record.precision   = fmt->precision;
6642		ai->record.channels    = fmt->channels;
6643		ai->record.sample_rate = fmt->sample_rate;
6644		ai->mode |= AUMODE_RECORD;
6645	}
6646}
6647
6648/*
6649 * audio_info details:
6650 *
6651 * ai.{play,record}.sample_rate		(R/W)
6652 * ai.{play,record}.encoding		(R/W)
6653 * ai.{play,record}.precision		(R/W)
6654 * ai.{play,record}.channels		(R/W)
6655 *	These specify the playback or recording format.
6656 *	Ignore members within an inactive track.
6657 *
6658 * ai.mode				(R/W)
6659 *	It specifies the playback or recording mode, AUMODE_*.
6660 *	Currently, a mode change operation by ai.mode after opening is
6661 *	prohibited.  In addition, AUMODE_PLAY_ALL no longer makes sense.
6662 *	However, it's possible to get or to set for backward compatibility.
6663 *
6664 * ai.{hiwat,lowat}			(R/W)
6665 *	These specify the high water mark and low water mark for playback
6666 *	track.  The unit is block.
6667 *
6668 * ai.{play,record}.gain		(R/W)
6669 *	It specifies the HW mixer volume in 0-255.
6670 *	It is historical reason that the gain is connected to HW mixer.
6671 *
6672 * ai.{play,record}.balance		(R/W)
6673 *	It specifies the left-right balance of HW mixer in 0-64.
6674 *	32 means the center.
6675 *	It is historical reason that the balance is connected to HW mixer.
6676 *
6677 * ai.{play,record}.port		(R/W)
6678 *	It specifies the input/output port of HW mixer.
6679 *
6680 * ai.monitor_gain			(R/W)
6681 *	It specifies the recording monitor gain(?) of HW mixer.
6682 *
6683 * ai.{play,record}.pause		(R/W)
6684 *	Non-zero means the track is paused.
6685 *
6686 * ai.play.seek				(R/-)
6687 *	It indicates the number of bytes written but not processed.
6688 * ai.record.seek			(R/-)
6689 *	It indicates the number of bytes to be able to read.
6690 *
6691 * ai.{play,record}.avail_ports		(R/-)
6692 *	Mixer info.
6693 *
6694 * ai.{play,record}.buffer_size		(R/-)
6695 *	It indicates the buffer size in bytes.  Internally it means usrbuf.
6696 *
6697 * ai.{play,record}.samples		(R/-)
6698 *	It indicates the total number of bytes played or recorded.
6699 *
6700 * ai.{play,record}.eof			(R/-)
6701 *	It indicates the number of times reached EOF(?).
6702 *
6703 * ai.{play,record}.error		(R/-)
6704 *	Non-zero indicates overflow/underflow has occured.
6705 *
6706 * ai.{play,record}.waiting		(R/-)
6707 *	Non-zero indicates that other process waits to open.
6708 *	It will never happen anymore.
6709 *
6710 * ai.{play,record}.open		(R/-)
6711 *	Non-zero indicates the direction is opened by this process(?).
6712 *	XXX Is this better to indicate that "the device is opened by
6713 *	at least one process"?
6714 *
6715 * ai.{play,record}.active		(R/-)
6716 *	Non-zero indicates that I/O is currently active.
6717 *
6718 * ai.blocksize				(R/-)
6719 *	It indicates the block size in bytes.
6720 *	XXX The blocksize of playback and recording may be different.
6721 */
6722
6723/*
6724 * Pause consideration:
6725 *
6726 * Pausing/unpausing never affect [pr]mixer.  This single rule makes
6727 * operation simple.  Note that playback and recording are asymmetric.
6728 *
6729 * For playback,
6730 *  1. Any playback open doesn't start pmixer regardless of initial pause
6731 *     state of this track.
6732 *  2. The first write access among playback tracks only starts pmixer
6733 *     regardless of this track's pause state.
6734 *  3. Even a pause of the last playback track doesn't stop pmixer.
6735 *  4. The last close of all playback tracks only stops pmixer.
6736 *
6737 * For recording,
6738 *  1. The first recording open only starts rmixer regardless of initial
6739 *     pause state of this track.
6740 *  2. Even a pause of the last track doesn't stop rmixer.
6741 *  3. The last close of all recording tracks only stops rmixer.
6742 */
6743
6744/*
6745 * Set both track's parameters within a file depending on ai.
6746 * Update sc_sound_[pr]* if set.
6747 * Must be called with sc_exlock held and without sc_lock held.
6748 */
6749static int
6750audio_file_setinfo(struct audio_softc *sc, audio_file_t *file,
6751	const struct audio_info *ai)
6752{
6753	const struct audio_prinfo *pi;
6754	const struct audio_prinfo *ri;
6755	audio_track_t *ptrack;
6756	audio_track_t *rtrack;
6757	audio_format2_t pfmt;
6758	audio_format2_t rfmt;
6759	int pchanges;
6760	int rchanges;
6761	int mode;
6762	struct audio_info saved_ai;
6763	audio_format2_t saved_pfmt;
6764	audio_format2_t saved_rfmt;
6765	int error;
6766
6767	KASSERT(sc->sc_exlock);
6768
6769	pi = &ai->play;
6770	ri = &ai->record;
6771	pchanges = 0;
6772	rchanges = 0;
6773
6774	ptrack = file->ptrack;
6775	rtrack = file->rtrack;
6776
6777#if defined(AUDIO_DEBUG)
6778	if (audiodebug >= 2) {
6779		char buf[256];
6780		char p[64];
6781		int buflen;
6782		int plen;
6783#define SPRINTF(var, fmt...) do {	\
6784	var##len += snprintf(var + var##len, sizeof(var) - var##len, fmt); \
6785} while (0)
6786
6787		buflen = 0;
6788		plen = 0;
6789		if (SPECIFIED(pi->encoding))
6790			SPRINTF(p, "/%s", audio_encoding_name(pi->encoding));
6791		if (SPECIFIED(pi->precision))
6792			SPRINTF(p, "/%dbit", pi->precision);
6793		if (SPECIFIED(pi->channels))
6794			SPRINTF(p, "/%dch", pi->channels);
6795		if (SPECIFIED(pi->sample_rate))
6796			SPRINTF(p, "/%dHz", pi->sample_rate);
6797		if (plen > 0)
6798			SPRINTF(buf, ",play.param=%s", p + 1);
6799
6800		plen = 0;
6801		if (SPECIFIED(ri->encoding))
6802			SPRINTF(p, "/%s", audio_encoding_name(ri->encoding));
6803		if (SPECIFIED(ri->precision))
6804			SPRINTF(p, "/%dbit", ri->precision);
6805		if (SPECIFIED(ri->channels))
6806			SPRINTF(p, "/%dch", ri->channels);
6807		if (SPECIFIED(ri->sample_rate))
6808			SPRINTF(p, "/%dHz", ri->sample_rate);
6809		if (plen > 0)
6810			SPRINTF(buf, ",record.param=%s", p + 1);
6811
6812		if (SPECIFIED(ai->mode))
6813			SPRINTF(buf, ",mode=%d", ai->mode);
6814		if (SPECIFIED(ai->hiwat))
6815			SPRINTF(buf, ",hiwat=%d", ai->hiwat);
6816		if (SPECIFIED(ai->lowat))
6817			SPRINTF(buf, ",lowat=%d", ai->lowat);
6818		if (SPECIFIED(ai->play.gain))
6819			SPRINTF(buf, ",play.gain=%d", ai->play.gain);
6820		if (SPECIFIED(ai->record.gain))
6821			SPRINTF(buf, ",record.gain=%d", ai->record.gain);
6822		if (SPECIFIED_CH(ai->play.balance))
6823			SPRINTF(buf, ",play.balance=%d", ai->play.balance);
6824		if (SPECIFIED_CH(ai->record.balance))
6825			SPRINTF(buf, ",record.balance=%d", ai->record.balance);
6826		if (SPECIFIED(ai->play.port))
6827			SPRINTF(buf, ",play.port=%d", ai->play.port);
6828		if (SPECIFIED(ai->record.port))
6829			SPRINTF(buf, ",record.port=%d", ai->record.port);
6830		if (SPECIFIED(ai->monitor_gain))
6831			SPRINTF(buf, ",monitor_gain=%d", ai->monitor_gain);
6832		if (SPECIFIED_CH(ai->play.pause))
6833			SPRINTF(buf, ",play.pause=%d", ai->play.pause);
6834		if (SPECIFIED_CH(ai->record.pause))
6835			SPRINTF(buf, ",record.pause=%d", ai->record.pause);
6836
6837		if (buflen > 0)
6838			TRACE(2, "specified %s", buf + 1);
6839	}
6840#endif
6841
6842	AUDIO_INITINFO(&saved_ai);
6843	/* XXX shut up gcc */
6844	memset(&saved_pfmt, 0, sizeof(saved_pfmt));
6845	memset(&saved_rfmt, 0, sizeof(saved_rfmt));
6846
6847	/*
6848	 * Set default value and save current parameters.
6849	 * For backward compatibility, use sticky parameters for nonexistent
6850	 * track.
6851	 */
6852	if (ptrack) {
6853		pfmt = ptrack->usrbuf.fmt;
6854		saved_pfmt = ptrack->usrbuf.fmt;
6855		saved_ai.play.pause = ptrack->is_pause;
6856	} else {
6857		pfmt = sc->sc_sound_pparams;
6858	}
6859	if (rtrack) {
6860		rfmt = rtrack->usrbuf.fmt;
6861		saved_rfmt = rtrack->usrbuf.fmt;
6862		saved_ai.record.pause = rtrack->is_pause;
6863	} else {
6864		rfmt = sc->sc_sound_rparams;
6865	}
6866	saved_ai.mode = file->mode;
6867
6868	/*
6869	 * Overwrite if specified.
6870	 */
6871	mode = file->mode;
6872	if (SPECIFIED(ai->mode)) {
6873		/*
6874		 * Setting ai->mode no longer does anything because it's
6875		 * prohibited to change playback/recording mode after open
6876		 * and AUMODE_PLAY_ALL is obsoleted.  However, it still
6877		 * keeps the state of AUMODE_PLAY_ALL itself for backward
6878		 * compatibility.
6879		 * In the internal, only file->mode has the state of
6880		 * AUMODE_PLAY_ALL flag and track->mode in both track does
6881		 * not have.
6882		 */
6883		if ((file->mode & AUMODE_PLAY)) {
6884			mode = (file->mode & (AUMODE_PLAY | AUMODE_RECORD))
6885			    | (ai->mode & AUMODE_PLAY_ALL);
6886		}
6887	}
6888
6889	pchanges = audio_track_setinfo_check(ptrack, &pfmt, pi);
6890	if (pchanges == -1) {
6891#if defined(AUDIO_DEBUG)
6892		TRACEF(1, file, "check play.params failed: "
6893		    "%s %ubit %uch %uHz",
6894		    audio_encoding_name(pi->encoding),
6895		    pi->precision,
6896		    pi->channels,
6897		    pi->sample_rate);
6898#endif
6899		return EINVAL;
6900	}
6901
6902	rchanges = audio_track_setinfo_check(rtrack, &rfmt, ri);
6903	if (rchanges == -1) {
6904#if defined(AUDIO_DEBUG)
6905		TRACEF(1, file, "check record.params failed: "
6906		    "%s %ubit %uch %uHz",
6907		    audio_encoding_name(ri->encoding),
6908		    ri->precision,
6909		    ri->channels,
6910		    ri->sample_rate);
6911#endif
6912		return EINVAL;
6913	}
6914
6915	if (SPECIFIED(ai->mode)) {
6916		pchanges = 1;
6917		rchanges = 1;
6918	}
6919
6920	/*
6921	 * Even when setting either one of playback and recording,
6922	 * both track must be halted.
6923	 */
6924	if (pchanges || rchanges) {
6925		audio_file_clear(sc, file);
6926#if defined(AUDIO_DEBUG)
6927		char nbuf[16];
6928		char fmtbuf[64];
6929		if (pchanges) {
6930			if (ptrack) {
6931				snprintf(nbuf, sizeof(nbuf), "%d", ptrack->id);
6932			} else {
6933				snprintf(nbuf, sizeof(nbuf), "-");
6934			}
6935			audio_format2_tostr(fmtbuf, sizeof(fmtbuf), &pfmt);
6936			DPRINTF(1, "audio track#%s play mode: %s\n",
6937			    nbuf, fmtbuf);
6938		}
6939		if (rchanges) {
6940			if (rtrack) {
6941				snprintf(nbuf, sizeof(nbuf), "%d", rtrack->id);
6942			} else {
6943				snprintf(nbuf, sizeof(nbuf), "-");
6944			}
6945			audio_format2_tostr(fmtbuf, sizeof(fmtbuf), &rfmt);
6946			DPRINTF(1, "audio track#%s rec  mode: %s\n",
6947			    nbuf, fmtbuf);
6948		}
6949#endif
6950	}
6951
6952	/* Set mixer parameters */
6953	mutex_enter(sc->sc_lock);
6954	error = audio_hw_setinfo(sc, ai, &saved_ai);
6955	mutex_exit(sc->sc_lock);
6956	if (error)
6957		goto abort1;
6958
6959	/*
6960	 * Set to track and update sticky parameters.
6961	 */
6962	error = 0;
6963	file->mode = mode;
6964
6965	if (SPECIFIED_CH(pi->pause)) {
6966		if (ptrack)
6967			ptrack->is_pause = pi->pause;
6968		sc->sc_sound_ppause = pi->pause;
6969	}
6970	if (pchanges) {
6971		if (ptrack) {
6972			audio_track_lock_enter(ptrack);
6973			error = audio_track_set_format(ptrack, &pfmt);
6974			audio_track_lock_exit(ptrack);
6975			if (error) {
6976				TRACET(1, ptrack, "set play.params failed");
6977				goto abort2;
6978			}
6979		}
6980		sc->sc_sound_pparams = pfmt;
6981	}
6982	/* Change water marks after initializing the buffers. */
6983	if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat)) {
6984		if (ptrack)
6985			audio_track_setinfo_water(ptrack, ai);
6986	}
6987
6988	if (SPECIFIED_CH(ri->pause)) {
6989		if (rtrack)
6990			rtrack->is_pause = ri->pause;
6991		sc->sc_sound_rpause = ri->pause;
6992	}
6993	if (rchanges) {
6994		if (rtrack) {
6995			audio_track_lock_enter(rtrack);
6996			error = audio_track_set_format(rtrack, &rfmt);
6997			audio_track_lock_exit(rtrack);
6998			if (error) {
6999				TRACET(1, rtrack, "set record.params failed");
7000				goto abort3;
7001			}
7002		}
7003		sc->sc_sound_rparams = rfmt;
7004	}
7005
7006	return 0;
7007
7008	/* Rollback */
7009abort3:
7010	if (error != ENOMEM) {
7011		rtrack->is_pause = saved_ai.record.pause;
7012		audio_track_lock_enter(rtrack);
7013		audio_track_set_format(rtrack, &saved_rfmt);
7014		audio_track_lock_exit(rtrack);
7015	}
7016	sc->sc_sound_rpause = saved_ai.record.pause;
7017	sc->sc_sound_rparams = saved_rfmt;
7018abort2:
7019	if (ptrack && error != ENOMEM) {
7020		ptrack->is_pause = saved_ai.play.pause;
7021		audio_track_lock_enter(ptrack);
7022		audio_track_set_format(ptrack, &saved_pfmt);
7023		audio_track_lock_exit(ptrack);
7024	}
7025	sc->sc_sound_ppause = saved_ai.play.pause;
7026	sc->sc_sound_pparams = saved_pfmt;
7027	file->mode = saved_ai.mode;
7028abort1:
7029	mutex_enter(sc->sc_lock);
7030	audio_hw_setinfo(sc, &saved_ai, NULL);
7031	mutex_exit(sc->sc_lock);
7032
7033	return error;
7034}
7035
7036/*
7037 * Write SPECIFIED() parameters within info back to fmt.
7038 * Note that track can be NULL here.
7039 * Return value of 1 indicates that fmt is modified.
7040 * Return value of 0 indicates that fmt is not modified.
7041 * Return value of -1 indicates that error EINVAL has occurred.
7042 */
7043static int
7044audio_track_setinfo_check(audio_track_t *track,
7045	audio_format2_t *fmt, const struct audio_prinfo *info)
7046{
7047	const audio_format2_t *hwfmt;
7048	int changes;
7049
7050	changes = 0;
7051	if (SPECIFIED(info->sample_rate)) {
7052		if (info->sample_rate < AUDIO_MIN_FREQUENCY)
7053			return -1;
7054		if (info->sample_rate > AUDIO_MAX_FREQUENCY)
7055			return -1;
7056		fmt->sample_rate = info->sample_rate;
7057		changes = 1;
7058	}
7059	if (SPECIFIED(info->encoding)) {
7060		fmt->encoding = info->encoding;
7061		changes = 1;
7062	}
7063	if (SPECIFIED(info->precision)) {
7064		fmt->precision = info->precision;
7065		/* we don't have API to specify stride */
7066		fmt->stride = info->precision;
7067		changes = 1;
7068	}
7069	if (SPECIFIED(info->channels)) {
7070		/*
7071		 * We can convert between monaural and stereo each other.
7072		 * We can reduce than the number of channels that the hardware
7073		 * supports.
7074		 */
7075		if (info->channels > 2) {
7076			if (track) {
7077				hwfmt = &track->mixer->hwbuf.fmt;
7078				if (info->channels > hwfmt->channels)
7079					return -1;
7080			} else {
7081				/*
7082				 * This should never happen.
7083				 * If track == NULL, channels should be <= 2.
7084				 */
7085				return -1;
7086			}
7087		}
7088		fmt->channels = info->channels;
7089		changes = 1;
7090	}
7091
7092	if (changes) {
7093		if (audio_check_params(fmt) != 0)
7094			return -1;
7095	}
7096
7097	return changes;
7098}
7099
7100/*
7101 * Change water marks for playback track if specfied.
7102 */
7103static void
7104audio_track_setinfo_water(audio_track_t *track, const struct audio_info *ai)
7105{
7106	u_int blks;
7107	u_int maxblks;
7108	u_int blksize;
7109
7110	KASSERT(audio_track_is_playback(track));
7111
7112	blksize = track->usrbuf_blksize;
7113	maxblks = track->usrbuf.capacity / blksize;
7114
7115	if (SPECIFIED(ai->hiwat)) {
7116		blks = ai->hiwat;
7117		if (blks > maxblks)
7118			blks = maxblks;
7119		if (blks < 2)
7120			blks = 2;
7121		track->usrbuf_usedhigh = blks * blksize;
7122	}
7123	if (SPECIFIED(ai->lowat)) {
7124		blks = ai->lowat;
7125		if (blks > maxblks - 1)
7126			blks = maxblks - 1;
7127		track->usrbuf_usedlow = blks * blksize;
7128	}
7129	if (SPECIFIED(ai->hiwat) || SPECIFIED(ai->lowat)) {
7130		if (track->usrbuf_usedlow > track->usrbuf_usedhigh - blksize) {
7131			track->usrbuf_usedlow = track->usrbuf_usedhigh -
7132			    blksize;
7133		}
7134	}
7135}
7136
7137/*
7138 * Set hardware part of *newai.
7139 * The parameters handled here are *.port, *.gain, *.balance and monitor_gain.
7140 * If oldai is specified, previous parameters are stored.
7141 * This function itself does not roll back if error occurred.
7142 * Must be called with sc_lock && sc_exlock held.
7143 */
7144static int
7145audio_hw_setinfo(struct audio_softc *sc, const struct audio_info *newai,
7146	struct audio_info *oldai)
7147{
7148	const struct audio_prinfo *newpi;
7149	const struct audio_prinfo *newri;
7150	struct audio_prinfo *oldpi;
7151	struct audio_prinfo *oldri;
7152	u_int pgain;
7153	u_int rgain;
7154	u_char pbalance;
7155	u_char rbalance;
7156	int error;
7157
7158	KASSERT(mutex_owned(sc->sc_lock));
7159	KASSERT(sc->sc_exlock);
7160
7161	/* XXX shut up gcc */
7162	oldpi = NULL;
7163	oldri = NULL;
7164
7165	newpi = &newai->play;
7166	newri = &newai->record;
7167	if (oldai) {
7168		oldpi = &oldai->play;
7169		oldri = &oldai->record;
7170	}
7171	error = 0;
7172
7173	/*
7174	 * It looks like unnecessary to halt HW mixers to set HW mixers.
7175	 * mixer_ioctl(MIXER_WRITE) also doesn't halt.
7176	 */
7177
7178	if (SPECIFIED(newpi->port)) {
7179		if (oldai)
7180			oldpi->port = au_get_port(sc, &sc->sc_outports);
7181		error = au_set_port(sc, &sc->sc_outports, newpi->port);
7182		if (error) {
7183			device_printf(sc->sc_dev,
7184			    "setting play.port=%d failed with %d\n",
7185			    newpi->port, error);
7186			goto abort;
7187		}
7188	}
7189	if (SPECIFIED(newri->port)) {
7190		if (oldai)
7191			oldri->port = au_get_port(sc, &sc->sc_inports);
7192		error = au_set_port(sc, &sc->sc_inports, newri->port);
7193		if (error) {
7194			device_printf(sc->sc_dev,
7195			    "setting record.port=%d failed with %d\n",
7196			    newri->port, error);
7197			goto abort;
7198		}
7199	}
7200
7201	/* Backup play.{gain,balance} */
7202	if (SPECIFIED(newpi->gain) || SPECIFIED_CH(newpi->balance)) {
7203		au_get_gain(sc, &sc->sc_outports, &pgain, &pbalance);
7204		if (oldai) {
7205			oldpi->gain = pgain;
7206			oldpi->balance = pbalance;
7207		}
7208	}
7209	/* Backup record.{gain,balance} */
7210	if (SPECIFIED(newri->gain) || SPECIFIED_CH(newri->balance)) {
7211		au_get_gain(sc, &sc->sc_inports, &rgain, &rbalance);
7212		if (oldai) {
7213			oldri->gain = rgain;
7214			oldri->balance = rbalance;
7215		}
7216	}
7217	if (SPECIFIED(newpi->gain)) {
7218		error = au_set_gain(sc, &sc->sc_outports,
7219		    newpi->gain, pbalance);
7220		if (error) {
7221			device_printf(sc->sc_dev,
7222			    "setting play.gain=%d failed with %d\n",
7223			    newpi->gain, error);
7224			goto abort;
7225		}
7226	}
7227	if (SPECIFIED(newri->gain)) {
7228		error = au_set_gain(sc, &sc->sc_inports,
7229		    newri->gain, rbalance);
7230		if (error) {
7231			device_printf(sc->sc_dev,
7232			    "setting record.gain=%d failed with %d\n",
7233			    newri->gain, error);
7234			goto abort;
7235		}
7236	}
7237	if (SPECIFIED_CH(newpi->balance)) {
7238		error = au_set_gain(sc, &sc->sc_outports,
7239		    pgain, newpi->balance);
7240		if (error) {
7241			device_printf(sc->sc_dev,
7242			    "setting play.balance=%d failed with %d\n",
7243			    newpi->balance, error);
7244			goto abort;
7245		}
7246	}
7247	if (SPECIFIED_CH(newri->balance)) {
7248		error = au_set_gain(sc, &sc->sc_inports,
7249		    rgain, newri->balance);
7250		if (error) {
7251			device_printf(sc->sc_dev,
7252			    "setting record.balance=%d failed with %d\n",
7253			    newri->balance, error);
7254			goto abort;
7255		}
7256	}
7257
7258	if (SPECIFIED(newai->monitor_gain) && sc->sc_monitor_port != -1) {
7259		if (oldai)
7260			oldai->monitor_gain = au_get_monitor_gain(sc);
7261		error = au_set_monitor_gain(sc, newai->monitor_gain);
7262		if (error) {
7263			device_printf(sc->sc_dev,
7264			    "setting monitor_gain=%d failed with %d\n",
7265			    newai->monitor_gain, error);
7266			goto abort;
7267		}
7268	}
7269
7270	/* XXX TODO */
7271	/* sc->sc_ai = *ai; */
7272
7273	error = 0;
7274abort:
7275	return error;
7276}
7277
7278/*
7279 * Setup the hardware with mixer format phwfmt, rhwfmt.
7280 * The arguments have following restrictions:
7281 * - setmode is the direction you want to set, AUMODE_PLAY or AUMODE_RECORD,
7282 *   or both.
7283 * - phwfmt and rhwfmt must not be NULL regardless of setmode.
7284 * - On non-independent devices, phwfmt and rhwfmt must have the same
7285 *   parameters.
7286 * - pfil and rfil must be zero-filled.
7287 * If successful,
7288 * - pfil, rfil will be filled with filter information specified by the
7289 *   hardware driver.
7290 * and then returns 0.  Otherwise returns errno.
7291 * Must be called without sc_lock held.
7292 */
7293static int
7294audio_hw_set_format(struct audio_softc *sc, int setmode,
7295	const audio_format2_t *phwfmt, const audio_format2_t *rhwfmt,
7296	audio_filter_reg_t *pfil, audio_filter_reg_t *rfil)
7297{
7298	audio_params_t pp, rp;
7299	int error;
7300
7301	KASSERT(phwfmt != NULL);
7302	KASSERT(rhwfmt != NULL);
7303
7304	pp = format2_to_params(phwfmt);
7305	rp = format2_to_params(rhwfmt);
7306
7307	mutex_enter(sc->sc_lock);
7308	error = sc->hw_if->set_format(sc->hw_hdl, setmode,
7309	    &pp, &rp, pfil, rfil);
7310	if (error) {
7311		mutex_exit(sc->sc_lock);
7312		device_printf(sc->sc_dev,
7313		    "set_format failed with %d\n", error);
7314		return error;
7315	}
7316
7317	if (sc->hw_if->commit_settings) {
7318		error = sc->hw_if->commit_settings(sc->hw_hdl);
7319		if (error) {
7320			mutex_exit(sc->sc_lock);
7321			device_printf(sc->sc_dev,
7322			    "commit_settings failed with %d\n", error);
7323			return error;
7324		}
7325	}
7326	mutex_exit(sc->sc_lock);
7327
7328	return 0;
7329}
7330
7331/*
7332 * Fill audio_info structure.  If need_mixerinfo is true, it will also
7333 * fill the hardware mixer information.
7334 * Must be called with sc_exlock held and without sc_lock held.
7335 */
7336static int
7337audiogetinfo(struct audio_softc *sc, struct audio_info *ai, int need_mixerinfo,
7338	audio_file_t *file)
7339{
7340	struct audio_prinfo *ri, *pi;
7341	audio_track_t *track;
7342	audio_track_t *ptrack;
7343	audio_track_t *rtrack;
7344	int gain;
7345
7346	KASSERT(sc->sc_exlock);
7347
7348	ri = &ai->record;
7349	pi = &ai->play;
7350	ptrack = file->ptrack;
7351	rtrack = file->rtrack;
7352
7353	memset(ai, 0, sizeof(*ai));
7354
7355	if (ptrack) {
7356		pi->sample_rate = ptrack->usrbuf.fmt.sample_rate;
7357		pi->channels    = ptrack->usrbuf.fmt.channels;
7358		pi->precision   = ptrack->usrbuf.fmt.precision;
7359		pi->encoding    = ptrack->usrbuf.fmt.encoding;
7360		pi->pause       = ptrack->is_pause;
7361	} else {
7362		/* Use sticky parameters if the track is not available. */
7363		pi->sample_rate = sc->sc_sound_pparams.sample_rate;
7364		pi->channels    = sc->sc_sound_pparams.channels;
7365		pi->precision   = sc->sc_sound_pparams.precision;
7366		pi->encoding    = sc->sc_sound_pparams.encoding;
7367		pi->pause       = sc->sc_sound_ppause;
7368	}
7369	if (rtrack) {
7370		ri->sample_rate = rtrack->usrbuf.fmt.sample_rate;
7371		ri->channels    = rtrack->usrbuf.fmt.channels;
7372		ri->precision   = rtrack->usrbuf.fmt.precision;
7373		ri->encoding    = rtrack->usrbuf.fmt.encoding;
7374		ri->pause       = rtrack->is_pause;
7375	} else {
7376		/* Use sticky parameters if the track is not available. */
7377		ri->sample_rate = sc->sc_sound_rparams.sample_rate;
7378		ri->channels    = sc->sc_sound_rparams.channels;
7379		ri->precision   = sc->sc_sound_rparams.precision;
7380		ri->encoding    = sc->sc_sound_rparams.encoding;
7381		ri->pause       = sc->sc_sound_rpause;
7382	}
7383
7384	if (ptrack) {
7385		pi->seek = ptrack->usrbuf.used;
7386		pi->samples = ptrack->usrbuf_stamp;
7387		pi->eof = ptrack->eofcounter;
7388		pi->error = (ptrack->dropframes != 0) ? 1 : 0;
7389		pi->open = 1;
7390		pi->buffer_size = ptrack->usrbuf.capacity;
7391	}
7392	pi->waiting = 0;		/* open never hangs */
7393	pi->active = sc->sc_pbusy;
7394
7395	if (rtrack) {
7396		ri->seek = rtrack->usrbuf.used;
7397		ri->samples = rtrack->usrbuf_stamp;
7398		ri->eof = 0;
7399		ri->error = (rtrack->dropframes != 0) ? 1 : 0;
7400		ri->open = 1;
7401		ri->buffer_size = rtrack->usrbuf.capacity;
7402	}
7403	ri->waiting = 0;		/* open never hangs */
7404	ri->active = sc->sc_rbusy;
7405
7406	/*
7407	 * XXX There may be different number of channels between playback
7408	 *     and recording, so that blocksize also may be different.
7409	 *     But struct audio_info has an united blocksize...
7410	 *     Here, I use play info precedencely if ptrack is available,
7411	 *     otherwise record info.
7412	 *
7413	 * XXX hiwat/lowat is a playback-only parameter.  What should I
7414	 *     return for a record-only descriptor?
7415	 */
7416	track = ptrack ? ptrack : rtrack;
7417	if (track) {
7418		ai->blocksize = track->usrbuf_blksize;
7419		ai->hiwat = track->usrbuf_usedhigh / track->usrbuf_blksize;
7420		ai->lowat = track->usrbuf_usedlow / track->usrbuf_blksize;
7421	}
7422	ai->mode = file->mode;
7423
7424	/*
7425	 * For backward compatibility, we have to pad these five fields
7426	 * a fake non-zero value even if there are no tracks.
7427	 */
7428	if (ptrack == NULL)
7429		pi->buffer_size = 65536;
7430	if (rtrack == NULL)
7431		ri->buffer_size = 65536;
7432	if (ptrack == NULL && rtrack == NULL) {
7433		ai->blocksize = 2048;
7434		ai->hiwat = ai->play.buffer_size / ai->blocksize;
7435		ai->lowat = ai->hiwat * 3 / 4;
7436	}
7437
7438	if (need_mixerinfo) {
7439		mutex_enter(sc->sc_lock);
7440
7441		pi->port = au_get_port(sc, &sc->sc_outports);
7442		ri->port = au_get_port(sc, &sc->sc_inports);
7443
7444		pi->avail_ports = sc->sc_outports.allports;
7445		ri->avail_ports = sc->sc_inports.allports;
7446
7447		au_get_gain(sc, &sc->sc_outports, &pi->gain, &pi->balance);
7448		au_get_gain(sc, &sc->sc_inports, &ri->gain, &ri->balance);
7449
7450		if (sc->sc_monitor_port != -1) {
7451			gain = au_get_monitor_gain(sc);
7452			if (gain != -1)
7453				ai->monitor_gain = gain;
7454		}
7455		mutex_exit(sc->sc_lock);
7456	}
7457
7458	return 0;
7459}
7460
7461/*
7462 * Return true if playback is configured.
7463 * This function can be used after audioattach.
7464 */
7465static bool
7466audio_can_playback(struct audio_softc *sc)
7467{
7468
7469	return (sc->sc_pmixer != NULL);
7470}
7471
7472/*
7473 * Return true if recording is configured.
7474 * This function can be used after audioattach.
7475 */
7476static bool
7477audio_can_capture(struct audio_softc *sc)
7478{
7479
7480	return (sc->sc_rmixer != NULL);
7481}
7482
7483/*
7484 * Get the afp->index'th item from the valid one of format[].
7485 * If found, stores it to afp->fmt and returns 0.  Otherwise return EINVAL.
7486 *
7487 * This is common routines for query_format.
7488 * If your hardware driver has struct audio_format[], the simplest case
7489 * you can write your query_format interface as follows:
7490 *
7491 * struct audio_format foo_format[] = { ... };
7492 *
7493 * int
7494 * foo_query_format(void *hdl, audio_format_query_t *afp)
7495 * {
7496 *   return audio_query_format(foo_format, __arraycount(foo_format), afp);
7497 * }
7498 */
7499int
7500audio_query_format(const struct audio_format *format, int nformats,
7501	audio_format_query_t *afp)
7502{
7503	const struct audio_format *f;
7504	int idx;
7505	int i;
7506
7507	idx = 0;
7508	for (i = 0; i < nformats; i++) {
7509		f = &format[i];
7510		if (!AUFMT_IS_VALID(f))
7511			continue;
7512		if (afp->index == idx) {
7513			afp->fmt = *f;
7514			return 0;
7515		}
7516		idx++;
7517	}
7518	return EINVAL;
7519}
7520
7521/*
7522 * This function is provided for the hardware driver's set_format() to
7523 * find index matches with 'param' from array of audio_format_t 'formats'.
7524 * 'mode' is either of AUMODE_PLAY or AUMODE_RECORD.
7525 * It returns the matched index and never fails.  Because param passed to
7526 * set_format() is selected from query_format().
7527 * This function will be an alternative to auconv_set_converter() to
7528 * find index.
7529 */
7530int
7531audio_indexof_format(const struct audio_format *formats, int nformats,
7532	int mode, const audio_params_t *param)
7533{
7534	const struct audio_format *f;
7535	int index;
7536	int j;
7537
7538	for (index = 0; index < nformats; index++) {
7539		f = &formats[index];
7540
7541		if (!AUFMT_IS_VALID(f))
7542			continue;
7543		if ((f->mode & mode) == 0)
7544			continue;
7545		if (f->encoding != param->encoding)
7546			continue;
7547		if (f->validbits != param->precision)
7548			continue;
7549		if (f->channels != param->channels)
7550			continue;
7551
7552		if (f->frequency_type == 0) {
7553			if (param->sample_rate < f->frequency[0] ||
7554			    param->sample_rate > f->frequency[1])
7555				continue;
7556		} else {
7557			for (j = 0; j < f->frequency_type; j++) {
7558				if (param->sample_rate == f->frequency[j])
7559					break;
7560			}
7561			if (j == f->frequency_type)
7562				continue;
7563		}
7564
7565		/* Then, matched */
7566		return index;
7567	}
7568
7569	/* Not matched.  This should not be happened. */
7570	panic("%s: cannot find matched format\n", __func__);
7571}
7572
7573/*
7574 * Get or set hardware blocksize in msec.
7575 * XXX It's for debug.
7576 */
7577static int
7578audio_sysctl_blk_ms(SYSCTLFN_ARGS)
7579{
7580	struct sysctlnode node;
7581	struct audio_softc *sc;
7582	audio_format2_t phwfmt;
7583	audio_format2_t rhwfmt;
7584	audio_filter_reg_t pfil;
7585	audio_filter_reg_t rfil;
7586	int t;
7587	int old_blk_ms;
7588	int mode;
7589	int error;
7590
7591	node = *rnode;
7592	sc = node.sysctl_data;
7593
7594	error = audio_exlock_enter(sc);
7595	if (error)
7596		return error;
7597
7598	old_blk_ms = sc->sc_blk_ms;
7599	t = old_blk_ms;
7600	node.sysctl_data = &t;
7601	error = sysctl_lookup(SYSCTLFN_CALL(&node));
7602	if (error || newp == NULL)
7603		goto abort;
7604
7605	if (t < 0) {
7606		error = EINVAL;
7607		goto abort;
7608	}
7609
7610	if (sc->sc_popens + sc->sc_ropens > 0) {
7611		error = EBUSY;
7612		goto abort;
7613	}
7614	sc->sc_blk_ms = t;
7615	mode = 0;
7616	if (sc->sc_pmixer) {
7617		mode |= AUMODE_PLAY;
7618		phwfmt = sc->sc_pmixer->hwbuf.fmt;
7619	}
7620	if (sc->sc_rmixer) {
7621		mode |= AUMODE_RECORD;
7622		rhwfmt = sc->sc_rmixer->hwbuf.fmt;
7623	}
7624
7625	/* re-init hardware */
7626	memset(&pfil, 0, sizeof(pfil));
7627	memset(&rfil, 0, sizeof(rfil));
7628	error = audio_hw_set_format(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
7629	if (error) {
7630		goto abort;
7631	}
7632
7633	/* re-init track mixer */
7634	error = audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
7635	if (error) {
7636		/* Rollback */
7637		sc->sc_blk_ms = old_blk_ms;
7638		audio_mixers_init(sc, mode, &phwfmt, &rhwfmt, &pfil, &rfil);
7639		goto abort;
7640	}
7641	error = 0;
7642abort:
7643	audio_exlock_exit(sc);
7644	return error;
7645}
7646
7647/*
7648 * Get or set multiuser mode.
7649 */
7650static int
7651audio_sysctl_multiuser(SYSCTLFN_ARGS)
7652{
7653	struct sysctlnode node;
7654	struct audio_softc *sc;
7655	bool t;
7656	int error;
7657
7658	node = *rnode;
7659	sc = node.sysctl_data;
7660
7661	error = audio_exlock_enter(sc);
7662	if (error)
7663		return error;
7664
7665	t = sc->sc_multiuser;
7666	node.sysctl_data = &t;
7667	error = sysctl_lookup(SYSCTLFN_CALL(&node));
7668	if (error || newp == NULL)
7669		goto abort;
7670
7671	sc->sc_multiuser = t;
7672	error = 0;
7673abort:
7674	audio_exlock_exit(sc);
7675	return error;
7676}
7677
7678#if defined(AUDIO_DEBUG)
7679/*
7680 * Get or set debug verbose level. (0..4)
7681 * XXX It's for debug.
7682 * XXX It is not separated per device.
7683 */
7684static int
7685audio_sysctl_debug(SYSCTLFN_ARGS)
7686{
7687	struct sysctlnode node;
7688	int t;
7689	int error;
7690
7691	node = *rnode;
7692	t = audiodebug;
7693	node.sysctl_data = &t;
7694	error = sysctl_lookup(SYSCTLFN_CALL(&node));
7695	if (error || newp == NULL)
7696		return error;
7697
7698	if (t < 0 || t > 4)
7699		return EINVAL;
7700	audiodebug = t;
7701	printf("audio: audiodebug = %d\n", audiodebug);
7702	return 0;
7703}
7704#endif /* AUDIO_DEBUG */
7705
7706#ifdef AUDIO_PM_IDLE
7707static void
7708audio_idle(void *arg)
7709{
7710	device_t dv = arg;
7711	struct audio_softc *sc = device_private(dv);
7712
7713#ifdef PNP_DEBUG
7714	extern int pnp_debug_idle;
7715	if (pnp_debug_idle)
7716		printf("%s: idle handler called\n", device_xname(dv));
7717#endif
7718
7719	sc->sc_idle = true;
7720
7721	/* XXX joerg Make pmf_device_suspend handle children? */
7722	if (!pmf_device_suspend(dv, PMF_Q_SELF))
7723		return;
7724
7725	if (!pmf_device_suspend(sc->hw_dev, PMF_Q_SELF))
7726		pmf_device_resume(dv, PMF_Q_SELF);
7727}
7728
7729static void
7730audio_activity(device_t dv, devactive_t type)
7731{
7732	struct audio_softc *sc = device_private(dv);
7733
7734	if (type != DVA_SYSTEM)
7735		return;
7736
7737	callout_schedule(&sc->sc_idle_counter, audio_idle_timeout * hz);
7738
7739	sc->sc_idle = false;
7740	if (!device_is_active(dv)) {
7741		/* XXX joerg How to deal with a failing resume... */
7742		pmf_device_resume(sc->hw_dev, PMF_Q_SELF);
7743		pmf_device_resume(dv, PMF_Q_SELF);
7744	}
7745}
7746#endif
7747
7748static bool
7749audio_suspend(device_t dv, const pmf_qual_t *qual)
7750{
7751	struct audio_softc *sc = device_private(dv);
7752	int error;
7753
7754	error = audio_exlock_mutex_enter(sc);
7755	if (error)
7756		return error;
7757	audio_mixer_capture(sc);
7758
7759	if (sc->sc_pbusy) {
7760		audio_pmixer_halt(sc);
7761	}
7762	if (sc->sc_rbusy) {
7763		audio_rmixer_halt(sc);
7764	}
7765
7766#ifdef AUDIO_PM_IDLE
7767	callout_halt(&sc->sc_idle_counter, sc->sc_lock);
7768#endif
7769	audio_exlock_mutex_exit(sc);
7770
7771	return true;
7772}
7773
7774static bool
7775audio_resume(device_t dv, const pmf_qual_t *qual)
7776{
7777	struct audio_softc *sc = device_private(dv);
7778	struct audio_info ai;
7779	int error;
7780
7781	error = audio_exlock_mutex_enter(sc);
7782	if (error)
7783		return error;
7784
7785	audio_mixer_restore(sc);
7786	/* XXX ? */
7787	AUDIO_INITINFO(&ai);
7788	audio_hw_setinfo(sc, &ai, NULL);
7789
7790	if (!sc->sc_pbusy)
7791		audio_pmixer_start(sc, true);
7792	if (!sc->sc_rbusy && sc->sc_ropens > 0)
7793		audio_rmixer_start(sc);
7794
7795	audio_exlock_mutex_exit(sc);
7796
7797	return true;
7798}
7799
7800#if defined(AUDIO_DEBUG)
7801static void
7802audio_format2_tostr(char *buf, size_t bufsize, const audio_format2_t *fmt)
7803{
7804	int n;
7805
7806	n = 0;
7807	n += snprintf(buf + n, bufsize - n, "%s",
7808	    audio_encoding_name(fmt->encoding));
7809	if (fmt->precision == fmt->stride) {
7810		n += snprintf(buf + n, bufsize - n, " %dbit", fmt->precision);
7811	} else {
7812		n += snprintf(buf + n, bufsize - n, " %d/%dbit",
7813			fmt->precision, fmt->stride);
7814	}
7815
7816	snprintf(buf + n, bufsize - n, " %uch %uHz",
7817	    fmt->channels, fmt->sample_rate);
7818}
7819#endif
7820
7821#if defined(AUDIO_DEBUG)
7822static void
7823audio_print_format2(const char *s, const audio_format2_t *fmt)
7824{
7825	char fmtstr[64];
7826
7827	audio_format2_tostr(fmtstr, sizeof(fmtstr), fmt);
7828	printf("%s %s\n", s, fmtstr);
7829}
7830#endif
7831
7832#ifdef DIAGNOSTIC
7833void
7834audio_diagnostic_format2(const char *where, const audio_format2_t *fmt)
7835{
7836
7837	KASSERTMSG(fmt, "called from %s", where);
7838
7839	/* XXX MSM6258 vs(4) only has 4bit stride format. */
7840	if (fmt->encoding == AUDIO_ENCODING_ADPCM) {
7841		KASSERTMSG(fmt->stride == 4 || fmt->stride == 8,
7842		    "called from %s: fmt->stride=%d", where, fmt->stride);
7843	} else {
7844		KASSERTMSG(fmt->stride % NBBY == 0,
7845		    "called from %s: fmt->stride=%d", where, fmt->stride);
7846	}
7847	KASSERTMSG(fmt->precision <= fmt->stride,
7848	    "called from %s: fmt->precision=%d fmt->stride=%d",
7849	    where, fmt->precision, fmt->stride);
7850	KASSERTMSG(1 <= fmt->channels && fmt->channels <= AUDIO_MAX_CHANNELS,
7851	    "called from %s: fmt->channels=%d", where, fmt->channels);
7852
7853	/* XXX No check for encodings? */
7854}
7855
7856void
7857audio_diagnostic_filter_arg(const char *where, const audio_filter_arg_t *arg)
7858{
7859
7860	KASSERT(arg != NULL);
7861	KASSERT(arg->src != NULL);
7862	KASSERT(arg->dst != NULL);
7863	audio_diagnostic_format2(where, arg->srcfmt);
7864	audio_diagnostic_format2(where, arg->dstfmt);
7865	KASSERT(arg->count > 0);
7866}
7867
7868void
7869audio_diagnostic_ring(const char *where, const audio_ring_t *ring)
7870{
7871
7872	KASSERTMSG(ring, "called from %s", where);
7873	audio_diagnostic_format2(where, &ring->fmt);
7874	KASSERTMSG(0 <= ring->capacity && ring->capacity < INT_MAX / 2,
7875	    "called from %s: ring->capacity=%d", where, ring->capacity);
7876	KASSERTMSG(0 <= ring->used && ring->used <= ring->capacity,
7877	    "called from %s: ring->used=%d ring->capacity=%d",
7878	    where, ring->used, ring->capacity);
7879	if (ring->capacity == 0) {
7880		KASSERTMSG(ring->mem == NULL,
7881		    "called from %s: capacity == 0 but mem != NULL", where);
7882	} else {
7883		KASSERTMSG(ring->mem != NULL,
7884		    "called from %s: capacity != 0 but mem == NULL", where);
7885		KASSERTMSG(0 <= ring->head && ring->head < ring->capacity,
7886		    "called from %s: ring->head=%d ring->capacity=%d",
7887		    where, ring->head, ring->capacity);
7888	}
7889}
7890#endif /* DIAGNOSTIC */
7891
7892
7893/*
7894 * Mixer driver
7895 */
7896
7897/*
7898 * Must be called without sc_lock held.
7899 */
7900int
7901mixer_open(dev_t dev, struct audio_softc *sc, int flags, int ifmt,
7902	struct lwp *l)
7903{
7904	struct file *fp;
7905	audio_file_t *af;
7906	int error, fd;
7907
7908	TRACE(1, "flags=0x%x", flags);
7909
7910	error = fd_allocfile(&fp, &fd);
7911	if (error)
7912		return error;
7913
7914	af = kmem_zalloc(sizeof(*af), KM_SLEEP);
7915	af->sc = sc;
7916	af->dev = dev;
7917
7918	error = fd_clone(fp, fd, flags, &audio_fileops, af);
7919	KASSERT(error == EMOVEFD);
7920
7921	return error;
7922}
7923
7924/*
7925 * Add a process to those to be signalled on mixer activity.
7926 * If the process has already been added, do nothing.
7927 * Must be called with sc_exlock held and without sc_lock held.
7928 */
7929static void
7930mixer_async_add(struct audio_softc *sc, pid_t pid)
7931{
7932	int i;
7933
7934	KASSERT(sc->sc_exlock);
7935
7936	/* If already exists, returns without doing anything. */
7937	for (i = 0; i < sc->sc_am_used; i++) {
7938		if (sc->sc_am[i] == pid)
7939			return;
7940	}
7941
7942	/* Extend array if necessary. */
7943	if (sc->sc_am_used >= sc->sc_am_capacity) {
7944		sc->sc_am_capacity += AM_CAPACITY;
7945		sc->sc_am = kern_realloc(sc->sc_am,
7946		    sc->sc_am_capacity * sizeof(pid_t), M_WAITOK);
7947		TRACE(2, "realloc am_capacity=%d", sc->sc_am_capacity);
7948	}
7949
7950	TRACE(2, "am[%d]=%d", sc->sc_am_used, (int)pid);
7951	sc->sc_am[sc->sc_am_used++] = pid;
7952}
7953
7954/*
7955 * Remove a process from those to be signalled on mixer activity.
7956 * If the process has not been added, do nothing.
7957 * Must be called with sc_exlock held and without sc_lock held.
7958 */
7959static void
7960mixer_async_remove(struct audio_softc *sc, pid_t pid)
7961{
7962	int i;
7963
7964	KASSERT(sc->sc_exlock);
7965
7966	for (i = 0; i < sc->sc_am_used; i++) {
7967		if (sc->sc_am[i] == pid) {
7968			sc->sc_am[i] = sc->sc_am[--sc->sc_am_used];
7969			TRACE(2, "am[%d](%d) removed, used=%d",
7970			    i, (int)pid, sc->sc_am_used);
7971
7972			/* Empty array if no longer necessary. */
7973			if (sc->sc_am_used == 0) {
7974				kern_free(sc->sc_am);
7975				sc->sc_am = NULL;
7976				sc->sc_am_capacity = 0;
7977				TRACE(2, "released");
7978			}
7979			return;
7980		}
7981	}
7982}
7983
7984/*
7985 * Signal all processes waiting for the mixer.
7986 * Must be called with sc_exlock held.
7987 */
7988static void
7989mixer_signal(struct audio_softc *sc)
7990{
7991	proc_t *p;
7992	int i;
7993
7994	KASSERT(sc->sc_exlock);
7995
7996	for (i = 0; i < sc->sc_am_used; i++) {
7997		mutex_enter(&proc_lock);
7998		p = proc_find(sc->sc_am[i]);
7999		if (p)
8000			psignal(p, SIGIO);
8001		mutex_exit(&proc_lock);
8002	}
8003}
8004
8005/*
8006 * Close a mixer device
8007 */
8008int
8009mixer_close(struct audio_softc *sc, audio_file_t *file)
8010{
8011	int error;
8012
8013	error = audio_exlock_enter(sc);
8014	if (error)
8015		return error;
8016	TRACE(1, "");
8017	mixer_async_remove(sc, curproc->p_pid);
8018	audio_exlock_exit(sc);
8019
8020	return 0;
8021}
8022
8023/*
8024 * Must be called without sc_lock nor sc_exlock held.
8025 */
8026int
8027mixer_ioctl(struct audio_softc *sc, u_long cmd, void *addr, int flag,
8028	struct lwp *l)
8029{
8030	mixer_devinfo_t *mi;
8031	mixer_ctrl_t *mc;
8032	int error;
8033
8034	TRACE(2, "(%lu,'%c',%lu)",
8035	    IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd & 0xff);
8036	error = EINVAL;
8037
8038	/* we can return cached values if we are sleeping */
8039	if (cmd != AUDIO_MIXER_READ) {
8040		mutex_enter(sc->sc_lock);
8041		device_active(sc->sc_dev, DVA_SYSTEM);
8042		mutex_exit(sc->sc_lock);
8043	}
8044
8045	switch (cmd) {
8046	case FIOASYNC:
8047		error = audio_exlock_enter(sc);
8048		if (error)
8049			break;
8050		if (*(int *)addr) {
8051			mixer_async_add(sc, curproc->p_pid);
8052		} else {
8053			mixer_async_remove(sc, curproc->p_pid);
8054		}
8055		audio_exlock_exit(sc);
8056		break;
8057
8058	case AUDIO_GETDEV:
8059		TRACE(2, "AUDIO_GETDEV");
8060		mutex_enter(sc->sc_lock);
8061		error = sc->hw_if->getdev(sc->hw_hdl, (audio_device_t *)addr);
8062		mutex_exit(sc->sc_lock);
8063		break;
8064
8065	case AUDIO_MIXER_DEVINFO:
8066		TRACE(2, "AUDIO_MIXER_DEVINFO");
8067		mi = (mixer_devinfo_t *)addr;
8068
8069		mi->un.v.delta = 0; /* default */
8070		mutex_enter(sc->sc_lock);
8071		error = audio_query_devinfo(sc, mi);
8072		mutex_exit(sc->sc_lock);
8073		break;
8074
8075	case AUDIO_MIXER_READ:
8076		TRACE(2, "AUDIO_MIXER_READ");
8077		mc = (mixer_ctrl_t *)addr;
8078
8079		error = audio_exlock_mutex_enter(sc);
8080		if (error)
8081			break;
8082		if (device_is_active(sc->hw_dev))
8083			error = audio_get_port(sc, mc);
8084		else if (mc->dev < 0 || mc->dev >= sc->sc_nmixer_states)
8085			error = ENXIO;
8086		else {
8087			int dev = mc->dev;
8088			memcpy(mc, &sc->sc_mixer_state[dev],
8089			    sizeof(mixer_ctrl_t));
8090			error = 0;
8091		}
8092		audio_exlock_mutex_exit(sc);
8093		break;
8094
8095	case AUDIO_MIXER_WRITE:
8096		TRACE(2, "AUDIO_MIXER_WRITE");
8097		error = audio_exlock_mutex_enter(sc);
8098		if (error)
8099			break;
8100		error = audio_set_port(sc, (mixer_ctrl_t *)addr);
8101		if (error) {
8102			audio_exlock_mutex_exit(sc);
8103			break;
8104		}
8105
8106		if (sc->hw_if->commit_settings) {
8107			error = sc->hw_if->commit_settings(sc->hw_hdl);
8108			if (error) {
8109				audio_exlock_mutex_exit(sc);
8110				break;
8111			}
8112		}
8113		mutex_exit(sc->sc_lock);
8114		mixer_signal(sc);
8115		audio_exlock_exit(sc);
8116		break;
8117
8118	default:
8119		if (sc->hw_if->dev_ioctl) {
8120			mutex_enter(sc->sc_lock);
8121			error = sc->hw_if->dev_ioctl(sc->hw_hdl,
8122			    cmd, addr, flag, l);
8123			mutex_exit(sc->sc_lock);
8124		} else
8125			error = EINVAL;
8126		break;
8127	}
8128	TRACE(2, "(%lu,'%c',%lu) result %d",
8129	    IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd & 0xff, error);
8130	return error;
8131}
8132
8133/*
8134 * Must be called with sc_lock held.
8135 */
8136int
8137au_portof(struct audio_softc *sc, char *name, int class)
8138{
8139	mixer_devinfo_t mi;
8140
8141	KASSERT(mutex_owned(sc->sc_lock));
8142
8143	for (mi.index = 0; audio_query_devinfo(sc, &mi) == 0; mi.index++) {
8144		if (mi.mixer_class == class && strcmp(mi.label.name, name) == 0)
8145			return mi.index;
8146	}
8147	return -1;
8148}
8149
8150/*
8151 * Must be called with sc_lock held.
8152 */
8153void
8154au_setup_ports(struct audio_softc *sc, struct au_mixer_ports *ports,
8155	mixer_devinfo_t *mi, const struct portname *tbl)
8156{
8157	int i, j;
8158
8159	KASSERT(mutex_owned(sc->sc_lock));
8160
8161	ports->index = mi->index;
8162	if (mi->type == AUDIO_MIXER_ENUM) {
8163		ports->isenum = true;
8164		for(i = 0; tbl[i].name; i++)
8165		    for(j = 0; j < mi->un.e.num_mem; j++)
8166			if (strcmp(mi->un.e.member[j].label.name,
8167						    tbl[i].name) == 0) {
8168				ports->allports |= tbl[i].mask;
8169				ports->aumask[ports->nports] = tbl[i].mask;
8170				ports->misel[ports->nports] =
8171				    mi->un.e.member[j].ord;
8172				ports->miport[ports->nports] =
8173				    au_portof(sc, mi->un.e.member[j].label.name,
8174				    mi->mixer_class);
8175				if (ports->mixerout != -1 &&
8176				    ports->miport[ports->nports] != -1)
8177					ports->isdual = true;
8178				++ports->nports;
8179			}
8180	} else if (mi->type == AUDIO_MIXER_SET) {
8181		for(i = 0; tbl[i].name; i++)
8182		    for(j = 0; j < mi->un.s.num_mem; j++)
8183			if (strcmp(mi->un.s.member[j].label.name,
8184						tbl[i].name) == 0) {
8185				ports->allports |= tbl[i].mask;
8186				ports->aumask[ports->nports] = tbl[i].mask;
8187				ports->misel[ports->nports] =
8188				    mi->un.s.member[j].mask;
8189				ports->miport[ports->nports] =
8190				    au_portof(sc, mi->un.s.member[j].label.name,
8191				    mi->mixer_class);
8192				++ports->nports;
8193			}
8194	}
8195}
8196
8197/*
8198 * Must be called with sc_lock && sc_exlock held.
8199 */
8200int
8201au_set_lr_value(struct audio_softc *sc, mixer_ctrl_t *ct, int l, int r)
8202{
8203
8204	KASSERT(mutex_owned(sc->sc_lock));
8205	KASSERT(sc->sc_exlock);
8206
8207	ct->type = AUDIO_MIXER_VALUE;
8208	ct->un.value.num_channels = 2;
8209	ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT] = l;
8210	ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT] = r;
8211	if (audio_set_port(sc, ct) == 0)
8212		return 0;
8213	ct->un.value.num_channels = 1;
8214	ct->un.value.level[AUDIO_MIXER_LEVEL_MONO] = (l+r)/2;
8215	return audio_set_port(sc, ct);
8216}
8217
8218/*
8219 * Must be called with sc_lock && sc_exlock held.
8220 */
8221int
8222au_get_lr_value(struct audio_softc *sc, mixer_ctrl_t *ct, int *l, int *r)
8223{
8224	int error;
8225
8226	KASSERT(mutex_owned(sc->sc_lock));
8227	KASSERT(sc->sc_exlock);
8228
8229	ct->un.value.num_channels = 2;
8230	if (audio_get_port(sc, ct) == 0) {
8231		*l = ct->un.value.level[AUDIO_MIXER_LEVEL_LEFT];
8232		*r = ct->un.value.level[AUDIO_MIXER_LEVEL_RIGHT];
8233	} else {
8234		ct->un.value.num_channels = 1;
8235		error = audio_get_port(sc, ct);
8236		if (error)
8237			return error;
8238		*r = *l = ct->un.value.level[AUDIO_MIXER_LEVEL_MONO];
8239	}
8240	return 0;
8241}
8242
8243/*
8244 * Must be called with sc_lock && sc_exlock held.
8245 */
8246int
8247au_set_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
8248	int gain, int balance)
8249{
8250	mixer_ctrl_t ct;
8251	int i, error;
8252	int l, r;
8253	u_int mask;
8254	int nset;
8255
8256	KASSERT(mutex_owned(sc->sc_lock));
8257	KASSERT(sc->sc_exlock);
8258
8259	if (balance == AUDIO_MID_BALANCE) {
8260		l = r = gain;
8261	} else if (balance < AUDIO_MID_BALANCE) {
8262		l = gain;
8263		r = (balance * gain) / AUDIO_MID_BALANCE;
8264	} else {
8265		r = gain;
8266		l = ((AUDIO_RIGHT_BALANCE - balance) * gain)
8267		    / AUDIO_MID_BALANCE;
8268	}
8269	TRACE(2, "gain=%d balance=%d, l=%d r=%d", gain, balance, l, r);
8270
8271	if (ports->index == -1) {
8272	usemaster:
8273		if (ports->master == -1)
8274			return 0; /* just ignore it silently */
8275		ct.dev = ports->master;
8276		error = au_set_lr_value(sc, &ct, l, r);
8277	} else {
8278		ct.dev = ports->index;
8279		if (ports->isenum) {
8280			ct.type = AUDIO_MIXER_ENUM;
8281			error = audio_get_port(sc, &ct);
8282			if (error)
8283				return error;
8284			if (ports->isdual) {
8285				if (ports->cur_port == -1)
8286					ct.dev = ports->master;
8287				else
8288					ct.dev = ports->miport[ports->cur_port];
8289				error = au_set_lr_value(sc, &ct, l, r);
8290			} else {
8291				for(i = 0; i < ports->nports; i++)
8292				    if (ports->misel[i] == ct.un.ord) {
8293					    ct.dev = ports->miport[i];
8294					    if (ct.dev == -1 ||
8295						au_set_lr_value(sc, &ct, l, r))
8296						    goto usemaster;
8297					    else
8298						    break;
8299				    }
8300			}
8301		} else {
8302			ct.type = AUDIO_MIXER_SET;
8303			error = audio_get_port(sc, &ct);
8304			if (error)
8305				return error;
8306			mask = ct.un.mask;
8307			nset = 0;
8308			for(i = 0; i < ports->nports; i++) {
8309				if (ports->misel[i] & mask) {
8310				    ct.dev = ports->miport[i];
8311				    if (ct.dev != -1 &&
8312					au_set_lr_value(sc, &ct, l, r) == 0)
8313					    nset++;
8314				}
8315			}
8316			if (nset == 0)
8317				goto usemaster;
8318		}
8319	}
8320	if (!error)
8321		mixer_signal(sc);
8322	return error;
8323}
8324
8325/*
8326 * Must be called with sc_lock && sc_exlock held.
8327 */
8328void
8329au_get_gain(struct audio_softc *sc, struct au_mixer_ports *ports,
8330	u_int *pgain, u_char *pbalance)
8331{
8332	mixer_ctrl_t ct;
8333	int i, l, r, n;
8334	int lgain, rgain;
8335
8336	KASSERT(mutex_owned(sc->sc_lock));
8337	KASSERT(sc->sc_exlock);
8338
8339	lgain = AUDIO_MAX_GAIN / 2;
8340	rgain = AUDIO_MAX_GAIN / 2;
8341	if (ports->index == -1) {
8342	usemaster:
8343		if (ports->master == -1)
8344			goto bad;
8345		ct.dev = ports->master;
8346		ct.type = AUDIO_MIXER_VALUE;
8347		if (au_get_lr_value(sc, &ct, &lgain, &rgain))
8348			goto bad;
8349	} else {
8350		ct.dev = ports->index;
8351		if (ports->isenum) {
8352			ct.type = AUDIO_MIXER_ENUM;
8353			if (audio_get_port(sc, &ct))
8354				goto bad;
8355			ct.type = AUDIO_MIXER_VALUE;
8356			if (ports->isdual) {
8357				if (ports->cur_port == -1)
8358					ct.dev = ports->master;
8359				else
8360					ct.dev = ports->miport[ports->cur_port];
8361				au_get_lr_value(sc, &ct, &lgain, &rgain);
8362			} else {
8363				for(i = 0; i < ports->nports; i++)
8364				    if (ports->misel[i] == ct.un.ord) {
8365					    ct.dev = ports->miport[i];
8366					    if (ct.dev == -1 ||
8367						au_get_lr_value(sc, &ct,
8368								&lgain, &rgain))
8369						    goto usemaster;
8370					    else
8371						    break;
8372				    }
8373			}
8374		} else {
8375			ct.type = AUDIO_MIXER_SET;
8376			if (audio_get_port(sc, &ct))
8377				goto bad;
8378			ct.type = AUDIO_MIXER_VALUE;
8379			lgain = rgain = n = 0;
8380			for(i = 0; i < ports->nports; i++) {
8381				if (ports->misel[i] & ct.un.mask) {
8382					ct.dev = ports->miport[i];
8383					if (ct.dev == -1 ||
8384					    au_get_lr_value(sc, &ct, &l, &r))
8385						goto usemaster;
8386					else {
8387						lgain += l;
8388						rgain += r;
8389						n++;
8390					}
8391				}
8392			}
8393			if (n != 0) {
8394				lgain /= n;
8395				rgain /= n;
8396			}
8397		}
8398	}
8399bad:
8400	if (lgain == rgain) {	/* handles lgain==rgain==0 */
8401		*pgain = lgain;
8402		*pbalance = AUDIO_MID_BALANCE;
8403	} else if (lgain < rgain) {
8404		*pgain = rgain;
8405		/* balance should be > AUDIO_MID_BALANCE */
8406		*pbalance = AUDIO_RIGHT_BALANCE -
8407			(AUDIO_MID_BALANCE * lgain) / rgain;
8408	} else /* lgain > rgain */ {
8409		*pgain = lgain;
8410		/* balance should be < AUDIO_MID_BALANCE */
8411		*pbalance = (AUDIO_MID_BALANCE * rgain) / lgain;
8412	}
8413}
8414
8415/*
8416 * Must be called with sc_lock && sc_exlock held.
8417 */
8418int
8419au_set_port(struct audio_softc *sc, struct au_mixer_ports *ports, u_int port)
8420{
8421	mixer_ctrl_t ct;
8422	int i, error, use_mixerout;
8423
8424	KASSERT(mutex_owned(sc->sc_lock));
8425	KASSERT(sc->sc_exlock);
8426
8427	use_mixerout = 1;
8428	if (port == 0) {
8429		if (ports->allports == 0)
8430			return 0;		/* Allow this special case. */
8431		else if (ports->isdual) {
8432			if (ports->cur_port == -1) {
8433				return 0;
8434			} else {
8435				port = ports->aumask[ports->cur_port];
8436				ports->cur_port = -1;
8437				use_mixerout = 0;
8438			}
8439		}
8440	}
8441	if (ports->index == -1)
8442		return EINVAL;
8443	ct.dev = ports->index;
8444	if (ports->isenum) {
8445		if (port & (port-1))
8446			return EINVAL; /* Only one port allowed */
8447		ct.type = AUDIO_MIXER_ENUM;
8448		error = EINVAL;
8449		for(i = 0; i < ports->nports; i++)
8450			if (ports->aumask[i] == port) {
8451				if (ports->isdual && use_mixerout) {
8452					ct.un.ord = ports->mixerout;
8453					ports->cur_port = i;
8454				} else {
8455					ct.un.ord = ports->misel[i];
8456				}
8457				error = audio_set_port(sc, &ct);
8458				break;
8459			}
8460	} else {
8461		ct.type = AUDIO_MIXER_SET;
8462		ct.un.mask = 0;
8463		for(i = 0; i < ports->nports; i++)
8464			if (ports->aumask[i] & port)
8465				ct.un.mask |= ports->misel[i];
8466		if (port != 0 && ct.un.mask == 0)
8467			error = EINVAL;
8468		else
8469			error = audio_set_port(sc, &ct);
8470	}
8471	if (!error)
8472		mixer_signal(sc);
8473	return error;
8474}
8475
8476/*
8477 * Must be called with sc_lock && sc_exlock held.
8478 */
8479int
8480au_get_port(struct audio_softc *sc, struct au_mixer_ports *ports)
8481{
8482	mixer_ctrl_t ct;
8483	int i, aumask;
8484
8485	KASSERT(mutex_owned(sc->sc_lock));
8486	KASSERT(sc->sc_exlock);
8487
8488	if (ports->index == -1)
8489		return 0;
8490	ct.dev = ports->index;
8491	ct.type = ports->isenum ? AUDIO_MIXER_ENUM : AUDIO_MIXER_SET;
8492	if (audio_get_port(sc, &ct))
8493		return 0;
8494	aumask = 0;
8495	if (ports->isenum) {
8496		if (ports->isdual && ports->cur_port != -1) {
8497			if (ports->mixerout == ct.un.ord)
8498				aumask = ports->aumask[ports->cur_port];
8499			else
8500				ports->cur_port = -1;
8501		}
8502		if (aumask == 0)
8503			for(i = 0; i < ports->nports; i++)
8504				if (ports->misel[i] == ct.un.ord)
8505					aumask = ports->aumask[i];
8506	} else {
8507		for(i = 0; i < ports->nports; i++)
8508			if (ct.un.mask & ports->misel[i])
8509				aumask |= ports->aumask[i];
8510	}
8511	return aumask;
8512}
8513
8514/*
8515 * It returns 0 if success, otherwise errno.
8516 * Must be called only if sc->sc_monitor_port != -1.
8517 * Must be called with sc_lock && sc_exlock held.
8518 */
8519static int
8520au_set_monitor_gain(struct audio_softc *sc, int monitor_gain)
8521{
8522	mixer_ctrl_t ct;
8523
8524	KASSERT(mutex_owned(sc->sc_lock));
8525	KASSERT(sc->sc_exlock);
8526
8527	ct.dev = sc->sc_monitor_port;
8528	ct.type = AUDIO_MIXER_VALUE;
8529	ct.un.value.num_channels = 1;
8530	ct.un.value.level[AUDIO_MIXER_LEVEL_MONO] = monitor_gain;
8531	return audio_set_port(sc, &ct);
8532}
8533
8534/*
8535 * It returns monitor gain if success, otherwise -1.
8536 * Must be called only if sc->sc_monitor_port != -1.
8537 * Must be called with sc_lock && sc_exlock held.
8538 */
8539static int
8540au_get_monitor_gain(struct audio_softc *sc)
8541{
8542	mixer_ctrl_t ct;
8543
8544	KASSERT(mutex_owned(sc->sc_lock));
8545	KASSERT(sc->sc_exlock);
8546
8547	ct.dev = sc->sc_monitor_port;
8548	ct.type = AUDIO_MIXER_VALUE;
8549	ct.un.value.num_channels = 1;
8550	if (audio_get_port(sc, &ct))
8551		return -1;
8552	return ct.un.value.level[AUDIO_MIXER_LEVEL_MONO];
8553}
8554
8555/*
8556 * Must be called with sc_lock && sc_exlock held.
8557 */
8558static int
8559audio_set_port(struct audio_softc *sc, mixer_ctrl_t *mc)
8560{
8561
8562	KASSERT(mutex_owned(sc->sc_lock));
8563	KASSERT(sc->sc_exlock);
8564
8565	return sc->hw_if->set_port(sc->hw_hdl, mc);
8566}
8567
8568/*
8569 * Must be called with sc_lock && sc_exlock held.
8570 */
8571static int
8572audio_get_port(struct audio_softc *sc, mixer_ctrl_t *mc)
8573{
8574
8575	KASSERT(mutex_owned(sc->sc_lock));
8576	KASSERT(sc->sc_exlock);
8577
8578	return sc->hw_if->get_port(sc->hw_hdl, mc);
8579}
8580
8581/*
8582 * Must be called with sc_lock && sc_exlock held.
8583 */
8584static void
8585audio_mixer_capture(struct audio_softc *sc)
8586{
8587	mixer_devinfo_t mi;
8588	mixer_ctrl_t *mc;
8589
8590	KASSERT(mutex_owned(sc->sc_lock));
8591	KASSERT(sc->sc_exlock);
8592
8593	for (mi.index = 0;; mi.index++) {
8594		if (audio_query_devinfo(sc, &mi) != 0)
8595			break;
8596		KASSERT(mi.index < sc->sc_nmixer_states);
8597		if (mi.type == AUDIO_MIXER_CLASS)
8598			continue;
8599		mc = &sc->sc_mixer_state[mi.index];
8600		mc->dev = mi.index;
8601		mc->type = mi.type;
8602		mc->un.value.num_channels = mi.un.v.num_channels;
8603		(void)audio_get_port(sc, mc);
8604	}
8605
8606	return;
8607}
8608
8609/*
8610 * Must be called with sc_lock && sc_exlock held.
8611 */
8612static void
8613audio_mixer_restore(struct audio_softc *sc)
8614{
8615	mixer_devinfo_t mi;
8616	mixer_ctrl_t *mc;
8617
8618	KASSERT(mutex_owned(sc->sc_lock));
8619	KASSERT(sc->sc_exlock);
8620
8621	for (mi.index = 0; ; mi.index++) {
8622		if (audio_query_devinfo(sc, &mi) != 0)
8623			break;
8624		if (mi.type == AUDIO_MIXER_CLASS)
8625			continue;
8626		mc = &sc->sc_mixer_state[mi.index];
8627		(void)audio_set_port(sc, mc);
8628	}
8629	if (sc->hw_if->commit_settings)
8630		sc->hw_if->commit_settings(sc->hw_hdl);
8631
8632	return;
8633}
8634
8635static void
8636audio_volume_down(device_t dv)
8637{
8638	struct audio_softc *sc = device_private(dv);
8639	mixer_devinfo_t mi;
8640	int newgain;
8641	u_int gain;
8642	u_char balance;
8643
8644	if (audio_exlock_mutex_enter(sc) != 0)
8645		return;
8646	if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
8647		mi.index = sc->sc_outports.master;
8648		mi.un.v.delta = 0;
8649		if (audio_query_devinfo(sc, &mi) == 0) {
8650			au_get_gain(sc, &sc->sc_outports, &gain, &balance);
8651			newgain = gain - mi.un.v.delta;
8652			if (newgain < AUDIO_MIN_GAIN)
8653				newgain = AUDIO_MIN_GAIN;
8654			au_set_gain(sc, &sc->sc_outports, newgain, balance);
8655		}
8656	}
8657	audio_exlock_mutex_exit(sc);
8658}
8659
8660static void
8661audio_volume_up(device_t dv)
8662{
8663	struct audio_softc *sc = device_private(dv);
8664	mixer_devinfo_t mi;
8665	u_int gain, newgain;
8666	u_char balance;
8667
8668	if (audio_exlock_mutex_enter(sc) != 0)
8669		return;
8670	if (sc->sc_outports.index == -1 && sc->sc_outports.master != -1) {
8671		mi.index = sc->sc_outports.master;
8672		mi.un.v.delta = 0;
8673		if (audio_query_devinfo(sc, &mi) == 0) {
8674			au_get_gain(sc, &sc->sc_outports, &gain, &balance);
8675			newgain = gain + mi.un.v.delta;
8676			if (newgain > AUDIO_MAX_GAIN)
8677				newgain = AUDIO_MAX_GAIN;
8678			au_set_gain(sc, &sc->sc_outports, newgain, balance);
8679		}
8680	}
8681	audio_exlock_mutex_exit(sc);
8682}
8683
8684static void
8685audio_volume_toggle(device_t dv)
8686{
8687	struct audio_softc *sc = device_private(dv);
8688	u_int gain, newgain;
8689	u_char balance;
8690
8691	if (audio_exlock_mutex_enter(sc) != 0)
8692		return;
8693	au_get_gain(sc, &sc->sc_outports, &gain, &balance);
8694	if (gain != 0) {
8695		sc->sc_lastgain = gain;
8696		newgain = 0;
8697	} else
8698		newgain = sc->sc_lastgain;
8699	au_set_gain(sc, &sc->sc_outports, newgain, balance);
8700	audio_exlock_mutex_exit(sc);
8701}
8702
8703/*
8704 * Must be called with sc_lock held.
8705 */
8706static int
8707audio_query_devinfo(struct audio_softc *sc, mixer_devinfo_t *di)
8708{
8709
8710	KASSERT(mutex_owned(sc->sc_lock));
8711
8712	return sc->hw_if->query_devinfo(sc->hw_hdl, di);
8713}
8714
8715#endif /* NAUDIO > 0 */
8716
8717#if NAUDIO == 0 && (NMIDI > 0 || NMIDIBUS > 0)
8718#include <sys/param.h>
8719#include <sys/systm.h>
8720#include <sys/device.h>
8721#include <sys/audioio.h>
8722#include <dev/audio/audio_if.h>
8723#endif
8724
8725#if NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0)
8726int
8727audioprint(void *aux, const char *pnp)
8728{
8729	struct audio_attach_args *arg;
8730	const char *type;
8731
8732	if (pnp != NULL) {
8733		arg = aux;
8734		switch (arg->type) {
8735		case AUDIODEV_TYPE_AUDIO:
8736			type = "audio";
8737			break;
8738		case AUDIODEV_TYPE_MIDI:
8739			type = "midi";
8740			break;
8741		case AUDIODEV_TYPE_OPL:
8742			type = "opl";
8743			break;
8744		case AUDIODEV_TYPE_MPU:
8745			type = "mpu";
8746			break;
8747		default:
8748			panic("audioprint: unknown type %d", arg->type);
8749		}
8750		aprint_normal("%s at %s", type, pnp);
8751	}
8752	return UNCONF;
8753}
8754
8755#endif /* NAUDIO > 0 || (NMIDI > 0 || NMIDIBUS > 0) */
8756
8757#ifdef _MODULE
8758
8759devmajor_t audio_bmajor = -1, audio_cmajor = -1;
8760
8761#include "ioconf.c"
8762
8763#endif
8764
8765MODULE(MODULE_CLASS_DRIVER, audio, NULL);
8766
8767static int
8768audio_modcmd(modcmd_t cmd, void *arg)
8769{
8770	int error = 0;
8771
8772	switch (cmd) {
8773	case MODULE_CMD_INIT:
8774		/* XXX interrupt level? */
8775		audio_psref_class = psref_class_create("audio", IPL_SOFTSERIAL);
8776#ifdef _MODULE
8777		error = devsw_attach(audio_cd.cd_name, NULL, &audio_bmajor,
8778		    &audio_cdevsw, &audio_cmajor);
8779		if (error)
8780			break;
8781
8782		error = config_init_component(cfdriver_ioconf_audio,
8783		    cfattach_ioconf_audio, cfdata_ioconf_audio);
8784		if (error) {
8785			devsw_detach(NULL, &audio_cdevsw);
8786		}
8787#endif
8788		break;
8789	case MODULE_CMD_FINI:
8790#ifdef _MODULE
8791		devsw_detach(NULL, &audio_cdevsw);
8792		error = config_fini_component(cfdriver_ioconf_audio,
8793		   cfattach_ioconf_audio, cfdata_ioconf_audio);
8794		if (error)
8795			devsw_attach(audio_cd.cd_name, NULL, &audio_bmajor,
8796			    &audio_cdevsw, &audio_cmajor);
8797#endif
8798		psref_class_destroy(audio_psref_class);
8799		break;
8800	default:
8801		error = ENOTTY;
8802		break;
8803	}
8804
8805	return error;
8806}
8807