Skip to main content

kodamaembed_cpu/
workers.rs

1//! KodamaEmbed's worker threads; on Windows they ask, best effort, not to be throttled.
2
3use rayon::ThreadPoolBuildError;
4#[cfg(target_os = "linux")]
5use std::collections::BTreeSet;
6use std::sync::LazyLock;
7
8/// A pool of worker threads.
9#[cfg(not(target_family = "wasm"))]
10pub type Workers = rayon::ThreadPool;
11
12/// Rayon's own pool: a wasm program starts no threads, and without any that pool runs every
13/// task on its caller.
14#[cfg(target_family = "wasm")]
15pub struct Workers;
16
17#[cfg(target_family = "wasm")]
18impl Workers {
19    /// Runs `op`; its parallel loops go to Rayon's pool.
20    pub fn install<R>(&self, op: impl FnOnce() -> R) -> R {
21        op()
22    }
23
24    /// The threads of Rayon's pool: one where the target has none.
25    pub fn current_num_threads(&self) -> usize {
26        rayon::current_num_threads()
27    }
28}
29
30/// The CPU backend's threads, one per logical processor the process may use.
31pub(crate) static POOL: LazyLock<Workers> = LazyLock::new(|| {
32    worker_pool("kodamaembed-cpu", allowed_processors()).expect("worker threads start")
33});
34
35/// [`short_pool_threads`] for the allowed cores, else none.
36pub(crate) static SHORT_POOL: LazyLock<Option<Workers>> = LazyLock::new(|| {
37    let threads = short_pool_threads(allowed_cores()?, POOL.current_num_threads())?;
38    Some(worker_pool("kodamaembed-cpu-short", threads).expect("short-input threads start"))
39});
40
41/// Physical cores the process may use, by class.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub(crate) struct Cores {
44    pub(crate) performance: usize,
45    pub(crate) efficiency: usize,
46}
47
48/// Short inputs: performance cores alone beat them joined by up to twice as many efficiency cores.
49pub(crate) fn short_pool_threads(cores: Cores, pool: usize) -> Option<usize> {
50    let Cores {
51        performance,
52        efficiency,
53    } = cores;
54    (performance > 0 && efficiency <= 2 * performance && performance < pool).then_some(performance)
55}
56
57/// RelationProcessorCore in LOGICAL_PROCESSOR_RELATIONSHIP.
58#[cfg(any(windows, test))]
59const PROCESSOR_CORE: i32 = 0;
60
61/// The system's fastest efficiency class marks performance cores.
62#[cfg(windows)]
63pub(crate) fn allowed_cores() -> Option<Cores> {
64    use std::ffi::c_void;
65
66    #[link(name = "kernel32")]
67    unsafe extern "system" {
68        fn GetLogicalProcessorInformationEx(
69            relationship: i32,
70            buffer: *mut c_void,
71            length: *mut u32,
72        ) -> i32;
73    }
74    let affinity = process_affinity()?;
75    let mut length = 0_u32;
76    // SAFETY: a null buffer of length 0 asks only for the length needed.
77    unsafe { GetLogicalProcessorInformationEx(PROCESSOR_CORE, std::ptr::null_mut(), &mut length) };
78    let mut buffer = vec![0_u64; (length as usize).div_ceil(8)];
79    // SAFETY: the buffer holds `length` bytes at 8-byte alignment.
80    let filled = unsafe {
81        GetLogicalProcessorInformationEx(PROCESSOR_CORE, buffer.as_mut_ptr().cast(), &mut length)
82    };
83    if filled == 0 {
84        return None;
85    }
86    // SAFETY: the call wrote `length` bytes into the buffer.
87    let bytes =
88        unsafe { std::slice::from_raw_parts(buffer.as_ptr().cast::<u8>(), length as usize) };
89    count_core_records(bytes, |group, mask| match affinity {
90        Affinity::Group(own, allowed) => group == own && mask & allowed != 0,
91        Affinity::Every => true,
92    })
93}
94
95/// Cores with an allowed processor; the fastest efficiency class marks performance cores.
96#[cfg(any(windows, test))]
97fn count_core_records(records: &[u8], allowed: impl Fn(u16, usize) -> bool) -> Option<Cores> {
98    // Records: Relationship and Size (u32 each), Flags, EfficiencyClass, 20 reserved bytes and
99    // GroupCount (u16); then GROUP_AFFINITY entries: Mask (pointer-sized), Group (u16), 6 reserved.
100    const MASK: usize = size_of::<usize>();
101    const ENTRY: usize = MASK + 8;
102    let mut cores = Vec::new();
103    let mut rest = records;
104    while !rest.is_empty() {
105        let size = u32::from_le_bytes(rest.get(4..8)?.try_into().ok()?) as usize;
106        let record = rest.get(..size).filter(|_| size >= 32)?;
107        rest = &rest[size..];
108        if i32::from_le_bytes(record[..4].try_into().ok()?) != PROCESSOR_CORE {
109            continue;
110        }
111        let groups = usize::from(u16::from_le_bytes(record[30..32].try_into().ok()?));
112        let (entries, _) = record.get(32..32 + groups * ENTRY)?.as_chunks::<ENTRY>();
113        let mut usable = false;
114        for entry in entries {
115            let mask = usize::from_le_bytes(entry[..MASK].try_into().ok()?);
116            let group = u16::from_le_bytes(entry[MASK..MASK + 2].try_into().ok()?);
117            usable |= allowed(group, mask);
118        }
119        cores.push((record[9], usable));
120    }
121    let fastest = cores.iter().map(|&(class, _)| class).max()?;
122    let count = |fast: bool| {
123        cores
124            .iter()
125            .filter(|&&(class, usable)| usable && (class == fastest) == fast)
126            .count()
127    };
128    Some(Cores {
129        performance: count(true),
130        efficiency: count(false),
131    })
132}
133
134#[cfg(windows)]
135#[derive(Clone, Copy)]
136enum Affinity {
137    /// A processor group and the mask of its processors the process may use.
138    Group(u16, usize),
139    /// Threads in several groups, for which Windows reports no mask.
140    Every,
141}
142
143#[cfg(windows)]
144fn process_affinity() -> Option<Affinity> {
145    use std::ffi::c_void;
146
147    /// PROCESSOR_NUMBER.
148    #[repr(C)]
149    #[derive(Default)]
150    struct Processor {
151        group: u16,
152        _number: u8,
153        _reserved: u8,
154    }
155    #[link(name = "kernel32")]
156    unsafe extern "system" {
157        fn GetCurrentProcess() -> *mut c_void;
158        fn GetProcessAffinityMask(
159            process: *mut c_void,
160            mask: *mut usize,
161            system: *mut usize,
162        ) -> i32;
163        fn GetCurrentProcessorNumberEx(processor: *mut Processor);
164    }
165    let (mut mask, mut system) = (0, 0);
166    // SAFETY: GetCurrentProcess returns a pseudo-handle, and both masks are writable.
167    if unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut mask, &mut system) } == 0 {
168        return None;
169    }
170    if mask == 0 {
171        return Some(Affinity::Every);
172    }
173    // A mask means the process is in one group, so the processor this thread runs on is too.
174    let mut processor = Processor::default();
175    // SAFETY: `processor` is a writable PROCESSOR_NUMBER.
176    unsafe { GetCurrentProcessorNumberEx(&mut processor) };
177    Some(Affinity::Group(processor.group, mask))
178}
179
180/// Rust's count ignores Windows affinity masks; 0 leaves Rayon's.
181#[cfg(windows)]
182fn allowed_processors() -> usize {
183    #[link(name = "kernel32")]
184    unsafe extern "system" {
185        fn GetActiveProcessorCount(group: u16) -> u32;
186    }
187    const ALL_PROCESSOR_GROUPS: u16 = 0xFFFF;
188    match process_affinity() {
189        Some(Affinity::Group(_, mask)) => mask.count_ones() as usize,
190        // SAFETY: the call reads only its argument.
191        Some(Affinity::Every) => unsafe { GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) as usize },
192        None => 0,
193    }
194}
195
196/// Rayon's count, which follows the process's affinity outside Windows.
197#[cfg(not(windows))]
198fn allowed_processors() -> usize {
199    0
200}
201
202/// From `/sys/devices/cpu_core/cpus` on hybrid Intel processors: frequencies
203/// cannot tell the classes apart, as favored cores report higher maxima.
204#[cfg(target_os = "linux")]
205pub(crate) fn allowed_cores() -> Option<Cores> {
206    let read = |path: &str| std::fs::read_to_string(path).ok();
207    let status = read("/proc/self/status")?;
208    let allowed = status
209        .lines()
210        .find_map(|line| line.strip_prefix("Cpus_allowed_list:"))?;
211    count_cores(
212        &read("/sys/devices/system/cpu/online")?,
213        allowed,
214        read("/sys/devices/cpu_core/cpus").as_deref(),
215        |cpu| {
216            read(&format!(
217                "/sys/devices/system/cpu/cpu{cpu}/topology/core_cpus_list"
218            ))
219        },
220    )
221}
222
223/// Cores with an allowed online processor; without a performance list, every core is one.
224#[cfg(target_os = "linux")]
225fn count_cores(
226    online: &str,
227    allowed: &str,
228    performance: Option<&str>,
229    siblings: impl Fn(usize) -> Option<String>,
230) -> Option<Cores> {
231    let (online, allowed) = (cpu_list(online)?, cpu_list(allowed)?);
232    let performance = match performance {
233        Some(listed) => Some(cpu_list(listed)?),
234        None => None,
235    };
236    let (mut fast, mut slow) = (BTreeSet::new(), BTreeSet::new());
237    for cpu in allowed.into_iter().filter(|cpu| online.contains(cpu)) {
238        let core = siblings(cpu)?.trim().to_owned();
239        if performance
240            .as_ref()
241            .is_none_or(|listed| listed.contains(&cpu))
242        {
243            fast.insert(core);
244        } else {
245            slow.insert(core);
246        }
247    }
248    Some(Cores {
249        performance: fast.len(),
250        efficiency: slow.len(),
251    })
252}
253
254/// The processors of a sysfs CPU list such as `0-7,16,18-19`.
255#[cfg(target_os = "linux")]
256fn cpu_list(text: &str) -> Option<Vec<usize>> {
257    let mut cpus = Vec::new();
258    for part in text.trim().split(',') {
259        match part.split_once('-') {
260            Some((first, last)) => cpus.extend(first.parse::<usize>().ok()?..=last.parse().ok()?),
261            None => cpus.push(part.parse().ok()?),
262        }
263    }
264    Some(cpus)
265}
266
267/// Performance levels 0 and 1, fastest first (Intel Macs: 0 only); macOS has no affinity masks.
268#[cfg(target_os = "macos")]
269pub(crate) fn allowed_cores() -> Option<Cores> {
270    let efficiency = match sysctl_count(c"hw.nperflevels")? {
271        1 => 0,
272        _ => sysctl_count(c"hw.perflevel1.physicalcpu")?,
273    };
274    Some(Cores {
275        performance: sysctl_count(c"hw.perflevel0.physicalcpu")?,
276        efficiency,
277    })
278}
279
280#[cfg(target_os = "macos")]
281fn sysctl_count(name: &std::ffi::CStr) -> Option<usize> {
282    use std::ffi::{c_char, c_int, c_void};
283
284    unsafe extern "C" {
285        fn sysctlbyname(
286            name: *const c_char,
287            old: *mut c_void,
288            old_length: *mut usize,
289            new: *mut c_void,
290            new_length: usize,
291        ) -> c_int;
292    }
293    let mut count: c_int = 0;
294    let mut length = size_of::<c_int>();
295    // SAFETY: `count` holds `length` bytes, and no new value is passed.
296    let status = unsafe {
297        sysctlbyname(
298            name.as_ptr(),
299            (&raw mut count).cast(),
300            &mut length,
301            std::ptr::null_mut(),
302            0,
303        )
304    };
305    if status != 0 || length != size_of::<c_int>() {
306        return None;
307    }
308    usize::try_from(count).ok()
309}
310
311/// No topology source elsewhere: short inputs use [`POOL`].
312#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
313pub(crate) fn allowed_cores() -> Option<Cores> {
314    None
315}
316
317/// `threads` workers named `name-0`, `name-1`, ... (0: one per logical processor).
318#[cfg(not(target_family = "wasm"))]
319pub fn worker_pool(name: &'static str, threads: usize) -> Result<Workers, ThreadPoolBuildError> {
320    rayon::ThreadPoolBuilder::new()
321        .num_threads(threads)
322        .thread_name(move |index| format!("{name}-{index}"))
323        .start_handler(|_| raise_quality_of_service())
324        .build()
325}
326
327/// Rayon's own pool whatever `threads` asks: a caller that needs a count compares it.
328#[cfg(target_family = "wasm")]
329pub fn worker_pool(_name: &'static str, _threads: usize) -> Result<Workers, ThreadPoolBuildError> {
330    Ok(Workers)
331}
332
333#[cfg(not(target_family = "wasm"))]
334fn raise_quality_of_service() {
335    #[cfg(windows)]
336    {
337        use std::ffi::c_void;
338
339        /// THREAD_POWER_THROTTLING_STATE.
340        #[repr(C)]
341        struct State {
342            version: u32,
343            control_mask: u32,
344            state_mask: u32,
345        }
346        const CURRENT_VERSION: u32 = 1;
347        const EXECUTION_SPEED: u32 = 0x1;
348        /// ThreadPowerThrottling in THREAD_INFORMATION_CLASS.
349        const POWER_THROTTLING: i32 = 3;
350
351        #[link(name = "kernel32")]
352        unsafe extern "system" {
353            fn GetCurrentThread() -> *mut c_void;
354            fn SetThreadInformation(
355                thread: *mut c_void,
356                class: i32,
357                information: *const c_void,
358                size: u32,
359            ) -> i32;
360        }
361
362        // The control bit set with the state bit clear asks for high quality of service.
363        let state = State {
364            version: CURRENT_VERSION,
365            control_mask: EXECUTION_SPEED,
366            state_mask: 0,
367        };
368        // SAFETY: `state` has the size given and outlives the call.
369        let _ = unsafe {
370            SetThreadInformation(
371                GetCurrentThread(),
372                POWER_THROTTLING,
373                (&raw const state).cast(),
374                size_of::<State>() as u32,
375            )
376        };
377        // Best effort: older Windows versions and restricted hosts can refuse it.
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::Cores;
384
385    fn cores(performance: usize, efficiency: usize) -> Cores {
386        Cores {
387            performance,
388            efficiency,
389        }
390    }
391
392    /// A hybrid processor's masks, one thread per core; then one core class with and without SMT.
393    #[test]
394    fn short_pool_follows_the_core_ratio() {
395        for (allowed, pool, short) in [
396            (cores(6, 8), 14, Some(6)),
397            (cores(4, 8), 12, Some(4)),
398            (cores(2, 2), 4, Some(2)),
399            (cores(2, 8), 10, None),
400            (cores(1, 4), 5, None),
401            (cores(0, 8), 8, None),
402            (cores(6, 0), 6, None),
403            (cores(6, 0), 12, Some(6)),
404        ] {
405            assert_eq!(
406                super::short_pool_threads(allowed, pool),
407                short,
408                "{allowed:?}"
409            );
410        }
411    }
412
413    /// A processor-core record: its efficiency class, then one group affinity in group 0.
414    fn core_record(class: u8, mask: usize) -> Vec<u8> {
415        let mut record = vec![0; 40 + size_of::<usize>()];
416        let size = record.len() as u32;
417        record[4..8].copy_from_slice(&size.to_le_bytes());
418        record[9] = class;
419        record[30..32].copy_from_slice(&1_u16.to_le_bytes());
420        record[32..32 + size_of::<usize>()].copy_from_slice(&mask.to_le_bytes());
421        record
422    }
423
424    /// Four two-processor cores of class 1 (0-7) and four of class 0 (8-11).
425    #[test]
426    fn windows_core_records_count_only_allowed_processors() {
427        let records: Vec<u8> = (0..4)
428            .map(|core| core_record(1, 0b11 << (2 * core)))
429            .chain((8..12).map(|processor| core_record(0, 1 << processor)))
430            .flatten()
431            .collect();
432        let count = |allowed: usize| {
433            super::count_core_records(&records, |group, mask| group == 0 && mask & allowed != 0)
434        };
435        assert_eq!(count(0xFFF), Some(cores(4, 4)));
436        assert_eq!(count(0b1000_0101), Some(cores(3, 0)));
437        assert_eq!(count(0b11_0000_0010), Some(cores(1, 2)));
438        assert_eq!(count(0xF00), Some(cores(0, 4)));
439        let alike: Vec<u8> = (0..4)
440            .flat_map(|core| core_record(0, 0b11 << (2 * core)))
441            .collect();
442        assert_eq!(
443            super::count_core_records(&alike, |_, _| true),
444            Some(cores(4, 0))
445        );
446    }
447
448    /// An i5-13500: six two-thread performance cores (0-11), eight efficiency cores.
449    #[cfg(target_os = "linux")]
450    #[test]
451    fn linux_cores_count_only_allowed_processors() {
452        let siblings = |cpu: usize| {
453            Some(if cpu < 12 {
454                format!("{}-{}\n", cpu & !1, cpu | 1)
455            } else {
456                format!("{cpu}\n")
457            })
458        };
459        let listed = Some("0-11\n");
460        for (online, allowed, performance, counted) in [
461            ("0-19\n", "0-19\n", listed, cores(6, 8)),
462            ("0-19\n", "0,2,4,7,12-19\n", listed, cores(4, 8)),
463            ("0-19\n", "1,12-15\n", listed, cores(1, 4)),
464            ("0-19\n", "12-17\n", listed, cores(0, 6)),
465            ("0-15\n", "0-19\n", listed, cores(6, 4)),
466            ("0-19\n", "0-19\n", None, cores(14, 0)),
467        ] {
468            let count = super::count_cores(online, allowed, performance, siblings);
469            assert_eq!(count, Some(counted), "{online} {allowed}");
470        }
471    }
472
473    #[cfg(target_os = "macos")]
474    #[test]
475    fn macs_report_their_cores() {
476        let logical = std::thread::available_parallelism().unwrap().get();
477        let cores = super::allowed_cores().unwrap();
478        assert!(cores.performance > 0 && cores.performance + cores.efficiency <= logical);
479    }
480
481    #[cfg(target_os = "linux")]
482    #[test]
483    fn cpu_lists_expand_ranges_and_single_processors() {
484        assert_eq!(
485            super::cpu_list("0-3,8,10-11\n"),
486            Some(vec![0, 1, 2, 3, 8, 10, 11])
487        );
488        assert_eq!(super::cpu_list("5"), Some(vec![5]));
489        assert_eq!(super::cpu_list(""), None);
490        assert_eq!(super::cpu_list("0-x"), None);
491    }
492}