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
272
coconut-svsm
00xc
@@ -677,32 +930,65 @@ impl PageTable { static INIT_PGTABLE: SpinLock<PageTableRef> = SpinLock::new(PageTableRef::unset()); +/// Sets the initial page table unless it is already set. +/// +/// # Parameters +/// - `pgtable`: The page table reference to set as the initial page table. +/// +/// # Panics +/// Panics if...
The function signature here is pretty self-explanatory, I'd remove the `# Returns`.
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -677,32 +930,65 @@ impl PageTable { static INIT_PGTABLE: SpinLock<PageTableRef> = SpinLock::new(PageTableRef::unset()); +/// Sets the initial page table unless it is already set. +/// +/// # Parameters +/// - `pgtable`: The page table reference to set as the initial page table. +/// +/// # Panics +/// Panics if...
The function signature here is pretty self-explanatory. ```suggestion /// Creates a new [`PageTableRef`] from a raw pointer to a [`PageTable`]. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -677,32 +930,65 @@ impl PageTable { static INIT_PGTABLE: SpinLock<PageTableRef> = SpinLock::new(PageTableRef::unset()); +/// Sets the initial page table unless it is already set. +/// +/// # Parameters +/// - `pgtable`: The page table reference to set as the initial page table. +/// +/// # Panics +/// Panics if...
The text already explains the return, so I'd remove the `# Returns` section.
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -663,6 +911,11 @@ impl PageTable { } } + /// Populates a part of the page table with the specified attributes. + /// + /// # Parameters + /// - `part`: The part of the page table to populate. + ///
```suggestion /// Populates this page table with the contents of the given subtree in `part`. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -640,6 +883,11 @@ impl PageTable { Ok(()) } + /// Unmaps a memory region. + /// + /// # Parameters + /// - `vregion`: The virtual memory region to unmap. + ///
```suggestion /// Unmaps the virtual memory region `vregion`. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -605,12 +833,27 @@ impl PageTable { Ok(()) } + /// Unmaps a region of memory using 2MB pages. + /// + /// # Parameters + /// - `vregion`: The virtual memory region to unmap. + ///
```suggestion /// Unmaps a region `vregion` of 2MB pages. The region must be /// 2MB-aligned and correspond to a set of huge mappings. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -468,6 +607,17 @@ impl PageTable { } } + /// Sets the encryption state for a 4KB page. + /// + /// # Parameters + /// - `vaddr`: The virtual address of the page. + /// + /// # Returns + /// A result indicating success or an error code. + /// + /// # Errors + /// Returns ...
```suggestion /// Attempts to set the C-bit for the given page at `vaddr`. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -16,6 +16,7 @@ use crate::types::{PAGE_SIZE, PAGE_SIZE_2M}; use crate::utils::MemoryRegion; +/// Guard for a per-CPU page mapping to ensure adequate cleanup if drop.
"if drop" sounds a bit strange. Should be "when dropped": ```suggestion /// Guard used to unmap a per-CPU mapping when dropped. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -24,6 +25,19 @@ pub struct PerCPUPageMappingGuard { } impl PerCPUPageMappingGuard { + /// Creates a new [`PerCPUPageMappingGuard`] for the specified physical + /// address range and alignment. + /// + /// # Arguments + /// + /// * `paddr_start` - The starting physical address of the range. + ...
Missing `# Panics` section.
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -66,10 +80,22 @@ impl PerCPUPageMappingGuard { }) } + /// Creates a new [`PerCPUPageMappingGuard`] for a 4KB page at the + /// specified physical address. + /// + /// # Arguments + /// + /// * `paddr` - The physical address for the 4KB page. + /// + /// # Returns + /// + ...
```suggestion /// Creates a new [`PerCPUPageMappingGuard`] for a 4KB page at the /// specified physical address, or an `SvsmError` if an error occurs. ```
svsm
github_2023
others
272
coconut-svsm
00xc
@@ -66,10 +80,22 @@ impl PerCPUPageMappingGuard { }) } + /// Creates a new [`PerCPUPageMappingGuard`] for a 4KB page at the + /// specified physical address. + /// + /// # Arguments + /// + /// * `paddr` - The physical address for the 4KB page. + /// + /// # Returns + /// + ...
This sounds like it's the address of the guard object. ```suggestion /// Returns the virtual address for the new mapping. ```
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -8,6 +8,9 @@ use crate::types::{PAGE_SHIFT, PAGE_SIZE}; use core::fmt; use core::ops; +extern crate alloc; +use alloc::slice;
Should probably use `core::slice` instead.
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -251,6 +254,25 @@ impl VirtAddr { pub const fn const_add(&self, offset: usize) -> Self { VirtAddr::new(self.0 + offset) } + + /// Converts the `VirtAddr` to a slice of a given type + /// + /// # Arguments: + /// + /// * `len` - Number of elements of type `T` in the slice + /// + ...
And that alignment is met. See the requirements in `core::slice::from_raw_parts`
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -213,6 +213,10 @@ impl VirtAddr { Self(sign_extend(addr)) } + pub const fn to_idx(&self) -> usize {
The method name does not explain much, I would make it more verbose or at least add some documentation. Could we also make it generic over the page table level, like `PageTable::index()`?
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -917,6 +917,19 @@ impl PageRef { pub fn phys_addr(&self) -> PhysAddr { self.phys_addr } + + pub fn try_copy_page(&self) -> Result<Self, SvsmError> { + let virt_addr = allocate_file_page()?; + unsafe { + let src = self.virt_addr.as_ptr::<[u8; PAGE_SIZE]>(); + ...
`copy_to_nonoverlapping()` seems more appropriate and cannot create an intermediate copy in debug builds.
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -153,18 +197,51 @@ extern "C" fn ex_handler_hypervisor_injection(_ctx: &mut X86ExceptionContext) { // VMM Communication handler #[no_mangle] -extern "C" fn ex_handler_vmm_communication(ctx: &mut X86ExceptionContext) { - handle_vc_exception(ctx).expect("Failed to handle #VC"); +extern "C" fn ex_handler_vmm_com...
We could also retrieve the specific error from `handle_vc_exception()` and display it.
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -969,11 +970,30 @@ impl PageTablePart { /// A new instance of PageTablePart pub fn new(start: VirtAddr) -> Self { PageTablePart { - raw: Box::<RawPageTablePart>::default(), + raw: None, idx: PageTable::index::<3>(start), } } + pub fn alloc(&mut...
```suggestion fn get_or_init_mut(&mut self) -> &mut RawPageTablePart { self.raw.get_or_insert_with(|| Box::default()) } ```
svsm
github_2023
others
314
coconut-svsm
00xc
@@ -153,18 +197,51 @@ extern "C" fn ex_handler_hypervisor_injection(_ctx: &mut X86ExceptionContext) { // VMM Communication handler #[no_mangle] -extern "C" fn ex_handler_vmm_communication(ctx: &mut X86ExceptionContext) { - handle_vc_exception(ctx).expect("Failed to handle #VC"); +extern "C" fn ex_handler_vmm_com...
This should get rid of an unnecessary unwrap: ```suggestion if !user_mode(ctxt) { panic!("Syscall handler called from kernel mode!"); } let Ok(input) = u64::try_from(ctx.regs.rax) else { ctx.regs.rax = !0; return; }; ctx.regs.rax = match input { SYS_HE...
svsm
github_2023
others
314
coconut-svsm
cxdong
@@ -136,3 +145,6 @@ default_entry_no_ist name=vc handler=vmm_communication error_code=1 vector=29 // #SX Security Exception (Vector 30) default_entry_no_ist name=sx handler=panic error_code=1 vector=30 + +// INT 0x80 system call handler +default_entry_no_ist name=int80 handler=system_call error_code=0 vector=0...
The TDX and SEV have disabled int80 in linux kernel with commits around this ( https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/arch/x86/coco/tdx?h=v6.7&id=b82a8dbd3d2f4563156f7150c6f2ecab6e960b30), which looks like to prevent with the Ahoi (https://ahoi-attacks.github.io/) attacks. It appears ...
svsm
github_2023
others
320
coconut-svsm
00xc
@@ -44,12 +44,23 @@ struct PValidateRequest { resv: u32, } -fn core_create_vcpu_error_restore(vaddr: VirtAddr) { - if let Err(err) = rmp_clear_guest_vmsa(vaddr) { - log::error!("Failed to restore page permissions: {:#?}", err); +fn core_create_vcpu_error_restore(paddr: Option<PhysAddr>, vaddr: Option<...
Why not `if let Some(v) = vaddr { ... }`? Seems more clear. Same thing below with `paddr`.
svsm
github_2023
others
320
coconut-svsm
00xc
@@ -44,12 +44,23 @@ struct PValidateRequest { resv: u32, } -fn core_create_vcpu_error_restore(vaddr: VirtAddr) { - if let Err(err) = rmp_clear_guest_vmsa(vaddr) { - log::error!("Failed to restore page permissions: {:#?}", err); +fn core_create_vcpu_error_restore(paddr: Option<PhysAddr>, vaddr: Option<...
This comment should be updated. This is only called in the error path for `core_create_vcpu()`.
svsm
github_2023
others
320
coconut-svsm
00xc
@@ -86,6 +86,11 @@ fn core_create_vcpu(params: &RequestParams) -> Result<(), SvsmReqError> { return Err(SvsmReqError::invalid_address()); } + // Check whether VMSA page and CAA region overlap + if overlap(paddr, paddr + PAGE_SIZE - 1, pcaa, pcaa + 7) {
Maybe this is clearer: ```suggestion if overlap(paddr, paddr + PAGE_SIZE - 1, pcaa, pcaa + size_of::<SvsmCaa> - 1) { ```
svsm
github_2023
others
320
coconut-svsm
roy-hopkins
@@ -293,6 +293,9 @@ fn core_pvalidate_one(entry: u64, flush: &mut bool) -> Result<(), SvsmReqError> // down the #NPF loops. // if writable_phys_addr(paddr) { + // FIXME: This checks leaves a window open for the attack described
"This check leaves" (remove the s).
svsm
github_2023
others
326
coconut-svsm
p4zuu
@@ -1653,10 +1631,9 @@ pub fn layout_from_size(size: usize) -> Layout { pub fn layout_from_ptr(ptr: *mut u8) -> Option<Layout> { let va = VirtAddr::from(ptr); - let Ok(pfn) = ROOT_MEM.lock().get_pfn(va) else { - return None; - }; - let info = ROOT_MEM.lock().read_page_info(pfn);
Double-fetch bug indeed, nice catch
svsm
github_2023
others
323
coconut-svsm
00xc
@@ -84,6 +87,15 @@ test-in-svsm: utils/cbit bin/coconut-test-qemu.igvm doc: cargo doc -p svsm --open --all-features --document-private-items +docsite: + mkdir -p ${DOC_SITE} + cargo doc -p svsm --all-features --document-private-items --no-deps
For the public docs I think we could omit `--document-private-items`? Or maybe leave it as an option.
svsm
github_2023
others
312
coconut-svsm
joergroedel
@@ -255,75 +324,51 @@ pub struct PerCpu { /// Task list that has been assigned for scheduling on this CPU runqueue: RWLock<RunQueue>, - /// Stack boundaries of the currently running task. This is stored in - /// [PerCpu] because it needs lockless read access. - pub current_stack: MemoryRegion<VirtA...
This creates a confusing imbalance. `alloc()` is an associated method of `struct PerCpu`, but does allocate a struct `PerCpuUnsafe` and returns an inner member of it. So while at it, the allocation of `PerCpuUnsafe` data structures should be moved into a generic function.
svsm
github_2023
others
135
coconut-svsm
Freax13
@@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (C) 2023 IBM +// +// Authors: Claudio Carvalho <cclaudio@linux.ibm.com> + +/// This crate implements the C wrappers required to build the libvtpm.a dependencies +use crate::console::_print; +use crate::mm::alloc::{ + layout_from_ptr, l...
This function, `free` and `serial_out` should be marked as unsafe.
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,140 @@ +LIBCRT_DIR = $(CURDIR)/libcrt +OPENSSL_DIR = $(CURDIR)/openssl +MSTPM_DIR = $(CURDIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a + +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBP...
On my system, I had an older version installed `bindgen v0.60.1` and after some struggle, I realized that this command was not updating it and I had several errors, so I suggest setting a version here: ```suggestion cargo install bindgen-cli@~0.69 ```
svsm
github_2023
others
135
coconut-svsm
roy-hopkins
@@ -0,0 +1,140 @@ +LIBCRT_DIR = $(CURDIR)/libcrt +OPENSSL_DIR = $(CURDIR)/openssl +MSTPM_DIR = $(CURDIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a + +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBP...
The MSTPM library is currently building with SSE enabled resulting in an exception on guest startup: ``` Thread 2 received signal SIGINT, Interrupt. [Switching to Thread 1.5] 0xffffff800013a730 in svsm::debug::gdbstub::svsm_gdbstub::debug_break () at src/debug/gdbstub.rs:172 172 asm!("int3"); (g...
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,140 @@ +LIBCRT_DIR = $(CURDIR)/libcrt +OPENSSL_DIR = $(CURDIR)/openssl +MSTPM_DIR = $(CURDIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a + +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A = Platform/src/libplatform.a +LIBP...
Using `./scripts/container/build.sh` in a `svsm` working tree created with `git-worktree`, I have the following issue: ``` (cd /home/stefano/repos/coconut/svsm-review/libvtpm/openssl && git checkout OpenSSL_1_1_1q && \ ./Configure \ --config=/home/stefano/repos/coconut/svsm-review/libvtpm/openssl_svsm.conf \ ...
svsm
github_2023
c
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: MIT */ + +#include <stdlib.h> +#include <stdint.h> +#include <stdio.h> + +static uint64_t seed; + +void srand(unsigned s) +{ + seed = s - 1; +} + +/* return 0 on success */ +static inline int rdrand64(uint64_t *rnd) +{ + unsigned char ok; + + __asm__ volatile("rdrand ...
I got a little lost in this thread [[1]](https://lore.kernel.org/linux-coco/62c3cd00-d072-4daa-8e67-442d52325cde@linux.intel.com/T/), but it seems that at least on Intel (so not our case for now), rdrand might fail. So should we cycle or panic here? Or should we use `rdseed` (and cycle of course, since it's even m...
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -53,14 +58,23 @@ bin/coconut-hyperv.igvm: $(IGVMBUILDER) stage1/kernel.elf stage1/stage2.bin $(IGVMBUILDER) --sort --output $@ --stage2 stage1/stage2.bin --kernel stage1/kernel.elf --comport 3 hyper-v test: - cargo test --target=x86_64-unknown-linux-gnu + cargo test ${CARGO_ARGS_TEST} --target=x86_64-unknown-li...
I think this target conflicts with `libvtpm/libvtpm.a:`, because running with `make -j10` I have several errors: ``` checking for suffix of object files... make[1]: *** [Makefile:105: /home/stefano/repos/coconut/svsm-review/libvtpm/ms-tpm-20-ref/TPMCmd/Makefile] Error 77 make[1]: Leaving directory '/home/stefano/rep...
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,141 @@ +DEPS_DIR = $(CURDIR)/deps + +LIBCRT_DIR = $(DEPS_DIR)/libcrt +OPENSSL_DIR = $(DEPS_DIR)/openssl +MSTPM_DIR = $(DEPS_DIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A =...
Playing with ms-tpm, I realized that `DEBUG=YES` is the default, so should we add `-DDEBUG=NO` here?
svsm
github_2023
others
135
coconut-svsm
joergroedel
@@ -139,15 +139,16 @@ openSUSE you can do this by: $ sudo zypper si -d qemu-ovmf-x86_64 ``` -Then go back to the EDK2 source directory and follow these steps to -build the firmware: +Then go back to the EDK2 source directory and follow the steps below to +build the firmware. `-DTPM2_ENABLE` is required only if you ...
Why is the --reconfig needed?
svsm
github_2023
others
135
coconut-svsm
joergroedel
@@ -0,0 +1,141 @@ +DEPS_DIR = $(CURDIR)/deps + +LIBCRT_DIR = $(DEPS_DIR)/libcrt +OPENSSL_DIR = $(DEPS_DIR)/openssl +MSTPM_DIR = $(DEPS_DIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A =...
Please do not install build dependencies on Makefiles. The right way to do this is to just call `cargo bindgen` and let the user install it (e.g. via distro package manager). I think changing this also requires updates to the documentation about which build dependencies to install and the docker-files.
svsm
github_2023
others
135
coconut-svsm
deeglaze
@@ -189,6 +193,15 @@ Building the SVSM itself requires: - `x86_64-unknown-none` target toolchain installed (`rustup target add x86_64-unknown-none`) - `binutils` >= 2.39 +You may also need to install the Microsoft TPM build dependencies. On OpenSUSE +you can do this by: + +``` +$ sudo zypper in system-user-mail mak...
I don't think we should be leaving the C library dependencies to open to the toolchain container. These need to be part of SVSM's own dependency management.
svsm
github_2023
others
135
coconut-svsm
deeglaze
@@ -6,11 +6,14 @@ pub mod core; pub mod errors; +#[cfg(feature = "mstpm")]
Is it possible to allow the build to have the tpm linked in but have a qemufwcfg file specify whether to make it discoverable? We want to have a single binary to release but still allow users to decide whether or not to attach a vTPM to their instance.
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -0,0 +1,192 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM +// +// Authors: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! This crate implements the virtual TPM interfaces for the TPM 2.0 +//! Reference Implementation (by Microsoft) + +/// Functions required to build the Microsoft TPM libraries...
```suggestion let mut request_ffi = buffer[..*length].to_vec(); ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -441,6 +443,11 @@ pub extern "C" fn svsm_main() { prepare_fw_launch(fw_meta).expect("Failed to setup guest VMSA/CAA"); } + #[cfg(feature = "mstpm")] + if let Err(e) = vtpm_init() { + panic!("vTPM failed to initialize - {:?}", e); + }
This will also display the error and is shorter: ```suggestion vtpm_init().expect("vTPM failed to initialize"); ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -0,0 +1,220 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM Corp +// +// Author: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! vTPM protocol implementation (SVSM spec, chapter 8). + +extern crate alloc; + +use alloc::vec::Vec; + +use crate::{ + address::{Address, PhysAddr, VirtAddr}, + mm...
This creates a reference to uninitialized memory and is undefined behavior, even if memory is not accessed. ```suggestion // The buffer slice must be large enough to hold the TPM command response buffer.resize(SEND_COMMAND_RESP_OUTBUF_SIZE, 0); ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -0,0 +1,220 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM Corp +// +// Author: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! vTPM protocol implementation (SVSM spec, chapter 8). + +extern crate alloc; + +use alloc::vec::Vec; + +use crate::{ + address::{Address, PhysAddr, VirtAddr}, + mm...
Again, we cannot set the length to capacity because that could include allocated but uninitialized memory (note that capacity might be greater than `SEND_COMMAND_RESP_OUTBUF_SIZE`, we are only guaranteed that's the minimum). With my previous suggestion we filled up buffer until `SEND_COMMAND_RESP_OUTBUF_SIZE` with z...
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -0,0 +1,220 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM Corp +// +// Author: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! vTPM protocol implementation (SVSM spec, chapter 8). + +extern crate alloc; + +use alloc::vec::Vec; + +use crate::{ + address::{Address, PhysAddr, VirtAddr}, + mm...
Please mark this function as unsafe - the caller must make sure that `iobuf` points to a sufficiently large region of memory, that it's properly aligned, that it is initialized to a valid representation of `TpmSendCommandResponse` and that it's not aliased.
svsm
github_2023
others
135
coconut-svsm
roy-hopkins
@@ -189,6 +193,15 @@ Building the SVSM itself requires: - `x86_64-unknown-none` target toolchain installed (`rustup target add x86_64-unknown-none`) - `binutils` >= 2.39 +You may also need to install the Microsoft TPM build dependencies. On OpenSUSE +you can do this by: + +``` +$ sudo zypper in system-user-mail mak...
I may have missed it elsewhere in the documentation but do we need to install git submodules now when cloning the SVSM repository? ``` $ git clone https://github.com/coconut-svsm/svsm $ git submodule update --init ```
svsm
github_2023
others
135
coconut-svsm
00xc
@@ -85,3 +110,8 @@ pub fn vtpm_init() -> Result<(), SvsmReqError> { vtpm.init()?; Ok(()) } + +pub fn vtpm_get_locked() -> VtpmRef { + let vtpm = addr_of_mut!(*VTPM.lock()); + VtpmRef::new(vtpm) +}
This is dropping the lock as soon as the function returns, which will lead to undefined behavior when using the `VtpmRef`. You need `VtpmRef` to hold a `SpinLockGuard<'a, Vtpm>` (or directly return that type from `vtpm_get_locked()`, which already implements `Deref` and `DerefMut`).
svsm
github_2023
others
135
coconut-svsm
roy-hopkins
@@ -0,0 +1,192 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2023 IBM +// +// Authors: Claudio Carvalho <cclaudio@linux.ibm.com> + +//! This crate implements the virtual TPM interfaces for the TPM 2.0 +//! Reference Implementation (by Microsoft) + +/// Functions required to build the Microsoft TPM libraries...
What is the purpose of this initialisation process? Maybe this should be moved to a `test-in-svsm` test and the startup process here simplified?
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -131,5 +131,4 @@ clean: rm -f ${STAGE1_OBJS} utils/gen_meta utils/print-meta rm -rf bin -.PHONY: test clean clippy bin/stage2.bin bin/svsm-kernel.elf bin/test-kernel.elf
Should we add `distclean` in `.PHONY` in the same commit where we define `distclean` target? (Maybe something went wrong with the rebase)
svsm
github_2023
others
135
coconut-svsm
stefano-garzarella
@@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (C) 2024 IBM +// +// Authors: Claudio Carvalho <cclaudio@linux.ibm.com> + +use std::process::Command; + +fn main() { + Command::new("make").status().unwrap();
If `make` fails here, is there any way to propagate the output? Even using `make V=2` in the root, I can't see the errors produced by this call (they might be useful, for example in my case it failed because it can't install `bindgen-cli`, but I discovered it only doing `make -C libmstpm ` )
svsm
github_2023
others
135
coconut-svsm
roy-hopkins
@@ -0,0 +1,141 @@ +DEPS_DIR = $(CURDIR)/deps + +LIBCRT_DIR = $(DEPS_DIR)/libcrt +OPENSSL_DIR = $(DEPS_DIR)/openssl +MSTPM_DIR = $(DEPS_DIR)/ms-tpm-20-ref/TPMCmd + +LIBCRT = $(LIBCRT_DIR)/libcrt.a +LIBCRYPTO = $(OPENSSL_DIR)/libcrypto.a + +LIBTPM_A = tpm/src/libtpm.a +LIBTPM = $(MSTPM_DIR)/$(LIBTPM_A) + +LIBPLATFORM_A =...
Debug information is turned on and optimisation level set to 0 here. Should optimisation be enabled?
svsm
github_2023
others
303
coconut-svsm
osteffenrh
@@ -6,7 +6,9 @@ members = [ # binary targets "kernel", # fuzzing - "fuzz" + "fuzz", + # ELF loader + "elf"
trailing commas are OK in TOML
svsm
github_2023
others
303
coconut-svsm
osteffenrh
@@ -0,0 +1,181 @@ +// SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +// +// Copyright (c) 2023-2024 SUSE LLC +// +// Author: Nicolai Stange <nstange@suse.de> +// +// vim: ts=4 sw=4 et
Do we really need editor specific formatting options in code files? There are things like [editorconfig](https://editorconfig.org/) that allows setting this easily for the whole project (supported by neovim out of the box) On the other hand, don't we run the rust formatter on everything automatically anyway?
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -71,11 +71,19 @@ impl IgvmBuilder { directive_a: &IgvmDirectiveHeader, directive_b: &IgvmDirectiveHeader, ) -> Ordering { - let IgvmDirectiveHeader::PageData { gpa: a, .. } = directive_a else { - panic!("Attempted to compare non-page directive"); + let a = if let IgvmD...
Or simply: ```suggestion let a = match directive_a { IgvmDirectiveHeader::PageData { gpa, .. } | IgvmDirectiveHeader::SnpVpContext { gpa, .. } => gpa, _ = panic!("Attempted to compare non-page/vp directive"), }; ```
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDa...
Perhaps it's better to implement `std::fmt::Display` for `SnpPageType` instead of doing the conversion here.
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDa...
Instead of having these verbose inline error strings, could we have an `IgvmMeasureError` enum that implements `std::fmt::Display` such that it prints these strings? e.g. ```rust enum IgvmMeasureError { InvalidVmsaCount(u32), InvalidVmsaGpa(u64), ... } impl std::fmt::Display for IgvmMeasureError ...
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDa...
```suggestion let mut vmsa_page = vmsa.as_bytes().to_vec(); vmsa_page.resize(PAGE_SIZE_4K as usize, 0); ```
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,39 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; + +use clap::Parser; +use cmd_options::CmdOptions; +use igvm_measure::IgvmMeasure; + +mod cmd_options; +mod igvm_measure; +mod page_info; + +fn main() -> Res...
I think you can avoid this `to_vec()`
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -104,3 +107,23 @@ pub fn get_regular_report(buffer: &mut [u8]) -> Result<usize, SvsmReqError> { pub fn get_extended_report(buffer: &mut [u8], certs: &mut [u8]) -> Result<usize, SvsmReqError> { get_report(buffer, Some(certs)) } + +/// Retrieve a VMP0 attestation report from the PSP and report the launch +/// m...
We probably want to return errors here and panic in the caller if necessary. Otherwise add a `# Panics` section to the function docs.
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -0,0 +1,279 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDa...
This can just return `Self`
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -71,11 +71,19 @@ impl IgvmBuilder { directive_a: &IgvmDirectiveHeader, directive_b: &IgvmDirectiveHeader, ) -> Ordering { - let IgvmDirectiveHeader::PageData { gpa: a, .. } = directive_a else { - panic!("Attempted to compare non-page directive"); + let a = if let IgvmD...
Same thing, a match here is a bit more clear
svsm
github_2023
others
294
coconut-svsm
00xc
@@ -104,3 +107,31 @@ pub fn get_regular_report(buffer: &mut [u8]) -> Result<usize, SvsmReqError> { pub fn get_extended_report(buffer: &mut [u8], certs: &mut [u8]) -> Result<usize, SvsmReqError> { get_report(buffer, Some(certs)) } + +/// Retrieve a VMP0 attestation report from the PSP and report the launch +/// m...
Perhaps we should turn these (the assert, the unwrap and the `report()` call) into errors as well.
svsm
github_2023
others
294
coconut-svsm
jepio
@@ -0,0 +1,333 @@ +// SPDX-License-Identifier: MIT +// +// Copyright (c) 2024 SUSE LLC +// +// Author: Roy Hopkins <roy.hopkins@suse.com> + +use std::error::Error; +use std::fs; + +use igvm::snp_defs::SevVmsa; +use igvm::{IgvmDirectiveHeader, IgvmFile, IgvmPlatformHeader}; +use igvm_defs::{IgvmPageDataFlags, IgvmPageDa...
this is not a legal transformation, we need to insert this as an actual page of zeros: ```suggestion } else if data.is_empty() { self.log_page(SnpPageType::Normal, gpa, PAGE_SIZE_4K); Some(PageInfo::new_normal_page(self.digest, gpa, &self.zero_page)) ...
svsm
github_2023
others
297
coconut-svsm
joergroedel
@@ -716,22 +708,29 @@ pub fn get_init_pgtable_locked<'a>() -> LockGuard<'a, PageTableRef> { #[derive(Debug)] pub struct PageTableRef { - pgtable_ptr: *mut PageTable, + ptr: *mut PageTable, + owned: bool,
I do not fully understand why this is needed. The page-table which do not allocate the root-page from the allocator are global static. And thus their drop-method is never called.
svsm
github_2023
others
288
coconut-svsm
00xc
@@ -257,3 +257,369 @@ fn vc_decode_insn(ctx: &X86ExceptionContext) -> Result<Instruction, SvsmError> { fn vc_decoding_needed(error_code: usize) -> bool { !(SVM_EXIT_EXCP_BASE..=SVM_EXIT_LAST_EXCP).contains(&error_code) } + +#[cfg(test)] +mod test { + use crate::cpu::msr::{rdtsc, rdtscp, RdtscpOut}; + use c...
We already have `read_msr()` / `write_msr()` in `kernel/src/cpu/msr.rs`, could you reuse those?
svsm
github_2023
others
288
coconut-svsm
00xc
@@ -257,3 +257,369 @@ fn vc_decode_insn(ctx: &X86ExceptionContext) -> Result<Instruction, SvsmError> { fn vc_decoding_needed(error_code: usize) -> bool { !(SVM_EXIT_EXCP_BASE..=SVM_EXIT_LAST_EXCP).contains(&error_code) } + +#[cfg(test)] +mod test { + use crate::cpu::msr::{rdtsc, rdtscp, RdtscpOut}; + use c...
This is creating an intermediate reference to the GHCB. I'd favor just using `slice::from_raw_parts()`, which is also less convoluted in my opinion. Also, you can test that at least one byte changed more easily with `Iterator::any()`: ```suggestion let ghcb_bytes = unsafe { core::slice::from_ra...
svsm
github_2023
others
295
coconut-svsm
00xc
@@ -198,8 +199,10 @@ impl Instruction { /// /// The caller should validate that `rip` is set to a valid address /// and that the next [`MAX_INSN_SIZE`] bytes are within valid memory. -pub unsafe fn insn_fetch(rip: *const u8) -> [u8; MAX_INSN_SIZE] { - rip.cast::<[u8; MAX_INSN_SIZE]>().read() +pub unsafe fn insn...
I guess you could just inline this :)
svsm
github_2023
others
295
coconut-svsm
00xc
@@ -248,4 +248,15 @@ mod tests { assert_eq!(test_buffer[0], data_to_write); } + + #[test] + #[cfg_attr(miri, ignore = "inline assembly")] + fn test_read_15_bytes_valid_address() { + let test_buffer = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; + let test_addr = VirtAddr::f...
This looks good. While you are at it, you could probably add another test that reads invalid memory and that only runs inside the SVSM.
svsm
github_2023
others
295
coconut-svsm
00xc
@@ -259,4 +262,28 @@ mod tests { assert_eq!(result, test_buffer); } + + #[test] + #[cfg_attr(miri, ignore = "inline assembly")] + #[cfg_attr(not(test_in_svsm), ignore = "Can only be run inside guest")] + fn test_read_invalid_address() { + let ptr: GuestPtr<u8> = GuestPtr::new(VirtAddr...
This test fails - the memory beyond the allocated page is not lent by the allocator, but it's mapped as part of its memory region. I suggest you simply remove this test.
svsm
github_2023
others
295
coconut-svsm
00xc
@@ -248,4 +251,39 @@ mod tests { assert_eq!(test_buffer[0], data_to_write); } + + #[test] + #[cfg_attr(miri, ignore = "inline assembly")] + fn test_read_15_bytes_valid_address() { + let test_buffer = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; + let test_addr = VirtAddr::f...
Could you move this into the new commit adding tests?
svsm
github_2023
others
292
coconut-svsm
00xc
@@ -111,8 +111,15 @@ impl GpaMap { 1 << 20 } Hypervisor::HyperV => { - // Load the kernel image after the firmware. - firmware_range.get_end() + // Load the kernel image after the firmware, but now lower than + // 1 M...
Or just: ```rust let firmware_end = firmware_range.get_end().max(1 << 20); ``` Anyway this LGTM.
svsm
github_2023
others
274
coconut-svsm
stefano-garzarella
@@ -224,6 +224,15 @@ Unit tests can be run inside the SVSM by $ QEMU=/path/to/qemu OVMF=/path/to/firmware/ make test-in-svsm ``` +Different (non-QEMU) hypervisors may provide the ACPI tables and ACPI RSDP at +different paths. If this is the case, they can be provided as environment +variables, e.g. +``` +$ ACPI_RSD...
I'd suggest adding in the documentation the default paths and maybe use something different in the example. The rest LGTM.
svsm
github_2023
others
273
coconut-svsm
stefano-garzarella
@@ -47,12 +47,16 @@ impl fmt::Debug for Console { } } -pub static WRITER: SpinLock<Console> = SpinLock::new(Console { +static WRITER: SpinLock<Console> = SpinLock::new(Console { writer: Some(&DEFAULT_SERIAL_PORT), }); static CONSOLE_INITIALIZED: ImmutAfterInitCell<bool> = ImmutAfterInitCell::new(false); ...
I think we are changing the behavior. Before this patch, the caller invoked `WRITER.lock().set()` without checking `CONSOLE_INITIALIZED`, so each time changed the serial port used by our console, here instead only the first invocation sets it, so I'm not sure if it's the behavior we wanted. It is true that we call ...
svsm
github_2023
others
269
coconut-svsm
roy-hopkins
@@ -362,8 +365,24 @@ pub mod svsm_gdbstub { } } - pub fn set_regs(&mut self, ctx: &TaskContext) { - self.ctx = (ctx as *const _) as usize; + fn ctx(&self) -> Option<&TaskContext> { + // SAFETY: this is a pointer to the exception context on the + // ...
Just a note - with rustc 1.74.1 you get this error: ``` error[E0658]: use of unstable library feature 'ptr_from_ref' --> kernel/src/debug/gdbstub.rs:385:24 | 385 | self.ctx = core::ptr::from_mut(ctx) | ^^^^^^^^^^^^^^^^^^^ | ``` Updating to 1.76.0 fixed it.
svsm
github_2023
others
237
coconut-svsm
cclaudio
@@ -81,26 +84,36 @@ $ sudo zypper refresh $ sudo zypper si -d qemu-kvm ``` +Support for IGVM within QEMU depends on the IGVM library. This will need to be +built and installed prior to building QEMU. + +``` +git clone https://github.com/microsoft/igvm +cd igvm +make -f igvm_c/Makefile +sudo make -f igvm_c/Makefile ...
We may need more changes in the igvm repository. Although the `igvm#3` got merged, it is still failing to build. First I installed some dependencies: ``` $ cargo install cbindgen $ sudo zypper install cunit-devel ``` Then I tried to build it: ``` cclaudio@dobby:~/src/coconut/igvm> make -f igvm_c/Makefile cb...
svsm
github_2023
others
256
coconut-svsm
stefano-garzarella
@@ -71,54 +69,61 @@ utils/print-meta: utils/print-meta.c utils/cbit: utils/cbit.c cc -O3 -Wall -o $@ $< -stage1/meta.bin: utils/gen_meta utils/print-meta +bin/meta.bin: utils/gen_meta utils/print-meta ./utils/gen_meta $@ -stage1/stage2.bin: +bin/stage2.bin: cargo build ${CARGO_ARGS} ${SVSM_ARGS} --bin stage2...
Since we're touching this code and adding more calls to `mkdir -v -p bin`, what about adding a dedicated target, so we can avoid duplicating/calling it multiple times? I mean something like this: ``` bin: mkdir -v -p bin ... bin/stage2.bin: bin ... bin/svsm-kernel.elf: bin ... etc. ```
svsm
github_2023
others
256
coconut-svsm
stefano-garzarella
@@ -71,54 +69,61 @@ utils/print-meta: utils/print-meta.c utils/cbit: utils/cbit.c cc -O3 -Wall -o $@ $< -stage1/meta.bin: utils/gen_meta utils/print-meta +bin/meta.bin: utils/gen_meta utils/print-meta ./utils/gen_meta $@ -stage1/stage2.bin: +bin/stage2.bin: cargo build ${CARGO_ARGS} ${SVSM_ARGS} --bin stage2...
I think we can remove this line, since `*.elf` and `*.bin` files are now in `bin/`, and `*.o` are covered in the next line by `${STAGE1_OBJS}` ```suggestion ```
svsm
github_2023
others
256
coconut-svsm
stefano-garzarella
@@ -71,54 +69,61 @@ utils/print-meta: utils/print-meta.c utils/cbit: utils/cbit.c cc -O3 -Wall -o $@ $< -stage1/meta.bin: utils/gen_meta utils/print-meta +bin/meta.bin: utils/gen_meta utils/print-meta ./utils/gen_meta $@ -stage1/stage2.bin: +bin/stage2.bin: cargo build ${CARGO_ARGS} ${SVSM_ARGS} --bin stage2...
Should we move these two to bin as well, or since they are the main artifacts do we leave them in the main folder?
svsm
github_2023
others
265
coconut-svsm
roy-hopkins
@@ -4,6 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] +zerocopy.workspace = true
This effectively adds a dependency on zerocopy to the kernel as it shares the bootlib package. Is that ok?
svsm
github_2023
others
266
coconut-svsm
00xc
@@ -11,29 +11,71 @@ use super::super::tss::IST_DF; use super::super::vc::handle_vc_exception; use super::common::PF_ERROR_WRITE; use super::common::{ - idt_mut, IdtEntry, BP_VECTOR, DB_VECTOR, DF_VECTOR, GP_VECTOR, HV_VECTOR, PF_VECTOR, VC_VECTOR, + idt_mut, IdtEntry, AC_VECTOR, BP_VECTOR, BR_VECTOR, CP_VECTOR...
`idt_mut()` acquires a lock, so perhaps we should acquire it just once: ```rust let idt = idt_mut(); idt.set_entry(DE_VECTOR, IdtEntry::entry_with_handler(asm_entry_de)); // ... idt.load(); ```
svsm
github_2023
others
266
coconut-svsm
00xc
@@ -92,6 +92,16 @@ impl IdtEntry { IdtEntry::create(target, SVSM_CS, ist) } + pub fn entry_with_handler(handler: unsafe extern "C" fn()) -> Self { + let target = VirtAddr::from(handler as *const () as u64); + IdtEntry::create(target, SVSM_CS, 0) + } + + pub fn ist_entry_with_handl...
`VirtAddr` implements `From<*const T>` so these can just be: ```rust let target = VirtAddr::from(handler as *const ()); ```
svsm
github_2023
others
98
coconut-svsm
stefano-garzarella
@@ -68,25 +68,35 @@ pub fn pvalidate_range(start: VirtAddr, end: VirtAddr, valid: bool) -> Result<() if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end { // Try to validate as a huge page. // If we fail, try to fall back to regular-sized pages. - pvalidate(addr,...
3 slashes also here for the doc comment?
svsm
github_2023
others
98
coconut-svsm
stefano-garzarella
@@ -68,25 +68,35 @@ pub fn pvalidate_range(start: VirtAddr, end: VirtAddr, valid: bool) -> Result<() if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end { // Try to validate as a huge page. // If we fail, try to fall back to regular-sized pages. - pvalidate(addr,...
I find a bit confusing the name, what about `Regular` and `Huge` ? Or `RegularPage` and `HugePage`?
svsm
github_2023
others
98
coconut-svsm
stefano-garzarella
@@ -68,25 +68,35 @@ pub fn pvalidate_range(start: VirtAddr, end: VirtAddr, valid: bool) -> Result<() if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end { // Try to validate as a huge page. // If we fail, try to fall back to regular-sized pages. - pvalidate(addr,...
Should we mention in the documentation that the enum values are the one used for the PVALIDATE instructions? Maybe it's implied and we can avoid it, it just occurred to me while looking at the code because we didn't add a match to choose the value.
svsm
github_2023
others
98
coconut-svsm
stefano-garzarella
@@ -11,6 +11,21 @@ pub const PAGE_SHIFT_2M: usize = 21; pub const PAGE_SIZE: usize = 1 << PAGE_SHIFT; pub const PAGE_SIZE_2M: usize = PAGE_SIZE * 512; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PageSize { + Regular, + Huge, +} + +impl From<PageSize> for usize {
What is the advantage of implementing `From` for `usize` compared to embed the values in the `enum`? I mean something like this: ``` #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(usize)] pub enum PageSize { Regular = PAGE_SIZE, Huge = PAGE_SIZE_2M, } ``` I'm asking because I'm worried about ...
svsm
github_2023
others
260
coconut-svsm
chris-oo
@@ -53,7 +53,21 @@ jobs: uses: actions-rs/cargo@v1 with: command: clippy - args: --workspace --all-features --exclude svsm --target=x86_64-unknown-linux-gnu -- -D warnings + args: --workspace --all-features --exclude svsm --exclude svsm-fuzz --target=x86_64-unknown-linux-g...
This really wasn't included in the above clippy call? I think it should be... Ideally I think we don't run clippy on all the individual crates, but we use `--workspace`, `--exclude` and `--target` to filter crates that don't build on a given target
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -81,138 +99,216 @@ impl PageStorageType { const NEXT_MASK: u64 = !((1u64 << Self::NEXT_SHIFT) - 1); const ORDER_MASK: u64 = (1u64 << (Self::NEXT_SHIFT - Self::TYPE_SHIFT)) - 1; + /// Creates a new [`PageStorageType`] with the specified page type. + /// + /// # Arguments + /// + /// * `t` -...
For these simple functions I don't think we need a `# Returns` section, but that's just personal taste.
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -81,138 +99,216 @@ impl PageStorageType { const NEXT_MASK: u64 = !((1u64 << Self::NEXT_SHIFT) - 1); const ORDER_MASK: u64 = (1u64 << (Self::NEXT_SHIFT - Self::TYPE_SHIFT)) - 1; + /// Creates a new [`PageStorageType`] with the specified page type. + /// + /// # Arguments + /// + /// * `t` -...
```suggestion /// Decodes a [`FreeInfo`] from a [`PageStorageType`] ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -279,6 +381,7 @@ impl MemoryRegion { } } + /// Converts a physical address to a virtual address within the memory region.
```suggestion /// Converts a physical address within this memory region to a virtual address. /// Returns `None` if the physical address does not belong to the memory region ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -297,12 +400,15 @@ impl MemoryRegion { Some(self.start_virt + offset) } + /// Converts a virtual address to a physical address within the memory region.
```suggestion /// Converts a virtual address within this memory region to a physical address. /// Returns `None` if the virtual address does not belong to the memory region ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -312,40 +418,47 @@ impl MemoryRegion { self.start_virt.as_mut_ptr::<PageStorageType>().add(pfn) } + /// Checks if a page frame number is valid.
```suggestion /// Checks if a page frame number is valid. /// /// # Panics /// /// Panics if the page frame number is invalid. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -312,40 +418,47 @@ impl MemoryRegion { self.start_virt.as_mut_ptr::<PageStorageType>().add(pfn) } + /// Checks if a page frame number is valid. fn check_pfn(&self, pfn: usize) { if pfn >= self.page_count { panic!("Invalid Page Number {}", pfn); } } + /...
```suggestion // SAFETY: we have checked that the pfn is valid via check_pfn() above. unsafe { self.page_info_ptr(pfn).write(info) }; ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -312,40 +418,47 @@ impl MemoryRegion { self.start_virt.as_mut_ptr::<PageStorageType>().add(pfn) } + /// Checks if a page frame number is valid. fn check_pfn(&self, pfn: usize) { if pfn >= self.page_count { panic!("Invalid Page Number {}", pfn); } } + /...
```suggestion // SAFETY: we have checked that the pfn is valid via check_pfn() above. unsafe { self.page_info_ptr(pfn).write(info) }; ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -385,6 +500,7 @@ impl MemoryRegion { self.mark_compound_page(pfn, order); } + /// Splits a page into two pages of a lower order.
```suggestion /// Splits a page into two pages of the next lower order. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -580,6 +713,7 @@ impl MemoryRegion { } } + /// Frees a raw page by updating the free list and marking it as a free page.
```suggestion /// Frees a raw page by updating the free list and marking it as a free page. /// /// # Panics /// /// Panics if `order` is greater than [`MAX_ORDER`]. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -538,6 +666,11 @@ impl MemoryRegion { fi.next_page } + /// Allocates a specific page frame number (`pfn`) within a given order. + /// If the page frame number is not found or is already allocated, an error + /// is returned. If the requested page frame number is the first in the + /// lis...
```suggestion /// Allocates a specific page frame number (`pfn`) within a given order. /// If the page frame number is not found or is already allocated, an error /// is returned. If the requested page frame number is the first in the /// list, it is marked as allocated, and the next page in the lis...
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -712,45 +859,59 @@ impl MemoryRegion { } } +/// Represents a reference to a memory page, holding both virtual and +/// physical addresses. #[derive(Debug)] pub struct PageRef { virt_addr: VirtAddr, phys_addr: PhysAddr, } impl PageRef { + /// Creates a new [`PageRef`] instance with the give...
Probably redundant I would say
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -760,11 +921,17 @@ impl Clone for PageRef { } impl Drop for PageRef { + /// Drops the [`PageRef`] instance, releasing the associated memory page.
```suggestion /// Drops the [`PageRef`], decreasing the reference count for the page. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -788,30 +955,73 @@ pub fn print_memory_info(info: &MemInfo) { ); } +/// Static spinlock-protected instance of [`MemoryRegion`] representing the +/// root memory region. static ROOT_MEM: SpinLock<MemoryRegion> = SpinLock::new(MemoryRegion::new()); +/// Allocates a single memory page from the root memory re...
```suggestion /// Allocate a reference-counted file page. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -827,14 +1037,18 @@ fn put_file_page(vaddr: VirtAddr) -> Result<(), SvsmError> { Ok(ROOT_MEM.lock().put_file_page(vaddr)?) } +/// Obtain a free page given a virtual address
```suggestion /// Free the page at the given virtual address. ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -827,14 +1037,18 @@ fn put_file_page(vaddr: VirtAddr) -> Result<(), SvsmError> { Ok(ROOT_MEM.lock().put_file_page(vaddr)?) } +/// Obtain a free page given a virtual address pub fn free_page(vaddr: VirtAddr) { ROOT_MEM.lock().free_page(vaddr) } +/// Retrieve the locked memory info
```suggestion /// Retrieve information about the root memory ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -1245,7 +1517,14 @@ impl SvsmAllocator { } } +/// Implements the `GlobalAlloc` trait for [`SvsmAllocator`], allowing it to
```suggestion /// Implements the [`GlobalAlloc`] trait for [`SvsmAllocator`], allowing it to ```
svsm
github_2023
others
243
coconut-svsm
00xc
@@ -1245,7 +1517,14 @@ impl SvsmAllocator { } } +/// Implements the `GlobalAlloc` trait for [`SvsmAllocator`], allowing it to +/// be used as a global allocator for Rust programs. unsafe impl GlobalAlloc for SvsmAllocator { + /// Allocates memory based on the specified layout. + /// + /// # Safety + ...
This is unnecessary, the safety requirements are already specified in [the trait documentation](https://doc.rust-lang.org/core/alloc/trait.GlobalAlloc.html). Also, the function is unsafe for different reasons than NULL pointers.