strat9_kernel/ostd/cpu.rs
1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! CPU abstraction layer
24//!
25//! Provides safe abstractions for CPU-related operations including:
26//! - CPU identification and topology
27//! - Per-CPU data access
28//! - CPU control (halt, interrupt control)
29//!
30//! Inspired by Asterinas OSTD CPU module.
31
32#![allow(unsafe_code)]
33
34/// CPU identifier
35///
36/// Represents a logical CPU in the system. On x86_64, this corresponds
37/// to the APIC ID.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
39#[repr(transparent)]
40pub struct CpuId {
41 id: usize,
42}
43
44impl CpuId {
45 /// Creates a new CpuId from a raw ID
46 pub const fn new(id: usize) -> Self {
47 Self { id }
48 }
49
50 /// Returns the raw CPU ID value
51 pub const fn id(&self) -> usize {
52 self.id
53 }
54
55 /// Returns the CpuId of the bootstrap processor (BSP)
56 pub const fn bsp() -> Self {
57 Self::new(0)
58 }
59
60 /// Returns the CpuId of the currently executing CPU
61 ///
62 /// # Safety
63 ///
64 /// This function reads the per-CPU GS base to determine the current CPU.
65 /// It requires that per-CPU data has been initialized for this CPU.
66 #[inline]
67 pub fn current_racy() -> Self {
68 // This is safe if per-CPU data has been set up via
69 // arch::x86_64::percpu::init_gs_base(). The "racy" suffix indicates
70 // that no additional synchronization is performed.
71 let cpu_index = crate::arch::percpu::current_cpu_index();
72 Self::new(cpu_index)
73 }
74
75 /// Returns the number of CPUs in the system
76 ///
77 /// On x86_64 this is the number of currently online CPUs. CPU indices are
78 /// sparse, so this count is not an upper bound for index scanning.
79 pub fn num_cpus() -> usize {
80 #[cfg(target_arch = "x86_64")]
81 {
82 crate::arch::percpu::online_count().max(1)
83 }
84 #[cfg(not(target_arch = "x86_64"))]
85 {
86 crate::arch::percpu::get_cpu_count().max(1)
87 }
88 }
89
90 /// Returns an iterator over all CPUs
91 pub fn iter() -> CpuIter {
92 CpuIter { next: 0 }
93 }
94}
95
96impl From<usize> for CpuId {
97 /// Performs the from operation.
98 fn from(id: usize) -> Self {
99 Self::new(id)
100 }
101}
102
103impl From<CpuId> for usize {
104 /// Performs the from operation.
105 fn from(cpu_id: CpuId) -> Self {
106 cpu_id.id
107 }
108}
109
110impl core::fmt::Display for CpuId {
111 /// Performs the fmt operation.
112 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
113 write!(f, "CPU #{}", self.id)
114 }
115}
116
117/// Iterator over all online CPUs
118///
119/// CPU indices may be sparse, so this scans the full `0..MAX_CPUS` index space
120/// and yields only slots that are currently online.
121pub struct CpuIter {
122 next: usize,
123}
124
125impl Iterator for CpuIter {
126 type Item = CpuId;
127
128 /// Performs the next operation.
129 fn next(&mut self) -> Option<Self::Item> {
130 #[cfg(target_arch = "x86_64")]
131 {
132 while self.next < crate::arch::percpu::MAX_CPUS {
133 let idx = self.next;
134 self.next += 1;
135 if crate::arch::percpu::is_online(idx) {
136 return Some(CpuId::new(idx));
137 }
138 }
139 None
140 }
141 #[cfg(not(target_arch = "x86_64"))]
142 {
143 if self.next < CpuId::num_cpus() {
144 let cpu = CpuId::new(self.next);
145 self.next += 1;
146 Some(cpu)
147 } else {
148 None
149 }
150 }
151 }
152}
153
154/// CPU halt function
155///
156/// Halts the CPU until the next interrupt arrives.
157#[inline]
158pub fn halt_cpu() {
159 // hlt is a privileged instruction that halts the CPU until
160 // the next interrupt. This is safe to call in kernel mode.
161 crate::arch::hlt();
162}
163
164/// Disable interrupts on the current CPU
165#[inline]
166pub fn disable_irqs() {
167 // cli is a privileged instruction that disables interrupts.
168 // This is safe to call in kernel mode and is commonly used to
169 // protect critical sections.
170 crate::arch::cli();
171}
172
173/// Enable interrupts on the current CPU
174#[inline]
175pub fn enable_irqs() {
176 // sti is a privileged instruction that enables interrupts.
177 // This is safe to call in kernel mode.
178 crate::arch::sti();
179}
180
181/// Check if interrupts are enabled on the current CPU
182#[inline]
183pub fn irqs_enabled() -> bool {
184 crate::arch::interrupts_enabled()
185}
186
187/// Save interrupt flags and disable interrupts
188///
189/// Returns the previous interrupt state.
190#[inline]
191pub fn save_and_disable_irqs() -> bool {
192 let flags = crate::arch::save_flags_and_cli();
193 (flags & 0x200) != 0
194}
195
196/// Restore interrupt flags
197///
198/// Restores the interrupt state to a previous value.
199#[inline]
200pub fn restore_irqs(enabled: bool) {
201 if enabled {
202 enable_irqs();
203 } else {
204 disable_irqs();
205 }
206}
207
208/// Execute a closure with interrupts disabled
209///
210/// Returns the result of the closure.
211pub fn without_interrupts<F, R>(f: F) -> R
212where
213 F: FnOnce() -> R,
214{
215 let irq_enabled = save_and_disable_irqs();
216 let result = f();
217 restore_irqs(irq_enabled);
218 result
219}