Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/scheduler/affinity.rs

kernel/scheduler/
affinity.rs

1// Copyright 2026 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use kernel_config::{KernelConfig, KernelConfigInterface};
16use pw_status::{Error, Result};
17
18/// Logical identifier for a CPU core in a system with up to `MAX_CORES` cores.
19#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub struct GenericCoreId<const MAX_CORES: usize>(usize);
21
22/// Logical identifier for a CPU core.
23pub type CoreId = GenericCoreId<{ KernelConfig::MAX_CORES }>;
24
25impl<const MAX_CORES: usize> GenericCoreId<MAX_CORES> {
26    const _ASSERT_VALID_MAX_CORES: () = assert!(MAX_CORES >= 1);
27
28    /// The primary (bootstrap) core identifier (`CoreId(0)`).
29    pub const ZERO: Self = {
30        let () = Self::_ASSERT_VALID_MAX_CORES;
31        Self(0)
32    };
33
34    /// Constructs a [`GenericCoreId`] for the given logical core index.
35    ///
36    /// # Panics
37    ///
38    /// Debug-asserts that `id < MAX_CORES`.
39    #[must_use]
40    #[inline]
41    pub fn new(id: usize) -> Self {
42        let () = Self::_ASSERT_VALID_MAX_CORES;
43        pw_assert::debug_assert!(id < MAX_CORES);
44        Self(id)
45    }
46
47    /// Returns the zero-based logical core index.
48    #[must_use]
49    #[inline]
50    pub const fn as_usize(self) -> usize {
51        self.0
52    }
53}
54
55/// Thread CPU affinity mask for a system with up to `MAX_CORES` cores.
56///
57/// Represents the set of CPU cores on which a thread is permitted to execute.
58#[derive(Copy, Clone, Debug, PartialEq, Eq)]
59pub struct GenericAffinityMask<const MAX_CORES: usize>(u32);
60
61/// Thread CPU affinity mask.
62pub type AffinityMask = GenericAffinityMask<{ KernelConfig::MAX_CORES }>;
63
64impl<const MAX_CORES: usize> GenericAffinityMask<MAX_CORES> {
65    const BITS: usize = pw_cast::cast!(u32::BITS => usize);
66    const _ASSERT_VALID_MAX_CORES: () = {
67        assert!(MAX_CORES >= 1);
68        assert!(MAX_CORES <= Self::BITS);
69    };
70
71    /// Constructs an affinity mask allowing the thread to run on any configured core.
72    #[must_use]
73    #[inline]
74    pub const fn all() -> Self {
75        let () = Self::_ASSERT_VALID_MAX_CORES;
76        Self(u32::MAX >> (Self::BITS - MAX_CORES))
77    }
78
79    /// Constructs an affinity mask pinning the thread exclusively to a single core.
80    #[must_use]
81    #[inline]
82    pub const fn pinned_to_core(core: GenericCoreId<MAX_CORES>) -> Self {
83        let () = Self::_ASSERT_VALID_MAX_CORES;
84        Self(1 << core.as_usize())
85    }
86
87    /// Constructs an affinity mask from a raw bitmask.
88    ///
89    /// Returns `Err(Error::InvalidArgument)` if `mask` is zero or sets any bits
90    /// outside the configured cores (`>= 1 << MAX_CORES`).
91    #[inline]
92    pub const fn from_raw(mask: u32) -> Result<Self> {
93        // A valid affinity mask must include at least one core (`mask != 0`)
94        // and must not set any bits outside the configured cores (`Self::all()`,
95        // which is `0b1` on uniprocessor builds where `MAX_CORES == 1`).
96        if mask != 0 && (mask & !Self::all().0) == 0 {
97            Ok(Self(mask))
98        } else {
99            Err(Error::InvalidArgument)
100        }
101    }
102
103    /// Returns `true` if the thread is permitted to execute on `core`.
104    #[must_use]
105    #[inline]
106    pub const fn contains(&self, core: GenericCoreId<MAX_CORES>) -> bool {
107        (self.0 & (1 << core.as_usize())) != 0
108    }
109
110    /// Returns the lowest-numbered core permitted by this affinity mask.
111    #[must_use]
112    #[inline]
113    pub const fn lowest_core(&self) -> GenericCoreId<MAX_CORES> {
114        GenericCoreId(pw_cast::cast!(self.0.trailing_zeros() => usize))
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use unittest::test;
121
122    use super::*;
123
124    /// Verifies `CoreId` and `AffinityMask` behavior on a single-core (`MAX_CORES = 1`) system.
125    #[test]
126    fn uniprocessor_core_id_and_affinity_mask() -> unittest::Result<()> {
127        type UpCoreId = GenericCoreId<1>;
128        type UpMask = GenericAffinityMask<1>;
129
130        unittest::assert_eq!(UpCoreId::ZERO.as_usize(), 0);
131        unittest::assert_eq!(UpCoreId::new(0), UpCoreId::ZERO);
132
133        let all = UpMask::all();
134        unittest::assert_true!(all.contains(UpCoreId::ZERO));
135        unittest::assert_eq!(all.lowest_core(), UpCoreId::ZERO);
136        unittest::assert_eq!(UpMask::pinned_to_core(UpCoreId::ZERO), all);
137
138        // Only `0b1` is a valid raw mask when `MAX_CORES == 1`.
139        unittest::assert_eq!(UpMask::from_raw(0), Err(Error::InvalidArgument));
140        unittest::assert_eq!(UpMask::from_raw(0b1), Ok(all));
141        unittest::assert_eq!(UpMask::from_raw(0b10), Err(Error::InvalidArgument));
142        unittest::assert_eq!(UpMask::from_raw(0b11), Err(Error::InvalidArgument));
143        unittest::assert_eq!(UpMask::from_raw(u32::MAX), Err(Error::InvalidArgument));
144        Ok(())
145    }
146
147    /// Verifies single-core pinning, multi-core subsets, and bounds checks for `MAX_CORES = 4`.
148    #[test]
149    fn quad_core_affinity_mask_subsets_and_bounds() -> unittest::Result<()> {
150        type QuadCoreId = GenericCoreId<4>;
151        type QuadMask = GenericAffinityMask<4>;
152
153        let all = QuadMask::all();
154        unittest::assert_eq!(all.lowest_core(), QuadCoreId::ZERO);
155        unittest::assert_eq!(QuadMask::from_raw(0b1111), Ok(all));
156
157        // Each core's pinned mask contains only that core.
158        for i in 0..4 {
159            let core = QuadCoreId::new(i);
160            unittest::assert_eq!(core.as_usize(), i);
161            unittest::assert_true!(all.contains(core));
162
163            let single = QuadMask::pinned_to_core(core);
164            unittest::assert_true!(single.contains(core));
165            unittest::assert_eq!(single.lowest_core(), core);
166            for other in 0..4 {
167                if other != i {
168                    unittest::assert_false!(single.contains(QuadCoreId::new(other)));
169                }
170            }
171        }
172
173        // Multi-core subset (cores 1 and 3): lowest core is 1.
174        let subset = QuadMask::from_raw(0b1010).unwrap();
175        unittest::assert_false!(subset.contains(QuadCoreId::new(0)));
176        unittest::assert_true!(subset.contains(QuadCoreId::new(1)));
177        unittest::assert_false!(subset.contains(QuadCoreId::new(2)));
178        unittest::assert_true!(subset.contains(QuadCoreId::new(3)));
179        unittest::assert_eq!(subset.lowest_core(), QuadCoreId::new(1));
180
181        // Empty and out-of-bounds bitmasks (`>= 1 << 4`) must be rejected.
182        unittest::assert_eq!(QuadMask::from_raw(0), Err(Error::InvalidArgument));
183        unittest::assert_eq!(QuadMask::from_raw(1 << 4), Err(Error::InvalidArgument));
184        unittest::assert_eq!(
185            QuadMask::from_raw(0b1111 | (1 << 4)),
186            Err(Error::InvalidArgument)
187        );
188        unittest::assert_eq!(QuadMask::from_raw(u32::MAX), Err(Error::InvalidArgument));
189        Ok(())
190    }
191
192    /// Verifies that `MAX_CORES = 32` handles the full 32-bit mask without shift overflow.
193    #[test]
194    fn max_32_cores_full_bitmask_boundary() -> unittest::Result<()> {
195        type MaxCoreId = GenericCoreId<32>;
196        type MaxMask = GenericAffinityMask<32>;
197
198        let all = MaxMask::all();
199        unittest::assert_eq!(MaxMask::from_raw(u32::MAX), Ok(all));
200        unittest::assert_eq!(all.lowest_core(), MaxCoreId::ZERO);
201        unittest::assert_eq!(MaxMask::from_raw(0), Err(Error::InvalidArgument));
202
203        // Pinning to the highest core (`CoreId(31)`) sets the MSB.
204        let high_core = MaxCoreId::new(31);
205        let high_mask = MaxMask::pinned_to_core(high_core);
206        unittest::assert_eq!(MaxMask::from_raw(1u32 << 31), Ok(high_mask));
207        unittest::assert_true!(high_mask.contains(high_core));
208        unittest::assert_false!(high_mask.contains(MaxCoreId::ZERO));
209        unittest::assert_eq!(high_mask.lowest_core(), high_core);
210        Ok(())
211    }
212}