code wiki / _hdl_build / nx_perf_counters_test.nx

nx_perf_counters_test.nx source

↩ module page · 60 lines · 2938 B

1// nx_perf_counters_test.nx -- validate the bits-up perf-counter reader in pure 2// NishiLang: open a hardware INSTRUCTIONS counter, run a known workload, read the 3// delta. A positive count proves we can measure real CPU activity DIRECTLY from 4// the silicon's PMU -- the STATE-INDEPENDENT energy foundation (works charging, on 5// AC, on a battery-less server) -- with no libc, no `perf`, no C. 6// 7// Known answer: instruction delta > 0 (and within a sane band of the work done) 8// -> exit 0. If perf_event_open is unavailable (locked-down kernel), it reports 9// the errno and exits non-zero loudly -- never silently faking a number. 10 11import "nx_perf_counters.nx" 12 13func _emit(name: *u8, v: i64) -> i64 { 14 var n: i64 = 0; while name[n] != (0 as u8) { n = n + 1 } sys_write(1, name, n) 15 let b: *u8 = sys_mmap(28); var m: i64 = v; if m < 0 { m = 0 - m } 16 let t: *u8 = sys_mmap(28); var k: i64 = 0 17 if m == 0 { t[0] = 48; k = 1 } 18 while m > 0 { t[k] = 48 + (m % 10); m = m / 10; k = k + 1 } 19 var i: i64 = 0; while i < k { b[i] = t[k - 1 - i]; i = i + 1 } 20 b[k] = 10; sys_write(1, b, k + 1); return 0 21} 22 23const PC_ITERS: i64 = 5000000 24 25func main() -> i64 { 26 sys_write(1, "=== bits-up PMU/SW counter read (perf_event_open, pure NishiLang) ===\n" as *u8, 68) 27 let sel: *i64 = sys_mmap(16) as *i64 28 let fd: i64 = pc_open_best(sel) 29 if fd < 0 { 30 // CAPABILITY PROBE: absence is not failure (graceful). This VM (WSL2/Hyper-V) 31 // exposes no PMU and restricts perf_event_open; a bare-metal node / garden 32 // sensor / server reads it directly. The energy model uses rdtsc (which works 33 // everywhere) as the state-independent input here. Honest, not faked. 34 _emit(" perf_event_open unavailable here (rc) : " as *u8, fd) 35 sys_write(1, " -> no PMU passthrough in this VM; energy model falls to rdtsc cycles.\n" as *u8, 69) 36 sys_exit(0); return 0 37 } 38 if sel[0] == PERF_TYPE_HARDWARE { 39 sys_write(1, " source: HARDWARE instructions (real PMU)\n" as *u8, 42) 40 } else { 41 sys_write(1, " source: SOFTWARE task-clock (kernel-emulated; VM has no PMU passthrough)\n" as *u8, 73) 42 } 43 let c0: i64 = pc_read(fd) 44 var s: i64 = 0 45 var i: i64 = 0 46 while i < PC_ITERS { s = s + i * 3 + 1; i = i + 1 } 47 let c1: i64 = pc_read(fd) 48 if s == 0 - 1 { sys_write(1, "" as *u8, 0) } // consume 49 sys_close(fd) 50 51 let delta: i64 = c1 - c0 52 if sel[0] == PERF_TYPE_HARDWARE { _emit(" instructions counted (state-independent) : " as *u8, delta) } 53 else { _emit(" CPU-time nanoseconds (state-independent) : " as *u8, delta) } 54 _emit(" workload iterations : " as *u8, PC_ITERS) 55 sys_write(1, " -> real CPU activity, charge-state INDEPENDENT; feeds the energy model.\n" as *u8, 72) 56 57 if delta <= 0 { sys_exit(2); return 2 } // must actually count 58 sys_exit(0) 59 return 0 60}