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
120
coconut-svsm
joergroedel
@@ -0,0 +1,33 @@ +use log::info; +use test::ShouldPanic; + +use crate::sev::msr_protocol::request_termination_msr; + +pub fn svsm_test_runner(test_cases: &[&test::TestDescAndFn]) { + info!("running {} tests", test_cases.len()); + for mut test_case in test_cases.iter().copied().copied() { + if test_case.desc.should_panic == ShouldPanic::Yes { + test_case.desc.ignore = true; + test_case + .desc + .ignore_message + .get_or_insert("#[should_panic] not supported"); + } + + if test_case.desc.ignore { + if let Some(message) = test_case.desc.ignore_message { + info!("test {} ... ignored, {message}", test_case.desc.name.0); + } else { + info!("test {} ... ignored", test_case.desc.name.0); + } + continue; + } + + info!("test {} ...", test_case.desc.name.0); + (test_case.testfn.0)(); + } + + info!("All tests passed!"); + + request_termination_msr();
I wonder if we can use the qemu exit device here?
svsm
github_2023
others
113
coconut-svsm
joergroedel
@@ -0,0 +1,79 @@ +FUZZING +======= + +The COCONUT SVSM includes several fuzzing harnesses to find bugs in +security-critical interfaces. These do not currently provide coverage +of all interesting interfaces, so contributions are welcome. + +At the moment, fuzzing is done through +[cargo-fuzz](/rust-fuzz/cargo-fuzz). You may find a complete tutorial +for this tool on the +[rust-fuzz website](https://rust-fuzz.github.io/book/cargo-fuzz.html).
Can you please add a section describing the dependencies and how install them on openSUSE? For me it was `cargo-fuzz`, `clang` and `lld`.
svsm
github_2023
others
113
coconut-svsm
joergroedel
@@ -125,6 +125,10 @@ impl ACPITable { let content = ptr.get(..size).ok_or(SvsmError::Acpi)?; let mut buf = Vec::<u8>::new(); + #[cfg(fuzzing)] + if size > 0x1000 { + return Err(SvsmError::Mem); + }
Why is that needed?
svsm
github_2023
others
113
coconut-svsm
joergroedel
@@ -176,6 +180,10 @@ impl ACPITableBuffer { let size = file.size() as usize; let mut buf = Vec::<u8>::new(); + #[cfg(fuzzing)] + if size > 0x1000 { + return Err(SvsmError::Mem); + }
Same here, why is that needed?
svsm
github_2023
others
113
coconut-svsm
joergroedel
@@ -286,9 +294,10 @@ pub fn load_acpi_cpu_info(fw_cfg: &FwCfg) -> Result<Vec<ACPICPUInfo>, SvsmError> .content_ptr::<RawMADTEntryHeader>(offset) .ok_or(SvsmError::Acpi)?; let (madt_type, entry_len) = unsafe { ((*entry_ptr).entry_type, (*entry_ptr).entry_len) }; + let entry_len = usize::from(entry_len); match madt_type { - 0 => { + 0 if entry_len == mem::size_of::<RawMADTEntryLocalApic>() => {
This looks like a fix for an issue found by fuzzing. Can you please submit all such fixes in a separate PR, please? We can merge them independently of the fuzzer itself.
svsm
github_2023
others
113
coconut-svsm
joergroedel
@@ -124,6 +126,11 @@ impl<'a> FwCfg<'a> { self.select(FW_CFG_FILE_DIR); let n: u32 = self.read_be(); + #[cfg(fuzzing)] + if n > 0x1000 { + return Err(SvsmError::FwCfg(FwCfgError::TooManyFiles)); + } +
This does not need to be limited to fuzzing. I think we can safely assume a maximum supported buffer size for the fw_cfg file-list.
svsm
github_2023
others
113
coconut-svsm
Freax13
@@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Carlos López <carlos.lopez@suse.com> + +#![no_main] + +use arbitrary::Arbitrary; +use core::hint::black_box; +use libfuzzer_sys::fuzz_target; +use std::rc::Rc; +use std::sync::OnceLock; +use svsm::fs::FileHandle; +use svsm::fs::{create, create_all, initialize_fs, list_dir, mkdir, open, uninitialize_fs, unlink}; +use svsm::mm::alloc::TestRootMem; + +const ROOT_MEM_SIZE: usize = 0x10000; +const MAX_READ_SIZE: usize = 4096 * 8; +const MAX_WRITE_SIZE: usize = 4096 * 8; +const WRITE_BYTE: u8 = 0x0; +const POISON_BYTE: u8 = 0xaf; + +#[derive(Arbitrary, Debug)] +enum FsAction<'a> { + Create(&'a str), + CreateNamed(usize), + CreateAll(&'a str), + CreateAllNamed(usize), + Open(&'a str), + OpenNamed(usize), + Close(usize), + Unlink(&'a str), + UnlinkNamed(usize), + Mkdir(&'a str), + MkdirNamed(usize), + ListDir(&'a str), + ListDirNamed(usize), + Read(usize, usize), + Write(usize, usize), + Seek(usize, usize), + Truncate(usize, usize), +} + +fn get_idx<T>(v: &[T], idx: usize) -> Option<usize> { + if !v.is_empty() { + Some(idx % v.len()) + } else { + None + } +}
```suggestion fn get_idx<T>(v: &[T], idx: usize) -> Option<usize> { idx.checked_rem(v.len()) } ```
svsm
github_2023
others
113
coconut-svsm
Freax13
@@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Carlos López <carlos.lopez@suse.com> + +#![no_main] + +use arbitrary::Arbitrary; +use core::hint::black_box; +use libfuzzer_sys::fuzz_target; +use std::rc::Rc; +use std::sync::OnceLock; +use svsm::fs::FileHandle; +use svsm::fs::{create, create_all, initialize_fs, list_dir, mkdir, open, uninitialize_fs, unlink}; +use svsm::mm::alloc::TestRootMem; + +const ROOT_MEM_SIZE: usize = 0x10000; +const MAX_READ_SIZE: usize = 4096 * 8; +const MAX_WRITE_SIZE: usize = 4096 * 8; +const WRITE_BYTE: u8 = 0x0; +const POISON_BYTE: u8 = 0xaf; + +#[derive(Arbitrary, Debug)] +enum FsAction<'a> { + Create(&'a str), + CreateNamed(usize), + CreateAll(&'a str), + CreateAllNamed(usize), + Open(&'a str), + OpenNamed(usize), + Close(usize), + Unlink(&'a str), + UnlinkNamed(usize), + Mkdir(&'a str), + MkdirNamed(usize), + ListDir(&'a str), + ListDirNamed(usize), + Read(usize, usize), + Write(usize, usize), + Seek(usize, usize), + Truncate(usize, usize), +} + +fn get_idx<T>(v: &[T], idx: usize) -> Option<usize> { + if !v.is_empty() { + Some(idx % v.len()) + } else { + None + } +} + +/// A handle for a file that also holds its original name +#[derive(Debug)] +struct Handle { + fd: FileHandle, + name: Rc<str>, +}
```suggestion /// A handle for a file that also holds its original name #[derive(Debug)] struct Handle<'a> { fd: FileHandle, name: &'a str, } ``` Allocating into an `Rc` is not needed here.
svsm
github_2023
others
113
coconut-svsm
Freax13
@@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Carlos López <carlos.lopez@suse.com> + +#![no_main] + +use arbitrary::Arbitrary; +use core::hint::black_box; +use libfuzzer_sys::fuzz_target; +use std::rc::Rc; +use std::sync::OnceLock; +use svsm::fs::FileHandle; +use svsm::fs::{create, create_all, initialize_fs, list_dir, mkdir, open, uninitialize_fs, unlink}; +use svsm::mm::alloc::TestRootMem; + +const ROOT_MEM_SIZE: usize = 0x10000; +const MAX_READ_SIZE: usize = 4096 * 8; +const MAX_WRITE_SIZE: usize = 4096 * 8; +const WRITE_BYTE: u8 = 0x0; +const POISON_BYTE: u8 = 0xaf; + +#[derive(Arbitrary, Debug)] +enum FsAction<'a> { + Create(&'a str), + CreateNamed(usize), + CreateAll(&'a str), + CreateAllNamed(usize), + Open(&'a str), + OpenNamed(usize), + Close(usize), + Unlink(&'a str), + UnlinkNamed(usize), + Mkdir(&'a str), + MkdirNamed(usize), + ListDir(&'a str), + ListDirNamed(usize), + Read(usize, usize), + Write(usize, usize), + Seek(usize, usize), + Truncate(usize, usize), +} + +fn get_idx<T>(v: &[T], idx: usize) -> Option<usize> {
All callers except one then go on to use the returned index to index into the slice. Have you considered just returning an `Option<&T>` instead of `Option<usize>`?
svsm
github_2023
others
113
coconut-svsm
Freax13
@@ -245,15 +244,17 @@ fn find_table<'a>(uuid: &Uuid, mem: &'a [u8]) -> Option<&'a [u8]> { None } -pub fn parse_fw_meta_data() -> Result<SevFWMetaData, SvsmError> { +/// Parse the firmware metadata located at the memory page starting at `vstart`. +/// +/// # Safety +/// +/// The caller must ensure that the provided virtual address points to a +/// page-sized mapped memory region +pub unsafe fn parse_fw_meta_data(vstart: VirtAddr) -> Result<SevFWMetaData, SvsmError> {
Should this function maybe just take a `&RawMetaBuffer` or `&[u8]`?
svsm
github_2023
others
113
coconut-svsm
Freax13
@@ -245,16 +244,18 @@ fn find_table<'a>(uuid: &Uuid, mem: &'a [u8]) -> Option<&'a [u8]> { None } -pub fn parse_fw_meta_data() -> Result<SevFWMetaData, SvsmError> { +/// Parse the firmware metadata from the given slice. +pub fn parse_fw_meta_data(mem: &[u8]) -> Result<SevFWMetaData, SvsmError> { let mut meta_data = SevFWMetaData::new(); - // Map meta-data location, it starts at 32 bytes below 4GiB - let pstart = PhysAddr::from((4 * SIZE_1G) - PAGE_SIZE); - let guard = PerCPUPageMappingGuard::create_4k(pstart)?; - let vstart = guard.virt_addr(); - - // Safety: RawMetaBuffer has a size of one page and it has no invalid - // representations. - let raw_meta = unsafe { &*vstart.as_ptr::<RawMetaBuffer>() }; + + if mem.len() != size_of::<RawMetaBuffer>() { + return Err(SvsmError::Firmware); + } + + // Safety: `RawMetaBuffer` has no invalid representations and is + // `repr(C, packed)`, which means there are no alignment requirements. + // We have also verified that the size of the slice matches.
Great job on the safety comments!
svsm
github_2023
others
122
coconut-svsm
roy-hopkins
@@ -37,7 +37,10 @@ pub const SVSM_CS_FLAGS: u16 = 0x29b; pub const SVSM_DS_FLAGS: u16 = 0xc93; pub const SVSM_TR_FLAGS: u16 = 0x89; -pub const GUEST_VMPL: usize = 1; +/// VMPL level the guest OS will be exectued at.
typo: executed
svsm
github_2023
others
126
coconut-svsm
joergroedel
@@ -125,3 +125,40 @@ pub fn free_stack(stack: VirtAddr) { STACK_ALLOC.lock().dealloc(stack); } + +#[cfg(test)] +mod tests { + use crate::mm::stack::*; + + #[test] + fn test_allocate_and_free_stack() { + /* + * For offline testing purposes, we can't + * really map physical memory. + */ + let stack_res = STACK_ALLOC.lock().alloc(); + let stack = stack_res.unwrap(); + let base_pointer = stack_base_pointer(stack); + + assert!(stack >= SVSM_SHARED_STACK_BASE); + assert!(stack < SVSM_SHARED_STACK_END); + + let bits = stack.bits(); + assert_eq!(0xFFFFFFC000000000, bits);
The constant here looks like it can be expressed based on `SVSM_SHARED_STACK_BASE`
svsm
github_2023
others
126
coconut-svsm
joergroedel
@@ -125,3 +125,40 @@ pub fn free_stack(stack: VirtAddr) { STACK_ALLOC.lock().dealloc(stack); } + +#[cfg(test)] +mod tests { + use crate::mm::stack::*; + + #[test] + fn test_allocate_and_free_stack() { + /* + * For offline testing purposes, we can't + * really map physical memory. + */ + let stack_res = STACK_ALLOC.lock().alloc(); + let stack = stack_res.unwrap(); + let base_pointer = stack_base_pointer(stack); + + assert!(stack >= SVSM_SHARED_STACK_BASE); + assert!(stack < SVSM_SHARED_STACK_END); + + let bits = stack.bits(); + assert_eq!(0xFFFFFFC000000000, bits); + + /* + * To calculate the base address we use stack.bits() + * plus STACK_SIZE + */ + let expected_base = if cfg!(feature = "enable-gdb") { + // 12 pages (GDB enabled) + VirtAddr::new(0xFFFFFFC000006000) + } else { + // 0 pages for STACK_PAGES_GDB (GDB disabled) + VirtAddr::new(0xFFFFFFC000004000) + };
And the expected base can be easier calculated using one of the STACK_SIZE or STACK_PAGES constants. Otherwise this test will always need adoption when we change the stack layout.
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -0,0 +1,74 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use super::VirtualMapping; +use crate::address::{PhysAddr, VirtAddr}; +use crate::error::SvsmError; +use crate::mm::address_space::{STACK_PAGES, STACK_SIZE}; +use crate::mm::pagetable::PTEntryFlags; +use crate::types::{PAGE_SHIFT, PAGE_SIZE}; + +use super::rawalloc::RawAllocMapping; + +#[derive(Default, Debug)] +pub struct VMKernelStack { + alloc: RawAllocMapping, + guard_pages: usize, +} + +impl VMKernelStack { + const fn guard_pages() -> usize { + STACK_PAGES.next_power_of_two() / 2
Why is the guard page count related to the size of the stack itself? Is there some particular attack against the stack that is mitigated by this sizing? If so, then it might be good to put a comment here.
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -0,0 +1,74 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use super::VirtualMapping; +use crate::address::{PhysAddr, VirtAddr}; +use crate::error::SvsmError; +use crate::mm::address_space::{STACK_PAGES, STACK_SIZE}; +use crate::mm::pagetable::PTEntryFlags; +use crate::types::{PAGE_SHIFT, PAGE_SIZE}; + +use super::rawalloc::RawAllocMapping; + +#[derive(Default, Debug)] +pub struct VMKernelStack { + alloc: RawAllocMapping, + guard_pages: usize, +} + +impl VMKernelStack { + const fn guard_pages() -> usize { + STACK_PAGES.next_power_of_two() / 2 + } + + pub fn top_of_stack(base: VirtAddr) -> VirtAddr { + let pages = Self::guard_pages() + STACK_PAGES; + base + (pages * PAGE_SIZE) + } + + pub fn new() -> Result<Self, SvsmError> { + let mut stack = VMKernelStack { + alloc: RawAllocMapping::new(STACK_SIZE),
Would it make more sense to pass the stack size in as a parameter? Would there be any situation where some tasks may require a larger kernel stack without having to increase the stack allocation for every task?
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -0,0 +1,74 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use super::VirtualMapping; +use crate::address::{PhysAddr, VirtAddr}; +use crate::error::SvsmError; +use crate::mm::address_space::{STACK_PAGES, STACK_SIZE}; +use crate::mm::pagetable::PTEntryFlags; +use crate::types::{PAGE_SHIFT, PAGE_SIZE}; + +use super::rawalloc::RawAllocMapping; + +#[derive(Default, Debug)] +pub struct VMKernelStack { + alloc: RawAllocMapping, + guard_pages: usize, +} + +impl VMKernelStack { + const fn guard_pages() -> usize { + STACK_PAGES.next_power_of_two() / 2 + } + + pub fn top_of_stack(base: VirtAddr) -> VirtAddr { + let pages = Self::guard_pages() + STACK_PAGES; + base + (pages * PAGE_SIZE) + } + + pub fn new() -> Result<Self, SvsmError> { + let mut stack = VMKernelStack { + alloc: RawAllocMapping::new(STACK_SIZE), + guard_pages: Self::guard_pages(), + }; + stack.alloc_pages()?; + + Ok(stack) + } + + pub fn alloc_pages(&mut self) -> Result<(), SvsmError> { + self.alloc.alloc_pages() + } +} + +impl VirtualMapping for VMKernelStack { + fn mapping_size(&self) -> usize { + (2 * STACK_PAGES.next_power_of_two()) << PAGE_SHIFT
Shouldn't this be `(STACK_PAGES + 2 * self.guard_pages).next_power_of_two()`?
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, PhysAddr}; +use crate::mm::pagetable::PTEntryFlags; + +use super::VirtualMapping; + +#[derive(Default, Debug)] +pub struct VMPhysMem { + base: PhysAddr, + size: usize, + writable: bool, +} + +impl VMPhysMem { + pub fn new(base: PhysAddr, size: usize, writable: bool) -> Self { + VMPhysMem { + base, + size, + writable, + } + } +} + +impl VirtualMapping for VMPhysMem { + fn mapping_size(&self) -> usize { + self.size + } + + fn map(&self, offset: usize) -> Option<PhysAddr> { + if offset < self.size { + Some((self.base + offset).page_align()) + } else { + None + } + } + + fn pt_flags(&self) -> PTEntryFlags { + PTEntryFlags::NX
We're going to need to support executable memory when loading modules.
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -0,0 +1,257 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, VirtAddr}; +use crate::cpu::flush_tlb_global_sync; +use crate::error::SvsmError; +use crate::locking::RWLock; +use crate::mm::pagetable::{PTEntryFlags, PageTable, PageTablePart, PageTableRef}; +use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M}; +use crate::utils::{align_down, align_up}; + +use core::cmp::max; + +use intrusive_collections::rbtree::{CursorMut, RBTree}; +use intrusive_collections::Bound; + +use super::{VMMAdapter, VirtualMapping, VMM}; + +extern crate alloc; +use alloc::rc::Rc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +const VMR_GRANULE: usize = PAGE_SIZE * 512 * 512 * 512; + +/// Virtual Memory Region +/// +/// This struct manages the mappings in a region of the virtual address space. +/// The region size is a multiple of 512GiB so that every region will fully +/// allocate one or more top-level page-table entries on x86-64. For the same +/// reason the start address must also be aligned to 512GB. +#[derive(Debug)] +pub struct VMR { + start_pfn: usize, + end_pfn: usize, + tree: RWLock<RBTree<VMMAdapter>>, + pgtbl_parts: RWLock<Vec<PageTablePart>>, + pt_flags: PTEntryFlags, +} + +impl VMR { + pub fn new(start: VirtAddr, end: VirtAddr, flags: PTEntryFlags) -> Self {
Will `flags` ever be anything other than `PTEntryFlags::GLOBAL` or 0? It might make sense to use a boolean instead if that is the case. I guess it might be useful to set `PTEntryFlags::USER` at this level too though.
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -0,0 +1,257 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, VirtAddr}; +use crate::cpu::flush_tlb_global_sync; +use crate::error::SvsmError; +use crate::locking::RWLock; +use crate::mm::pagetable::{PTEntryFlags, PageTable, PageTablePart, PageTableRef}; +use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M}; +use crate::utils::{align_down, align_up}; + +use core::cmp::max; + +use intrusive_collections::rbtree::{CursorMut, RBTree}; +use intrusive_collections::Bound; + +use super::{VMMAdapter, VirtualMapping, VMM}; + +extern crate alloc; +use alloc::rc::Rc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +const VMR_GRANULE: usize = PAGE_SIZE * 512 * 512 * 512; + +/// Virtual Memory Region +/// +/// This struct manages the mappings in a region of the virtual address space. +/// The region size is a multiple of 512GiB so that every region will fully +/// allocate one or more top-level page-table entries on x86-64. For the same +/// reason the start address must also be aligned to 512GB. +#[derive(Debug)] +pub struct VMR { + start_pfn: usize, + end_pfn: usize, + tree: RWLock<RBTree<VMMAdapter>>, + pgtbl_parts: RWLock<Vec<PageTablePart>>, + pt_flags: PTEntryFlags, +} + +impl VMR { + pub fn new(start: VirtAddr, end: VirtAddr, flags: PTEntryFlags) -> Self { + // Global and User are per VMR flags + VMR { + start_pfn: start.pfn(), + end_pfn: end.pfn(), + tree: RWLock::new(RBTree::new(VMMAdapter::new())), + pgtbl_parts: RWLock::new(Vec::new()), + pt_flags: flags, + } + } + + fn alloc_page_tables(&self) -> Result<(), SvsmError> { + let count = ((self.end_pfn - self.start_pfn) << PAGE_SHIFT) / VMR_GRANULE; + let start = VirtAddr::from(self.start_pfn << PAGE_SHIFT); + let mut vec = self.pgtbl_parts.lock_write(); + + for idx in 0..count { + vec.push(PageTablePart::new(start + (idx * VMR_GRANULE))); + } + + Ok(()) + } + + pub fn populate(&self, pgtbl: &mut PageTableRef) { + let parts = self.pgtbl_parts.lock_read(); + + for part in parts.iter() { + pgtbl.populate_pgtbl_part(part); + } + } + + pub fn initialize(&mut self) -> Result<(), SvsmError> { + let start = VirtAddr::from(self.start_pfn << PAGE_SHIFT); + let end = VirtAddr::from(self.end_pfn << PAGE_SHIFT); + assert!(start.is_aligned(VMR_GRANULE) && end.is_aligned(VMR_GRANULE));
Probably ought to also check for `end >= (start + VMR_GRANULE)`. `alloc_page_tables()` arithmetic operations can overflow if end < start.
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -0,0 +1,257 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{Address, VirtAddr}; +use crate::cpu::flush_tlb_global_sync; +use crate::error::SvsmError; +use crate::locking::RWLock; +use crate::mm::pagetable::{PTEntryFlags, PageTable, PageTablePart, PageTableRef}; +use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M}; +use crate::utils::{align_down, align_up}; + +use core::cmp::max; + +use intrusive_collections::rbtree::{CursorMut, RBTree}; +use intrusive_collections::Bound; + +use super::{VMMAdapter, VirtualMapping, VMM}; + +extern crate alloc; +use alloc::rc::Rc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +const VMR_GRANULE: usize = PAGE_SIZE * 512 * 512 * 512; + +/// Virtual Memory Region +/// +/// This struct manages the mappings in a region of the virtual address space. +/// The region size is a multiple of 512GiB so that every region will fully +/// allocate one or more top-level page-table entries on x86-64. For the same +/// reason the start address must also be aligned to 512GB. +#[derive(Debug)] +pub struct VMR { + start_pfn: usize, + end_pfn: usize, + tree: RWLock<RBTree<VMMAdapter>>, + pgtbl_parts: RWLock<Vec<PageTablePart>>, + pt_flags: PTEntryFlags, +} + +impl VMR { + pub fn new(start: VirtAddr, end: VirtAddr, flags: PTEntryFlags) -> Self { + // Global and User are per VMR flags + VMR { + start_pfn: start.pfn(), + end_pfn: end.pfn(), + tree: RWLock::new(RBTree::new(VMMAdapter::new())), + pgtbl_parts: RWLock::new(Vec::new()), + pt_flags: flags, + } + } + + fn alloc_page_tables(&self) -> Result<(), SvsmError> { + let count = ((self.end_pfn - self.start_pfn) << PAGE_SHIFT) / VMR_GRANULE; + let start = VirtAddr::from(self.start_pfn << PAGE_SHIFT); + let mut vec = self.pgtbl_parts.lock_write(); + + for idx in 0..count { + vec.push(PageTablePart::new(start + (idx * VMR_GRANULE))); + } + + Ok(()) + } + + pub fn populate(&self, pgtbl: &mut PageTableRef) { + let parts = self.pgtbl_parts.lock_read(); + + for part in parts.iter() { + pgtbl.populate_pgtbl_part(part); + } + } + + pub fn initialize(&mut self) -> Result<(), SvsmError> { + let start = VirtAddr::from(self.start_pfn << PAGE_SHIFT); + let end = VirtAddr::from(self.end_pfn << PAGE_SHIFT); + assert!(start.is_aligned(VMR_GRANULE) && end.is_aligned(VMR_GRANULE)); + + self.alloc_page_tables() + } + + fn virt_range(&self) -> (VirtAddr, VirtAddr) { + ( + VirtAddr::from(self.start_pfn << PAGE_SHIFT), + VirtAddr::from(self.end_pfn << PAGE_SHIFT), + ) + } + + fn map_vmm(&self, vmm: &VMM) -> Result<(), SvsmError> { + let (rstart, _) = self.virt_range(); + let (vmm_start, vmm_end) = vmm.range(); + let pt_flags = self.pt_flags | vmm.pt_flags() | PTEntryFlags::PRESENT; + let mut pgtbl_parts = self.pgtbl_parts.lock_write(); + let mut offset: usize = 0; + let page_size = vmm.page_size(); + let shared = vmm.shared(); + + while vmm_start + offset < vmm_end { + let idx = PageTable::index::<3>(VirtAddr::from(vmm_start - rstart)); + if let Some(paddr) = vmm.map(offset) { + if page_size == PAGE_SIZE { + pgtbl_parts[idx].map_4k(vmm_start + offset, paddr, pt_flags, shared)?; + } else if page_size == PAGE_SIZE_2M { + pgtbl_parts[idx].map_2m(vmm_start + offset, paddr, pt_flags, shared)?; + } + } + offset += page_size; + } + + Ok(()) + } + + fn unmap_vmm(&self, vmm: &VMM) { + let (rstart, _) = self.virt_range(); + let (vmm_start, vmm_end) = vmm.range(); + let mut pgtbl_parts = self.pgtbl_parts.lock_write(); + let mut offset: usize = 0; + + while vmm_start + offset < vmm_end { + let idx = PageTable::index::<3>(VirtAddr::from(vmm_start - rstart)); + if pgtbl_parts[idx].unmap_4k(vmm_start + offset).is_some() {
Does this need to handle when `vmm.page_size() == PAGE_SIZE_2M`?
svsm
github_2023
others
97
coconut-svsm
Freax13
@@ -745,3 +759,218 @@ impl DerefMut for PageTableRef { unsafe { &mut *self.pgtable_ptr } } } + +/// Represents a sub-tree of a page-table which can be mapped at a top-level index +#[derive(Default, Debug)] +struct RawPageTablePart { + page: PTPage, +} + +impl RawPageTablePart { + fn entry_to_page(entry: PTEntry) -> Option<&'static mut PTPage> { + let flags = entry.flags(); + if !flags.contains(PTEntryFlags::PRESENT) || flags.contains(PTEntryFlags::HUGE) { + return None; + } + + let address = phys_to_virt(entry.address()); + Some(unsafe { &mut *address.as_mut_ptr::<PTPage>() }) + } + + fn free_lvl1(page: &mut PTPage) { + for idx in 0..ENTRY_COUNT { + let entry = page[idx]; + + if RawPageTablePart::entry_to_page(entry).is_some() { + free_page(phys_to_virt(entry.address())); + } + } + } + + fn free_lvl2(page: &mut PTPage) { + for idx in 0..ENTRY_COUNT { + let entry = page[idx]; + + if let Some(l1_page) = RawPageTablePart::entry_to_page(entry) { + RawPageTablePart::free_lvl1(l1_page); + free_page(phys_to_virt(entry.address())); + } + } + } + + fn free(&mut self) { + RawPageTablePart::free_lvl2(&mut self.page); + }
This method and the functions it's calling should be unsafe. Freeing up memory is intrinsically unsafe as the caller has to ensure that there are no use-after-free or double-free situations. For similar reasons either `PageTablePart::map_4k` or `PageTablePart::unmap_4k` (or both) have to be unsafe.
svsm
github_2023
others
97
coconut-svsm
Freax13
@@ -0,0 +1,145 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{PhysAddr, VirtAddr}; +use crate::locking::RWLock; +use crate::mm::pagetable::PTEntryFlags; +use crate::types::{PAGE_SHIFT, PAGE_SIZE}; + +use core::cell::RefCell; + +use intrusive_collections::rbtree::Link; +use intrusive_collections::{intrusive_adapter, KeyAdapter}; + +extern crate alloc; +use alloc::rc::Rc; +use alloc::sync::Arc; + +pub trait VirtualMapping: core::fmt::Debug { + fn mapping_size(&self) -> usize; + + fn map(&self, offset: usize) -> Option<PhysAddr>; + + fn unmap(&self, _offset: usize) { + // Provide default in case there is nothing to do + } + + fn pt_flags(&self) -> PTEntryFlags; + + fn page_size(&self) -> usize { + // Default to system page-size + PAGE_SIZE + } + + fn shared(&self) -> bool { + // Shared with the HV - defaults not No + false + } +} + +#[derive(Default, Debug)] +struct Range { + start: usize, + end: usize, +} + +impl Range { + pub const fn new(start: usize, end: usize) -> Self { + Range { start, end } + } +} + +/// Virtual Memory Mapping +/// +/// A single mapping of virtual memory in a virtual memory range +#[derive(Debug)] +pub struct VMM { + link: Link, + + // Use a RefCell here to check borrowing rules at runtime. This should + // yield no errors as link and range are protected by the VMR RWLock. + range: RefCell<Range>, + + pt_flags: PTEntryFlags, + mapping: RWLock<Rc<dyn VirtualMapping>>, +} + +unsafe impl Send for VMM {} +unsafe impl Sync for VMM {}
The `Send` implementation is incorrect as the `Rc` contained within `VMM` isn't `Send`. The `Sync` implementation is incorrect as the `RefCell` contained within `VMM` isn't `Sync`.
svsm
github_2023
others
97
coconut-svsm
Freax13
@@ -745,3 +759,218 @@ impl DerefMut for PageTableRef { unsafe { &mut *self.pgtable_ptr } } } + +/// Represents a sub-tree of a page-table which can be mapped at a top-level index +#[derive(Default, Debug)] +struct RawPageTablePart { + page: PTPage, +} + +impl RawPageTablePart { + fn entry_to_page(entry: PTEntry) -> Option<&'static mut PTPage> { + let flags = entry.flags(); + if !flags.contains(PTEntryFlags::PRESENT) || flags.contains(PTEntryFlags::HUGE) { + return None; + } + + let address = phys_to_virt(entry.address()); + Some(unsafe { &mut *address.as_mut_ptr::<PTPage>() }) + }
The unsafe at the bottom seems dubious. How is it guaranteed that now other references to the page exist?
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -18,7 +18,7 @@ all: svsm.bin test: cargo test --target=x86_64-unknown-linux-gnu - RUSTFLAGS="--cfg doctest" cargo test --target=x86_64-unknown-linux-gnu --doc +# RUSTFLAGS="--cfg doctest" cargo test --target=x86_64-unknown-linux-gnu --doc
This can be re-enabled now #119 has been merged.
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -0,0 +1,110 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use super::VirtualMapping; +use crate::address::{PhysAddr, VirtAddr}; +use crate::error::SvsmError; +use crate::mm::address_space::STACK_SIZE; +use crate::mm::pagetable::PTEntryFlags; +use crate::types::{PAGE_SHIFT, PAGE_SIZE}; +use crate::utils::page_align_up; + +use super::rawalloc::RawAllocMapping; + +/// Mapping to be used as a kernel stack. This maps a stack including guard +/// pages at the top and bottom. +#[derive(Default, Debug)] +pub struct VMKernelStack { + /// Allocation for stack pages + alloc: RawAllocMapping, + /// Number of guard pages to reserve address space for + guard_pages: usize, +} + +impl VMKernelStack { + /// Returns the virtual address for the top of this kernel stack + /// + /// # Arguments + /// + /// * `base` - Virtual base address this stack is mapped at (including + /// guard pages). + /// + /// # Returns + /// + /// Virtual address to program into the hardware stack register + pub fn top_of_stack(&self, base: VirtAddr) -> VirtAddr { + let guard_size = self.guard_pages * PAGE_SIZE; + base + guard_size + self.alloc.mapping_size() + } + + /// Create a new [`VMKernelStack`] with a given size. This function will + /// already allocate the backing pages for the stack. + /// + /// # Arguments + /// + /// * `size` - Size of the kernel stack, without guard pages + /// + /// # Returns + /// + /// Initialized stack on success, Err(SvsmError::Mem) on error + pub fn new_size(size: usize) -> Result<Self, SvsmError> { + // Make sure size is page-aligned + let size = page_align_up(size); + // At least two guard-pages needed + let total_size = (size + 2 * PAGE_SIZE).next_power_of_two(); + let guard_pages = ((total_size - size) >> PAGE_SHIFT) / 2; + let mut stack = VMKernelStack { + alloc: RawAllocMapping::new(size), + guard_pages, + }; + stack.alloc_pages()?; + + Ok(stack) + } + + /// Create a new [`VMKernelStack`] with the default size. This function + /// will already allocate the backing pages for the stack. + /// + /// # Returns + /// + /// Initialized stack on success, Err(SvsmError::Mem) on error + pub fn new() -> Result<Self, SvsmError> { + VMKernelStack::new_size(STACK_SIZE) + } + + fn alloc_pages(&mut self) -> Result<(), SvsmError> { + self.alloc.alloc_pages() + } +}
I'm just looking at rebasing the task code against this and I think we're going to need a way to populate content within the stack pages using a temporary virtual address before the stack is mapped into a tasks's virtual memory space. When a task is first created, a `VMKernelStack` will be created for the task kernel stack. This will initially contain a task frame which includes the entry point of the task as expected by `switch_context`. So, `create_task()` will need to access the new task's stack from the context of another task in order to create this frame.
svsm
github_2023
others
97
coconut-svsm
Freax13
@@ -0,0 +1,218 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{PhysAddr, VirtAddr}; +use crate::locking::RWLock; +use crate::mm::pagetable::PTEntryFlags; +use crate::types::{PAGE_SHIFT, PAGE_SIZE}; + +use intrusive_collections::rbtree::Link; +use intrusive_collections::{intrusive_adapter, KeyAdapter}; + +extern crate alloc; +use alloc::boxed::Box; +use alloc::rc::Rc; + +pub trait VirtualMapping: core::fmt::Debug { + /// Request the size of the virtual memory mapping + /// + /// # Returns + /// + /// Mapping size. Will always be a multiple of `VirtualMapping::page_size()` + fn mapping_size(&self) -> usize; + + /// Request physical address to map for a given offset + /// + /// # Arguments + /// + /// * `offset` - Offset into the virtual memory mapping + /// + /// # Returns + /// + /// Physical address to map for the given offset, if any. None is also a + /// valid return value and does not indicate an error. + fn map(&self, offset: usize) -> Option<PhysAddr>; + + /// Inform the virtual memory mapping about an offset being unmapped. + /// Implementing `unmap()` is optional. + /// + /// # Arguments + /// + /// * `_offset` + fn unmap(&self, _offset: usize) { + // Provide default in case there is nothing to do + } + + /// Request the PTEntryFlags used for this virtual memory mapping. This is + /// a combination of + /// + /// * PTEntryFlags::WRITABLE + /// * PTEntryFlags::NX, + /// * PTEntryFlags::ACCESSED + /// * PTEntryFlags::DIRTY + fn pt_flags(&self) -> PTEntryFlags; + + /// Request the page size used for mappings + /// + /// # Returns + /// + /// Either PAGE_SIZE or PAGE_SIZE_2M + fn page_size(&self) -> usize { + // Default to system page-size + PAGE_SIZE + } + + /// Request whether the mapping is shared or private. Defaults to private + /// unless overwritten by the specific type. + /// + /// # Returns + /// + /// * `True` - When mapping is shared + /// * `False` - When mapping is private + fn shared(&self) -> bool { + // Shared with the HV - defaults not No + false + } +} + +#[derive(Default, Debug)] +struct Range { + start: usize, + end: usize, +} + +impl Range { + pub const fn new(start: usize, end: usize) -> Self { + Range { start, end } + } +}
Have you considered using the [`Range`](https://doc.rust-lang.org/core/ops/struct.Range.html) type in the standard library instead?
svsm
github_2023
others
97
coconut-svsm
Freax13
@@ -0,0 +1,218 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::address::{PhysAddr, VirtAddr}; +use crate::locking::RWLock; +use crate::mm::pagetable::PTEntryFlags; +use crate::types::{PAGE_SHIFT, PAGE_SIZE}; + +use intrusive_collections::rbtree::Link; +use intrusive_collections::{intrusive_adapter, KeyAdapter}; + +extern crate alloc; +use alloc::boxed::Box; +use alloc::rc::Rc; + +pub trait VirtualMapping: core::fmt::Debug { + /// Request the size of the virtual memory mapping + /// + /// # Returns + /// + /// Mapping size. Will always be a multiple of `VirtualMapping::page_size()` + fn mapping_size(&self) -> usize; + + /// Request physical address to map for a given offset + /// + /// # Arguments + /// + /// * `offset` - Offset into the virtual memory mapping + /// + /// # Returns + /// + /// Physical address to map for the given offset, if any. None is also a + /// valid return value and does not indicate an error. + fn map(&self, offset: usize) -> Option<PhysAddr>; + + /// Inform the virtual memory mapping about an offset being unmapped. + /// Implementing `unmap()` is optional. + /// + /// # Arguments + /// + /// * `_offset` + fn unmap(&self, _offset: usize) { + // Provide default in case there is nothing to do + } + + /// Request the PTEntryFlags used for this virtual memory mapping. This is + /// a combination of + /// + /// * PTEntryFlags::WRITABLE + /// * PTEntryFlags::NX, + /// * PTEntryFlags::ACCESSED + /// * PTEntryFlags::DIRTY + fn pt_flags(&self) -> PTEntryFlags; + + /// Request the page size used for mappings + /// + /// # Returns + /// + /// Either PAGE_SIZE or PAGE_SIZE_2M + fn page_size(&self) -> usize { + // Default to system page-size + PAGE_SIZE + } + + /// Request whether the mapping is shared or private. Defaults to private + /// unless overwritten by the specific type. + /// + /// # Returns + /// + /// * `True` - When mapping is shared + /// * `False` - When mapping is private + fn shared(&self) -> bool { + // Shared with the HV - defaults not No + false + } +} + +#[derive(Default, Debug)] +struct Range { + start: usize, + end: usize, +} + +impl Range { + pub const fn new(start: usize, end: usize) -> Self { + Range { start, end } + } +} + +/// A single mapping of virtual memory in a virtual memory range +#[derive(Debug)] +pub struct VMM { + /// Link for storing this instance in an RBTree + link: Link, + + /// The virtual memory range covered by this mapping + /// It is stored in a RefCell to check borrowing rules at runtime. + /// This is safe as any modification to `range` is protected by a lock in + /// the parent data structure. This is required because changes here also + /// need changes in the parent data structure. + range: Range, + + /// Flags used for mapping the virtual memory + pt_flags: PTEntryFlags, + + /// Pointer to the actual mapping + /// It is protected by an RWLock to serialize concurent accesses. + mapping: RWLock<Rc<dyn VirtualMapping>>, +} + +intrusive_adapter!(pub VMMAdapter = Box<VMM>: VMM { link: Link }); + +impl<'a> KeyAdapter<'a> for VMMAdapter { + type Key = usize; + fn get_key(&self, node: &'a VMM) -> Self::Key { + node.range.start + } +} + +impl VMM { + /// Create a new VMM instance with at a given address and backing struct + /// + /// # Arguments + /// + /// * `start` - Virtual start address to store in the mapping
`start` is a virtual page number, not an address.
svsm
github_2023
others
97
coconut-svsm
roy-hopkins
@@ -183,14 +184,23 @@ pub struct PerCpu { guest_vmsa: SpinLock<GuestVmsaRef>, reset_ip: u64, + /// PerCpu Virtual Memory Range + vm_range: VMR,
This is private but the `Tasks` structure needs access to this in order to update the task pagetable when performing a task switch and also to add a range when configuring a new task stack.
svsm
github_2023
others
111
coconut-svsm
00xc
@@ -13,17 +13,34 @@ use alloc::vec::Vec; use core::mem; use log; +/// ACPI Root System Description Pointer (RSDP) +/// used by ACPI programming interface #[derive(Debug, Default)] #[repr(C, packed)] struct RSDPDesc { + /// Signature must contain "RSD PTR" sig: [u8; 8], + /// Checksum to add to all other bytes chksum: u8, + /// OEM-supplied string oem_id: [u8; 6], + /// Revision of the ACPI rev: u8, + /// Physical address of the RSDT rsdt_addr: u32, } impl RSDPDesc { + /// Create an RSPDesc instance from FwCfg + /// + /// # Arguments + /// + /// - [`fw_cfg`]: A reference to the FwCfg instance.
This use of square brackets does not do anything, sadly. As far as I know, they only work for types, not variable names.
svsm
github_2023
others
111
coconut-svsm
00xc
@@ -764,18 +1164,29 @@ impl Elf64Hdr { } } +/// Program header entry in an ELF64 file #[derive(Debug)] pub struct Elf64Phdr { + /// Type of the program header entry pub p_type: Elf64Word, + /// Flags specifying the attributes of the segment pub p_flags: Elf64PhdrFlags, + /// Offset in the ELF file where the segment data begins pub p_offset: Elf64Off, + /// Virtual address at which the segment should be loaded into memory pub p_vaddr: Elf64Addr, + /// Physical address at which the segment should be loaded (for systems with separate physical memory) pub p_paddr: Elf64Addr, + /// Size of the segment in the ELF file (may be smaller than `p_memsz`) pub p_filesz: Elf64Xword, + /// Size of the segment in memory (may include additional padding) pub p_memsz: Elf64Xword, + /// Alignment of the segment in memory and in the file pub p_align: Elf64Xword, } +// Attributes of an ELF64 program header, to specify whether +// the segment is readable, writable, and/or executable bitflags! { #[derive(Debug)] pub struct Elf64PhdrFlags : Elf64Word {
These need to be `///` and be inside the `bitflags!` macro in order to show up in the generated docs.
svsm
github_2023
others
111
coconut-svsm
00xc
@@ -814,6 +1237,12 @@ impl Elf64Phdr { } } + /// Verifies the integrity and validity of the program header. + /// + /// # Returns + /// + /// Returns [`Ok(())`] if the program header is valid; otherwise, an [`Err`]
This should just be `Ok` without the parenthesis. This won't show up in the generated docs because it is a private function, so it is just a nitpick.
svsm
github_2023
others
111
coconut-svsm
00xc
@@ -599,6 +919,28 @@ impl<'a> Elf64File<'a> { } } + /// + /// This function processes dynamic relocations (relas) in the ELF file and applies them + /// to the loaded image. It takes a generic `rela_proc` parameter that should implement the + /// [`Elf64RelocProcessor`] trait, allowing custom relocation processing logic. + /// + /// The `image_load_addr` parameter specifies the virtual address where the ELF image is + /// loaded in memory. + /// + /// # Arguments + /// + /// * `rela_proc` - A relocation processor implementing the [`Elf64RelocProcessor`] trait. + /// * `image_load_addr` - The virtual address where the ELF image is loaded in memory. + /// + /// # Returns + /// + /// - [`Ok(Some(iterator))`]: If relocations are successfully applied, returns an iterator + /// over the applied relocations. + /// - [`Ok(None)`]: If no relocations are present or an error occurs during processing, + /// returns [`None`]. + /// - [`Err(ElfError)`]: If an error occurs while processing relocations, returns an + /// [`ElfError`].
Again, these won't render properly. Most of these can be fixed by using angle brackets (`<>`). For example: ```rust /// - [`Ok<None>`]: If no relocations ... ``` You may also simplify the doc by not writing out all the types if you wish so.
svsm
github_2023
others
111
coconut-svsm
00xc
@@ -599,6 +919,28 @@ impl<'a> Elf64File<'a> { } } + /// + /// This function processes dynamic relocations (relas) in the ELF file and applies them + /// to the loaded image. It takes a generic `rela_proc` parameter that should implement the + /// [`Elf64RelocProcessor`] trait, allowing custom relocation processing logic. + /// + /// The `image_load_addr` parameter specifies the virtual address where the ELF image is + /// loaded in memory. + /// + /// # Arguments + /// + /// * `rela_proc` - A relocation processor implementing the [`Elf64RelocProcessor`] trait. + /// * `image_load_addr` - The virtual address where the ELF image is loaded in memory. + /// + /// # Returns + /// + /// - [`Ok<Some(iterator)>`]: If relocations are successfully applied, returns an iterator
This one still does not render properly
svsm
github_2023
others
111
coconut-svsm
00xc
@@ -1532,22 +2313,37 @@ impl<'a, RP: Elf64RelocProcessor> Elf64AppliedRelaIterator<'a, RP> { impl<'a, RP: Elf64RelocProcessor> Iterator for Elf64AppliedRelaIterator<'a, RP> { type Item = Result<Option<Elf64RelocOp>, ElfError>; + /// Advances the iterator to the next relocation operation, processes it, + /// and returns the result. + /// + /// If there are no more relocations to process, [`None`] is returned to signal + /// the end of the iterator. + /// + /// # Returns + /// + /// - [`Some(Ok(None))`]: If the relocation entry indicates no operation (type == 0). + /// - [`Some(Ok(Some(reloc_op)))`]: If a relocation operation is successfully applied. + /// - [`Some(Err(ElfError))`]: If an error occurs during relocation processing.
These ones as well
svsm
github_2023
others
111
coconut-svsm
00xc
@@ -1215,21 +1815,31 @@ pub struct Elf64ImageLoadSegmentIterator<'a> { impl<'a> Iterator for Elf64ImageLoadSegmentIterator<'a> { type Item = Elf64ImageLoadSegment<'a>; + /// Advances the iterator to the next ELF64 image load segment and returns it. + /// + /// # Returns + /// + /// - [`Some(Elf64ImageLoadSegment)`] if there are more segments to iterate over.
Also this one.
svsm
github_2023
others
111
coconut-svsm
00xc
@@ -214,6 +288,32 @@ impl convert::TryFrom<(Elf64Addr, Elf64Xword)> for Elf64AddrRange { } } +/// Compares two [`Elf64AddrRange`] instances for partial ordering. It returns +/// [`Some(Ordering)`] if there is a partial order, and [`None`] if there is no +/// order (i.e., if the ranges overlap without being equal). +/// +/// # Arguments +/// +/// * `other` - The other [`Elf64AddrRange`] to compare to. +/// +/// # Returns +/// +/// - [`Some(Ordering::Less)`] if [`self`] is less than `other`. +/// - [`Some(Ordering::Greater)`] if [`self`] is greater than `other`. +/// - [`Some(Ordering::Equal)`] if [`self`] is equal to `other`.
These `Some`s as well. Although I think they can be omitted as the explanation is already present in the `PartialOrd` documentation, so it is a bit redundant.
svsm
github_2023
others
99
coconut-svsm
00xc
@@ -1605,3 +1605,198 @@ impl<'a, RP: Elf64RelocProcessor> Iterator for Elf64AppliedRelaIterator<'a, RP> Some(Ok(Some(reloc_op))) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_elf64_shdr_verify_methods() { + // Create a valid Elf64Shdr instance for testing. + let valid_shdr = Elf64Shdr { + sh_name: 1, + sh_type: 2, + sh_flags: Elf64ShdrFlags::WRITE | Elf64ShdrFlags::ALLOC, + sh_addr: 0x1000, + sh_offset: 0x2000, + sh_size: 0x3000, + sh_link: 3, + sh_info: 4, + sh_addralign: 8, + sh_entsize: 0, + }; + + // Verify that the valid Elf64Shdr instance passes verification. + assert!(valid_shdr.verify().is_ok()); + + // Create an invalid Elf64Shdr instance for testing. + let invalid_shdr = Elf64Shdr { + sh_name: 0, + sh_type: 2, + sh_flags: Elf64ShdrFlags::from_bits(0).unwrap(), + sh_addr: 0x1000, + sh_offset: 0x2000, + sh_size: 0x3000, + sh_link: 3, + sh_info: 4, + sh_addralign: 7, // Invalid alignment + sh_entsize: 0, + }; + + // Verify that the invalid Elf64Shdr instance fails verification. + assert!(invalid_shdr.verify().is_err()); + } + + #[test] + fn test_elf64_dynamic_reloc_table_verify_valid() { + // Create a valid Elf64DynamicRelocTable instance for testing. + let reloc_table = Elf64DynamicRelocTable { + base_vaddr: 0x1000, + size: 0x2000, + entsize: 0x30, + }; + + // Verify that the valid Elf64DynamicRelocTable instance passes verification. + assert!(reloc_table.verify().is_ok()); + } + + #[test] + fn test_elf64_addr_range_methods() { + // Test Elf64AddrRange::len() and Elf64AddrRange::is_empty(). + + // Create an Elf64AddrRange instance for testing. + let addr_range = Elf64AddrRange { + vaddr_begin: 0x1000, + vaddr_end: 0x2000, + }; + + // Check that the length calculation is correct. + assert_eq!(addr_range.len(), 0x1000); + + // Check if the address range is empty. + assert!(!addr_range.is_empty()); + + // Test Elf64AddrRange::try_from(). + + // Create a valid input tuple for try_from. + let valid_input: (Elf64Addr, Elf64Xword) = (0x1000, 0x2000); + + // Attempt to create an Elf64AddrRange from the valid input. + let result = Elf64AddrRange::try_from(valid_input); + + // Verify that the result is Ok and contains the expected Elf64AddrRange. + assert!(result.is_ok()); + let valid_addr_range = result.unwrap(); + assert_eq!(valid_addr_range.vaddr_begin, 0x1000); + assert_eq!(valid_addr_range.vaddr_end, 0x3000); + } + + #[test] + fn test_elf64_file_range_try_from() { + // Valid range + let valid_range: (Elf64Off, Elf64Xword) = (0, 100); + let result: Result<Elf64FileRange, ElfError> = valid_range.try_into(); + assert!(result.is_ok()); + let file_range = result.unwrap(); + assert_eq!(file_range.offset_begin, 0); + assert_eq!(file_range.offset_end, 100); + + // Invalid range (overflow) + let invalid_range: (Elf64Off, Elf64Xword) = (usize::MAX as Elf64Off, 100); + let result: Result<Elf64FileRange, ElfError> = invalid_range.try_into(); + assert!(result.is_err()); + } + + #[test] + fn test_elf64_file_read() { + // In the future, you can play around with this skeleton ELF + // file to test other cases + let byte_data: [u8; 184] = [ + // ELF Header + 0x7F, 0x45, 0x4C, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x00, 0x3E, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Program Header (with PT_LOAD) + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Section Header (simplified) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Raw Machine Code Instructions + 0xf3, 0x0f, 0x1e, 0xfa, 0x31, 0xed, 0x49, 0x89, 0xd1, 0x5e, 0x48, 0x89, 0xe2, 0x48, + 0x83, 0xe4, 0xf0, 0x50, 0x54, 0x45, 0x31, 0xc0, 0x31, 0xc9, 0x48, 0x8d, 0x3d, 0xca, + 0x00, 0x00, 0x00, 0xff, 0x15, 0x53, 0x2f, 0x00, 0x00, 0xf4, 0x66, 0x2e, 0x0f, 0x1f, + 0x84, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x3d, 0x79, 0x2f, 0x00, 0x00, 0x48, 0x8d, + 0x05, 0x72, 0x2f, 0x00, 0x00, 0x48, 0x39, 0xf8, 0x74, 0x15, 0x48, 0x8b, 0x05, 0x36, + 0x2f, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x09, 0xff, 0xe0, 0x0f, 0x1f, 0x80, 0x00, + 0x00, 0x00, 0x00, 0xc3, + ]; + + // Use the Elf64File::read method to create an Elf64File instance + match Elf64File::read(&byte_data) { + Ok(_elf_file) => { + assert!(false); + } + Err(err) => { + assert!(matches!(err, crate::elf::ElfError::InvalidPhdrSize)); + } + }
This can probably be collapsed to a single statement (instead of having an `assert!(false)`) to something like: ```rust let res = Elf64File::read(&byte_data); assert!(matches!(res, Err(crate::elf::ElfError::InvalidPhdrSize))); ``` You could also use `assert_eq!()` instead of `assert!(matches!())` if you derive `Eq` for `ElfError`.
svsm
github_2023
others
99
coconut-svsm
cclaudio
@@ -1605,3 +1605,192 @@ impl<'a, RP: Elf64RelocProcessor> Iterator for Elf64AppliedRelaIterator<'a, RP> Some(Ok(Some(reloc_op))) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_elf64_shdr_verify_methods() { + // Create a valid Elf64Shdr instance for testing. + let valid_shdr = Elf64Shdr { + sh_name: 1, + sh_type: 2, + sh_flags: Elf64ShdrFlags::WRITE | Elf64ShdrFlags::ALLOC, + sh_addr: 0x1000, + sh_offset: 0x2000, + sh_size: 0x3000, + sh_link: 3, + sh_info: 4, + sh_addralign: 8, + sh_entsize: 0, + }; + + // Verify that the valid Elf64Shdr instance passes verification. + assert!(valid_shdr.verify().is_ok()); + + // Create an invalid Elf64Shdr instance for testing. + let invalid_shdr = Elf64Shdr { + sh_name: 0, + sh_type: 2, + sh_flags: Elf64ShdrFlags::from_bits(0).unwrap(), + sh_addr: 0x1000, + sh_offset: 0x2000, + sh_size: 0x3000, + sh_link: 3, + sh_info: 4, + sh_addralign: 7, // Invalid alignment + sh_entsize: 0, + }; + + // Verify that the invalid Elf64Shdr instance fails verification. + assert!(invalid_shdr.verify().is_err()); + } + + #[test] + fn test_elf64_dynamic_reloc_table_verify_valid() { + // Create a valid Elf64DynamicRelocTable instance for testing. + let reloc_table = Elf64DynamicRelocTable { + base_vaddr: 0x1000, + size: 0x2000, + entsize: 0x30, + }; + + // Verify that the valid Elf64DynamicRelocTable instance passes verification. + assert!(reloc_table.verify().is_ok()); + } + + #[test] + fn test_elf64_addr_range_methods() { + // Test Elf64AddrRange::len() and Elf64AddrRange::is_empty(). + + // Create an Elf64AddrRange instance for testing. + let addr_range = Elf64AddrRange { + vaddr_begin: 0x1000, + vaddr_end: 0x2000, + }; + + // Check that the length calculation is correct. + assert_eq!(addr_range.len(), 0x1000); + + // Check if the address range is empty. + assert!(!addr_range.is_empty()); + + // Test Elf64AddrRange::try_from(). + + // Create a valid input tuple for try_from. + let valid_input: (Elf64Addr, Elf64Xword) = (0x1000, 0x2000); + + // Attempt to create an Elf64AddrRange from the valid input. + let result = Elf64AddrRange::try_from(valid_input); + + // Verify that the result is Ok and contains the expected Elf64AddrRange. + assert!(result.is_ok()); + let valid_addr_range = result.unwrap(); + assert_eq!(valid_addr_range.vaddr_begin, 0x1000); + assert_eq!(valid_addr_range.vaddr_end, 0x3000); + } + + #[test] + fn test_elf64_file_range_try_from() { + // Valid range + let valid_range: (Elf64Off, Elf64Xword) = (0, 100); + let result: Result<Elf64FileRange, ElfError> = valid_range.try_into(); + assert!(result.is_ok()); + let file_range = result.unwrap(); + assert_eq!(file_range.offset_begin, 0); + assert_eq!(file_range.offset_end, 100); + + // Invalid range (overflow) + let invalid_range: (Elf64Off, Elf64Xword) = (usize::MAX as Elf64Off, 100); + let result: Result<Elf64FileRange, ElfError> = invalid_range.try_into(); + assert!(result.is_err()); + } + + #[test] + fn test_elf64_file_read() { + // In the future, you can play around with this skeleton ELF + // file to test other cases + let byte_data: [u8; 184] = [ + // ELF Header + 0x7F, 0x45, 0x4C, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x00, 0x3E, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Program Header (with PT_LOAD) + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Section Header (simplified) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Raw Machine Code Instructions + 0xf3, 0x0f, 0x1e, 0xfa, 0x31, 0xed, 0x49, 0x89, 0xd1, 0x5e, 0x48, 0x89, 0xe2, 0x48, + 0x83, 0xe4, 0xf0, 0x50, 0x54, 0x45, 0x31, 0xc0, 0x31, 0xc9, 0x48, 0x8d, 0x3d, 0xca, + 0x00, 0x00, 0x00, 0xff, 0x15, 0x53, 0x2f, 0x00, 0x00, 0xf4, 0x66, 0x2e, 0x0f, 0x1f, + 0x84, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x3d, 0x79, 0x2f, 0x00, 0x00, 0x48, 0x8d, + 0x05, 0x72, 0x2f, 0x00, 0x00, 0x48, 0x39, 0xf8, 0x74, 0x15, 0x48, 0x8b, 0x05, 0x36, + 0x2f, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x09, 0xff, 0xe0, 0x0f, 0x1f, 0x80, 0x00, + 0x00, 0x00, 0x00, 0xc3, + ]; + + // Use the Elf64File::read method to create an Elf64File instance + let res = Elf64File::read(&byte_data); + assert!(matches!(res, Err(crate::elf::ElfError::InvalidPhdrSize)));
If you use `assert_eq` here, the test case would have a better error message. I was able to do that deriving some structures from PartialEq. ```diff diff --git a/src/elf/mod.rs b/src/elf/mod.rs index f795560f0963..ecec8543c06f 100644 --- a/src/elf/mod.rs +++ b/src/elf/mod.rs @@ -17,7 +17,7 @@ use core::fmt; use core::matches; use core::mem; -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum ElfError { FileTooShort, @@ -250,7 +250,7 @@ impl convert::TryFrom<(Elf64Off, Elf64Xword)> for Elf64FileRange { } } -#[derive(Default, Debug)] +#[derive(Default, Debug, PartialEq)] pub struct Elf64File<'a> { elf_file_buf: &'a [u8], elf_hdr: Elf64Hdr, @@ -647,7 +647,7 @@ impl<'a> Elf64File<'a> { } } -#[derive(Debug, Default)] +#[derive(Debug, Default, PartialEq)] pub struct Elf64Hdr { #[allow(unused)] e_ident: [Elf64char; 16], @@ -958,7 +958,7 @@ impl Elf64Shdr { } } -#[derive(Debug, Default)] +#[derive(Debug, Default, PartialEq)] struct Elf64LoadSegments { segments: Vec<(Elf64AddrRange, Elf64Half)>, } @@ -1026,7 +1026,7 @@ impl Elf64LoadSegments { } } -#[derive(Debug)] +#[derive(Debug, PartialEq)] struct Elf64DynamicRelocTable { base_vaddr: Elf64Addr, // DT_RELA / DT_REL size: Elf64Xword, // DT_RELASZ / DT_RELSZ @@ -1044,7 +1044,7 @@ impl Elf64DynamicRelocTable { } } -#[derive(Debug)] +#[derive(Debug, PartialEq)] struct Elf64DynamicSymtab { base_vaddr: Elf64Addr, // DT_SYMTAB entsize: Elf64Xword, // DT_SYMENT @@ -1058,7 +1058,7 @@ impl Elf64DynamicSymtab { } } -#[derive(Debug)] +#[derive(Debug, PartialEq)] struct Elf64Dynamic { // No DT_REL representation: "The AMD64 ABI architectures uses only // Elf64_Rela relocation entries [...]". @@ -1241,7 +1241,7 @@ impl<'a> Iterator for Elf64ImageLoadSegmentIterator<'a> { } } -#[derive(Debug, Default)] +#[derive(Debug, Default, PartialEq)] struct Elf64Strtab<'a> { strtab_buf: &'a [u8], } @@ -1733,10 +1733,13 @@ mod tests { // Use the Elf64File::read method to create an Elf64File instance let res = Elf64File::read(&byte_data); - assert!(matches!(res, Err(crate::elf::ElfError::InvalidPhdrSize))); + assert_eq!(res.err(), Some(crate::elf::ElfError::InvalidPhdrSize)); ```
svsm
github_2023
others
99
coconut-svsm
cclaudio
@@ -1605,3 +1605,192 @@ impl<'a, RP: Elf64RelocProcessor> Iterator for Elf64AppliedRelaIterator<'a, RP> Some(Ok(Some(reloc_op))) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_elf64_shdr_verify_methods() { + // Create a valid Elf64Shdr instance for testing. + let valid_shdr = Elf64Shdr { + sh_name: 1, + sh_type: 2, + sh_flags: Elf64ShdrFlags::WRITE | Elf64ShdrFlags::ALLOC, + sh_addr: 0x1000, + sh_offset: 0x2000, + sh_size: 0x3000, + sh_link: 3, + sh_info: 4, + sh_addralign: 8, + sh_entsize: 0, + }; + + // Verify that the valid Elf64Shdr instance passes verification. + assert!(valid_shdr.verify().is_ok()); + + // Create an invalid Elf64Shdr instance for testing. + let invalid_shdr = Elf64Shdr { + sh_name: 0, + sh_type: 2, + sh_flags: Elf64ShdrFlags::from_bits(0).unwrap(), + sh_addr: 0x1000, + sh_offset: 0x2000, + sh_size: 0x3000, + sh_link: 3, + sh_info: 4, + sh_addralign: 7, // Invalid alignment + sh_entsize: 0, + }; + + // Verify that the invalid Elf64Shdr instance fails verification. + assert!(invalid_shdr.verify().is_err()); + } + + #[test] + fn test_elf64_dynamic_reloc_table_verify_valid() { + // Create a valid Elf64DynamicRelocTable instance for testing. + let reloc_table = Elf64DynamicRelocTable { + base_vaddr: 0x1000, + size: 0x2000, + entsize: 0x30, + }; + + // Verify that the valid Elf64DynamicRelocTable instance passes verification. + assert!(reloc_table.verify().is_ok()); + } + + #[test] + fn test_elf64_addr_range_methods() { + // Test Elf64AddrRange::len() and Elf64AddrRange::is_empty(). + + // Create an Elf64AddrRange instance for testing. + let addr_range = Elf64AddrRange { + vaddr_begin: 0x1000, + vaddr_end: 0x2000, + }; + + // Check that the length calculation is correct. + assert_eq!(addr_range.len(), 0x1000); + + // Check if the address range is empty. + assert!(!addr_range.is_empty()); + + // Test Elf64AddrRange::try_from(). + + // Create a valid input tuple for try_from. + let valid_input: (Elf64Addr, Elf64Xword) = (0x1000, 0x2000); + + // Attempt to create an Elf64AddrRange from the valid input. + let result = Elf64AddrRange::try_from(valid_input); + + // Verify that the result is Ok and contains the expected Elf64AddrRange. + assert!(result.is_ok()); + let valid_addr_range = result.unwrap(); + assert_eq!(valid_addr_range.vaddr_begin, 0x1000); + assert_eq!(valid_addr_range.vaddr_end, 0x3000); + } + + #[test] + fn test_elf64_file_range_try_from() { + // Valid range + let valid_range: (Elf64Off, Elf64Xword) = (0, 100); + let result: Result<Elf64FileRange, ElfError> = valid_range.try_into(); + assert!(result.is_ok()); + let file_range = result.unwrap(); + assert_eq!(file_range.offset_begin, 0); + assert_eq!(file_range.offset_end, 100); + + // Invalid range (overflow) + let invalid_range: (Elf64Off, Elf64Xword) = (usize::MAX as Elf64Off, 100); + let result: Result<Elf64FileRange, ElfError> = invalid_range.try_into(); + assert!(result.is_err()); + } + + #[test] + fn test_elf64_file_read() { + // In the future, you can play around with this skeleton ELF + // file to test other cases + let byte_data: [u8; 184] = [ + // ELF Header + 0x7F, 0x45, 0x4C, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x00, 0x3E, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Program Header (with PT_LOAD) + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Section Header (simplified) + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, // Raw Machine Code Instructions + 0xf3, 0x0f, 0x1e, 0xfa, 0x31, 0xed, 0x49, 0x89, 0xd1, 0x5e, 0x48, 0x89, 0xe2, 0x48, + 0x83, 0xe4, 0xf0, 0x50, 0x54, 0x45, 0x31, 0xc0, 0x31, 0xc9, 0x48, 0x8d, 0x3d, 0xca, + 0x00, 0x00, 0x00, 0xff, 0x15, 0x53, 0x2f, 0x00, 0x00, 0xf4, 0x66, 0x2e, 0x0f, 0x1f, + 0x84, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x3d, 0x79, 0x2f, 0x00, 0x00, 0x48, 0x8d, + 0x05, 0x72, 0x2f, 0x00, 0x00, 0x48, 0x39, 0xf8, 0x74, 0x15, 0x48, 0x8b, 0x05, 0x36, + 0x2f, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x09, 0xff, 0xe0, 0x0f, 0x1f, 0x80, 0x00, + 0x00, 0x00, 0x00, 0xc3, + ]; + + // Use the Elf64File::read method to create an Elf64File instance + let res = Elf64File::read(&byte_data); + assert!(matches!(res, Err(crate::elf::ElfError::InvalidPhdrSize))); + + // Construct an Elf64Hdr instance from the byte data + let elf_hdr = Elf64Hdr::read(&byte_data).expect("Failed to read ELF header");
If we hit this expect, will the remaining tests not be executed? If so, we could have something like this ```diff // Construct an Elf64Hdr instance from the byte data - let elf_hdr = Elf64Hdr::read(&byte_data).expect("Failed to read ELF header"); + let elf_hdr = Elf64Hdr::read(&byte_data); + assert!(elf_hdr.is_ok()); + + let elf_hdr = elf_hdr.unwrap(); ```
svsm
github_2023
others
105
coconut-svsm
Freax13
@@ -155,3 +155,46 @@ impl<T: Debug> RWLock<T> { } } } + +mod tests { + + #[test] + fn test_lock_rw() {
Note that this test fails when run with miri: ``` $ MIRIFLAGS="-Zmiri-permissive-provenance" cargo +nightly miri test --target=x86_64-unknown-linux-gnu test_lock_rw [...] test locking::rwlock::tests::test_lock_rw ... error: Undefined Behavior: trying to retag from <137787> for SharedReadOnly permission at alloc48741[0x8], but that tag does not exist in the borrow stack for this location --> src/locking/rwlock.rs:27:9 | 27 | self.data | ^^^^^^^^^ | | | trying to retag from <137787> for SharedReadOnly permission at alloc48741[0x8], but that tag does not exist in the borrow stack for this location | this error occurs as part of retag at alloc48741[0x8..0xc] | = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information help: <137787> was created by a Unique retag at offsets [0x8..0xc] --> src/locking/rwlock.rs:190:27 | 190 | let read_guard1 = rwlock_concurrent.lock_read(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: <137787> was later invalidated at offsets [0x8..0xc] by a Unique retag --> src/locking/rwlock.rs:127:28 | 127 | data: unsafe { &mut *self.data.get() }, | ^^^^^^^^^^^^^^^^^^^^^ = note: BACKTRACE (of the first span): = note: inside `<locking::rwlock::ReadLockGuard<'_, i32> as core::ops::Deref>::deref` at src/locking/rwlock.rs:27:9: 27:18 note: inside `locking::rwlock::tests::test_lock_rw` --> src/locking/rwlock.rs:194:20 | 194 | assert_eq!(*read_guard1, 123); | ^^^^^^^^^^^^ note: inside closure --> src/locking/rwlock.rs:163:23 | 162 | #[test] | ------- in this procedural macro expansion 163 | fn test_lock_rw() { | ^ = note: this error originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace ```
svsm
github_2023
others
105
coconut-svsm
joergroedel
@@ -89,3 +89,28 @@ impl<T: Debug> SpinLock<T> { None } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_spin_lock() { + let spin_lock = SpinLock::new(0); + + let mut guard = spin_lock.lock(); + *guard += 1; + + // Ensure the locked data is updated. + assert_eq!(*guard, 1); + + let spin_lock = SpinLock::new(0); + + let mut guard_failed = spin_lock.lock(); + *guard_failed += 1;
I don't get what this tests, you are defining a new spinlock, overwriting the old name. Can you explain what this tests and what guard_failed is for?
svsm
github_2023
others
96
coconut-svsm
00xc
@@ -134,43 +188,100 @@ impl ACPITable { Ok(Self { header, buf }) } + /// Get the signature of the ACPI table. + /// + /// This method returns the 4-character signature of the ACPI table, such as "APIC." + #[allow(dead_code)] fn signature(&self) -> FixedString<4> { FixedString::from(self.header.sig) } + /// Get the content of the ACPI table. + /// + /// This method returns a reference to the binary content of the ACPI table, + /// excluding the header. + /// + /// # Returns + /// + /// A reference to the ACPI table content, or `None` if the content is empty. + fn content(&self) -> Option<&[u8]> { let offset = mem::size_of::<RawACPITableHeader>(); // Zero-length slices are valid, but we do not want them self.buf.get(offset..).filter(|b| !b.is_empty()) } + /// Get a pointer to the content of the ACPI table at a specific offset. + /// + /// This method returns a pointer to the content of the ACPI table at the specified offset, + /// converted to the desired type `T`. + /// + /// # Arguments + /// + /// * `offset` - The offset at which to obtain the pointer. + /// + /// # Returns + /// +
Aren't we missing the return type here?
svsm
github_2023
others
96
coconut-svsm
00xc
@@ -222,11 +346,37 @@ impl ACPITableBuffer { Ok(()) } + /// Retrieve an ACPI table from a specified offset within the ACPI table buffer. + /// + /// This function attempts to retrieve an ACPI table from the ACPI table buffer starting from the + /// specified offset. It parses the table header and creates an `ACPITable` instance representing + /// the ACPI table's content. + /// + /// # Arguments + /// + /// * `offset` - The offset within the ACPI table buffer from which to retrieve the ACPI table. + /// + /// # Returns + /// + /// An `Result` containing the `ACPITable` instance if successfully retrieved, or an `SvsmError`
Should be "A `Result` containing...". There's a few more of these, just pointing it out once to avoid spamming.
svsm
github_2023
others
108
coconut-svsm
Freax13
@@ -1219,61 +1219,64 @@ impl SvsmAllocator { slab_size_2048: SpinLock::new(Slab::new(2048)), } } -} - -unsafe impl GlobalAlloc for SvsmAllocator { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - let ret: Result<VirtAddr, SvsmError>; - let size = layout.size(); + fn get_slab(&self, size: usize) -> Option<&SpinLock<Slab>> { if size <= 32 { - ret = self.slab_size_32.lock().allocate(); + Some(&self.slab_size_32) } else if size <= 64 { - ret = self.slab_size_64.lock().allocate(); + Some(&self.slab_size_64) } else if size <= 128 { - ret = self.slab_size_128.lock().allocate(); + Some(&self.slab_size_128) } else if size <= 256 { - ret = self.slab_size_256.lock().allocate(); + Some(&self.slab_size_256) } else if size <= 512 { - ret = self.slab_size_512.lock().allocate(); + Some(&self.slab_size_512) } else if size <= 1024 { - ret = self.slab_size_1024.lock().allocate(); + Some(&self.slab_size_1024) } else if size <= 2048 { - ret = self.slab_size_2048.lock().allocate(); - } else if size <= 4096 { - ret = allocate_page(); + Some(&self.slab_size_2048) } else { - let order = get_order(size); - if order >= MAX_ORDER { - return ptr::null_mut(); - } - ret = allocate_pages(order); + None } + } +} + +unsafe impl GlobalAlloc for SvsmAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let size = layout.size(); + let ret = match self.get_slab(size) { + Some(slab) => slab.lock().allocate(), + None => { + let order = get_order(size); + if order >= MAX_ORDER { + return ptr::null_mut(); + } + allocate_pages(order) + } + }; ret.map(|addr| addr.as_mut_ptr::<u8>()) .unwrap_or_else(|_| ptr::null_mut()) } - unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let virt_addr = VirtAddr::from(ptr); + let size = layout.size(); let result = ROOT_MEM.lock().get_page_info(virt_addr); - - if result.is_err() { + let Ok(info) = result else { panic!("Freeing unknown memory"); - } - - let info = result.unwrap(); + }; match info { Page::Allocated(_ai) => { free_page(virt_addr); } - Page::SlabPage(si) => { - assert!(!si.slab.is_null()); - let slab = si.slab.as_mut_ptr::<Slab>(); - - (*slab).deallocate(virt_addr); + Page::SlabPage(_si) => { + let Some(slab) = self.get_slab(size) else { + panic!("Invalid page info"); + };
```suggestion let slab = self.get_slab(size).expect("Invalid page info"); ```
svsm
github_2023
others
108
coconut-svsm
Freax13
@@ -1219,61 +1219,64 @@ impl SvsmAllocator { slab_size_2048: SpinLock::new(Slab::new(2048)), } } -} - -unsafe impl GlobalAlloc for SvsmAllocator { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - let ret: Result<VirtAddr, SvsmError>; - let size = layout.size(); + fn get_slab(&self, size: usize) -> Option<&SpinLock<Slab>> { if size <= 32 { - ret = self.slab_size_32.lock().allocate(); + Some(&self.slab_size_32) } else if size <= 64 { - ret = self.slab_size_64.lock().allocate(); + Some(&self.slab_size_64) } else if size <= 128 { - ret = self.slab_size_128.lock().allocate(); + Some(&self.slab_size_128) } else if size <= 256 { - ret = self.slab_size_256.lock().allocate(); + Some(&self.slab_size_256) } else if size <= 512 { - ret = self.slab_size_512.lock().allocate(); + Some(&self.slab_size_512) } else if size <= 1024 { - ret = self.slab_size_1024.lock().allocate(); + Some(&self.slab_size_1024) } else if size <= 2048 { - ret = self.slab_size_2048.lock().allocate(); - } else if size <= 4096 { - ret = allocate_page(); + Some(&self.slab_size_2048) } else { - let order = get_order(size); - if order >= MAX_ORDER { - return ptr::null_mut(); - } - ret = allocate_pages(order); + None } + } +} + +unsafe impl GlobalAlloc for SvsmAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let size = layout.size(); + let ret = match self.get_slab(size) { + Some(slab) => slab.lock().allocate(), + None => { + let order = get_order(size); + if order >= MAX_ORDER { + return ptr::null_mut(); + } + allocate_pages(order) + } + }; ret.map(|addr| addr.as_mut_ptr::<u8>()) .unwrap_or_else(|_| ptr::null_mut()) } - unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let virt_addr = VirtAddr::from(ptr); + let size = layout.size(); let result = ROOT_MEM.lock().get_page_info(virt_addr); - - if result.is_err() { + let Ok(info) = result else { panic!("Freeing unknown memory"); - } - - let info = result.unwrap(); + };
This can be shortened to: ```rust let info = result.expect("Freeing unknown memory"); ```
svsm
github_2023
others
89
coconut-svsm
00xc
@@ -250,18 +367,39 @@ impl convert::TryFrom<(Elf64Off, Elf64Xword)> for Elf64FileRange { } } +/// This struct represents a parsed 64-bit ELF file. It contains information +/// about the ELF file's header, load segments, dynamic section, and more. #[derive(Default, Debug)] pub struct Elf64File<'a> { + /// Buffer containing the ELF file data elf_file_buf: &'a [u8], + /// The ELF file header elf_hdr: Elf64Hdr, + /// The load segments present in the ELF file load_segments: Elf64LoadSegments, + /// The maximum alignment requirement among load segments max_load_segment_align: Elf64Xword, + /// THe section header string table may not be present #[allow(unused)] sh_strtab: Option<Elf64Strtab<'a>>, dynamic: Option<Elf64Dynamic>, } impl<'a> Elf64File<'a> { + /// This method takes a byte buffer containing the ELF file data and parses + /// it into an `Elf64File` struct, providing access to the ELF file's information. + /// + /// # Errors + /// + /// Returns an `ElfError` if there are issues parsing the ELF file. + /// + /// # Examples + /// + /// ```rust + /// use your_module::Elf64File; + /// + /// let elf_file = Elf64File::read(&elf_file_buf).unwrap(); + /// ``
There's a missing closing backtick here. `cargo doc` will warn about it: ``` warning: could not parse code block as Rust code --> src/elf/mod.rs:398:9 | 398 | /// ```rust | _________^ 399 | | /// use your_module::Elf64File; 400 | | /// 401 | | /// let elf_file = Elf64File::read(&elf_file_buf).unwrap(); 402 | | /// `` | |__________^ | = note: error from rustc: unknown start of token: ` = note: `#[warn(rustdoc::invalid_rust_codeblocks)]` on by default ```
svsm
github_2023
others
85
coconut-svsm
00xc
@@ -309,9 +309,9 @@ fn mapping_info_init(launch_info: &KernelLaunchInfo) { } #[no_mangle] -pub extern "C" fn svsm_start(li: &KernelLaunchInfo, vb_addr: VirtAddr) { +pub extern "C" fn svsm_start(li: &KernelLaunchInfo, vb_addr: usize) { let launch_info: KernelLaunchInfo = *li; - let vb_ptr = vb_addr.as_mut_ptr::<u64>(); + let vb_ptr = VirtAddr::new(vb_addr).as_mut_ptr::<u64>();
Hm. `VirtAddr` is `repr(transparent)` so that it works with external ABIs (i.e. it is a zero-cost abstraction), but making it non-trivial defeats this purpose. I'd rather have a `sign_extend()` method on the type (or on the `Address` trait) and use that conversion here. Another idea is to have a sign-extending constructor and a "trivial" constructor.
svsm
github_2023
others
76
coconut-svsm
stefano-garzarella
@@ -0,0 +1,38 @@ +#!/bin/bash + +set -x + +CURDIR=$(dirname $(realpath "$0")) +WORKDIR=$(realpath ${CURDIR}/../..) +DOCKER_FILE=$WORKDIR/scripts/docker/opensuse-rust.docker + +IMAGE_NAME=opensuse-rust +CONTAINER_NAME=coconut-build + +if ! command -v docker &> /dev/null ; then + echo "ERR: docker not found" + exit +fi + +IMAGE_ID=$(docker images -q ${IMAGE_NAME}) + +# Build the container image if it's the first time +if [ -z ${IMAGE_ID} ] ; then + docker build -t ${IMAGE_NAME} --build-arg USER_NAME=${USER} --build-arg USER_ID=$(id -u) -f ${DOCKER_FILE} . +fi + +CONTAINER_ID=$(docker ps -q -f name=${CONTAINER_NAME}) + +# Create and start the the container if it's not running +if [ -z ${CONTAINER_ID} ] ; then + + CONTAINER_ID=$(docker ps -q -f name=coconut-build) + + if [ -z ${CONTAINER_ID} ] ; then + docker create -it --name=${CONTAINER_NAME} --workdir=${WORKDIR} --user ${USER} --mount type=bind,source=${WORKDIR},target=${WORKDIR} ${IMAGE_NAME} /bin/bash + fi + + docker start ${CONTAINER_NAME} +fi + +docker exec -it ${CONTAINER_NAME} /bin/bash -c "source $HOME/.cargo/env && make clean && make"
What about replacing with just `docker run`: ```suggestion docker run --rm -it --workdir=${WORKDIR} --user ${USER} --userns keep-id --mount type=bind,source=${WORKDIR},target=${WORKDIR} ${IMAGE_NAME} /bin/bash -c "source $HOME/.cargo/env && make clean && make" ``` I added ` --userns keep-id` to properly work with `podman-docker`, eventually what about using podman directly?
svsm
github_2023
others
76
coconut-svsm
stefano-garzarella
@@ -0,0 +1,23 @@ +# Usage example: +# +# git clone https://github.com/coconut-svsm/svsm.git +# cd svsm +# docker build -t fedora-rust -f scripsts/fedora-rust.docker .
s/fedora/opensuse
svsm
github_2023
others
76
coconut-svsm
stefano-garzarella
@@ -0,0 +1,127 @@ +#!/bin/bash + +CURDIR=$(dirname $(realpath "$0")) +WORKDIR=$(realpath ${CURDIR}/../..) +DOCKER_FILE=$WORKDIR/scripts/docker/opensuse-rust.docker + +IMAGE_NAME=opensuse-rust +CONTAINER_NAME=coconut-build + +# Command line arguments +ARG_REUSE=0 + +#### +#### Help function +#### +Help() +{ + echo "Build the SVSM within a container." + echo + echo "Syntax: $0 [-r|v|h]" + echo "options:" + echo "r Reuse the ${CONTAINER_NAME} to build the SVSM" + echo "v Verbose mode" + echo "h Print this help" +} + +#### +#### ParseOptions function +#### +ParseOptions() +{ + while getopts "rvh" option; do + case $option in + r) # Reuse option + ARG_REUSE=1 + ;; + v) # Verbose mode + set -x + ;; + h) # Display help + Help + exit + ;; + \?) # Invalid option + echo -e "ERR: Invalid option\n" + Help + exit + ;; + esac + done +} + +#### +#### Reuse container to build the SVSM +#### +BuildSvsmReuse() +{ + CONTAINER_ID=$(docker ps -q -f name=${CONTAINER_NAME}) + + # Create and start the the container if it's not running + if [ -z ${CONTAINER_ID} ] ; then + + CONTAINER_ID=$(docker ps -q -f name=coconut-build)
Should we add `-a` here? We can also use `${CONTAINER_NAME}` ```suggestion CONTAINER_ID=$(docker ps -q -a -f name=${CONTAINER_NAME}) ```
svsm
github_2023
others
76
coconut-svsm
stefano-garzarella
@@ -0,0 +1,127 @@ +#!/bin/bash + +CURDIR=$(dirname $(realpath "$0")) +WORKDIR=$(realpath ${CURDIR}/../..) +DOCKER_FILE=$WORKDIR/scripts/docker/opensuse-rust.docker + +IMAGE_NAME=opensuse-rust +CONTAINER_NAME=coconut-build + +# Command line arguments +ARG_REUSE=0 + +#### +#### Help function +#### +Help() +{ + echo "Build the SVSM within a container." + echo + echo "Syntax: $0 [-r|v|h]" + echo "options:" + echo "r Reuse the ${CONTAINER_NAME} to build the SVSM" + echo "v Verbose mode" + echo "h Print this help" +} + +#### +#### ParseOptions function +#### +ParseOptions() +{ + while getopts "rvh" option; do + case $option in + r) # Reuse option + ARG_REUSE=1 + ;; + v) # Verbose mode + set -x + ;; + h) # Display help + Help + exit + ;; + \?) # Invalid option + echo -e "ERR: Invalid option\n" + Help + exit + ;; + esac + done +} + +#### +#### Reuse container to build the SVSM +#### +BuildSvsmReuse() +{ + CONTAINER_ID=$(docker ps -q -f name=${CONTAINER_NAME}) + + # Create and start the the container if it's not running + if [ -z ${CONTAINER_ID} ] ; then + + CONTAINER_ID=$(docker ps -q -f name=coconut-build) + + if [ -z ${CONTAINER_ID} ] ; then + docker create \ + -it --name=${CONTAINER_NAME} \ + --workdir=${WORKDIR} \ + --user ${USER} \ + --mount type=bind,source=${WORKDIR},target=${WORKDIR} \ + ${IMAGE_NAME} \ + /bin/bash + fi + + docker start ${CONTAINER_NAME} + fi + + docker exec \ + -it ${CONTAINER_NAME} \ + /bin/bash -c "source $HOME/.cargo/env && make clean && make" +} + +#### +#### Build the SVSM in the container, but delete the container afterwards +#### +BuildSvsmDelete() +{ + docker run \ + --rm -it \ + --workdir=${WORKDIR} \ + --user ${USER} \
After a second thought and a chat with @osteffenrh, if we want to avoid having to download dependencies every time, we can create a volume for the cargo home: ``` --mount type=volume,source=${VOLUME_NAME},target=${HOME}/.cargo \ ``` However, I don't have a strong opinion on this, just a suggestion that crossed my mind, the current state is fine with me ;-)
svsm
github_2023
others
81
coconut-svsm
stefano-garzarella
@@ -1,14 +0,0 @@ -{ - "llvm-target": "x86_64-unknown-none", - "data-layout": "e-m:e-i64:64-f80:128-n8:16:32:64-S128", - "arch": "x86_64", - "target-endian": "little", - "target-pointer-width": "64", - "target-c-int-width": "32", - "os": "none", - "executables": true, - "linker-flavor": "gcc", - "panic-strategy": "abort",
Just a question to let me understand better the rust targets ;-) How we are now specifying the `panic-strategy`? Is default to `abort` for `x86_64-unknown-none`? I found something [here](https://doc.rust-lang.org/rustc/platform-support/x86_64-unknown-none.html) for example about the red-zone, but nothing about panic.
svsm
github_2023
others
78
coconut-svsm
00xc
@@ -325,6 +331,46 @@ impl PageTable { PageTable::walk_addr_lvl3(&mut self.root, vaddr) } + fn free_pgtbl_lvl1(page: &PTPage) { + for idx in 0..ENTRY_COUNT { + let entry = page[idx]; + + if PageTable::entry_to_pagetable(entry).is_some() { + free_page(phys_to_virt(entry.address())); + } + } + } + + fn free_pgtbl_lvl2(page: &PTPage) { + for idx in 0..ENTRY_COUNT { + let entry = page[idx]; + + if let Some(l1_page) = PageTable::entry_to_pagetable(entry) { + PageTable::free_pgtbl_lvl1(l1_page); + free_page(phys_to_virt(entry.address())); + } + } + } + fn free_pgtbl_lvl3(page: &PTPage) { + for idx in 0..ENTRY_COUNT { + // Do not free the per-cpu and shared parts of the page-table + if idx == PGTABLE_LVL3_IDX_PERCPU || idx == PGTABLE_LVL3_IDX_SHARED { + continue; + } + + let entry = page[idx]; + + if let Some(l2_page) = PageTable::entry_to_pagetable(entry) { + PageTable::free_pgtbl_lvl2(l2_page); + free_page(phys_to_virt(entry.address())); + } + } + } + + pub fn free(&mut self) { + PageTable::free_pgtbl_lvl3(&self.root); + } +
Shouldn't `free_pgtbl_lvl{1,2,3}` be methods on `PTPage` that take `&self`? `PageTable::free()` would then simply be `self.root.free_lvl3()`
svsm
github_2023
others
77
coconut-svsm
00xc
@@ -0,0 +1,204 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::types::PAGE_SHIFT; +use crate::utils::{align_down, align_up}; +use core::cmp::max; +use intrusive_collections::rbtree::{Link, RBTree}; +use intrusive_collections::{intrusive_adapter, KeyAdapter}; + +extern crate alloc; +use alloc::boxed::Box; + +struct Range<T> { + link: Link, + start: usize, + end: usize, + data: T, +} + +impl<T> Range<T> { + const fn new(start: usize, end: usize, data: T) -> Self { + Self { + link: Link::new(), + start, + end, + data, + } + } + + fn get(&self) -> &T { + &self.data + } +} + +intrusive_adapter!(RangeAdapater<T> = Box<Range<T>>: Range::<T> { link: Link });
Small typo, should be `RangeAdapter`
svsm
github_2023
others
77
coconut-svsm
00xc
@@ -0,0 +1,204 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::types::PAGE_SHIFT; +use crate::utils::{align_down, align_up}; +use core::cmp::max; +use intrusive_collections::rbtree::{Link, RBTree}; +use intrusive_collections::{intrusive_adapter, KeyAdapter}; + +extern crate alloc; +use alloc::boxed::Box; + +struct Range<T> { + link: Link, + start: usize, + end: usize, + data: T, +} + +impl<T> Range<T> { + const fn new(start: usize, end: usize, data: T) -> Self { + Self { + link: Link::new(), + start, + end, + data, + } + } + + fn get(&self) -> &T { + &self.data + } +} + +intrusive_adapter!(RangeAdapater<T> = Box<Range<T>>: Range::<T> { link: Link }); + +impl<'a, T> KeyAdapter<'a> for RangeAdapater<T> { + type Key = usize; + fn get_key(&self, node: &'a Range<T>) -> usize { + node.start + } +} + +pub struct AddressAllocator<T> { + tree: RBTree<RangeAdapater<T>>, + pfn_low: usize, + pfn_high: usize, +} + +impl<T> AddressAllocator<T> { + pub fn new(low: usize, high: usize) -> Self { + Self { + tree: RBTree::new(RangeAdapater::new()), + pfn_low: low >> PAGE_SHIFT, + pfn_high: high >> PAGE_SHIFT, + } + } + + pub fn alloc_aligned(&mut self, size: usize, align: usize, data: T) -> Option<usize> { + assert!(align.is_power_of_two()); + + let size = size.checked_next_power_of_two().unwrap_or(0) >> PAGE_SHIFT; + let align = align >> PAGE_SHIFT; + let mut start = align_up(self.pfn_low, align); + let mut end = start; + + if size == 0 { + return None; + } + + let mut cursor = self.tree.front_mut(); + while !cursor.is_null() { + let node = cursor.get().unwrap();
This is equivalent and avoids an unwrap: ```rust while let Some(node) = cursor.get() { ... } ```
svsm
github_2023
others
77
coconut-svsm
00xc
@@ -0,0 +1,204 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use crate::types::PAGE_SHIFT; +use crate::utils::{align_down, align_up}; +use core::cmp::max; +use intrusive_collections::rbtree::{Link, RBTree}; +use intrusive_collections::{intrusive_adapter, KeyAdapter}; + +extern crate alloc; +use alloc::boxed::Box; + +struct Range<T> { + link: Link, + start: usize, + end: usize, + data: T, +} + +impl<T> Range<T> { + const fn new(start: usize, end: usize, data: T) -> Self { + Self { + link: Link::new(), + start, + end, + data, + } + } + + fn get(&self) -> &T { + &self.data + } +} + +intrusive_adapter!(RangeAdapater<T> = Box<Range<T>>: Range::<T> { link: Link }); + +impl<'a, T> KeyAdapter<'a> for RangeAdapater<T> { + type Key = usize; + fn get_key(&self, node: &'a Range<T>) -> usize { + node.start + } +} + +pub struct AddressAllocator<T> { + tree: RBTree<RangeAdapater<T>>, + pfn_low: usize, + pfn_high: usize, +} + +impl<T> AddressAllocator<T> { + pub fn new(low: usize, high: usize) -> Self { + Self { + tree: RBTree::new(RangeAdapater::new()), + pfn_low: low >> PAGE_SHIFT, + pfn_high: high >> PAGE_SHIFT, + } + } + + pub fn alloc_aligned(&mut self, size: usize, align: usize, data: T) -> Option<usize> { + assert!(align.is_power_of_two()); + + let size = size.checked_next_power_of_two().unwrap_or(0) >> PAGE_SHIFT; + let align = align >> PAGE_SHIFT; + let mut start = align_up(self.pfn_low, align); + let mut end = start; + + if size == 0 { + return None; + } + + let mut cursor = self.tree.front_mut(); + while !cursor.is_null() { + let node = cursor.get().unwrap(); + end = node.start; + if end > start && end - start >= size { + break; + } + start = max(start, align_up(node.end, align)); + cursor.move_next(); + } + + if cursor.is_null() { + end = align_down(self.pfn_high, align); + } + + if end > start && end - start >= size { + cursor.insert_before(Box::new(Range::<T>::new(start, start + size, data))); + Some(start << PAGE_SHIFT) + } else { + None + } + } + + pub fn alloc(&mut self, size: usize, data: T) -> Option<usize> {
Maybe the return value should be an `Option<VirtAddr>`? Same with the input for `free()` and `get()` taking a `VirtAddr`.
svsm
github_2023
others
79
coconut-svsm
stefano-garzarella
@@ -4,6 +4,9 @@ // // Author: Joerg Roedel <jroedel@suse.de> +// For bitflags definitions +#![allow(clippy::bad_bit_mask)]
Is clippy complains about `RMPFlags`? What about allow it only for that definition?
svsm
github_2023
others
75
coconut-svsm
joergroedel
@@ -19,19 +19,10 @@ use log; pub const MAX_ORDER: usize = 6; pub fn get_order(size: usize) -> usize { - let mut val = (size - 1) >> PAGE_SHIFT; - let mut order: usize = 0; - - loop { - if val == 0 { - break; - } - - order += 1; - val >>= 1; - } - - order + // FIXME: Use `div_ceil` once stabilized. + (size.saturating_add(PAGE_SIZE - 1) / PAGE_SIZE) + .next_power_of_two() + .ilog2() as usize
Thanks! Maybe you can change that to Paolo's latest version (using usize::BITS)?
svsm
github_2023
others
73
coconut-svsm
00xc
@@ -121,9 +121,15 @@ bitflags! { } #[repr(C)] -#[derive(Copy, Clone)] +#[derive(Copy, Clone, Debug)] pub struct PTEntry(PhysAddr); +impl Default for PTEntry { + fn default() -> Self { + PTEntry(PhysAddr::new(0)) + } +} +
I think this could be derived as well, since you added Default for PhysAddr.
svsm
github_2023
others
73
coconut-svsm
00xc
@@ -184,6 +198,7 @@ pub enum Mapping<'a> { } #[repr(C)] +#[derive(Default)] pub struct PageTable { root: PTPage, }
Might as well derive Debug here too.
svsm
github_2023
others
73
coconut-svsm
00xc
@@ -24,6 +24,8 @@ pub struct X86GeneralRegs { pub rax: usize, } +impl Copy for X86GeneralRegs {} +
This can also be derived.
svsm
github_2023
others
73
coconut-svsm
00xc
@@ -36,10 +38,13 @@ pub struct X86SegmentRegs { } #[repr(C, packed)] +#[derive(Default, Debug, Clone)] pub struct X86InterruptFrame { pub rip: usize, pub cs: usize, pub flags: usize, pub rsp: usize, pub ss: usize, } + +impl Copy for X86InterruptFrame {}
Same here, could be derived
svsm
github_2023
others
73
coconut-svsm
00xc
@@ -17,8 +17,9 @@ use core::fmt; use core::matches; use core::mem; -#[derive(Debug)] +#[derive(Debug, Default)] pub enum ElfError { + #[default]
Not sure how I feel about this. Does it make sense to have a default `ElfError`? If we had an `Other` variant this would probably be fine but in this case I'm not sure.
svsm
github_2023
others
73
coconut-svsm
00xc
@@ -18,8 +18,9 @@ use packit::PackItError; const MAX_FILENAME_LENGTH: usize = 64; pub type FileName = FixedString<MAX_FILENAME_LENGTH>; -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone, Debug, Default)] pub enum FsError { + #[default] Inval,
This one I think is fine since EINVAL is usually very generic.
svsm
github_2023
others
33
coconut-svsm
osteffenrh
@@ -0,0 +1,35 @@ +#!/usr/bin/env bash +set -e + +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +if [[ $1 == "debug" ]]; then + LOG_FILE="ovmf_debug.build" +else + LOG_FILE="ovmf_release.build" +fi +rm -f $LOG_FILE + +pushd $SCRIPT_DIR/../edk2 + +export PYTHON3_ENABLE=TRUE +export PYTHON_COMMAND=python3 +export CC=/usr/bin/gcc-7
Why require gcc 7 explicitly? Ovmf builds fine with versions up to and including gcc 12.
svsm
github_2023
others
25
coconut-svsm
joergroedel
@@ -5,21 +5,17 @@ // Author: Joerg Roedel <jroedel@suse.de> use crate::locking::SpinLock; -use crate::serial::DEFAULT_SERIAL_PORT; +use crate::serial::{DEFAULT_SERIAL_PORT, Terminal}; use crate::utils::immut_after_init::ImmutAfterInitCell; use core::fmt; use log; -pub trait ConsoleWriter { - fn put_byte(&self, _ch: u8) {} -} - pub struct Console { - writer: *mut dyn ConsoleWriter, + writer: *mut dyn Terminal,
Please factor out the renaming of ConsoleWriter to Terminal to a separate patch.
svsm
github_2023
others
25
coconut-svsm
joergroedel
@@ -0,0 +1,488 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +// +// For release builds this module should not be compiled into the +// binary. See the bottom of this file for placeholders that are +// used when the gdb stub is disabled. +// +#[cfg(feature = "enable-gdb")] +pub mod svsm_gdbstub { + use gdbstub::stub::{ GdbStubBuilder, SingleThreadStopReason}; + use gdbstub::stub::state_machine::GdbStubStateMachine; + use gdbstub::conn::Connection; + use gdbstub::target::{ Target, TargetError }; + use gdbstub::target::ext::base::BaseOps; + use gdbstub::target::ext::base::singlethread::{SingleThreadBase, SingleThreadResumeOps, SingleThreadResume, SingleThreadSingleStepOps, SingleThreadSingleStep}; + use gdbstub::target::ext::breakpoints::{ Breakpoints, SwBreakpoint }; + use gdbstub_arch::x86::X86_64_SSE; + use core::arch::asm; + use crate::svsm_console::SVSMIOPort; + use crate::serial::{ SerialPort, Terminal }; + use crate::cpu::X86Regs; + use crate::types::VirtAddr; + + const INT3_INSTR: u8 = 0xcc; + const MAX_BREAKPOINTS: usize = 32; + + pub fn gdbstub_start() -> Result<(), u64> { + unsafe { + let mut target = GdbStubTarget::new(); + let gdb = GdbStubBuilder::new(GdbStubConnection::new()) + .with_packet_buffer(&mut PACKET_BUFFER) + .build() + .expect("Failed to initialise GDB stub") + .run_state_machine(&mut target).expect("Failed to start GDB state machine"); + GDB_STATE = Some(SvsmGdbStub { gdb, target }); + } + init_pf_handler(); + Ok(()) + } + + pub fn handle_debug_pf_exception(regs: &mut X86Regs) -> bool { + unsafe { + if HANDLE_PF_FAULT { + PF_FAULT = true; + regs.rip = PF_RETURN_ADDR as usize; + true + } else { + false + } + } + } + + pub fn handle_bp_exception(regs: &mut X86Regs) { + handle_stop(regs, true); + } + + pub fn handle_db_exception(regs: &mut X86Regs) { + handle_stop(regs, false); + } + + pub fn debug_break() { + if unsafe { GDB_STATE.is_some() } { + log::info!("***********************************"); + log::info!("* Waiting for connection from GDB *"); + log::info!("***********************************"); + unsafe { asm!("int3"); } + } + } + + static mut GDB_STATE: Option<SvsmGdbStub> = None; + static GDB_IO: SVSMIOPort = SVSMIOPort::new(); + static mut GDB_SERIAL: SerialPort = SerialPort { driver: &GDB_IO, port: 0x2f8 }; + static mut PACKET_BUFFER: [u8; 4096] = [0; 4096]; + static mut SINGLE_STEP: bool = false; + static mut BREAKPOINT_ADDR: [VirtAddr; MAX_BREAKPOINTS] = [ 0; MAX_BREAKPOINTS ]; + static mut BREAKPOINT_INST: [u8; MAX_BREAKPOINTS] = [ 0xcc; MAX_BREAKPOINTS ]; + + struct SvsmGdbStub<'a> { + gdb: GdbStubStateMachine<'a, GdbStubTarget, GdbStubConnection>, + target: GdbStubTarget + } + + fn handle_stop(regs: &mut X86Regs, bp_exception: bool) { + let SvsmGdbStub { gdb, mut target } = unsafe { + GDB_STATE.take().unwrap_or_else(|| { + panic!("GDB stub not initialised!"); + }) + }; + + target.set_regs(regs); + + // If the current address is on a breakpoint then we need to + // move the IP back by one byte + if bp_exception && is_breakpoint(regs.rip - 1) { + regs.rip -= 1; + } + + let mut new_gdb = match gdb { + GdbStubStateMachine::Running(gdb_inner) => { + match gdb_inner.report_stop(&mut target, SingleThreadStopReason::SwBreak(())) { + Ok(gdb) => gdb, + Err(_) => panic!("Failed to handle software breakpoint") + } + } + _ => { + gdb + } + }; + + loop { + new_gdb = match new_gdb { + // The first entry into the debugger is via a forced breakpoint during + // initialisation. The state at this point will be Idle instead of + // Running. + GdbStubStateMachine::Idle(mut gdb_inner) => { + let byte = gdb_inner.borrow_conn().read().map_err(|_| 1 as u64).expect("Failed to read from GDB port"); + match gdb_inner.incoming_data(&mut target, byte) { + Ok(gdb) => gdb, + Err(_) => panic!("Could not open serial port for GDB connection. \ + Please ensure the virtual machine is configured to provide a second serial port.") + } + } + GdbStubStateMachine::Running(gdb_inner) => { + new_gdb = gdb_inner.into(); + break; + } + _ => { + log::info!("Invalid GDB state when handling breakpoint interrupt"); + return; + } + }; + } + if unsafe { SINGLE_STEP } { + regs.flags |= 0x100; + } else { + regs.flags &= !0x100; + } + unsafe { GDB_STATE = Some(SvsmGdbStub { gdb: new_gdb, target }) }; + } + + fn is_breakpoint(rip: usize) -> bool { + unsafe { + for index in 0..BREAKPOINT_ADDR.len() { + if (BREAKPOINT_INST[index] != INT3_INSTR) && + (BREAKPOINT_ADDR[index] == rip as VirtAddr) { + return true; + } + } + } + false + } + + static mut HANDLE_PF_FAULT: bool = false; + static mut PF_RETURN_ADDR: u64 = 0; + static mut PF_FAULT: bool = false; + + fn init_pf_handler() { + // Grab the address of the 'try_done' label in the asm + // section in safe_access_memory(). If a page fault occurs + // then the handler will check to see if HANDLE_PF_FAULT is + // set indicating that we are trying to safely access memory. + // In this case the handler will set rip to try_done to handle + // the error without panicking. + unsafe { + let td: u64; + asm!( + "lea try_done(%rip), %rax", + out("rax") td, + options(att_syntax) + ); + PF_RETURN_ADDR = td; + } + } + + #[allow(named_asm_labels)] + pub fn safe_access_memory(addr: VirtAddr, write: bool, value: u8) -> Result<u8, ()> {
This can probably be implemented with the exception fixup code that is already available in SVSM.
svsm
github_2023
others
25
coconut-svsm
joergroedel
@@ -203,6 +203,14 @@ impl PageTable { }) } + // When GDB is enabled allow the executable memory to be writable to
I think it is better to use temporary mapping for pages that need to be written to. That way code pages can stay read-only.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,186 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; + +use super::INITIAL_TASK_ID; +use super::{task::TaskState, Task}; + +pub static TASKLIST: SpinLock<TaskList> = SpinLock::new(TaskList::new()); + +#[derive(Copy, Clone)] +pub struct TaskList { + pub root: Option<*mut Task>, +}
I have not tested this at all, but could we use the [LinkedList](https://doc.rust-lang.org/alloc/collections/linked_list/struct.LinkedList.html) type in the alloc module? It would save us a lot of unsafe code.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,186 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; + +use super::INITIAL_TASK_ID; +use super::{task::TaskState, Task}; + +pub static TASKLIST: SpinLock<TaskList> = SpinLock::new(TaskList::new()); + +#[derive(Copy, Clone)] +pub struct TaskList { + pub root: Option<*mut Task>, +} + +impl TaskList { + pub const fn new() -> Self { + Self { root: None } + } + + pub fn insert(&mut self, task: *mut Task) { + if self.root.is_none() { + self.root = Some(task); + } else { + unsafe { + let root_task = self.root.unwrap(); + (*task).next = (*root_task).next; + (*root_task).next = task; + } + } + } + + pub fn foreach<F>(&self, mut action: F) + where + F: FnMut(*mut Task) -> bool, + { + if self.root.is_some() { + let root = self.root.unwrap(); + let mut current_task = root; + loop { + let this_task = unsafe { &mut *current_task }; + if !action(current_task) { + break; + } + current_task = this_task.next; + if current_task == root { + break; + } + } + } + } + + pub fn get_task(&self, id: u32) -> Option<*mut Task> { + let mut task: Option<*mut Task> = None; + self.foreach(|t| { + if unsafe { (*t).id } == id { + task = Some(t); + return false; + } + true + }); + task + } + + /// + /// Each processor that is assigned to run tasks must call this function + /// before further tasks can be scheduled onto the CPU by schedule(). + /// + pub fn launch_initial_cpu_task(task: *mut Task) { + if this_cpu().current_task.is_some() { + panic!("Attempt to run an initial task on a previously initialised processor"); + } + if unsafe { (*task).state } != TaskState::RUNNING { + panic!("Attempt to launch a non-running initial task"); + } + unsafe { (*task).state = TaskState::SCHEDULED }; + this_cpu_mut().current_task = Some(task); + unsafe { (*task).set_current(None) }; + } + + pub fn schedule() {
This should probably be a standalone function, no? I find it quite confusing that this is an associated function on `TaskList`, but takes a lock on `TASKLIST`, which itself is a lock around a `TaskList` instance.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -182,6 +183,8 @@ pub struct PerCpu { pub vrange_4k: VirtualRange, /// Address allocator for per-cpu 2m temporary mappings pub vrange_2m: VirtualRange, + + pub current_task: Option<*mut Task>,
If we are guarding against NULL with an `Option` we could use a [`ptr::NonNull`](https://doc.rust-lang.org/core/ptr/struct.NonNull.html) to improve struct layout.
svsm
github_2023
others
50
coconut-svsm
joergroedel
@@ -0,0 +1,69 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +#[repr(C, packed)] +pub struct X86Regs {
This struct is unused now, no?
svsm
github_2023
others
50
coconut-svsm
joergroedel
@@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +use core::arch::asm; + +pub fn rdtsc() -> u64 {
No need for a new file, this function can be added to src/cpu/msr.rs.
svsm
github_2023
others
50
coconut-svsm
joergroedel
@@ -0,0 +1,404 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::arch::{asm, global_asm}; +use core::mem::size_of; +use core::sync::atomic::{AtomicU32, Ordering}; + +use alloc::boxed::Box; + +use crate::address::{Address, PhysAddr, VirtAddr}; +use crate::cpu::idt::X86ExceptionContext; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::cpu::tsc::rdtsc; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::alloc::{allocate_pages, get_order}; +use crate::mm::pagetable::{get_init_pgtable_locked, PageTable, PageTableRef}; +use crate::mm::{ + virt_to_phys, PAGE_SIZE, PGTABLE_LVL3_IDX_PERCPU, SVSM_PERTASK_STACK_BASE, + SVSM_PERTASK_STACK_TOP, +}; +use crate::utils::zero_mem_region; + +use super::schedule::schedule; + +pub const INITIAL_TASK_ID: u32 = 1; + +const STACK_SIZE: usize = 65536; + +#[derive(PartialEq, Debug, Copy, Clone)] +pub enum TaskState { + RUNNING, + SCHEDULED, + TERMINATED, +} + +pub struct TaskStack { + pub virt_base: VirtAddr, + pub virt_top: VirtAddr, + pub phys: PhysAddr, +} + +pub const TASK_FLAG_SHARE_PT: u16 = 0x01; + +struct TaskIDAllocator { + next_id: AtomicU32, +} + +impl TaskIDAllocator { + fn next_id(&self) -> u32 { + let mut id = self.next_id.fetch_add(1, Ordering::Relaxed); + // Reserve IDs of 0 and 1 + while (id == 0_u32) || (id == INITIAL_TASK_ID) { + id = self.next_id.fetch_add(1, Ordering::Relaxed); + } + id + } +} + +static TASK_ID_ALLOCATOR: TaskIDAllocator = TaskIDAllocator { + next_id: AtomicU32::new(INITIAL_TASK_ID + 1), +}; + +/// This trait is used to implement the strategy that determines +/// how much CPU time a task has been allocated. The task with the +/// lowest runtime value is likely to be the next scheduled task +pub trait TaskRuntime { + /// Called when a task is allocated to a CPU just before the task + /// context is restored. The task should start tracking the CPU + /// execution allocation at this point. + fn schedule_in(&mut self); + + /// Called by the scheduler at the point the task is interrupted + /// and marked for deallocation from the CPU. The task should + /// update the runtime calculation at this point. + fn schedule_out(&mut self); + + /// Returns whether this is the first time a task has been + /// considered for scheduling. + fn first(&self) -> bool; + + /// Overrides the calculated runtime value with the given value. + /// This can be used to set or adjust the runtime of a task. + fn set(&mut self, runtime: u64); + + /// Flag the runtime as terminated so the scheduler does not + /// find terminated tasks before running tasks. + fn terminated(&mut self); + + /// Returns a value that represents the amount of CPU the task + /// has been allocated + fn value(&self) -> u64; +} + +/// Tracks task runtime based on the CPU timestamp counter +pub struct TscRuntime { + runtime: u64, +} + +impl TaskRuntime for TscRuntime { + fn schedule_in(&mut self) { + self.runtime = rdtsc(); + } + + fn schedule_out(&mut self) { + self.runtime += rdtsc() - self.runtime; + } + + fn first(&self) -> bool { + self.runtime == 0 + } + + fn set(&mut self, runtime: u64) { + self.runtime = runtime; + } + + fn terminated(&mut self) { + self.runtime = u64::MAX; + } + + fn value(&self) -> u64 { + self.runtime + } +} + +impl TscRuntime { + #[allow(unused)] + pub fn new() -> Self { + Self { runtime: 0 } + } +} + +/// Tracks task runtime based on the number of times the task has been +/// scheduled +pub struct CountRuntime { + count: u64, +} + +impl TaskRuntime for CountRuntime { + fn schedule_in(&mut self) { + self.count += 1; + } + + fn schedule_out(&mut self) {} + + fn first(&self) -> bool { + self.count == 0 + } + + fn set(&mut self, runtime: u64) { + self.count = runtime; + } + + fn terminated(&mut self) { + self.count = u64::MAX; + } + + fn value(&self) -> u64 { + self.count + } +} + +impl CountRuntime { + #[allow(unused)] + pub fn new() -> Self { + Self { count: 0 } + } +} + +// Define which runtime counter to use +type TaskRuntimeImpl = CountRuntime; + +#[repr(C)] +pub struct Task { + /// Current stack pointer for non-scheduled tasks. Restored to rsp + /// when the task is resumed + pub rsp: u64, + pub ss: u64, + + /// Context of task for non-scheduled tasks. + pub context: *mut X86ExceptionContext, + + /// Information about the task stack + pub stack: TaskStack, + + /// Page table that is loaded when the task is scheduled + pub page_table: SpinLock<PageTableRef>, + + /// Current state of the task + pub state: TaskState, + + /// Task affinity + /// None: The task can be scheduled to any CPU + /// u32: The APIC ID of the CPU that the task must run on + pub affinity: Option<u32>, + + /// ID of the task + pub id: u32, + + /// Amount of CPU resource the task has consumed + pub runtime: TaskRuntimeImpl, + + /// Next task in the task list + pub next: *mut Task, +} + +impl Task { + pub fn create(entry: extern "C" fn(), flags: u16) -> Result<Box<Task>, SvsmError> { + let mut pgtable = if (flags & TASK_FLAG_SHARE_PT) != 0 { + this_cpu().get_pgtable().clone_shared()? + } else { + Self::allocate_page_table()? + }; + + let (task_stack, rsp) = Self::allocate_stack(entry, &mut pgtable)?; + + let task: Box<Task> = Box::new(Task { + rsp: u64::from(rsp), + ss: 0, + context: core::ptr::null_mut(), + stack: task_stack, + page_table: SpinLock::new(pgtable), + state: TaskState::RUNNING, + affinity: None, + id: TASK_ID_ALLOCATOR.next_id(), + runtime: TaskRuntimeImpl::new(), + next: core::ptr::null_mut(), + }); + Ok(task) + } + + pub fn set_current(&mut self, previous_task: Option<*mut Task>) { + // This function is called by one task but returns in the context of + // another task. The context of the current task is saved and execution + // can resume at the point of the task switch, effectively completing + // the function call for the original task. + let previous_task_addr = match previous_task { + Some(t) => t as *const u64 as u64, + None => 0_u64, + }; + let new_task_addr = (self as *mut Task) as u64; + + // Keep track of when the new task was scheduled in + self.runtime.schedule_in(); + + // Switch to the new task + unsafe { + asm!( + r#" + int $0x20
Okay, as I understand this, the code switches a task via a software interrupt to simplify switching the contents of the GPRs. The GPRs are then stored/restored in/from the struct task. Can we instead write some assembly which stores the GPRs directly on the task stack, switches the stack pointer, and restores the GPRs? This would avoid the overhead of having a separate context store and the software IRQ.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use super::Task; +use super::{task::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::{boxed::Box, rc::Rc}; +use core::cell::{Ref, RefCell, RefMut}; +use core::ptr::null_mut; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub struct TaskNode { + link: RBTreeLink, + task_internal: RefCell<Box<Task>>, + id: u32, +} + +impl TaskNode { + pub fn task(&self) -> Ref<'_, Box<Task>> { + self.task_internal.borrow() + } + + pub fn task_mut(&self) -> RefMut<'_, Box<Task>> { + self.task_internal.borrow_mut() + } + + pub fn task_id(&self) -> u32 { + self.id + } +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + if self.tree.is_none() { + self.tree = Some(RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())); + } + self.tree.as_mut().unwrap()
This saves us an unwrap: ```rust self.tree.get_or_insert_with(|| RBTree::new(TaskNodeAdapter::new())) ```
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use super::Task; +use super::{task::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::{boxed::Box, rc::Rc}; +use core::cell::{Ref, RefCell, RefMut}; +use core::ptr::null_mut; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub struct TaskNode { + link: RBTreeLink, + task_internal: RefCell<Box<Task>>, + id: u32, +} + +impl TaskNode { + pub fn task(&self) -> Ref<'_, Box<Task>> { + self.task_internal.borrow() + } + + pub fn task_mut(&self) -> RefMut<'_, Box<Task>> { + self.task_internal.borrow_mut() + } + + pub fn task_id(&self) -> u32 { + self.id + } +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + if self.tree.is_none() { + self.tree = Some(RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())); + } + self.tree.as_mut().unwrap() + } + + pub fn get_task(&mut self, id: u32) -> Option<Rc<TaskNode>> { + let mut cursor = self.tree().front(); + while cursor.get().is_some() { + if cursor.get().unwrap().task().id == id { + return Some(cursor.clone_pointer().unwrap()); + } + cursor.move_next(); + } + None
This saves us an unwrap: ```rust let mut cursor = self.tree().front(); while let Some(node) = cursor.get() { if node.task().id == id { return Some(cursor.clone_pointer().unwrap()) } cursor.move_next(); } None ```
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,404 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::arch::{asm, global_asm}; +use core::mem::size_of; +use core::sync::atomic::{AtomicU32, Ordering}; + +use alloc::boxed::Box; + +use crate::address::{Address, PhysAddr, VirtAddr}; +use crate::cpu::idt::X86ExceptionContext; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::cpu::tsc::rdtsc; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::alloc::{allocate_pages, get_order}; +use crate::mm::pagetable::{get_init_pgtable_locked, PageTable, PageTableRef}; +use crate::mm::{ + virt_to_phys, PAGE_SIZE, PGTABLE_LVL3_IDX_PERCPU, SVSM_PERTASK_STACK_BASE, + SVSM_PERTASK_STACK_TOP, +}; +use crate::utils::zero_mem_region; + +use super::schedule::schedule; + +pub const INITIAL_TASK_ID: u32 = 1; + +const STACK_SIZE: usize = 65536; + +#[derive(PartialEq, Debug, Copy, Clone)] +pub enum TaskState { + RUNNING, + SCHEDULED, + TERMINATED, +} + +pub struct TaskStack { + pub virt_base: VirtAddr, + pub virt_top: VirtAddr, + pub phys: PhysAddr, +} + +pub const TASK_FLAG_SHARE_PT: u16 = 0x01; + +struct TaskIDAllocator { + next_id: AtomicU32, +} + +impl TaskIDAllocator { + fn next_id(&self) -> u32 { + let mut id = self.next_id.fetch_add(1, Ordering::Relaxed); + // Reserve IDs of 0 and 1 + while (id == 0_u32) || (id == INITIAL_TASK_ID) { + id = self.next_id.fetch_add(1, Ordering::Relaxed); + } + id + } +} + +static TASK_ID_ALLOCATOR: TaskIDAllocator = TaskIDAllocator { + next_id: AtomicU32::new(INITIAL_TASK_ID + 1), +}; + +/// This trait is used to implement the strategy that determines +/// how much CPU time a task has been allocated. The task with the +/// lowest runtime value is likely to be the next scheduled task +pub trait TaskRuntime { + /// Called when a task is allocated to a CPU just before the task + /// context is restored. The task should start tracking the CPU + /// execution allocation at this point. + fn schedule_in(&mut self); + + /// Called by the scheduler at the point the task is interrupted + /// and marked for deallocation from the CPU. The task should + /// update the runtime calculation at this point. + fn schedule_out(&mut self); + + /// Returns whether this is the first time a task has been + /// considered for scheduling. + fn first(&self) -> bool; + + /// Overrides the calculated runtime value with the given value. + /// This can be used to set or adjust the runtime of a task. + fn set(&mut self, runtime: u64); + + /// Flag the runtime as terminated so the scheduler does not + /// find terminated tasks before running tasks. + fn terminated(&mut self); + + /// Returns a value that represents the amount of CPU the task + /// has been allocated + fn value(&self) -> u64; +} + +/// Tracks task runtime based on the CPU timestamp counter +pub struct TscRuntime { + runtime: u64, +} + +impl TaskRuntime for TscRuntime { + fn schedule_in(&mut self) { + self.runtime = rdtsc(); + } + + fn schedule_out(&mut self) { + self.runtime += rdtsc() - self.runtime; + } + + fn first(&self) -> bool { + self.runtime == 0 + } + + fn set(&mut self, runtime: u64) { + self.runtime = runtime; + } + + fn terminated(&mut self) { + self.runtime = u64::MAX; + } + + fn value(&self) -> u64 { + self.runtime + } +} + +impl TscRuntime { + #[allow(unused)] + pub fn new() -> Self { + Self { runtime: 0 } + } +} + +/// Tracks task runtime based on the number of times the task has been +/// scheduled +pub struct CountRuntime { + count: u64, +} + +impl TaskRuntime for CountRuntime { + fn schedule_in(&mut self) { + self.count += 1; + } + + fn schedule_out(&mut self) {} + + fn first(&self) -> bool { + self.count == 0 + } + + fn set(&mut self, runtime: u64) { + self.count = runtime; + } + + fn terminated(&mut self) { + self.count = u64::MAX; + } + + fn value(&self) -> u64 { + self.count + } +} + +impl CountRuntime { + #[allow(unused)] + pub fn new() -> Self { + Self { count: 0 } + } +} + +// Define which runtime counter to use +type TaskRuntimeImpl = CountRuntime; + +#[repr(C)] +pub struct Task { + /// Current stack pointer for non-scheduled tasks. Restored to rsp + /// when the task is resumed + pub rsp: u64, + pub ss: u64, + + /// Context of task for non-scheduled tasks. + pub context: *mut X86ExceptionContext, + + /// Information about the task stack + pub stack: TaskStack, + + /// Page table that is loaded when the task is scheduled + pub page_table: SpinLock<PageTableRef>, + + /// Current state of the task + pub state: TaskState, + + /// Task affinity + /// None: The task can be scheduled to any CPU + /// u32: The APIC ID of the CPU that the task must run on + pub affinity: Option<u32>, + + /// ID of the task + pub id: u32, + + /// Amount of CPU resource the task has consumed + pub runtime: TaskRuntimeImpl, + + /// Next task in the task list + pub next: *mut Task, +} + +impl Task { + pub fn create(entry: extern "C" fn(), flags: u16) -> Result<Box<Task>, SvsmError> { + let mut pgtable = if (flags & TASK_FLAG_SHARE_PT) != 0 { + this_cpu().get_pgtable().clone_shared()? + } else { + Self::allocate_page_table()? + }; + + let (task_stack, rsp) = Self::allocate_stack(entry, &mut pgtable)?; + + let task: Box<Task> = Box::new(Task { + rsp: u64::from(rsp), + ss: 0, + context: core::ptr::null_mut(), + stack: task_stack, + page_table: SpinLock::new(pgtable), + state: TaskState::RUNNING, + affinity: None, + id: TASK_ID_ALLOCATOR.next_id(), + runtime: TaskRuntimeImpl::new(), + next: core::ptr::null_mut(), + }); + Ok(task) + } + + pub fn set_current(&mut self, previous_task: Option<*mut Task>) {
As before, `Option<*mut Task>` could perhaps be switched to `Option<NonNull<Task>>`, since we use `None` to signify null.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,230 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use super::Task; +use super::{task::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::{boxed::Box, rc::Rc}; +use core::cell::{Ref, RefCell, RefMut}; +use core::ptr::null_mut; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub struct TaskNode { + link: RBTreeLink, + task_internal: RefCell<Box<Task>>, + id: u32, +} + +impl TaskNode { + pub fn task(&self) -> Ref<'_, Box<Task>> { + self.task_internal.borrow() + } + + pub fn task_mut(&self) -> RefMut<'_, Box<Task>> { + self.task_internal.borrow_mut() + } + + pub fn task_id(&self) -> u32 { + self.id + } +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + if self.tree.is_none() { + self.tree = Some(RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())); + } + self.tree.as_mut().unwrap() + } + + pub fn get_task(&mut self, id: u32) -> Option<Rc<TaskNode>> { + let mut cursor = self.tree().front(); + while cursor.get().is_some() { + if cursor.get().unwrap().task().id == id { + return Some(cursor.clone_pointer().unwrap()); + } + cursor.move_next(); + } + None + } +} + +pub static TASKS: SpinLock<TaskRBTree> = SpinLock::new(TaskRBTree { tree: None }); + +/// +/// Each processor that is assigned to run tasks must call this function +/// before further tasks can be scheduled onto the CPU by schedule(). +/// +pub fn launch_initial_cpu_task(task_node: Rc<TaskNode>) -> Result<(), SvsmError> { + if this_cpu().current_task.is_some() { + return Err(SvsmError::Task); + } + // Restrict the scope of the mutable borrow below otherwise when the task context + // is switched via set_current() the borrow remains in scope. + let task_ptr = { + let mut task = task_node.task_mut(); + if task.state != TaskState::RUNNING { + panic!("Attempt to launch a non-running initial task"); + } + this_cpu_mut().current_task = Some(task_node.clone()); + task.state = TaskState::SCHEDULED; + task.as_mut() as *mut Task + }; + unsafe { (*task_ptr).set_current(None) };
Not a huge fan of this unsafe, I wonder if we could remove it. If `Task::set_current()` took `&self` instead of `&mut self` we could avoid it I think. There are two things that prevent this: 1. This line in `Task::set_current()`: ```rust let new_task_addr = (self as *mut Task) as u64; ``` But perhaps this could be `*const`? 2. The fact that `TaskRuntime::schedule_in()` takes `&mut self` (and therefore `CountRuntime::schedule_in()`. If we could make the trait signature take `&self` that would be great for this. For `CountRuntime` this is trivial, we simply need to use an `AtomicU64` instead of an `u64`: ```rust pub struct CountRuntime { count: AtomicU64, } impl TaskRuntime for CountRuntime { fn schedule_in(&self) { self.count.fetch_add(1, Ordering::SeqCst); } ... } ``` I'm unsure if we could use a more relaxed ordering though. For `TscRuntime` we could do the same via `AtomicU64::store()`
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,404 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::arch::{asm, global_asm}; +use core::mem::size_of; +use core::sync::atomic::{AtomicU32, Ordering}; + +use alloc::boxed::Box; + +use crate::address::{Address, PhysAddr, VirtAddr}; +use crate::cpu::idt::X86ExceptionContext; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::cpu::tsc::rdtsc; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::alloc::{allocate_pages, get_order}; +use crate::mm::pagetable::{get_init_pgtable_locked, PageTable, PageTableRef}; +use crate::mm::{ + virt_to_phys, PAGE_SIZE, PGTABLE_LVL3_IDX_PERCPU, SVSM_PERTASK_STACK_BASE, + SVSM_PERTASK_STACK_TOP, +}; +use crate::utils::zero_mem_region; + +use super::schedule::schedule; + +pub const INITIAL_TASK_ID: u32 = 1; + +const STACK_SIZE: usize = 65536; + +#[derive(PartialEq, Debug, Copy, Clone)] +pub enum TaskState { + RUNNING, + SCHEDULED, + TERMINATED, +} + +pub struct TaskStack { + pub virt_base: VirtAddr, + pub virt_top: VirtAddr, + pub phys: PhysAddr, +} + +pub const TASK_FLAG_SHARE_PT: u16 = 0x01; + +struct TaskIDAllocator { + next_id: AtomicU32, +} + +impl TaskIDAllocator { + fn next_id(&self) -> u32 { + let mut id = self.next_id.fetch_add(1, Ordering::Relaxed); + // Reserve IDs of 0 and 1 + while (id == 0_u32) || (id == INITIAL_TASK_ID) { + id = self.next_id.fetch_add(1, Ordering::Relaxed); + } + id + } +} + +static TASK_ID_ALLOCATOR: TaskIDAllocator = TaskIDAllocator { + next_id: AtomicU32::new(INITIAL_TASK_ID + 1), +}; + +/// This trait is used to implement the strategy that determines +/// how much CPU time a task has been allocated. The task with the +/// lowest runtime value is likely to be the next scheduled task +pub trait TaskRuntime { + /// Called when a task is allocated to a CPU just before the task + /// context is restored. The task should start tracking the CPU + /// execution allocation at this point. + fn schedule_in(&mut self); + + /// Called by the scheduler at the point the task is interrupted + /// and marked for deallocation from the CPU. The task should + /// update the runtime calculation at this point. + fn schedule_out(&mut self); + + /// Returns whether this is the first time a task has been + /// considered for scheduling. + fn first(&self) -> bool; + + /// Overrides the calculated runtime value with the given value. + /// This can be used to set or adjust the runtime of a task. + fn set(&mut self, runtime: u64); + + /// Flag the runtime as terminated so the scheduler does not + /// find terminated tasks before running tasks. + fn terminated(&mut self); + + /// Returns a value that represents the amount of CPU the task + /// has been allocated + fn value(&self) -> u64; +} + +/// Tracks task runtime based on the CPU timestamp counter +pub struct TscRuntime { + runtime: u64, +} + +impl TaskRuntime for TscRuntime { + fn schedule_in(&mut self) { + self.runtime = rdtsc(); + } + + fn schedule_out(&mut self) { + self.runtime += rdtsc() - self.runtime; + } + + fn first(&self) -> bool { + self.runtime == 0 + } + + fn set(&mut self, runtime: u64) { + self.runtime = runtime; + } + + fn terminated(&mut self) { + self.runtime = u64::MAX; + } + + fn value(&self) -> u64 { + self.runtime + } +} + +impl TscRuntime { + #[allow(unused)] + pub fn new() -> Self { + Self { runtime: 0 } + } +} + +/// Tracks task runtime based on the number of times the task has been +/// scheduled +pub struct CountRuntime { + count: u64, +}
Perhaps this should be `#[repr(transparent)]` so it's guaranteed that it doesn't affect the layout of `Task`, which is `#[repr(C)]`.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,404 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::arch::{asm, global_asm}; +use core::mem::size_of; +use core::sync::atomic::{AtomicU32, Ordering}; + +use alloc::boxed::Box; + +use crate::address::{Address, PhysAddr, VirtAddr}; +use crate::cpu::idt::X86ExceptionContext; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::cpu::tsc::rdtsc; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::alloc::{allocate_pages, get_order}; +use crate::mm::pagetable::{get_init_pgtable_locked, PageTable, PageTableRef}; +use crate::mm::{ + virt_to_phys, PAGE_SIZE, PGTABLE_LVL3_IDX_PERCPU, SVSM_PERTASK_STACK_BASE, + SVSM_PERTASK_STACK_TOP, +}; +use crate::utils::zero_mem_region; + +use super::schedule::schedule; + +pub const INITIAL_TASK_ID: u32 = 1; + +const STACK_SIZE: usize = 65536; + +#[derive(PartialEq, Debug, Copy, Clone)] +pub enum TaskState { + RUNNING, + SCHEDULED, + TERMINATED, +} + +pub struct TaskStack { + pub virt_base: VirtAddr, + pub virt_top: VirtAddr, + pub phys: PhysAddr, +} + +pub const TASK_FLAG_SHARE_PT: u16 = 0x01; + +struct TaskIDAllocator { + next_id: AtomicU32, +} + +impl TaskIDAllocator { + fn next_id(&self) -> u32 { + let mut id = self.next_id.fetch_add(1, Ordering::Relaxed); + // Reserve IDs of 0 and 1 + while (id == 0_u32) || (id == INITIAL_TASK_ID) { + id = self.next_id.fetch_add(1, Ordering::Relaxed); + } + id + } +} + +static TASK_ID_ALLOCATOR: TaskIDAllocator = TaskIDAllocator { + next_id: AtomicU32::new(INITIAL_TASK_ID + 1), +}; + +/// This trait is used to implement the strategy that determines +/// how much CPU time a task has been allocated. The task with the +/// lowest runtime value is likely to be the next scheduled task +pub trait TaskRuntime { + /// Called when a task is allocated to a CPU just before the task + /// context is restored. The task should start tracking the CPU + /// execution allocation at this point. + fn schedule_in(&mut self); + + /// Called by the scheduler at the point the task is interrupted + /// and marked for deallocation from the CPU. The task should + /// update the runtime calculation at this point. + fn schedule_out(&mut self); + + /// Returns whether this is the first time a task has been + /// considered for scheduling. + fn first(&self) -> bool; + + /// Overrides the calculated runtime value with the given value. + /// This can be used to set or adjust the runtime of a task. + fn set(&mut self, runtime: u64); + + /// Flag the runtime as terminated so the scheduler does not + /// find terminated tasks before running tasks. + fn terminated(&mut self); + + /// Returns a value that represents the amount of CPU the task + /// has been allocated + fn value(&self) -> u64; +} + +/// Tracks task runtime based on the CPU timestamp counter +pub struct TscRuntime { + runtime: u64, +} + +impl TaskRuntime for TscRuntime { + fn schedule_in(&mut self) { + self.runtime = rdtsc(); + } + + fn schedule_out(&mut self) { + self.runtime += rdtsc() - self.runtime; + } + + fn first(&self) -> bool { + self.runtime == 0 + } + + fn set(&mut self, runtime: u64) { + self.runtime = runtime; + } + + fn terminated(&mut self) { + self.runtime = u64::MAX; + } + + fn value(&self) -> u64 { + self.runtime + } +} + +impl TscRuntime { + #[allow(unused)] + pub fn new() -> Self { + Self { runtime: 0 } + } +} + +/// Tracks task runtime based on the number of times the task has been +/// scheduled +pub struct CountRuntime { + count: u64, +} + +impl TaskRuntime for CountRuntime { + fn schedule_in(&mut self) { + self.count += 1; + } + + fn schedule_out(&mut self) {} + + fn first(&self) -> bool { + self.count == 0 + } + + fn set(&mut self, runtime: u64) { + self.count = runtime; + } + + fn terminated(&mut self) { + self.count = u64::MAX; + } + + fn value(&self) -> u64 { + self.count + } +} + +impl CountRuntime { + #[allow(unused)] + pub fn new() -> Self { + Self { count: 0 } + } +} + +// Define which runtime counter to use +type TaskRuntimeImpl = CountRuntime; + +#[repr(C)] +pub struct Task { + /// Current stack pointer for non-scheduled tasks. Restored to rsp + /// when the task is resumed + pub rsp: u64, + pub ss: u64, + + /// Context of task for non-scheduled tasks. + pub context: *mut X86ExceptionContext, + + /// Information about the task stack + pub stack: TaskStack, + + /// Page table that is loaded when the task is scheduled + pub page_table: SpinLock<PageTableRef>, + + /// Current state of the task + pub state: TaskState, + + /// Task affinity + /// None: The task can be scheduled to any CPU + /// u32: The APIC ID of the CPU that the task must run on + pub affinity: Option<u32>, + + /// ID of the task + pub id: u32, + + /// Amount of CPU resource the task has consumed + pub runtime: TaskRuntimeImpl, + + /// Next task in the task list + pub next: *mut Task,
Unused, right?
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,214 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::cell::RefCell; + +use super::Task; +use super::{tasks::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::boxed::Box; +use alloc::rc::Rc; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub type TaskPointer = Rc<TaskNode>; + +pub struct TaskNode { + link: RBTreeLink, + pub task: RefCell<Box<Task>>, +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task.borrow().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + self.tree + .get_or_insert_with(|| RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())) + } + + pub fn get_task(&self, id: u32) -> Option<Rc<TaskNode>> { + let mut cursor = self.tree.as_ref().unwrap().front(); + while let Some(task_node) = cursor.get() { + if task_node.task.borrow().id == id { + return cursor.clone_pointer(); + } + cursor.move_next(); + } + None + } +} + +pub static TASKS: SpinLock<TaskRBTree> = SpinLock::new(TaskRBTree { tree: None }); + +/// +/// Each processor that is assigned to run tasks must call this function +/// before further tasks can be scheduled onto the CPU by schedule(). +/// +pub fn create_initial_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<(), SvsmError> { + if this_cpu().current_task.is_some() { + return Err(SvsmError::Task); + } + let task_node = create_task(entry, flags, affinity)?; + this_cpu_mut().current_task = Some(task_node.clone()); + + let task_ptr = { + let task_ptr = task_node.task.as_ptr(); + let mut task = task_node.task.borrow_mut(); + if task.state != TaskState::RUNNING { + panic!("Attempt to launch a non-running initial task"); + } + task.state = TaskState::SCHEDULED; + task_ptr + }; + unsafe { (*task_ptr).set_current(core::ptr::null_mut()) }; + Ok(()) +} + +pub fn create_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<TaskPointer, SvsmError> { + let mut task = Task::create(entry, flags)?; + task.set_affinity(affinity); + let node = Rc::new(TaskNode { + link: RBTreeLink::default(), + task: RefCell::new(task), + }); + let node_ret = node.clone(); + TASKS.lock().tree().insert(node); + Ok(node_ret) +} + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn close_task(task: TaskPointer) -> Result<(), SvsmError> { + // All tasks are protected via the task tree lock + let mut tl = TASKS.lock(); + let mut cursor = unsafe { + tl.tree() + .cursor_mut_from_ptr(task.as_ref() as *const TaskNode)
Just a nitpick, but the reference will automatically be coerced to a pointer, this would do: ``` tl.tree() .cursor_mut_from_ptr(task.as_ref()) ``` Or if you want to be more explicit: ``` tl.tree() .cursor_mut_from_ptr(Rc::as_ptr(&task)) ```
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,214 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::cell::RefCell; + +use super::Task; +use super::{tasks::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::boxed::Box; +use alloc::rc::Rc; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub type TaskPointer = Rc<TaskNode>; + +pub struct TaskNode { + link: RBTreeLink, + pub task: RefCell<Box<Task>>, +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task.borrow().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + self.tree + .get_or_insert_with(|| RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())) + } + + pub fn get_task(&self, id: u32) -> Option<Rc<TaskNode>> { + let mut cursor = self.tree.as_ref().unwrap().front(); + while let Some(task_node) = cursor.get() { + if task_node.task.borrow().id == id { + return cursor.clone_pointer(); + } + cursor.move_next(); + } + None + } +} + +pub static TASKS: SpinLock<TaskRBTree> = SpinLock::new(TaskRBTree { tree: None }); + +/// +/// Each processor that is assigned to run tasks must call this function +/// before further tasks can be scheduled onto the CPU by schedule(). +/// +pub fn create_initial_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<(), SvsmError> { + if this_cpu().current_task.is_some() { + return Err(SvsmError::Task); + } + let task_node = create_task(entry, flags, affinity)?; + this_cpu_mut().current_task = Some(task_node.clone()); + + let task_ptr = { + let task_ptr = task_node.task.as_ptr(); + let mut task = task_node.task.borrow_mut(); + if task.state != TaskState::RUNNING { + panic!("Attempt to launch a non-running initial task"); + } + task.state = TaskState::SCHEDULED; + task_ptr + }; + unsafe { (*task_ptr).set_current(core::ptr::null_mut()) }; + Ok(()) +} + +pub fn create_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<TaskPointer, SvsmError> { + let mut task = Task::create(entry, flags)?; + task.set_affinity(affinity); + let node = Rc::new(TaskNode { + link: RBTreeLink::default(), + task: RefCell::new(task), + }); + let node_ret = node.clone(); + TASKS.lock().tree().insert(node); + Ok(node_ret) +} + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn close_task(task: TaskPointer) -> Result<(), SvsmError> { + // All tasks are protected via the task tree lock + let mut tl = TASKS.lock(); + let mut cursor = unsafe { + tl.tree() + .cursor_mut_from_ptr(task.as_ref() as *const TaskNode) + }; + if cursor.get().is_none() + || (cursor.get().unwrap().task.borrow().state != TaskState::TERMINATED) + { + Err(SvsmError::Task) + } else { + cursor.remove().ok_or(SvsmError::Task).map(|_| ()) + }
We can get rid of the unwrap via `Option::filter()`: ```rust if cursor .get() .filter(|ptr| ptr.task.borrow().state == TaskState::TERMINATED) .is_none() { return Err(SvsmError::Task); }
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,214 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::cell::RefCell; + +use super::Task; +use super::{tasks::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::boxed::Box; +use alloc::rc::Rc; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub type TaskPointer = Rc<TaskNode>; + +pub struct TaskNode { + link: RBTreeLink, + pub task: RefCell<Box<Task>>, +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task.borrow().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + self.tree + .get_or_insert_with(|| RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())) + } + + pub fn get_task(&self, id: u32) -> Option<Rc<TaskNode>> { + let mut cursor = self.tree.as_ref().unwrap().front(); + while let Some(task_node) = cursor.get() { + if task_node.task.borrow().id == id { + return cursor.clone_pointer(); + } + cursor.move_next(); + } + None + } +} + +pub static TASKS: SpinLock<TaskRBTree> = SpinLock::new(TaskRBTree { tree: None }); + +/// +/// Each processor that is assigned to run tasks must call this function +/// before further tasks can be scheduled onto the CPU by schedule(). +/// +pub fn create_initial_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<(), SvsmError> { + if this_cpu().current_task.is_some() { + return Err(SvsmError::Task); + } + let task_node = create_task(entry, flags, affinity)?; + this_cpu_mut().current_task = Some(task_node.clone()); + + let task_ptr = { + let task_ptr = task_node.task.as_ptr(); + let mut task = task_node.task.borrow_mut(); + if task.state != TaskState::RUNNING { + panic!("Attempt to launch a non-running initial task"); + } + task.state = TaskState::SCHEDULED; + task_ptr + }; + unsafe { (*task_ptr).set_current(core::ptr::null_mut()) }; + Ok(()) +} + +pub fn create_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<TaskPointer, SvsmError> { + let mut task = Task::create(entry, flags)?; + task.set_affinity(affinity); + let node = Rc::new(TaskNode { + link: RBTreeLink::default(), + task: RefCell::new(task), + }); + let node_ret = node.clone(); + TASKS.lock().tree().insert(node); + Ok(node_ret) +} + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn close_task(task: TaskPointer) -> Result<(), SvsmError> { + // All tasks are protected via the task tree lock + let mut tl = TASKS.lock(); + let mut cursor = unsafe { + tl.tree() + .cursor_mut_from_ptr(task.as_ref() as *const TaskNode) + }; + if cursor.get().is_none() + || (cursor.get().unwrap().task.borrow().state != TaskState::TERMINATED) + { + Err(SvsmError::Task) + } else { + cursor.remove().ok_or(SvsmError::Task).map(|_| ()) + } +} + +/// Check to see if the task scheduled on the current processor has the given id +pub fn is_current_task(id: u32) -> bool { + match &this_cpu().current_task { + Some(current_task) => current_task.task.borrow().id == id, + None => id == INITIAL_TASK_ID, + } +} + +fn update_current_task(tree: &mut RBTree<TaskNodeAdapter>) -> TaskPointer { + // This function leaves the CPU in an invalid state as it takes the current + // task, replacing it with None. The caller must assign a new task or reassign + // the current task to the CPU before resuming. + let task_ptr = this_cpu_mut().current_task.take().unwrap(); + let mut task_cursor = unsafe { tree.cursor_mut_from_ptr(task_ptr.as_ref() as *const TaskNode) };
Same thing here about the reference to pointer coercion.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,214 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::cell::RefCell; + +use super::Task; +use super::{tasks::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::boxed::Box; +use alloc::rc::Rc; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub type TaskPointer = Rc<TaskNode>; + +pub struct TaskNode { + link: RBTreeLink, + pub task: RefCell<Box<Task>>, +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task.borrow().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + self.tree + .get_or_insert_with(|| RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())) + } + + pub fn get_task(&self, id: u32) -> Option<Rc<TaskNode>> { + let mut cursor = self.tree.as_ref().unwrap().front(); + while let Some(task_node) = cursor.get() { + if task_node.task.borrow().id == id { + return cursor.clone_pointer(); + } + cursor.move_next(); + } + None + } +} + +pub static TASKS: SpinLock<TaskRBTree> = SpinLock::new(TaskRBTree { tree: None }); + +/// +/// Each processor that is assigned to run tasks must call this function +/// before further tasks can be scheduled onto the CPU by schedule(). +/// +pub fn create_initial_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<(), SvsmError> { + if this_cpu().current_task.is_some() { + return Err(SvsmError::Task); + } + let task_node = create_task(entry, flags, affinity)?; + this_cpu_mut().current_task = Some(task_node.clone()); + + let task_ptr = { + let task_ptr = task_node.task.as_ptr(); + let mut task = task_node.task.borrow_mut(); + if task.state != TaskState::RUNNING { + panic!("Attempt to launch a non-running initial task"); + } + task.state = TaskState::SCHEDULED; + task_ptr + }; + unsafe { (*task_ptr).set_current(core::ptr::null_mut()) }; + Ok(()) +} + +pub fn create_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<TaskPointer, SvsmError> { + let mut task = Task::create(entry, flags)?; + task.set_affinity(affinity); + let node = Rc::new(TaskNode { + link: RBTreeLink::default(), + task: RefCell::new(task), + }); + let node_ret = node.clone(); + TASKS.lock().tree().insert(node); + Ok(node_ret) +} + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn close_task(task: TaskPointer) -> Result<(), SvsmError> { + // All tasks are protected via the task tree lock + let mut tl = TASKS.lock(); + let mut cursor = unsafe { + tl.tree() + .cursor_mut_from_ptr(task.as_ref() as *const TaskNode) + }; + if cursor.get().is_none() + || (cursor.get().unwrap().task.borrow().state != TaskState::TERMINATED) + { + Err(SvsmError::Task) + } else { + cursor.remove().ok_or(SvsmError::Task).map(|_| ()) + } +} + +/// Check to see if the task scheduled on the current processor has the given id +pub fn is_current_task(id: u32) -> bool { + match &this_cpu().current_task { + Some(current_task) => current_task.task.borrow().id == id, + None => id == INITIAL_TASK_ID, + } +} + +fn update_current_task(tree: &mut RBTree<TaskNodeAdapter>) -> TaskPointer { + // This function leaves the CPU in an invalid state as it takes the current + // task, replacing it with None. The caller must assign a new task or reassign + // the current task to the CPU before resuming. + let task_ptr = this_cpu_mut().current_task.take().unwrap(); + let mut task_cursor = unsafe { tree.cursor_mut_from_ptr(task_ptr.as_ref() as *const TaskNode) }; + assert!( + !task_cursor.is_null(), + "The current task is not in the task tree" + ); + let task_node = task_cursor.remove().unwrap();
This assert can be removed since the unwrap() already would cause a panic. You can use expect to add a message to the panic.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,214 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::cell::RefCell; + +use super::Task; +use super::{tasks::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::boxed::Box; +use alloc::rc::Rc; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub type TaskPointer = Rc<TaskNode>; + +pub struct TaskNode { + link: RBTreeLink, + pub task: RefCell<Box<Task>>, +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task.borrow().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + self.tree + .get_or_insert_with(|| RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())) + } + + pub fn get_task(&self, id: u32) -> Option<Rc<TaskNode>> { + let mut cursor = self.tree.as_ref().unwrap().front(); + while let Some(task_node) = cursor.get() { + if task_node.task.borrow().id == id { + return cursor.clone_pointer(); + } + cursor.move_next(); + } + None + } +} + +pub static TASKS: SpinLock<TaskRBTree> = SpinLock::new(TaskRBTree { tree: None }); + +/// +/// Each processor that is assigned to run tasks must call this function +/// before further tasks can be scheduled onto the CPU by schedule(). +/// +pub fn create_initial_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<(), SvsmError> { + if this_cpu().current_task.is_some() { + return Err(SvsmError::Task); + } + let task_node = create_task(entry, flags, affinity)?; + this_cpu_mut().current_task = Some(task_node.clone()); + + let task_ptr = { + let task_ptr = task_node.task.as_ptr(); + let mut task = task_node.task.borrow_mut(); + if task.state != TaskState::RUNNING { + panic!("Attempt to launch a non-running initial task"); + } + task.state = TaskState::SCHEDULED; + task_ptr + }; + unsafe { (*task_ptr).set_current(core::ptr::null_mut()) }; + Ok(()) +} + +pub fn create_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<TaskPointer, SvsmError> { + let mut task = Task::create(entry, flags)?; + task.set_affinity(affinity); + let node = Rc::new(TaskNode { + link: RBTreeLink::default(), + task: RefCell::new(task), + }); + let node_ret = node.clone(); + TASKS.lock().tree().insert(node); + Ok(node_ret) +} + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn close_task(task: TaskPointer) -> Result<(), SvsmError> { + // All tasks are protected via the task tree lock + let mut tl = TASKS.lock(); + let mut cursor = unsafe { + tl.tree() + .cursor_mut_from_ptr(task.as_ref() as *const TaskNode) + }; + if cursor.get().is_none() + || (cursor.get().unwrap().task.borrow().state != TaskState::TERMINATED) + { + Err(SvsmError::Task) + } else { + cursor.remove().ok_or(SvsmError::Task).map(|_| ()) + } +} + +/// Check to see if the task scheduled on the current processor has the given id +pub fn is_current_task(id: u32) -> bool { + match &this_cpu().current_task { + Some(current_task) => current_task.task.borrow().id == id, + None => id == INITIAL_TASK_ID, + } +} + +fn update_current_task(tree: &mut RBTree<TaskNodeAdapter>) -> TaskPointer { + // This function leaves the CPU in an invalid state as it takes the current + // task, replacing it with None. The caller must assign a new task or reassign + // the current task to the CPU before resuming. + let task_ptr = this_cpu_mut().current_task.take().unwrap(); + let mut task_cursor = unsafe { tree.cursor_mut_from_ptr(task_ptr.as_ref() as *const TaskNode) }; + assert!( + !task_cursor.is_null(), + "The current task is not in the task tree" + ); + let task_node = task_cursor.remove().unwrap(); + { + let mut task = task_node.task.borrow_mut(); + if task.state == TaskState::SCHEDULED { + task.state = TaskState::RUNNING; + } + + // If this is the first time the task is considered for scheduling then + // take the minimum value from the tree to ensure the new task is not + // allocated all of the CPU until it catches up. + if task.runtime.first() { + let cursor = tree.lower_bound(Bound::Included(&0)); + if let Some(t) = cursor.get() { + task.runtime.set(t.task.borrow().runtime.value()); + } + } + task.runtime.schedule_out(); + } + tree.insert(task_node); + task_ptr +} + +pub fn schedule() { + let (next_task, current_task) = { + let mut tl = TASKS.lock(); + + // Update the state of the current task. This will change the runtime value which + // is used as a key in the RB tree therefore we need to remove and reinsert the + // task. + let tree = tl.tree(); + let current_task_node = update_current_task(tree); + + // Find the task with the lowest runtime that is eligible to run + // on this CPU + let mut cursor = tree.lower_bound(Bound::Included(&0)); + while cursor.get().is_some() { + let candidate_task = cursor.get().unwrap().task.borrow();
We should use the `while let Some(node) = cursor.get()` construct we have in other places.
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,214 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::cell::RefCell; + +use super::Task; +use super::{tasks::TaskRuntime, TaskState, INITIAL_TASK_ID}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use alloc::boxed::Box; +use alloc::rc::Rc; +use intrusive_collections::{intrusive_adapter, Bound, KeyAdapter, RBTree, RBTreeLink}; + +pub type TaskPointer = Rc<TaskNode>; + +pub struct TaskNode { + link: RBTreeLink, + pub task: RefCell<Box<Task>>, +} + +intrusive_adapter!(pub TaskNodeAdapter = Rc<TaskNode>: TaskNode { link: RBTreeLink }); +impl<'a> KeyAdapter<'a> for TaskNodeAdapter { + type Key = u64; + fn get_key(&self, node: &'a TaskNode) -> u64 { + node.task.borrow().runtime.value() + } +} + +pub struct TaskRBTree { + tree: Option<RBTree<TaskNodeAdapter>>, +} + +impl TaskRBTree { + pub fn tree(&mut self) -> &mut RBTree<TaskNodeAdapter> { + self.tree + .get_or_insert_with(|| RBTree::<TaskNodeAdapter>::new(TaskNodeAdapter::new())) + } + + pub fn get_task(&self, id: u32) -> Option<Rc<TaskNode>> { + let mut cursor = self.tree.as_ref().unwrap().front(); + while let Some(task_node) = cursor.get() { + if task_node.task.borrow().id == id { + return cursor.clone_pointer(); + } + cursor.move_next(); + } + None + } +} + +pub static TASKS: SpinLock<TaskRBTree> = SpinLock::new(TaskRBTree { tree: None }); + +/// +/// Each processor that is assigned to run tasks must call this function +/// before further tasks can be scheduled onto the CPU by schedule(). +/// +pub fn create_initial_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<(), SvsmError> { + if this_cpu().current_task.is_some() { + return Err(SvsmError::Task); + } + let task_node = create_task(entry, flags, affinity)?; + this_cpu_mut().current_task = Some(task_node.clone()); + + let task_ptr = { + let task_ptr = task_node.task.as_ptr(); + let mut task = task_node.task.borrow_mut(); + if task.state != TaskState::RUNNING { + panic!("Attempt to launch a non-running initial task"); + } + task.state = TaskState::SCHEDULED; + task_ptr + }; + unsafe { (*task_ptr).set_current(core::ptr::null_mut()) }; + Ok(()) +} + +pub fn create_task( + entry: extern "C" fn(), + flags: u16, + affinity: Option<u32>, +) -> Result<TaskPointer, SvsmError> { + let mut task = Task::create(entry, flags)?; + task.set_affinity(affinity); + let node = Rc::new(TaskNode { + link: RBTreeLink::default(), + task: RefCell::new(task), + }); + let node_ret = node.clone(); + TASKS.lock().tree().insert(node); + Ok(node_ret) +} + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn close_task(task: TaskPointer) -> Result<(), SvsmError> { + // All tasks are protected via the task tree lock + let mut tl = TASKS.lock(); + let mut cursor = unsafe { + tl.tree() + .cursor_mut_from_ptr(task.as_ref() as *const TaskNode) + }; + if cursor.get().is_none() + || (cursor.get().unwrap().task.borrow().state != TaskState::TERMINATED) + { + Err(SvsmError::Task) + } else { + cursor.remove().ok_or(SvsmError::Task).map(|_| ()) + } +} + +/// Check to see if the task scheduled on the current processor has the given id +pub fn is_current_task(id: u32) -> bool { + match &this_cpu().current_task { + Some(current_task) => current_task.task.borrow().id == id, + None => id == INITIAL_TASK_ID, + } +} + +fn update_current_task(tree: &mut RBTree<TaskNodeAdapter>) -> TaskPointer { + // This function leaves the CPU in an invalid state as it takes the current + // task, replacing it with None. The caller must assign a new task or reassign + // the current task to the CPU before resuming. + let task_ptr = this_cpu_mut().current_task.take().unwrap(); + let mut task_cursor = unsafe { tree.cursor_mut_from_ptr(task_ptr.as_ref() as *const TaskNode) }; + assert!( + !task_cursor.is_null(), + "The current task is not in the task tree" + ); + let task_node = task_cursor.remove().unwrap(); + { + let mut task = task_node.task.borrow_mut(); + if task.state == TaskState::SCHEDULED { + task.state = TaskState::RUNNING; + } + + // If this is the first time the task is considered for scheduling then + // take the minimum value from the tree to ensure the new task is not + // allocated all of the CPU until it catches up. + if task.runtime.first() { + let cursor = tree.lower_bound(Bound::Included(&0)); + if let Some(t) = cursor.get() { + task.runtime.set(t.task.borrow().runtime.value()); + } + } + task.runtime.schedule_out(); + } + tree.insert(task_node); + task_ptr +} + +pub fn schedule() { + let (next_task, current_task) = { + let mut tl = TASKS.lock(); + + // Update the state of the current task. This will change the runtime value which + // is used as a key in the RB tree therefore we need to remove and reinsert the + // task. + let tree = tl.tree(); + let current_task_node = update_current_task(tree); + + // Find the task with the lowest runtime that is eligible to run + // on this CPU + let mut cursor = tree.lower_bound(Bound::Included(&0)); + while cursor.get().is_some() { + let candidate_task = cursor.get().unwrap().task.borrow(); + // If the runtime of the candidate task is greater than the task that was + // current running on the CPU then don't switch + if candidate_task.state == TaskState::RUNNING + && (candidate_task.affinity.is_none() + || (candidate_task.affinity.unwrap() == this_cpu().get_apic_id()))
We can use `Option::filter()` here as well to avoid the unwrap. Or as an alternative, we can use `map()` + `unwrap_or()`: ```rust if candidate_task.state == TaskState::RUNNING && candidate_task .affinity .map(|af| af == this_cpu().get_apic_id()) .unwrap_or(true) { break; } ```
svsm
github_2023
others
50
coconut-svsm
00xc
@@ -0,0 +1,400 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::arch::{asm, global_asm}; +use core::mem::size_of; +use core::sync::atomic::{AtomicU32, Ordering}; + +use alloc::boxed::Box; + +use crate::address::{Address, PhysAddr, VirtAddr}; +use crate::cpu::msr::{rdtsc, read_flags}; +use crate::cpu::percpu::{this_cpu, this_cpu_mut}; +use crate::cpu::{X86GeneralRegs, X86SegmentRegs}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::alloc::{allocate_pages, get_order}; +use crate::mm::pagetable::{get_init_pgtable_locked, PageTable, PageTableRef}; +use crate::mm::{ + virt_to_phys, PAGE_SIZE, PGTABLE_LVL3_IDX_PERCPU, SVSM_PERTASK_STACK_BASE, + SVSM_PERTASK_STACK_TOP, +}; +use crate::utils::zero_mem_region; + +use super::schedule::schedule; + +pub const INITIAL_TASK_ID: u32 = 1; + +const STACK_SIZE: usize = 65536; + +#[derive(PartialEq, Debug, Copy, Clone)] +pub enum TaskState { + RUNNING, + SCHEDULED, + TERMINATED, +} + +pub struct TaskStack { + pub virt_base: VirtAddr, + pub virt_top: VirtAddr, + pub phys: PhysAddr, +} + +pub const TASK_FLAG_SHARE_PT: u16 = 0x01; + +struct TaskIDAllocator { + next_id: AtomicU32, +} + +impl TaskIDAllocator { + fn next_id(&self) -> u32 { + let mut id = self.next_id.fetch_add(1, Ordering::Relaxed); + // Reserve IDs of 0 and 1 + while (id == 0_u32) || (id == INITIAL_TASK_ID) { + id = self.next_id.fetch_add(1, Ordering::Relaxed); + } + id + } +} + +static TASK_ID_ALLOCATOR: TaskIDAllocator = TaskIDAllocator { + next_id: AtomicU32::new(INITIAL_TASK_ID + 1),
Maybe we should have this as `TaskIdAllocator::new()`.
svsm
github_2023
others
61
coconut-svsm
00xc
@@ -37,3 +37,30 @@ pub fn write_msr(msr: u32, val: u64) { options(att_syntax)); } } + +pub fn rdtsc() -> u64 { + let eax: u32; + let edx: u32; + + unsafe { + asm!("rdtsc", + out("eax") eax, + out("edx") edx, + options(att_syntax));
We can add `nomem, nostack` to `options()` to help the compiler a bit.
svsm
github_2023
others
61
coconut-svsm
joergroedel
@@ -0,0 +1,404 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +extern crate alloc; + +use core::arch::{asm, global_asm}; +use core::fmt; +use core::mem::size_of; +use core::sync::atomic::{AtomicU32, Ordering}; + +use alloc::boxed::Box; + +use crate::address::{Address, PhysAddr, VirtAddr}; +use crate::cpu::msr::{rdtsc, read_flags}; +use crate::cpu::percpu::this_cpu; +use crate::cpu::{X86GeneralRegs, X86SegmentRegs}; +use crate::error::SvsmError; +use crate::locking::SpinLock; +use crate::mm::alloc::{allocate_pages, get_order}; +use crate::mm::pagetable::{get_init_pgtable_locked, PageTable, PageTableRef}; +use crate::mm::{ + virt_to_phys, PAGE_SIZE, PGTABLE_LVL3_IDX_PERCPU, SVSM_PERTASK_STACK_BASE, + SVSM_PERTASK_STACK_TOP, +}; +use crate::utils::zero_mem_region; + +pub const INITIAL_TASK_ID: u32 = 1; + +const STACK_SIZE: usize = 65536; + +#[derive(PartialEq, Debug, Copy, Clone)] +pub enum TaskState { + RUNNING, + SCHEDULED, + TERMINATED, +} + +#[derive(Debug)] +pub struct TaskStack { + pub virt_base: VirtAddr, + pub virt_top: VirtAddr, + pub phys: PhysAddr, +} + +pub const TASK_FLAG_SHARE_PT: u16 = 0x01; + +struct TaskIDAllocator { + next_id: AtomicU32, +} + +impl TaskIDAllocator { + const fn new() -> Self { + Self { + next_id: AtomicU32::new(INITIAL_TASK_ID + 1), + } + } + + fn next_id(&self) -> u32 { + let mut id = self.next_id.fetch_add(1, Ordering::Relaxed); + // Reserve IDs of 0 and 1 + while (id == 0_u32) || (id == INITIAL_TASK_ID) { + id = self.next_id.fetch_add(1, Ordering::Relaxed); + } + id + } +} + +static TASK_ID_ALLOCATOR: TaskIDAllocator = TaskIDAllocator::new(); + +/// This trait is used to implement the strategy that determines +/// how much CPU time a task has been allocated. The task with the +/// lowest runtime value is likely to be the next scheduled task +pub trait TaskRuntime { + /// Called when a task is allocated to a CPU just before the task + /// context is restored. The task should start tracking the CPU + /// execution allocation at this point. + fn schedule_in(&mut self); + + /// Called by the scheduler at the point the task is interrupted + /// and marked for deallocation from the CPU. The task should + /// update the runtime calculation at this point. + fn schedule_out(&mut self); + + /// Returns whether this is the first time a task has been + /// considered for scheduling. + fn first(&self) -> bool; + + /// Overrides the calculated runtime value with the given value. + /// This can be used to set or adjust the runtime of a task. + fn set(&mut self, runtime: u64); + + /// Flag the runtime as terminated so the scheduler does not + /// find terminated tasks before running tasks. + fn terminated(&mut self); + + /// Returns a value that represents the amount of CPU the task + /// has been allocated + fn value(&self) -> u64; +} + +/// Tracks task runtime based on the CPU timestamp counter +#[derive(Default, Debug)] +#[repr(transparent)] +pub struct TscRuntime { + runtime: u64, +} + +impl TaskRuntime for TscRuntime { + fn schedule_in(&mut self) { + self.runtime = rdtsc(); + } + + fn schedule_out(&mut self) { + self.runtime += rdtsc() - self.runtime; + } + + fn first(&self) -> bool { + self.runtime == 0 + } + + fn set(&mut self, runtime: u64) { + self.runtime = runtime; + } + + fn terminated(&mut self) { + self.runtime = u64::MAX; + } + + fn value(&self) -> u64 { + self.runtime + } +} + +/// Tracks task runtime based on the number of times the task has been +/// scheduled +#[derive(Default, Debug)] +#[repr(transparent)] +pub struct CountRuntime { + count: u64, +} + +impl TaskRuntime for CountRuntime { + fn schedule_in(&mut self) { + self.count += 1; + } + + fn schedule_out(&mut self) {} + + fn first(&self) -> bool { + self.count == 0 + } + + fn set(&mut self, runtime: u64) { + self.count = runtime; + } + + fn terminated(&mut self) { + self.count = u64::MAX; + } + + fn value(&self) -> u64 { + self.count + } +} + +// Define which runtime counter to use +type TaskRuntimeImpl = CountRuntime; + +#[repr(C)] +#[derive(Default, Debug)] +pub struct TaskContext { + pub seg: X86SegmentRegs, + pub regs: X86GeneralRegs, + pub flags: u64, + pub ret_addr: u64, +} + +#[repr(C)] +pub struct Task { + pub rsp: u64, + + /// Information about the task stack + pub stack: TaskStack, + + /// Page table that is loaded when the task is scheduled + pub page_table: SpinLock<PageTableRef>, + + /// Current state of the task + pub state: TaskState, + + /// Task affinity + /// None: The task can be scheduled to any CPU + /// u32: The APIC ID of the CPU that the task must run on + pub affinity: Option<u32>, + + /// ID of the task + pub id: u32, + + /// Amount of CPU resource the task has consumed + pub runtime: TaskRuntimeImpl, +} + +impl fmt::Debug for Task { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Task") + .field("rsp", &self.rsp) + .field("stack", &self.stack) + .field("state", &self.state) + .field("affinity", &self.affinity) + .field("id", &self.id) + .field("runtime", &self.runtime) + .finish() + } +} + +impl Task { + pub fn create(entry: extern "C" fn(), flags: u16) -> Result<Box<Task>, SvsmError> { + let mut pgtable = if (flags & TASK_FLAG_SHARE_PT) != 0 { + this_cpu().get_pgtable().clone_shared()? + } else { + Self::allocate_page_table()? + }; + + let (task_stack, rsp) = Self::allocate_stack(entry, &mut pgtable)?; + + let task: Box<Task> = Box::new(Task { + rsp: u64::from(rsp), + stack: task_stack, + page_table: SpinLock::new(pgtable), + state: TaskState::RUNNING, + affinity: None, + id: TASK_ID_ALLOCATOR.next_id(), + runtime: TaskRuntimeImpl::default(), + }); + Ok(task) + } + + pub fn set_current(&mut self, previous_task: *mut Task) { + // This function is called by one task but returns in the context of + // another task. The context of the current task is saved and execution + // can resume at the point of the task switch, effectively completing + // the function call for the original task. + let new_task_addr = (self as *mut Task) as u64; + + // Switch to the new task + unsafe { + asm!( + r#" + call switch_context + "#, + in("rsi") previous_task as u64, + in("rdi") new_task_addr, + options(att_syntax)); + } + } + + pub fn set_affinity(&mut self, affinity: Option<u32>) { + self.affinity = affinity; + } + + fn allocate_stack( + entry: extern "C" fn(), + pgtable: &mut PageTableRef, + ) -> Result<(TaskStack, VirtAddr), SvsmError> { + let stack_size = SVSM_PERTASK_STACK_TOP - SVSM_PERTASK_STACK_BASE; + let num_pages = 1 << get_order(STACK_SIZE); + assert!(stack_size == num_pages * PAGE_SIZE); + let pages = allocate_pages(get_order(STACK_SIZE))?; + zero_mem_region(pages, pages + stack_size); + + let task_stack = TaskStack { + virt_base: VirtAddr::from(SVSM_PERTASK_STACK_BASE), + virt_top: VirtAddr::from(SVSM_PERTASK_STACK_TOP), + phys: virt_to_phys(pages), + }; + + // We current have a virtual address in SVSM shared memory for the stack. Configure + // the per-task pagetable to map the stack into the task memory map. + pgtable.map_region_4k( + task_stack.virt_base, + task_stack.virt_top, + task_stack.phys, + PageTable::task_data_flags(), + )?; + + // We need to setup a context on the stack that matches the stack layout + // defined in switch_context below. + let stack_pos = pages + stack_size; + let stack_ptr: *mut u64 = stack_pos.as_mut_ptr(); + + // 'Push' the task frame onto the stack + unsafe { + // flags + stack_ptr.offset(-3).write(read_flags()); + // ret_addr + stack_ptr.offset(-2).write(entry as *const () as u64); + // Task termination handler for when entry point returns + stack_ptr.offset(-1).write(task_exit as *const () as u64); + } + + let initial_rsp = + VirtAddr::from(SVSM_PERTASK_STACK_TOP - (size_of::<TaskContext>() + size_of::<u64>())); + Ok((task_stack, initial_rsp)) + } + + fn allocate_page_table() -> Result<PageTableRef, SvsmError> { + // Base the new task page table on the initial SVSM kernel page table. + // When the pagetable is schedule to a CPU, the per CPU entry will also + // be added to the pagetable. + get_init_pgtable_locked().clone_shared() + } +} + +extern "C" fn task_exit() { + panic!("Current task has exited"); +} + +#[allow(unused)] +#[no_mangle] +extern "C" fn apply_new_context(new_task: *mut Task) -> u64 { + unsafe { + let mut pt = (*new_task).page_table.lock(); + pt.copy_entry(&this_cpu().get_pgtable(), PGTABLE_LVL3_IDX_PERCPU); + pt.cr3_value().bits() as u64 + } +} + +global_asm!( + r#" + .text + + switch_context: + // Save the current context. The layout must match the TaskContext structure. + pushfq + pushq %rax + pushq %rbx + pushq %rcx + pushq %rdx + pushq %rsi + pushq %rdi + pushq %rbp + pushq %r8 + pushq %r9 + pushq %r10 + pushq %r11 + pushq %r12 + pushq %r13 + pushq %r14 + pushq %r15 + + movq %ss, %rax + pushq %rax + movq %gs, %rax + pushq %rax + movq %fs, %rax + pushq %rax + movq %es, %rax + pushq %rax + movq %ds, %rax + pushq %rax + movq %cs, %rax + pushq %rax
No need to save and restore the segment selectors, as we are switching between SVSM kernel tasks here and they will all run with the same segments. User-space segment switches will happen in the entry/exit code.
svsm
github_2023
others
24
coconut-svsm
joergroedel
@@ -0,0 +1,111 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 SUSE LLC +// +// Author: Roy Hopkins <rhopkins@suse.de> + +use crate::types::{VirtAddr, PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M, PAGE_SHIFT_2M}; +use crate::locking::SpinLock; +use crate::error::SvsmError; +use crate::utils::bitmap_allocator::{BitmapAllocator1024, BitmapAllocator}; + +use super::{SVSM_PERCPU_TEMP_BASE_4K, SVSM_PERCPU_TEMP_END_4K, SVSM_PERCPU_TEMP_BASE_2M, SVSM_PERCPU_TEMP_END_2M}; + +pub const VIRT_ALIGN_4K: usize = PAGE_SHIFT - 12; +pub const VIRT_ALIGN_2M: usize = PAGE_SHIFT_2M - 12; + +pub struct VirtualRange { + start_virt: VirtAddr, + page_count: usize, + bits: BitmapAllocator1024, +} + +impl VirtualRange { + pub const fn new() -> VirtualRange { + VirtualRange { + start_virt: 0, + page_count: 0, + bits: BitmapAllocator1024::new() + } + } + + pub fn map_pages(self: &mut Self, page_count: usize, alignment: usize) -> Result<VirtAddr, SvsmError> { + // Always reserve an extra page to leave a guard between virtual memory allocations + match self.bits.alloc(page_count + 1, alignment) { + Some(offset) => Ok(self.start_virt + (offset << PAGE_SHIFT)), + None => Err(SvsmError::Mem) + } + } + + pub fn unmap_pages(self: &mut Self, vaddr: VirtAddr, page_count: usize) { + let offset = (vaddr - self.start_virt) >> PAGE_SHIFT; + // Add 1 to the page count for the VM guard + self.bits.free(offset, page_count + 1); + } + + pub fn used_pages(&self) -> usize { + self.bits.used() + } +} + +static VIRTUAL_MAP_4K: SpinLock<VirtualRange> = SpinLock::new(VirtualRange::new()); +static VIRTUAL_MAP_2M: SpinLock<VirtualRange> = SpinLock::new(VirtualRange::new()); + +pub fn virt_range_init() { + let mut pm4k = VIRTUAL_MAP_4K.lock(); + let page_count = (SVSM_PERCPU_TEMP_END_4K - SVSM_PERCPU_TEMP_BASE_4K) / PAGE_SIZE; + if page_count > BitmapAllocator1024::CAPACITY { + panic!("Attempted to allocate page map with more than 4K pages"); + } + pm4k.start_virt = SVSM_PERCPU_TEMP_BASE_4K; + pm4k.page_count = page_count; + pm4k.bits.set(0, page_count, false); + + let mut pm2m = VIRTUAL_MAP_2M.lock(); + let page_count = (SVSM_PERCPU_TEMP_END_2M - SVSM_PERCPU_TEMP_BASE_2M) / PAGE_SIZE_2M; + if page_count > BitmapAllocator1024::CAPACITY { + panic!("Attempted to allocate page map with more than 4K pages");
This panic message is the same as above. Can you please add the page-size to each message to make it clear for which size the allocation failed?
svsm
github_2023
others
24
coconut-svsm
joergroedel
@@ -0,0 +1,493 @@ +
Please add a copyright header to each new file.
svsm
github_2023
others
24
coconut-svsm
joergroedel
@@ -0,0 +1,493 @@ + + +pub trait BitmapAllocator { + const CAPACITY: usize; + + fn alloc(&mut self, entries: usize, align: usize) -> Option<usize>; + fn free(&mut self, start: usize, entries: usize); + + fn set(&mut self, start: usize, entries: usize, value: bool); + fn next_free(&self, start: usize) -> Option<usize>; + fn get(&self, offset: usize) -> bool; + fn empty(&self) -> bool; + fn capacity(&self) -> usize; + fn used(&self) -> usize; +} + +pub type BitmapAllocator1024 = BitmapAllocatorTree::<BitmapAllocator64>; + +pub struct BitmapAllocator64 { + bits: u64 +} + +impl BitmapAllocator64 { + pub const fn new() -> Self { + Self { bits: u64::MAX } + } +} + +impl BitmapAllocator for BitmapAllocator64 { + const CAPACITY: usize = u64::BITS as usize; + + fn alloc(&mut self, entries: usize, align: usize) -> Option<usize> { + alloc_aligned(self, entries, align) + } + + fn free(&mut self, start: usize, entries: usize) { + self.set(start, entries, false); + } + + fn set(&mut self, start: usize, entries: usize, value: bool) { + assert!((start + entries) <= BitmapAllocator64::CAPACITY); + // Create a mask for changing the bitmap + let start_mask = !((1 << start) - 1); + // Need to do some bit shifting to avoid overflow when top bit set + let end_mask = (((1 << (start + entries - 1)) - 1) << 1) + 1; + let mask = start_mask & end_mask; + + if value { + self.bits |= mask; + } else { + self.bits &= !mask; + } + } + + fn next_free(&self, start: usize) -> Option<usize> { + assert!(start < BitmapAllocator64::CAPACITY); + for offset in start..BitmapAllocator64::CAPACITY { + if ((1 << offset) & self.bits) == 0 { + return Some(offset); + } + } + None + } + + fn get(&self, offset: usize) -> bool { + assert!(offset < BitmapAllocator64::CAPACITY); + return (self.bits & (1 << offset)) != 0
The 'return' is not needed.
svsm
github_2023
others
24
coconut-svsm
joergroedel
@@ -0,0 +1,493 @@ + + +pub trait BitmapAllocator { + const CAPACITY: usize; + + fn alloc(&mut self, entries: usize, align: usize) -> Option<usize>; + fn free(&mut self, start: usize, entries: usize); + + fn set(&mut self, start: usize, entries: usize, value: bool); + fn next_free(&self, start: usize) -> Option<usize>; + fn get(&self, offset: usize) -> bool; + fn empty(&self) -> bool; + fn capacity(&self) -> usize; + fn used(&self) -> usize; +} + +pub type BitmapAllocator1024 = BitmapAllocatorTree::<BitmapAllocator64>; + +pub struct BitmapAllocator64 { + bits: u64 +} + +impl BitmapAllocator64 { + pub const fn new() -> Self { + Self { bits: u64::MAX } + } +} + +impl BitmapAllocator for BitmapAllocator64 { + const CAPACITY: usize = u64::BITS as usize; + + fn alloc(&mut self, entries: usize, align: usize) -> Option<usize> { + alloc_aligned(self, entries, align) + } + + fn free(&mut self, start: usize, entries: usize) { + self.set(start, entries, false); + } + + fn set(&mut self, start: usize, entries: usize, value: bool) { + assert!((start + entries) <= BitmapAllocator64::CAPACITY); + // Create a mask for changing the bitmap + let start_mask = !((1 << start) - 1); + // Need to do some bit shifting to avoid overflow when top bit set + let end_mask = (((1 << (start + entries - 1)) - 1) << 1) + 1; + let mask = start_mask & end_mask; + + if value { + self.bits |= mask; + } else { + self.bits &= !mask; + } + } + + fn next_free(&self, start: usize) -> Option<usize> { + assert!(start < BitmapAllocator64::CAPACITY); + for offset in start..BitmapAllocator64::CAPACITY { + if ((1 << offset) & self.bits) == 0 { + return Some(offset); + } + } + None + } + + fn get(&self, offset: usize) -> bool { + assert!(offset < BitmapAllocator64::CAPACITY); + return (self.bits & (1 << offset)) != 0 + } + + fn empty(&self) -> bool { + return self.bits == 0;
'return' and semicolon are not needed.
svsm
github_2023
others
43
coconut-svsm
joergroedel
@@ -81,8 +81,8 @@ kernel_elf_end: kernel_fs_bin: .incbin "stage1/svsm-fs.bin" - .align 4
Right, that was my mistake. Thanks for fixing that.
svsm
github_2023
others
57
coconut-svsm
stefano-garzarella
@@ -41,3 +41,9 @@ jobs: with: command: fmt args: --all -- --check + + - name: Clippy + uses: actions-rs/cargo@v1 + with: + command: clippy + args: --all-features -- -D warnings
What about adding `--locked` ? In this way, we will have an error if `Cargo.lock` is not updated
svsm
github_2023
others
45
coconut-svsm
00xc
@@ -239,6 +240,32 @@ fn core_pvalidate_one(entry: u64, flush: &mut bool) -> Result<(), SvsmReqError> })?; if valid { + // Zero out a page when it is validated and before giving other VMPLs + // access to it. This is necessary to prevent a possible HV attack: + // + // Attack scenario: + // 1) SVSM stores secrets in VMPL0 memory at GPA A + // 2) HV invalidates GPA A and maps the SPA to GPA B, which is in the + // OS range of GPAs + // 3) Guest OS asks SVSM to validate GPA B + // 4) SVSM validates page and gives OS access + // 5) OS can now read SVSM secrets from GPA B + // + // The SVSM will not notice the attack until it tries to access GPA A + // again. Prevent it by clearing every page before giving access to + // other VMPLs. + // + // Be careful to not clear GPAs which the HV might have mapped + // read-only, as the write operation might cause infinite #NPF loops. + // + // Special thanks to Tom Lendacky for reporting the issue and tracking + // down the #NPF loops. + // + if writable_phys_addr(paddr) { + zero_mem_region(vaddr, vaddr + page_size_bytes); + } else { + log::warn!("Not clearing possible read-only page at PA {:#x}", paddr); + }
Is there a valid reason for a guest OS to ask the SVSM for access to the ISA range?
svsm
github_2023
others
2
coconut-svsm
nicstange
@@ -102,7 +118,7 @@ impl<T: Copy> Deref for ImmutAfterInitCell<T> { /// Dereference the wrapped value. Must **only ever** get called on an /// initialized instance! fn deref(&self) -> &T { - unsafe { (&*self.data.get()).assume_init_ref() } + unsafe { self.as_ref() }.unwrap()
Would it perhaps make sense to restrict this misuse tracking to debug builds only? Because there are some values wrapped in `ImmutAfterInitCell<>` whose accesses might be performance-sensitive, like `ENCRYPT_MASK`.
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -75,6 +76,22 @@ impl<const N: usize> PartialEq<&str> for FixedString<N> { } } +impl<const N: usize> PartialEq<FixedString<N>> for FixedString<N> { + fn eq(&self, other: &FixedString<N>) -> bool { + if self.len != other.len { + return false; + } + + for i in 0..self.len { + if self.data[i] != other.data[i] {
An iterator would be more conventional here. Something like: ```rust for (a, b) in self.data.iter().zip(&other.data).take(self.len) { ... } ``` Or even: ```rust self.data .iter() .zip(&other.data) .take(self.len) .all(|(a, b)| *a == *b) ```
svsm
github_2023
others
27
coconut-svsm
00xc
@@ -0,0 +1,411 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2023 SUSE LLC +// +// Author: Joerg Roedel <jroedel@suse.de> + +use super::ramfs::RamDirectory; +use super::*; + +use crate::error::SvsmError; +use crate::locking::SpinLock; + +use core::cmp::min; + +extern crate alloc; +use alloc::sync::Arc; +use alloc::vec::Vec; + +struct RawFileHandle { + file: Arc<dyn File>, + current: usize, +} + +impl RawFileHandle { + pub fn new(file: &Arc<dyn File>) -> Self { + RawFileHandle { + file: file.clone(), + current: 0, + } + } + + pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, SvsmError> { + let result = self.file.read(buf, self.current); + if result.is_ok() { + self.current += result.unwrap(); + }
Instead of checking via `is_ok()` and then unwrapping one can do: ```rust if let Ok(result) = self.file.read(buf, self.current) { self.current += result; } ```