ostd/arch/x86/mod.rs
1// SPDX-License-Identifier: MPL-2.0
2//! Platform-specific code for the x86 platform.
3use vstd::prelude::*;
4
5use crate::specs::context::cpu_feature_model;
6
7/*pub mod boot;
8pub(crate) mod cpu;*/
9pub mod device;
10pub(crate) mod ex_table;
11pub(crate) mod io;
12/*pub(crate) mod iommu;*/
13pub(crate) mod irq;
14pub(crate) mod kernel;
15pub(crate) mod mm;
16pub(crate) mod pci;
17/*pub mod qemu;
18pub(crate) mod serial; */
19pub(crate) mod task;
20pub mod timer;
21/* pub mod trap; */
22
23/*use io::construct_io_mem_allocator_builder;
24use spin::Once;
25use x86::cpuid::{CpuId, FeatureInfo};
26
27#[cfg(feature = "cvm_guest")]
28pub(crate) mod tdx_guest;
29
30use core::sync::atomic::Ordering;
31
32use log::warn;
33
34#[cfg(feature = "cvm_guest")]
35pub(crate) fn init_cvm_guest() {
36 match ::tdx_guest::init_tdx() {
37 Ok(td_info) => {
38 crate::early_println!(
39 "[kernel] Intel TDX initialized\n[kernel] td gpaw: {}, td attributes: {:?}",
40 td_info.gpaw,
41 td_info.attributes
42 );
43 }
44 Err(::tdx_guest::tdcall::InitError::TdxGetVpInfoError(td_call_error)) => {
45 panic!(
46 "[kernel] Intel TDX not initialized, Failed to get TD info: {:?}",
47 td_call_error
48 );
49 }
50 // The machine has no TDX support.
51 Err(_) => {}
52 }
53}
54
55static CPU_FEATURES: Once<FeatureInfo> = Once::new();
56
57/// Architecture-specific initialization on the bootstrapping processor.
58///
59/// It should be called when the heap and frame allocators are available.
60///
61/// # Safety
62///
63/// This function must be called only once in the boot context of the
64/// bootstrapping processor.
65pub(crate) unsafe fn late_init_on_bsp() {
66 // SAFETY: This function is only called once on BSP.
67 unsafe { trap::init() };
68
69 let io_mem_builder = construct_io_mem_allocator_builder();
70
71 kernel::apic::init(&io_mem_builder).expect("APIC doesn't exist");
72 kernel::irq::init(&io_mem_builder);
73
74 kernel::tsc::init_tsc_freq();
75 timer::init_bsp();
76
77 // SAFETY: We're on the BSP and we're ready to boot all APs.
78 unsafe { crate::boot::smp::boot_all_aps() };
79
80 if_tdx_enabled!({
81 } else {
82 match iommu::init(&io_mem_builder) {
83 Ok(_) => {}
84 Err(err) => warn!("IOMMU initialization error:{:?}", err),
85 }
86 });
87
88 // SAFETY:
89 // 1. All the system device memory have been removed from the builder.
90 // 2. All the port I/O regions belonging to the system device are defined using the macros.
91 // 3. `MAX_IO_PORT` defined in `crate::arch::io` is the maximum value specified by x86-64.
92 unsafe { crate::io::init(io_mem_builder) };
93}
94
95/// Architecture-specific initialization on the application processor.
96///
97/// # Safety
98///
99/// This function must be called only once on each application processor.
100/// And it should be called after the BSP's call to [`init_on_bsp`].
101///
102/// [`init_on_bsp`]: crate::cpu::init_on_bsp
103pub(crate) unsafe fn init_on_ap() {
104 timer::init_ap();
105}
106
107pub(crate) fn interrupts_ack(irq_number: usize) {
108 if !cpu::context::CpuException::is_cpu_exception(irq_number) {
109 // TODO: We're in the interrupt context, so `disable_preempt()` is not
110 // really necessary here.
111 kernel::apic::get_or_init(&crate::task::disable_preempt() as _).eoi();
112 }
113}
114
115/// Returns the frequency of TSC. The unit is Hz.
116pub fn tsc_freq() -> u64 {
117 kernel::tsc::TSC_FREQ.load(Ordering::Acquire)
118}
119
120/// Reads the current value of the processor’s time-stamp counter (TSC).
121pub fn read_tsc() -> u64 {
122 use core::arch::x86_64::_rdtsc;
123
124 // SAFETY: It is safe to read a time-related counter.
125 unsafe { _rdtsc() }
126}
127
128/// Reads a hardware generated 64-bit random value.
129///
130/// Returns None if no random value was generated.
131pub fn read_random() -> Option<u64> {
132 use core::arch::x86_64::_rdrand64_step;
133
134 // Recommendation from "Intel® Digital Random Number Generator (DRNG) Software
135 // Implementation Guide" - Section 5.2.1 and "Intel® 64 and IA-32 Architectures
136 // Software Developer’s Manual" - Volume 1 - Section 7.3.17.1.
137 const RETRY_LIMIT: usize = 10;
138
139 for _ in 0..RETRY_LIMIT {
140 let mut val = 0;
141 let generated = unsafe { _rdrand64_step(&mut val) };
142 if generated == 1 {
143 return Some(val);
144 }
145 }
146 None
147}*/
148
149#[verus_spec(returns cpu_feature_model().supports_avx)]
150fn has_avx() -> bool {
151 use core::arch::x86_64::{__cpuid, __cpuid_count};
152
153 let cpuid_result = unsafe { __cpuid(0) };
154 if cpuid_result.eax < 1 {
155 // CPUID function 1 is not supported
156 return false;
157 }
158
159 let cpuid_result = unsafe { __cpuid_count(1, 0) };
160 // Check for AVX (bit 28 of ecx)
161 cpuid_result.ecx & (1 << 28) != 0
162}
163
164#[verus_spec(returns cpu_feature_model().supports_avx512f)]
165fn has_avx512() -> bool {
166 use core::arch::x86_64::{__cpuid, __cpuid_count};
167
168 let cpuid_result = unsafe { __cpuid(0) };
169 if cpuid_result.eax < 7 {
170 // CPUID function 7 is not supported
171 return false;
172 }
173
174 let cpuid_result = unsafe { __cpuid_count(7, 0) };
175 // Check for AVX-512 Foundation (bit 16 of ebx)
176 cpuid_result.ebx & (1 << 16) != 0
177}
178
179/*
180pub(crate) fn enable_cpu_features() {
181 use x86_64::registers::{control::Cr4Flags, model_specific::EferFlags, xcontrol::XCr0Flags};
182
183 CPU_FEATURES.call_once(|| {
184 let cpuid = CpuId::new();
185 cpuid.get_feature_info().unwrap()
186 });
187
188 let mut cr4 = x86_64::registers::control::Cr4::read();
189 cr4 |= Cr4Flags::FSGSBASE
190 | Cr4Flags::OSXSAVE
191 | Cr4Flags::OSFXSR
192 | Cr4Flags::OSXMMEXCPT_ENABLE
193 | Cr4Flags::PAGE_GLOBAL;
194 unsafe {
195 x86_64::registers::control::Cr4::write(cr4);
196 }
197
198 let mut xcr0 = x86_64::registers::xcontrol::XCr0::read();
199
200 xcr0 |= XCr0Flags::SSE;
201
202 if has_avx() {
203 xcr0 |= XCr0Flags::AVX;
204 }
205
206 if has_avx512() {
207 xcr0 |= XCr0Flags::OPMASK | XCr0Flags::ZMM_HI256 | XCr0Flags::HI16_ZMM;
208 }
209
210 unsafe {
211 x86_64::registers::xcontrol::XCr0::write(xcr0);
212 }
213
214 cpu::context::enable_essential_features();
215
216 unsafe {
217 // enable non-executable page protection
218 x86_64::registers::model_specific::Efer::update(|efer| {
219 *efer |= EferFlags::NO_EXECUTE_ENABLE;
220 });
221 }
222}*/
223
224/// Inserts a TDX-specific code block.
225///
226/// This macro conditionally executes a TDX-specific code block based on the following conditions:
227/// (1) The `cvm_guest` feature is enabled at compile time.
228/// (2) The TDX feature is detected at runtime via `::tdx_guest::tdx_is_enabled()`.
229///
230/// If both conditions are met, the `if_block` is executed. If an `else_block` is provided, it will be executed
231/// when either the `cvm_guest` feature is not enabled or the TDX feature is not detected at runtime.
232#[macro_export]
233macro_rules! if_tdx_enabled {
234 // Match when there is an else block
235 ($if_block:block else $else_block:block) => {{
236 #[cfg(feature = "cvm_guest")]
237 {
238 if ::tdx_guest::tdx_is_enabled() {
239 $if_block
240 } else {
241 $else_block
242 }
243 }
244 #[cfg(not(feature = "cvm_guest"))]
245 {
246 $else_block
247 }
248 }};
249 // Match when there is no else block
250 ($if_block:block) => {{
251 #[cfg(feature = "cvm_guest")]
252 {
253 if ::tdx_guest::tdx_is_enabled() {
254 $if_block
255 }
256 }
257 }};
258}
259
260pub use if_tdx_enabled;