Skip to content

os: implement Futex for NetBSD - #640

Merged
lalinsky merged 3 commits into
mainfrom
netbsd-futex
Aug 1, 2026
Merged

lalinsky merged 3 commits into
mainfrom
netbsd-futex

Conversation

@lalinsky

@lalinsky lalinsky commented Aug 1, 2026 •

Copy link
Copy Markdown
Owner

NetBSD was the one supported POSIX target whose Futex resolved to void (FreeBSD, OpenBSD, DragonFly and Darwin all have implementations), so anything built on os.Futex failed to compile there — first hit by the metrics monitor thread in #636, whose NetBSD CI job fails until this lands.

NetBSD >= 10 provides a Linux-compatible futex via the __futex syscall: FUTEX_WAIT blocks while *uaddr == val with a relative timeout (ETIMEDOUT on expiry, EAGAIN when the value already changed), FUTEX_WAKE wakes up to val waiters, and FUTEX_PRIVATE_FLAG matches Linux (128). One wrinkle: libc ships no ___futex stub (zig's NetBSD abilists confirm), so the implementation goes through the generic syscall(2) entry point with SYS___futex (166), which the symbol list does provide.

Also adds a Futex.timedWait test covering both the expiry path and the already-changed-value path, so CI's NetBSD VM (and every other futex platform) exercises the new syscall for real — the existing test only covered wake.

The switch's else => void fallback remains for targets genuinely without a futex; #636 will grow a comptime guard for those separately.

Follow-up commits

  • Review fixes: the documented minimum is NetBSD 10 (NetBSD 9 leaves syscall 166 unimplemented; Zig's floor is 10.1 so no fallback is needed), and the futex word now travels via @bitCast in all three c_int-taking implementations (NetBSD, OpenBSD, DragonFly had the same latent @intCast), with a 0x8000_0000 case added to the timedWait test.
  • Retire the NetBSD-specific thread primitives (-182 lines): NotifyNetBSD (lwp_park based) and the MutexNotify selection existed only because NetBSD had no futex. NetBSD now uses the same futex-based Notify/Mutex/Condition as the other POSIX targets (Condition already selected on futex availability), deleting the lwp_park externs and the create-Notify-on-the-waiting-thread constraint.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

NetBSD futex support

Layer / File(s) Summary
NetBSD futex syscall bindings
src/os/netbsd.zig
Adds futex constants, the syscall number, a variadic syscall declaration, and a futex wrapper. Removes the LWP park and unpark declarations.
NetBSD futex wait and wake integration
src/os/thread.zig
Selects FutexNetBSD, implements waits and wake operations, and routes Notify and mutex behavior through futexes.
Expected-value handling and tests
src/os/thread.zig
Preserves raw expected-value bits on OpenBSD and DragonFly. Adds futex timeout, changed-value, and high-bit tests. Removes tests for MutexNotify.

Estimated code review effort: 4 (Complex) | ~40 minutes

Possibly related PRs

  • lalinsky/zio#277: Introduced the NetBSD LWP-based thread-wait implementation replaced here.
  • lalinsky/zio#289: Modifies related futex wait and timed-wait behavior.
  • lalinsky/zio#305: Modifies platform-specific futex behavior in src/os/thread.zig.

Poem

NetBSD calls futex near,
Waits and wakes now persevere.
High bits keep their rightful place,
Timeouts end the waiting race.
LWP paths disappear.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: implementing Futex support for NetBSD.
Description check ✅ Passed The description directly explains the NetBSD Futex implementation, syscall details, platform changes, tests, and compatibility scope.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch netbsd-futex

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

lalinsky added a commit that referenced this pull request Aug 1, 2026
Targets whose os.Futex is void (the else fallback) get a warning
instead of a compile error in runMetricsMonitor. NetBSD leaves that
set once #640 lands; anything genuinely futex-less stays buildable.

Reported by the NetBSD build failure on #636.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/os/netbsd.zig`:
- Around line 8-19: Update the NetBSD futex support around FUTEX_WAIT,
FUTEX_WAKE, and SYS___futex to either require NetBSD 10 or provide a NetBSD 9
fallback with equivalent wait/wake behavior. In src/os/netbsd.zig lines 8-19,
correct the documented minimum version or add the fallback; in src/os/thread.zig
lines 59-67, do not select FutexNetBSD on NetBSD 9 unless that fallback is
available.

In `@src/os/thread.zig`:
- Around line 538-561: Replace the `@intCast`(expected) futex comparison arguments
with `@bitCast`(expected) in both wait and timedWait, preserving the exact 32-bit
word representation for high-bit values. Add a regression test covering expected
= 0x8000_0000 and verify both NetBSD futex call paths accept it without runtime
safety failure.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 0d6aa343-bb4d-441c-b49a-1faf77702e63

📥 Commits

Reviewing files that changed from the base of the PR and between 5d108e6 and b54a2fa.

📒 Files selected for processing (2)
  • src/os/netbsd.zig
  • src/os/thread.zig

Comment thread src/os/netbsd.zig Resolved
Comment thread src/os/thread.zig Resolved
lalinsky added a commit that referenced this pull request Aug 1, 2026
NetBSD 9 leaves syscall 166 unimplemented; __futex shipped in NetBSD 10.
Zig's minimum supported NetBSD is 10.1, so no fallback is needed, but
the documented requirement was wrong.

The expected value is a raw 32-bit word, and @intcast to the platform
calls' c_int rejects values with the high bit set under runtime safety.
Use @bitcast in all three implementations that take c_int (NetBSD,
OpenBSD, DragonFly - the latter two had the same latent cast), and
extend the timedWait test with a 0x8000_0000 word so every futex
platform exercises the high-bit path.

Reported by review on #640.
NetBSD was the one supported POSIX target whose Futex resolved to void:
FreeBSD, OpenBSD, DragonFly and Darwin all have implementations, and
anything built on os.Futex (the metrics monitor in #636 being the first)
failed to compile there.

NetBSD >= 9 provides a Linux-compatible futex through the __futex
syscall (FUTEX_WAIT with a relative timeout, FUTEX_WAKE,
FUTEX_PRIVATE_FLAG). libc ships no ___futex stub, so the call goes
through the generic syscall(2) entry point with SYS___futex (166),
which the libc symbol list does provide.

Also adds a timedWait test (expiry and already-changed-value paths) so
CI exercises the syscall on every futex platform, not just the wake
path the existing test covers.
NetBSD 9 leaves syscall 166 unimplemented; __futex shipped in NetBSD 10.
Zig's minimum supported NetBSD is 10.1, so no fallback is needed, but
the documented requirement was wrong.

The expected value is a raw 32-bit word, and @intcast to the platform
calls' c_int rejects values with the high bit set under runtime safety.
Use @bitcast in all three implementations that take c_int (NetBSD,
OpenBSD, DragonFly - the latter two had the same latent cast), and
extend the timedWait test with a 0x8000_0000 word so every futex
platform exercises the high-bit path.

Reported by review on #640.
NotifyNetBSD (lwp_park based) and the MutexNotify selection existed only
because NetBSD had no futex. With FutexNetBSD in place, NetBSD uses the
same futex-based Notify, Mutex and Condition as the other POSIX targets
(Condition already selected by futex availability), so the lwp_park
externs and the WaitQueue-based mutex go away, along with the
requirement that a Notify be created on its waiting thread.
@lalinsky

lalinsky commented Aug 1, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai please check for me if the futex syscall in netbsd is actually meant to be used

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== PR diff and local declarations =='
git diff -- src/os/netbsd.zig src/os/thread.zig
printf '\n== netbsd.zig outline ==\n'
ast-grep outline src/os/netbsd.zig --items all
printf '\n== relevant declarations ==\n'
rg -n -C 5 '(__futex|futex|SYS___futex|syscall)' src/os/netbsd.zig src/os/thread.zig

echo '== NetBSD upstream code search: syscall and libc wrapper =='
gh api -H 'Accept: application/vnd.github+json' \
  '/search/code?q=repo%3ANetBSD%2Fsrc+__futex' \
  --jq '.items[] | [.path, .html_url] | `@tsv`' || true

echo '== NetBSD CVS source queries =='
for url in \
  'https://raw.githubusercontent.com/NetBSD/src/trunk/sys/kern/sys_futex.c' \
  'https://raw.githubusercontent.com/NetBSD/src/trunk/sys/sys/futex.h' \
  'https://raw.githubusercontent.com/NetBSD/src/trunk/lib/libc/sys/futex.2' \
  'https://raw.githubusercontent.com/NetBSD/src/trunk/lib/libc/sys/Makefile.inc'
do
  echo "--- $url"
  curl --fail --silent --show-error --location "$url" | sed -n '1,240p' || true
done

Length of output: 44056


🏁 Script executed:

#!/bin/bash
set -euo pipefail

base='https://raw.githubusercontent.com/NetBSD/src'
files=(
  'trunk/lib/libc/include/futex_private.h'
  'trunk/sys/kern/syscalls.master'
  'trunk/lib/libc/pthread/pthread__futex.c'
  'netbsd-10/sys/sys/futex.h'
  'netbsd-10/sys/kern/syscalls.master'
  'netbsd-10/sys/kern/sys_futex.c'
)

for file in "${files[@]}"; do
  echo "===== ${file} ====="
  if content=$(curl --fail --silent --show-error --location "${base}/${file}"); then
    printf '%s\n' "$content" |
      rg -n -C 8 '(__futex|futex|166|FUTEX_WAIT|FUTEX_WAKE|PRIVATE)' || true
  else
    echo 'not found'
  fi
done

echo '===== libc uses of private futex interface ====='
curl --fail --silent --show-error --location \
  'https://api.github.com/search/code?q=repo%3ANetBSD%2Fsrc+path%3Alib%2Flibc+__futex' |
  jq -r '.items[]? | [.path, .html_url] | `@tsv`'

Length of output: 62719


@lalinsky Yes. NetBSD intends __futex for user-space synchronization.

The NetBSD 10 source defines syscall 166 as a STD syscall:

__futex(int *uaddr, int op, int val,
    const struct timespec *timeout, int *uaddr2, int val2, int val3)

Its public kernel header, sys/sys/futex.h, calls it the "__futex(2) synchronization primitive". The header also specifies Linux-compatible ABI values for FUTEX_WAIT, FUTEX_WAKE, and FUTEX_PRIVATE_FLAG.

NetBSD libc also has an internal wrapper in lib/libc/include/futex_private.h. That wrapper calls:

_syscall(SYS___futex, uaddr, op, val, timeout, uaddr2, val2, val3)

This matches the PR wrapper exactly. The NetBSD kernel implementation documents the expected lock use case and implements relative FUTEX_WAIT timeouts, FUTEX_WAKE, and private futexes.

There is no exported libc futex() or __futex() stub. Therefore, using the generic syscall(2) entry point is appropriate here. Keep the wrapper internal to the runtime. Do not present it as a public libc API.

The PR’s NetBSD 10 guard is also correct. NetBSD 9 leaves syscall 166 unimplemented.

You are interacting with an AI system.

@lalinsky
lalinsky merged commit 2b60e85 into main Aug 1, 2026
28 checks passed
@lalinsky
lalinsky deleted the netbsd-futex branch August 1, 2026 17:29
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