Skip to main content

ntex_server/
affinity.rs

1use std::{cell::Cell, collections::BTreeMap, fmt};
2
3#[non_exhaustive]
4#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
5/// CPU affinity of worker threads.
6///
7/// Workers are placed on one logical CPU of each physical core first, spread
8/// across NUMA nodes and shared L3 caches, and on the remaining SMT siblings
9/// after that. On hybrid CPUs, performance cores are used before efficiency
10/// cores. When there are more workers than CPUs, the placement starts over.
11///
12/// The default is [`Soft`](Self::Soft) on Windows and [`Core`](Self::Core) on
13/// other platforms. Affinity is supported on Windows, Linux and Android, other
14/// platforms ignore it.
15pub enum Affinity {
16    /// Worker threads are not pinned, the OS scheduler places them.
17    Disabled,
18    /// Pins each worker to one logical CPU.
19    Cpu,
20    /// Pins each worker to the logical CPUs of one physical core.
21    ///
22    /// The scheduler can move the worker between the SMT siblings of its
23    /// core. Works like [`Cpu`](Self::Cpu) on CPUs without SMT.
24    Core,
25    /// Sets the preferred CPU of each worker without pinning it.
26    ///
27    /// On Windows, this sets the ideal processor of the worker thread. The
28    /// scheduler runs the worker there when that CPU is free, and on another
29    /// CPU otherwise. On machines with several processor groups, the worker is
30    /// also kept in the group of its CPU. Other platforms have no such hint,
31    /// there it works like [`Core`](Self::Core).
32    Soft,
33}
34
35impl Default for Affinity {
36    fn default() -> Self {
37        if cfg!(windows) {
38            Affinity::Soft
39        } else {
40            Affinity::Core
41        }
42    }
43}
44
45#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
46/// Logical CPU, `group` is the Windows processor group.
47pub(crate) struct Cpu {
48    group: u16,
49    num: u32,
50}
51
52impl fmt::Display for Cpu {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        if self.group == 0 {
55            write!(f, "{}", self.num)
56        } else {
57            write!(f, "{}:{}", self.group, self.num)
58        }
59    }
60}
61
62#[derive(Copy, Clone, Debug)]
63/// Topology of one logical CPU.
64///
65/// `core`, `l3` and `node` identify the physical core, L3 cache and NUMA
66/// node. Higher `class` means a faster core. `allowed` is `false` if the
67/// process may not use the CPU.
68struct CpuInfo {
69    cpu: Cpu,
70    core: usize,
71    l3: usize,
72    node: usize,
73    class: u32,
74    allowed: bool,
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
78/// CPU placement of a worker thread.
79pub(crate) struct Placement {
80    mode: Affinity,
81    cpu: Cpu,
82    /// Logical CPUs of the physical core of `cpu` the process may use.
83    core: Vec<Cpu>,
84    /// All logical CPUs of the physical core of `cpu`.
85    siblings: Vec<Cpu>,
86}
87
88impl Placement {
89    /// Pins to the logical CPU with index `idx`.
90    ///
91    /// On Windows, CPUs are numbered across processor groups, the CPUs of
92    /// group 1 follow the CPUs of group 0.
93    pub(crate) fn cpu(idx: usize) -> Self {
94        let cpu = sys::cpu(idx);
95        Placement {
96            mode: Affinity::Cpu,
97            cpu,
98            core: vec![cpu],
99            siblings: vec![cpu],
100        }
101    }
102
103    /// Applies the placement to the current thread.
104    pub(crate) fn apply(&self) -> bool {
105        sys::apply(self.mode, self.cpu, &self.core)
106    }
107
108    /// Returns the index of the placement CPU, followed by the indexes of
109    /// its SMT siblings, including siblings the process may not use. The
110    /// network stack may still process packets on them.
111    pub(crate) fn cpus(&self) -> Vec<usize> {
112        let mut cpus = vec![sys::index(self.cpu)];
113        cpus.extend(
114            self.siblings
115                .iter()
116                .filter(|cpu| **cpu != self.cpu)
117                .map(|cpu| sys::index(*cpu)),
118        );
119        cpus
120    }
121}
122
123/// Returns the index of the logical CPU that receives the packets of the
124/// connection, if known.
125///
126/// On Windows, this is the receive-side scaling (RSS) CPU of the connection,
127/// on Linux and Android the CPU that processed its last received packet
128/// (`SO_INCOMING_CPU`). Not supported on other platforms.
129pub(crate) fn incoming_cpu(stream: &std::net::TcpStream) -> Option<usize> {
130    sys::incoming_cpu(stream).map(sys::index)
131}
132
133thread_local! {
134    static CURRENT_CPU: Cell<Option<usize>> = const { Cell::new(None) };
135}
136
137/// Sets the index of the CPU the current worker thread is placed on.
138pub(crate) fn set_current_cpu(cpu: Option<usize>) {
139    CURRENT_CPU.with(|c| c.set(cpu));
140}
141
142/// Returns the index of the CPU the current worker thread is placed on.
143pub(crate) fn current_cpu() -> Option<usize> {
144    CURRENT_CPU.with(Cell::get)
145}
146
147/// Sets `SO_INCOMING_CPU` of the listener, so `SO_REUSEPORT` sends
148/// connections whose packets are processed on `cpu` to this listener.
149///
150/// Supported on Linux and Android.
151pub(crate) fn set_incoming_cpu(lst: &std::net::TcpListener, cpu: usize) -> std::io::Result<()> {
152    sys::set_incoming_cpu(lst, cpu)
153}
154
155impl fmt::Display for Placement {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        write!(f, "{:?} cpu {} (core", self.mode, self.cpu)?;
158        for c in &self.core {
159            write!(f, " {c}")?;
160        }
161        write!(f, ")")
162    }
163}
164
165/// Returns worker placements in the order workers should use them.
166///
167/// Each logical CPU available to the process appears once. Empty if
168/// affinity is disabled or not supported.
169pub(crate) fn plan(mode: Affinity) -> Vec<Placement> {
170    if mode == Affinity::Disabled {
171        return Vec::new();
172    }
173    order(&sys::topology())
174        .into_iter()
175        .map(|(cpu, core, siblings)| Placement {
176            mode,
177            cpu,
178            core,
179            siblings,
180        })
181        .collect()
182}
183
184/// Returns the number of logical CPUs the process may use.
185pub(crate) fn cpu_count() -> usize {
186    // std counts only one processor group on Windows
187    if cfg!(windows) {
188        let n = sys::topology().iter().filter(|info| info.allowed).count();
189        if n > 0 {
190            return n;
191        }
192    }
193    std::thread::available_parallelism().map_or(2, std::num::NonZeroUsize::get)
194}
195
196struct Core {
197    cpus: Vec<Cpu>,
198    all: Vec<Cpu>,
199    l3: usize,
200    node: usize,
201    class: u32,
202}
203
204/// Orders the logical CPUs the process may use, see [`Affinity`].
205///
206/// Returns each CPU with the CPUs of its physical core the process may use,
207/// and all CPUs of that core.
208fn order(cpus: &[CpuInfo]) -> Vec<(Cpu, Vec<Cpu>, Vec<Cpu>)> {
209    let mut cores = BTreeMap::<usize, Core>::new();
210    for info in cpus {
211        let core = cores.entry(info.core).or_insert_with(|| Core {
212            cpus: Vec::new(),
213            all: Vec::new(),
214            l3: info.l3,
215            node: info.node,
216            class: info.class,
217        });
218        core.all.push(info.cpu);
219        if info.allowed {
220            core.cpus.push(info.cpu);
221        }
222    }
223    let mut cores: Vec<Core> = cores
224        .into_values()
225        .filter(|core| !core.cpus.is_empty())
226        .collect();
227    for core in &mut cores {
228        core.cpus.sort_unstable();
229        core.cpus.dedup();
230        core.all.sort_unstable();
231        core.all.dedup();
232    }
233    cores.sort_by_key(|core| core.cpus[0]);
234
235    let mut classes: Vec<u32> = cores.iter().map(|core| core.class).collect();
236    classes.sort_unstable_by(|a, b| b.cmp(a));
237    classes.dedup();
238
239    // cores of each class, interleaved across L3 caches within a NUMA node,
240    // then across NUMA nodes
241    let mut seq = Vec::with_capacity(cores.len());
242    for class in classes {
243        let mut nodes = BTreeMap::<usize, BTreeMap<usize, Vec<&Core>>>::new();
244        for core in cores.iter().filter(|core| core.class == class) {
245            nodes
246                .entry(core.node)
247                .or_default()
248                .entry(core.l3)
249                .or_default()
250                .push(core);
251        }
252        seq.extend(interleave(
253            nodes
254                .into_values()
255                .map(|l3| interleave(l3.into_values().collect()))
256                .collect(),
257        ));
258    }
259
260    // first logical CPU of every core, then the second one, and so on
261    let depth = cores.iter().map(|core| core.cpus.len()).max().unwrap_or(0);
262    let mut result = Vec::with_capacity(cpus.len());
263    for idx in 0..depth {
264        for core in &seq {
265            if let Some(cpu) = core.cpus.get(idx) {
266                result.push((*cpu, core.cpus.clone(), core.all.clone()));
267            }
268        }
269    }
270    result
271}
272
273/// Takes the first item of each list, then the second one, and so on.
274fn interleave<T>(lists: Vec<Vec<T>>) -> Vec<T> {
275    let mut iters: Vec<_> = lists.into_iter().map(Vec::into_iter).collect();
276    let mut result = Vec::new();
277    loop {
278        let len = result.len();
279        result.extend(iters.iter_mut().filter_map(Iterator::next));
280        if result.len() == len {
281            return result;
282        }
283    }
284}
285
286#[cfg(any(target_os = "linux", target_os = "android"))]
287mod sys {
288    use std::{fs, io, mem, path::Path};
289
290    use super::{Affinity, Cpu, CpuInfo};
291
292    pub(super) fn topology() -> Vec<CpuInfo> {
293        let root = Path::new("/sys/devices/system/cpu");
294        let allowed = allowed();
295        let mut cpus = list(&root.join("online")).unwrap_or_default();
296        cpus.extend(&allowed);
297        cpus.sort_unstable();
298        cpus.dedup();
299        read(root, &cpus, &allowed)
300    }
301
302    /// Reads the topology of `cpus` from sysfs at `root`, the process may
303    /// use the `allowed` ones.
304    pub(super) fn read(root: &Path, cpus: &[u32], allowed: &[u32]) -> Vec<CpuInfo> {
305        cpus.iter()
306            .map(|&num| {
307                let dir = root.join(format!("cpu{num}"));
308                let first = |files: &[&str]| {
309                    files
310                        .iter()
311                        .find_map(|file| list(&dir.join(file))?.into_iter().min())
312                        .unwrap_or(num) as usize
313                };
314                let node = fs::read_dir(&dir)
315                    .ok()
316                    .and_then(|entries| {
317                        entries.flatten().find_map(|entry| {
318                            entry
319                                .file_name()
320                                .to_str()?
321                                .strip_prefix("node")?
322                                .parse()
323                                .ok()
324                        })
325                    })
326                    .unwrap_or(0);
327                let class = fs::read_to_string(dir.join("cpu_capacity"))
328                    .ok()
329                    .and_then(|s| s.trim().parse().ok())
330                    .unwrap_or(0);
331
332                CpuInfo {
333                    cpu: Cpu { group: 0, num },
334                    core: first(&["topology/core_cpus_list", "topology/thread_siblings_list"]),
335                    l3: first(&[
336                        "cache/index3/shared_cpu_list",
337                        "topology/package_cpus_list",
338                        "topology/core_siblings_list",
339                    ]),
340                    node,
341                    class,
342                    allowed: allowed.contains(&num),
343                }
344            })
345            .collect()
346    }
347
348    fn list(path: &Path) -> Option<Vec<u32>> {
349        parse_list(&fs::read_to_string(path).ok()?)
350    }
351
352    /// Parses a CPU list like `0-3,8-11`.
353    pub(super) fn parse_list(s: &str) -> Option<Vec<u32>> {
354        let mut cpus = Vec::new();
355        for item in s.trim().split(',').filter(|item| !item.is_empty()) {
356            if let Some((from, to)) = item.split_once('-') {
357                cpus.extend(from.parse::<u32>().ok()?..=to.parse().ok()?);
358            } else {
359                cpus.push(item.parse().ok()?);
360            }
361        }
362        Some(cpus)
363    }
364
365    /// Returns the CPUs the current thread may run on.
366    fn allowed() -> Vec<u32> {
367        query_mask(|mask| {
368            // SAFETY: the kernel writes at most `size_of_val(mask)` bytes,
369            // the mask has the layout of a larger `cpu_set_t`
370            let res = unsafe {
371                libc::sched_getaffinity(0, mem::size_of_val(mask), mask.as_mut_ptr().cast())
372            };
373            if res == 0 {
374                Ok(())
375            } else {
376                Err(std::io::Error::last_os_error().raw_os_error().unwrap_or(0))
377            }
378        })
379        .unwrap_or_default()
380    }
381
382    /// Words of a `cpu_set_t`.
383    const SET_WORDS: usize = mem::size_of::<libc::cpu_set_t>() / mem::size_of::<libc::c_ulong>();
384    /// Largest mask tried, in words.
385    const MAX_WORDS: usize = SET_WORDS << 10;
386
387    /// Reads a CPU mask with `query`.
388    ///
389    /// The kernel mask may be larger than `cpu_set_t`, the query fails with
390    /// `EINVAL` until the mask is large enough.
391    pub(super) fn query_mask(
392        mut query: impl FnMut(&mut [libc::c_ulong]) -> Result<(), i32>,
393    ) -> Option<Vec<u32>> {
394        let mut words = SET_WORDS;
395        loop {
396            let mut mask = vec![0; words];
397            match query(&mut mask) {
398                Ok(()) => {
399                    let bits = libc::c_ulong::BITS;
400                    return Some(
401                        (0u32..)
402                            .zip(&mask)
403                            .flat_map(|(idx, word)| {
404                                (0..bits)
405                                    .filter(move |bit| word & (1 << bit) != 0)
406                                    .map(move |bit| idx * bits + bit)
407                            })
408                            .collect(),
409                    );
410                }
411                Err(libc::EINVAL) if words < MAX_WORDS => words *= 2,
412                Err(_) => return None,
413            }
414        }
415    }
416
417    /// Returns a CPU mask of `cpus`, at least the size of `cpu_set_t`.
418    pub(super) fn mask_of(cpus: &[Cpu]) -> Vec<libc::c_ulong> {
419        let bits = libc::c_ulong::BITS;
420        let max = cpus.iter().map(|cpu| cpu.num / bits + 1).max().unwrap_or(0);
421        let mut mask = vec![0; SET_WORDS.max(max as usize)];
422        for cpu in cpus {
423            mask[(cpu.num / bits) as usize] |= 1 << (cpu.num % bits);
424        }
425        mask
426    }
427
428    pub(super) fn cpu(idx: usize) -> Cpu {
429        Cpu {
430            group: 0,
431            num: u32::try_from(idx).unwrap_or(u32::MAX),
432        }
433    }
434
435    pub(super) fn index(cpu: Cpu) -> usize {
436        usize::try_from(cpu.num).unwrap_or(usize::MAX)
437    }
438
439    #[cfg(target_os = "linux")]
440    const SO_INCOMING_CPU: libc::c_int = libc::SO_INCOMING_CPU;
441    #[cfg(target_os = "android")]
442    const SO_INCOMING_CPU: libc::c_int = 49;
443
444    pub(super) fn set_incoming_cpu(lst: &std::net::TcpListener, cpu: usize) -> io::Result<()> {
445        use std::os::fd::AsRawFd;
446
447        let cpu = libc::c_int::try_from(cpu).map_err(io::Error::other)?;
448        let len =
449            libc::socklen_t::try_from(mem::size_of::<libc::c_int>()).map_err(io::Error::other)?;
450        // SAFETY: the input buffer holds `len` bytes
451        let res = unsafe {
452            libc::setsockopt(
453                lst.as_raw_fd(),
454                libc::SOL_SOCKET,
455                SO_INCOMING_CPU,
456                (&raw const cpu).cast(),
457                len,
458            )
459        };
460        if res == 0 {
461            Ok(())
462        } else {
463            Err(io::Error::last_os_error())
464        }
465    }
466
467    pub(super) fn incoming_cpu(stream: &std::net::TcpStream) -> Option<Cpu> {
468        use std::os::fd::AsRawFd;
469
470        let mut cpu: libc::c_int = -1;
471        let mut len = libc::socklen_t::try_from(mem::size_of::<libc::c_int>()).ok()?;
472        // SAFETY: the output buffer holds `len` bytes
473        let res = unsafe {
474            libc::getsockopt(
475                stream.as_raw_fd(),
476                libc::SOL_SOCKET,
477                SO_INCOMING_CPU,
478                (&raw mut cpu).cast(),
479                &raw mut len,
480            )
481        };
482        // -1 if no packet was received yet
483        let num = u32::try_from(cpu).ok().filter(|_| res == 0)?;
484        Some(Cpu { group: 0, num })
485    }
486
487    pub(super) fn apply(mode: Affinity, cpu: Cpu, core: &[Cpu]) -> bool {
488        let cpus = if mode == Affinity::Cpu {
489            std::slice::from_ref(&cpu)
490        } else {
491            core
492        };
493        if cpus
494            .iter()
495            .any(|cpu| cpu.num as usize >= MAX_WORDS * libc::c_ulong::BITS as usize)
496        {
497            return false;
498        }
499        let mask = mask_of(cpus);
500        // SAFETY: the kernel reads `size_of_val(mask)` bytes, the mask has
501        // the layout of a larger `cpu_set_t`
502        unsafe {
503            libc::sched_setaffinity(0, mem::size_of_val(&mask[..]), mask.as_ptr().cast()) == 0
504        }
505    }
506
507    #[cfg(test)]
508    /// Returns the CPUs the current thread may run on and its preferred CPU.
509    pub(super) fn current() -> (Vec<Cpu>, Option<Cpu>) {
510        let cpus = allowed()
511            .into_iter()
512            .map(|num| Cpu { group: 0, num })
513            .collect();
514        (cpus, None)
515    }
516}
517
518#[cfg(windows)]
519mod sys {
520    use std::{mem, net::TcpStream, os::windows::io::AsRawSocket, ptr};
521
522    use windows_sys::Win32::Networking::WinSock::{
523        SIO_QUERY_RSS_PROCESSOR_INFO, SOCKET, SOCKET_PROCESSOR_AFFINITY, WSAIoctl,
524    };
525    use windows_sys::Win32::System::JobObjects::{
526        JobObjectGroupInformationEx, QueryInformationJobObject,
527    };
528    use windows_sys::Win32::System::Kernel::PROCESSOR_NUMBER;
529    use windows_sys::Win32::System::SystemInformation::{
530        CpuSetInformation, GROUP_AFFINITY, GetLogicalProcessorInformationEx,
531        GetSystemCpuSetInformation, RelationAll, RelationCache, RelationNumaNode,
532        RelationNumaNodeEx, RelationProcessorCore, SYSTEM_CPU_SET_INFORMATION,
533        SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
534    };
535    use windows_sys::Win32::System::Threading::{
536        GetActiveProcessorCount, GetActiveProcessorGroupCount, GetCurrentProcess, GetCurrentThread,
537        GetProcessAffinityMask, GetProcessDefaultCpuSets, GetProcessGroupAffinity,
538        GetThreadGroupAffinity, SetThreadGroupAffinity, SetThreadIdealProcessorEx,
539    };
540
541    use super::{Affinity, Cpu, CpuInfo};
542
543    #[allow(non_upper_case_globals)]
544    pub(super) fn topology() -> Vec<CpuInfo> {
545        let Some(buf) = query() else {
546            return Vec::new();
547        };
548
549        let mut cpus = Vec::new();
550        let mut l3 = Vec::new();
551        let mut nodes = Vec::new();
552        let base = buf.as_ptr();
553        let len = buf.len() * mem::size_of::<u64>();
554        let mut offset = 0;
555        let mut idx = 0;
556
557        // SAFETY: records are 8-byte aligned and lie within the buffer filled
558        // by GetLogicalProcessorInformationEx, `GroupCount` masks follow
559        // each record's mask field
560        unsafe {
561            while offset + mem::size_of::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>() <= len {
562                let rec = base
563                    .byte_add(offset)
564                    .cast::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>();
565                let size = (*rec).Size as usize;
566                if size == 0 {
567                    break;
568                }
569                let info = ptr::addr_of!((*rec).Anonymous);
570                match (*rec).Relationship {
571                    RelationProcessorCore => {
572                        let p = ptr::addr_of!((*info).Processor);
573                        let class = u32::from((*p).EfficiencyClass);
574                        let masks = ptr::addr_of!((*p).GroupMask).cast::<GROUP_AFFINITY>();
575                        for mask in masks_of(masks, (*p).GroupCount) {
576                            cpus.extend(cpus_of(&mask).map(|cpu| CpuInfo {
577                                cpu,
578                                core: idx,
579                                l3: usize::MAX,
580                                node: usize::MAX - usize::from(cpu.group),
581                                class,
582                                allowed: true,
583                            }));
584                        }
585                    }
586                    RelationCache => {
587                        let c = ptr::addr_of!((*info).Cache);
588                        if (*c).Level == 3 {
589                            let masks = ptr::addr_of!((*c).Anonymous).cast::<GROUP_AFFINITY>();
590                            l3.extend(masks_of(masks, (*c).GroupCount).map(|m| (idx, m)));
591                        }
592                    }
593                    RelationNumaNode | RelationNumaNodeEx => {
594                        let n = ptr::addr_of!((*info).NumaNode);
595                        let node = (*n).NodeNumber as usize;
596                        let masks = ptr::addr_of!((*n).Anonymous).cast::<GROUP_AFFINITY>();
597                        nodes.extend(masks_of(masks, (*n).GroupCount).map(|m| (node, m)));
598                    }
599                    _ => (),
600                }
601                offset += size;
602                idx += 1;
603            }
604        }
605
606        let contains = |mask: &GROUP_AFFINITY, cpu: Cpu| {
607            mask.Group == cpu.group && cpu.num < usize::BITS && mask.Mask & (1 << cpu.num) != 0
608        };
609        for info in &mut cpus {
610            if let Some((id, _)) = l3.iter().find(|(_, m)| contains(m, info.cpu)) {
611                info.l3 = *id;
612            } else {
613                // no L3 cache, group by NUMA node
614                info.l3 = usize::MAX - usize::from(info.cpu.group);
615            }
616            if let Some((id, _)) = nodes.iter().find(|(_, m)| contains(m, info.cpu)) {
617                info.node = *id;
618            }
619        }
620
621        let mask = affinity_mask();
622        for info in &mut cpus {
623            info.allowed = mask.is_none_or(|(group, mask)| {
624                info.cpu.group == group
625                    && info.cpu.num < usize::BITS
626                    && mask & (1 << info.cpu.num) != 0
627            });
628        }
629        if let Some(restricted) = restricted()
630            && cpus
631                .iter()
632                .any(|info| info.allowed && restricted.contains(&info.cpu))
633        {
634            for info in &mut cpus {
635                info.allowed &= restricted.contains(&info.cpu);
636            }
637        }
638        cpus
639    }
640
641    /// Returns the CPUs allowed by the job object group affinity and the
642    /// default CPU sets of the process, if any.
643    ///
644    /// The process affinity mask covers only one processor group.
645    pub(super) fn restricted() -> Option<Vec<Cpu>> {
646        let mut result: Option<Vec<Cpu>> = None;
647
648        // SAFETY: buffers hold the lengths passed with them
649        unsafe {
650            let mut masks = [GROUP_AFFINITY::default(); 64];
651            let mut len = 0u32;
652            if QueryInformationJobObject(
653                ptr::null_mut(),
654                JobObjectGroupInformationEx,
655                masks.as_mut_ptr().cast(),
656                u32::try_from(mem::size_of_val(&masks)).unwrap_or(0),
657                &raw mut len,
658            ) != 0
659            {
660                let n = len as usize / mem::size_of::<GROUP_AFFINITY>();
661                let cpus: Vec<Cpu> = masks[..n.min(masks.len())]
662                    .iter()
663                    .flat_map(cpus_of)
664                    .collect();
665                if !cpus.is_empty() {
666                    result = Some(cpus);
667                }
668            }
669
670            let process = GetCurrentProcess();
671            let mut count = 0u32;
672            GetProcessDefaultCpuSets(process, ptr::null_mut(), 0, &raw mut count);
673            let mut ids = vec![0u32; count as usize];
674            if count > 0
675                && GetProcessDefaultCpuSets(process, ids.as_mut_ptr(), count, &raw mut count) != 0
676            {
677                ids.truncate(count as usize);
678                let sets: Vec<Cpu> = cpu_sets()
679                    .into_iter()
680                    .filter(|(id, cpu)| {
681                        ids.contains(id) && result.as_ref().is_none_or(|r| r.contains(cpu))
682                    })
683                    .map(|(_, cpu)| cpu)
684                    .collect();
685                if !sets.is_empty() {
686                    result = Some(sets);
687                }
688            }
689        }
690        result
691    }
692
693    /// Returns the id and CPU of each CPU set of the system.
694    fn cpu_sets() -> Vec<(u32, Cpu)> {
695        let mut result = Vec::new();
696        // SAFETY: the buffer holds `len` bytes and is 8-byte aligned, records
697        // lie within the buffer
698        unsafe {
699            let mut len = 0u32;
700            GetSystemCpuSetInformation(ptr::null_mut(), 0, &raw mut len, ptr::null_mut(), 0);
701            let mut buf = vec![0u64; (len as usize).div_ceil(mem::size_of::<u64>())];
702            if GetSystemCpuSetInformation(
703                buf.as_mut_ptr().cast(),
704                len,
705                &raw mut len,
706                ptr::null_mut(),
707                0,
708            ) == 0
709            {
710                return result;
711            }
712            let base = buf.as_ptr();
713            let mut offset = 0;
714            while offset + mem::size_of::<SYSTEM_CPU_SET_INFORMATION>() <= len as usize {
715                let rec = base.byte_add(offset).cast::<SYSTEM_CPU_SET_INFORMATION>();
716                let size = (*rec).Size as usize;
717                if size == 0 {
718                    break;
719                }
720                if (*rec).Type == CpuSetInformation {
721                    let set = ptr::addr_of!((*rec).Anonymous.CpuSet);
722                    result.push((
723                        (*set).Id,
724                        Cpu {
725                            group: (*set).Group,
726                            num: u32::from((*set).LogicalProcessorIndex),
727                        },
728                    ));
729                }
730                offset += size;
731            }
732        }
733        result
734    }
735
736    fn query() -> Option<Vec<u64>> {
737        let mut len = 0u32;
738        // SAFETY: the buffer holds `len` bytes and is 8-byte aligned
739        unsafe {
740            GetLogicalProcessorInformationEx(RelationAll, ptr::null_mut(), &raw mut len);
741            for _ in 0..3 {
742                let mut buf = vec![0u64; (len as usize).div_ceil(mem::size_of::<u64>())];
743                if GetLogicalProcessorInformationEx(
744                    RelationAll,
745                    buf.as_mut_ptr().cast(),
746                    &raw mut len,
747                ) != 0
748                {
749                    buf.truncate((len as usize).div_ceil(mem::size_of::<u64>()));
750                    return Some(buf);
751                }
752            }
753        }
754        None
755    }
756
757    /// Reads `count` group masks starting at `ptr`.
758    ///
759    /// Older Windows versions report zero for a single mask.
760    unsafe fn masks_of(
761        ptr: *const GROUP_AFFINITY,
762        count: u16,
763    ) -> impl Iterator<Item = GROUP_AFFINITY> {
764        // SAFETY: the caller guarantees `count` masks at `ptr`
765        (0..usize::from(count.max(1))).map(move |i| unsafe { ptr.add(i).read_unaligned() })
766    }
767
768    fn cpus_of(mask: &GROUP_AFFINITY) -> impl Iterator<Item = Cpu> {
769        let (group, mask) = (mask.Group, mask.Mask);
770        (0..usize::BITS)
771            .filter(move |num| mask & (1 << num) != 0)
772            .map(move |num| Cpu { group, num })
773    }
774
775    /// Returns the processor group and affinity mask of the process if the
776    /// mask restricts it to part of its group.
777    ///
778    /// A process starts in one processor group, and its threads may move to
779    /// other groups. The groups the process currently runs in do not restrict
780    /// it, an explicit affinity mask (`start /affinity`, job object affinity
781    /// limits) does.
782    pub(super) fn affinity_mask() -> Option<(u16, usize)> {
783        // SAFETY: plain process affinity queries, the buffer holds one group
784        unsafe {
785            let process = GetCurrentProcess();
786            let (mut mask, mut system) = (0, 0);
787            // zero masks if the process runs in several groups
788            if GetProcessAffinityMask(process, &raw mut mask, &raw mut system) == 0
789                || mask == 0
790                || mask == system
791            {
792                return None;
793            }
794            let (mut count, mut group) = (1u16, 0u16);
795            (GetProcessGroupAffinity(process, &raw mut count, &raw mut group) != 0)
796                .then_some((group, mask))
797        }
798    }
799
800    fn mask_of(cpus: &[Cpu], group: u16) -> usize {
801        cpus.iter()
802            .filter(|cpu| cpu.group == group && cpu.num < usize::BITS)
803            .fold(0, |mask, cpu| mask | (1 << cpu.num))
804    }
805
806    pub(super) fn cpu(mut idx: usize) -> Cpu {
807        // SAFETY: plain processor count queries
808        unsafe {
809            for group in 0..GetActiveProcessorGroupCount() {
810                let n = GetActiveProcessorCount(group);
811                match u32::try_from(idx) {
812                    Ok(num) if num < n => return Cpu { group, num },
813                    _ => idx -= n as usize,
814                }
815            }
816        }
817        // no such CPU, applying it fails
818        Cpu {
819            group: u16::MAX,
820            num: 0,
821        }
822    }
823
824    pub(super) fn index(cpu: Cpu) -> usize {
825        // SAFETY: plain processor count queries
826        let before: u32 = (0..cpu.group)
827            .map(|group| unsafe { GetActiveProcessorCount(group) })
828            .sum();
829        (before + cpu.num) as usize
830    }
831
832    pub(super) fn set_incoming_cpu(_: &std::net::TcpListener, _: usize) -> std::io::Result<()> {
833        Err(std::io::ErrorKind::Unsupported.into())
834    }
835
836    // sockets are pointer-sized, the output buffer has a few bytes
837    #[allow(clippy::cast_possible_truncation)]
838    pub(super) fn incoming_cpu(stream: &TcpStream) -> Option<Cpu> {
839        let mut info = SOCKET_PROCESSOR_AFFINITY::default();
840        let mut len = 0u32;
841        // SAFETY: the output buffer holds the length passed with it, the
842        // call completes synchronously without an overlapped structure
843        let res = unsafe {
844            WSAIoctl(
845                stream.as_raw_socket() as SOCKET,
846                SIO_QUERY_RSS_PROCESSOR_INFO,
847                ptr::null(),
848                0,
849                (&raw mut info).cast(),
850                mem::size_of::<SOCKET_PROCESSOR_AFFINITY>() as u32,
851                &raw mut len,
852                ptr::null_mut(),
853                None,
854            )
855        };
856        (res == 0 && len as usize >= mem::size_of::<SOCKET_PROCESSOR_AFFINITY>()).then_some(Cpu {
857            group: info.Processor.Group,
858            num: u32::from(info.Processor.Number),
859        })
860    }
861
862    pub(super) fn apply(mode: Affinity, cpu: Cpu, core: &[Cpu]) -> bool {
863        // SAFETY: plain thread affinity calls on the current thread
864        unsafe {
865            let thread = GetCurrentThread();
866            let mut affinity = GROUP_AFFINITY {
867                Mask: 0,
868                Group: cpu.group,
869                Reserved: [0; 3],
870            };
871            match mode {
872                Affinity::Disabled => true,
873                Affinity::Cpu | Affinity::Core => {
874                    affinity.Mask = if mode == Affinity::Cpu {
875                        mask_of(&[cpu], cpu.group)
876                    } else {
877                        mask_of(core, cpu.group)
878                    };
879                    SetThreadGroupAffinity(thread, &raw const affinity, ptr::null_mut()) != 0
880                }
881                Affinity::Soft => {
882                    // the ideal processor must be in the thread's group
883                    let mut current = GROUP_AFFINITY::default();
884                    if GetThreadGroupAffinity(thread, &raw mut current) != 0
885                        && current.Group != cpu.group
886                    {
887                        let n = GetActiveProcessorCount(cpu.group);
888                        affinity.Mask = if n >= usize::BITS { usize::MAX } else { (1 << n) - 1 };
889                        if SetThreadGroupAffinity(thread, &raw const affinity, ptr::null_mut()) == 0
890                        {
891                            return false;
892                        }
893                    }
894                    let Ok(num) = u8::try_from(cpu.num) else {
895                        return false;
896                    };
897                    let ideal = PROCESSOR_NUMBER {
898                        Group: cpu.group,
899                        Number: num,
900                        Reserved: 0,
901                    };
902                    SetThreadIdealProcessorEx(thread, &raw const ideal, ptr::null_mut()) != 0
903                }
904            }
905        }
906    }
907
908    #[cfg(test)]
909    /// Returns the CPUs the current thread may run on and its preferred CPU.
910    pub(super) fn current() -> (Vec<Cpu>, Option<Cpu>) {
911        use windows_sys::Win32::System::Threading::GetThreadIdealProcessorEx;
912
913        // SAFETY: plain thread affinity calls on the current thread
914        unsafe {
915            let thread = GetCurrentThread();
916            let mut affinity = GROUP_AFFINITY::default();
917            let cpus = if GetThreadGroupAffinity(thread, &raw mut affinity) != 0 {
918                cpus_of(&affinity).collect()
919            } else {
920                Vec::new()
921            };
922            let mut ideal = PROCESSOR_NUMBER::default();
923            let ideal = (GetThreadIdealProcessorEx(thread, &raw mut ideal) != 0).then_some(Cpu {
924                group: ideal.Group,
925                num: u32::from(ideal.Number),
926            });
927            (cpus, ideal)
928        }
929    }
930}
931
932#[cfg(not(any(windows, target_os = "linux", target_os = "android")))]
933mod sys {
934    use super::{Affinity, Cpu, CpuInfo};
935
936    pub(super) fn topology() -> Vec<CpuInfo> {
937        Vec::new()
938    }
939
940    pub(super) fn cpu(idx: usize) -> Cpu {
941        Cpu {
942            group: 0,
943            num: u32::try_from(idx).unwrap_or(u32::MAX),
944        }
945    }
946
947    pub(super) fn index(cpu: Cpu) -> usize {
948        usize::try_from(cpu.num).unwrap_or(usize::MAX)
949    }
950
951    pub(super) fn incoming_cpu(_: &std::net::TcpStream) -> Option<Cpu> {
952        None
953    }
954
955    pub(super) fn set_incoming_cpu(_: &std::net::TcpListener, _: usize) -> std::io::Result<()> {
956        Err(std::io::ErrorKind::Unsupported.into())
957    }
958
959    pub(super) fn apply(_: Affinity, _: Cpu, _: &[Cpu]) -> bool {
960        false
961    }
962}
963
964#[cfg(test)]
965mod tests {
966    use super::*;
967
968    fn cpu(num: u32) -> Cpu {
969        Cpu { group: 0, num }
970    }
971
972    fn info(num: u32, core: usize, l3: usize, node: usize) -> CpuInfo {
973        CpuInfo {
974            cpu: cpu(num),
975            core,
976            l3,
977            node,
978            class: 0,
979            allowed: true,
980        }
981    }
982
983    fn nums(cpus: &[CpuInfo]) -> Vec<u32> {
984        order(cpus).into_iter().map(|(cpu, ..)| cpu.num).collect()
985    }
986
987    /// STATEMENT: CPU ordering puts one CPU of each core before SMT siblings, for either
988    /// sibling numbering.
989    ///
990    /// HOW:
991    /// - Order 8 CPUs with siblings numbered next to each other (Windows) and apart (Linux).
992    /// - Expect each core's first CPU before the siblings, and both siblings in a core list.
993    #[test]
994    fn order_smt() {
995        // siblings numbered next to each other (Windows)
996        let cpus: Vec<_> = (0..8).map(|n| info(n, n as usize / 2, 0, 0)).collect();
997        assert_eq!(nums(&cpus), [0, 2, 4, 6, 1, 3, 5, 7]);
998        assert_eq!(order(&cpus)[5].1, [cpu(2), cpu(3)]);
999
1000        // siblings numbered apart (Linux)
1001        let cpus: Vec<_> = (0..8).map(|n| info(n, n as usize % 4, 0, 0)).collect();
1002        assert_eq!(nums(&cpus), [0, 1, 2, 3, 4, 5, 6, 7]);
1003        assert_eq!(order(&cpus)[5].1, [cpu(1), cpu(5)]);
1004    }
1005
1006    /// STATEMENT: CPU ordering spreads consecutive CPUs across L3 caches and NUMA nodes.
1007    ///
1008    /// HOW:
1009    /// - Order CPUs with two L3 caches, then two nodes with two caches each.
1010    /// - Expect CPUs to alternate between caches, and between nodes first.
1011    /// - With uneven caches, expect the extra CPUs of the larger cache last.
1012    #[test]
1013    fn order_cache_and_nodes() {
1014        // two L3 caches
1015        let cpus: Vec<_> = (0..8)
1016            .map(|n| info(n, n as usize, n as usize / 4, 0))
1017            .collect();
1018        assert_eq!(nums(&cpus), [0, 4, 1, 5, 2, 6, 3, 7]);
1019
1020        // two NUMA nodes with two L3 caches each
1021        let cpus: Vec<_> = (0..8)
1022            .map(|n| info(n, n as usize, n as usize / 2, n as usize / 4))
1023            .collect();
1024        assert_eq!(nums(&cpus), [0, 4, 2, 6, 1, 5, 3, 7]);
1025
1026        // uneven L3 caches
1027        let cpus: Vec<_> = (0..6)
1028            .map(|n| info(n, n as usize, usize::from(n > 3), 0))
1029            .collect();
1030        assert_eq!(nums(&cpus), [0, 4, 1, 5, 2, 3]);
1031    }
1032
1033    /// STATEMENT: CPU ordering puts performance cores first, then efficiency cores, then SMT
1034    /// siblings.
1035    ///
1036    /// HOW:
1037    /// - Mark 2 SMT cores as performance class and add 2 efficiency cores without SMT.
1038    /// - Expect the order `[0, 2, 4, 5, 1, 3]`.
1039    #[test]
1040    fn order_hybrid() {
1041        // performance cores with SMT, efficiency cores without
1042        let mut cpus: Vec<_> = (0..4).map(|n| info(n, n as usize / 2, 0, 0)).collect();
1043        for c in &mut cpus {
1044            c.class = 1;
1045        }
1046        cpus.extend((4..6).map(|n| info(n, n as usize, 0, 0)));
1047        assert_eq!(nums(&cpus), [0, 2, 4, 5, 1, 3]);
1048    }
1049
1050    /// STATEMENT: CPU ordering uses only allowed CPUs and keeps disallowed siblings for
1051    /// locality.
1052    ///
1053    /// HOW:
1054    /// - Order a sparse CPU set; expect one CPU per core first, matching core lists, and an
1055    ///   empty order for no CPUs.
1056    /// - Allow only CPUs 4 and 6 of 8; expect only them ordered, a core list for CPU 4 with
1057    ///   only CPU 4, and sibling lists that include disallowed siblings.
1058    #[test]
1059    fn order_restricted() {
1060        // the process may only use some CPUs
1061        let cpus = [
1062            info(1, 0, 0, 0),
1063            info(2, 1, 0, 0),
1064            info(3, 1, 0, 0),
1065            info(5, 2, 0, 0),
1066        ];
1067        assert_eq!(nums(&cpus), [1, 2, 5, 3]);
1068        assert_eq!(order(&cpus)[0].1, [cpu(1)]);
1069        assert_eq!(order(&cpus)[3].1, [cpu(2), cpu(3)]);
1070        assert_eq!(order(&[]), []);
1071
1072        // siblings the process may not use are kept for locality only
1073        let mut cpus: Vec<_> = (0..8).map(|n| info(n, n as usize % 4, 0, 0)).collect();
1074        for c in &mut cpus {
1075            c.allowed = [4, 6].contains(&c.cpu.num);
1076        }
1077        let order = order(&cpus);
1078        assert_eq!(nums(&cpus), [4, 6]);
1079        assert_eq!(order[0].1, [cpu(4)]);
1080        assert_eq!(order[0].2, [cpu(0), cpu(4)]);
1081        assert_eq!(order[1].2, [cpu(2), cpu(6)]);
1082    }
1083
1084    /// STATEMENT: The placement plan for this machine gives each worker a distinct CPU within
1085    /// its core and siblings.
1086    ///
1087    /// HOW:
1088    /// - Expect an empty plan for `Affinity::Disabled`.
1089    /// - For `Affinity::Core`, expect each CPU in its core, the core in its siblings, and no
1090    ///   repeated CPU.
1091    /// - Expect one placement per usable CPU on Windows and Linux, and none elsewhere.
1092    #[test]
1093    fn plan_system() {
1094        assert_eq!(plan(Affinity::Disabled), []);
1095
1096        let plan = plan(Affinity::Core);
1097        let mut cpus: Vec<_> = plan
1098            .iter()
1099            .map(|p| {
1100                assert_eq!(p.mode, Affinity::Core);
1101                assert!(p.core.contains(&p.cpu));
1102                assert!(p.core.iter().all(|cpu| p.siblings.contains(cpu)));
1103                p.cpu
1104            })
1105            .collect();
1106        cpus.sort_unstable();
1107        cpus.dedup();
1108        assert_eq!(cpus.len(), plan.len());
1109        assert!(cpu_count() > 0);
1110        if cfg!(windows) {
1111            assert_eq!(cpu_count(), plan.len());
1112        }
1113        #[cfg(any(windows, target_os = "linux", target_os = "android"))]
1114        assert_ne!(plan, []);
1115        #[cfg(any(target_os = "linux", target_os = "android"))]
1116        assert_eq!(sys::current().0.len(), plan.len());
1117        #[cfg(not(any(windows, target_os = "linux", target_os = "android")))]
1118        assert_eq!(plan, []);
1119    }
1120
1121    /// STATEMENT: Applying a placement binds the thread to its CPU, its core, or a preferred
1122    /// CPU, depending on the mode.
1123    ///
1124    /// HOW:
1125    /// - Apply a planned placement in `Cpu`, `Core` and `Soft` modes on new threads.
1126    /// - Expect the thread mask to be the CPU for `Cpu` and the core for `Core`.
1127    /// - For `Soft`, expect the ideal CPU on Windows and the core mask elsewhere.
1128    #[cfg(any(windows, target_os = "linux", target_os = "android"))]
1129    #[test]
1130    fn apply_placement() {
1131        let Some(Placement { cpu, core, .. }) = plan(Affinity::Core).pop() else {
1132            return;
1133        };
1134        for mode in [Affinity::Cpu, Affinity::Core, Affinity::Soft] {
1135            let p = Placement {
1136                mode,
1137                cpu,
1138                core: core.clone(),
1139                siblings: core.clone(),
1140            };
1141            let (cpus, ideal) = std::thread::spawn(move || {
1142                assert!(p.apply());
1143                sys::current()
1144            })
1145            .join()
1146            .unwrap();
1147            match mode {
1148                Affinity::Cpu => assert_eq!(cpus, [cpu]),
1149                Affinity::Core => assert_eq!(cpus, core),
1150                _ if cfg!(windows) => assert_eq!(ideal, Some(cpu)),
1151                _ => assert_eq!(cpus, core),
1152            }
1153        }
1154    }
1155
1156    /// STATEMENT: `Placement::cpu` maps a CPU index to that CPU, and an unknown index fails
1157    /// to apply.
1158    ///
1159    /// HOW:
1160    /// - Build a placement from the highest planned group-0 CPU; expect the same CPU.
1161    /// - Apply it on a new thread; expect the thread mask to hold only that CPU.
1162    /// - Expect applying a huge index to fail.
1163    #[cfg(any(windows, target_os = "linux", target_os = "android"))]
1164    #[test]
1165    fn apply_cpu_index() {
1166        let Some(cpu) = plan(Affinity::Core)
1167            .into_iter()
1168            .map(|p| p.cpu)
1169            .filter(|cpu| cpu.group == 0)
1170            .max()
1171        else {
1172            return;
1173        };
1174        let p = Placement::cpu(cpu.num as usize);
1175        assert_eq!(p.cpu, cpu);
1176        let (cpus, _) = std::thread::spawn(move || {
1177            assert!(p.apply());
1178            sys::current()
1179        })
1180        .join()
1181        .unwrap();
1182        assert_eq!(cpus, [cpu]);
1183
1184        assert!(!Placement::cpu(usize::MAX >> 1).apply());
1185    }
1186
1187    /// STATEMENT: `Placement::cpus` lists the sibling CPU indexes, starting with the
1188    /// placement CPU.
1189    ///
1190    /// HOW:
1191    /// - Map the indexes of each `Affinity::Core` placement back to CPUs.
1192    /// - Expect the placement CPU first, one index per sibling, and only sibling CPUs.
1193    #[test]
1194    fn cpu_indexes() {
1195        for p in plan(Affinity::Core) {
1196            let cpus = p.cpus();
1197            assert_eq!(sys::cpu(cpus[0]), p.cpu);
1198            assert_eq!(cpus.len(), p.siblings.len());
1199            for idx in &cpus {
1200                assert!(p.siblings.contains(&sys::cpu(*idx)), "{p}: {cpus:?}");
1201            }
1202        }
1203    }
1204
1205    /// STATEMENT: `incoming_cpu` returns a valid CPU index for a TCP stream when known, and it
1206    /// is always known on Linux.
1207    ///
1208    /// HOW:
1209    /// - Connect a loopback client and accept it.
1210    /// - For both streams, expect a returned index to round-trip through `sys::cpu` and
1211    ///   `sys::index`, and an index on Linux.
1212    #[test]
1213    fn incoming_cpu_loopback() {
1214        let lst = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1215        let client = std::net::TcpStream::connect(lst.local_addr().unwrap()).unwrap();
1216        let (server, _) = lst.accept().unwrap();
1217        // loopback connections have no RSS CPU on Windows, if known the CPU
1218        // must exist
1219        for stream in [&client, &server] {
1220            let cpu = incoming_cpu(stream);
1221            if let Some(cpu) = cpu {
1222                assert_eq!(sys::index(sys::cpu(cpu)), cpu);
1223            }
1224            #[cfg(any(target_os = "linux", target_os = "android"))]
1225            assert!(cpu.is_some());
1226        }
1227    }
1228
1229    /// STATEMENT: The Linux topology reader parses CPU lists and reads core, L3 and node ids
1230    /// from sysfs, keeping disallowed siblings.
1231    ///
1232    /// HOW:
1233    /// - Parse ranges, a single CPU, an empty list and an invalid list.
1234    /// - Read a fake sysfs tree with 3 CPUs on node 1 sharing an L3 cache and one CPU without
1235    ///   topology files; expect their ids and order.
1236    /// - Disallow CPU 2; expect it left out of the order but kept as a sibling of CPU 0.
1237    #[cfg(any(target_os = "linux", target_os = "android"))]
1238    #[test]
1239    fn linux_sysfs() {
1240        use std::fs;
1241
1242        assert_eq!(
1243            sys::parse_list("0-3,8-11\n"),
1244            Some(vec![0, 1, 2, 3, 8, 9, 10, 11])
1245        );
1246        assert_eq!(sys::parse_list("5"), Some(vec![5]));
1247        assert_eq!(sys::parse_list("\n"), Some(vec![]));
1248        assert_eq!(sys::parse_list("a-b"), None);
1249
1250        // cpus 0-2 on node 1 share an L3 cache, cpu0 and cpu2 are siblings.
1251        // cpu3 has no topology files, it is a separate core on node 0
1252        let root = std::env::temp_dir().join(format!("ntex-affinity-{}", std::process::id()));
1253        let _ = fs::remove_dir_all(&root);
1254        for (num, core) in [(0, "0,2"), (1, "1,3"), (2, "0,2")] {
1255            let dir = root.join(format!("cpu{num}"));
1256            fs::create_dir_all(dir.join("topology")).unwrap();
1257            fs::create_dir_all(dir.join("cache/index3")).unwrap();
1258            fs::create_dir_all(dir.join("node1")).unwrap();
1259            fs::write(dir.join("topology/core_cpus_list"), core).unwrap();
1260            fs::write(dir.join("cache/index3/shared_cpu_list"), "0-3\n").unwrap();
1261        }
1262        let cpus = sys::read(&root, &[0, 1, 2, 3], &[0, 1, 2, 3]);
1263        let restricted = sys::read(&root, &[0, 1, 2, 3], &[0, 1, 3]);
1264        fs::remove_dir_all(&root).unwrap();
1265
1266        let ids: Vec<_> = cpus.iter().map(|c| (c.core, c.l3, c.node)).collect();
1267        assert_eq!(ids, [(0, 0, 1), (1, 0, 1), (0, 0, 1), (3, 3, 0)]);
1268        assert_eq!(nums(&cpus), [3, 0, 1, 2]);
1269
1270        // cpu2 is not allowed, it remains a sibling of cpu0
1271        assert_eq!(nums(&restricted), [3, 0, 1]);
1272        let (_, core, siblings) = &order(&restricted)[1];
1273        assert_eq!(
1274            (&core[..], &siblings[..]),
1275            (&[cpu(0)][..], &[cpu(0), cpu(2)][..])
1276        );
1277    }
1278
1279    /// STATEMENT: Linux CPU masks hold CPU numbers beyond `cpu_set_t`, and the mask query
1280    /// grows its buffer until the kernel accepts it.
1281    ///
1282    /// HOW:
1283    /// - Build a mask for CPUs 1 and 3000; expect the right words and bits, and a one-CPU
1284    ///   mask the size of `cpu_set_t`.
1285    /// - Query a fake kernel that rejects small buffers; expect CPUs 1 and 3000 after 3 tries.
1286    /// - Expect `None` for `EPERM` or a buffer that is never large enough, and a failed apply
1287    ///   for a huge CPU index.
1288    #[cfg(any(target_os = "linux", target_os = "android"))]
1289    #[test]
1290    fn linux_large_mask() {
1291        let bits = libc::c_ulong::BITS;
1292        let mask = sys::mask_of(&[cpu(1), cpu(3000)]);
1293        assert_eq!(mask.len(), (3000 / bits + 1) as usize);
1294        assert_eq!(mask[0], 2);
1295        assert_eq!(mask[(3000 / bits) as usize], 1 << (3000 % bits));
1296        assert_eq!(
1297            sys::mask_of(&[cpu(0)]).len() * size_of::<libc::c_ulong>(),
1298            size_of::<libc::cpu_set_t>()
1299        );
1300
1301        // the kernel mask is larger than `cpu_set_t`
1302        let mut sizes = Vec::new();
1303        let cpus = sys::query_mask(|m| {
1304            sizes.push(m.len());
1305            if m.len() * bits as usize <= 3000 {
1306                return Err(libc::EINVAL);
1307            }
1308            m[..mask.len()].copy_from_slice(&mask);
1309            Ok(())
1310        });
1311        assert_eq!(cpus, Some(vec![1, 3000]));
1312        assert_eq!(sizes.len(), 3, "{sizes:?}");
1313        assert_eq!(sys::query_mask(|_| Err(libc::EPERM)), None);
1314        assert_eq!(sys::query_mask(|_| Err(libc::EINVAL)), None);
1315
1316        assert!(!Placement::cpu(usize::MAX >> 1).apply());
1317    }
1318
1319    /// STATEMENT: On Windows the plan uses all processor groups without restrictions, and only
1320    /// the process mask CPUs with one.
1321    ///
1322    /// HOW:
1323    /// - Without a mask or restriction, expect one placement per active processor.
1324    /// - In a child process, restrict the mask to the two highest CPUs of the group.
1325    /// - Expect the mask read back, a plan with exactly those CPUs, and a CPU count of 2.
1326    #[cfg(windows)]
1327    #[test]
1328    fn windows_process_mask() {
1329        use windows_sys::Win32::System::Threading::{
1330            ALL_PROCESSOR_GROUPS, GetActiveProcessorCount, GetCurrentProcess,
1331            GetProcessAffinityMask, SetProcessAffinityMask,
1332        };
1333
1334        const CHILD: &str = "NTEX_AFFINITY_MASK_CHILD";
1335        if std::env::var_os(CHILD).is_none() {
1336            // without restrictions, all processor groups are used
1337            if sys::affinity_mask().is_none() && sys::restricted().is_none() {
1338                // SAFETY: plain processor count query
1339                let n = unsafe { GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) };
1340                assert_eq!(plan(Affinity::Core).len(), n as usize);
1341            }
1342            // the process mask is changed in a separate process
1343            let status = std::process::Command::new(std::env::current_exe().unwrap())
1344                .args(["affinity::tests::windows_process_mask", "--exact"])
1345                .env(CHILD, "1")
1346                .status()
1347                .unwrap();
1348            assert!(status.success());
1349            return;
1350        }
1351
1352        // SAFETY: plain process affinity calls on the current process
1353        unsafe {
1354            let process = GetCurrentProcess();
1355            let (mut mask, mut system) = (0, 0);
1356            assert_ne!(
1357                GetProcessAffinityMask(process, &raw mut mask, &raw mut system),
1358                0
1359            );
1360            if mask.count_ones() < 3 {
1361                return;
1362            }
1363            // the two highest CPUs of the group
1364            let high = usize::BITS - 1 - mask.leading_zeros();
1365            let next = usize::BITS - 1 - (mask & !(1 << high)).leading_zeros();
1366            let restricted = (1usize << high) | (1 << next);
1367            assert_ne!(SetProcessAffinityMask(process, restricted), 0);
1368
1369            let (group, mask) = sys::affinity_mask().unwrap();
1370            assert_eq!(mask, restricted);
1371            let mut cpus: Vec<_> = plan(Affinity::Core).into_iter().map(|p| p.cpu).collect();
1372            cpus.sort_unstable();
1373            assert_eq!(cpus, [Cpu { group, num: next }, Cpu { group, num: high }]);
1374            assert_eq!(cpu_count(), 2);
1375        }
1376    }
1377}