Files
unkernel/kernel/patches/linux/0023-wasm-kwsnd-ALSA-playback-to-the-JavaScript-host.patch
Pooya Parsa 951bb8e5dd kernel: let kwsnd periods go down to 2 ms, in a buffer of 10 ms or more (#22)
The shortest period and tick drop from 5 ms to 2 ms for programs that
ask for low latency. A buffer is 10 ms or more as before (two 5 ms
periods), and a late tick still hands over up to 15 ms' worth when ticks
are shorter than 5 ms, so a short period tolerates the same host stall.
Programs that leave the period to alsa-lib, plain aplay, OSS without
SETFRAGMENT and requests of 256 frames or more negotiate what they did;
snd_pcm_set_params() with a latency under 20 ms now gets four periods of
2.5 to 3.75 ms (measured on Node, 2026-11-24).

Co-authored-by: Adam Meghji <566793+adammeghji@users.noreply.github.com>
2026-11-24 16:25:03 +00:00

449 lines
16 KiB
Diff

From 56cc67bbc6080a15e42d6c8aa5d7a66c6d10657c Mon Sep 17 00:00:00 2001
From: Pooya Parsa <pooya@pi0.io>
Date: Sun, 15 Nov 2026 10:16:10 +0000
Subject: [PATCH] wasm: kwsnd, ALSA playback to the JavaScript host
A playback-only ALSA PCM for programs that play sound, registered only
when the host has audio (wasm_driver_sound_init() < 0 means none, so a
normal boot only pays for the code). With audio it is card 0 with one
PCM (hw:0,0: /dev/snd/pcmC0D0p and controlC0), no mixer and no capture:
U8 and S16_LE, mono or stereo, 8000-48000 Hz (continuous), up to 64 KiB
of buffer, periods of 2 ms or more in a buffer of 10 ms or more.
alsa-lib's default device for an unknown card is plug:hw, so no PCM
timer (dmix) is needed. The init import also returns the host's
preferred rate, which the card's long name shows.
Nothing runs and nothing beyond the card is allocated until a program
opens the PCM: the per-open state is allocated at open, and the ring is
ALSA's managed buffer (SNDRV_DMA_TYPE_CONTINUOUS, allocated at
hw_params), which is direct-mapped, so the host reads it at a plain
linear address and mmap works through remap_pfn_range.
An hrtimer on CLOCK_MONOTONIC (the host's monotonic clock) paces the
stream every 2 to 10 ms (the period time, clamped). Each tick hands the
frames the elapsed time is worth to wasm_driver_sound_write(), which
copies them out during the call, and advances the hardware pointer by
as much; the host's return value (frames it still has queued) becomes
runtime->delay. Frames past appl_ptr are never sent unless the stream
fills silence: the pointer still advances, so the core sees an underrun
and stops the stream, and the host plays silence. A late tick (a long
stay in the kernel) advances by three ticks' worth at most, or 15 ms'
worth with ticks shorter than 5 ms, and skips the rest, so the queued
frames play on at the normal pace rather than being rushed out, and the
pointer never moves by a whole buffer.
wasm_driver_sound_event() reports open, prepare (rate, channels,
format), start, stop (and whether it was the end of a drain) and close.
No import suspends.
On the lowered kernel this adds 142 KiB (49 KiB with gzip -9), of which
OSS PCM emulation (/dev/dsp, which static SDL 1.2 builds use) is 29 KiB
(9 KiB).
---
sound/drivers/Kconfig | 9 ++
sound/drivers/Makefile | 2 +
sound/drivers/kwsnd.c | 351 +++++++++++++++++++++++++++++++++++++++++
3 files changed, 362 insertions(+)
create mode 100644 sound/drivers/kwsnd.c
diff --git a/sound/drivers/Kconfig b/sound/drivers/Kconfig
index 6debd8e95cb..56fcfaa54c5 100644
--- a/sound/drivers/Kconfig
+++ b/sound/drivers/Kconfig
@@ -76,6 +76,15 @@ config SND_PCSP
Say M if you don't.
Say Y only if you really know what you do.
+config SND_KWSND
+ tristate "unkernel host audio"
+ depends on WASM
+ select SND_PCM
+ help
+ A playback-only PCM whose samples go to the JavaScript host of a
+ unkernel instance (js/core/sound.ts). The card is registered only
+ when the host has audio.
+
config SND_DUMMY
tristate "Dummy (/dev/null) soundcard"
select SND_PCM
diff --git a/sound/drivers/Makefile b/sound/drivers/Makefile
index a08bdd70ec9..a5abb0cf1ad 100644
--- a/sound/drivers/Makefile
+++ b/sound/drivers/Makefile
@@ -5,6 +5,7 @@
#
snd-dummy-y := dummy.o
+snd-kwsnd-y := kwsnd.o
snd-aloop-y := aloop.o
snd-mtpav-y := mtpav.o
snd-mts64-y := mts64.o
@@ -16,6 +17,7 @@ snd-virmidi-y := virmidi.o
# Toplevel Module Dependency
obj-$(CONFIG_SND_DUMMY) += snd-dummy.o
+obj-$(CONFIG_SND_KWSND) += snd-kwsnd.o
obj-$(CONFIG_SND_ALOOP) += snd-aloop.o
obj-$(CONFIG_SND_VIRMIDI) += snd-virmidi.o
obj-$(CONFIG_SND_PCMTEST) += snd-pcmtest.o
diff --git a/sound/drivers/kwsnd.c b/sound/drivers/kwsnd.c
new file mode 100644
index 00000000000..a10a5442ac6
--- /dev/null
+++ b/sound/drivers/kwsnd.c
@@ -0,0 +1,351 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * kwsnd: ALSA playback to the JavaScript host (unkernel).
+ *
+ * One card with one playback PCM (hw:0,0; /dev/snd/pcmC0D0p and
+ * controlC0), registered only when the host has audio
+ * (wasm_driver_sound_init() < 0 means none). No mixer, no capture.
+ *
+ * Nothing runs and nothing beyond the card is allocated until a program
+ * opens the PCM: the ring buffer is ALSA's managed buffer (one physically
+ * contiguous allocation at hw_params, freed at hw_free), so the host gets a
+ * plain linear address.
+ *
+ * Playback is paced by an hrtimer on CLOCK_MONOTONIC, which is the host's
+ * monotonic clock (WASI clock_time_get), every 2 to 10 ms (the period time,
+ * clamped). Each tick works out how many frames the elapsed time is worth,
+ * hands that many frames of the ring to the host with
+ * wasm_driver_sound_write() (the host copies them out during the call) and
+ * advances the hardware pointer by the same amount. So the pointer always
+ * means "the host has these frames"; the host's own queue (its return
+ * value, reported as runtime->delay) adds the rest of the latency. The
+ * host plays on its own clock and absorbs the drift between the two.
+ *
+ * Data the program has not written yet is never sent: when the elapsed
+ * time is worth more than the queued frames, the pointer still advances
+ * (so the core sees the underrun and stops the stream, or, with silence
+ * filling as dmix uses, keeps running) but only the written part goes to
+ * the host, which plays silence for the rest. A tick that comes late (a
+ * long stay in the kernel, a host that did not run) advances by three
+ * ticks' worth at most (15 ms' worth with ticks shorter than 5 ms, so a
+ * short period tolerates the same stall) and skips the rest of the missed
+ * time: the queued frames then play on at the normal pace instead of being
+ * rushed out, the program sees no underrun from the stall alone, and the
+ * pointer never moves by a whole buffer, which the core cannot see.
+ *
+ * A tick reports to the core (snd_pcm_period_elapsed()) only when the
+ * pointer crossed a period boundary or reached appl_ptr (the end of a
+ * drain, an underrun). The core takes each report for a whole period, and
+ * one that falls short of the next boundary more than half a buffer after
+ * the pointer last moved (the first tick after a stall, when a period is
+ * longer than three ticks) for a missed buffer: it would add a buffer to
+ * the pointer and stop the stream. Between reports the core reads the
+ * pointer only when the program calls it, so a tick works from its own
+ * position, not the core's hw_ptr.
+ *
+ * The host is told about every state change with wasm_driver_sound_event():
+ * open, prepare (rate, channels, format), start, stop (drain or not) and
+ * close. No import suspends.
+ */
+
+#include <linux/hrtimer.h>
+#include <linux/init.h>
+#include <linux/math64.h>
+#include <linux/module.h>
+#include <linux/slab.h>
+#include <sound/core.h>
+#include <sound/pcm.h>
+#include <asm/wasm.h>
+
+/* Events for wasm_driver_sound_event(). */
+#define KWSND_EV_CLOSE 0
+#define KWSND_EV_OPEN 1
+#define KWSND_EV_PREPARE 2 /* rate, channels, format (SNDRV_PCM_FORMAT_*) */
+#define KWSND_EV_START 3
+#define KWSND_EV_STOP 4 /* rate = 1 when the stream drained */
+
+#define KWSND_TICK_MIN_NS (2 * NSEC_PER_MSEC)
+#define KWSND_TICK_MAX_NS (10 * NSEC_PER_MSEC)
+/* The shortest buffer: a short period is no reason for less slack. */
+#define KWSND_BUFFER_MIN_NS (10 * NSEC_PER_MSEC)
+/* A late tick hands over this much at least, however short the tick. */
+#define KWSND_BURST_MIN_NS (15 * NSEC_PER_MSEC)
+
+/* Host imports, module "unkernel". None of them suspends. */
+/* < 0: no audio. Else the host's preferred rate in Hz (0: no preference). */
+long wasm_driver_sound_init(void)
+ __unkernel_import(wasm_driver_sound_init);
+void wasm_driver_sound_event(u32 event, u32 rate, u32 channels, u32 format)
+ __unkernel_import(wasm_driver_sound_event);
+/* Copy @bytes of PCM at @buf; returns the frames the host now has queued. */
+long wasm_driver_sound_write(const void *buf, long bytes)
+ __unkernel_import(wasm_driver_sound_write);
+
+struct kwsnd_stream {
+ struct snd_pcm_substream *substream;
+ struct hrtimer timer;
+ ktime_t base; /* when frame 0 was due */
+ u64 played; /* frames handed to the host since start */
+ u32 pos0; /* the hardware position at start */
+ u64 tick_ns;
+ u32 burst; /* most frames one tick hands over */
+ bool running;
+};
+
+static const struct snd_pcm_hardware kwsnd_hw = {
+ .info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID |
+ SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER,
+ .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_U8,
+ .rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
+ .rate_min = 8000,
+ .rate_max = 48000,
+ .channels_min = 1,
+ .channels_max = 2,
+ .buffer_bytes_max = 64 * 1024,
+ .period_bytes_min = 64,
+ .period_bytes_max = 32 * 1024,
+ .periods_min = 2,
+ .periods_max = 1024,
+};
+
+/* Hand @frames frames from ring position @pos on to the host. */
+static void kwsnd_push(struct snd_pcm_runtime *runtime, snd_pcm_uframes_t pos,
+ snd_pcm_uframes_t frames)
+{
+ long queued = -1;
+
+ while (frames) {
+ snd_pcm_uframes_t n = min(frames, runtime->buffer_size - pos);
+
+ queued = wasm_driver_sound_write(runtime->dma_area +
+ frames_to_bytes(runtime, pos),
+ frames_to_bytes(runtime, n));
+ frames -= n;
+ pos = 0;
+ }
+ if (queued >= 0)
+ runtime->delay = queued;
+}
+
+static enum hrtimer_restart kwsnd_tick(struct hrtimer *timer)
+{
+ struct kwsnd_stream *s = container_of(timer, struct kwsnd_stream, timer);
+ struct snd_pcm_runtime *runtime = s->substream->runtime;
+ ktime_t now = ktime_get();
+ u64 due, want;
+ unsigned long flags;
+
+ snd_pcm_stream_lock_irqsave(s->substream, flags);
+ if (!s->running)
+ goto stopped;
+
+ due = div_u64(ktime_to_ns(ktime_sub(now, s->base)) * runtime->rate,
+ NSEC_PER_SEC);
+ want = due > s->played ? due - s->played : 0;
+ if (want > s->burst) {
+ /*
+ * Late by more than the burst (a long stay in the kernel, a host
+ * that did not run): skip the missed time instead of catching up,
+ * so the queued frames still play at the normal pace.
+ */
+ want = s->burst;
+ s->base = ktime_sub_ns(now, div_u64((s->played + want) *
+ NSEC_PER_SEC, runtime->rate));
+ }
+ if (want) {
+ u64 pos = s->pos0 + s->played; /* period-aligned like hw_ptr */
+ u32 ring, ahead;
+ snd_pcm_sframes_t queued;
+ u64 send = want;
+ bool report;
+
+ /*
+ * The core's hw_ptr is where the pointer was at the last report
+ * or call from the program, less than a period ago: the frames
+ * the program has queued start @ahead frames after it.
+ */
+ div_u64_rem(pos, runtime->buffer_size, &ring);
+ ahead = (ring + runtime->buffer_size -
+ runtime->status->hw_ptr % runtime->buffer_size) %
+ runtime->buffer_size;
+ queued = snd_pcm_playback_hw_avail(runtime) - ahead;
+ /* Without silence filling, frames past appl_ptr are stale. */
+ if (!runtime->silence_size && send > (u64)max_t(snd_pcm_sframes_t, queued, 0))
+ send = max_t(snd_pcm_sframes_t, queued, 0);
+ kwsnd_push(runtime, ring, send);
+ s->played += want;
+ /*
+ * A period ended, or the pointer reached appl_ptr: the end of a
+ * drain, or an underrun, which the core must see now, before a
+ * write in progress (it copies without the lock) moves appl_ptr
+ * past frames the pointer has gone by without sending them.
+ */
+ report = div_u64(pos, runtime->period_size) !=
+ div_u64(pos + want, runtime->period_size) ||
+ (snd_pcm_sframes_t)want >= queued;
+ /* May stop the stream (underrun, drain done): see kwsnd_trigger. */
+ if (report)
+ snd_pcm_period_elapsed_under_stream_lock(s->substream);
+ }
+ if (!s->running)
+ goto stopped;
+ snd_pcm_stream_unlock_irqrestore(s->substream, flags);
+ hrtimer_forward_now(timer, ns_to_ktime(s->tick_ns));
+ return HRTIMER_RESTART;
+stopped:
+ snd_pcm_stream_unlock_irqrestore(s->substream, flags);
+ return HRTIMER_NORESTART;
+}
+
+static int kwsnd_open(struct snd_pcm_substream *substream)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct kwsnd_stream *s;
+ int err;
+
+ s = kzalloc_obj(*s);
+ if (!s)
+ return -ENOMEM;
+ s->substream = substream;
+ hrtimer_setup(&s->timer, kwsnd_tick, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
+ runtime->hw = kwsnd_hw;
+ /* These return 1 when they narrowed the range. */
+ err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
+ if (err >= 0)
+ /* No period shorter than the shortest tick. */
+ err = snd_pcm_hw_constraint_minmax(runtime,
+ SNDRV_PCM_HW_PARAM_PERIOD_TIME,
+ KWSND_TICK_MIN_NS / NSEC_PER_USEC,
+ UINT_MAX);
+ if (err >= 0)
+ err = snd_pcm_hw_constraint_minmax(runtime,
+ SNDRV_PCM_HW_PARAM_BUFFER_TIME,
+ KWSND_BUFFER_MIN_NS / NSEC_PER_USEC,
+ UINT_MAX);
+ if (err < 0) {
+ kfree(s);
+ return err;
+ }
+ runtime->private_data = s;
+ wasm_driver_sound_event(KWSND_EV_OPEN, 0, 0, 0);
+ return 0;
+}
+
+static int kwsnd_close(struct snd_pcm_substream *substream)
+{
+ struct kwsnd_stream *s = substream->runtime->private_data;
+
+ hrtimer_cancel(&s->timer);
+ kfree(s);
+ wasm_driver_sound_event(KWSND_EV_CLOSE, 0, 0, 0);
+ return 0;
+}
+
+static int kwsnd_prepare(struct snd_pcm_substream *substream)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct kwsnd_stream *s = runtime->private_data;
+ u64 period_ns = div_u64((u64)runtime->period_size * NSEC_PER_SEC,
+ runtime->rate);
+
+ hrtimer_cancel(&s->timer);
+ s->tick_ns = clamp_t(u64, period_ns, KWSND_TICK_MIN_NS, KWSND_TICK_MAX_NS);
+ s->burst = min_t(u64, runtime->buffer_size - 1,
+ div_u64(max_t(u64, 3 * s->tick_ns, KWSND_BURST_MIN_NS) *
+ runtime->rate, NSEC_PER_SEC));
+ runtime->delay = 0;
+ wasm_driver_sound_event(KWSND_EV_PREPARE, runtime->rate,
+ runtime->channels, runtime->format);
+ return 0;
+}
+
+/*
+ * Called with the stream lock held, possibly from kwsnd_tick itself (an
+ * underrun or the end of a drain), whose callback then returns
+ * HRTIMER_NORESTART.
+ */
+static int kwsnd_trigger(struct snd_pcm_substream *substream, int cmd)
+{
+ struct snd_pcm_runtime *runtime = substream->runtime;
+ struct kwsnd_stream *s = runtime->private_data;
+
+ switch (cmd) {
+ case SNDRV_PCM_TRIGGER_START:
+ s->base = ktime_get();
+ s->played = 0;
+ s->pos0 = runtime->status->hw_ptr % runtime->buffer_size;
+ s->running = true;
+ hrtimer_start(&s->timer, ns_to_ktime(s->tick_ns), HRTIMER_MODE_REL);
+ wasm_driver_sound_event(KWSND_EV_START, 0, 0, 0);
+ return 0;
+ case SNDRV_PCM_TRIGGER_STOP:
+ s->running = false;
+ hrtimer_try_to_cancel(&s->timer);
+ wasm_driver_sound_event(KWSND_EV_STOP,
+ runtime->state == SNDRV_PCM_STATE_DRAINING,
+ 0, 0);
+ return 0;
+ }
+ return -EINVAL;
+}
+
+static snd_pcm_uframes_t kwsnd_pointer(struct snd_pcm_substream *substream)
+{
+ struct kwsnd_stream *s = substream->runtime->private_data;
+ u32 pos;
+
+ div_u64_rem(s->pos0 + s->played, substream->runtime->buffer_size, &pos);
+ return pos;
+}
+
+static const struct snd_pcm_ops kwsnd_ops = {
+ .open = kwsnd_open,
+ .close = kwsnd_close,
+ .prepare = kwsnd_prepare,
+ .trigger = kwsnd_trigger,
+ .pointer = kwsnd_pointer,
+};
+
+static int __init kwsnd_init(void)
+{
+ struct snd_card *card;
+ struct snd_pcm *pcm;
+ long pref = wasm_driver_sound_init();
+ int err;
+
+ if (pref < 0) {
+ pr_info("kwsnd: no host audio\n");
+ return 0;
+ }
+ err = snd_card_new(NULL, -1, "kwsnd", THIS_MODULE, 0, &card);
+ if (err)
+ return err;
+ strscpy(card->driver, "kwsnd");
+ strscpy(card->shortname, "unkernel audio");
+ /* Programs may pick any rate; this is the one the host plays natively. */
+ if (pref)
+ snprintf(card->longname, sizeof(card->longname),
+ "unkernel host audio, %ld Hz preferred", pref);
+ else
+ strscpy(card->longname, "unkernel host audio");
+
+ err = snd_pcm_new(card, "kwsnd", 0, 1, 0, &pcm);
+ if (err)
+ goto err_free;
+ strscpy(pcm->name, "unkernel host audio");
+ snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &kwsnd_ops);
+ /* No preallocation: allocated at hw_params, up to the maximum. */
+ snd_pcm_set_managed_buffer_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS, NULL,
+ 0, kwsnd_hw.buffer_bytes_max);
+
+ err = snd_card_register(card);
+ if (err)
+ goto err_free;
+ pr_info("kwsnd: %s\n", card->longname);
+ return 0;
+
+err_free:
+ snd_card_free(card);
+ return err;
+}
+device_initcall(kwsnd_init);
--
2.56.0