oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `thread` on Linux: `gettid`, `sched_yield`, the affinity calls and
//! `prctl` for the name.

use crate::sys::syscall;
use crate::{ErrorKind, Result};

// include/uapi/linux/prctl.h
const PR_SET_NAME: u32 = 15;
const PR_GET_NAME: u32 = 16;

/// `TASK_COMM_LEN`: the size of a task's name, with its NUL.
const COMM_LEN: usize = 16;

pub(crate) const NAME_MAX: usize = COMM_LEN - 1;

/// The most processors a kernel can be built for (`CONFIG_NR_CPUS`).
const MAX_CPUS: usize = 8192;

pub(crate) fn id() -> u64 {
    // SAFETY: gettid takes nothing and cannot fail.
    unsafe { syscall!(GETTID) }.unwrap_or(0) as u64
}

pub(crate) fn yield_now() {
    // SAFETY: sched_yield takes nothing and cannot fail.
    let _ = unsafe { syscall!(SCHED_YIELD) };
}

pub(crate) fn affinity(mask: &mut [usize]) -> Result<()> {
    // SAFETY: the kernel writes at most the size given, the whole of
    // `mask`; 0 is the calling thread.
    let written = unsafe { syscall!(SCHED_GETAFFINITY, 0, size_of_val(mask), mask.as_mut_ptr()) }?;
    // The system call returns the size of the kernel's own mask, in bytes
    // and whole words, and leaves the rest of the buffer alone.
    let words = written / size_of::<usize>();
    mask.get_mut(words..).ok_or(ErrorKind::Other)?.fill(0);
    Ok(())
}

pub(crate) fn set_affinity(mask: &[usize]) -> Result<()> {
    // SAFETY: the kernel reads the size given, the whole of `mask`; 0 is
    // the calling thread.
    unsafe { syscall!(SCHED_SETAFFINITY, 0, size_of_val(mask), mask.as_ptr()) }?;
    Ok(())
}

pub(crate) fn available_parallelism() -> Result<usize> {
    let mut mask = [0usize; MAX_CPUS / usize::BITS as usize];
    affinity(&mut mask)?;
    Ok(mask.iter().map(|word| word.count_ones() as usize).sum())
}

pub(crate) fn set_name(name: &str) -> Result<()> {
    // The caller cut the name to `NAME_MAX` bytes: there is a NUL after it.
    let mut comm = [0u8; COMM_LEN];
    comm.get_mut(..name.len())
        .ok_or(ErrorKind::InvalidInput)?
        .copy_from_slice(name.as_bytes());
    // SAFETY: the kernel reads a NUL-terminated string of at most 16 bytes.
    unsafe { syscall!(PRCTL, PR_SET_NAME, comm.as_ptr(), 0, 0, 0) }?;
    Ok(())
}

pub(crate) fn name(buf: &mut [u8]) -> Result<usize> {
    let mut comm = [0u8; COMM_LEN];
    // SAFETY: the kernel writes 16 bytes, NUL included.
    unsafe { syscall!(PRCTL, PR_GET_NAME, comm.as_mut_ptr(), 0, 0, 0) }?;
    let len = comm.iter().position(|&b| b == 0).unwrap_or(COMM_LEN);
    buf.get_mut(..len)
        .ok_or(ErrorKind::BufferTooSmall)?
        .copy_from_slice(&comm[..len]);
    Ok(len)
}