Skip to content

smp: keep guest clocks monotonic across workers - #94

Open
Crashel1 wants to merge 7 commits into
pithings:mainfrom
Crashel1:fix/smp-monotonic-clock
Open

Crashel1 wants to merge 7 commits into
pithings:mainfrom
Crashel1:fix/smp-monotonic-clock

Conversation

@Crashel1

@Crashel1 Crashel1 commented Nov 29, 2026 •

Copy link
Copy Markdown

Problem

Two independent failure modes can make the SMP guest clock go backwards. This PR addresses the original worker clock-sampling and cross-CPU ordering issue. A separate Binaryen miscompile can also cause a backwards step by removing memory fences used by the kernel timekeeper. The compiler bug and its upstream fix are documented below.

An Alpine guest running with two vCPUs in iOS 27.1 WKWebView can observe negative deltas from direct clock_gettime system calls. A worker computing performance.timeOrigin + performance.now() - epochMs on each read has two problems: WebKit can vary the sampled timeOrigin, and adding a Unix epoch before subtracting it loses precision. Freezing the origin alone still permits a small backwards step when a task switches CPUs and their calibrations disagree.

Change

  • Calibrate each secondary worker once, using an origin delta relative to CPU 0, then calculate in the small relative-time domain.
  • Feed the CPU 0 and secondary non-realtime imports from one atomic nanosecond high-water mark. A lagging sample returns the last published value instead of inventing elapsed time.
  • Retain the allocation-free UP path, direct realtime sampling, and the existing snapshot resume and held-VM adjustment behavior.

Kernel clock fast path and benchmark

The SMP kernel now clamps each numeric host clock sample against a shared watermark. This removes the WASI scratch-buffer round trip and BigInt arithmetic from each guest clock read when the kernel exposes the fast path.

On a Linux host with six guest vCPUs, the median time for 3.5 million four-thread sysbench threads events fell from 2.93 s to 2.35 s in Chromium and from 2.17 s to 1.77 s in WebKitGTK. Both builds completed 23.2 million concurrent clock reads per engine with zero backwards steps under forced CPU migration.

Separate issue: Binaryen fence miscompile during SMP lowering

Binaryen 133's precompute pass drops atomic.fence instructions from the SMP kernel. Linux's timekeeper uses these barriers around its sequence-counter reads and writes. Missing barriers can allow the old seconds base to be combined with nanoseconds from after a one-second carry. Two samples from multithreaded sysbench threads runs were consistent with this failure mode, with deltas of −1 s and −0.99998 s despite successful clock calls.

The recommended permanent fix is to update the Binaryen version pin and checksums to the first official release containing Binaryen #9379. That change prevents the optimizer from folding away atomic.fence. The latest official release, version_133, still lacks this fix.

Upstream CI build validation

The macOS CI build for c35bddec04ca preserved the fence in a minimal shared-memory module with standard -O2. With the same linked SMP kernel and lowering flags, the official version_133 build emitted 0 fences and the CI build emitted 6,454. Both used standard -O2 with precompute enabled.

Optional temporary patch for Binaryen 133

This patch can be applied locally for testing. It skips precompute for the SMP build, rejects a zero-fence output, and adds the lowering flags to the build stamp. Rebuild both UP and SMP after applying it so the new build stamp is used.

Patch for kernel/build.sh
diff --git a/kernel/build.sh b/kernel/build.sh
index 238035d..298a6ac 100755
--- a/kernel/build.sh
+++ b/kernel/build.sh
@@ -42,8 +42,8 @@
 # banner (linux_banner, `uname -v`) has fixed stamps instead of the user,
 # host, build count and time: (unkernel@unkernel), the build id as the build
 # "number" (#<12 hex digits>: a hash of the kernel tree with its uncommitted
-# changes, the kwemu sources, the wasm-ld patches and the zig version, so
-# every other build of the kernel module has another banner, which is what a
+# changes, the kwemu sources, the wasm-ld patches, the zig version and the
+# SMP lowering flags, so every other build has another banner, which is what a
 # snapshot is matched against), and the date of the newest commit (author
 # date) on the kernel tree. KBUILD_BUILD_USER, _HOST, _VERSION and
 # _TIMESTAMP in the environment take precedence.
@@ -122,6 +122,8 @@ LLVM_COMMIT=ca7933e47d3a3451d81e72ac174dcb5aa28b59d1
 BINARYEN_VERSION=133
 BINARYEN_SHA256_x86_64=2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af4797782a37489
 BINARYEN_SHA256_aarch64=89c07ea56faf38d0fbecf36ca8ec0721756716185f265b568e133d427f299bf8
+# Binaryen 133's precompute pass folds atomic.fence into a no-op.
+smp_lower_flags=(--skip-pass=precompute)
 
 ksrc="${KSRC:-$vendor/src/linux-wasm-kernel}"
 kout="${KOUT:-$build/kernel}"
@@ -286,6 +288,7 @@ kernel_stamps() {
 			(cd "$ksrc" && git --no-optional-locks ls-files -z -o --exclude-standard | xargs -0r sha256sum)
 			digest_files "$root" src include build.zig build.zig.zon kernel/patches/llvm kernel/tools/fake-llvm
 			echo "zig $("${zig:-zig}" version 2>/dev/null) jit ${KWEMU_JIT:-1} stats ${KWEMU_STATS:-0}"
+			echo "SMP lowering ${smp_lower_flags[*]}"
 		} | sha256sum | cut -c1-12
 	)"
 	when="$({
@@ -358,7 +361,7 @@ build_kernel() {
 	fi
 	"${make_cmd[@]}" -j"$jobs" vmlinux
 	echo "kernel ($variant): $out/vmlinux"
-	lower_kernel "$out"
+	lower_kernel "$out" "$variant"
 }
 
 # Binaryen release binaries (wasm-opt) into vendor/toolchain/binaryen.
@@ -398,9 +401,9 @@ find_wasm_opt() {
 # every load/store, memory and table op wraps its address to i32, which is
 # exact because guest RAM is < 4 GiB. The import/export signatures (and with
 # them JSPI) are unchanged. Fetches the pinned Binaryen if there is no wasm-opt.
-# $1: the kernel build output (default KOUT).
+# $1: the kernel build output; $2: up or smp.
 lower_kernel() {
-	local k="${1:-$kout}" wasm_opt
+	local k="$1" variant="$2" wasm_opt flags=(-O2)
 	wasm_opt="$(find_wasm_opt)"
 	[ -n "$wasm_opt" ] || { fetch_binaryen && wasm_opt="$(find_wasm_opt)"; } || true
 	if [ -z "$wasm_opt" ]; then
@@ -418,7 +421,14 @@ lower_kernel() {
 	# covers releases where they were separate passes. -O2 then optimizes
 	# the lowered module (about 4% smaller and as much faster on shell
 	# commands; -O3 was no faster).
-	"$wasm_opt" "$k/vmlinux" -g --memory64-lowering --table64-lowering -O2 -o "$k/vmlinux32.wasm.tmp"
+	[ "$variant" != smp ] || flags+=("${smp_lower_flags[@]}")
+	"$wasm_opt" "$k/vmlinux" -g --memory64-lowering --table64-lowering "${flags[@]}" -o "$k/vmlinux32.wasm.tmp"
+	if [ "$variant" = smp ] && ! "$wasm_opt" "$k/vmlinux32.wasm.tmp" --metrics -o /dev/null |
+		awk '$1 == "AtomicFence" && $3 > 0 { found = 1 } END { exit !found }'; then
+		echo "lower: could not verify atomic.fence instructions in the SMP kernel" >&2
+		rm -f "$k/vmlinux32.wasm.tmp"
+		return 1
+	fi
 	mv "$k/vmlinux32.wasm.tmp" "$k/vmlinux32.wasm"
 	echo "kernel (32-bit memory): $k/vmlinux32.wasm ($("$wasm_opt" --version))"
 }
@@ -547,8 +557,8 @@ binaryen) fetch_binaryen ;;
 kernel) build_kernel up; refresh_bundle ;;
 smp) build_kernel smp; refresh_bundle ;;
 lower)
-	lower_kernel "$kout"
-	if [ -f "$kout_smp/vmlinux" ]; then lower_kernel "$kout_smp"; fi
+	lower_kernel "$kout" up
+	if [ -f "$kout_smp/vmlinux" ]; then lower_kernel "$kout_smp" smp; fi
 	refresh_bundle
 	;;
 datadisk) build_datadisk; refresh_bundle ;;

The optional patch was tested separately.

  • With the same linked SMP module, Binaryen 133 produced zero fences under the old pipeline and 5,172 with precompute skipped. The build's artifact check rejected the zero-fence output. The UP output was byte-identical for the same linked input.
  • Clean UP and SMP kernel builds passed the five bundle/patch tests, including byte-identical reconstruction in both directions. The rebuilt SMP kernel booted Alpine with six vCPUs on a Linux host, completed three 10-second four-thread, one-yield sysbench threads runs without a wrapped maximum latency, and shut down cleanly.
  • In repeated four-thread, one-yield sysbench threads runs on an iOS device, the reporter did not observe the one-second reversal again after switching to a kernel built with this optimization change. The reversal was intermittent before the change.

Verification

  • Added tests for sub-microsecond precision, negative and skewed samples, snapshot offset advances, and four concurrently reading workers. The skew regression fails when the clamp is removed.
  • SDK typecheck and package build, 118 focused Node tests, and 15 packaged-kernel API checks in UP/SMP modes, including snapshots on a busy SMP guest. The Alpine distro integration suite also passed.
  • iOS 27.1 WKWebView, 2 vCPUs, the same release kernel and Alpine image, with 3 million direct syscalls per clock per CPU. The released SDK saw 41 backwards steps on CPU 1 across monotonic, raw, boot and realtime clocks. The SDK built from this patch saw zero across all 24 million samples. This iOS check used the JS-only revision and the released kernel.

Calibrate worker origins once and publish a shared high-water mark so WebKit jitter and cross-CPU skew cannot move guest time backwards. Keep the existing single-CPU path and snapshot clock advance.

Verified SDK typecheck and bundle, 118 focused Node tests, UP and SMP boot/snapshot tests, and 24 million guest clock_gettime calls in iOS WebKit.
@Crashel1 Crashel1 changed the title Keep SMP guest clocks monotonic across workers js: keep SMP guest clocks monotonic across workers Nov 29, 2026
Expose the clock test command already used by the SDK test suite and release workflow. Verified that npm run test:clock runs all four clock regressions.
@Crashel1
Crashel1 marked this pull request as draft November 29, 2026 16:34
Only declare the generic fallback when the architecture provides no hook. The macro for the Wasm override otherwise redeclares its external function as static and prevents a clean kernel build.

Verified by reproducing the declaration error and recompiling the SMP kernel without that conflicting declaration.
Take one numeric host sample for each monotonic read and publish it through a shared nanosecond watermark in the kernel. The WASI path stays available for UP and previously built kernels. Share the same watermark with host timers and snapshot reads.

Verified with the clock regression suite, SDK typecheck, package build and a clean SMP kernel build.
Keep the clock regression test in the expanded SDK test suite and retain both changes to the Wasm architecture patch.
@Crashel1
Crashel1 force-pushed the fix/smp-monotonic-clock branch from 63473db to acd3b4f Compare November 29, 2026 18:06
@Crashel1
Crashel1 marked this pull request as ready for review November 29, 2026 18:10
Binaryen 133's precompute pass removes atomic.fence instructions from
the SMP kernel. Keep the rest of the O2 pipeline and reject a lowered
SMP module without fences before publishing it. Include the SMP flags
in the shared build stamp so rebuilt UP/SMP pairs keep a common identity
and snapshots distinguish the new binaries.

Verified the old pipeline emits zero fences for the same linked SMP
module and the new pipeline retains 5,172. The guard rejected a
zero-fence output, the UP output was byte-identical for the same input,
and the clock and real-kernel bundle tests passed.
Keep the temporary patch in the pull request description. The
permanent fix is to use an official Binaryen release that includes
the upstream precompute fix.

This reverts commit 8a39ee0.
Verified that the source tree matches the preceding revision and that
the clock tests pass.
@Crashel1 Crashel1 changed the title js: keep SMP guest clocks monotonic across workers smp: keep guest clocks monotonic across workers Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant