#[cfg(target_os = "linux")]
use std::fs;
pub fn resolve_pinning(policy: AffinityPolicy, nthreads: usize) -> Vec<usize> {
match policy {
AffinityPolicy::None => Vec::new(),
AffinityPolicy::Big => resolve_big(nthreads).unwrap_or_else(|| resolve_physical(nthreads)),
AffinityPolicy::Physical => resolve_physical(nthreads),
}
}
pub fn policy_from_env() -> AffinityPolicy {
match std::env::var("YSCV_POOL_AFFINITY").as_deref() {
Ok("none") => AffinityPolicy::None,
Ok("big") => AffinityPolicy::Big,
_ => AffinityPolicy::Physical,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AffinityPolicy {
None,
Big,
Physical,
}
pub fn pin_current_thread(cpu_id: usize) {
#[cfg(target_os = "linux")]
{
pin_linux(cpu_id);
}
#[cfg(target_os = "macos")]
{
pin_darwin(cpu_id);
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
let _ = cpu_id;
}
}
#[cfg(target_os = "linux")]
fn pin_linux(cpu_id: usize) {
#[allow(unsafe_code)]
unsafe {
let mut set: libc::cpu_set_t = std::mem::zeroed();
libc::CPU_SET(cpu_id, &mut set);
let _ = libc::sched_setaffinity(
0, std::mem::size_of::<libc::cpu_set_t>(),
&set,
);
}
}
#[cfg(target_os = "macos")]
fn pin_darwin(cpu_id: usize) {
#[allow(unsafe_code)]
unsafe {
#[repr(C)]
struct ThreadAffinityPolicy {
affinity_tag: i32,
}
const THREAD_AFFINITY_POLICY: i32 = 4;
const THREAD_AFFINITY_POLICY_COUNT: u32 = 1;
unsafe extern "C" {
fn mach_thread_self() -> u32;
fn thread_policy_set(
thread: u32,
flavor: i32,
policy_info: *const i32,
policy_count: u32,
) -> i32;
fn mach_port_deallocate(task: u32, port: u32) -> i32;
fn mach_task_self() -> u32;
}
let policy = ThreadAffinityPolicy {
affinity_tag: (cpu_id as i32) + 1, };
let thread = mach_thread_self();
let _ = thread_policy_set(
thread,
THREAD_AFFINITY_POLICY,
&policy as *const _ as *const i32,
THREAD_AFFINITY_POLICY_COUNT,
);
let _ = mach_port_deallocate(mach_task_self(), thread);
}
}
#[cfg(target_os = "linux")]
fn resolve_big(nthreads: usize) -> Option<Vec<usize>> {
let mut caps: Vec<(usize, u32)> = Vec::new();
for id in 0..1024usize {
let path = format!("/sys/devices/system/cpu/cpu{id}/cpu_capacity");
match fs::read_to_string(&path) {
Ok(s) => {
if let Ok(cap) = s.trim().parse::<u32>() {
caps.push((id, cap));
}
}
Err(_) => {
let cpu_dir = format!("/sys/devices/system/cpu/cpu{id}");
if !std::path::Path::new(&cpu_dir).exists() {
break;
}
}
}
}
if caps.is_empty() {
return None;
}
let max_cap = caps.iter().map(|&(_, c)| c).max()?;
let min_cap = caps.iter().map(|&(_, c)| c).min()?;
if max_cap == min_cap {
return None; }
let big: Vec<usize> = caps
.into_iter()
.filter(|&(_, c)| c == max_cap)
.map(|(id, _)| id)
.collect();
Some(take_first_n(big, nthreads))
}
#[cfg(not(target_os = "linux"))]
fn resolve_big(nthreads: usize) -> Option<Vec<usize>> {
#[cfg(target_os = "macos")]
{
if let Ok(out) = std::process::Command::new("sysctl")
.args(["-n", "hw.perflevel0.logicalcpu_max"])
.output()
&& out.status.success()
&& let Ok(s) = String::from_utf8(out.stdout)
&& let Ok(n) = s.trim().parse::<usize>()
&& n > 0
{
let big: Vec<usize> = (0..n).collect();
return Some(take_first_n(big, nthreads));
}
}
let _ = nthreads;
None
}
#[cfg(target_os = "linux")]
fn resolve_physical(nthreads: usize) -> Vec<usize> {
use std::collections::BTreeSet;
let mut seen: BTreeSet<usize> = BTreeSet::new();
let mut reps: Vec<usize> = Vec::new();
for id in 0..1024usize {
let path = format!("/sys/devices/system/cpu/cpu{id}/topology/thread_siblings_list");
let s = match fs::read_to_string(&path) {
Ok(s) => s,
Err(_) => {
let cpu_dir = format!("/sys/devices/system/cpu/cpu{id}");
if !std::path::Path::new(&cpu_dir).exists() {
break;
}
continue;
}
};
let sibling_min = parse_cpu_list_min(&s);
let Some(rep) = sibling_min else { continue };
if seen.insert(rep) {
reps.push(rep);
}
}
if reps.is_empty() {
return (0..nthreads).collect();
}
take_first_n(reps, nthreads)
}
#[cfg(not(target_os = "linux"))]
fn resolve_physical(nthreads: usize) -> Vec<usize> {
(0..nthreads).collect()
}
#[cfg(target_os = "linux")]
fn parse_cpu_list_min(s: &str) -> Option<usize> {
let s = s.trim();
let mut min: Option<usize> = None;
for part in s.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
if let Some((a, _b)) = part.split_once('-') {
if let Ok(v) = a.trim().parse::<usize>() {
min = Some(min.map_or(v, |m| m.min(v)));
}
} else if let Ok(v) = part.parse::<usize>() {
min = Some(min.map_or(v, |m| m.min(v)));
}
}
min
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
fn take_first_n(mut v: Vec<usize>, n: usize) -> Vec<usize> {
if v.len() > n {
v.truncate(n);
}
v
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn none_policy_returns_empty() {
assert!(resolve_pinning(AffinityPolicy::None, 6).is_empty());
}
#[test]
fn physical_returns_at_most_nthreads() {
let v = resolve_pinning(AffinityPolicy::Physical, 4);
assert!(v.len() <= 4, "got {} ids for 4 threads", v.len());
}
#[cfg(target_os = "linux")]
#[test]
fn cpu_list_min_parses() {
assert_eq!(parse_cpu_list_min("0,6"), Some(0));
assert_eq!(parse_cpu_list_min("3,9"), Some(3));
assert_eq!(parse_cpu_list_min("2-3,5"), Some(2));
assert_eq!(parse_cpu_list_min(""), None);
}
#[test]
fn policy_from_env_defaults_to_physical() {
let _p = policy_from_env();
}
#[test]
fn pin_current_thread_is_noop_safe() {
pin_current_thread(0);
}
}