SchOS/kernel/dev/audio.c
Nexoniarz c77841ce3d Sound through ALSA, a 2D game, and a stack walk that cannot panic
SDL 3 has no OSS backend and SchOS has no ALSA kernel side, so sound now
goes SDL -> alsa-lib -> alsa-plugins' OSS plugin -> /dev/dsp. That path
found two bugs underneath it:

- ac97: resetting the PCM-out box also clears the descriptor list address,
  and nothing set it again. Every stream after the first stop played a
  "list" at physical address 0 -- silence -- and ALSA resets before each
  stream. If the engine halts at the end of the queue, the run bit is set
  again.
- /dev/dsp: SETFRAGMENT, GETFMTS, GETCAPS, SETTRIGGER, GETOPTR and GETODELAY
  for the plugin's ring-and-pointer model, and poll(), writable once a whole
  fragment fits (ALSA spun at 76% CPU otherwise). speaker-test now plays in
  real time at 0% CPU, verified in a recording of QEMU's AC'97.
- /etc/asound.conf: the default device is a plug to the OSS device at 16-bit
  stereo 48 kHz, what every SchOS audio driver plays.

Also:

- getstackpcs: each frame link must go up the same stack by less than
  KSTACKSIZE. The chain ends at the syscall entry with the user's rbp,
  which lbreakouthd uses as a register (-1024); the walk dereferenced it
  under the syscall tracer and the kernel panicked inside acquire().
- fb: FBIOGET_VSCREENINFO reports nominal timings, as Linux's efifb does,
  instead of zeros, which Xorg's fbdev turned into a 0 Hz RandR mode.
- procdump (Ctrl-P) shows where runnable threads are in user space.
- World: lbreakouthd instead of lbreakout2 (its stk.c passes vsnprintf a
  size of 511 plus the prefix length, and Alpine's fortified headers trap on
  that), plus curl, alsa-lib and alsa-plugins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S1giNvrHTrPMPw7V6x1kQ4
2026-10-25 05:39:16 +01:00

397 lines
11 KiB
C

// AudioEngine: the audio class, and /dev/dsp above it.
//
// See include/dev/audio.h for what this is and what it deliberately is not. In
// short: a program opens /dev/dsp, says what its samples are, writes them, and
// stops. Everything here is either the class vtable's thin wrapper or the part
// of "play this" that is not specific to a chip.
#include "core/types.h"
#include "core/defs.h"
#include "core/param.h"
#include "core/spinlock.h"
#include "core/sleeplock.h"
#include "fs/fs.h"
#include "fs/file.h"
#include "dev/device.h"
#include "dev/audio.h"
#include "core/proc.h"
#include "core/uaccess.h"
#include "uapi/errno.h"
static struct spinlock audio_lock;
static int audio_lock_init;
// The format the device is currently in. Kept here rather than asked of the
// driver on every write, because a caller that set 44100 and got 48000 needs
// to be told once and then have it stay told.
static struct audio_format current_fmt = { 48000, 2, AUDIO_FMT_S16LE };
// The OSS view of the stream, for clients that track a play pointer in a ring
// rather than just writing: bytes accepted by the driver since boot, where the
// last reset left the count, the ring geometry SETFRAGMENT asked for, and the
// played count GETOPTR last reported (for its fragment count).
static uint64 queued_total;
static uint64 reset_base;
static uint64 last_optr;
static int frag_size = 4096;
static int frag_count = 16;
static void
lock_once(void)
{
if (!audio_lock_init) {
initlock(&audio_lock, "audio");
audio_lock_init = 1;
}
}
// --- the class -------------------------------------------------------------
struct device *
audio_get(void)
{
return device_find_class(DEVCLASS_AUDIO);
}
static const struct audio_ops *
ops_of(struct device *d)
{
return d && d->ops ? (const struct audio_ops *)d->ops : 0;
}
int
audio_configure(struct audio_format *f)
{
struct device *d = audio_get();
const struct audio_ops *o = ops_of(d);
int r;
if (!o || !o->configure)
return -ENODEV;
if (f->bits != AUDIO_FMT_S16LE)
return -EINVAL;
if (f->channels != 1 && f->channels != 2)
return -EINVAL;
if (f->rate < 4000 || f->rate > 192000)
return -EINVAL;
r = o->configure(d, f);
if (r < 0)
return r;
lock_once();
acquire(&audio_lock);
current_fmt = *f; // what the driver settled on, not what was asked
release(&audio_lock);
return 0;
}
// Queue bytes, blocking while the hardware is full.
//
// The blocking is here rather than in a driver because it is the same in every
// driver: there is a ring, it has room or it does not, and a writer that is
// ahead of the speaker has nothing useful to do but wait. Sleeping on the
// device and being woken by its interrupt is the whole of it.
int
audio_write(const void *pcm, int bytes)
{
struct device *d = audio_get();
const struct audio_ops *o = ops_of(d);
const char *p = pcm;
int done = 0;
if (!o || !o->queue)
return -ENODEV;
if (bytes <= 0)
return 0;
while (done < bytes) {
int n = o->queue(d, p + done, bytes - done);
if (n < 0)
return done ? done : n;
if (n == 0) {
// Full. Start what is already queued -- a writer that fills the ring
// and then waits for space would otherwise wait for a stream nobody
// started -- and give the CPU up until some of it has been played.
if (o->start)
o->start(d);
if (myproc() && myproc()->killed)
return done ? done : -EINTR;
audio_wait(d);
continue;
}
done += n;
lock_once();
acquire(&audio_lock);
queued_total += (uint64)n;
release(&audio_lock);
}
if (o->start)
o->start(d);
return done;
}
// Wait for the hardware to make room. A driver signals this from its
// interrupt handler with audio_wakeup().
//
// The timeout is not a nicety: a driver whose interrupt never arrives -- a
// misrouted line, a chip that needs a kick -- would otherwise hang the writer
// for ever with no way to tell what happened. Waking up anyway and asking the
// hardware again turns that into audio that stutters, which is a bug report
// somebody can make.
void
audio_wait(struct device *d)
{
uint t0;
(void)d;
// One timer tick, the same way kernel/sys/sys_poll.c waits: there is no
// timed sleep() in this kernel, and adding one for a single caller would be
// a scheduler change to avoid a ten-line loop.
//
// Sleeping on `ticks` rather than on the device means a driver interrupt is
// not strictly required to make progress -- which is the point. A ring that
// drains is a ring that has room, and asking again in ten milliseconds
// costs one wakeup per buffer.
acquire(&tickslock);
t0 = ticks;
while (ticks == t0 && !(myproc() && myproc()->killed))
sleep(&ticks, &tickslock);
release(&tickslock);
}
void
audio_drain(void)
{
struct device *d = audio_get();
const struct audio_ops *o = ops_of(d);
int spins;
if (!o || !o->pending)
return;
// Bounded, for the same reason the wait above is. Ten seconds of audio is
// longer than any buffer this engine will hold, so a `pending` that has not
// reached zero by then is a driver that is not playing rather than one that
// is busy.
for (spins = 0; spins < 1000 && o->pending(d) > 0; spins++) {
if (myproc() && myproc()->killed)
return;
audio_wait(d);
}
}
void
audio_stop(void)
{
struct device *d = audio_get();
const struct audio_ops *o = ops_of(d);
if (o && o->stop)
o->stop(d);
}
// --- /dev/dsp ---------------------------------------------------------------
int
dspwrite(struct inode *ip, uint64 off, char *src, int n)
{
(void)ip; (void)off;
return audio_write(src, n);
}
// Recording is not implemented, and says so. Returning zero would look like
// end-of-file and a recorder would write an empty file and call it a success.
int
dspread(struct inode *ip, uint64 off, char *dst, int n)
{
(void)ip; (void)off; (void)dst; (void)n;
return -ENOSYS;
}
// The last descriptor is closing. Anything still queued is played out first:
// a program that writes a sound and exits expects to hear the end of it, and
// dropping the tail is the one behaviour that would make this device feel
// broken while technically working.
void
dspclose(struct inode *ip)
{
(void)ip;
audio_drain();
audio_stop();
}
// Bytes the speaker has played since boot: everything queued, less what is
// still waiting. A reset discards the waiting part, which then counts as played
// -- the count only goes forward, and GETOPTR measures from the reset.
static uint64
played_total(struct device *d, const struct audio_ops *o)
{
uint64 q, p;
int pend = o->pending ? o->pending(d) : 0;
lock_once();
acquire(&audio_lock);
q = queued_total;
release(&audio_lock);
p = (pend > 0 && (uint64)pend <= q) ? q - (uint64)pend : q;
return p;
}
// Writable once a whole fragment fits, as OSS defines it. ALSA's plugin sets
// the fragment to its period and waits in poll() for one to be free; reporting
// writable at the first free byte had it wake, find less than a period of
// room, and poll again -- 76% of a CPU to play a sine wave.
int
dsp_writable(void)
{
struct device *d = audio_get();
const struct audio_ops *o = ops_of(d);
int want;
if (!o || !o->space)
return 0;
lock_once();
acquire(&audio_lock);
want = frag_size;
release(&audio_lock);
if (want > 65536)
want = 65536; // never more than a driver's ring can free at once
return o->space(d) >= want;
}
int
dsp_ioctl(int request, uint64 argp)
{
struct device *d = audio_get();
const struct audio_ops *o = ops_of(d);
struct audio_format f;
int val;
if (!o)
return -ENODEV;
lock_once();
acquire(&audio_lock);
f = current_fmt;
release(&audio_lock);
switch (request) {
case SNDCTL_DSP_SPEED:
case SNDCTL_DSP_CHANNELS:
case SNDCTL_DSP_SETFMT: {
if (copy_from_user(&val, argp, sizeof(val)) < 0)
return -EFAULT;
if (request == SNDCTL_DSP_SPEED) f.rate = (unsigned)val;
else if (request == SNDCTL_DSP_CHANNELS) f.channels = (unsigned)val;
else {
if (val != AFMT_S16_LE)
return -EINVAL;
f.bits = AUDIO_FMT_S16LE;
}
int r = audio_configure(&f);
if (r < 0)
return r;
// OSS writes back what was actually set, which is the entire reason these
// are read/write ioctls: a program asks for 44100, is told 48000, and
// resamples. One that ignores the answer gets a chipmunk, and that is its
// bug rather than ours.
val = (request == SNDCTL_DSP_SPEED) ? (int)f.rate
: (request == SNDCTL_DSP_CHANNELS) ? (int)f.channels
: AFMT_S16_LE;
if (copy_to_user(argp, &val, sizeof(val)) < 0)
return -EFAULT;
return 0;
}
case SNDCTL_DSP_SYNC:
audio_drain();
return 0;
case SNDCTL_DSP_RESET: {
audio_stop();
uint64 p = played_total(d, o);
acquire(&audio_lock);
reset_base = last_optr = p;
release(&audio_lock);
return 0;
}
// The ring the client thinks in. The driver's own ring is whatever it is;
// these only shape the numbers GETOPTR and GETOSPACE report, which is all a
// client does with them. Fragments of 256 bytes to 64 KiB, 2 to 1024 of them.
case SNDCTL_DSP_SETFRAGMENT: {
if (copy_from_user(&val, argp, sizeof(val)) < 0)
return -EFAULT;
int shift = val & 0xffff, count = (val >> 16) & 0xffff;
if (shift < 8) shift = 8;
if (shift > 16) shift = 16;
if (count < 2) count = 2;
if (count > 1024 || count == 0x7fff) count = 1024;
acquire(&audio_lock);
frag_size = 1 << shift;
frag_count = count;
release(&audio_lock);
val = (count << 16) | shift;
return copy_to_user(argp, &val, sizeof(val)) < 0 ? -EFAULT : 0;
}
case SNDCTL_DSP_GETFMTS:
val = AFMT_S16_LE;
return copy_to_user(argp, &val, sizeof(val)) < 0 ? -EFAULT : 0;
case SNDCTL_DSP_GETCAPS:
val = DSP_CAP_TRIGGER;
return copy_to_user(argp, &val, sizeof(val)) < 0 ? -EFAULT : 0;
// Enabling output starts whatever is queued. Disabling is accepted and does
// nothing: the stream stops by itself when the queue runs dry, and stopping
// it here would throw away what is queued, which a pause must not.
case SNDCTL_DSP_SETTRIGGER:
if (copy_from_user(&val, argp, sizeof(val)) < 0)
return -EFAULT;
if ((val & PCM_ENABLE_OUTPUT) && o->start)
o->start(d);
return 0;
case SNDCTL_DSP_GETOPTR: {
struct count_info ci;
uint64 p = played_total(d, o);
acquire(&audio_lock);
uint64 since = p - reset_base;
uint64 ring = (uint64)frag_size * (uint64)frag_count;
ci.bytes = (int)since;
ci.blocks = (int)((p - last_optr) / (uint64)frag_size);
ci.ptr = (int)(since % ring);
last_optr = p;
release(&audio_lock);
return copy_to_user(argp, &ci, sizeof(ci)) < 0 ? -EFAULT : 0;
}
case SNDCTL_DSP_GETODELAY:
val = o->pending ? o->pending(d) : 0;
return copy_to_user(argp, &val, sizeof(val)) < 0 ? -EFAULT : 0;
case SNDCTL_DSP_GETOSPACE: {
struct audio_buf_info bi;
int space = o->space ? o->space(d) : 0;
bi.fragsize = frag_size;
bi.bytes = space;
bi.fragments = space / bi.fragsize;
bi.fragstotal = frag_count;
if (copy_to_user(argp, &bi, sizeof(bi)) < 0)
return -EFAULT;
return 0;
}
}
return -ENOTTY;
}