code wiki / (root) / nx_mutex.nx

nx_mutex.nx

buildroot/runtime/nx_mutex.nx

5439 B162 linesdepth 3pulls 3 transitivereach 2 importersview sourcekind tool
docsdependenciesstructsconstsfunctions

about

nx_mutex.nx -- futex-based mutex (FUTEX_WAIT / FUTEX_WAKE). Companion to nx_atom (atomic primitives). When SMP arrives, mutual exclusion needs more than a spinlock -- spinning under contention burns CPU and starves the holder. Futex (fast userspace mutex) lets contended waiters sleep in the kernel until the lock is released. State word: 0 = unlocked 1 = locked, no waiters 2 = locked, possibly contended (waiters parked in kernel) Lock fast path: CAS(0, 1). Lock slow path: spin a few times, then transition to 2 + futex_wait. Unlock fast path: store 0; if previous == 2, futex_wake one. Today the sim is single-threaded, so we just track lock/unlock state without actual blocking; the API matches the SMP path so callers don't need to change later. Linux RV64 futex syscall: 98. Pairs with nx_atom for the CAS primitive (which is currently non-atomic since SMP isn't on); will be a no-source-change upgrade once nx_atom emits real LR/SC sequences.

dependencies 2 imports · 2 importers

nx_syscalls.nx nx_atom.nx nx_mutex.nx nx_cond.nx nx_mutex_race_test.nx

imports: nx_syscalls.nxnx_atom.nx

imported by: nx_cond.nxnx_mutex_race_test.nx

call flow from main pre-order; caps 40 nodes / depth 6 declared; ↻ = already shown

main nx_mutex_new sys_mmap nx_mutex_lock nx_mutex_cas nx_mutex_futex_wait nx_mutex_try_lock nx_mutex_cas ↻ nx_mutex_unlock nx_mutex_futex_wake

structs

50struct NxMutex

consts

37const NX_SYS_FUTEX: i64 = 98
40const NX_FUTEX_WAIT: i64 = 0
41const NX_FUTEX_WAKE: i64 = 1
42const NX_FUTEX_PRIVATE_FLAG: i64 = 128
44const NX_MUTEX_UNLOCKED: i64 = 0
45const NX_MUTEX_LOCKED: i64 = 1
46const NX_MUTEX_CONTENDED: i64 = 2
48const NX_MUTEX_SPIN_TRIES: i64 = 100
54const NX_MUTEX_BYTES: i64 = 8

functions

56func nx_mutex_new() -> *NxMutex
called by 1: main calls 1: sys_mmap
66func nx_mutex_cas(m: *NxMutex, expect: i64, new_val: i64) -> i64
74func nx_mutex_futex_wait(m: *NxMutex, expected: i64) -> i64
called by 1: nx_mutex_lock
80func nx_mutex_futex_wake(m: *NxMutex, n: i64) -> i64
called by 1: nx_mutex_unlock
86func nx_mutex_lock(m: *NxMutex) -> i64
122func nx_mutex_try_lock(m: *NxMutex) -> i64
called by 1: main calls 1: nx_mutex_cas
129func nx_mutex_unlock(m: *NxMutex) -> i64
141func main() -> i64