yscv_threadpool/
affinity.rs1#[cfg(target_os = "linux")]
21use std::fs;
22
23pub fn resolve_pinning(policy: AffinityPolicy, nthreads: usize) -> Vec<usize> {
27 match policy {
28 AffinityPolicy::None => Vec::new(),
29 AffinityPolicy::Big => resolve_big(nthreads).unwrap_or_else(|| resolve_physical(nthreads)),
30 AffinityPolicy::Physical => resolve_physical(nthreads),
31 }
32}
33
34pub fn policy_from_env() -> AffinityPolicy {
36 match std::env::var("YSCV_POOL_AFFINITY").as_deref() {
37 Ok("none") => AffinityPolicy::None,
38 Ok("big") => AffinityPolicy::Big,
39 _ => AffinityPolicy::Physical,
43 }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum AffinityPolicy {
48 None,
49 Big,
50 Physical,
51}
52
53pub fn pin_current_thread(cpu_id: usize) {
55 #[cfg(target_os = "linux")]
56 {
57 pin_linux(cpu_id);
58 }
59 #[cfg(target_os = "macos")]
60 {
61 pin_darwin(cpu_id);
62 }
63 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
64 {
65 let _ = cpu_id;
66 }
67}
68
69#[cfg(target_os = "linux")]
70fn pin_linux(cpu_id: usize) {
71 #[allow(unsafe_code)]
75 unsafe {
76 let mut set: libc::cpu_set_t = std::mem::zeroed();
77 libc::CPU_SET(cpu_id, &mut set);
78 let _ = libc::sched_setaffinity(
79 0, std::mem::size_of::<libc::cpu_set_t>(),
81 &set,
82 );
83 }
84}
85
86#[cfg(target_os = "macos")]
87fn pin_darwin(cpu_id: usize) {
88 #[allow(unsafe_code)]
96 unsafe {
97 #[repr(C)]
98 struct ThreadAffinityPolicy {
99 affinity_tag: i32,
100 }
101 const THREAD_AFFINITY_POLICY: i32 = 4;
102 const THREAD_AFFINITY_POLICY_COUNT: u32 = 1;
103
104 unsafe extern "C" {
105 fn mach_thread_self() -> u32;
106 fn thread_policy_set(
107 thread: u32,
108 flavor: i32,
109 policy_info: *const i32,
110 policy_count: u32,
111 ) -> i32;
112 fn mach_port_deallocate(task: u32, port: u32) -> i32;
113 fn mach_task_self() -> u32;
114 }
115
116 let policy = ThreadAffinityPolicy {
117 affinity_tag: (cpu_id as i32) + 1, };
119 let thread = mach_thread_self();
120 let _ = thread_policy_set(
121 thread,
122 THREAD_AFFINITY_POLICY,
123 &policy as *const _ as *const i32,
124 THREAD_AFFINITY_POLICY_COUNT,
125 );
126 let _ = mach_port_deallocate(mach_task_self(), thread);
127 }
128}
129
130#[cfg(target_os = "linux")]
136fn resolve_big(nthreads: usize) -> Option<Vec<usize>> {
137 let mut caps: Vec<(usize, u32)> = Vec::new();
138 for id in 0..1024usize {
139 let path = format!("/sys/devices/system/cpu/cpu{id}/cpu_capacity");
140 match fs::read_to_string(&path) {
141 Ok(s) => {
142 if let Ok(cap) = s.trim().parse::<u32>() {
143 caps.push((id, cap));
144 }
145 }
146 Err(_) => {
147 let cpu_dir = format!("/sys/devices/system/cpu/cpu{id}");
148 if !std::path::Path::new(&cpu_dir).exists() {
149 break;
150 }
151 }
152 }
153 }
154 if caps.is_empty() {
155 return None;
156 }
157 let max_cap = caps.iter().map(|&(_, c)| c).max()?;
158 let min_cap = caps.iter().map(|&(_, c)| c).min()?;
159 if max_cap == min_cap {
160 return None; }
162 let big: Vec<usize> = caps
163 .into_iter()
164 .filter(|&(_, c)| c == max_cap)
165 .map(|(id, _)| id)
166 .collect();
167 Some(take_first_n(big, nthreads))
168}
169
170#[cfg(not(target_os = "linux"))]
171fn resolve_big(nthreads: usize) -> Option<Vec<usize>> {
172 #[cfg(target_os = "macos")]
175 {
176 if let Ok(out) = std::process::Command::new("sysctl")
177 .args(["-n", "hw.perflevel0.logicalcpu_max"])
178 .output()
179 && out.status.success()
180 && let Ok(s) = String::from_utf8(out.stdout)
181 && let Ok(n) = s.trim().parse::<usize>()
182 && n > 0
183 {
184 let big: Vec<usize> = (0..n).collect();
185 return Some(take_first_n(big, nthreads));
186 }
187 }
188 let _ = nthreads;
189 None
190}
191
192#[cfg(target_os = "linux")]
200fn resolve_physical(nthreads: usize) -> Vec<usize> {
201 use std::collections::BTreeSet;
202 let mut seen: BTreeSet<usize> = BTreeSet::new();
203 let mut reps: Vec<usize> = Vec::new();
204
205 for id in 0..1024usize {
206 let path = format!("/sys/devices/system/cpu/cpu{id}/topology/thread_siblings_list");
207 let s = match fs::read_to_string(&path) {
208 Ok(s) => s,
209 Err(_) => {
210 let cpu_dir = format!("/sys/devices/system/cpu/cpu{id}");
211 if !std::path::Path::new(&cpu_dir).exists() {
212 break;
213 }
214 continue;
215 }
216 };
217 let sibling_min = parse_cpu_list_min(&s);
220 let Some(rep) = sibling_min else { continue };
221 if seen.insert(rep) {
222 reps.push(rep);
223 }
224 }
225 if reps.is_empty() {
226 return (0..nthreads).collect();
228 }
229 take_first_n(reps, nthreads)
230}
231
232#[cfg(not(target_os = "linux"))]
233fn resolve_physical(nthreads: usize) -> Vec<usize> {
234 (0..nthreads).collect()
237}
238
239#[cfg(target_os = "linux")]
241fn parse_cpu_list_min(s: &str) -> Option<usize> {
242 let s = s.trim();
243 let mut min: Option<usize> = None;
244 for part in s.split(',') {
245 let part = part.trim();
246 if part.is_empty() {
247 continue;
248 }
249 if let Some((a, _b)) = part.split_once('-') {
250 if let Ok(v) = a.trim().parse::<usize>() {
251 min = Some(min.map_or(v, |m| m.min(v)));
252 }
253 } else if let Ok(v) = part.parse::<usize>() {
254 min = Some(min.map_or(v, |m| m.min(v)));
255 }
256 }
257 min
258}
259
260#[cfg(any(target_os = "linux", target_os = "macos"))]
261fn take_first_n(mut v: Vec<usize>, n: usize) -> Vec<usize> {
262 if v.len() > n {
263 v.truncate(n);
264 }
265 v
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 #[test]
273 fn none_policy_returns_empty() {
274 assert!(resolve_pinning(AffinityPolicy::None, 6).is_empty());
275 }
276
277 #[test]
278 fn physical_returns_at_most_nthreads() {
279 let v = resolve_pinning(AffinityPolicy::Physical, 4);
280 assert!(v.len() <= 4, "got {} ids for 4 threads", v.len());
281 }
282
283 #[cfg(target_os = "linux")]
284 #[test]
285 fn cpu_list_min_parses() {
286 assert_eq!(parse_cpu_list_min("0,6"), Some(0));
287 assert_eq!(parse_cpu_list_min("3,9"), Some(3));
288 assert_eq!(parse_cpu_list_min("2-3,5"), Some(2));
289 assert_eq!(parse_cpu_list_min(""), None);
290 }
291
292 #[test]
293 fn policy_from_env_defaults_to_physical() {
294 let _p = policy_from_env();
297 }
298
299 #[test]
300 fn pin_current_thread_is_noop_safe() {
301 pin_current_thread(0);
303 }
304}