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 | 533 | coconut-svsm | stefano-garzarella | @@ -259,3 +275,99 @@ pub fn get_vp_register(name: hyperv::HvRegisterName) -> Result<u64, SvsmError> {
Ok(reg)
}
+
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Default)]
+struct HvInputEnableVpVtl {
+ partition_id: u64,
+ vp_index: u32,
+ vtl: u8,
+ _rsvd: [u8; 3],
+ context: hyperv::HvInitialVpContext,
+}
+
+fn enable_vp_vtl_hypercall(
+ cpu: &PerCpu,
+ vtl: u8,
+ context: &HvInitialVpContext,
+) -> Result<(), SvsmError> {
+ let input_header = HvInputEnableVpVtl {
+ partition_id: HV_PARTITION_ID_SELF,
+ vtl,
+ vp_index: cpu.get_apic_id(),
+ context: *context,
+ ..Default::default()
+ };
+
+ let input_control = HvHypercallInput::new().with_call_code(HvCallCode::EnableVpVtl as u16);
+
+ let mut hypercall_pages = this_cpu().get_hypercall_pages();
+ let header = hypercall_pages.hypercall_input::<HvInputEnableVpVtl>();
+ *header = input_header;
+
+ let call_output = unsafe {
+ // SAFETY - the EnableVpVtl hypercall does not write to any memory and
+ // does not consume memory that is not included in the hypercall input.
+ hypercall(input_control, &hypercall_pages)
+ };
+ let status = call_output.status();
+
+ if status != 0 {
+ Err(HyperV(status))
+ } else {
+ Ok(())
+ }
+}
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Default)]
+struct HvInputStartVirtualProcessor {
+ partition_id: u64,
+ vp_index: u32,
+ vtl: u8,
+ _rsvd: [u8; 3],
+ context: hyperv::HvInitialVpContext,
+}
+
+fn start_vp_hypercall(
+ cpu: &PerCpu,
+ vtl: u8,
+ context: &HvInitialVpContext,
+) -> Result<(), SvsmError> {
+ let input_header = HvInputStartVirtualProcessor {
+ partition_id: HV_PARTITION_ID_SELF,
+ vtl,
+ vp_index: cpu.get_apic_id(),
+ context: *context,
+ ..Default::default()
+ };
+
+ let input_control =
+ HvHypercallInput::new().with_call_code(HvCallCode::StartVirtualProcessor as u16);
+
+ let mut hypercall_pages = this_cpu().get_hypercall_pages();
+ let header = hypercall_pages.hypercall_input::<HvInputStartVirtualProcessor>();
+ *header = input_header;
+
+ let call_output = unsafe {
+ // SAFETY - the StartVp hypercall does not write to any memory and does | Ditto |
svsm | github_2023 | others | 533 | coconut-svsm | stefano-garzarella | @@ -438,6 +450,30 @@ impl PerCpu {
self.ghcb.get()
}
+ /// Allocates hypercall input/output pages for this CPU.
+ pub fn allocate_hypercall_pages(&self) -> Result<(), SvsmError> {
+ let vaddr = allocate_pages(2)?;
+ let pages = (
+ VirtPhysPair::new(vaddr),
+ VirtPhysPair::new(vaddr + PAGE_SIZE),
+ );
+ *self.hypercall_pages.borrow_mut() = Some(pages);
+ Ok(())
+ }
+
+ pub fn get_hypercall_pages(&self) -> HypercallPagesGuard<'_> {
+ // The hypercall page cell is never mutated, but is borrowed mutably
+ // to ensure that only a single reference can ever be taken at a time.
+ let page_ref: RefMut<'_, Option<(VirtPhysPair, VirtPhysPair)>> =
+ self.hypercall_pages.borrow_mut();
+ unsafe {
+ // SAFETY - the virtual addresses were allocated when the hypercall | This should be the last block to be fixed, then the rest seems okay to me. Thank you! |
svsm | github_2023 | others | 525 | coconut-svsm | vijaydhanraj | @@ -51,18 +52,34 @@ pub fn exec_user(binary: &str) -> Result<(), SvsmError> {
for seg in elf_bin.image_load_segment_iter(virt_base) {
let virt_start = VirtAddr::from(seg.vaddr_range.vaddr_begin);
let virt_end = VirtAddr::from(seg.vaddr_range.vaddr_end).align_up(PAGE_SIZE);
+ let virt_len = virt_end - virt_start;
let file_offset = seg.file_range.offset_begin;
- let len = virt_end - virt_start;
+ let file_end = seg.file_range.offset_end;
+ let file_len = file_end - file_offset;
let flags = convert_elf_phdr_flags(seg.flags);
if !virt_start.is_aligned(PAGE_SIZE) {
return Err(SvsmError::Mem);
}
if file_offset > 0 {
- task.mmap_user(virt_start, Some(&fh), file_offset, len, flags)?;
+ // Map file part | ELF spec states that `file_len` (`p_filesz`)may not be larger than ` virt_len`(`p_memsz`), so it may be better to check for this error condition. |
svsm | github_2023 | others | 525 | coconut-svsm | vijaydhanraj | @@ -51,18 +52,34 @@ pub fn exec_user(binary: &str) -> Result<(), SvsmError> {
for seg in elf_bin.image_load_segment_iter(virt_base) {
let virt_start = VirtAddr::from(seg.vaddr_range.vaddr_begin);
let virt_end = VirtAddr::from(seg.vaddr_range.vaddr_end).align_up(PAGE_SIZE);
+ let virt_len = virt_end - virt_start;
let file_offset = seg.file_range.offset_begin;
- let len = virt_end - virt_start;
+ let file_end = seg.file_range.offset_end;
+ let file_len = file_end - file_offset;
let flags = convert_elf_phdr_flags(seg.flags);
if !virt_start.is_aligned(PAGE_SIZE) { | While we are at it, it is also better to fix the `virt_start` alignment requirement. ELF spec doesn't seem to mandate that `virt_start` (or in other words `p_vaddr`) should be page aligned.
|
svsm | github_2023 | others | 510 | coconut-svsm | Freax13 | @@ -90,7 +90,16 @@ impl VMFileMapping {
.mapping(offset + page_index * PAGE_SIZE)
.ok_or(SvsmError::Mem)?;
if flags.contains(VMFileMappingFlags::Private) {
- pages.push(page_ref.try_copy_page()?);
+ let private_page_ref = page_ref.try_copy_page()?;
+ if page_index == count - 1
+ && flags.contains(VMFileMappingFlags::Write) | Why do we need to check if the page is writable? |
svsm | github_2023 | others | 510 | coconut-svsm | Freax13 | @@ -53,14 +54,32 @@ pub fn exec_user(binary: &str) -> Result<(), SvsmError> {
let virt_end = VirtAddr::from(seg.vaddr_range.vaddr_end).align_up(PAGE_SIZE);
let file_offset = seg.file_range.offset_begin;
let len = virt_end - virt_start;
+ let file_size = seg.file_range.offset_end - seg.file_range.offset_begin;
let flags = convert_elf_phdr_flags(seg.flags);
- if !virt_start.is_aligned(PAGE_SIZE) {
- return Err(SvsmError::Mem);
- }
-
if file_offset > 0 {
- task.mmap_user(virt_start, Some(&fh), file_offset, len, flags)?;
+ if file_size > len {
+ return Err(SvsmError::Elf(elf::ElfError::InvalidFileRange));
+ }
+
+ // Handle unaligned VirtAddr and Offset
+ let (start_aligned, offset, size) = if !virt_start.is_aligned(PAGE_SIZE) {
+ (
+ virt_start.page_align(),
+ file_offset - virt_start.page_offset(),
+ file_size + virt_start.page_offset(),
+ )
+ } else {
+ (virt_start, file_offset, file_size)
+ }; | We don't need this if-block here, do we? The calculations also work out if we always use `virt_start.page_align()`, `file_offset - virt_start.page_offset()`, and `file_size + virt_start.page_offset()`, don't they? |
svsm | github_2023 | others | 510 | coconut-svsm | joergroedel | @@ -90,7 +90,13 @@ impl VMFileMapping {
.mapping(offset + page_index * PAGE_SIZE)
.ok_or(SvsmError::Mem)?;
if flags.contains(VMFileMappingFlags::Private) {
- pages.push(page_ref.try_copy_page()?);
+ let private_page_ref = page_ref.try_copy_page()?;
+ if page_index == count - 1 && !is_aligned(size as u64, PAGE_SIZE as u64) {
+ let start = private_page_ref.virt_addr() + (size & (PAGE_SIZE - 1));
+ let end = private_page_ref.virt_addr() + PAGE_SIZE;
+ zero_mem_region(start, end);
+ }
+ pages.push(private_page_ref); | I wonder why this is necessary. File pages are zeroed out on allocation and try_copy_page() always copies full pages. The truncate operation on files also zeroes out all content after new EOF. So anything in the page after EOF should already be zero. |
svsm | github_2023 | others | 510 | coconut-svsm | joergroedel | @@ -53,14 +54,26 @@ pub fn exec_user(binary: &str) -> Result<(), SvsmError> {
let virt_end = VirtAddr::from(seg.vaddr_range.vaddr_end).align_up(PAGE_SIZE);
let file_offset = seg.file_range.offset_begin;
let len = virt_end - virt_start;
+ let file_size = seg.file_range.offset_end - seg.file_range.offset_begin;
let flags = convert_elf_phdr_flags(seg.flags);
- if !virt_start.is_aligned(PAGE_SIZE) {
- return Err(SvsmError::Mem);
- }
-
if file_offset > 0 {
- task.mmap_user(virt_start, Some(&fh), file_offset, len, flags)?;
+ if file_size > len {
+ return Err(SvsmError::Elf(elf::ElfError::InvalidFileRange));
+ }
+
+ // Handle unaligned VirtAddr and Offset
+ let start_aligned = virt_start.page_align();
+ let offset = file_offset - virt_start.page_offset();
+ let size = file_size + virt_start.page_offset();
+ task.mmap_user(start_aligned, Some(&fh), offset, size, flags)?;
+
+ let size_aligned = align_up(size, PAGE_SIZE);
+ if size_aligned < len {
+ let start_anon = start_aligned.const_add(size_aligned);
+ let remaining_len = len - size_aligned;
+ task.mmap_user(start_anon, None, 0, remaining_len, flags)?;
+ } | Okay, I missed that and have a similar fix in #525 (As I have seen you just noticed as well :) ). |
svsm | github_2023 | others | 518 | coconut-svsm | vijaydhanraj | @@ -0,0 +1,32 @@
+{
+ "igvm": {
+ "output": "coconut-qemu.igvm",
+ "target": "qemu",
+ "platforms": ["snp", "tdp"],
+ "policy": "0x30000",
+ "measure": "print",
+ "check-kvm": true
+ },
+
+ "kernel": {
+ "tdx-stage1": {
+ "type": "make",
+ "file": "bin/stage1-trampoline", | Would it be better to rename it explicitly as `output_file`? |
svsm | github_2023 | others | 518 | coconut-svsm | vijaydhanraj | @@ -0,0 +1,32 @@
+{
+ "igvm": {
+ "output": "coconut-qemu.igvm",
+ "target": "qemu",
+ "platforms": ["snp", "tdp"],
+ "policy": "0x30000",
+ "measure": "print",
+ "check-kvm": true
+ },
+
+ "kernel": {
+ "tdx-stage1": {
+ "type": "make",
+ "file": "bin/stage1-trampoline",
+ "objcopy": "binary"
+ },
+ "stage2" : {
+ "manifest": "kernel/Cargo.toml",
+ "features": "default", | Build recipes documentation specifies default value for `features` is empty but here we have added `default`. Is this necessary? Also, for other attributes like `policy` which seems to have a default value of `0x30000`. Should this be explicitly added? |
svsm | github_2023 | others | 518 | coconut-svsm | vijaydhanraj | @@ -0,0 +1,167 @@
+# COCONUT Build Recipes Format
+
+This document describes the format of COCONUT build recipes as consumed by the
+`scripts/build.py` script. The script takes a build recipe as input and builds
+all tooling and component to generate an IGVM output file.
+
+Build recipes, as IGVM files, are hypervisor specific. The COCONUT source
+repository ships with ready-to-use recipes for all supported hypervisors.
+
+## General Format
+
+A build recipe is a text file containing a JSON object. The top-level object
+has attributes which point to sub-objects describing different parts of the
+build process.
+
+The currently recognized attributes are:
+
+* `igvm`: Parameters for creating the IGVM file.
+* `kernel`: Configuration for compiling the COCONUT kernel and its boot stages.
+* `firmware`: Information on how to retrieve the guest firmware to put into the
+ IGVM output file (optional).
+
+The objects these attributes point to are described in more detail below:
+
+## `igvm`: Parameter for IGVM File Creation
+
+The `igvm` attribute points to an object containing parameters for invoking the
+`igvmbuilder` and `igvmmeasure` tools.
+
+The supported attributes are described below.
+
+### `output`: Output File Name
+
+The name of the output file to generate. The file will be placed in the `bin/`
+directory.
+
+### `target`: Target hypervisor
+
+The hypervisor for which the IGVM file is generated. The supported values are:
+
+* `qemu`: QEMU/KVM
+* `hyper-v`: Microsoft Hyper-V
+* `vanadium`: Google Vanadium Hypervisor
+
+### `platforms`: Host Platforms the IGVM File Supports
+
+This attribute takes an array with a list of platforms to support in the output
+IGVM file. The supported platforms are:
+
+* `native`: Non-confidential guest environment.
+* `snp`: AMD SEV-SNP guest environment.
+* `tdp`: Intel TDX guest environment with support for TD-Partitioning.
+* `vsm`: Hyper-V Virtual Secure Mode.
+
+### `policy`: Value of the Policy Field on the SEV-SNP Platform
+
+This is a hex value with the `policy` field used when creating an AMD SEV-SNP
+virtual machine with the IGVM file (default: `0x30000`).
+
+### `comport`: Serial Port Number to use for the Console
+
+This attribute specifies the number of the serial port COCONUT uses for console
+output.
+
+### `measure`: Expected Launch Measurement Calculation
+
+This has only one supported value for now: `print`. The build script will
+invoke the `igvmmeasure` tool on the IGVM file to print the expected SEV-SNP
+launch measurement for the specified target hypervisor.
+
+### `check-kvm`: Calculate Launch Measurement for KVM-based Hypervisors
+
+This attribute takes a boolean value which must be set to `true` if the target
+hypervisor is based on the Linux Kernel Virtual Machine (KVM). It is used to
+calculate the correct expected launch measurement for KVM-based hypervisors.
+Default value is `false`.
+
+### `measure-native-zeroes`: How to Measure Zero-Pages
+
+This is a boolean flag which defines how zero-pages are treated when
+calculating the expected launch measurement. The behavior is:
+
+* If `true`: Use native SEV-SNP zero-page type for measurement.
+* If `false`: Measure pages as data-pages containing all zeroes.
+
+The default value is `false`. Whether this setting is needed depends on how the
+hypervisor loads the IGVM file.
+
+## `kernel`: Definitions for Building COCONUT Kernel Parts
+
+The `kernel` attribute points to a JSON object whose attributes describe how to
+build the individual parts of the COCONUT kernel. The recognized attributes are:
+
+* `tdx-stage1`: Stage1 needed for TD-Partitioning platforms
+* `stage2`: The stage2 loader of the COCONUT kernel
+* `svsm`: The COCONUT kernel itself.
+
+Each attribute points to another object describing the build parameters. For
+all three parts of the kernel recognize the same build parameters. They are
+described in the following sections.
+
+### `type`: The Build Type
+
+This attribute currently has two supported values:
+
+* `cargo`: Build the component with cargo.
+* `make`: Run GNU make to build the component.
+
+The default is `cargo`. Some of the other attributes are specific to either
+build type.
+
+### `file`: Expected Build Output File
+
+This is the expected output filename of the build run. It is only recognized
+for `make` builds and used as the make target.
+
+### `manifest`: Build Manifest to use for Cargo.
+
+Path to the `Cargo.toml` file to pass as the build manifest when running cargo.
+Default is `None`.
+
+### `features`: Cargo Features to use for Kernel Component
+
+This attribute points to a comma-separated list of cargo features to enable
+when building the specified component. Default is empty.
+
+### `binary`: Whether to Build a Package or Binary
+
+This is a boolean value and defines the way cargo is invoked:
+
+* If `true`, the component is build with the `--bin` parameter to cargo.
+* If `false`, the component is build from the cargo workspace with the | `build` -> `built`? |
svsm | github_2023 | python | 518 | coconut-svsm | stefano-garzarella | @@ -0,0 +1,565 @@
+#!/usr/bin/env python3
+#
+
+import subprocess
+import argparse
+import platform
+import json
+import os
+
+class CargoRunner:
+ """
+ A class for running cargo to build specific packages from the workspace.
+ """
+
+ def __init__(self, package):
+ self.package = package
+ self.binary = False
+ self.features = []
+ self.release = False
+ self.target = None
+ self.manifest = None
+ self.offline = False
+ self.verbose = False
+
+ def set_package(self, package):
+ """
+ Sets the package to build.
+ """
+ self.package = package
+
+ def enable_binary(self):
+ """
+ Builds a binary instead of a package (--package vs. --bin)
+ """
+ self.binary = True
+
+ def add_feature(self, feature):
+ """
+ Adds a feature to build with.
+ """
+ self.features.append(feature)
+
+ def enable_release(self):
+ """
+ Sets whether to build in release mode.
+ """
+ self.release = True
+
+ def set_target(self, target):
+ """
+ Sets the target to build for.
+ """
+ self.target = target
+
+ def set_manifest(self, manifest):
+ """
+ Sets the manifest to build with.
+ """
+ self.manifest = manifest
+
+ def enable_offline(self):
+ """
+ Enable offline builds.
+ """
+ self.offline = True
+
+ def enable_verbose(self):
+ """
+ Enable verbosity build output
+ """
+ self.verbose = True
+
+ def execute(self):
+ """
+ Executes the cargo command.
+ """
+ if self.package is None:
+ raise ValueError("Package not set")
+
+ command = ["cargo", "build"]
+ if self.verbose:
+ command.append("-vv")
+ if self.binary:
+ command.extend(["--bin", self.package])
+ else:
+ command.extend(["--package", self.package])
+
+ if self.offline:
+ command.extend(["--locked", "--offline"])
+ if self.features:
+ command.extend(["--features", ",".join(self.features)])
+ if self.manifest:
+ command.extend(["--manifest-path", self.manifest])
+ if self.release:
+ command.append("--release")
+ if self.target:
+ command.extend(["--target", self.target])
+
+ if self.verbose:
+ print(command)
+ subprocess.run(command, check=True)
+
+ def get_binary_path(self):
+ """
+ Gets the path of the resulting binary.
+ """
+ target_dir = "target"
+ if self.target:
+ target_dir = os.path.join(target_dir, self.target)
+ binary_dir = os.path.join(target_dir, "release" if self.release else "debug")
+ return os.path.join(binary_dir, self.package)
+
+def parse_kernel(recipe):
+ """
+ Parse a recipe for a single kernel component like tdx-stage1, stage2 or svsm.
+
+ Args:
+ recipe: A build data structure from a parsed JSON document.
+
+ Returns:
+ A sanitized dictionary with component-related build parameters.
+ """
+ kernel_config = {}
+
+ for package, settings in recipe.items():
+ kernel_config[package] = {
+ "type": settings.get("type", "cargo"),
+ "file": settings.get("output_file", None),
+ "manifest": settings.get("manifest", None),
+ "features": settings.get("features", "").split(),
+ "binary": settings.get("binary", False),
+ "objcopy": settings.get("objcopy", get_svsm_elf_target())
+ }
+
+ return kernel_config
+
+def kernel_recipe(config):
+ """
+ Parses the JSON configuration for kernel components.
+
+ Args:
+ json_data: A Python dictionary representing the configuration.
+
+ Returns:
+ A dictionary with parsed build settings for each component.
+ """
+
+ kernel_json = config.get("kernel", {})
+
+ return parse_kernel(kernel_json)
+
+def igvm_recipe(config):
+ """
+ Parse a parameters for the IGVM file to build.
+
+ Args:
+ config: A Python dictionary from a parsed JSON document.
+
+ Returns:
+ A sanitized dictionary with IGVM build parameters.
+ """
+ igvm_json = config.get("igvm", {})
+
+ igvm_config = {
+ "policy": igvm_json.get("policy", "0x30000"),
+ "target": igvm_json.get("target", "qemu"),
+ "output": igvm_json.get("output", "default.json"),
+ "comport": igvm_json.get("comport", None),
+ "platforms": igvm_json.get("platforms", ["snp", "tdp", "vsm"]),
+ "measure": igvm_json.get("measure", "print"),
+ "measure-native-zeroes": igvm_json.get("measure-native-zeroes", False),
+ "check-kvm": igvm_json.get("check-kvm", False),
+ }
+
+ return igvm_config
+
+def firmware_recipe(config):
+ """
+ Parse a parameters for retrieving the firmware.
+
+ Args:
+ config: A Python dictionary from a parsed JSON document.
+
+ Returns:
+ A sanitized dictionary with firmware build/retrieval parameters.
+ """
+ firmware_json = config.get("firmware", {})
+
+ firmware_config = {
+ "env": firmware_json.get("env", None),
+ "file": firmware_json.get("file", None),
+ "command": firmware_json.get("command", None),
+ }
+
+ if firmware_config["command"] and not isinstance(firmware_config["command"], list):
+ raise ValueError("Value of firmware.command must be a JSON array")
+
+ return firmware_config
+
+def read_recipe(file_path):
+ """
+ Reads a JSON file and parses its content.
+
+ Args:
+ file_path: Path to the JSON file.
+
+ Returns:
+ A Python dictionary representing the parsed JSON data or None in case of
+ a parse error.
+ """
+ try:
+ with open(file_path, 'r') as f:
+ data = json.load(f)
+ return data
+ except FileNotFoundError:
+ print(f"Error: File not found: {file_path}")
+ return None
+ except json.JSONDecodeError as e:
+ print(f"Error: decoding JSON in {file_path}: {e}")
+ return None
+
+def get_host_target():
+ """
+ Returns the Rust target for building the helper utilities (like igvmbuilder
+ and igvmmeasure).
+ """
+ return "x86_64-unknown-linux-gnu"
+
+def get_svsm_kernel_target():
+ """
+ Returns the Rust target for building the helper utilities (like igvmbuilder
+ and igvmmeasure).
+ """
+ return "x86_64-unknown-none"
+
+def get_svsm_user_target():
+ """
+ Returns the Rust target for building the user-space components which are
+ packaged into the SVSM file-system image.
+ """
+ return "x86_64-unknown-none"
+
+def get_svsm_elf_target():
+ """
+ Returns the binutils target used in objcopy when copying the SVSM kernel
+ ELF file.
+ """
+ return "elf64-x86-64"
+
+def objcopy_kernel(binary_path, target_path, elf_target, args):
+ """
+ Execute objcopy to prepare a binary for packaging into the IGVM file.
+
+ Args:
+ binary_path: File path to source binary.
+ target_path: File path where copied binary is stored.
+ target: Binary target to use for the output file. | `s/target/elf_target` |
svsm | github_2023 | python | 518 | coconut-svsm | stefano-garzarella | @@ -0,0 +1,565 @@
+#!/usr/bin/env python3
+#
+
+import subprocess
+import argparse
+import platform
+import json
+import os
+
+class CargoRunner:
+ """
+ A class for running cargo to build specific packages from the workspace.
+ """
+
+ def __init__(self, package):
+ self.package = package
+ self.binary = False
+ self.features = []
+ self.release = False
+ self.target = None
+ self.manifest = None
+ self.offline = False
+ self.verbose = False
+
+ def set_package(self, package):
+ """
+ Sets the package to build.
+ """
+ self.package = package
+
+ def enable_binary(self):
+ """
+ Builds a binary instead of a package (--package vs. --bin)
+ """
+ self.binary = True
+
+ def add_feature(self, feature):
+ """
+ Adds a feature to build with.
+ """
+ self.features.append(feature)
+
+ def enable_release(self):
+ """
+ Sets whether to build in release mode.
+ """
+ self.release = True
+
+ def set_target(self, target):
+ """
+ Sets the target to build for.
+ """
+ self.target = target
+
+ def set_manifest(self, manifest):
+ """
+ Sets the manifest to build with.
+ """
+ self.manifest = manifest
+
+ def enable_offline(self):
+ """
+ Enable offline builds.
+ """
+ self.offline = True
+
+ def enable_verbose(self):
+ """
+ Enable verbosity build output
+ """
+ self.verbose = True
+
+ def execute(self):
+ """
+ Executes the cargo command.
+ """
+ if self.package is None:
+ raise ValueError("Package not set")
+
+ command = ["cargo", "build"]
+ if self.verbose:
+ command.append("-vv")
+ if self.binary:
+ command.extend(["--bin", self.package])
+ else:
+ command.extend(["--package", self.package])
+
+ if self.offline:
+ command.extend(["--locked", "--offline"])
+ if self.features:
+ command.extend(["--features", ",".join(self.features)])
+ if self.manifest:
+ command.extend(["--manifest-path", self.manifest])
+ if self.release:
+ command.append("--release")
+ if self.target:
+ command.extend(["--target", self.target])
+
+ if self.verbose:
+ print(command)
+ subprocess.run(command, check=True)
+
+ def get_binary_path(self):
+ """
+ Gets the path of the resulting binary.
+ """
+ target_dir = "target"
+ if self.target:
+ target_dir = os.path.join(target_dir, self.target)
+ binary_dir = os.path.join(target_dir, "release" if self.release else "debug")
+ return os.path.join(binary_dir, self.package)
+
+def parse_kernel(recipe):
+ """
+ Parse a recipe for a single kernel component like tdx-stage1, stage2 or svsm.
+
+ Args:
+ recipe: A build data structure from a parsed JSON document.
+
+ Returns:
+ A sanitized dictionary with component-related build parameters.
+ """
+ kernel_config = {}
+
+ for package, settings in recipe.items():
+ kernel_config[package] = {
+ "type": settings.get("type", "cargo"),
+ "file": settings.get("output_file", None),
+ "manifest": settings.get("manifest", None),
+ "features": settings.get("features", "").split(),
+ "binary": settings.get("binary", False),
+ "objcopy": settings.get("objcopy", get_svsm_elf_target())
+ }
+
+ return kernel_config
+
+def kernel_recipe(config):
+ """
+ Parses the JSON configuration for kernel components.
+
+ Args:
+ json_data: A Python dictionary representing the configuration.
+
+ Returns:
+ A dictionary with parsed build settings for each component.
+ """
+
+ kernel_json = config.get("kernel", {})
+
+ return parse_kernel(kernel_json)
+
+def igvm_recipe(config):
+ """
+ Parse a parameters for the IGVM file to build.
+
+ Args:
+ config: A Python dictionary from a parsed JSON document.
+
+ Returns:
+ A sanitized dictionary with IGVM build parameters.
+ """
+ igvm_json = config.get("igvm", {})
+
+ igvm_config = {
+ "policy": igvm_json.get("policy", "0x30000"),
+ "target": igvm_json.get("target", "qemu"),
+ "output": igvm_json.get("output", "default.json"),
+ "comport": igvm_json.get("comport", None),
+ "platforms": igvm_json.get("platforms", ["snp", "tdp", "vsm"]),
+ "measure": igvm_json.get("measure", "print"),
+ "measure-native-zeroes": igvm_json.get("measure-native-zeroes", False),
+ "check-kvm": igvm_json.get("check-kvm", False),
+ }
+
+ return igvm_config
+
+def firmware_recipe(config):
+ """
+ Parse a parameters for retrieving the firmware.
+
+ Args:
+ config: A Python dictionary from a parsed JSON document.
+
+ Returns:
+ A sanitized dictionary with firmware build/retrieval parameters.
+ """
+ firmware_json = config.get("firmware", {})
+
+ firmware_config = {
+ "env": firmware_json.get("env", None),
+ "file": firmware_json.get("file", None),
+ "command": firmware_json.get("command", None),
+ }
+
+ if firmware_config["command"] and not isinstance(firmware_config["command"], list):
+ raise ValueError("Value of firmware.command must be a JSON array")
+
+ return firmware_config
+
+def read_recipe(file_path):
+ """
+ Reads a JSON file and parses its content.
+
+ Args:
+ file_path: Path to the JSON file.
+
+ Returns:
+ A Python dictionary representing the parsed JSON data or None in case of
+ a parse error.
+ """
+ try:
+ with open(file_path, 'r') as f:
+ data = json.load(f)
+ return data
+ except FileNotFoundError:
+ print(f"Error: File not found: {file_path}")
+ return None
+ except json.JSONDecodeError as e:
+ print(f"Error: decoding JSON in {file_path}: {e}")
+ return None
+
+def get_host_target():
+ """
+ Returns the Rust target for building the helper utilities (like igvmbuilder
+ and igvmmeasure).
+ """
+ return "x86_64-unknown-linux-gnu"
+
+def get_svsm_kernel_target():
+ """
+ Returns the Rust target for building the helper utilities (like igvmbuilder
+ and igvmmeasure).
+ """
+ return "x86_64-unknown-none"
+
+def get_svsm_user_target():
+ """
+ Returns the Rust target for building the user-space components which are
+ packaged into the SVSM file-system image.
+ """
+ return "x86_64-unknown-none"
+
+def get_svsm_elf_target():
+ """
+ Returns the binutils target used in objcopy when copying the SVSM kernel
+ ELF file.
+ """
+ return "elf64-x86-64"
+
+def objcopy_kernel(binary_path, target_path, elf_target, args):
+ """
+ Execute objcopy to prepare a binary for packaging into the IGVM file.
+
+ Args:
+ binary_path: File path to source binary.
+ target_path: File path where copied binary is stored.
+ target: Binary target to use for the output file.
+ args: A structure initialized from command line options.
+ """
+ command = ["objcopy", "-O", elf_target, "--strip-unneeded"]
+ command.append(binary_path)
+ command.append(target_path)
+ if args.verbose:
+ print(command)
+ subprocess.run(command, check=True)
+
+def cargo_build(package, config, target, args):
+ """
+ Run a single build step using cargo.
+
+ Args:
+ package: Name of the workspace package or binary to build.
+ config: A Python dictionary carrying the cargo specific build options.
+ target: Rust target to build for.
+ args: A structure initialized from command line options.
+
+ Returns:
+ Path to the binary built with cargo.
+ """
+ runner = CargoRunner(package)
+ runner.set_target(target)
+ for feature in config.get("features", []):
+ runner.add_feature(feature)
+ if config.get("binary"):
+ runner.enable_binary()
+ if config.get("manifest"):
+ runner.set_manifest(config.get("manifest"))
+ if args.release:
+ runner.enable_release()
+ if args.verbose:
+ runner.enable_verbose()
+ if args.offline:
+ runner.enable_offline()
+
+ runner.execute()
+
+ return runner.get_binary_path()
+
+def make_build(package, config, args):
+ """
+ Run a single build step using GNU Make.
+
+ Args:
+ package: Name of the package to build.
+ config: A Python dictionary carrying the make specific build options.
+ args: A structure initialized from command line options.
+
+ Returns:
+ Path to the make target which was built.
+ """
+ if config["file"]:
+ command = ["make", config["file"]]
+ if args.verbose:
+ command.append("V=2")
+ print(command)
+ subprocess.run(command, check=True)
+ return config["file"]
+ else:
+ raise ValueError("Build type make in package {} requires an 'output_file' attribute".format(package));
+
+def recipe_build(recipe, target, args):
+ """
+ Takes a list of package build recipes and builds them one by one.
+
+ Args:
+ recipe: A Python dictionary with package name as the key and another
+ dictionary with build options as their value.
+ target: Rust target to use for cargo builds
+ args: A structure initialized from command line options.
+
+ Returns:
+ A Python dictionary with package names as key and paths to built binaries
+ as value.
+ """
+ binaries = {}
+ for package, config in recipe.items():
+ print("Building {}...".format(package))
+ build_type = config.get("type", "cargo")
+ if build_type == "cargo":
+ binary = cargo_build(package, config, target, args)
+ elif build_type == "make":
+ binary = make_build(package, config, args)
+ else:
+ raise ValueError("Unknown build type: {}".format(build_type))
+
+ binaries[package] = binary
+
+ return binaries
+
+def build_helpers(args):
+ """
+ Build the tooling needed to create the IGVM file and its components.
+ Currently it takes care of building the igvmbuilder and the igvmmeasure tool.
+
+ Args:
+ args: A structure initialized from command line options.
+
+ Returns:
+ A Python dictionary with build names as key and paths to their binaries
+ as value.
+ """
+ helpers = {
+ "igvmbuilder": {},
+ "igvmmeasure": {}
+ }
+ return recipe_build(helpers, get_host_target(), args)
+
+def build_kernel_parts(k_recipe, args):
+ """
+ Build all parts needed for the COCONUT kernel as specified in the JSON file.
+
+ Args:
+ k_recipe: A Python dictionary with the build options for each kernel part.
+ args: A structure initialized from command line options.
+
+ Returns:
+ A Python dictionary with kernel parts as key and paths to theor binary
+ files as value.
+ """
+ parts = {}
+ binaries = recipe_build(k_recipe, get_svsm_kernel_target(), args)
+ for binary, source_path in binaries.items():
+ bin_target = k_recipe[binary].get("objcopy", get_svsm_elf_target());
+ target_path = "bin/{}".format(binary)
+ objcopy_kernel(source_path, target_path, bin_target, args)
+ parts[binary] = target_path
+
+ return parts
+
+def build_firmware(args, firmware_config):
+ """
+ Retrieves and/or builds the firmware to package into the IGVM file.
+
+ Args:
+ args: A structure initialized from command line options.
+ firmware_config: A Python dictionary with options on how to
+ build/retrieve the firmware.
+
+ Returns:
+ Path to the firmware file to package or None.
+ """
+ if firmware_config["command"]:
+ if args.verbose:
+ print(firmware_config["command"])
+ subprocess.run(firmware_config["command"], check=True)
+ if firmware_config["file"]:
+ return firmware_config["file"]
+ elif firmware_config["env"]:
+ return os.getenv(firmware_config["env"])
+ else:
+ return None
+
+def build_igvm_file(args, helpers, igvm_config):
+ """
+ Takes the collected information and binaries and builds the resulting IGVM
+ file as specified in the JSON recipe. It will also invoke igvmmeasure to
+ calculate the expected launch measurement.
+
+ Args:
+ args: A structure initialized from command line options.
+ helpers: A Python dictionary with the helper tools to use, as returned by
+ build_helpers().
+ igvm_config: A Python dictionary with all necessary information and
+ parameters to build the IGVM file.
+
+ Returns:
+ Path to the firmware file to package or None. | Maybe a leftover, IIUC this function doesn't return anything, right? |
svsm | github_2023 | others | 518 | coconut-svsm | stefano-garzarella | @@ -0,0 +1,167 @@
+# COCONUT Build Recipes Format
+
+This document describes the format of COCONUT build recipes as consumed by the
+`scripts/build.py` script. The script takes a build recipe as input and builds
+all tooling and component to generate an IGVM output file.
+
+Build recipes, as IGVM files, are hypervisor specific. The COCONUT source
+repository ships with ready-to-use recipes for all supported hypervisors.
+
+## General Format
+
+A build recipe is a text file containing a JSON object. The top-level object
+has attributes which point to sub-objects describing different parts of the
+build process.
+
+The currently recognized attributes are:
+
+* `igvm`: Parameters for creating the IGVM file.
+* `kernel`: Configuration for compiling the COCONUT kernel and its boot stages.
+* `firmware`: Information on how to retrieve the guest firmware to put into the
+ IGVM output file (optional).
+
+The objects these attributes point to are described in more detail below:
+
+## `igvm`: Parameter for IGVM File Creation
+
+The `igvm` attribute points to an object containing parameters for invoking the
+`igvmbuilder` and `igvmmeasure` tools.
+
+The supported attributes are described below.
+
+### `output`: Output File Name
+
+The name of the output file to generate. The file will be placed in the `bin/`
+directory.
+
+### `target`: Target hypervisor
+
+The hypervisor for which the IGVM file is generated. The supported values are:
+
+* `qemu`: QEMU/KVM
+* `hyper-v`: Microsoft Hyper-V
+* `vanadium`: Google Vanadium Hypervisor
+
+### `platforms`: Host Platforms the IGVM File Supports
+
+This attribute takes an array with a list of platforms to support in the output
+IGVM file. The supported platforms are:
+
+* `native`: Non-confidential guest environment.
+* `snp`: AMD SEV-SNP guest environment.
+* `tdp`: Intel TDX guest environment with support for TD-Partitioning.
+* `vsm`: Hyper-V Virtual Secure Mode.
+
+### `policy`: Value of the Policy Field on the SEV-SNP Platform
+
+This is a hex value with the `policy` field used when creating an AMD SEV-SNP
+virtual machine with the IGVM file (default: `0x30000`).
+
+### `comport`: Serial Port Number to use for the Console
+
+This attribute specifies the number of the serial port COCONUT uses for console
+output.
+
+### `measure`: Expected Launch Measurement Calculation
+
+This has only one supported value for now: `print`. The build script will
+invoke the `igvmmeasure` tool on the IGVM file to print the expected SEV-SNP
+launch measurement for the specified target hypervisor.
+
+### `check-kvm`: Calculate Launch Measurement for KVM-based Hypervisors
+
+This attribute takes a boolean value which must be set to `true` if the target
+hypervisor is based on the Linux Kernel Virtual Machine (KVM). It is used to
+calculate the correct expected launch measurement for KVM-based hypervisors.
+Default value is `false`.
+
+### `measure-native-zeroes`: How to Measure Zero-Pages
+
+This is a boolean flag which defines how zero-pages are treated when
+calculating the expected launch measurement. The behavior is:
+
+* If `true`: Use native SEV-SNP zero-page type for measurement.
+* If `false`: Measure pages as data-pages containing all zeroes.
+
+The default value is `false`. Whether this setting is needed depends on how the
+hypervisor loads the IGVM file.
+
+## `kernel`: Definitions for Building COCONUT Kernel Parts
+
+The `kernel` attribute points to a JSON object whose attributes describe how to
+build the individual parts of the COCONUT kernel. The recognized attributes are:
+
+* `tdx-stage1`: Stage1 needed for TD-Partitioning platforms
+* `stage2`: The stage2 loader of the COCONUT kernel
+* `svsm`: The COCONUT kernel itself.
+
+Each attribute points to another object describing the build parameters. For
+all three parts of the kernel recognize the same build parameters. They are
+described in the following sections.
+
+### `type`: The Build Type
+
+This attribute currently has two supported values:
+
+* `cargo`: Build the component with cargo.
+* `make`: Run GNU make to build the component.
+
+The default is `cargo`. Some of the other attributes are specific to either | What about avoiding defaults?
When I was reading the json, I was a bit confused seeing `type` just for `make`.
Not a strong opinion, just my feeling. |
svsm | github_2023 | others | 526 | coconut-svsm | stefano-garzarella | @@ -15,25 +15,19 @@ const EFLAGS_IF: u64 = 1 << 9;
/// Unconditionally disable IRQs
///
-/// # Safety
-///
/// Callers need to take care of re-enabling IRQs.
-#[inline(always)] | Is removing `#[inline(always)]` intentional?
Not sure if we really need it or not, just asking ;-) |
svsm | github_2023 | others | 526 | coconut-svsm | stefano-garzarella | @@ -15,25 +15,19 @@ const EFLAGS_IF: u64 = 1 << 9;
/// Unconditionally disable IRQs
///
-/// # Safety
-///
/// Callers need to take care of re-enabling IRQs.
-#[inline(always)]
-pub unsafe fn raw_irqs_disable() {
+pub fn raw_irqs_disable() {
unsafe {
asm!("cli", options(att_syntax, preserves_flags, nomem));
}
}
/// Unconditionally enable IRQs
///
-/// # Safety
-///
/// Callers need to make sure it is safe to enable IRQs. e.g. that no data
/// structures or locks which are accessed in IRQ handlers are used after IRQs
/// have been enabled.
-#[inline(always)] | Ditto. |
svsm | github_2023 | others | 526 | coconut-svsm | stefano-garzarella | @@ -455,9 +455,7 @@ pub extern "C" fn stage2_main(launch_info: &Stage2LaunchInfo) {
// Shut down the GHCB
unsafe {
shutdown_percpu();
- } | I am not sure if this is a good practice, there is also a lint, to eventually enable, to discourage this:
https://rust-lang.github.io/rust-clippy/master/index.html#multiple_unsafe_ops_per_block
That said, I don't have a strong opinion since we already do this in several places, but maybe in the future we could avoid it and enable that lint. |
svsm | github_2023 | others | 524 | coconut-svsm | msft-jlange | @@ -10,24 +10,39 @@ use crate::error::SvsmError;
pub enum TdxError {
Unknown(u64),
Unimplemented,
+ OperandBusy,
PageAlreadyAccepted,
PageSizeMismatch,
}
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum TdVmcallError {
+ Unknown(u64),
+}
+
impl From<TdxError> for SvsmError {
fn from(err: TdxError) -> SvsmError {
SvsmError::Tdx(err)
}
}
-pub fn tdx_result(err: u64) -> Result<u64, TdxError> {
+pub fn tdx_result(err: u64) -> Result<(), TdxError> {
let code = err >> 32;
- if code < 0x8000_0000 {
- return Ok(code);
+ if code == 0 { | The TDX architecture defines results codes less than 0x8000_0000_0000_0000 as non-fatal conditions. We can't treat a non-zero success condition as an error. This is why this function is defined to return a `u64` in the `Ok` variant of the result - to provide a specific value of the success return in case it is a non-zero success value. |
svsm | github_2023 | others | 524 | coconut-svsm | msft-jlange | @@ -50,14 +50,28 @@ unsafe fn tdg_mem_page_accept(frame: PageFrame) -> u64 {
let mut ret: u64;
unsafe {
asm!("tdcall",
- in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rax") TDG_MEM_PAGE_ACCEPT,
in("rcx") EptMappingInfo::from(frame).into_bits(),
lateout("rax") ret,
options(att_syntax));
}
ret
}
+/// # Safety
+/// This function has the potential to zero arbitrary memory, so the caller is
+/// required to ensure that the supplied physical address range is appropriate
+/// for acceptance.
+unsafe fn accept_one_page(frame: PageFrame) -> Result<(), TdxError> {
+ for _ in 0..10000 {
+ match tdx_result(tdg_mem_page_accept(frame)) {
+ Err(TdxError::OperandBusy) => continue, | My understanding is that TDX_OPERAND_BUSY only applies to TDH operations and not TDG operations. When a TDG operation encounters a busy state, the TDX module will simply not advance RIP past the `tdcall` instruction, so the TD will naturally just reattempt the same call again. |
svsm | github_2023 | others | 524 | coconut-svsm | msft-jlange | @@ -50,14 +50,28 @@ unsafe fn tdg_mem_page_accept(frame: PageFrame) -> u64 {
let mut ret: u64;
unsafe {
asm!("tdcall",
- in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rax") TDG_MEM_PAGE_ACCEPT,
in("rcx") EptMappingInfo::from(frame).into_bits(),
lateout("rax") ret,
options(att_syntax));
}
ret
}
+/// # Safety
+/// This function has the potential to zero arbitrary memory, so the caller is
+/// required to ensure that the supplied physical address range is appropriate
+/// for acceptance.
+unsafe fn accept_one_page(frame: PageFrame) -> Result<(), TdxError> {
+ for _ in 0..10000 { | What makes 10000 - or any other arbitrary constant - a reasonable retry count? Any retry count needs to be justified with on an architectural basis. |
svsm | github_2023 | others | 524 | coconut-svsm | msft-jlange | @@ -50,14 +50,28 @@ unsafe fn tdg_mem_page_accept(frame: PageFrame) -> u64 {
let mut ret: u64;
unsafe {
asm!("tdcall",
- in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rax") TDG_MEM_PAGE_ACCEPT,
in("rcx") EptMappingInfo::from(frame).into_bits(),
lateout("rax") ret,
options(att_syntax));
}
ret
}
+/// # Safety
+/// This function has the potential to zero arbitrary memory, so the caller is
+/// required to ensure that the supplied physical address range is appropriate
+/// for acceptance.
+unsafe fn accept_one_page(frame: PageFrame) -> Result<(), TdxError> { | Assuming my statement about retries on `tdcall` operations is correct, this function is not needed at all. |
svsm | github_2023 | others | 524 | coconut-svsm | msft-jlange | @@ -10,24 +10,39 @@ use crate::error::SvsmError;
pub enum TdxError {
Unknown(u64),
Unimplemented,
+ OperandBusy,
PageAlreadyAccepted,
PageSizeMismatch,
}
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum TdVmcallError { | I don't see any conversion path from `TdVmcallError` to `SvsmError`. We want to ensure that all defined error types can be represented in `SvsmError`. I suspect that the best way to do this is not to define `TdVmcallError` as a separate class, but rather as an element of `TdxError`. Then your ` tdvmcall_result` function could return `TdxError::TdVmcallError(result)` and stay within the error class that is already established. |
svsm | github_2023 | others | 524 | coconut-svsm | msft-jlange | @@ -216,35 +222,41 @@ pub unsafe fn td_accept_virtual_memory(region: MemoryRegion<VirtAddr>) -> Result
pub fn tdvmcall_halt() {
let pass_regs = (1 << 10) | (1 << 11) | (1 << 12);
+ let mut ret: u64;
unsafe {
asm!("tdcall",
in("rax") TDG_VP_TDVMCALL,
in("rcx") pass_regs,
in("r10") 0,
in("r11") TDVMCALL_HLT,
in("r12") 0,
+ lateout("rax") ret,
lateout("r10") _,
lateout("r11") _,
lateout("r12") _,
options(att_syntax));
}
+ debug_assert!(tdx_result(ret).is_ok());
+ // r10 is guaranteed to be TDG.VP.VMCALL_SUCCESS | R10 isn't trusted so it isn't guaranteed to be anything. However, there's nothing this code can do based on the contents of R10. It may be more helpful to change the comment to indicate this: R10 is *expected* to be zero but the untrusted host can do anything it wants, so we assert in case we want to be aware of something unexpected. |
svsm | github_2023 | others | 486 | coconut-svsm | Freax13 | @@ -0,0 +1,387 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Ziqiao Zhou <ziqiaozhou@microsoft.com>
+use vstd::arithmetic::power2::pow2;
+use vstd::bits::low_bits_mask;
+use vstd::prelude::*;
+
+#[macro_export]
+macro_rules! POW2_VALUE {
+ (0) => {
+ 0x1u64
+ };
+ (1) => {
+ 0x2u64
+ };
+ (2) => {
+ 0x4u64
+ };
+ (3) => {
+ 0x8u64
+ };
+ (4) => {
+ 0x10u64
+ };
+ (5) => {
+ 0x20u64
+ };
+ (6) => {
+ 0x40u64
+ };
+ (7) => {
+ 0x80u64
+ };
+ (8) => {
+ 0x100u64
+ };
+ (9) => {
+ 0x200u64
+ };
+ (10) => {
+ 0x400u64
+ };
+ (11) => {
+ 0x800u64
+ };
+ (12) => {
+ 0x1000u64
+ };
+ (13) => {
+ 0x2000u64
+ };
+ (14) => {
+ 0x4000u64
+ };
+ (15) => {
+ 0x8000u64
+ };
+ (16) => {
+ 0x10000u64
+ };
+ (17) => {
+ 0x20000u64
+ };
+ (18) => {
+ 0x40000u64
+ };
+ (19) => {
+ 0x80000u64
+ };
+ (20) => {
+ 0x100000u64
+ };
+ (21) => {
+ 0x200000u64
+ };
+ (22) => {
+ 0x400000u64
+ };
+ (23) => {
+ 0x800000u64
+ };
+ (24) => {
+ 0x1000000u64
+ };
+ (25) => {
+ 0x2000000u64
+ };
+ (26) => {
+ 0x4000000u64
+ };
+ (27) => {
+ 0x8000000u64
+ };
+ (28) => {
+ 0x10000000u64
+ };
+ (29) => {
+ 0x20000000u64
+ };
+ (30) => {
+ 0x40000000u64
+ };
+ (31) => {
+ 0x80000000u64
+ };
+ (32) => {
+ 0x100000000u64
+ };
+ (33) => {
+ 0x200000000u64
+ };
+ (34) => {
+ 0x400000000u64
+ };
+ (35) => {
+ 0x800000000u64
+ };
+ (36) => {
+ 0x1000000000u64
+ };
+ (37) => {
+ 0x2000000000u64
+ };
+ (38) => {
+ 0x4000000000u64
+ };
+ (39) => {
+ 0x8000000000u64
+ };
+ (40) => {
+ 0x10000000000u64
+ };
+ (41) => {
+ 0x20000000000u64
+ };
+ (42) => {
+ 0x40000000000u64
+ };
+ (43) => {
+ 0x80000000000u64
+ };
+ (44) => {
+ 0x100000000000u64
+ };
+ (45) => {
+ 0x200000000000u64
+ };
+ (46) => {
+ 0x400000000000u64
+ };
+ (47) => {
+ 0x800000000000u64
+ };
+ (48) => {
+ 0x1000000000000u64
+ };
+ (49) => {
+ 0x2000000000000u64
+ };
+ (50) => {
+ 0x4000000000000u64
+ };
+ (51) => {
+ 0x8000000000000u64
+ };
+ (52) => {
+ 0x10000000000000u64
+ };
+ (53) => {
+ 0x20000000000000u64
+ };
+ (54) => {
+ 0x40000000000000u64
+ };
+ (55) => {
+ 0x80000000000000u64
+ };
+ (56) => {
+ 0x100000000000000u64
+ };
+ (57) => {
+ 0x200000000000000u64
+ };
+ (58) => {
+ 0x400000000000000u64
+ };
+ (59) => {
+ 0x800000000000000u64
+ };
+ (60) => {
+ 0x1000000000000000u64
+ };
+ (61) => {
+ 0x2000000000000000u64
+ };
+ (62) => {
+ 0x4000000000000000u64
+ };
+ (63) => {
+ 0x8000000000000000u64
+ };
+ ($_:expr) => {
+ 0u64
+ };
+}
+
+verus! {
+
+#[verifier(inline)]
+pub open spec fn bit_value(n: u64) -> u64
+ recommends
+ n < 64,
+{
+ seq_macro::seq! { N in 1..64 {
+ if n == 0 {
+ POW2_VALUE!(0)
+ }
+ #(else if n == N {
+ POW2_VALUE!(N)
+ })*
+ else {
+ 0
+ } | ```suggestion
#(if n == N {
POW2_VALUE!(N)
} else)*
{
0
}
```
Does this maybe work? |
svsm | github_2023 | others | 486 | coconut-svsm | Freax13 | @@ -0,0 +1,387 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Ziqiao Zhou <ziqiaozhou@microsoft.com>
+use vstd::arithmetic::power2::pow2;
+use vstd::bits::low_bits_mask;
+use vstd::prelude::*;
+
+#[macro_export]
+macro_rules! POW2_VALUE { | Why do we need this rather than just doing a bitshift `1 << N`? Is this a performance optimization or is this because the proofs in `bit_shl_values` depend on this macro? |
svsm | github_2023 | others | 486 | coconut-svsm | joergroedel | @@ -0,0 +1,4 @@
+builtin=`cargo metadata --format-version 1 | jq -r '.packages[] | select(.name == "builtin_macros") | .targets[].src_path'`
+verus=`dirname $builtin`/../../../
+verus=`realpath $verus`
+export VERUS_PATH=$verus | Scripts need license-headers as well. |
svsm | github_2023 | others | 486 | coconut-svsm | joergroedel | @@ -0,0 +1,13 @@
+#!/bin/bash
+VERISMO_REV=5186244
+cargo install --git https://github.com/microsoft/verismo/ --rev $VERISMO_REV cargo-v
+builtin=`cargo metadata --format-version 1 | jq -r '.packages[] | select(.name == "builtin_macros") | .targets[].src_path'`
+verus=`dirname $builtin`/../../../source/target-verus/release/verus
+if [ -f ${verus} ]; then
+ echo "verus (${verus}) is already built"
+else
+ cargo v prepare-verus
+fi
+cargo install --git https://github.com/microsoft/verismo/ --rev $VERISMO_REV verus-rustc
+curl --proto '=https' --tlsv1.2 -LsSf https://github.com/verus-lang/verusfmt/releases/download/v0.5.0/verusfmt-installer.sh | sh
+sudo apt-get install build-essential ninja-build libclang-dev | What are these packages needed for?
If they are truely needed this needs to be aware of the distribution. Please make sure the installation works on Debian/Ubuntu, Fedora, and openSUSE. If none of these distros are detected, just print a warning and instruct the user what to install manually. |
svsm | github_2023 | others | 486 | coconut-svsm | joergroedel | @@ -0,0 +1,13 @@
+#!/bin/bash
+VERISMO_REV=5186244
+cargo install --git https://github.com/microsoft/verismo/ --rev $VERISMO_REV cargo-v
+builtin=`cargo metadata --format-version 1 | jq -r '.packages[] | select(.name == "builtin_macros") | .targets[].src_path'`
+verus=`dirname $builtin`/../../../source/target-verus/release/verus
+if [ -f ${verus} ]; then
+ echo "verus (${verus}) is already built"
+else
+ cargo v prepare-verus
+fi
+cargo install --git https://github.com/microsoft/verismo/ --rev $VERISMO_REV verus-rustc
+curl --proto '=https' --tlsv1.2 -LsSf https://github.com/verus-lang/verusfmt/releases/download/v0.5.0/verusfmt-installer.sh | sh | Please ask the user before downloading and executing a script from the internet. Even better would be if you could commit this script directly to the SVSM repository. |
svsm | github_2023 | others | 519 | coconut-svsm | Freax13 | @@ -79,14 +79,16 @@ pub fn sse_init() {
/// no other part of the code is accessing this memory at the same time.
pub unsafe fn sse_save_context(addr: u64) {
let save_bits = XCR0_X87_ENABLE | XCR0_SSE_ENABLE | XCR0_YMM_ENABLE;
- asm!(
+ unsafe {
+ asm!( | rustfmt seems to choke on the multi-line asm! block. Could you please fix the indentation levels of these? |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn tdg_mem_page_accept(gpa_info: u64) -> u64 {
+ let mut ret: u64;
+ unsafe {
+ asm!("tdcall",
+ in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rcx") gpa_info,
+ lateout("rax") ret,
+ options(att_syntax));
+ }
+ ret
+}
+
+pub fn td_accept_physical_memory(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> {
+ let mut addr = region.start();
+ let end = region.end();
+
+ while addr < end {
+ if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // The caller is expected not to accept a page twice unlee
+ // doing so is known to be safe. If the TDX module
+ // indicates that the page was already accepted, it must
+ // mean that the page was not removed after a previous
+ // attempt to accept. In this case, the page must be
+ // zeroed now because the caller expects every accepted
+ // page to be zeroed.
+ unsafe {
+ let mapping = PerCPUPageMappingGuard::create(addr, addr + PAGE_SIZE_2M, 0)?;
+ mapping
+ .virt_addr()
+ .as_mut_ptr::<u8>()
+ .write_bytes(0, PAGE_SIZE_2M);
+ }
+ addr = addr + PAGE_SIZE_2M;
+ continue;
+ }
+ Ok(_) => {
+ addr = addr + PAGE_SIZE_2M;
+ continue;
+ }
+ Err(TdxError::PageSizeMismatch) => {
+ // Fall through to the 4 KB path below.
+ }
+ Err(e) => {
+ return Err(e.into());
+ }
+ }
+ }
+
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr)));
+ if let Err(e) = ret {
+ if e != TdxError::PageAlreadyAccepted {
+ return Err(e.into());
+ }
+
+ // Zero the 4 KB page.
+ unsafe {
+ let mapping = PerCPUPageMappingGuard::create(addr, addr + PAGE_SIZE, 0)?;
+ mapping
+ .virt_addr()
+ .as_mut_ptr::<u8>()
+ .write_bytes(0, PAGE_SIZE);
+ }
+ }
+
+ addr = addr + PAGE_SIZE;
+ }
+
+ Ok(())
+}
+
+fn td_accept_virtual_4k(vaddr: VirtAddr, paddr: PhysAddr) -> Result<(), SvsmError> {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(paddr)));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // Zero the 4 KB page.
+ unsafe {
+ vaddr.as_mut_ptr::<u8>().write_bytes(0, PAGE_SIZE);
+ }
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ Ok(_) => Ok(()),
+ }
+}
+
+fn td_accept_virtual_2m(vaddr: VirtAddr, paddr: PhysAddr) -> Result<(), SvsmError> {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(paddr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // Zero the 2M page.
+ unsafe {
+ vaddr.as_mut_ptr::<u8>().write_bytes(0, PAGE_SIZE_2M);
+ }
+ Ok(())
+ }
+ Err(TdxError::PageSizeMismatch) => {
+ // Process this 2 MB page as a series of 4 KB pages.
+ for offset in 0usize..512usize {
+ td_accept_virtual_4k(
+ vaddr + (offset << PAGE_SHIFT),
+ paddr + (offset << PAGE_SHIFT),
+ )?;
+ }
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ Ok(_) => Ok(()),
+ }
+}
+
+pub fn td_accept_virtual_memory(region: MemoryRegion<VirtAddr>) -> Result<(), SvsmError> {
+ let mut vaddr = region.start();
+ let vaddr_end = region.end();
+ while vaddr < vaddr_end {
+ let frame = virt_to_frame(vaddr);
+ let size = if vaddr.is_aligned(PAGE_SIZE_2M)
+ && vaddr + PAGE_SIZE_2M <= vaddr_end
+ && frame.size() >= PAGE_SIZE_2M
+ {
+ td_accept_virtual_2m(vaddr, frame.address())?;
+ PAGE_SIZE_2M
+ } else {
+ td_accept_virtual_4k(vaddr, frame.address())?;
+ PAGE_SIZE
+ };
+
+ vaddr = vaddr + size;
+ }
+ Ok(())
+}
+
+pub fn tdvmcall_halt() {
+ let pass_regs = (1 << 10) | (1 << 11) | (1 << 12);
+ unsafe {
+ asm!("tdcall",
+ in("eax") 0,
+ in("ecx") pass_regs,
+ in("r10d") 0,
+ in("r11d") TDVMCALL_HLT,
+ in("r12d") 0, | The host can modify these. We should use `inout("r10d") 0 => _,` (or `lateout("r10") _`) etc.
The same applies to `tdvmcall_io`. |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn tdg_mem_page_accept(gpa_info: u64) -> u64 {
+ let mut ret: u64;
+ unsafe {
+ asm!("tdcall",
+ in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rcx") gpa_info,
+ lateout("rax") ret,
+ options(att_syntax));
+ }
+ ret
+}
+
+pub fn td_accept_physical_memory(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> {
+ let mut addr = region.start();
+ let end = region.end();
+
+ while addr < end {
+ if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // The caller is expected not to accept a page twice unlee | ```suggestion
// The caller is expected not to accept a page twice unless
``` |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn tdg_mem_page_accept(gpa_info: u64) -> u64 {
+ let mut ret: u64;
+ unsafe {
+ asm!("tdcall",
+ in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rcx") gpa_info,
+ lateout("rax") ret,
+ options(att_syntax));
+ }
+ ret
+}
+
+pub fn td_accept_physical_memory(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> { | This method, `tdg_mem_page_accept`, `td_accept_virtual_4k`, `td_accept_virtual_2m`, and `td_accept_virtual_memory` should be marked as unsafe. |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn tdg_mem_page_accept(gpa_info: u64) -> u64 {
+ let mut ret: u64;
+ unsafe {
+ asm!("tdcall",
+ in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rcx") gpa_info,
+ lateout("rax") ret,
+ options(att_syntax));
+ }
+ ret
+}
+
+pub fn td_accept_physical_memory(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> {
+ let mut addr = region.start();
+ let end = region.end();
+
+ while addr < end {
+ if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // The caller is expected not to accept a page twice unlee
+ // doing so is known to be safe. If the TDX module
+ // indicates that the page was already accepted, it must
+ // mean that the page was not removed after a previous
+ // attempt to accept. In this case, the page must be
+ // zeroed now because the caller expects every accepted
+ // page to be zeroed.
+ unsafe {
+ let mapping = PerCPUPageMappingGuard::create(addr, addr + PAGE_SIZE_2M, 0)?;
+ mapping
+ .virt_addr()
+ .as_mut_ptr::<u8>()
+ .write_bytes(0, PAGE_SIZE_2M);
+ }
+ addr = addr + PAGE_SIZE_2M;
+ continue;
+ }
+ Ok(_) => {
+ addr = addr + PAGE_SIZE_2M;
+ continue;
+ }
+ Err(TdxError::PageSizeMismatch) => {
+ // Fall through to the 4 KB path below.
+ }
+ Err(e) => {
+ return Err(e.into());
+ }
+ }
+ }
+
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr)));
+ if let Err(e) = ret {
+ if e != TdxError::PageAlreadyAccepted {
+ return Err(e.into());
+ }
+
+ // Zero the 4 KB page.
+ unsafe {
+ let mapping = PerCPUPageMappingGuard::create(addr, addr + PAGE_SIZE, 0)?;
+ mapping
+ .virt_addr()
+ .as_mut_ptr::<u8>()
+ .write_bytes(0, PAGE_SIZE);
+ }
+ }
+
+ addr = addr + PAGE_SIZE;
+ }
+
+ Ok(())
+}
+
+fn td_accept_virtual_4k(vaddr: VirtAddr, paddr: PhysAddr) -> Result<(), SvsmError> {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(paddr)));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // Zero the 4 KB page.
+ unsafe {
+ vaddr.as_mut_ptr::<u8>().write_bytes(0, PAGE_SIZE);
+ }
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ Ok(_) => Ok(()),
+ }
+}
+
+fn td_accept_virtual_2m(vaddr: VirtAddr, paddr: PhysAddr) -> Result<(), SvsmError> {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(paddr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // Zero the 2M page.
+ unsafe {
+ vaddr.as_mut_ptr::<u8>().write_bytes(0, PAGE_SIZE_2M);
+ }
+ Ok(())
+ }
+ Err(TdxError::PageSizeMismatch) => {
+ // Process this 2 MB page as a series of 4 KB pages.
+ for offset in 0usize..512usize {
+ td_accept_virtual_4k(
+ vaddr + (offset << PAGE_SHIFT),
+ paddr + (offset << PAGE_SHIFT),
+ )?;
+ }
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ Ok(_) => Ok(()),
+ }
+}
+
+pub fn td_accept_virtual_memory(region: MemoryRegion<VirtAddr>) -> Result<(), SvsmError> {
+ let mut vaddr = region.start();
+ let vaddr_end = region.end();
+ while vaddr < vaddr_end {
+ let frame = virt_to_frame(vaddr);
+ let size = if vaddr.is_aligned(PAGE_SIZE_2M)
+ && vaddr + PAGE_SIZE_2M <= vaddr_end
+ && frame.size() >= PAGE_SIZE_2M
+ {
+ td_accept_virtual_2m(vaddr, frame.address())?;
+ PAGE_SIZE_2M
+ } else {
+ td_accept_virtual_4k(vaddr, frame.address())?;
+ PAGE_SIZE
+ };
+
+ vaddr = vaddr + size;
+ }
+ Ok(())
+}
+
+pub fn tdvmcall_halt() {
+ let pass_regs = (1 << 10) | (1 << 11) | (1 << 12);
+ unsafe {
+ asm!("tdcall",
+ in("eax") 0, | Can we introduce a constant named `TDCALL_TDG_VMCALL` here?` |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn tdg_mem_page_accept(gpa_info: u64) -> u64 { | Can we split `gpa_info` into `gpa` and `level`? I don't think we need to expose to the caller that these are passed as a single value in a single register. |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn tdg_mem_page_accept(gpa_info: u64) -> u64 {
+ let mut ret: u64;
+ unsafe {
+ asm!("tdcall",
+ in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rcx") gpa_info,
+ lateout("rax") ret,
+ options(att_syntax));
+ }
+ ret
+}
+
+pub fn td_accept_physical_memory(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> {
+ let mut addr = region.start();
+ let end = region.end();
+
+ while addr < end {
+ if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // The caller is expected not to accept a page twice unlee
+ // doing so is known to be safe. If the TDX module
+ // indicates that the page was already accepted, it must
+ // mean that the page was not removed after a previous
+ // attempt to accept. In this case, the page must be
+ // zeroed now because the caller expects every accepted
+ // page to be zeroed.
+ unsafe {
+ let mapping = PerCPUPageMappingGuard::create(addr, addr + PAGE_SIZE_2M, 0)?;
+ mapping
+ .virt_addr()
+ .as_mut_ptr::<u8>()
+ .write_bytes(0, PAGE_SIZE_2M);
+ }
+ addr = addr + PAGE_SIZE_2M;
+ continue;
+ }
+ Ok(_) => {
+ addr = addr + PAGE_SIZE_2M;
+ continue;
+ }
+ Err(TdxError::PageSizeMismatch) => {
+ // Fall through to the 4 KB path below.
+ }
+ Err(e) => {
+ return Err(e.into());
+ }
+ }
+ }
+
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr)));
+ if let Err(e) = ret {
+ if e != TdxError::PageAlreadyAccepted {
+ return Err(e.into());
+ }
+
+ // Zero the 4 KB page.
+ unsafe {
+ let mapping = PerCPUPageMappingGuard::create(addr, addr + PAGE_SIZE, 0)?;
+ mapping
+ .virt_addr()
+ .as_mut_ptr::<u8>()
+ .write_bytes(0, PAGE_SIZE);
+ }
+ }
+
+ addr = addr + PAGE_SIZE;
+ }
+
+ Ok(())
+}
+
+fn td_accept_virtual_4k(vaddr: VirtAddr, paddr: PhysAddr) -> Result<(), SvsmError> {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(paddr)));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // Zero the 4 KB page.
+ unsafe {
+ vaddr.as_mut_ptr::<u8>().write_bytes(0, PAGE_SIZE);
+ }
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ Ok(_) => Ok(()),
+ }
+}
+
+fn td_accept_virtual_2m(vaddr: VirtAddr, paddr: PhysAddr) -> Result<(), SvsmError> {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(paddr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // Zero the 2M page.
+ unsafe {
+ vaddr.as_mut_ptr::<u8>().write_bytes(0, PAGE_SIZE_2M);
+ }
+ Ok(())
+ }
+ Err(TdxError::PageSizeMismatch) => {
+ // Process this 2 MB page as a series of 4 KB pages.
+ for offset in 0usize..512usize {
+ td_accept_virtual_4k(
+ vaddr + (offset << PAGE_SHIFT),
+ paddr + (offset << PAGE_SHIFT),
+ )?;
+ }
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ Ok(_) => Ok(()),
+ }
+}
+
+pub fn td_accept_virtual_memory(region: MemoryRegion<VirtAddr>) -> Result<(), SvsmError> {
+ let mut vaddr = region.start();
+ let vaddr_end = region.end();
+ while vaddr < vaddr_end {
+ let frame = virt_to_frame(vaddr);
+ let size = if vaddr.is_aligned(PAGE_SIZE_2M)
+ && vaddr + PAGE_SIZE_2M <= vaddr_end
+ && frame.size() >= PAGE_SIZE_2M
+ {
+ td_accept_virtual_2m(vaddr, frame.address())?;
+ PAGE_SIZE_2M
+ } else {
+ td_accept_virtual_4k(vaddr, frame.address())?;
+ PAGE_SIZE
+ };
+
+ vaddr = vaddr + size;
+ }
+ Ok(())
+}
+
+pub fn tdvmcall_halt() {
+ let pass_regs = (1 << 10) | (1 << 11) | (1 << 12);
+ unsafe {
+ asm!("tdcall",
+ in("eax") 0,
+ in("ecx") pass_regs,
+ in("r10d") 0,
+ in("r11d") TDVMCALL_HLT,
+ in("r12d") 0,
+ options(att_syntax));
+ }
+}
+
+fn tdvmcall_io(port: u16, data: u32, size: usize, write: bool) -> u32 {
+ let pass_regs = (1 << 10) | (1 << 11) | (1 << 12) | (1 << 13) | (1 << 14) | (1 << 15);
+ let mut output: u32;
+ unsafe {
+ asm!("tdcall",
+ in("eax") 0,
+ in("ecx") pass_regs,
+ in("r10d") 0,
+ in("r11d") TDVMCALL_IO,
+ in("r12d") size,
+ in("r13d") write as u32,
+ in("r14d") port as u32,
+ in("r15d") data,
+ lateout("r11d") output,
+ options(att_syntax));
+ }
+
+ // Ignore errors here. The caller cannot handle them, and since the
+ // I/O operation was performed by an untrusted source, the error
+ // information is not meaningfully different than a maliciously unreliable
+ // operation.
+
+ output
+}
+
+pub fn tdvmcall_io_write<T>(port: u16, data: T)
+where
+ T: Sized, | ```suggestion
```
`T` must be `Sized` by default unless there's a `?Sized` bound. `From<T>` also implies that `T` is `Sized`.
This also applies to `tdvmcall_io_read`. |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -187,26 +166,26 @@ impl GHCIIOPort {
impl IOPort for GHCIIOPort {
fn outb(&self, port: u16, value: u8) {
- tdvmcall_io_write_8(port, value);
+ tdvmcall_io_write::<u8>(port, value); | ```suggestion
tdvmcall_io_write(port, value);
``` |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn tdg_mem_page_accept(gpa_info: u64) -> u64 {
+ let mut ret: u64;
+ unsafe {
+ asm!("tdcall",
+ in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rcx") gpa_info,
+ lateout("rax") ret,
+ options(att_syntax));
+ }
+ ret
+}
+
+pub fn td_accept_physical_memory(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> {
+ let mut addr = region.start();
+ let end = region.end();
+
+ while addr < end {
+ if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // The caller is expected not to accept a page twice unlee
+ // doing so is known to be safe. If the TDX module
+ // indicates that the page was already accepted, it must
+ // mean that the page was not removed after a previous
+ // attempt to accept. In this case, the page must be
+ // zeroed now because the caller expects every accepted
+ // page to be zeroed.
+ unsafe {
+ let mapping = PerCPUPageMappingGuard::create(addr, addr + PAGE_SIZE_2M, 0)?;
+ mapping
+ .virt_addr()
+ .as_mut_ptr::<u8>()
+ .write_bytes(0, PAGE_SIZE_2M);
+ }
+ addr = addr + PAGE_SIZE_2M;
+ continue;
+ }
+ Ok(_) => {
+ addr = addr + PAGE_SIZE_2M;
+ continue;
+ }
+ Err(TdxError::PageSizeMismatch) => {
+ // Fall through to the 4 KB path below.
+ }
+ Err(e) => {
+ return Err(e.into());
+ }
+ }
+ }
+
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(addr)));
+ if let Err(e) = ret {
+ if e != TdxError::PageAlreadyAccepted {
+ return Err(e.into());
+ }
+
+ // Zero the 4 KB page.
+ unsafe {
+ let mapping = PerCPUPageMappingGuard::create(addr, addr + PAGE_SIZE, 0)?;
+ mapping
+ .virt_addr()
+ .as_mut_ptr::<u8>()
+ .write_bytes(0, PAGE_SIZE);
+ }
+ }
+
+ addr = addr + PAGE_SIZE;
+ }
+
+ Ok(())
+}
+
+fn td_accept_virtual_4k(vaddr: VirtAddr, paddr: PhysAddr) -> Result<(), SvsmError> {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(paddr)));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // Zero the 4 KB page.
+ unsafe {
+ vaddr.as_mut_ptr::<u8>().write_bytes(0, PAGE_SIZE);
+ }
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ Ok(_) => Ok(()),
+ }
+}
+
+fn td_accept_virtual_2m(vaddr: VirtAddr, paddr: PhysAddr) -> Result<(), SvsmError> {
+ let ret = tdx_result(tdg_mem_page_accept(u64::from(paddr) | 1));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => {
+ // Zero the 2M page.
+ unsafe {
+ vaddr.as_mut_ptr::<u8>().write_bytes(0, PAGE_SIZE_2M);
+ }
+ Ok(())
+ }
+ Err(TdxError::PageSizeMismatch) => {
+ // Process this 2 MB page as a series of 4 KB pages.
+ for offset in 0usize..512usize {
+ td_accept_virtual_4k(
+ vaddr + (offset << PAGE_SHIFT),
+ paddr + (offset << PAGE_SHIFT),
+ )?;
+ }
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ Ok(_) => Ok(()),
+ }
+}
+
+pub fn td_accept_virtual_memory(region: MemoryRegion<VirtAddr>) -> Result<(), SvsmError> {
+ let mut vaddr = region.start();
+ let vaddr_end = region.end();
+ while vaddr < vaddr_end {
+ let frame = virt_to_frame(vaddr);
+ let size = if vaddr.is_aligned(PAGE_SIZE_2M)
+ && vaddr + PAGE_SIZE_2M <= vaddr_end
+ && frame.size() >= PAGE_SIZE_2M
+ {
+ td_accept_virtual_2m(vaddr, frame.address())?;
+ PAGE_SIZE_2M
+ } else {
+ td_accept_virtual_4k(vaddr, frame.address())?;
+ PAGE_SIZE
+ };
+
+ vaddr = vaddr + size;
+ }
+ Ok(())
+}
+
+pub fn tdvmcall_halt() {
+ let pass_regs = (1 << 10) | (1 << 11) | (1 << 12);
+ unsafe {
+ asm!("tdcall",
+ in("eax") 0,
+ in("ecx") pass_regs,
+ in("r10d") 0,
+ in("r11d") TDVMCALL_HLT,
+ in("r12d") 0,
+ options(att_syntax));
+ }
+}
+
+fn tdvmcall_io(port: u16, data: u32, size: usize, write: bool) -> u32 {
+ let pass_regs = (1 << 10) | (1 << 11) | (1 << 12) | (1 << 13) | (1 << 14) | (1 << 15);
+ let mut output: u32;
+ unsafe {
+ asm!("tdcall",
+ in("eax") 0,
+ in("ecx") pass_regs,
+ in("r10d") 0,
+ in("r11d") TDVMCALL_IO,
+ in("r12d") size,
+ in("r13d") write as u32,
+ in("r14d") port as u32,
+ in("r15d") data,
+ lateout("r11d") output,
+ options(att_syntax));
+ }
+
+ // Ignore errors here. The caller cannot handle them, and since the
+ // I/O operation was performed by an untrusted source, the error
+ // information is not meaningfully different than a maliciously unreliable
+ // operation. | Information about errors could still be useful for debugging. We could use the `debug_assert!` family of macros. These are only active in development mode and don't do anything in release mode. |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,234 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::pagetable::PageFrame;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDG_VP_TDVMCALL: u32 = 0;
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn gpa_info(frame: PageFrame) -> u64 { | Out of curiosity, you've mentioned "gpa info" a couple of times, but I can't find this anywhere in the ABI spec. Where did you find this?
ABI spec 1.0:

ABI spec 1.5:

|
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,234 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::pagetable::PageFrame;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDG_VP_TDVMCALL: u32 = 0;
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn gpa_info(frame: PageFrame) -> u64 {
+ // Callers are expected to guarantee alignment before calling this
+ // function. If the caller verifies the alignment, then it can be done
+ // once without having to do it in a loop.
+ debug_assert!(u64::from(frame.address()) & (frame.size() - 1) as u64 == 0); | ```suggestion
debug_assert_eq!(u64::from(frame.address()) & (frame.size() - 1) as u64, 0);
```
If the value is not `0`, it'd be useful to know what it was.
What's the reasoning behind using `debug_assert!` rather than just `assert!`. Is see that we're already checking the alignment in `td_accept_physical_memory` and `td_accept_virtual_memory`, but we don't in `td_accept_virtual_4k` and `td_accept_virtual_2m`. |
svsm | github_2023 | others | 515 | coconut-svsm | Freax13 | @@ -0,0 +1,234 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::pagetable::PageFrame;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use core::arch::asm;
+
+const TDG_VP_TDVMCALL: u32 = 0;
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+fn gpa_info(frame: PageFrame) -> u64 {
+ // Callers are expected to guarantee alignment before calling this
+ // function. If the caller verifies the alignment, then it can be done
+ // once without having to do it in a loop.
+ debug_assert!(u64::from(frame.address()) & (frame.size() - 1) as u64 == 0);
+ match frame {
+ PageFrame::Size4K(gpa) => u64::from(gpa),
+ PageFrame::Size2M(gpa) => u64::from(gpa) | 1,
+ PageFrame::Size1G(gpa) => u64::from(gpa) | 2,
+ }
+}
+
+fn tdg_mem_page_accept(frame: PageFrame) -> u64 {
+ let mut ret: u64;
+ unsafe {
+ asm!("tdcall",
+ in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rcx") gpa_info(frame),
+ lateout("rax") ret,
+ options(att_syntax));
+ }
+ ret
+}
+
+pub fn td_accept_physical_memory(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> {
+ let mut addr = region.start();
+ if !addr.is_aligned(PAGE_SIZE) {
+ return Err(SvsmError::InvalidAddress);
+ }
+
+ let end = region.end(); | Can we also check the alignment of `end`?
This also applies to `td_accept_virtual_memory`. |
svsm | github_2023 | others | 515 | coconut-svsm | ereshetova | @@ -0,0 +1,268 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) Microsoft Corporation
+//
+// Author: Jon Lange <jlange@microsoft.com>
+
+use super::error::{tdx_result, TdxError};
+use crate::address::{Address, PhysAddr, VirtAddr};
+use crate::error::SvsmError;
+use crate::mm::pagetable::PageFrame;
+use crate::mm::{virt_to_frame, PerCPUPageMappingGuard};
+use crate::types::{PAGE_SHIFT, PAGE_SIZE, PAGE_SIZE_2M};
+use crate::utils::MemoryRegion;
+
+use bitfield_struct::bitfield;
+use core::arch::asm;
+
+const TDG_VP_TDVMCALL: u32 = 0;
+const TDCALL_TDG_MEM_PAGE_ACCEPT: u32 = 6;
+
+const TDVMCALL_HLT: u32 = 12;
+const TDVMCALL_IO: u32 = 30;
+
+#[bitfield(u64)]
+struct EptMappingInfo {
+ #[bits(12)]
+ pub flags: u64,
+ #[bits(52)]
+ pub page_frame_number: u64,
+}
+
+impl From<PageFrame> for EptMappingInfo {
+ fn from(frame: PageFrame) -> Self {
+ let (gpa, flags) = match frame {
+ PageFrame::Size4K(gpa) => (u64::from(gpa), 0),
+ PageFrame::Size2M(gpa) => (u64::from(gpa), 1),
+ PageFrame::Size1G(gpa) => (u64::from(gpa), 2),
+ };
+ Self::new()
+ .with_flags(flags)
+ .with_page_frame_number(gpa >> PAGE_SHIFT)
+ }
+}
+
+/// # Safety
+/// This function has the potential to zero arbitrary memory, so the caller is
+/// required to ensure that the supplied physical address range is appropriate
+/// for acceptance.
+unsafe fn tdg_mem_page_accept(frame: PageFrame) -> u64 {
+ let mut ret: u64;
+ unsafe {
+ asm!("tdcall",
+ in("rax") TDCALL_TDG_MEM_PAGE_ACCEPT,
+ in("rcx") EptMappingInfo::from(frame).into_bits(),
+ lateout("rax") ret,
+ options(att_syntax));
+ }
+ ret
+}
+
+/// # Safety
+/// This function will zero arbitrary memory, so the caller is required to
+/// ensure that the supplied physical address range is appropriate for
+/// acceptance. The caller is additionally required to ensure that the address
+/// range is appropriate aligned to 4 KB boundaries.
+pub unsafe fn td_accept_physical_memory(region: MemoryRegion<PhysAddr>) -> Result<(), SvsmError> {
+ let mut addr = region.start();
+ if !addr.is_aligned(PAGE_SIZE) {
+ return Err(SvsmError::InvalidAddress);
+ }
+
+ let end = region.end();
+
+ while addr < end {
+ if addr.is_aligned(PAGE_SIZE_2M) && addr + PAGE_SIZE_2M <= end {
+ let ret = tdx_result(tdg_mem_page_accept(PageFrame::Size2M(addr)));
+ match ret {
+ Err(TdxError::PageAlreadyAccepted) => { | What is the usecase to allow such behavior, i.e. why we don't treat PageAlreadyAccepted as a bug condition? |
svsm | github_2023 | others | 514 | coconut-svsm | cclaudio | @@ -1,6 +1,6 @@
-[submodule "libmstpm/deps/openssl"]
- path = libmstpm/deps/openssl
+[submodule "libvtcgtpm/deps/openssl"] | There seems to have a typo here (`v` not needed) |
svsm | github_2023 | others | 415 | coconut-svsm | stefano-garzarella | @@ -62,12 +62,24 @@ QEMU_MINOR=${QEMU_MINOR%%.$QEMU_BUILD}
# The QEMU machine and memory command line changed after QEMU 8.2.0 from
# the coconut-svsm git repository.
-if (( (QEMU_MAJOR > 8) || ((QEMU_MAJOR == 8) && (QEMU_MINOR >= 2)) )); then
+if (( QEMU_MAJOR >= 9 )); then
+ MACHINE=q35,confidential-guest-support=sev0,memory-backend=mem0,igvm-cfg=igvm0
+ IGVM_OBJECT= | I guess it's a left over. Can we remove this line (67)? |
svsm | github_2023 | others | 415 | coconut-svsm | stefano-garzarella | @@ -103,7 +115,8 @@ $SUDO_CMD \
-cpu EPYC-v4 \
-machine $MACHINE \
-object $MEMORY \
- -object sev-snp-guest,id=sev0,cbitpos=$C_BIT_POS,reduced-phys-bits=1,init-flags=5,igvm-file=$IGVM \
+ -object sev-snp-guest,id=sev0,cbitpos=$C_BIT_POS,reduced-phys-bits=1$INIT_FLAGS$IGVM_FILE \ | Not a strong opinion, but what about defining an `SEV_SNP_OBJECT` and assign it for each QEMU version, so it's a bit clear also for the reader the differences between the versions?
I mean something like this:
```
if (( QEMU_MAJOR >= 9 )); then
...
SEV_SNP_OBJECT="-object sev-snp-guest,id=sev0,cbitpos=$C_BIT_POS,reduced-phys-bits=1"
elif (( (QEMU_MAJOR > 8) || ((QEMU_MAJOR == 8) && (QEMU_MINOR >= 2)) )); then
...
SEV_SNP_OBJECT="-object sev-snp-guest,id=sev0,cbitpos=$C_BIT_POS,reduced-phys-bits=1,init-flags=5,igvm-file=$IGVM"
...
``` |
svsm | github_2023 | others | 455 | coconut-svsm | joergroedel | @@ -431,5 +468,63 @@ global_asm!(
ret
"#,
+ // TODO: Replace this with a `const` operand once we upgrade the MSRV to 1.82.
+ CONTEXT_SWITCH_RESTORE_TOKEN = sym CONTEXT_SWITCH_RESTORE_TOKEN,
options(att_syntax)
);
+
+/// The location of a shadow stack restore token that's mapped into every set
+/// of page tables for use during context switches.
+///
+/// One interesting difference between the normal stack pointer and the shadow
+/// stack pointer is how they can be switched: For the normal stack pointer we
+/// can just move a new value into the RSP register. This doesn't work for the
+/// SSP register (the shadow stack pointer) because there's no way to directly
+/// move a value into it. Instead we have to use the `rstorssp` instruction.
+/// The key difference between this instruction and a regular `mov` is that
+/// `rstorssp` expects a "shadow stack restore token" to be at the top of the
+/// new shadow stack (this is just a special value that marks the top of a
+/// inactive shadow stack). After switching to a new shadow stack, the previous
+/// shadow stack is now inactive, and so the `saveprevssp` instruction can be
+/// used to transfer the shadow stack restore token from the new shadow stack
+/// to the previous one: `saveprevssp` atomically pops the stack token of the
+/// new shadow stack and pushes it on the previous shadow stack. This means
+/// that we have to execute both `rstorssp` and `saveprevssp` every time we
+/// want to switch the shadow stacks.
+///
+/// There's one major problem though: `saveprevssp` needs to access both the
+/// previous and the new shadow stack, but we only map each shadow stack into a
+/// single task's page tables. If each set of page tables only has access to
+/// either the previous or the new shadow stack, but not both, we can't execute
+/// `saveprevssp` and so we we can't move the shadow stack restore token to the
+/// previous shadow stack. If there's no shadow stack restore token on the
+/// previous shadow stack that means we can't restore this shadow stack at a
+/// later point. We obviously want to do switch back to the shadow stack later
+/// though so we need a work-around: We place a second shadow stack restore
+/// token at a fixed address in both page tables. This allows us to do
+/// the following:
+///
+/// 1. Switch to the shadow stack at the fixed address using `rstorssp`.
+/// 2. Transfer the shadow stack restore token from the shadow stack at the
+/// fixed address to the previous shadow stack by executing `saveprevssp`.
+/// 3. Switch the page tables. This doesn't lead to problems with the shadow
+/// stack because is mapped into both page tables.
+/// 4. Switch to the new shadow stack using `rstorssp`.
+/// 5. Transfer the shadow stack restore token from the new shadow stack back
+/// to the shadow stacks at the fixed address by executing `saveprevssp`. | There is another issue around the task-switch code which needs fixing, and that might help for shadow stacks as well.
The problem currently is that the task-switch assembly is not safe against exceptions (like #HV and #NMI) that can occur at any time. The unsafe part come from the fact that the code can not switch page-tables and stack pointers atomically. The solution for that problem is either using IST stacks for these exceptions, or using a per-cpu task-switch stack.
The preferred solution is a per-cpu task switch stack, which would then also need a shadow stack. I think this would solve this problem as well. |
svsm | github_2023 | others | 455 | coconut-svsm | msft-jlange | @@ -182,6 +201,15 @@ restart_hv:
movq 2*8(%rsp), %rax
movq %rax, -2*8(%rcx)
leaq -4*8(%rcx), %rsp
+ .if CFG_SHADOW_STACKS
+ // Pop the current stack frame, so that the previous stack frame sits
+ // on top of the shadow stack.
+ cmpb $0, {IS_CET_SUPPORTED}(%rip)
+ je 2f
+ movq $3, %rax | Prefer `movl $3, %eax`. This instruction is 4 bytes shorter since it moves a 32-bit constant instead of a 64-bit constant, and since `rax` is a 64-bit extension of `eax`, the subsequent instruction will be guaranteed to observe the correct value. |
svsm | github_2023 | others | 455 | coconut-svsm | msft-jlange | @@ -100,6 +111,14 @@ asm_entry_hv:
// RIP is in the return window, so update RIP to the cancel point.
leaq switch_vmpl_cancel(%rip), %rbx
movq %rbx, 0x20(%rsp)
+ .if CFG_SHADOW_STACKS
+ // Update RIP on the shadow stack to the cancel point.
+ cmpb $0, {IS_CET_SUPPORTED}(%rip)
+ je 2f
+ rdsspq %rax
+ wrss %rbx, 8(%rax) | Prefer `wrssq` because it makes the operand size more explicit. |
svsm | github_2023 | others | 455 | coconut-svsm | msft-jlange | @@ -29,6 +29,17 @@ HV_DOORBELL_ADDR:
pushq %r13
pushq %r14
pushq %r15
+ pushq $0
+ .if CFG_SHADOW_STACKS
+ cmpb $0, {IS_CET_SUPPORTED}(%rip)
+ je 2f
+ rdsspq %rax | RDSSPQ is in the NOP space so it will behave as a NOP if CET is not enabled. That means you can simplify this sequence to remove the jump by doing this instead:
```
xorl %eax, %eax // prefer the 32-bit form because it eliminates one instruction byte but has the same effect
rdsspq %rax
pushq %rax
``` |
svsm | github_2023 | others | 455 | coconut-svsm | msft-jlange | @@ -29,6 +29,12 @@ HV_DOORBELL_ADDR:
pushq %r13
pushq %r14
pushq %r15
+ pushq $0
+ # rdsspq is a nop when shadow stacks are not supported. Make sure that
+ # rax is 0 if that's the case.
+ xorl %eax, %eax
+ rdsspq %rax
+ push %rax | Prefer `pushq` so the size is explicit. |
svsm | github_2023 | others | 455 | coconut-svsm | msft-jlange | @@ -199,6 +231,12 @@ continue_hv:
pushq %r13
pushq %r14
pushq %r15
+ pushq $0
+ # rdsspq is a nop when shadow stacks are not supported. Make sure that
+ # rdx is 0 if that's the case.
+ xorl %edx, %edx
+ rdsspq %rdx
+ push %rdx | Prefer `pushq` so the size is explicit. |
svsm | github_2023 | others | 496 | coconut-svsm | joergroedel | @@ -27,6 +27,10 @@ impl NativePlatform {
pub fn new() -> Self {
Self {}
}
+
+ pub fn halt() {
+ halt()
+ } | SNP and native use the same method, it is better to put this as the default implementation directly into the trait and avoid the duplication. |
svsm | github_2023 | others | 496 | coconut-svsm | joergroedel | @@ -481,6 +490,10 @@ fn panic(info: &PanicInfo<'_>) -> ! {
loop {
debug_break();
- halt();
+
+ // Use a platform-specific halt. However, the SVSM_PLATFORM global
+ // may not yet be initialized, so go choose the halt implementation
+ // based on the platform-specific halt instead.
+ SvsmPlatformCell::halt(*SVSM_PLATFORM_TYPE); | A general comment on the direction of the platform abstraction (not a change request to **this** PR):
I don't like the way we are passing the platform abstraction around as a parameter. This is not the only instance, there are more examples of that in the code base. The platform type basically follows a singleton pattern and can be implemented as a global instance with public wrapper functions around the trait methods. That makes the code better and easier to read.
That can be solved in a separate PR, of course. |
svsm | github_2023 | others | 496 | coconut-svsm | Freax13 | @@ -157,4 +157,12 @@ impl SvsmPlatformCell {
SvsmPlatformCell::Tdp(platform) => platform,
}
}
+
+ pub fn halt(platform_type: SvsmPlatformType) { | What's the reasoning behind making this a function on `SvsmPlatformCell`? |
svsm | github_2023 | others | 460 | coconut-svsm | msft-jlange | @@ -197,36 +197,28 @@ impl<T: ?Sized> DerefMut for PageBox<T> {
impl<T: ?Sized> borrow::Borrow<T> for PageBox<T> {
#[inline]
fn borrow(&self) -> &T {
- // SAFETY: this is part of the invariants of this type, as it must
- // hold a pointer to valid memory for the given `T`.
- unsafe { self.ptr.as_ref() }
+ self | If this function doesn't require any manipulation of `self` before returning, then why keep the function body at all? I just tried an experiment where I completely removed the four functions you're touching here, and the compiler is perfectly happy, so it doesn't seem like we get any benefit from keeping functions that contain no logic. |
svsm | github_2023 | others | 410 | coconut-svsm | 00xc | @@ -0,0 +1,80 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Author: Vasant Karasulli <vkarasulli@suse.de>
+
+use crate::cpu::control_regs::{cr0_sse_enable, cr4_osfxsr_enable, cr4_xsave_enable};
+use crate::cpu::cpuid::CpuidResult;
+use core::arch::asm;
+const CPUID_EDX_SSE1: u32 = 25;
+const CPUID_ECX_XSAVE: u32 = 26;
+const CPUID_EAX_XSAVEOPT: u32 = 0;
+
+// Check if at least SSE1 is supported
+fn legacy_sse_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.edx & (1 << CPUID_EDX_SSE1)) != 0
+}
+
+fn legacy_sse_enable() {
+ if legacy_sse_supported() {
+ cr4_osfxsr_enable();
+ cr0_sse_enable();
+ } else {
+ log::info!("Legacy SSE instructions not supported by this hardware"); | Perhaps this should be an error?
```suggestion
log::error!("Legacy SSE instructions not supported by this hardware");
``` |
svsm | github_2023 | others | 410 | coconut-svsm | 00xc | @@ -0,0 +1,80 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Author: Vasant Karasulli <vkarasulli@suse.de>
+
+use crate::cpu::control_regs::{cr0_sse_enable, cr4_osfxsr_enable, cr4_xsave_enable};
+use crate::cpu::cpuid::CpuidResult;
+use core::arch::asm;
+const CPUID_EDX_SSE1: u32 = 25;
+const CPUID_ECX_XSAVE: u32 = 26;
+const CPUID_EAX_XSAVEOPT: u32 = 0;
+
+// Check if at least SSE1 is supported
+fn legacy_sse_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.edx & (1 << CPUID_EDX_SSE1)) != 0
+}
+
+fn legacy_sse_enable() {
+ if legacy_sse_supported() {
+ cr4_osfxsr_enable();
+ cr0_sse_enable();
+ } else {
+ log::info!("Legacy SSE instructions not supported by this hardware");
+ }
+}
+
+// Check if Extended SSE is supported
+fn extended_sse_supported() -> bool {
+ let res = CpuidResult::get(0x0000000D, 1);
+ (res.eax & 0x7) == 0x7
+}
+
+fn xsave_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.ecx & (1 << CPUID_ECX_XSAVE)) != 0
+}
+
+fn xcr0_set() {
+ let mut xsse_val: u32;
+ let ecx_val = 0;
+ let mut edx_val: u32;
+
+ unsafe {
+ asm!("xgetbv", out("eax") xsse_val, in("ecx") ecx_val, out("edx") edx_val,
+ options(att_syntax))
+ }
+
+ // set bits [0-2] in XCR0 to enable extended SSE
+ xsse_val |= 0x7;
+ unsafe {
+ asm!("xsetbv", in("eax") xsse_val, in("ecx") ecx_val, in("edx") edx_val,
+ options(att_syntax))
+ }
+} | Rust has builtins for extended control register access, so these should work:
```suggestion
use core::arch::x86_64::{_xgetbv, _xsetbv};
fn xcr0_set() {
unsafe {
// set bits [0-2] in XCR0 to enable extended SSE
let xr0 = _xgetbv(0) | 0x7;
_xsetbv(0, xr0);
}
}
``` |
svsm | github_2023 | others | 410 | coconut-svsm | 00xc | @@ -112,10 +113,15 @@ impl TaskSchedState {
}
}
+// Layout of this struct is important. Offset of the members
+// have to be kept the same. Add members to the end if necessary.
#[repr(C)]
pub struct Task {
pub rsp: u64,
+ /// XSave area address for the task
+ pub xsa_addr: u64, | ```suggestion
pub xsa_addr: VirtAddr,
``` |
svsm | github_2023 | others | 410 | coconut-svsm | 00xc | @@ -0,0 +1,43 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) 2022-2024 SUSE LLC
+//
+// Author: Vasant Karasulli <vkarasulli@suse.de>
+
+use super::VirtualMapping;
+use crate::address::PhysAddr;
+use crate::error::SvsmError;
+use crate::mm::alloc::allocate_file_page_ref;
+use crate::mm::pagetable::PTEntryFlags;
+use crate::mm::{PageRef, PAGE_SIZE};
+
+#[derive(Debug)]
+pub struct XSaveArea {
+ pg: PageRef,
+}
+
+impl XSaveArea {
+ pub fn new() -> Result<Self, SvsmError> {
+ let pg = allocate_file_page_ref()?; | Any reason we're not using a regular page, i.e. `allocate_page()`? |
svsm | github_2023 | others | 410 | coconut-svsm | 00xc | @@ -0,0 +1,80 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Author: Vasant Karasulli <vkarasulli@suse.de>
+
+use crate::cpu::control_regs::{cr0_sse_enable, cr4_osfxsr_enable, cr4_xsave_enable};
+use crate::cpu::cpuid::CpuidResult;
+use core::arch::asm;
+const CPUID_EDX_SSE1: u32 = 25;
+const CPUID_ECX_XSAVE: u32 = 26;
+const CPUID_EAX_XSAVEOPT: u32 = 0;
+
+// Check if at least SSE1 is supported
+fn legacy_sse_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.edx & (1 << CPUID_EDX_SSE1)) != 0
+}
+
+fn legacy_sse_enable() {
+ if legacy_sse_supported() {
+ cr4_osfxsr_enable();
+ cr0_sse_enable();
+ } else {
+ log::info!("Legacy SSE instructions not supported by this hardware");
+ }
+}
+
+// Check if Extended SSE is supported
+fn extended_sse_supported() -> bool {
+ let res = CpuidResult::get(0x0000000D, 1);
+ (res.eax & 0x7) == 0x7
+}
+
+fn xsave_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.ecx & (1 << CPUID_ECX_XSAVE)) != 0
+}
+
+fn xcr0_set() {
+ let mut xsse_val: u32;
+ let ecx_val = 0;
+ let mut edx_val: u32;
+
+ unsafe {
+ asm!("xgetbv", out("eax") xsse_val, in("ecx") ecx_val, out("edx") edx_val,
+ options(att_syntax))
+ }
+
+ // set bits [0-2] in XCR0 to enable extended SSE
+ xsse_val |= 0x7;
+ unsafe {
+ asm!("xsetbv", in("eax") xsse_val, in("ecx") ecx_val, in("edx") edx_val,
+ options(att_syntax))
+ }
+}
+
+fn check_xsave_features() {
+ let res = CpuidResult::get(0x0000000D, 0);
+ log::info!("xsave area size: {}", res.ecx);
+ if (res.eax & (1 << CPUID_EAX_XSAVEOPT)) == 0 {
+ log::info!("XSAVEOPT is not supported by this hardware")
+ }
+}
+
+fn extended_sse_enable() {
+ if extended_sse_supported() && xsave_supported() {
+ cr4_xsave_enable();
+ xcr0_set();
+ check_xsave_features();
+ } else {
+ log::info!("XSAVE is not supported by this hardware"); | Same here, perhaps this should be an error. Also, can we continue operation without XSAVE? |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -385,18 +385,33 @@ global_asm!(
// Save the current stack pointer
testq %rsi, %rsi
jz 1f
+
+ //set bits in edx:eax that correspond to SSE/FPU context
+ movq $0x7, %rax
+ xorq %rdx, %rdx
+ //rsi + 8 contains xsave area address
+ movq 8(%rsi), %rbx
+ xsaveopt (%rbx)
+ | Can this happen outside of the main task-switching assembly? The task switching code does not need FPU, so the context can be saved in a preparation state (using a helper method/function) and the new task can restore the content after the actual switch happened. |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -0,0 +1,80 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Author: Vasant Karasulli <vkarasulli@suse.de>
+
+use crate::cpu::control_regs::{cr0_sse_enable, cr4_osfxsr_enable, cr4_xsave_enable};
+use crate::cpu::cpuid::CpuidResult;
+use core::arch::asm;
+const CPUID_EDX_SSE1: u32 = 25;
+const CPUID_ECX_XSAVE: u32 = 26;
+const CPUID_EAX_XSAVEOPT: u32 = 0;
+
+// Check if at least SSE1 is supported
+fn legacy_sse_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.edx & (1 << CPUID_EDX_SSE1)) != 0
+}
+
+fn legacy_sse_enable() {
+ if legacy_sse_supported() {
+ cr4_osfxsr_enable();
+ cr0_sse_enable();
+ } else {
+ log::info!("Legacy SSE instructions not supported by this hardware");
+ }
+}
+
+// Check if Extended SSE is supported
+fn extended_sse_supported() -> bool {
+ let res = CpuidResult::get(0x0000000D, 1);
+ (res.eax & 0x7) == 0x7
+}
+
+fn xsave_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.ecx & (1 << CPUID_ECX_XSAVE)) != 0
+}
+
+fn xcr0_set() {
+ let mut xsse_val: u32;
+ let ecx_val = 0;
+ let mut edx_val: u32;
+
+ unsafe {
+ asm!("xgetbv", out("eax") xsse_val, in("ecx") ecx_val, out("edx") edx_val,
+ options(att_syntax))
+ } | We should cache the current value of XCR register in per-cpu and not read it every time we make a change. |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -0,0 +1,80 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Author: Vasant Karasulli <vkarasulli@suse.de>
+
+use crate::cpu::control_regs::{cr0_sse_enable, cr4_osfxsr_enable, cr4_xsave_enable};
+use crate::cpu::cpuid::CpuidResult;
+use core::arch::asm;
+const CPUID_EDX_SSE1: u32 = 25;
+const CPUID_ECX_XSAVE: u32 = 26;
+const CPUID_EAX_XSAVEOPT: u32 = 0;
+
+// Check if at least SSE1 is supported
+fn legacy_sse_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.edx & (1 << CPUID_EDX_SSE1)) != 0
+}
+
+fn legacy_sse_enable() {
+ if legacy_sse_supported() {
+ cr4_osfxsr_enable();
+ cr0_sse_enable();
+ } else {
+ log::info!("Legacy SSE instructions not supported by this hardware");
+ }
+}
+
+// Check if Extended SSE is supported
+fn extended_sse_supported() -> bool {
+ let res = CpuidResult::get(0x0000000D, 1);
+ (res.eax & 0x7) == 0x7
+}
+
+fn xsave_supported() -> bool {
+ let res = CpuidResult::get(0x00000001, 0);
+ (res.ecx & (1 << CPUID_ECX_XSAVE)) != 0
+}
+
+fn xcr0_set() {
+ let mut xsse_val: u32;
+ let ecx_val = 0;
+ let mut edx_val: u32;
+
+ unsafe {
+ asm!("xgetbv", out("eax") xsse_val, in("ecx") ecx_val, out("edx") edx_val,
+ options(att_syntax))
+ }
+
+ // set bits [0-2] in XCR0 to enable extended SSE
+ xsse_val |= 0x7; | Can you please split the 7 up into individual bits we can OR together? |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -0,0 +1,115 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Author: Vasant Karasulli <vkarasulli@suse.de>
+
+use crate::cpu::control_regs::{cr0_sse_enable, cr4_osfxsr_enable, cr4_xsave_enable};
+use crate::cpu::cpuid::cpuid_table_raw;
+use core::arch::asm;
+use core::arch::x86_64::{_xgetbv, _xsetbv};
+
+const CPUID_EDX_SSE1: u32 = 25;
+const CPUID_ECX_XSAVE: u32 = 26;
+const CPUID_EAX_XSAVEOPT: u32 = 0;
+const XCR0_X87_ENABLE: u64 = 0x1;
+const XCR0_SSE_ENABLE: u64 = 0x2;
+const XCR0_YMM_ENABLE: u64 = 0x4;
+
+// Check if at least SSE1 is supported
+fn legacy_sse_supported() -> bool {
+ let Some(res) = cpuid_table_raw(1, 0, 0, 0) else { | This code needs to use the `cpuid` instruction directly to be compatible with the native and TD platform targets. I just realized there is no wrapper yet for `cpuid`, so please add one and use it for any FPU-related CPUID queries. This also affects other places in this PR. |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -0,0 +1,115 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Author: Vasant Karasulli <vkarasulli@suse.de>
+
+use crate::cpu::control_regs::{cr0_sse_enable, cr4_osfxsr_enable, cr4_xsave_enable};
+use crate::cpu::cpuid::cpuid_table_raw;
+use core::arch::asm;
+use core::arch::x86_64::{_xgetbv, _xsetbv};
+
+const CPUID_EDX_SSE1: u32 = 25;
+const CPUID_ECX_XSAVE: u32 = 26;
+const CPUID_EAX_XSAVEOPT: u32 = 0;
+const XCR0_X87_ENABLE: u64 = 0x1;
+const XCR0_SSE_ENABLE: u64 = 0x2;
+const XCR0_YMM_ENABLE: u64 = 0x4;
+
+// Check if at least SSE1 is supported
+fn legacy_sse_supported() -> bool {
+ let Some(res) = cpuid_table_raw(1, 0, 0, 0) else {
+ panic!("Legacy SSE support couldn't be determined");
+ };
+ (res.edx & (1 << CPUID_EDX_SSE1)) != 0
+}
+
+fn legacy_sse_enable() {
+ if legacy_sse_supported() {
+ cr4_osfxsr_enable();
+ cr0_sse_enable();
+ } else {
+ panic!("Legacy SSE instructions not supported by this hardware");
+ }
+}
+
+// Check if Extended SSE is supported
+fn extended_sse_supported() -> bool {
+ let Some(res) = cpuid_table_raw(0xd, 1, 1, 0) else {
+ panic!("extend SSE support couldn't be determined");
+ };
+ (res.eax & 0x7) == 0x7
+}
+
+fn xsave_supported() -> bool {
+ let Some(res) = cpuid_table_raw(1, 0, 0, 0) else {
+ panic!("XSAVE support couldn't be determined");
+ };
+ (res.ecx & (1 << CPUID_ECX_XSAVE)) != 0
+}
+
+fn xcr0_set() {
+ unsafe {
+ // set bits [0-2] in XCR0 to enable extended SSE
+ let xr0 = _xgetbv(0) | XCR0_X87_ENABLE | XCR0_SSE_ENABLE | XCR0_YMM_ENABLE;
+ _xsetbv(0, xr0);
+ }
+}
+
+pub fn get_xsave_area_size() -> u32 {
+ let Some(res) = cpuid_table_raw(0xd, 0, 1, 0) else {
+ panic!("XSAVE area size can't be calculated");
+ };
+
+ if (res.eax & (1 << CPUID_EAX_XSAVEOPT)) == 0 {
+ panic!("XSAVEOPT is not supported by this hardware");
+ }
+ res.ecx
+}
+
+fn extended_sse_enable() {
+ if extended_sse_supported() && xsave_supported() {
+ cr4_xsave_enable();
+ xcr0_set();
+ } else {
+ panic!("XSAVE is not supported by this hardware");
+ } | ```suggestion
if !extended_sse_supported() {
panic!("Extended SSE is not supported by this hardware");
}
if !xsave_supported() {
panic!("XSAVE is not supported by this hardware");
}
cr4_xsave_enable();
xcr0_set();
```
Make the panic messages a bit more concise. |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -298,6 +300,10 @@ unsafe fn task_pointer(taskptr: TaskPointer) -> *const Task {
unsafe fn switch_to(prev: *const Task, next: *const Task) {
let cr3: u64 = unsafe { (*next).page_table.lock().cr3_value().bits() as u64 };
+ if !prev.is_null() {
+ sse_save_context(u64::from((*prev).xsa.vaddr()));
+ }
+ | This can happen in `schedule()`. |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -361,8 +367,13 @@ pub fn schedule() {
drop(guard);
- // We're now in the context of the new task. If the previous task had terminated
- // then we can release it's reference here.
+ // We're now in the context of the new task.
+ let cur = current_task();
+ unsafe {
+ sse_restore_context(u64::from(cur.xsa.vaddr()));
+ } | This needs to be moved into the `if let Some((current, next)) = work {` branch. Otherwise the code will load an old FPU context when no context switch is happening. |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -501,8 +525,11 @@ fn setup_new_task() {
}
}
-extern "C" fn run_kernel_task(entry: extern "C" fn()) {
+extern "C" fn run_kernel_task(entry: extern "C" fn(), xsa_addr: u64) {
setup_new_task();
+ unsafe {
+ sse_restore_context(xsa_addr);
+ } | This needs to be in `setup_new_task()`. |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -176,7 +184,9 @@ impl Task {
let vm_kernel_range = VMR::new(SVSM_PERTASK_BASE, SVSM_PERTASK_END, PTEntryFlags::empty());
vm_kernel_range.initialize()?;
- let (stack, raw_bounds, rsp_offset) = Self::allocate_ktask_stack(cpu, entry)?;
+ let xsa = Self::allocate_xsave_area();
+ let xsa_addr = u64::from(xsa.vaddr()) as usize;
+ let (stack, raw_bounds, rsp_offset) = Self::allocate_ktask_stack(cpu, entry, xsa_addr)?; | The same needs to happen for user tasks. |
svsm | github_2023 | others | 410 | coconut-svsm | joergroedel | @@ -353,16 +355,20 @@ pub fn schedule() {
unsafe {
let a = task_pointer(current);
let b = task_pointer(next);
+ sse_save_context(u64::from((*a).xsa.vaddr()));
// Switch tasks
switch_to(a, b);
+
+ // We're now in the context of the new task.
+ sse_restore_context(u64::from((*a).xsa.vaddr())); | The context needs to be loaded from `*b` instead of `*a`, no? |
svsm | github_2023 | others | 485 | coconut-svsm | Freax13 | @@ -404,3 +404,21 @@ global_asm!(
"#,
options(att_syntax)
);
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub enum IdtEventType {
+ Unknown = 0,
+ External,
+ Software, | Are the `External` and `Software` event types instantiated anywhere? I can't find any uses. |
svsm | github_2023 | others | 485 | coconut-svsm | Freax13 | @@ -404,3 +404,21 @@ global_asm!(
"#,
options(att_syntax)
);
+
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub enum IdtEventType {
+ Unknown = 0,
+ External,
+ Software,
+}
+
+impl IdtEventType {
+ pub fn is_external_interrupt(&self, vector: usize) -> bool {
+ match self {
+ Self::External => true,
+ Self::Software => false,
+ _ => SVSM_PLATFORM.as_dyn_ref().is_external_interrupt(vector), | ```suggestion
Self::Unknown => SVSM_PLATFORM.as_dyn_ref().is_external_interrupt(vector),
``` |
svsm | github_2023 | others | 485 | coconut-svsm | Freax13 | @@ -224,7 +224,16 @@ extern "C" fn ex_handler_vmm_communication(ctxt: &mut X86ExceptionContext, vecto
// System Call SoftIRQ handler
#[no_mangle]
-extern "C" fn ex_handler_system_call(ctxt: &mut X86ExceptionContext) {
+extern "C" fn ex_handler_system_call(
+ ctxt: &mut X86ExceptionContext,
+ vector: usize,
+ event_type: IdtEventType,
+) {
+ // Ensure that this vector was not invoked as a hardware interrupt vector.
+ if event_type.is_external_interrupt(vector) {
+ panic!("Syscall handler invoked as external interrupt!");
+ } | ```suggestion
assert!(event_type.is_external_interrupt(vector), "Syscall handler invoked as external interrupt!");
``` |
svsm | github_2023 | others | 485 | coconut-svsm | Freax13 | @@ -152,6 +152,19 @@ impl IrqState {
pub fn count(&self) -> isize {
self.count.load(Ordering::Relaxed)
}
+
+ /// Changes whether interrupts will be enabled when the nesting count
+ /// drops to zero.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the current nesting count is non-zero,
+ /// and must ensure that the specified value is appropriate for the
+ /// current environment.
+ pub unsafe fn set_restore_state(&self, enabled: bool) {
+ assert!(self.count.load(Ordering::Relaxed) != 0); | ```suggestion
assert_ne!(self.count.load(Ordering::Relaxed), 0);
``` |
svsm | github_2023 | others | 485 | coconut-svsm | Freax13 | @@ -114,12 +114,23 @@ impl SvsmPlatform for TdpPlatform {
false
}
+ fn use_interrupts(&self) -> bool {
+ true
+ }
+
fn post_irq(&self, _icr: u64) -> Result<(), SvsmError> {
Err(SvsmError::Tdx)
}
fn eoi(&self) {}
+ fn is_external_interrupt(&self, _vector: usize) -> bool {
+ // Examine the APIC ISR to determine whether this interrupt vector is
+ // active. If so, it is assumed to be an external interrupt.
+ // TODO - add code to read the APIC ISR.
+ todo!(); | Are you planning on implementing this in this PR or will this be done in a follow-up PR? |
svsm | github_2023 | others | 485 | coconut-svsm | Freax13 | @@ -377,8 +377,14 @@ impl GHCB {
let ghcb_address = VirtAddr::from(self as *const GHCB);
let ghcb_pa = u64::from(virt_to_phys(ghcb_address));
+ // Disable interrupts between writing the MSR and making the GHCB call
+ // to prevent reentrant use of the GHCB MSR.
+ let guard = IrqGuard::new(); | Should we move this guard to the top of the function and not drop it until the end? Guarding the MSR is one thing, we'll probably also want to protect the GHCB contents as well. |
svsm | github_2023 | others | 485 | coconut-svsm | p4zuu | @@ -224,7 +224,16 @@ extern "C" fn ex_handler_vmm_communication(ctxt: &mut X86ExceptionContext, vecto
// System Call SoftIRQ handler
#[no_mangle]
-extern "C" fn ex_handler_system_call(ctxt: &mut X86ExceptionContext) {
+extern "C" fn ex_handler_system_call(
+ ctxt: &mut X86ExceptionContext,
+ vector: usize,
+ event_type: IdtEventType,
+) {
+ // Ensure that this vector was not invoked as a hardware interrupt vector.
+ if event_type.is_external_interrupt(vector) {
+ panic!("Syscall handler invoked as external interrupt!"); | Why exactly handling an injected interrupt as a system call is a security issue? Making the kernel possibly `panic!()` in the system call handler still looks like a security issue to me, why can't we gracefully return? |
svsm | github_2023 | others | 494 | coconut-svsm | Freax13 | @@ -108,8 +108,15 @@ impl SvsmPlatform for SnpPlatform {
cpu.setup_ghcb()
}
- fn setup_percpu_current(&self, cpu: &PerCpu) -> Result<(), SvsmError> {
+ fn setup_percpu_current(&self, cpu: &PerCpu, is_bsp: bool) -> Result<(), SvsmError> { | Instead of adding a parameter here, we could also add a method `is_bsp(&self) -> bool` to `PerCpu`. |
svsm | github_2023 | others | 419 | coconut-svsm | joergroedel | @@ -83,7 +83,11 @@ pub trait SvsmPlatform {
) -> Result<(), SvsmError>;
/// Marks a range of pages as valid for use as private pages.
- fn validate_page_range(&self, region: MemoryRegion<VirtAddr>) -> Result<(), SvsmError>;
+ fn validate_page_range(
+ &self,
+ region: MemoryRegion<VirtAddr>,
+ paddr: PhysAddr,
+ ) -> Result<(), SvsmError>; | This interface change puzzles me a bit. I imposes certain constraints on the method caller (like that the virtual region maps physically contiguous memory).
At least the interface needs to be documented after that change. In general I think it is possible to get the physical address from within the method. Stage2 is identity-mapped and for the COCONUT kernel there is `virt_to_phys()`. |
svsm | github_2023 | others | 419 | coconut-svsm | joergroedel | @@ -440,6 +440,8 @@ pub extern "C" fn stage2_main(launch_info: &Stage2LaunchInfo) {
// Shut down the GHCB
shutdown_percpu();
+ log::info!("Starting SVSM kernel..."); | This needs to happen before `shutdown_percpu()`, otherwise it crashes on SNP. The `shutdown_percpu()` function also shuts down the GHCB on SNP which is required for serial port access, and as a consequence also to print any log messages. |
svsm | github_2023 | others | 419 | coconut-svsm | msft-jlange | @@ -52,6 +55,33 @@ impl IOPort for SVSMIOPort {
}
}
+#[derive(Clone, Copy, Debug, Default)]
+pub struct SvsmTdIOPort {} | Can we not just change `SVSMIOPort` to use IN and OUT instructions natively, and then have the #VC handler issue GHCB calls and the #VE handler issue GHCI calls? This seems like it would be much cleaner because it restricts platform-specific functionality to code paths that are already platform-specific (exception handlers) instead of common code (the console code). |
svsm | github_2023 | others | 419 | coconut-svsm | msft-jlange | @@ -215,7 +215,7 @@ impl WriteLockGuard<'static, IDT> {
/// Load an IDT. Its lifetime must be static so that its entries are
/// always available to the CPU.
pub fn load(&self) {
- let desc: IdtDesc = IdtDesc {
+ let desc = IdtDesc { | What's the reason for this change? Is this related to TDP? |
svsm | github_2023 | others | 419 | coconut-svsm | msft-jlange | @@ -173,7 +173,7 @@ pub mod svsm_gdbstub {
static GDB_INITIALISED: AtomicBool = AtomicBool::new(false);
static GDB_STATE: SpinLock<Option<SvsmGdbStub<'_>>> = SpinLock::new(None);
- static GDB_IO: SVSMIOPort = SVSMIOPort::new();
+ static GDB_IO: SvsmSevIOPort = SvsmSevIOPort::new(); | Isn't this going to be problematic when we finally make GDB work on TDP? Wouldn't it be better to define a platform abstraction now since you are already forced to touch this code? |
svsm | github_2023 | others | 419 | coconut-svsm | msft-jlange | @@ -611,9 +647,9 @@ impl PageTable {
/// - `vaddr': The virtual address to transalte.
///
/// # Returns
- /// Some(PhysAddr) if the virtual address is valid.
+ /// Some(PageFrame) if the virtual address is valid.
/// None if the virtual address is not valid.
- pub fn virt_to_phys(vaddr: VirtAddr) -> Option<PhysAddr> {
+ pub fn virt_to_phys(vaddr: VirtAddr) -> Option<PageFrame> { | For consistency, this function should be renamed `virt_to_frame` because it returns a `PageFrame` and not a `PhysAddr`. |
svsm | github_2023 | others | 419 | coconut-svsm | msft-jlange | @@ -450,6 +450,42 @@ pub enum Mapping<'a> {
Level0(&'a mut PTEntry),
}
+/// A physical address within a page frame
+#[derive(Debug)]
+pub enum PageFrame {
+ Size4K(PhysAddr),
+ Size2M(PhysAddr),
+ Size1G(PhysAddr),
+}
+
+impl PageFrame {
+ pub fn address(&self) -> PhysAddr {
+ match *self {
+ Self::Size4K(pa) => pa,
+ Self::Size2M(pa) => pa,
+ Self::Size1G(pa) => pa,
+ }
+ }
+
+ fn size(&self) -> usize {
+ let sz = match *self {
+ Self::Size4K(_) => PageSize::Regular,
+ Self::Size2M(_) => PageSize::Huge,
+ Self::Size1G(_) => PageSize::Huge1G,
+ };
+ usize::from(sz) | ```suggestion
match self {
Self::Size4K(_) => PageSize::Regular,
Self::Size2M(_) => PageSize::Huge,
Self::Size1G(_) => PageSize::Huge1G,
}.into()
```
Note that you don't need an explicit dereference of `self` (the compiler will do that for you) and you can use `into` instead of `from` and skip the temporary variable. |
svsm | github_2023 | others | 419 | coconut-svsm | msft-jlange | @@ -611,9 +647,9 @@ impl PageTable {
/// - `vaddr': The virtual address to transalte. | Since you're fixing some of my other typos, it would be great if you could change `transalte` to `translate` while you're at it. |
svsm | github_2023 | others | 419 | coconut-svsm | msft-jlange | @@ -9,20 +9,24 @@ use crate::sev::vmsa::VMPL_MAX;
pub const PAGE_SHIFT: usize = 12;
pub const PAGE_SHIFT_2M: usize = 21;
+pub const PAGE_SHIFT_1G: usize = 30;
pub const PAGE_SIZE: usize = 1 << PAGE_SHIFT;
-pub const PAGE_SIZE_2M: usize = PAGE_SIZE * 512;
+pub const PAGE_SIZE_2M: usize = 1 << PAGE_SHIFT_2M;
+pub const PAGE_SIZE_1G: usize = 1 << PAGE_SHIFT_1G;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PageSize {
Regular,
Huge,
+ Huge1G, | Is this really necessary? Given that SNP does not support 1 GB pages, I don't believe COCONUT-SVSM will ever attempt to make any use of them, and thus this size will never be meaningful. |
svsm | github_2023 | others | 492 | coconut-svsm | Freax13 | @@ -173,6 +172,8 @@ pub fn request_loop() {
flush_tlb_global_sync();
switch_to_vmpl(GUEST_VMPL as u32);
+
+ drop(guard); | This line isn't needed, but if your goal is to be explicit about this, I'm also fine with leaving this as is. |
svsm | github_2023 | others | 480 | coconut-svsm | Freax13 | @@ -6,43 +6,64 @@
use bitfield_struct::bitfield;
+#[derive(Clone, Copy, Debug, PartialEq)]
+#[allow(dead_code, non_camel_case_types)] | ```suggestion
#[allow(dead_code)]
``` |
svsm | github_2023 | others | 480 | coconut-svsm | Freax13 | @@ -6,43 +6,64 @@
use bitfield_struct::bitfield;
+#[derive(Clone, Copy, Debug, PartialEq)]
+#[allow(dead_code, non_camel_case_types)]
+pub struct GuestVMExit(u64);
+
+macro_rules! guest_vmexits {
+ (
+ $(
+ ($exit:ident, $value:expr);
+ )+
+ ) => {
+ impl GuestVMExit {
+ $(
+ pub const $exit: Self = Self($value);
+ )+
+ }
+ };
+} | I'm not sure if we need to use a macro for this. I get that the macro makes the code a bit less verbose, but it also makes it less obvious that there is nothing else going on.
I could understand the need for the macro if we also used it to generate a prettier `Debug` implementation. |
svsm | github_2023 | others | 480 | coconut-svsm | Freax13 | @@ -6,43 +6,50 @@
use bitfield_struct::bitfield;
+#[derive(Clone, Copy, Debug, PartialEq)]
+#[allow(dead_code)]
+pub struct GuestVMExit(u64); | ```suggestion
#[repr(transparent)]
pub struct GuestVMExit(u64);
``` |
svsm | github_2023 | others | 473 | coconut-svsm | Freax13 | @@ -0,0 +1,20 @@
+// SPDX-License-Identifier: MIT
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Authors: Thomas Leroy <tleroy@suse.de>
+
+.code64
+
+.section .text
+.macro asm_clac
+ .if CFG_SMAP
+ .byte 0x0f, 0x01, 0xca | Here and elsewhere:
```suggestion
clac
```
Is there a reason we need to use directives? |
svsm | github_2023 | others | 473 | coconut-svsm | Freax13 | @@ -0,0 +1,27 @@
+// SPDX-License-Identifier: MIT
+//
+// Copyright (c) 2024 SUSE LLC
+//
+// Authors: Thomas Leroy <tleroy@suse.de>
+
+use core::arch::asm;
+
+/// Clears RFLAGS.AC to enable SMAP.
+/// This is currently only used when SMAP is supported and enabled.
+/// SMAP protection is effective only if CR4.SMAP is set and if RFLAGS.AC = 0.
+#[inline(always)]
+pub fn clac() {
+ if !cfg!(feature = "nosmap") {
+ unsafe { asm!("clac", options(att_syntax, nomem, nostack)) } | ```suggestion
unsafe { asm!("clac", options(att_syntax, nomem, nostack, preserves_flags)) }
```
[Inline assembly](https://doc.rust-lang.org/reference/inline-assembly.html) may touch the `AC` flag if the `preserves_flags` is set. |
svsm | github_2023 | others | 473 | coconut-svsm | cxdong | @@ -45,7 +47,16 @@ pub const HV_VECTOR: usize = 28;
pub const VC_VECTOR: usize = 29;
pub const SX_VECTOR: usize = 30;
-pub const PF_ERROR_WRITE: usize = 2;
+bitflags! {
+ #[repr(transparent)]
+ #[derive(Copy, Clone, Debug, PartialEq)]
+ pub struct PFErrors: usize {
+ const PROT = 1 << 0;
+ const WRITE = 1 << 1;
+ const USER = 1 << 2;
+ const INSTR = 1 << 4;
+ }
+}
| It appears that `PFError` has the similar error flags with the `PageFaultError` within this file. It might be beneficial to consider merging the two for consistency and to reduce redundancy? |
svsm | github_2023 | others | 412 | coconut-svsm | msft-jlange | @@ -249,6 +249,8 @@ impl LocalApic {
Some(calling_area)
}
+ /// Attempts to deliver the specified IRQ into the specified guest CPU | We should distinguish this from queueing an interrupt. The key here is that this function attempts to deliver the specified interrupt so it will be observed immediately upon the next guest entry, and will fail if the guest state is such that interrupt delivery would need to be deferred (e.g. due to disabled interrupts or interrupt priority). I'm not sure how to state this succinctly in a comment, but it would be helpful. |
svsm | github_2023 | others | 472 | coconut-svsm | roy-hopkins | @@ -64,6 +64,10 @@ pub struct CmdOptions {
#[arg(long, default_value_t = false)]
pub native: bool,
+ /// Includ VSM isolation platform target. | Typo: "Includ" |
svsm | github_2023 | others | 472 | coconut-svsm | roy-hopkins | @@ -52,56 +176,105 @@ pub fn construct_vmsa(
let mut vmsa_box = SevVmsa::new_box_zeroed();
let vmsa = vmsa_box.as_mut();
- // Copy GPRs.
- vmsa.rax = context.rax;
- vmsa.rcx = context.rcx;
- vmsa.rdx = context.rdx;
- vmsa.rbx = context.rbx;
- vmsa.rsp = context.rsp;
- vmsa.rbp = context.rbp;
- vmsa.rsi = context.rsi;
- vmsa.rdi = context.rdi;
- vmsa.r8 = context.r8;
- vmsa.r9 = context.r9;
- vmsa.r10 = context.r10;
- vmsa.r11 = context.r11;
- vmsa.r12 = context.r12;
- vmsa.r13 = context.r13;
- vmsa.r14 = context.r14;
- vmsa.r15 = context.r15;
-
- // Configure other initial state registers.
- vmsa.rip = context.rip;
- vmsa.rflags = context.rflags;
-
- // Configure selectors.
- vmsa.cs.selector = context.code_selector;
- vmsa.cs.attrib = vmsa_convert_attributes(context.code_attributes);
- vmsa.cs.base = context.code_base as u64;
- vmsa.cs.limit = context.code_limit;
-
- vmsa.ds.attrib = vmsa_convert_attributes(context.data_attributes);
- vmsa.ds.limit = context.data_limit;
- vmsa.ds.base = context.data_base as u64;
- vmsa.ds.selector = context.data_selector;
- vmsa.ss = vmsa.ds;
- vmsa.es = vmsa.ds;
- vmsa.fs = vmsa.ds;
- vmsa.gs = vmsa.ds;
- vmsa.gs.base = context.gs_base;
-
- vmsa.idtr.base = context.idtr_base;
- vmsa.idtr.limit = context.idtr_limit as u32;
- vmsa.gdtr.base = context.gdtr_base;
- vmsa.gdtr.limit = context.gdtr_limit as u32;
-
- // Configure control registers.
- vmsa.cr0 = context.cr0;
- vmsa.cr3 = context.cr3;
- vmsa.cr4 = context.cr4;
+ // Copy values from the register list.
+ for reg in regs.iter() {
+ match reg {
+ X86Register::Rsp(r) => {
+ vmsa.rsp = *r;
+ }
+ X86Register::Rbp(r) => {
+ vmsa.rbp = *r;
+ }
+ X86Register::Rsi(r) => {
+ vmsa.rsi = *r;
+ }
+ X86Register::R8(r) => {
+ vmsa.r8 = *r;
+ }
+ X86Register::R9(r) => {
+ vmsa.r9 = *r;
+ }
+ X86Register::R10(r) => {
+ vmsa.r10 = *r;
+ }
+ X86Register::R11(r) => {
+ vmsa.r11 = *r;
+ }
+ X86Register::R12(r) => {
+ vmsa.r12 = *r;
+ }
+ X86Register::Rip(r) => {
+ vmsa.rip = *r;
+ }
+ X86Register::Rflags(r) => {
+ vmsa.rflags = *r;
+ }
+ X86Register::Idtr(table) => {
+ vmsa.gdtr.base = table.base;
+ vmsa.gdtr.limit = table.limit as u32;
+ }
+ X86Register::Gdtr(table) => {
+ vmsa.idtr.base = table.base;
+ vmsa.idtr.limit = table.limit as u32;
+ } | These two have been mixed up - Idtr sets gdtr and vise versa. |
svsm | github_2023 | others | 472 | coconut-svsm | roy-hopkins | @@ -52,56 +176,105 @@ pub fn construct_vmsa(
let mut vmsa_box = SevVmsa::new_box_zeroed();
let vmsa = vmsa_box.as_mut();
- // Copy GPRs.
- vmsa.rax = context.rax;
- vmsa.rcx = context.rcx;
- vmsa.rdx = context.rdx;
- vmsa.rbx = context.rbx;
- vmsa.rsp = context.rsp;
- vmsa.rbp = context.rbp;
- vmsa.rsi = context.rsi;
- vmsa.rdi = context.rdi;
- vmsa.r8 = context.r8;
- vmsa.r9 = context.r9;
- vmsa.r10 = context.r10;
- vmsa.r11 = context.r11;
- vmsa.r12 = context.r12;
- vmsa.r13 = context.r13;
- vmsa.r14 = context.r14;
- vmsa.r15 = context.r15;
-
- // Configure other initial state registers.
- vmsa.rip = context.rip;
- vmsa.rflags = context.rflags;
-
- // Configure selectors.
- vmsa.cs.selector = context.code_selector;
- vmsa.cs.attrib = vmsa_convert_attributes(context.code_attributes);
- vmsa.cs.base = context.code_base as u64;
- vmsa.cs.limit = context.code_limit;
-
- vmsa.ds.attrib = vmsa_convert_attributes(context.data_attributes);
- vmsa.ds.limit = context.data_limit;
- vmsa.ds.base = context.data_base as u64;
- vmsa.ds.selector = context.data_selector;
- vmsa.ss = vmsa.ds;
- vmsa.es = vmsa.ds;
- vmsa.fs = vmsa.ds;
- vmsa.gs = vmsa.ds;
- vmsa.gs.base = context.gs_base;
-
- vmsa.idtr.base = context.idtr_base;
- vmsa.idtr.limit = context.idtr_limit as u32;
- vmsa.gdtr.base = context.gdtr_base;
- vmsa.gdtr.limit = context.gdtr_limit as u32;
-
- // Configure control registers.
- vmsa.cr0 = context.cr0;
- vmsa.cr3 = context.cr3;
- vmsa.cr4 = context.cr4;
+ // Copy values from the register list.
+ for reg in regs.iter() {
+ match reg {
+ X86Register::Rsp(r) => {
+ vmsa.rsp = *r;
+ }
+ X86Register::Rbp(r) => {
+ vmsa.rbp = *r;
+ }
+ X86Register::Rsi(r) => {
+ vmsa.rsi = *r;
+ }
+ X86Register::R8(r) => { | No rdi? |
svsm | github_2023 | others | 472 | coconut-svsm | roy-hopkins | @@ -4,46 +4,170 @@
//
// Author: Roy Hopkins <roy.hopkins@suse.com>
-use igvm::snp_defs::{SevFeatures, SevVmsa};
+use igvm::registers::{SegmentRegister, X86Register};
+use igvm::snp_defs::{SevFeatures, SevSelector, SevVmsa};
use igvm::IgvmDirectiveHeader;
use igvm_defs::IgvmNativeVpContextX64;
use zerocopy::FromZeroes;
use crate::cmd_options::SevExtraFeatures;
-pub fn construct_start_context(start_rip: u64, start_rsp: u64) -> Box<IgvmNativeVpContextX64> {
- let mut context_box = IgvmNativeVpContextX64::new_box_zeroed();
- let context = context_box.as_mut();
+pub fn construct_start_context(start_rip: u64, start_rsp: u64) -> Vec<X86Register> {
+ let mut vec: Vec<X86Register> = Vec::new();
// Establish CS as a 32-bit code selector.
- context.code_attributes = 0xc09b;
- context.code_limit = 0xffffffff;
- context.code_selector = 0x08;
+ let cs = SegmentRegister {
+ attributes: 0xc09b,
+ base: 0,
+ limit: 0xffffffff,
+ selector: 0x08,
+ };
+ vec.push(X86Register::Cs(cs));
// Establish all data segments as generic data selectors.
- context.data_attributes = 0xa093;
- context.data_limit = 0xffffffff;
- context.data_selector = 0x10;
+ let ds = SegmentRegister {
+ attributes: 0xa093,
+ base: 0,
+ limit: 0xffffffff,
+ selector: 0x10,
+ };
+ vec.push(X86Register::Ds(ds));
+ vec.push(X86Register::Ss(ds));
+ vec.push(X86Register::Es(ds));
+ vec.push(X86Register::Fs(ds));
+ vec.push(X86Register::Gs(ds));
// CR0.PE | CR0.NE | CR0.ET.
- context.cr0 = 0x31;
+ vec.push(X86Register::Cr0(0x31));
// CR4.MCE.
- context.cr4 = 0x40;
+ vec.push(X86Register::Cr4(0x40));
+
+ vec.push(X86Register::Rflags(2));
+ vec.push(X86Register::Rip(start_rip));
+ vec.push(X86Register::Rsp(start_rsp));
+
+ vec
+}
+
+pub fn construct_native_start_context(
+ regs: &[X86Register],
+ compatibility_mask: u32,
+) -> IgvmDirectiveHeader {
+ let mut context_box = IgvmNativeVpContextX64::new_box_zeroed();
+ let context = context_box.as_mut();
- context.rflags = 2;
- context.rip = start_rip;
- context.rsp = start_rsp;
+ // Copy values from the register list.
+ for reg in regs.iter() {
+ match reg {
+ X86Register::Rsp(r) => {
+ context.rsp = *r;
+ }
+ X86Register::Rbp(r) => {
+ context.rbp = *r;
+ }
+ X86Register::Rsi(r) => {
+ context.rsi = *r;
+ }
+ X86Register::R8(r) => { | No rdi? |
svsm | github_2023 | others | 461 | coconut-svsm | Freax13 | @@ -361,6 +362,11 @@ impl PTEntry {
let addr = PhysAddr::from(self.0.bits() & 0x000f_ffff_ffff_f000);
strip_confidentiality_bits(addr)
}
+
+ /// Read a page table entry from the specified virtual address.
+ pub fn read_pte(vaddr: VirtAddr) -> PTEntry {
+ unsafe { *vaddr.as_ptr::<PTEntry>() }
+ } | ```suggestion
/// Read a page table entry from the specified virtual address.
pub unsafe fn read_pte(vaddr: VirtAddr) -> Self {
unsafe { *vaddr.as_ptr::<Self>() }
}
``` |
svsm | github_2023 | others | 461 | coconut-svsm | Freax13 | @@ -457,14 +463,28 @@ impl PageTable {
virt_to_phys(pgtable)
}
+ /// Initializes the self-map pointer within the page table.
+ pub fn set_self_map(&mut self, paddr: PhysAddr) { | ```suggestion
pub unsafe fn set_self_map(&mut self, paddr: PhysAddr) {
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.