|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +//! Provides a mapper implementation for the page pool that uses the hcl ioctl |
| 5 | +//! crate to map guest memory. |
| 6 | +
|
| 7 | +#![cfg(target_os = "linux")] |
| 8 | +#![warn(missing_docs)] |
| 9 | + |
| 10 | +use anyhow::Context; |
| 11 | +use hcl::ioctl::MshvVtlLow; |
| 12 | +use hvdef::HV_PAGE_SIZE; |
| 13 | +use inspect::Inspect; |
| 14 | +use inspect::Response; |
| 15 | +use page_pool_alloc::Mapper; |
| 16 | +use page_pool_alloc::PoolType; |
| 17 | +use sparse_mmap::SparseMapping; |
| 18 | + |
| 19 | +/// A mapper that uses [`MshvVtlLow`] to map pages. |
| 20 | +#[derive(Inspect)] |
| 21 | +#[inspect(extra = "HclMapper::inspect_extra")] |
| 22 | +pub struct HclMapper { |
| 23 | + #[inspect(skip)] |
| 24 | + fd: MshvVtlLow, |
| 25 | +} |
| 26 | + |
| 27 | +impl HclMapper { |
| 28 | + /// Creates a new [`HclMapper`]. |
| 29 | + pub fn new() -> Result<Self, anyhow::Error> { |
| 30 | + let fd = MshvVtlLow::new().context("failed to open gpa fd")?; |
| 31 | + Ok(Self { fd }) |
| 32 | + } |
| 33 | + |
| 34 | + fn inspect_extra(&self, resp: &mut Response<'_>) { |
| 35 | + resp.field("type", "hcl_mapper"); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +impl Mapper for HclMapper { |
| 40 | + fn map( |
| 41 | + &self, |
| 42 | + base_pfn: u64, |
| 43 | + size_pages: u64, |
| 44 | + pool_type: PoolType, |
| 45 | + ) -> Result<SparseMapping, anyhow::Error> { |
| 46 | + let len = (size_pages * HV_PAGE_SIZE) as usize; |
| 47 | + let mapping = SparseMapping::new(len).context("failed to create mapping")?; |
| 48 | + let gpa = base_pfn * HV_PAGE_SIZE; |
| 49 | + |
| 50 | + // When the pool references shared memory, on hardware isolated |
| 51 | + // platforms the file_offset must have the shared bit set as these |
| 52 | + // are decrypted pages. Setting this bit is okay on non-hardware |
| 53 | + // isolated platforms, as it does nothing. |
| 54 | + let file_offset = match pool_type { |
| 55 | + PoolType::Private => gpa, |
| 56 | + PoolType::Shared => { |
| 57 | + tracing::trace!("setting MshvVtlLow::SHARED_MEMORY_FLAG"); |
| 58 | + gpa | MshvVtlLow::SHARED_MEMORY_FLAG |
| 59 | + } |
| 60 | + }; |
| 61 | + |
| 62 | + tracing::trace!(gpa, file_offset, len, "mapping allocation"); |
| 63 | + |
| 64 | + mapping |
| 65 | + .map_file(0, len, self.fd.get(), file_offset, true) |
| 66 | + .context("unable to map allocation")?; |
| 67 | + |
| 68 | + Ok(mapping) |
| 69 | + } |
| 70 | +} |
0 commit comments