How to get a NUMA node of the current thread?

I want to get a NUMA node of the current thread on Linux. C language provides libraries like libnuma for this. Linux provides a getcpu syscall. But what is about Rust?

I spent an hour searching and reading but could not find anything. getcpu is not provided by any popular library in Rust (I found only two libraries that contain this syscall, but this syscall is private in they). I also found only one binding to libnuma, and it was patched 8 years ago last time.

I don't want to reinvent the wheel, do you know how I can achieve my goal with existing solutions?

1 Like

You can use libc crate to invoke the syscall directly:

use libc::{__errno_location, SYS_getcpu, c_uint, c_void, syscall};
use std::ptr::null;

#[derive(Debug)]
struct Error(i32);

fn getcpu() -> Result<(u32, u32), Error> {
    let (mut cpu, mut node): (c_uint, c_uint) = (0, 0);
    let retval = unsafe {
        syscall(SYS_getcpu, &mut cpu as *mut c_uint, &mut node as *mut c_uint, null::<c_void>())
    };
    if retval == 0 {
        Ok((cpu as u32, node as u32))
    } else {
        Err(Error(unsafe { *__errno_location() }))
    }
}

fn main() {
    let (cpu, node) = getcpu().expect("Something went wrong!");
    println!("CPU: {}, Node: {}", cpu, node);
}
2 Likes

Thank you!