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