repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -0,0 +1,242 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::cpu::{irqs_disable, irqs_enable}; +use core::arch::asm; +use core::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; + +/// Interrupt flag in RFLAGS register +const EFLAGS_IF: u64 = 1 << 9; + +/// Unconditionally disable IRQs +/// +/// # Safety +/// +/// Callers need to take care of re-enabling IRQs. +#[inline(always)] +pub unsafe fn raw_irqs_disable() { + asm!("cli", options(att_syntax, preserves_flags, nostack)); +} + +/// Unconditionally enable IRQs +/// +/// # Safety +/// +/// Callers need to make sure it is safe to enable IRQs. e.g. that no data +/// structures or locks which are accessed in IRQ handlers are used after IRQs +/// have been enabled. +#[inline(always)] +pub unsafe fn raw_irqs_enable() { + asm!("sti", options(att_syntax, preserves_flags, nostack)); +} + +/// Query IRQ state on current CPU +/// +/// # Returns +/// +/// `true` when IRQs are enabled, `false` otherwise +#[inline(always)] +#[must_use = "Unused irqs_enabled() result - meant to be irq_enable()?"] +pub fn irqs_enabled() -> bool { + // SAFETY: The inline assembly just reads the processors RFLAGS register + // and does not change any state. + let state: u64 = unsafe { + let s: u64; + asm!("pushfq", + "popq {}", + out(reg) s, + options(att_syntax, nomem, preserves_flags)); + s + }; + + (state & EFLAGS_IF) == EFLAGS_IF +} + +/// Query IRQ state on current CPU +/// +/// # Returns +/// +/// `false` when IRQs are enabled, `true` otherwise +#[inline(always)] +#[must_use = "Unused irqs_disabled() result - meant to be irq_disable()?"] +pub fn irqs_disabled() -> bool { + !irqs_enabled() +} + +/// This structure keeps track of PerCpu IRQ states. It tracks the original IRQ +/// state and how deep IRQ-disable calls have been nested. The use of atomics +/// is necessary for interior mutability and to make state modifications safe +/// wrt. to IRQs. +/// +/// The original state needs to be stored to not accidentially enable IRQs in +/// contexts which have IRQs disabled by other means, e.g. in an exception or +/// NMI/HV context. +#[derive(Debug, Default)] +pub struct IrqState {
This type should be `!Sync` because we don't want CPUs to mess with the irq state of other CPUs.
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -213,6 +213,11 @@ handle_as_hv: call process_hv_events // fall through to default_return +.globl return_new_task +return_new_task: + call setup_new_task + jmp default_return
```suggestion .globl return_new_task return_new_task: sub rsp, 8 call setup_new_task add rsp, 8 jmp default_return ``` Make sure that the stack is correctly aligned.
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -4,22 +4,26 @@ // // Author: Joerg Roedel <jroedel@suse.de> +use super::common::*; use core::cell::UnsafeCell; +use core::marker::PhantomData; use core::ops::{Deref, DerefMut}; use core::sync::atomic::{AtomicU64, Ordering}; /// A guard that provides read access to the data protected by [`RWLock`] #[derive(Debug)] #[must_use = "if unused the RWLock will immediately unlock"] -pub struct ReadLockGuard<'a, T> { +pub struct RawReadLockGuard<'a, T, I: IrqLocking> {
See https://github.com/coconut-svsm/svsm/pull/441#discussion_r1724624363
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -93,12 +107,14 @@ pub struct SpinLock<T> { /// protected data. That is, it allows the data to be accessed/modified /// while enforcing the locking mechanism. data: UnsafeCell<T>, + /// Use generic type I in the struct without consuming space. + phantom: PhantomData<I>,
This makes the lock `!Send` and `!Sync` if `I` is `!Send` and `!Sync`. Try this instead: ```suggestion phantom: PhantomData<fn(I)>, ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -28,26 +32,31 @@ impl<T> Drop for ReadLockGuard<'_, T> { /// Implements the behavior of dereferencing the [`ReadLockGuard`] to /// access the protected data. -impl<T> Deref for ReadLockGuard<'_, T> { +impl<T, I: IrqLocking> Deref for RawReadLockGuard<'_, T, I> {
```suggestion impl<T, I> Deref for RawReadLockGuard<'_, T, I> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -56,7 +65,7 @@ impl<T> Drop for WriteLockGuard<'_, T> { /// Implements the behavior of dereferencing the [`WriteLockGuard`] to /// access the protected data. -impl<T> Deref for WriteLockGuard<'_, T> { +impl<T, I: IrqLocking> Deref for RawWriteLockGuard<'_, T, I> {
```suggestion impl<T, I> Deref for RawWriteLockGuard<'_, T, I> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -65,26 +74,31 @@ impl<T> Deref for WriteLockGuard<'_, T> { /// Implements the behavior of dereferencing the [`WriteLockGuard`] to /// access the protected data in a mutable way. -impl<T> DerefMut for WriteLockGuard<'_, T> { +impl<T, I: IrqLocking> DerefMut for RawWriteLockGuard<'_, T, I> {
```suggestion impl<T, I> DerefMut for RawWriteLockGuard<'_, T, I> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -65,26 +74,31 @@ impl<T> Deref for WriteLockGuard<'_, T> { /// Implements the behavior of dereferencing the [`WriteLockGuard`] to /// access the protected data in a mutable way. -impl<T> DerefMut for WriteLockGuard<'_, T> { +impl<T, I: IrqLocking> DerefMut for RawWriteLockGuard<'_, T, I> { fn deref_mut(&mut self) -> &mut T { self.data } } +pub type WriteLockGuard<'a, T> = RawWriteLockGuard<'a, T, IrqUnsafeLocking>; +pub type WriteLockGuardIrqSafe<'a, T> = RawWriteLockGuard<'a, T, IrqSafeLocking>; + /// A simple Read-Write Lock (RWLock) that allows multiple readers or /// one exclusive writer. #[derive(Debug)] -pub struct RWLock<T> { +pub struct RawRWLock<T, I: IrqLocking> {
```suggestion pub struct RawRWLock<T, I> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -65,26 +74,31 @@ impl<T> Deref for WriteLockGuard<'_, T> { /// Implements the behavior of dereferencing the [`WriteLockGuard`] to /// access the protected data in a mutable way. -impl<T> DerefMut for WriteLockGuard<'_, T> { +impl<T, I: IrqLocking> DerefMut for RawWriteLockGuard<'_, T, I> { fn deref_mut(&mut self) -> &mut T { self.data } } +pub type WriteLockGuard<'a, T> = RawWriteLockGuard<'a, T, IrqUnsafeLocking>; +pub type WriteLockGuardIrqSafe<'a, T> = RawWriteLockGuard<'a, T, IrqSafeLocking>; + /// A simple Read-Write Lock (RWLock) that allows multiple readers or /// one exclusive writer. #[derive(Debug)] -pub struct RWLock<T> { +pub struct RawRWLock<T, I: IrqLocking> { /// An atomic 64-bit integer used for synchronization rwlock: AtomicU64, /// An UnsafeCell for interior mutability data: UnsafeCell<T>, + /// Silence unused type warning + phantom: PhantomData<fn(I)>, } /// Implements the trait `Sync` for the [`RWLock`], allowing safe /// concurrent access across threads. -unsafe impl<T: Send> Send for RWLock<T> {} -unsafe impl<T: Send + Sync> Sync for RWLock<T> {} +unsafe impl<T: Send, I: IrqLocking> Send for RawRWLock<T, I> {} +unsafe impl<T: Send + Sync, I: IrqLocking> Sync for RawRWLock<T, I> {}
```suggestion unsafe impl<T: Send, I> Send for RawRWLock<T, I> {} unsafe impl<T: Send + Sync, I> Sync for RawRWLock<T, I> {} ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -27,13 +29,15 @@ use core::sync::atomic::{AtomicU64, Ordering}; /// ``` #[derive(Debug)] #[must_use = "if unused the SpinLock will immediately unlock"] -pub struct LockGuard<'a, T> { +pub struct RawLockGuard<'a, T, I: IrqLocking = IrqUnsafeLocking> { holder: &'a AtomicU64, data: &'a mut T, + #[allow(dead_code)] + irq_state: I, } /// Implements the behavior of the [`LockGuard`] when it is dropped -impl<T> Drop for LockGuard<'_, T> { +impl<T, I: IrqLocking> Drop for RawLockGuard<'_, T, I> {
```suggestion impl<T, I> Drop for RawLockGuard<'_, T, I> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -27,13 +29,15 @@ use core::sync::atomic::{AtomicU64, Ordering}; /// ``` #[derive(Debug)] #[must_use = "if unused the SpinLock will immediately unlock"] -pub struct LockGuard<'a, T> { +pub struct RawLockGuard<'a, T, I: IrqLocking = IrqUnsafeLocking> {
```suggestion pub struct RawLockGuard<'a, T, I = IrqUnsafeLocking> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -42,7 +46,7 @@ impl<T> Drop for LockGuard<'_, T> { /// Implements the behavior of dereferencing the [`LockGuard`] to /// access the protected data. -impl<T> Deref for LockGuard<'_, T> { +impl<T, I: IrqLocking> Deref for RawLockGuard<'_, T, I> {
```suggestion impl<T, I> Deref for RawLockGuard<'_, T, I> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -52,14 +56,24 @@ impl<T> Deref for LockGuard<'_, T> { /// Implements the behavior of dereferencing the [`LockGuard`] to /// access the protected data in a mutable way. -impl<T> DerefMut for LockGuard<'_, T> { +impl<T, I: IrqLocking> DerefMut for RawLockGuard<'_, T, I> {
```suggestion impl<T, I> DerefMut for RawLockGuard<'_, T, I> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -81,7 +95,7 @@ impl<T> DerefMut for LockGuard<'_, T> { /// }; /// ``` #[derive(Debug, Default)] -pub struct SpinLock<T> { +pub struct RawSpinLock<T, I: IrqLocking = IrqUnsafeLocking> {
```suggestion pub struct RawSpinLock<T, I = IrqUnsafeLocking> { ```
svsm
github_2023
others
441
coconut-svsm
Freax13
@@ -93,12 +107,14 @@ pub struct SpinLock<T> { /// protected data. That is, it allows the data to be accessed/modified /// while enforcing the locking mechanism. data: UnsafeCell<T>, + /// Use generic type I in the struct without consuming space. + phantom: PhantomData<fn(I)>, } -unsafe impl<T: Send> Send for SpinLock<T> {} -unsafe impl<T: Send> Sync for SpinLock<T> {} +unsafe impl<T: Send, I: IrqLocking> Send for RawSpinLock<T, I> {} +unsafe impl<T: Send, I: IrqLocking> Sync for RawSpinLock<T, I> {}
```suggestion unsafe impl<T: Send, I> Send for RawSpinLock<T, I> {} unsafe impl<T: Send, I> Sync for RawSpinLock<T, I> {} ```
svsm
github_2023
others
442
coconut-svsm
Freax13
@@ -977,7 +977,7 @@ struct RawPageTablePart { impl RawPageTablePart { /// Frees a level 1 page table. fn free_lvl1(page: &PTPage) { - for entry in page.entries { + for &entry in &page.entries {
```suggestion for entry in page.entries.iter().copied() { ``` Nit: This could be a little more idiomatic.
svsm
github_2023
others
422
coconut-svsm
cclaudio
@@ -1,10 +1,8 @@ FEATURES ?= "default" -SVSM_ARGS = --features ${FEATURES} +SVSM_ARGS = --no-default-features --features ${FEATURES}
`FEATURES=default make` or just `make`, will that still pick the features set in the the default flag? If not we may want to control those features under a different flag (e.g. svsm_default :-P)
svsm
github_2023
others
422
coconut-svsm
joergroedel
@@ -22,7 +22,7 @@ members = [ bootlib = { path = "bootlib" } cpuarch = { path = "cpuarch" } test = { path = "test" } -svsm = { path = "kernel" } +svsm = { path = "kernel", default-features = false }
I'd like to avoid removing the ability to add default features. Can we instead remove `mstpm` from the default freature set and add it to the default setting of `FEATURES` in the Makefile? This will also allow to disable `mstpm` during the build process.
svsm
github_2023
others
420
coconut-svsm
Freax13
@@ -22,76 +22,88 @@ fn bitmap_alloc_order(region: MemoryRegion<PhysAddr>) -> usize { } pub fn init_valid_bitmap_ptr(region: MemoryRegion<PhysAddr>, bitmap: *mut u64) { - let mut vb_ref = VALID_BITMAP.lock(); - vb_ref.set_region(region); - vb_ref.set_bitmap(bitmap); + let bitmap = ValidBitmap::new(region, bitmap); + *VALID_BITMAP.lock() = Some(bitmap); } pub fn init_valid_bitmap_alloc(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> { let order: usize = bitmap_alloc_order(region); - let bitmap_addr = allocate_pages(order)?; + let bitmap_addr = allocate_pages(order)?.as_mut_ptr(); - let mut vb_ref = VALID_BITMAP.lock(); - vb_ref.set_region(region); - vb_ref.set_bitmap(bitmap_addr.as_mut_ptr::<u64>()); - vb_ref.clear_all(); + let mut bitmap = ValidBitmap::new(region, bitmap_addr); + bitmap.clear_all(); + *VALID_BITMAP.lock() = Some(bitmap); Ok(()) } pub fn migrate_valid_bitmap() -> Result<(), SvsmError> { - let order: usize = VALID_BITMAP.lock().alloc_order(); + let order: usize = VALID_BITMAP.lock().as_ref().unwrap().alloc_order(); let bitmap_addr = allocate_pages(order)?; // lock again here because allocator path also takes VALID_BITMAP.lock() - let mut vb_ref = VALID_BITMAP.lock(); - vb_ref.migrate(bitmap_addr.as_mut_ptr::<u64>()); + VALID_BITMAP + .lock() + .as_mut() + .unwrap() + .migrate(bitmap_addr.as_mut_ptr()); Ok(()) } pub fn validated_phys_addr(paddr: PhysAddr) -> bool { - let vb_ref = VALID_BITMAP.lock(); - vb_ref.is_valid_4k(paddr) + VALID_BITMAP + .lock() + .as_ref() + .map(|vb| vb.is_valid_4k(paddr)) + .unwrap_or(false) } pub fn valid_bitmap_set_valid_4k(paddr: PhysAddr) { - let mut vb_ref = VALID_BITMAP.lock(); - vb_ref.set_valid_4k(paddr) + if let Some(vb) = VALID_BITMAP.lock().as_mut() { + vb.set_valid_4k(paddr); + };
```suggestion } ``` The same change can be done in a couple of functions below this one.
svsm
github_2023
others
420
coconut-svsm
Freax13
@@ -134,84 +138,44 @@ impl ValidBitmap { (index, bit) } - fn clear_all(&mut self) { - let len = self.bitmap_len(); - unsafe { - ptr::write_bytes(self.bitmap, 0, len); + fn migrate(&mut self, mut new: PageBox<[MaybeUninit<u64>]>) { + for (dst, src) in new.iter_mut().zip(self.bitmap.iter()) {
Here's another way to implement this with a single loop: ```rust for (dst, src) in new .iter_mut() .zip(self.bitmap.iter().copied().chain(repeat(0))) { dst.write(src); } ```
svsm
github_2023
others
420
coconut-svsm
Freax13
@@ -192,10 +174,8 @@ impl ValidBitmap { assert!(paddr.is_aligned(PAGE_SIZE_2M)); assert!(self.check_addr(paddr)); - for i in 0..NR_INDEX { - unsafe { - ptr::write(self.bitmap.add(index + i), val); - } + for dst in self.bitmap[index..index + NR_INDEX].iter_mut() { + *dst = val;
This loop (and the one in line 207) can be replaced with ```rust self.bitmap[index..index + NR_INDEX].fill(val); ```
svsm
github_2023
others
420
coconut-svsm
Freax13
@@ -245,8 +202,8 @@ impl ValidBitmap { let mask_head = mask >> bit_head_begin << bit_head_begin; self.modify_bitmap_word(index_head, mask_head, new_val); - for index in (index_head + 1)..index_tail { - unsafe { ptr::write(self.bitmap.add(index), new_val) }; + for val in self.bitmap[index_head + 1..index_tail].iter_mut() { + *val = new_val;
This loop can also be expressed using `.fill(new_value)`.
svsm
github_2023
others
438
coconut-svsm
Freax13
@@ -257,12 +257,15 @@ pub fn triple_fault() { } extern "C" { - static generic_idt_handler_return: u8; + static entry_code_start: u8; + static entry_code_end: u8; } pub fn is_exception_handler_return_site(rip: VirtAddr) -> bool { - let addr = unsafe { VirtAddr::from(addr_of!(generic_idt_handler_return)) }; - addr == rip + let start = unsafe { VirtAddr::from(addr_of!(entry_code_start)) }; + let end = unsafe { VirtAddr::from(addr_of!(entry_code_end)) }; + + rip >= start && rip < end
```suggestion let start = VirtAddr::from(unsafe { addr_of!(entry_code_start) }); let end = VirtAddr::from(unsafe { addr_of!(entry_code_end) }); (start..end).contains(&rip) ```
svsm
github_2023
others
438
coconut-svsm
Freax13
@@ -204,6 +204,23 @@ where self.start() <= addr && addr < self.end() } + /// Check whether an address is within this region, treating `end` as part + /// of the region. + /// + /// ```rust + /// # use svsm::address::VirtAddr; + /// # use svsm::types::{PAGE_SIZE, PageSize}; + /// # use svsm::utils::MemoryRegion; + /// let region = MemoryRegion::new(VirtAddr::from(0xffffff0000u64), PAGE_SIZE); + /// assert!(region.contains_inclusive(VirtAddr::from(0xffffff0000u64))); + /// assert!(region.contains_inclusive(VirtAddr::from(0xffffff0fffu64))); + /// assert!(region.contains_inclusive(VirtAddr::from(0xffffff1000u64))); + /// assert!(!region.contains_inclusive(VirtAddr::from(0xffffff1001u64))); + /// ``` + pub fn contains_inclusive(&self, addr: A) -> bool { + self.start() <= addr && addr <= self.end()
```suggestion (self.start()..=self.end()).contains(&addr) ```
svsm
github_2023
others
438
coconut-svsm
Freax13
@@ -73,9 +73,17 @@ impl StackUnwinder { rip: VirtAddr, stacks: &StacksBounds, ) -> UnwoundStackFrame { - // The next frame's rsp should live on some valid stack, otherwise mark - // the unwound frame as invalid. - let Some(stack) = stacks.iter().find(|stack| stack.contains(rsp)) else { + // The next frame's rsp or rbp should live on some valid stack, + // otherwise mark the unwound frame as invalid. + let Some(stack) = stacks + .iter() + .find(|stack| stack.contains_inclusive(rsp) || stack.contains_inclusive(rbp)) + else { + log::info!( + "check_unwound_frame: rsp {:#018x} and rbp {:#018x} does not match any known stack", + rsp, + rbp + );
```suggestion log::info!("check_unwound_frame: rsp {rsp:#018x} and rbp {rbp:#018x} does not match any known stack"); ```
svsm
github_2023
others
271
coconut-svsm
msft-jlange
@@ -257,3 +256,42 @@ fn vc_decode_insn(ctx: &mut X86ExceptionContext) -> Result<Instruction, SvsmErro fn vc_decoding_needed(error_code: usize) -> bool { !(SVM_EXIT_EXCP_BASE..=SVM_EXIT_LAST_EXCP).contains(&error_code) } + +/// Used to move to a safe stack if #VC is a nested one or raised from user-mode. +/// +/// # Arguments: +/// +/// - `ctx`: registers from the exception raising context that have been pushed on the initial +/// handler stack at the early handling stage. +/// +/// # Returns: +/// +/// [`VirtAddr`]: the new stack address. This address is directly moved to RSP in the caller. +/// Therefore, the new address should absolutely be valid. +#[no_mangle] +extern "C" fn vc_switch_off_ist(ctx: &X86ExceptionContext) -> VirtAddr { + // Detect user #VC or nested IST #VC + let mut new_rsp = if from_user(ctx) || vc_on_ist_stack(ctx) { + this_cpu().current_stack.end() + } else { + VirtAddr::from(ctx.frame.rsp)
This will not be correct in a SYSCALL gap. If the #VC is delivered immediately after control transfers to kernel mode to the SYSCALL entry point, the CS on the exception frame will indicate a kernel mode CS, but the RSP in the exception frame will be the user-mode RSP since the SYSCALL entry point will not yet have been able to switch to the kernel-mode stack. It would be a serious problem if this routine were to attempt to switch off of the IST stack back onto the user-mode stack. Because the untrusted host can choose to remove the page backing the SYSCALL entry point and replace it with a different page, it is certainly possible for the first instruction at the SYSCALL entry point to raise #VC due to a page-not-validated error, so this must be anticipated. A similar problem exists immediately prior to SYSRET. A carefully timed interrupt by the untrusted host could cause the code page to disappear after the user RSP is reloaded but before SYSRET executes, and the resulting #VC will again appear to come from kernel mode on the user stack. This code must also anticipate that possibility. Of course, both of these cases are security attacks which could reasonably result in a panic, but that panic must occur before an inadvertent switch to the user stack.
svsm
github_2023
others
417
coconut-svsm
00xc
@@ -106,6 +106,6 @@ impl Drop for PerCPUPageMappingGuard { this_cpu().get_pgtable().unmap_region_4k(self.mapping); virt_free_range_4k(self.mapping); } - flush_address_sync(self.mapping.start()); + flush_address_percpu(self.mapping.start());
The mapping may be larger than a single page, does this call take that into account?
svsm
github_2023
others
417
coconut-svsm
00xc
@@ -50,6 +50,29 @@ pub fn flush_tlb_global_sync() { do_tlbsync(); } +pub fn flush_tlb_global_percpu() { + unsafe { + asm!( + "movq %cr4, %rax", + "movl $0x80, %edx", // CR4_PGE + "not %rdx", + "andq %rax, %rdx", + "movq %rdx, %cr4", + "movq %rax, %cr4", + options(att_syntax) + ); + }
Could we do this using `read_cr4()` and `write_cr4()` in `kernel/src/cpu/control_regs.rs`?
svsm
github_2023
others
417
coconut-svsm
00xc
@@ -24,10 +24,14 @@ pub fn cr4_init() { cr4.insert(CR4Flags::PSE); // Enable Page Size Extensions - if cpu_has_pge() { - cr4.insert(CR4Flags::PGE); // Enable Global Pages + if !cpu_has_pge() { + // All processors that are capable of virtualization will support + // global page table entries, so there is no reason to support any + // processor that does not enumerate PGE capability. + panic!("CPU does not support PGE"); }
Minor style suggestion: ```suggestion // All processors that are capable of virtualization will support // global page table entries, so there is no reason to support any // processor that does not enumerate PGE capability. assert!(cpu_has_pge(), "CPU does not support PGE"); ```
svsm
github_2023
others
417
coconut-svsm
00xc
@@ -36,9 +36,13 @@ pub fn write_efer(efer: EFERFlags) { pub fn efer_init() { let mut efer = read_efer(); - if cpu_has_nx() { - efer.insert(EFERFlags::NXE); + if !cpu_has_nx() { + // All processors that are capable of virtualization will support + // no-execute table entries, so there is no reason to support any + // processor that does not enumerate NX capability. + panic!("CPU does not support NX"); }
Again, style suggestion, feel free to ignore: ```suggestion // All processors that are capable of virtualization will support // no-execute table entries, so there is no reason to support any // processor that does not enumerate NX capability. assert!(cpu_has_nx(), "CPU does not support NX"); ```
svsm
github_2023
others
417
coconut-svsm
00xc
@@ -50,6 +52,28 @@ pub fn flush_tlb_global_sync() { do_tlbsync(); } +pub fn flush_tlb_global_percpu() { + let cr4 = read_cr4(); + let cr4_nopge = { + // bitflags requires a mut object to add/remove flags, and bitflags + // does not implement either Clone or Copy. + let mut temp = CR4Flags::from_bits_truncate(cr4.bits()); + temp.toggle(CR4Flags::PGE); + temp + }; + write_cr4(cr4_nopge); + write_cr4(cr4);
We should derive `Copy` (and `Clone`) for `CR4Flags` so that we can do: ```suggestion let cr4 = read_cr4(); write_cr4(cr4 ^ CR4Flags::PGE); write_cr4(cr4); ```
svsm
github_2023
others
348
coconut-svsm
msft-jlange
@@ -309,25 +283,26 @@ impl PerCpuUnsafe { } pub fn setup_ghcb(&mut self) -> Result<(), SvsmError> { - let ghcb_page = allocate_zeroed_page().expect("Failed to allocate GHCB page"); - if let Err(e) = GHCB::init(ghcb_page) { - free_page(ghcb_page); - return Err(e); - }; - self.ghcb = ghcb_page.as_mut_ptr(); + self.ghcb = Some(GhcbPage::new()?); Ok(()) } - pub fn ghcb_unsafe(&self) -> *mut GHCB { + pub fn ghcb_unsafe(&mut self) -> *mut GHCB { self.ghcb + .as_mut() + .map(|g| g.as_mut_ptr()) + .unwrap_or(ptr::null_mut()) } - pub fn hv_doorbell_unsafe(&self) -> *mut HVDoorbell { - self.hv_doorbell + pub fn hv_doorbell(&self) -> Option<&HVDoorbell> {
I have two concerns with this approach. First, this is still a method on `PerCpuUnsafe`, which means that callers will still have to access this via unsafe code (since `this_cpu_unsafe()` returns a pointer). I think it would be better to define a global function called `current_hv_doorbell()` or similar which hides all of the unsafe and returns a static reference. Second, it changes the return type to an `Option` which means that all callers must be prepared to handle error cases. The intention with the use of the doorbell page is that no caller should ever attempt to access the doorbell page until it has been allocated, which means it is preferable to put the unwrap and associated panic into the global function instead of requiring every caller to handle it separately. I know that's not how it's implemented today but that's the path I've been on with APIC emulation. It would be unfortunate to require every caller to perform Option checks on their own on a data structure that is expected to be always present.
svsm
github_2023
others
348
coconut-svsm
msft-jlange
@@ -5,45 +5,85 @@ // Author: Joerg Roedel <jroedel@suse.de> use super::utils::{rmp_adjust, RMPFlags}; -use crate::address::{Address, VirtAddr}; +use crate::address::{Address, PhysAddr}; use crate::error::SvsmError; -use crate::mm::alloc::{allocate_pages, free_page}; +use crate::mm::{virt_to_phys, PageBox}; use crate::platform::guest_cpu::GuestCpuState; use crate::sev::status::SEVStatusFlags; -use crate::types::{PageSize, PAGE_SIZE, PAGE_SIZE_2M}; -use crate::utils::zero_mem_region; +use crate::types::{PageSize, PAGE_SIZE_2M}; +use core::mem::ManuallyDrop; +use core::ops::{Deref, DerefMut}; use cpuarch::vmsa::{VmsaEventInject, VmsaEventType, VMSA}; pub const VMPL_MAX: usize = 4; -pub fn allocate_new_vmsa(vmpl: RMPFlags) -> Result<VirtAddr, SvsmError> { - assert!(vmpl.bits() < (VMPL_MAX as u64)); - - // Make sure the VMSA page is not 2M aligned. Some hardware generations - // can't handle this properly. - let mut vmsa_page = allocate_pages(0)?; - if vmsa_page.is_aligned(PAGE_SIZE_2M) { - free_page(vmsa_page); - vmsa_page = allocate_pages(1)?; - if vmsa_page.is_aligned(PAGE_SIZE_2M) { - vmsa_page = vmsa_page + PAGE_SIZE; +/// An allocated page containing a VMSA structure. +#[derive(Debug)] +pub struct VmsaPage(PageBox<VMSA>); + +impl VmsaPage { + /// Allocates a new VMSA for the given VPML. + pub fn new(vmpl: RMPFlags) -> Result<Self, SvsmError> { + assert!(vmpl.bits() < (VMPL_MAX as u64)); + + let mut page = PageBox::try_new_zeroed()?; + // Make sure the VMSA page is not 2M aligned. Some hardware generations + // can't handle this properly. + while page.vaddr().is_aligned(PAGE_SIZE_2M) {
This can result in an infinite loop as the allocator could keep flip-flopping between the same two 2M-aligned pages. The original code would allocate two contiguous pages in the case that the first allocation was 2M-aligned, because allocating two contiguous pages is guaranteed to produce at least one that is not 2M-aligned. The old code would also have the unfortunate behavior that when allocating a pair of pages, one of them would be leaked, which is not strictly necessary as I believe the page allocator can free partial allocations. We should make sure that the new code has compatible behavior. Perhaps we need a flag to `PageBox::try_new()` (and its callers) to indicate that the allocation must not be 2M-aligned, and then `PageBox::try_new()` can internally do the dance required to produce (and not leak) an unaligned page. Alternatively, a distinct function like `PageBox::try_new_unaligned()` could be implemented, and since its use is so rare, we could require callers to take responsibility for initializing the contents rather than having to implement a whole suite of unaligned functions.
svsm
github_2023
others
348
coconut-svsm
msft-jlange
@@ -46,6 +47,59 @@ pub struct HVExtIntInfo { pub isr: [AtomicU32; 8], } +/// An allocation containing the `#HV` doorbell page. +#[derive(Debug)] +pub struct HVDoorbellPage(PageBox<HVDoorbell>); + +impl HVDoorbellPage { + /// Allocates a new HV doorbell page and registers it on the hypervisor + /// using the given GHCB. + pub fn new(ghcb: &GHCB) -> Result<Self, SvsmError> { + // SAFETY: all zeroes is a valid representation for `HVDoorbell`. + let page = PageBox::try_new_zeroed()?; + let paddr = virt_to_phys(page.vaddr()); + + // The #HV doorbell page must be shared before it can be used. + make_page_shared(page.vaddr())?; + + // Now Drop will have correct behavior, so construct the new type.
`Drop` will not have the correct behavior once the page has been made shared, because the implementation of `PageBox::drop()` is not aware that the page has become shared and thus cannot make the page private before it is returned to the free pool. This will cause fatal errors if the page is attempted to be used again in a private context. I think we're going to need to introduce `PageBox::make_page_shared(&self)` and a matching function to make the page private, and to have the `PageBox` structure hold a flag indicating whether the page was made shared so that it can be made private again if necessary before being freed.
svsm
github_2023
others
348
coconut-svsm
msft-jlange
@@ -46,6 +47,59 @@ pub struct HVExtIntInfo { pub isr: [AtomicU32; 8], } +/// An allocation containing the `#HV` doorbell page. +#[derive(Debug)] +pub struct HVDoorbellPage(PageBox<HVDoorbell>); + +impl HVDoorbellPage { + /// Allocates a new HV doorbell page and registers it on the hypervisor + /// using the given GHCB. + pub fn new(ghcb: &GHCB) -> Result<Self, SvsmError> { + // SAFETY: all zeroes is a valid representation for `HVDoorbell`. + let page = PageBox::try_new_zeroed()?; + let paddr = virt_to_phys(page.vaddr()); + + // The #HV doorbell page must be shared before it can be used. + make_page_shared(page.vaddr())?; + + // Now Drop will have correct behavior, so construct the new type. + // SAFETY: all zeros is a valid representation of the HV doorbell page. + let page = unsafe { Self(page.assume_init()) }; + ghcb.register_hv_doorbell(paddr)?; + Ok(page) + } + + /// Leaks the page allocation, ensuring it will never be freed. + pub fn leak(self) -> &'static HVDoorbell { + let mut doorbell = ManuallyDrop::new(self); + let ptr = core::ptr::from_mut(&mut doorbell); + // SAFETY: this pointer will never be freed because of ManuallyDrop, + // so we can create a static mutable reference. We go through a raw + // pointer to promote the lifetime to static. + unsafe { &mut *ptr } + } +} + +impl Deref for HVDoorbellPage { + type Target = HVDoorbell; + + fn deref(&self) -> &Self::Target { + self.0.deref() + } +} + +impl DerefMut for HVDoorbellPage {
All of the fields of `HVDoorbellPage` are atomic, and thus all uses should only be attempted using shared references. I think we will want to discourage - even outlaw - the use of mutable references to the doorbell page as they are unlikely ever to work as expected, so perhaps we should not implement this trait.
svsm
github_2023
others
348
coconut-svsm
msft-jlange
@@ -126,6 +128,56 @@ impl TryFrom<Bytes> for GHCBIOSize { } } +#[derive(Debug)] +pub struct GhcbPage(PageBox<GHCB>); + +impl GhcbPage { + pub fn new() -> Result<Self, SvsmError> { + let page = PageBox::try_new_zeroed()?; + let vaddr = page.vaddr(); + let paddr = virt_to_phys(vaddr); + + if sev_snp_enabled() { + // Make page invalid + pvalidate(vaddr, PageSize::Regular, PvalidateOp::Invalid)?;
This should use `make_page_shared()` in the same way that the HV doorbell page makes the page shared. The old code was different, but this is our opportunity to align the two implementations - especially since we will want to have the same shared/private tracking for the GHCB page that we do for the HV doorbell page.
svsm
github_2023
others
396
coconut-svsm
00xc
@@ -32,9 +38,15 @@ impl Default for TdpPlatform { } impl SvsmPlatform for TdpPlatform { - fn env_setup(&mut self) {} - - fn env_setup_late(&mut self) {} + fn env_setup(&mut self, _debug_serial_port: u16) {} + + fn env_setup_late(&mut self, debug_serial_port: u16) { + CONSOLE_SERIAL + .init(&SerialPort::new(&CONSOLE_IO, debug_serial_port)) + .expect("console serial output already configured"); + (*CONSOLE_SERIAL).init(); + init_console(&*CONSOLE_SERIAL).expect("Console writer already initialized");
Let's perhaps return an error here and let the caller panic (and the same for other platforms).
svsm
github_2023
others
396
coconut-svsm
00xc
@@ -101,19 +99,11 @@ fn setup_env( // Init IDT again with handlers requiring GHCB (eg. #VC handler) early_idt_init(); - CONSOLE_SERIAL - .init(&SerialPort::new( - platform.get_console_io_port(), - config.debug_serial_port(), - )) - .expect("console serial output already configured"); - (*CONSOLE_SERIAL).init(); - init_console(&*CONSOLE_SERIAL).expect("Console writer already initialized"); - - // Console is fully working now and any unsupported configuration can be - // properly reported. + // Complete initializtio of the platform. After that point, the console
```suggestion // Complete initialization of the platform. After that point, the console ```
svsm
github_2023
others
396
coconut-svsm
00xc
@@ -34,8 +39,19 @@ impl Default for NativePlatform { } impl SvsmPlatform for NativePlatform { - fn env_setup(&mut self) {} - fn env_setup_late(&mut self) {} + fn env_setup(&mut self, debug_serial_port: u16) -> Result<(), SvsmError> { + // In the native platform, console output does not require the use of + // any platform services, so it can be initialized immediately. + CONSOLE_SERIAL + .init(&SerialPort::new(&CONSOLE_IO, debug_serial_port)) + .expect("console serial output already configured");
Could we also return an error here? The caller will panic anyway and this way we have less implicit panics.
svsm
github_2023
others
396
coconut-svsm
00xc
@@ -43,13 +47,20 @@ impl Default for SnpPlatform { } impl SvsmPlatform for SnpPlatform { - fn env_setup(&mut self) { + fn env_setup(&mut self, _debug_serial_port: u16) -> Result<(), SvsmError> { sev_status_init(); + Ok(()) } - fn env_setup_late(&mut self) { + fn env_setup_late(&mut self, debug_serial_port: u16) -> Result<(), SvsmError> { + CONSOLE_SERIAL + .init(&SerialPort::new(&CONSOLE_IO, debug_serial_port)) + .expect("console serial output already configured");
Same thing here
svsm
github_2023
others
396
coconut-svsm
00xc
@@ -32,9 +38,17 @@ impl Default for TdpPlatform { } impl SvsmPlatform for TdpPlatform { - fn env_setup(&mut self) {} + fn env_setup(&mut self, _debug_serial_port: u16) -> Result<(), SvsmError> { + Ok(()) + } - fn env_setup_late(&mut self) {} + fn env_setup_late(&mut self, debug_serial_port: u16) -> Result<(), SvsmError> { + CONSOLE_SERIAL + .init(&SerialPort::new(&CONSOLE_IO, debug_serial_port)) + .expect("console serial output already configured");
And here
svsm
github_2023
others
396
coconut-svsm
00xc
@@ -73,6 +73,8 @@ macro_rules! ghcb_setter { #[derive(Clone, Copy, Debug)] pub enum GhcbError { + // Failed to initialize the GHCB + Initialization,
I see we introduced this but we're not using it anywhere.
svsm
github_2023
others
407
coconut-svsm
00xc
@@ -735,28 +735,31 @@ impl PerCpu { let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - // This function should never be called if APIC emulation is not - // enabled, so the unwrap below is appropriate. - self.apic_mut() - .unwrap() - .read_register(self.shared(), vmsa, caa_addr, register) + if let Some(mut apic) = self.apic_mut() { + apic.read_register(self.shared(), vmsa, caa_addr, register) + } else { + Err(SvsmError::Apic(ApicError::Disabled)) + }
```suggestion self.apic_mut() .ok_or(SvsmError::Apic(ApicError::Disabled))? .read_register(self.shared(), vmsa, caa_addr, register) ```
svsm
github_2023
others
407
coconut-svsm
00xc
@@ -735,28 +735,31 @@ impl PerCpu { let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - // This function should never be called if APIC emulation is not - // enabled, so the unwrap below is appropriate. - self.apic_mut() - .unwrap() - .read_register(self.shared(), vmsa, caa_addr, register) + if let Some(mut apic) = self.apic_mut() { + apic.read_register(self.shared(), vmsa, caa_addr, register) + } else { + Err(SvsmError::Apic(ApicError::Disabled)) + } } pub fn write_apic_register(&self, register: u64, value: u64) -> Result<(), SvsmError> { let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - // This function should never be called if APIC emulation is not - // enabled, so the unwrap below is appropriate. - self.apic_mut() - .unwrap() - .write_register(vmsa, caa_addr, register, value) + if let Some(mut apic) = self.apic_mut() { + apic.write_register(vmsa, caa_addr, register, value) + } else { + Err(SvsmError::Apic(ApicError::Disabled)) + }
```suggestion self.apic_mut() .ok_or(SvsmError::Apic(ApicError::Disabled))? .write_register(vmsa, caa_addr, register, value) ```
svsm
github_2023
others
407
coconut-svsm
00xc
@@ -735,28 +735,31 @@ impl PerCpu { let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - // This function should never be called if APIC emulation is not - // enabled, so the unwrap below is appropriate. - self.apic_mut() - .unwrap() - .read_register(self.shared(), vmsa, caa_addr, register) + if let Some(mut apic) = self.apic_mut() { + apic.read_register(self.shared(), vmsa, caa_addr, register) + } else { + Err(SvsmError::Apic(ApicError::Disabled)) + } } pub fn write_apic_register(&self, register: u64, value: u64) -> Result<(), SvsmError> { let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - // This function should never be called if APIC emulation is not - // enabled, so the unwrap below is appropriate. - self.apic_mut() - .unwrap() - .write_register(vmsa, caa_addr, register, value) + if let Some(mut apic) = self.apic_mut() { + apic.write_register(vmsa, caa_addr, register, value) + } else { + Err(SvsmError::Apic(ApicError::Disabled)) + } } - pub fn configure_apic_vector(&self, vector: u8, allowed: bool) { - // This function should never be called if APIC emulation is not - // enabled, so the unwrap below is appropriate. - self.apic_mut().unwrap().configure_vector(vector, allowed) + pub fn configure_apic_vector(&self, vector: u8, allowed: bool) -> Result<(), SvsmError> { + if let Some(mut apic) = self.apic_mut() { + apic.configure_vector(vector, allowed); + Ok(()) + } else { + Err(SvsmError::Apic(ApicError::Disabled)) + }
```suggestion self.apic_mut() .ok_or(SvsmError::Apic(ApicError::Disabled))? .configure_vector(vector, allowed); Ok(()) ```
svsm
github_2023
others
403
coconut-svsm
00xc
@@ -28,6 +28,17 @@ use crate::sev::SevSnpError; use crate::task::TaskError; use elf::ElfError; +/// Errors related to APIC handling. These may originate from multiple +/// layers in the system. +#[derive(Clone, Copy, Debug)] +pub enum ApicError { + /// An error relted to APIC emulation.
```suggestion /// An error related to APIC emulation. ```
svsm
github_2023
others
403
coconut-svsm
00xc
@@ -72,7 +83,7 @@ pub enum SvsmError { /// The operation is not supported. NotSupported, /// Generic errors related to APIC emulation. - Apic, + Apic(ApicError),
Let's also implement `From<ApicError> for SvsmError` to follow the convention in the rest of the codebase.
svsm
github_2023
others
403
coconut-svsm
00xc
@@ -47,7 +45,7 @@ fn apic_configure(params: &RequestParams) -> Result<(), SvsmReqError> { // this will not cause any change to the state of the current CPU. return match platform.change_apic_registration_state(true) { Ok(_) => Ok(()), - Err(_) => Err(SvsmReqError::protocol(SVSM_ERR_APIC_CANNOT_REGISTER)), + Err(e) => Err(SvsmReqError::from(e)), };
We can now take advantage of the `From` implementation by using the `?` operator: ```rust platform.change_apic_registration_state(true)?; return Ok(()); ```
svsm
github_2023
others
403
coconut-svsm
00xc
@@ -71,7 +69,7 @@ fn apic_read_register(params: &mut RequestParams) -> Result<(), SvsmReqError> { } let value = cpu .read_apic_register(params.rcx) - .map_err(|_| SvsmReqError::invalid_parameter())?; + .map_err(SvsmReqError::from)?;
Same here, the `?` operator will already use the `From` conversion, so this should just work: ```rust let value = cpu.read_apic_register(params.rcx)?; ```
svsm
github_2023
others
403
coconut-svsm
00xc
@@ -82,7 +80,7 @@ fn apic_write_register(params: &RequestParams) -> Result<(), SvsmReqError> { return Err(SvsmReqError::invalid_request()); } cpu.write_apic_register(params.rcx, params.rdx) - .map_err(|_| SvsmReqError::invalid_parameter()) + .map_err(SvsmReqError::from)
Same here
svsm
github_2023
others
403
coconut-svsm
00xc
@@ -75,6 +84,7 @@ impl From<SvsmError> for SvsmReqError { // to the guest as protocol-specific errors. SvsmError::SevSnp(e) => Self::protocol(e.ret()), SvsmError::InvalidAddress => Self::invalid_address(), + SvsmError::Apic(e) => Self::translate_apic_error(e),
Any reason we are implementing `translate_apic_error()` instead of just inlining the conversion? ```suggestion SvsmError::Apic(e) => match e { ApicError::Emulation => Self::invalid_parameter(), ApicError::Registration => Self::protocol(SVSM_ERR_APIC_CANNOT_REGISTER), } ``` We can also do: ```suggestion SvsmError::Apic(ApicError::Emulation) => Self::invalid_parameter(), SvsmError::Apic(ApicError::Registration) => { Self::protocol(SVSM_ERR_APIC_CANNOT_REGISTER) } ```
svsm
github_2023
others
331
coconut-svsm
00xc
@@ -602,6 +772,15 @@ impl PageTable { } } + /// Maps a region of memory using 4KB pages. + /// + /// # Parameters + /// - `vregion`: The virtual memory region to map. + /// - `phys`: The starting physical address to map to. + /// - `flags`: The flags to apply to the mapping. + /// + /// # Returns + /// A result indicating success or failure (`SvsmError`).
```suggestion /// A result indicating success or failure ([`SvsmError`]). ```
svsm
github_2023
others
331
coconut-svsm
00xc
@@ -576,6 +738,14 @@ impl PageTable { } } + /// Retrieves the physical address of a mapping. + /// + /// # Parameters + /// - `vaddr`: The virtual address to query. + /// + /// # Returns + /// The physical address of the mapping if present; otherwise, an error + /// (`SvsmError`).
```suggestion /// ([`SvsmError`]). ```
svsm
github_2023
others
331
coconut-svsm
00xc
@@ -615,12 +794,25 @@ impl PageTable { Ok(()) } + /// Unmaps a region of memory using 4KB pages. + /// + /// # Parameters + /// - `vregion`: The virtual memory region to unmap. pub fn unmap_region_4k(&mut self, vregion: MemoryRegion<VirtAddr>) { for addr in vregion.iter_pages(PageSize::Regular) { self.unmap_4k(addr); } } + /// Maps a region of memory using 2MB pages. + /// + /// # Parameters + /// - `vregion`: The virtual memory region to map. + /// - `phys`: The starting physical address to map to. + /// - `flags`: The flags to apply to the mapping. + /// + /// # Returns + /// A result indicating success or failure (`SvsmError`).
```suggestion /// A result indicating success or failure ([`SvsmError`]). ```
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -24,14 +24,26 @@ use core::{cmp, ptr}; extern crate alloc; use alloc::boxed::Box; +/// Number of entries in a page table (4KB/8B). const ENTRY_COUNT: usize = 512; + +/// Mask for private page table entry
```suggestion /// Mask for private page table entry. ```
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -24,14 +24,26 @@ use core::{cmp, ptr}; extern crate alloc; use alloc::boxed::Box; +/// Number of entries in a page table (4KB/8B). const ENTRY_COUNT: usize = 512; + +/// Mask for private page table entry static PRIVATE_PTE_MASK: ImmutAfterInitCell<usize> = ImmutAfterInitCell::new(0); + +/// Mask for shared page table entry
```suggestion /// Mask for shared page table entry. ```
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -120,14 +135,17 @@ pub fn max_phys_addr() -> PhysAddr { PhysAddr::from(*MAX_PHYS_ADDR) } +/// Returns the supported flags considering the feature mask. fn supported_flags(flags: PTEntryFlags) -> PTEntryFlags { flags & *FEATURE_MASK } +/// Set address as shared via mask
```suggestion /// Set address as shared via mask. ```
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -120,14 +135,17 @@ pub fn max_phys_addr() -> PhysAddr { PhysAddr::from(*MAX_PHYS_ADDR) } +/// Returns the supported flags considering the feature mask. fn supported_flags(flags: PTEntryFlags) -> PTEntryFlags { flags & *FEATURE_MASK } +/// Set address as shared via mask fn make_shared_address(paddr: PhysAddr) -> PhysAddr { PhysAddr::from(paddr.bits() & !private_pte_mask() | shared_pte_mask()) } +/// Set address as private via mask
```suggestion /// Set address as private via mask. ```
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -294,12 +354,21 @@ impl PageTable { Some(unsafe { &mut *address.as_mut_ptr::<PTPage>() }) } + /// Walks a page table at level 0 to find a mapping. + /// + /// # Parameters + /// - `page`: A mutable reference to the root page table. + /// - `vaddr`: The virtual address to find a mapping for. + /// + /// # Returns + /// A `Mapping` representing the found mapping. fn walk_addr_lvl0(page: &mut PTPage, vaddr: VirtAddr) -> Mapping<'_> { let idx = PageTable::index::<0>(vaddr); Mapping::Level0(&mut page[idx]) } + /// Walks a page table at level 1 to find a mapping.
We are documenting parameters and return values for `walk_addr_lvl0` and `walk_addr_lvl3`, so maybe we can do also for `walk_addr_lvl1` and `walk_addr_lvl2`
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -322,6 +392,14 @@ impl PageTable { }; } + /// Walks the page table to find a mapping for a given virtual address.
Should we mention "level 3"? I mean something like `Walks the page table at level 3 to find ...`
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -692,6 +896,8 @@ impl PageTable { } } + /// Populates this paghe table with the contents of the given.
```suggestion /// Populates this paghe table with the contents of the given ```
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -793,6 +1039,7 @@ impl RawPageTablePart { Some(unsafe { &mut *address.as_mut_ptr::<PTPage>() }) } + /// Frees a level 1 page table.
```suggestion /// Frees a level 1 page table. /// /// # Parameters /// - `page`: A reference to the level 1 page table to be freed. ```
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -920,6 +1232,16 @@ impl RawPageTablePart { } } + /// Unmaps a 2MB page. + /// + /// # Parameters + /// - `vaddr`: The virtual address of the mapping to unmap. + /// + /// # Returns + /// An optional [`PTEntry`] representing the unmapped page table entry. + /// # Panics + /// + /// Panics if `vaddr` is not memory aligned.
```suggestion /// An optional [`PTEntry`] representing the unmapped page table entry. /// /// # Panics /// Panics if `vaddr` is not memory aligned. ```
svsm
github_2023
others
331
coconut-svsm
stefano-garzarella
@@ -24,6 +25,24 @@ pub struct PerCPUPageMappingGuard { } impl PerCPUPageMappingGuard { + /// Creates a new [`PerCPUPageMappingGuard`] for the specified physical + /// address range and alignment. + /// + /// # Arguments + /// + /// * `paddr_start` - The starting physical address of the range. + /// * `paddr_end` - The ending physical address of the range. + /// * `alignment` - The desired alignment for the mapping. + /// + /// # Returns + /// + /// A `Result` containing the [`PerCPUPageMappingGuard`] if successful, + /// or an `SvsmError` if an error occurs. + /// + /// # Panics + /// + /// Panics if either `paddr_start`, the size, or `paddr_end`, are not + /// aligned
```suggestion /// aligned. ```
svsm
github_2023
others
398
coconut-svsm
vijaydhanraj
@@ -140,60 +133,52 @@ impl SvsmPlatform for SnpPlatform { return Err(SvsmError::NotSupported); } - self.use_alternate_injection = alt_inj_requested; + APIC_EMULATION_REG_COUNT.store(1, Ordering::Relaxed); Ok(()) } - fn use_alternate_injection(&self) -> bool { - self.use_alternate_injection - } - - fn lock_unlock_apic_emulation(&self, lock: bool) -> Result<(), SvsmError> { - // The lock state can only be changed if APIC emulation has not already - // been disabled on any CPU. - let new_state = if lock { - APIC_EMULATION_LOCKED - } else { - APIC_EMULATION_ENABLED - }; - let mut current = APIC_EMULATION_STATE.load(Ordering::Relaxed); + fn change_apic_registration_state(&self, incr: bool) -> Result<bool, SvsmError> {
Would it be better to rename `incr` to something like `register`? Agree that as part of `change_apic_registration_state()`, the `APIC_EMULATION_REG_COUNT` is either incremented or decremented, but this is an internal mechanism of how registration works. To the end user of this call, it is either register or deregister.
svsm
github_2023
others
398
coconut-svsm
vijaydhanraj
@@ -140,60 +133,52 @@ impl SvsmPlatform for SnpPlatform { return Err(SvsmError::NotSupported); } - self.use_alternate_injection = alt_inj_requested; + APIC_EMULATION_REG_COUNT.store(1, Ordering::Relaxed); Ok(()) } - fn use_alternate_injection(&self) -> bool { - self.use_alternate_injection - } - - fn lock_unlock_apic_emulation(&self, lock: bool) -> Result<(), SvsmError> { - // The lock state can only be changed if APIC emulation has not already - // been disabled on any CPU. - let new_state = if lock { - APIC_EMULATION_LOCKED - } else { - APIC_EMULATION_ENABLED - }; - let mut current = APIC_EMULATION_STATE.load(Ordering::Relaxed); + fn change_apic_registration_state(&self, incr: bool) -> Result<bool, SvsmError> { + let mut current = APIC_EMULATION_REG_COUNT.load(Ordering::Relaxed); loop { - if current == APIC_EMULATION_DISABLED { - return Err(SvsmError::Apic); - } - match APIC_EMULATION_STATE.compare_exchange_weak( + let new = if incr { + // Incrementing is only possible if the registration count + // has not already dropped to zero, and only if the + // registration count will not wrap around. + if current == 0 { + return Err(SvsmError::Apic); + } + match current.checked_add(1) { + None => { + return Err(SvsmError::Apic);
Spec explicitly calls out to return `SVSM_ERR_APIC_CANNOT_REGISTER` if the count is zero but here it looks like even for overflow, we may be returning the same error? Is this expected?
svsm
github_2023
others
398
coconut-svsm
vijaydhanraj
@@ -33,22 +28,40 @@ fn apic_query_features(params: &mut RequestParams) -> Result<(), SvsmReqError> { } fn apic_configure(params: &RequestParams) -> Result<(), SvsmReqError> { - match params.rcx { - SVSM_APIC_CONFIGURE_DISABLED => this_cpu() - .disable_apic_emulation() - .map_err(|_| SvsmReqError::protocol(SVSM_ERR_APIC_CANNOT_DISABLE)), - SVSM_APIC_CONFIGURE_ENABLED => { - // If this fails, the platform is known not to be in the locked - // state, so any error can be ignored in that case. - let _ = SVSM_PLATFORM.as_dyn_ref().lock_unlock_apic_emulation(false); - Ok(()) + let platform = SVSM_PLATFORM.as_dyn_ref(); + let enabled = match params.rcx { + 0b00 => { + // Query the current registration state of APIC emulation to + // determine whether it should be disabled on the current CPU. + platform.query_apic_registration_state() + } + + 0b01 => { + // Deregister APIC emulation if possible, noting whether it is now + // disabled for the platform. This cannot fail. + platform.change_apic_registration_state(false).unwrap() + } + + 0b10 => { + // Increment the APIC emulation registration count. If successful,
Similar to above case, can the comment be reworded to something like `Register APIC emulation if possible`?
svsm
github_2023
others
398
coconut-svsm
00xc
@@ -140,60 +133,52 @@ impl SvsmPlatform for SnpPlatform { return Err(SvsmError::NotSupported); } - self.use_alternate_injection = alt_inj_requested; + APIC_EMULATION_REG_COUNT.store(1, Ordering::Relaxed); Ok(()) } - fn use_alternate_injection(&self) -> bool { - self.use_alternate_injection - } - - fn lock_unlock_apic_emulation(&self, lock: bool) -> Result<(), SvsmError> { - // The lock state can only be changed if APIC emulation has not already - // been disabled on any CPU. - let new_state = if lock { - APIC_EMULATION_LOCKED - } else { - APIC_EMULATION_ENABLED - }; - let mut current = APIC_EMULATION_STATE.load(Ordering::Relaxed); + fn change_apic_registration_state(&self, incr: bool) -> Result<bool, SvsmError> { + let mut current = APIC_EMULATION_REG_COUNT.load(Ordering::Relaxed); loop { - if current == APIC_EMULATION_DISABLED { - return Err(SvsmError::Apic); - } - match APIC_EMULATION_STATE.compare_exchange_weak( + let new = if incr { + // Incrementing is only possible if the registration count + // has not already dropped to zero, and only if the + // registration count will not wrap around. + if current == 0 { + return Err(SvsmError::Apic); + } + match current.checked_add(1) { + None => { + return Err(SvsmError::Apic); + } + Some(v) => v, + }
Just as a suggestion: ```suggestion current.checked_add(1).ok_or(SvsmError::Apic)? ```
svsm
github_2023
others
309
coconut-svsm
p4zuu
@@ -58,27 +133,11 @@ where /// A view of an x86 instruction. #[derive(Default, Debug, Copy, Clone, PartialEq)] -pub struct Instruction { - /// Optional x86 instruction prefixes. - pub prefixes: Option<InsnBuffer<MAX_INSN_FIELD_SIZE>>, - /// Raw bytes copied from rip location. - /// After decoding, `self.insn_bytes.nb_bytes` is adjusted - /// to the total len of the instruction, prefix included. - pub insn_bytes: InsnBuffer<MAX_INSN_SIZE>, - /// Mandatory opcode. - pub opcode: InsnBuffer<MAX_INSN_FIELD_SIZE>, - /// Operand size in bytes. - pub opnd_bytes: usize, -} +pub struct Instruction(InsnBuffer<MAX_INSN_SIZE>);
I think we can continue cleaning this a bit. for example, `self.0.nb_bytes` doesn't seem to be used anymore. It was introduced to get the effective bytes to take in an InsnBuffer (~ the length), but now that we `DecodedInsn::size()` I think we can get rid of it, and maybe of `InsnBuffer` in general. `Instruction::len()` and `Instruction::is_empty()` are also now quite useless.
svsm
github_2023
others
309
coconut-svsm
p4zuu
@@ -114,44 +119,79 @@ pub fn stage2_handle_vc_exception(ctx: &mut X86ExceptionContext) -> Result<(), S pub fn handle_vc_exception(ctx: &mut X86ExceptionContext) -> Result<(), SvsmError> { let error_code = ctx.error_code; - /* - * To handle NAE events, we're supposed to reset the VALID_BITMAP field of the GHCB. - * This is currently only relevant for IOIO handling. This field is currently reset in - * the ioio_{in,ou} methods but it would be better to move the reset out of the different - * handlers. - */ + // To handle NAE events, we're supposed to reset the VALID_BITMAP field of the GHCB. + // This is currently only relevant for IOIO handling. This field is currently reset in + // the ioio_{in,ou} methods but it would be better to move the reset out of the different + // handlers. let mut ghcb = current_ghcb(); let insn = vc_decode_insn(ctx)?; - match error_code { + match (error_code, insn) { // If the gdb stub is enabled then debugging operations such as single stepping // will cause either an exception via DB_VECTOR if the DEBUG_SWAP sev_feature is // clear, or a VC exception with an error code of X86_TRAP if set. - X86_TRAP => { + (X86_TRAP, _) => { handle_debug_exception(ctx, ctx.vector); Ok(()) } - SVM_EXIT_CPUID => handle_cpuid(ctx), - SVM_EXIT_IOIO => handle_ioio(ctx, &mut ghcb, &insn), + (SVM_EXIT_CPUID, Some(DecodedInsn::Cpuid)) => handle_cpuid(ctx), + (SVM_EXIT_IOIO, Some(ins)) => handle_ioio(ctx, &mut ghcb, ins), + (SVM_EXIT_MSR, Some(ins)) => handle_msr(ctx, &mut ghcb, ins), _ => Err(VcError::new(ctx, VcErrorType::Unsupported).into()), }?; vc_finish_insn(ctx, &insn); Ok(()) } -fn handle_cpuid(ctx: &mut X86ExceptionContext) -> Result<(), SvsmError> { - /* - * Section 2.3.1 GHCB MSR Protocol in SEV-ES Guest-Hypervisor Communication Block - * Standardization Rev. 2.02. - * For SEV-ES/SEV-SNP, we can use the CPUID table already defined and populated with - * firmware information. - * We choose for now not to call the hypervisor to perform CPUID, since it's no trusted. - * Since GHCB is not needed to handle CPUID with the firmware table, we can call the handler - * very soon in stage 2. - */ +#[inline] +const fn get_msr(regs: &X86GeneralRegs) -> u64 { + ((regs.rdx as u64) << 32) | regs.rax as u64 & 0xffffffff
Maybe we can use `u32::MAX` here
svsm
github_2023
others
309
coconut-svsm
p4zuu
@@ -175,55 +215,72 @@ fn snp_cpuid(ctx: &mut X86ExceptionContext) -> Result<(), SvsmError> { Ok(()) } -fn vc_finish_insn(ctx: &mut X86ExceptionContext, insn: &Instruction) { - ctx.frame.rip += insn.len() +fn vc_finish_insn(ctx: &mut X86ExceptionContext, insn: &Option<DecodedInsn>) { + ctx.frame.rip += insn.as_ref().map(DecodedInsn::size).unwrap_or(0); +} + +fn ioio_get_port(source: Operand, ctx: &X86ExceptionContext) -> u16 { + match source { + Operand::Reg(Register::Rdx) => (ctx.regs.rdx & 0xffff) as u16,
Same comment with `u16::MAX`
svsm
github_2023
others
327
coconut-svsm
p4zuu
@@ -70,6 +52,27 @@ const PSC_FLAG_HUGE: u64 = 1 << PSC_FLAG_HUGE_SHIFT; const GHCB_BUFFER_SIZE: usize = 0x7f0; +macro_rules! ghcb_getter { + ($name:ident, $field:ident,$t:ty) => { + #[allow(unused)] + fn $name(&self) -> Result<$t, GhcbError> { + self.is_valid(offset_of!(Self, $field))
Do we always need to check if the related bit in `VALID_BITMAP` is set? Without asking right now for other getters and setters that don't check the valid bit, I like the Linux kernel naming `get_##field##` and `get_##field##_if_valid`. When reading a call to one of the new `ghcb_getter` here, I would find it slightly clearer to have `if_valid` suffix at the end of the method
svsm
github_2023
others
327
coconut-svsm
p4zuu
@@ -250,91 +298,26 @@ impl GHCB { exit_info_2: u64, ) -> Result<(), GhcbError> { // GHCB is version 2 - self.version = 2; - self.set_valid(OFF_VERSION); - + self.set_version(2); // GHCB Follows standard format - self.usage = 0; - self.set_valid(OFF_USAGE); - - self.sw_exit_code = exit_code; - self.set_valid(OFF_SW_EXIT_CODE); - - self.sw_exit_info_1 = exit_info_1; - self.set_valid(OFF_SW_EXIT_INFO_1); - - self.sw_exit_info_2 = exit_info_2; - self.set_valid(OFF_SW_EXIT_INFO_2); + self.set_usage(0); + self.set_exit_code(exit_code); + self.set_exit_info_1(exit_info_1); + self.set_exit_info_2(exit_info_2); let ghcb_address = VirtAddr::from(self as *const GHCB); let ghcb_pa = u64::from(virt_to_phys(ghcb_address)); write_msr(SEV_GHCB, ghcb_pa); raw_vmgexit(); - if !self.is_valid(OFF_SW_EXIT_INFO_1) { - return Err(GhcbError::VmgexitInvalid); - } - - if self.sw_exit_info_1 != 0 { - return Err(GhcbError::VmgexitError( - self.sw_exit_info_1, - self.sw_exit_info_2, - )); + let sw_exit_info_1 = self.get_exit_info_1()?;
Just an example of my comment about `ghcb_getter`s, I would find this clearer to have `self.get_exit_info_1_if_valid()?`, but it's maybe nitpicking :)
svsm
github_2023
others
327
coconut-svsm
p4zuu
@@ -97,9 +99,10 @@ pub fn stage2_handle_vc_exception_no_ghcb(ctx: &mut X86ExceptionContext) -> Resu pub fn stage2_handle_vc_exception(ctx: &mut X86ExceptionContext) -> Result<(), SvsmError> { let err = ctx.error_code; - // To handle NAE events, we're supposed to reset the VALID_BITMAP field of the GHCB. - // This is currently only relevant for IOIO handling. This field is currently reset in - // the ioio_{in,ou} methods but it would be better to move the reset out of the different + // To handle NAE events, we're supposed to reset the VALID_BITMAP field of
Would it be a better to call `ghcb.clear()` here now? I mean in the `*handle_vc_exception()` functions. That would factorize the `self.clear()` calls in the GHCB handlers (eg. in the new `rdtsc_regs()` and `rdtsc_regs()`). I don't really know which solution is better
svsm
github_2023
others
389
coconut-svsm
joergroedel
@@ -8,15 +8,15 @@ use super::gdt::GDTEntry; use crate::address::VirtAddr; // IST offsets -pub const _IST_INVALID: usize = 0; -pub const IST_DF: usize = 1; +pub const IST_DF: usize = 0;
Even if this is `0` now it still means that it needs to be referenced from the IDT by index `1`. I suggest to leave the `IST_DF` index as is and add a method to `struct X86TSS` do correctly set the indices (allowed values are `0-7`)
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -272,7 +272,11 @@ fn vc_decode_insn(ctx: &X86ExceptionContext) -> Result<Option<DecodedInsnCtx>, S // rip and rip+15 addresses should belong to a mapped page. // To ensure this, we rely on GuestPtr::read() that uses the exception table // to handle faults while fetching. - let insn_raw = rip.read()?; + // SAFETY: rip can be any mapped address, including userpace. It's technically + // not possible for a user to raise a #VC from a different context (different + // user or kernelspace), so rip can't belong to a different user or kernel + // memory.
This is a very convoluted explanation. I would just say: we trust the CPU-provided register state to be valid. Thus, RIP will point to the instruction that caused `#VC` to be raised, so it can safely be read. I think the worst case scenario is that somehow another CPU might unmap the code page where the instruction resides, causing the read to fail. Anyhow, that is not undefined behavior so it is safe.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -394,13 +394,20 @@ pub mod svsm_gdbstub { // mapping let Ok(phys) = this_cpu().get_pgtable().phys_addr(addr) else { - // The virtual address is not one that SVSM has mapped. Try safely - // writing it to the original virtual address - return write_u8(addr, value); + // SAFETY: The virtual address is not one that SVSM has mapped. + // Try safely writing it to the original virtual address + return unsafe { write_u8(addr, value) };
This does not explain why it is safe. This should say something like: it is up to the user to ensure that the address we are writing a breakpoint to is valid.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -532,9 +539,12 @@ pub mod svsm_gdbstub { ) -> gdbstub::target::TargetResult<(), Self> { let start_addr = VirtAddr::from(start_addr); for (off, src) in data.iter().enumerate() { - if write_u8(start_addr + off, *src).is_err() { - return Err(TargetError::NonFatal); - } + let dst = start_addr.checked_add(off).ok_or(TargetError::NonFatal)?; + + // SAFETY: we only cheked that start_adddr + off didn't overflow + // The validity (ie. attacker controlability) relies on write_addrs + // caller. + unsafe { write_u8(dst, *src).map_err(|_| TargetError::NonFatal)? }
I'm having trouble understanding this one. Also, what do we mean by "attacker" here?
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -196,29 +196,35 @@ impl IgvmParams<'_> { return Err(SvsmError::Firmware); } - mem_map - .offset(i as isize) - .write(IGVM_VHS_MEMORY_MAP_ENTRY { + mem_map.offset(i as isize); + // SAFETY: mem_map_va points to a new mapped memory, whose address + // is defined in the config.
```suggestion // SAFETY: mem_map_va points to newly mapped memory, whose physical // address is defined in the IGVM config. ```
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -196,29 +196,35 @@ impl IgvmParams<'_> { return Err(SvsmError::Firmware); } - mem_map - .offset(i as isize) - .write(IGVM_VHS_MEMORY_MAP_ENTRY { + mem_map.offset(i as isize); + // SAFETY: mem_map_va points to a new mapped memory, whose address + // is defined in the config. + unsafe { + mem_map.write(IGVM_VHS_MEMORY_MAP_ENTRY { starting_gpa_page_number: u64::from(entry.start()) / PAGE_SIZE as u64, number_of_pages: entry.len() as u64 / PAGE_SIZE as u64, entry_type: MemoryMapEntryType::default(), flags: 0, reserved: 0, })?; + } } // Write a zero page count into the last entry to terminate the list. let index = map.len(); if index < max_entries { - mem_map - .offset(index as isize) - .write(IGVM_VHS_MEMORY_MAP_ENTRY { + mem_map.offset(index as isize); + // SAFETY: mem_map_va points to a new mapped memory, whose address + // is defined in the config.
Same as the previous one.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -39,9 +39,21 @@ pub fn read_u8(v: VirtAddr) -> Result<u8, SvsmError> { } } +/// Writes 1 byte at a virtual address. +/// +/// # Safety +/// +/// The caller should verify that the write address (`v`) is valid for write: +/// - `v` should belong to a mapped memory region +/// - `v` should only belong to the issuer's memory space (a guest should not be +/// able to write in the SVSM kernel's memory, or a different guest's +/// memory).
* `v` does not need to be a mapped address for this function to be safe. In fact, that is what this function guarantees: that accessing unmapped memory will simply return an error instead of causing an unexpected #PF or #GP. * `v` does not need to belong to the issuer's address space. In fact we can use this to write to guest memory from the SVSM kernel IIUC. I'd reword that point to say that the caller needs to take care not to corrupt arbitrary memory, as this function won't make any checks in that regard.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -39,9 +39,21 @@ pub fn read_u8(v: VirtAddr) -> Result<u8, SvsmError> { } } +/// Writes 1 byte at a virtual address. +/// +/// # Safety +/// +/// The caller should verify that the write address (`v`) is valid for write: +/// - `v` should belong to a mapped memory region +/// - `v` should only belong to the issuer's memory space (a guest should not be +/// able to write in the SVSM kernel's memory, or a different guest's +/// memory). +/// +/// This function returns an error if it tries to write to an unmapped address, +/// and that the #PF or #GP handler returns an error.
This sentence does not make much sense I think, and also talks about exceptions, which are an implementation detail the caller does not need to know about. I'd simply say: ```suggestion /// # Returns /// /// Returns an error if the specified address is not mapped or is not mapped /// with the appropriate write permissions. ```
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -189,8 +201,19 @@ impl<T: Copy> GuestPtr<T> { Self { ptr: p } } + /// # Safety + /// + /// The caller should verify that the read address (`self.ptr`) is valid + /// for read: + /// - it should belong to a mapped memory region + /// - it should only belong to the issuer's memory space (a guest should not be + /// able to read in the SVSM kernel's memory, or a different guest's + /// memory). + /// + /// This function returns an error if it tries to read to an unmapped address, + /// and that the #PF or #GP handler returns an error.
Same as with `write_u8`
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -199,13 +222,35 @@ impl<T: Copy> GuestPtr<T> { } } + /// # Safety + /// + /// The caller should verify that the write address (`self.ptr`) is valid + /// for write: + /// - it should belong to a mapped memory region + /// - it should only belong to the issuer's memory space (a guest should not be + /// able to write in the SVSM kernel's memory, or a different guest's + /// memory). + /// + /// This function returns an error if it tries to write to an unmapped address, + /// and that the #PF or #GP handler returns an error.
Same as with `write_u8`
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -199,13 +222,35 @@ impl<T: Copy> GuestPtr<T> { } } + /// # Safety + /// + /// The caller should verify that the write address (`self.ptr`) is valid + /// for write: + /// - it should belong to a mapped memory region + /// - it should only belong to the issuer's memory space (a guest should not be + /// able to write in the SVSM kernel's memory, or a different guest's + /// memory). + /// + /// This function returns an error if it tries to write to an unmapped address, + /// and that the #PF or #GP handler returns an error. #[inline] - pub fn write(&self, buf: T) -> Result<(), SvsmError> { + pub unsafe fn write(&self, buf: T) -> Result<(), SvsmError> { unsafe { do_movsb(&buf, self.ptr) } } + /// # Safety + /// + /// The caller should verify that the write address (`self.ptr`) is valid + /// for write: + /// - it should belong to a mapped memory region + /// - it should only belong to the issuer's memory space (a guest should not be + /// able to write in the SVSM kernel's memory, or a different guest's + /// memory). + /// + /// This function returns an error if it tries to write to an unmapped address, + /// and that the #PF or #GP handler returns an error.
Same as with `write_u8`
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -244,7 +289,10 @@ mod tests { let test_address = VirtAddr::from(test_buffer.as_mut_ptr()); let data_to_write = 0x42; - write_u8(test_address, data_to_write).unwrap(); + // SAFETY: it's a test. + unsafe { + write_u8(test_address, data_to_write).unwrap(); + }
We don't want tests corrupting memory, so I'd give an actual explanation.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -255,7 +303,8 @@ mod tests { let test_buffer = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; let test_addr = VirtAddr::from(test_buffer.as_ptr()); let ptr: GuestPtr<[u8; 15]> = GuestPtr::new(test_addr); - let result = ptr.read().unwrap(); + // SAFETY: this is a test + let result = unsafe { ptr.read().unwrap() };
Same here, we need an explanation.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -265,8 +314,8 @@ mod tests { #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] fn test_read_invalid_address() { let ptr: GuestPtr<u8> = GuestPtr::new(VirtAddr::new(0xDEAD_BEEF)); - - let err = ptr.read(); + //SAFETY: this is a test + let err = unsafe { ptr.read() };
Same here, we need an explanation.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -57,15 +57,35 @@ impl SecretsPage { } } - pub fn copy_from(&mut self, source: VirtAddr) { + /// Copy secrets page's content pointed by a [`VirtAddr`] + /// + /// # Safety + /// + /// The caller should verify that both `self` and `source`: + /// * are memory-mapped + /// * have been allocated with the size of [`SecretsPage`] structure. + /// + /// The coller should also verify that `self` doesn't point to an + /// attacker-controllable address.
The caller here is not responsible for verifying `self`. We are under the assumption that we are working with a valid type, since `&mut self` is a safe Rust reference. Otherwise every method call that takes `&self` or `&mut self` should be unsafe for that exact same reason.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -57,15 +57,35 @@ impl SecretsPage { } } - pub fn copy_from(&mut self, source: VirtAddr) { + /// Copy secrets page's content pointed by a [`VirtAddr`] + /// + /// # Safety + /// + /// The caller should verify that both `self` and `source`: + /// * are memory-mapped + /// * have been allocated with the size of [`SecretsPage`] structure. + /// + /// The coller should also verify that `self` doesn't point to an + /// attacker-controllable address. + pub unsafe fn copy_from(&mut self, source: VirtAddr) { let from = source.as_ptr::<SecretsPage>(); unsafe { *self = *from; } } - pub fn copy_to(&self, target: VirtAddr) { + /// Copy a secrets page's content to memory pointed by a [`VirtAddr`] + /// + /// # Safety + /// + /// The caller should verify that both `self` and `target`: + /// * are memory-mapped + /// * have been allocated with the size of [`SecretsPage`] structure. + /// + /// The coller should also verify that `target` doesn't point to an + /// attacker-controllable address. + pub unsafe fn copy_to(&self, target: VirtAddr) {
Same here `&self` can be assumed to be valid.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -138,7 +138,11 @@ fn copy_secrets_page_to_fw(fw_addr: PhysAddr, caa_addr: PhysAddr) -> Result<(), u64::from(caa_addr), ); - fw_secrets_page.copy_to(start); + // SAFETY: start points to a new allocated and zeroed page. + // fw_secrets_page is a static memory region. + unsafe { + fw_secrets_page.copy_to(start); + }
This should be updated regarding my comment above about `&self`.
svsm
github_2023
others
382
coconut-svsm
00xc
@@ -189,8 +200,17 @@ impl<T: Copy> GuestPtr<T> { Self { ptr: p } } + /// # Safety + /// + /// The caller must verify not to read arbitrary memory, as this function + /// doesn't make any checks in that regard. + /// + /// # Returns + /// + /// Returns an error if the specified address is not mapped or is not mapped + /// with the appropriate read permissions.
On x86 there is no way to restrict read permissions on a page, so I think we cannot get `#GP`.
svsm
github_2023
others
386
coconut-svsm
00xc
@@ -700,66 +682,72 @@ impl PerCpu { } pub fn disable_apic_emulation(&self) -> Result<(), SvsmError> { - if self.apic_emulation.get() { + if self.apic.borrow().is_some() { // APIC emulation cannot be disabled if the platform has locked // the use of APIC emulation. SVSM_PLATFORM.as_dyn_ref().disable_apic_emulation()?; let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .disable_apic_emulation(vmsa, caa_addr); + let mut apic = self.apic.borrow_mut().take().unwrap(); + apic.disable_apic_emulation(vmsa, caa_addr); drop(vmsa_ref); - - self.apic_emulation.set(false); } Ok(()) } pub fn clear_pending_interrupts(&self) { - if self.apic_emulation.get() { + if let Some(apic) = self.apic.borrow_mut().deref_mut() { let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .check_delivered_interrupts(vmsa, caa_addr); + apic.check_delivered_interrupts(vmsa, caa_addr); } } pub fn update_apic_emulation(&self, vmsa: &mut VMSA, caa_addr: Option<VirtAddr>) { - if self.apic_emulation.get() { - self.apic - .borrow_mut() - .present_interrupts(self.shared(), vmsa, caa_addr); + if let Some(apic) = self.apic.borrow_mut().deref_mut() { + apic.present_interrupts(self.shared(), vmsa, caa_addr); } } pub fn use_apic_emulation(&self) -> bool { - self.apic_emulation.get() + self.apic.borrow().is_some() } - pub fn read_apic_register(&self, register: u64) -> Result<u64, ApicError> { - let mut vmsa_ref = self.guest_vmsa_ref(); - let caa_addr = vmsa_ref.caa_addr(); - let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .read_register(self.shared(), vmsa, caa_addr, register) + pub fn read_apic_register(&self, register: u64) -> Option<Result<u64, ApicError>> { + if let Some(apic) = self.apic.borrow_mut().deref_mut() { + let mut vmsa_ref = self.guest_vmsa_ref(); + let caa_addr = vmsa_ref.caa_addr(); + let vmsa = vmsa_ref.vmsa(); + Some(apic.read_register(self.shared(), vmsa, caa_addr, register)) + } else { + None + }
```suggestion let apic = self.apic.borrow_mut().deref_mut()?; let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); Some(apic.read_register(self.shared(), vmsa, caa_addr, register)) ```
svsm
github_2023
others
386
coconut-svsm
00xc
@@ -700,66 +682,72 @@ impl PerCpu { } pub fn disable_apic_emulation(&self) -> Result<(), SvsmError> { - if self.apic_emulation.get() { + if self.apic.borrow().is_some() { // APIC emulation cannot be disabled if the platform has locked // the use of APIC emulation. SVSM_PLATFORM.as_dyn_ref().disable_apic_emulation()?; let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .disable_apic_emulation(vmsa, caa_addr); + let mut apic = self.apic.borrow_mut().take().unwrap(); + apic.disable_apic_emulation(vmsa, caa_addr); drop(vmsa_ref); - - self.apic_emulation.set(false); } Ok(()) } pub fn clear_pending_interrupts(&self) { - if self.apic_emulation.get() { + if let Some(apic) = self.apic.borrow_mut().deref_mut() { let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .check_delivered_interrupts(vmsa, caa_addr); + apic.check_delivered_interrupts(vmsa, caa_addr); } } pub fn update_apic_emulation(&self, vmsa: &mut VMSA, caa_addr: Option<VirtAddr>) { - if self.apic_emulation.get() { - self.apic - .borrow_mut() - .present_interrupts(self.shared(), vmsa, caa_addr); + if let Some(apic) = self.apic.borrow_mut().deref_mut() { + apic.present_interrupts(self.shared(), vmsa, caa_addr); } } pub fn use_apic_emulation(&self) -> bool { - self.apic_emulation.get() + self.apic.borrow().is_some() } - pub fn read_apic_register(&self, register: u64) -> Result<u64, ApicError> { - let mut vmsa_ref = self.guest_vmsa_ref(); - let caa_addr = vmsa_ref.caa_addr(); - let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .read_register(self.shared(), vmsa, caa_addr, register) + pub fn read_apic_register(&self, register: u64) -> Option<Result<u64, ApicError>> { + if let Some(apic) = self.apic.borrow_mut().deref_mut() { + let mut vmsa_ref = self.guest_vmsa_ref(); + let caa_addr = vmsa_ref.caa_addr(); + let vmsa = vmsa_ref.vmsa(); + Some(apic.read_register(self.shared(), vmsa, caa_addr, register)) + } else { + None + } } - pub fn write_apic_register(&self, register: u64, value: u64) -> Result<(), ApicError> { - let mut vmsa_ref = self.guest_vmsa_ref(); - let caa_addr = vmsa_ref.caa_addr(); - let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .write_register(vmsa, caa_addr, register, value) + pub fn write_apic_register(&self, register: u64, value: u64) -> Option<Result<(), ApicError>> { + if let Some(apic) = self.apic.borrow_mut().deref_mut() {
Same thing here, let's use `?`
svsm
github_2023
others
386
coconut-svsm
00xc
@@ -700,66 +682,72 @@ impl PerCpu { } pub fn disable_apic_emulation(&self) -> Result<(), SvsmError> { - if self.apic_emulation.get() { + if self.apic.borrow().is_some() { // APIC emulation cannot be disabled if the platform has locked // the use of APIC emulation. SVSM_PLATFORM.as_dyn_ref().disable_apic_emulation()?; let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .disable_apic_emulation(vmsa, caa_addr); + let mut apic = self.apic.borrow_mut().take().unwrap(); + apic.disable_apic_emulation(vmsa, caa_addr); drop(vmsa_ref); - - self.apic_emulation.set(false); } Ok(()) } pub fn clear_pending_interrupts(&self) { - if self.apic_emulation.get() { + if let Some(apic) = self.apic.borrow_mut().deref_mut() { let mut vmsa_ref = self.guest_vmsa_ref(); let caa_addr = vmsa_ref.caa_addr(); let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .check_delivered_interrupts(vmsa, caa_addr); + apic.check_delivered_interrupts(vmsa, caa_addr); } } pub fn update_apic_emulation(&self, vmsa: &mut VMSA, caa_addr: Option<VirtAddr>) { - if self.apic_emulation.get() { - self.apic - .borrow_mut() - .present_interrupts(self.shared(), vmsa, caa_addr); + if let Some(apic) = self.apic.borrow_mut().deref_mut() { + apic.present_interrupts(self.shared(), vmsa, caa_addr); } } pub fn use_apic_emulation(&self) -> bool { - self.apic_emulation.get() + self.apic.borrow().is_some() } - pub fn read_apic_register(&self, register: u64) -> Result<u64, ApicError> { - let mut vmsa_ref = self.guest_vmsa_ref(); - let caa_addr = vmsa_ref.caa_addr(); - let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .read_register(self.shared(), vmsa, caa_addr, register) + pub fn read_apic_register(&self, register: u64) -> Option<Result<u64, ApicError>> { + if let Some(apic) = self.apic.borrow_mut().deref_mut() { + let mut vmsa_ref = self.guest_vmsa_ref(); + let caa_addr = vmsa_ref.caa_addr(); + let vmsa = vmsa_ref.vmsa(); + Some(apic.read_register(self.shared(), vmsa, caa_addr, register)) + } else { + None + } } - pub fn write_apic_register(&self, register: u64, value: u64) -> Result<(), ApicError> { - let mut vmsa_ref = self.guest_vmsa_ref(); - let caa_addr = vmsa_ref.caa_addr(); - let vmsa = vmsa_ref.vmsa(); - self.apic - .borrow_mut() - .write_register(vmsa, caa_addr, register, value) + pub fn write_apic_register(&self, register: u64, value: u64) -> Option<Result<(), ApicError>> { + if let Some(apic) = self.apic.borrow_mut().deref_mut() { + let mut vmsa_ref = self.guest_vmsa_ref(); + let caa_addr = vmsa_ref.caa_addr(); + let vmsa = vmsa_ref.vmsa(); + Some(apic.write_register(vmsa, caa_addr, register, value)) + } else { + None + } } - pub fn configure_apic_vector(&self, vector: u8, allowed: bool) { - self.apic.borrow_mut().configure_vector(vector, allowed) + pub fn configure_apic_vector( + &self, + vector: u8, + allowed: bool, + ) -> Option<Result<(), SvsmError>> { + if let Some(apic) = self.apic.borrow_mut().deref_mut() {
Same thing here, let's use `?`
svsm
github_2023
others
386
coconut-svsm
stefano-garzarella
@@ -755,11 +749,12 @@ impl PerCpu { let vmsa = vmsa_ref.vmsa(); self.apic .borrow_mut() + .unwrap()
This can panic here now, should we return an error instead?
svsm
github_2023
others
386
coconut-svsm
stefano-garzarella
@@ -755,11 +749,12 @@ impl PerCpu { let vmsa = vmsa_ref.vmsa(); self.apic .borrow_mut() + .unwrap() .write_register(vmsa, caa_addr, register, value) } pub fn configure_apic_vector(&self, vector: u8, allowed: bool) { - self.apic.borrow_mut().configure_vector(vector, allowed) + self.apic.borrow_mut().unwrap().configure_vector(vector, allowed)
Ditto. IIUC previous implementation allowed this call if apic was enabled or not, not sure if it was right, but at least wasn't panicking. So not sure if now is better to ignore it or add a return error.
svsm
github_2023
others
386
coconut-svsm
stefano-garzarella
@@ -53,37 +53,38 @@ fn apic_configure(params: &RequestParams) -> Result<(), SvsmReqError> { fn apic_read_register(params: &mut RequestParams) -> Result<(), SvsmReqError> { let cpu = this_cpu(); - if !cpu.use_apic_emulation() { - return Err(SvsmReqError::invalid_request()); + match cpu.read_apic_register(params.rcx) { + None => Err(SvsmReqError::invalid_request()), + Some(r) => { + params.rdx = r.map_err(|_| SvsmReqError::invalid_parameter())?; + Ok(()) + } } - let value = cpu - .read_apic_register(params.rcx) - .map_err(|_| SvsmReqError::invalid_parameter())?; - params.rdx = value; - Ok(()) } fn apic_write_register(params: &RequestParams) -> Result<(), SvsmReqError> { let cpu = this_cpu(); - if !cpu.use_apic_emulation() { - return Err(SvsmReqError::invalid_request()); + match cpu.write_apic_register(params.rcx, params.rdx) { + None => Err(SvsmReqError::invalid_request()), + Some(r) => r.map_err(|_| SvsmReqError::invalid_parameter()), } - cpu.write_apic_register(params.rcx, params.rdx) - .map_err(|_| SvsmReqError::invalid_parameter()) } fn apic_configure_vector(params: &RequestParams) -> Result<(), SvsmReqError> { let cpu = this_cpu(); - if !cpu.use_apic_emulation() { - return Err(SvsmReqError::invalid_request()); - } + if params.rcx <= 0x1FF { let vector: u8 = (params.rcx & 0xFF) as u8; let allowed = (params.rcx & 0x100) != 0; - cpu.configure_apic_vector(vector, allowed); - Ok(()) + match cpu.configure_apic_vector(vector, allowed) {
What about returning these errors directly in `configure_apic_vector()` so we don't need to return the `Option`?
svsm
github_2023
others
386
coconut-svsm
stefano-garzarella
@@ -382,22 +384,24 @@ impl LocalApic { pub fn perform_eoi(&mut self) { // Pop any in-service interrupt from the stack, and schedule the APIC
What about moving this comment after the early return?
svsm
github_2023
others
386
coconut-svsm
00xc
@@ -102,7 +102,10 @@ pub enum ApicError { ApicError, } -#[derive(Default, Clone, Copy, Debug)] +// This structure must never be copied because a silent copy will cause APIC +// +// state to be lost.
Seems something went wrong with formatting here