1use alloc::boxed::Box;
6use core::arch::x86_64::{_fxrstor64, _fxsave64, _xrstor64, _xsave64};
7
8use bitflags::bitflags;
9use ostd_pod::{FromZeros, IntoBytes};
10use spin::Once;
11use x86::bits64::segmentation::{rdfsbase, rdgsbase, swapgs, wrfsbase, wrgsbase};
12use x86_64::registers::{
13 control::{Cr0, Cr0Flags},
14 rflags::RFlags,
15 xcontrol::XCr0,
16};
17
18use crate::{
19 arch::{
20 irq::HwIrqLine,
21 trap::{RawUserContext, TrapFrame},
22 },
23 cpu::PrivilegeLevel,
24 debug,
25 irq::{DisabledLocalIrqGuard, call_irq_callback_functions},
26 mm::Vaddr,
27 user::{ReturnReason, UserContextApi, UserContextApiInternal, UserModeHooks},
28};
29
30cfg_select! {
31 feature = "cvm_guest" => {
32 mod tdx;
33
34 use tdx::VirtualizationExceptionHandler;
35 }
36}
37
38#[repr(C)]
40#[derive(Clone, Debug, Default)]
41pub struct UserContext {
42 user_context: RawUserContext,
43 exception: Option<CpuException>,
44}
45
46#[expect(missing_docs)]
48#[repr(C)]
49#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
50pub struct GeneralRegs {
51 pub rax: usize,
52 pub rbx: usize,
53 pub rcx: usize,
54 pub rdx: usize,
55 pub rsi: usize,
56 pub rdi: usize,
57 pub rbp: usize,
58 pub rsp: usize,
59 pub r8: usize,
60 pub r9: usize,
61 pub r10: usize,
62 pub r11: usize,
63 pub r12: usize,
64 pub r13: usize,
65 pub r14: usize,
66 pub r15: usize,
67 pub rip: usize,
68 pub rflags: usize,
69}
70
71#[derive(Clone, Copy, Debug, Default)]
73pub struct FsBase(usize);
74
75impl FsBase {
76 pub fn new(addr: usize) -> Self {
78 Self(addr)
79 }
80
81 pub fn addr(&self) -> usize {
83 self.0
84 }
85
86 pub fn save(&mut self) {
88 self.0 = unsafe { rdfsbase() as usize };
90 }
91
92 pub fn load(&self) {
94 unsafe { wrfsbase(self.0 as u64) }
96 }
97}
98
99#[derive(Clone, Copy, Debug, Default)]
101pub struct GsBase(usize);
102
103impl GsBase {
104 pub fn new(addr: usize) -> Self {
106 Self(addr)
107 }
108
109 pub fn addr(&self) -> usize {
111 self.0
112 }
113
114 pub fn save(&mut self, _guard: &DisabledLocalIrqGuard) {
116 unsafe {
120 swapgs();
121 self.0 = rdgsbase() as usize;
122 swapgs();
123 }
124 }
125
126 pub fn load(&self, _guard: &DisabledLocalIrqGuard) {
128 unsafe {
132 swapgs();
133 wrgsbase(self.0 as u64);
134 swapgs();
135 }
136 }
137}
138
139#[derive(Clone, Copy, Debug, Eq, PartialEq)]
156pub enum CpuException {
157 DivisionError,
159 Debug,
161 NonMaskableInterrupt,
163 BreakPoint,
165 Overflow,
167 BoundRangeExceeded,
169 InvalidOpcode,
171 DeviceNotAvailable,
173 DoubleFault,
175 CoprocessorSegmentOverrun,
177 InvalidTss(SelectorErrorCode),
179 SegmentNotPresent(SelectorErrorCode),
181 StackSegmentFault(SelectorErrorCode),
183 GeneralProtectionFault(Option<SelectorErrorCode>),
185 PageFault(RawPageFaultInfo),
187 X87FloatingPointException,
190 AlignmentCheck,
192 MachineCheck,
194 SIMDFloatingPointException,
196 VirtualizationException,
198 ControlProtectionException,
200 HypervisorInjectionException,
203 VMMCommunicationException,
205 SecurityException,
207 Reserved,
210}
211
212impl CpuException {
213 pub(crate) fn new(trap_num: usize, error_code: usize) -> Option<Self> {
214 let exception = match trap_num {
215 0 => Self::DivisionError,
216 1 => Self::Debug,
217 2 => Self::NonMaskableInterrupt,
218 3 => Self::BreakPoint,
219 4 => Self::Overflow,
220 5 => Self::BoundRangeExceeded,
221 6 => Self::InvalidOpcode,
222 7 => Self::DeviceNotAvailable,
223 8 => {
224 debug_assert_eq!(error_code, 0);
226 Self::DoubleFault
227 }
228 9 => Self::CoprocessorSegmentOverrun,
229 10 => Self::InvalidTss(SelectorErrorCode(error_code)),
230 11 => Self::SegmentNotPresent(SelectorErrorCode(error_code)),
231 12 => Self::StackSegmentFault(SelectorErrorCode(error_code)),
232 13 => {
233 let error_code = if error_code == 0 {
234 None
235 } else {
236 Some(SelectorErrorCode(error_code))
237 };
238 Self::GeneralProtectionFault(error_code)
239 }
240 14 => {
241 let page_fault_addr = x86_64::registers::control::Cr2::read_raw() as usize;
242 Self::PageFault(RawPageFaultInfo {
243 error_code: PageFaultErrorCode::from_bits(error_code).unwrap(),
244 addr: page_fault_addr,
245 })
246 }
247 16 => Self::X87FloatingPointException,
249 17 => Self::AlignmentCheck,
250 18 => Self::MachineCheck,
251 19 => Self::SIMDFloatingPointException,
252 20 => Self::VirtualizationException,
253 21 => Self::ControlProtectionException,
254 28 => Self::HypervisorInjectionException,
256 29 => Self::VMMCommunicationException,
257 30 => Self::SecurityException,
258 15 | 22..=27 | 31 => Self::Reserved,
260 _ => return None,
261 };
262
263 Some(exception)
264 }
265
266 const fn type_(&self) -> CpuExceptionType {
267 match self {
268 Self::Debug => CpuExceptionType::FaultOrTrap,
269 Self::NonMaskableInterrupt => CpuExceptionType::Interrupt,
270 Self::BreakPoint | Self::Overflow => CpuExceptionType::Trap,
271 Self::DoubleFault | Self::MachineCheck => CpuExceptionType::Abort,
272 Self::Reserved => CpuExceptionType::Reserved,
273 _ => CpuExceptionType::Fault,
274 }
275 }
276
277 pub(crate) const fn is_cpu_exception(trap_num: usize) -> bool {
278 trap_num <= 31
279 }
280}
281
282#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
286pub struct SelectorErrorCode(usize);
287
288impl UserContext {
289 pub fn general_regs(&self) -> &GeneralRegs {
291 &self.user_context.general
292 }
293
294 pub fn general_regs_mut(&mut self) -> &mut GeneralRegs {
296 &mut self.user_context.general
297 }
298
299 pub fn take_exception(&mut self) -> Option<CpuException> {
301 self.exception.take()
302 }
303}
304
305impl UserContextApiInternal for UserContext {
306 fn execute<T: UserModeHooks>(&mut self, hooks: &T) -> ReturnReason {
307 self.user_context.general.rflags |= (RFlags::INTERRUPT_FLAG | RFlags::ID).bits() as usize;
310
311 const SYSCALL_TRAPNUM: usize = 0x100;
312
313 loop {
315 crate::task::scheduler::might_preempt();
316
317 let guard = crate::irq::disable_local();
318 hooks.pre_user_run(&guard);
319 self.user_context.run(guard);
320
321 let exception =
322 CpuException::new(self.user_context.trap_num, self.user_context.error_code);
323 match exception {
324 #[cfg(feature = "cvm_guest")]
325 Some(CpuException::VirtualizationException) => {
326 let ve_handler = VirtualizationExceptionHandler::new();
327 crate::arch::irq::enable_local();
330 ve_handler.handle(self);
331 }
332 Some(exception) if exception.type_().is_fault_or_trap() => {
333 crate::arch::irq::enable_local();
334 self.exception = Some(exception);
335 return ReturnReason::UserException;
336 }
337 Some(exception) => {
338 panic!(
339 "Cannot handle user CPU exception: {:?}; trapframe: {:?}",
340 exception,
341 self.as_trap_frame()
342 );
343 }
344 None if self.user_context.trap_num == SYSCALL_TRAPNUM => {
345 crate::arch::irq::enable_local();
346 return ReturnReason::UserSyscall;
347 }
348 None => {
349 call_irq_callback_functions(
350 &self.as_trap_frame(),
351 &HwIrqLine::new(self.as_trap_frame().trap_num as u8),
352 PrivilegeLevel::User,
353 );
354 crate::arch::irq::enable_local();
355 }
356 }
357
358 if hooks.has_kernel_event() {
359 break ReturnReason::KernelEvent;
360 }
361 }
362 }
363
364 fn as_trap_frame(&self) -> TrapFrame {
365 TrapFrame {
366 rax: self.user_context.general.rax,
367 rbx: self.user_context.general.rbx,
368 rcx: self.user_context.general.rcx,
369 rdx: self.user_context.general.rdx,
370 rsi: self.user_context.general.rsi,
371 rdi: self.user_context.general.rdi,
372 rbp: self.user_context.general.rbp,
373 r8: self.user_context.general.r8,
374 r9: self.user_context.general.r9,
375 r10: self.user_context.general.r10,
376 r11: self.user_context.general.r11,
377 r12: self.user_context.general.r12,
378 r13: self.user_context.general.r13,
379 r14: self.user_context.general.r14,
380 r15: self.user_context.general.r15,
381 trap_num: self.user_context.trap_num,
382 error_code: self.user_context.error_code,
383 rip: self.user_context.general.rip,
384 cs: 0,
385 rflags: self.user_context.general.rflags,
386 rsp: self.user_context.general.rsp,
387 ss: 0,
388 }
389 }
390}
391
392#[derive(Clone, Copy, Debug, Eq, PartialEq)]
404pub enum CpuExceptionType {
405 Fault,
407 Trap,
409 FaultOrTrap,
411 Interrupt,
413 Abort,
415 Reserved,
417}
418
419impl CpuExceptionType {
420 pub fn is_fault_or_trap(self) -> bool {
422 match self {
423 CpuExceptionType::Trap | CpuExceptionType::Fault | CpuExceptionType::FaultOrTrap => {
424 true
425 }
426 CpuExceptionType::Abort | CpuExceptionType::Interrupt | CpuExceptionType::Reserved => {
427 false
428 }
429 }
430 }
431}
432
433#[derive(Clone, Copy, Debug, Eq, PartialEq)]
435pub struct RawPageFaultInfo {
436 pub error_code: PageFaultErrorCode,
438 pub addr: Vaddr,
440}
441
442bitflags! {
443 pub struct PageFaultErrorCode : usize{
445 const PRESENT = 1 << 0;
447 const WRITE = 1 << 1;
449 const USER = 1 << 2;
451 const RESERVED = 1 << 3;
454 const INSTRUCTION = 1 << 4;
456 const PROTECTION = 1 << 5;
459 const SHADOW_STACK = 1 << 6;
461 const HLAT = 1 << 7;
463 const SGX = 1 << 15;
466 }
467}
468
469impl UserContextApi for UserContext {
470 fn set_instruction_pointer(&mut self, ip: usize) {
471 self.set_rip(ip);
472 }
473
474 fn set_stack_pointer(&mut self, sp: usize) {
475 self.set_rsp(sp)
476 }
477
478 fn stack_pointer(&self) -> usize {
479 self.rsp()
480 }
481
482 fn instruction_pointer(&self) -> usize {
483 self.rip()
484 }
485}
486
487macro_rules! cpu_context_impl_getter_setter {
488 ( $( [ $field: ident, $setter_name: ident] ),*) => {
489 impl UserContext {
490 $(
491 #[doc = concat!("Gets the value of ", stringify!($field))]
492 #[inline(always)]
493 pub fn $field(&self) -> usize {
494 self.user_context.general.$field
495 }
496
497 #[doc = concat!("Sets the value of ", stringify!(field))]
498 #[inline(always)]
499 pub fn $setter_name(&mut self, $field: usize) {
500 self.user_context.general.$field = $field;
501 }
502 )*
503 }
504 };
505}
506
507cpu_context_impl_getter_setter!(
508 [rax, set_rax],
509 [rbx, set_rbx],
510 [rcx, set_rcx],
511 [rdx, set_rdx],
512 [rsi, set_rsi],
513 [rdi, set_rdi],
514 [rbp, set_rbp],
515 [rsp, set_rsp],
516 [r8, set_r8],
517 [r9, set_r9],
518 [r10, set_r10],
519 [r11, set_r11],
520 [r12, set_r12],
521 [r13, set_r13],
522 [r14, set_r14],
523 [r15, set_r15],
524 [rip, set_rip],
525 [rflags, set_rflags]
526);
527
528#[derive(Debug)]
532pub struct FpuContext {
533 xsave_area: Box<XSaveArea>,
534 area_size: usize,
535}
536
537impl FpuContext {
538 pub fn new() -> Self {
540 let mut area_size = size_of::<FxSaveArea>();
541 if let Some(xsave_area_size) = XSAVE_AREA_SIZE.get() {
542 area_size = area_size.max(*xsave_area_size);
543 }
544
545 Self {
546 xsave_area: Box::new(XSaveArea::new()),
547 area_size,
548 }
549 }
550
551 pub fn save(&mut self) {
553 let mem_addr = self.as_bytes_mut().as_mut_ptr();
554
555 if XSTATE_MAX_FEATURES.is_completed() {
556 unsafe { _xsave64(mem_addr, XFEATURE_MASK_USER_RESTORE) };
557 } else {
558 unsafe { _fxsave64(mem_addr) };
559 }
560
561 debug!("Save FPU context");
562 }
563
564 pub fn load(&self) {
566 let mem_addr = self.as_bytes().as_ptr();
567
568 if let Some(xstate_max_features) = XSTATE_MAX_FEATURES.get() {
569 let rs_mask = XFEATURE_MASK_USER_RESTORE & *xstate_max_features;
570
571 unsafe { _xrstor64(mem_addr, rs_mask) };
572 } else {
573 unsafe { _fxrstor64(mem_addr) };
574 }
575
576 debug!("Load FPU context");
577 }
578
579 pub fn as_bytes(&self) -> &[u8] {
581 &self.xsave_area.as_bytes()[..self.area_size]
582 }
583
584 pub fn as_bytes_mut(&mut self) -> &mut [u8] {
586 &mut self.xsave_area.as_mut_bytes()[..self.area_size]
587 }
588}
589
590impl Default for FpuContext {
591 fn default() -> Self {
592 Self::new()
593 }
594}
595
596impl Clone for FpuContext {
597 fn clone(&self) -> Self {
598 let mut xsave_area = Box::new(XSaveArea::new());
599 xsave_area.fxsave_area = self.xsave_area.fxsave_area;
600 xsave_area.features = self.xsave_area.features;
601 xsave_area.compaction = self.xsave_area.compaction;
602 if self.area_size > size_of::<FxSaveArea>() {
603 let len = self.area_size - size_of::<FxSaveArea>() - 64;
604 xsave_area.extended_state_area[..len]
605 .copy_from_slice(&self.xsave_area.extended_state_area[..len]);
606 }
607
608 Self {
609 xsave_area,
610 area_size: self.area_size,
611 }
612 }
613}
614
615#[repr(C)]
617#[repr(align(64))]
618#[derive(Clone, Copy, Debug, Pod)]
619struct XSaveArea {
620 fxsave_area: FxSaveArea,
621 features: u64,
622 compaction: u64,
623 reserved: [u64; 6],
624 extended_state_area: [u8; MAX_XSAVE_AREA_SIZE - size_of::<FxSaveArea>() - 64],
625}
626
627impl XSaveArea {
628 fn new() -> Self {
629 let features = if let Some(xstate_max_features) = XSTATE_MAX_FEATURES.get() {
630 XCr0::read().bits() & *xstate_max_features
631 } else {
632 0
633 };
634
635 let mut xsave_area = Self::new_zeroed();
636 xsave_area.fxsave_area.control = 0x037F;
639 xsave_area.fxsave_area.tag = 0;
646 xsave_area.fxsave_area.mxcsr = 0x1F80;
647 xsave_area.features = features;
648
649 xsave_area
650 }
651}
652
653#[repr(C)]
655#[repr(align(16))]
656#[derive(Clone, Copy, Debug, Pod)]
657struct FxSaveArea {
658 control: u16, status: u16, tag: u8, reserved1: u8, op: u16, ip: u32, cs: u32, dp: u32, ds: u32, mxcsr: u32, mxcsr_mask: u32, st_space: [u32; 32], xmm_space: [u32; 64], reserved2: [u32; 12], reserved3: [u32; 12], }
674
675static XSTATE_MAX_FEATURES: Once<u64> = Once::new();
677
678const XFEATURE_MASK_USER_RESTORE: u64 = 0b1110_0111;
682
683static XSAVE_AREA_SIZE: Once<usize> = Once::new();
685
686const MAX_XSAVE_AREA_SIZE: usize = 4096;
688
689pub(in crate::arch) fn enable_essential_features() {
690 use super::extension::{IsaExtensions, has_extensions};
691
692 if has_extensions(IsaExtensions::XSAVE) {
693 XSTATE_MAX_FEATURES.call_once(|| super::cpuid::query_xstate_max_features().unwrap());
694 XSAVE_AREA_SIZE.call_once(|| {
695 let xsave_area_size = super::cpuid::query_xsave_area_size().unwrap() as usize;
696 assert!(xsave_area_size <= MAX_XSAVE_AREA_SIZE);
697 xsave_area_size
698 });
699 }
700
701 {
704 let mut cr0 = Cr0::read();
705 cr0.remove(Cr0Flags::TASK_SWITCHED | Cr0Flags::EMULATE_COPROCESSOR);
706
707 unsafe {
708 Cr0::write(cr0);
709 core::arch::asm!("fninit");
711 }
712 }
713}