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