blob: d63d35ab28f09add2b6272c92b5f0cb538620de3 [file]
// Copyright 2018 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
//! Pages of physical memory used by the hypervisor.
use core::array;
use core::mem::{align_of, size_of};
use core::ops::{Deref, DerefMut};
use core::ptr::{self, NonNull};
use pin_init::{Init, stack_pin_init};
use zr::static_assert;
use zx_status::Status;
use crate::kernel::types::PAddr;
use crate::vm::page::{VmPageDoublyLinkedList, VmPagePtr};
use crate::vm::page_state::VmPageState;
use crate::vm::{physmap, pmm};
/// A wired page of physical memory, which is freed when dropped.
///
/// The C++ `hypervisor::Page` in `<hypervisor/page.h>` is a facade over this type.
#[derive(Debug)]
#[repr(C)]
pub struct Page {
/// The allocated page, or `None` if no page has been allocated.
// Safety invariant: If `Some`, the page was allocated from the PMM without allowing loaned
// pages, is in the WIRED state, is not in any page queue, and is exclusively owned by this
// `Page`.
page: Option<VmPagePtr>,
/// The physical address of `page`, or 0 if no page has been allocated.
// Safety invariant: `pa` is `PAddr(0)` if and only if `page` is `None`. When `page` is
// `Some(p)`, `pa` is `p`'s non-zero, `page::SIZE`-aligned physical address mapped in the
// kernel physmap.
pa: PAddr,
}
static_assert!(size_of::<Page>() == 16);
static_assert!(align_of::<Page>() == 8);
// SAFETY: `Page` uniquely owns its page, so it may be dropped (freeing the page) on any thread.
unsafe impl Send for Page {}
// SAFETY: Shared references only read `page` and `pa`, which are never mutated through `&Page`.
// Accesses to the page's memory are made through raw pointers, which callers must synchronize.
unsafe impl Sync for Page {}
impl Page {
/// Creates a `Page` with no page allocated.
#[inline]
pub const fn new() -> Self {
Self { page: None, pa: PAddr(0) }
}
/// Allocates a wired page, and fills it with `fill`.
///
/// # Panics
///
/// Panics if `self` is already allocated (`self.is_allocated()`) or if `pmm::alloc_page`
/// returns physical address 0, preventing a wired PMM page leak on double allocation.
///
/// # Safety-usable invariant
///
/// When this returns `Ok(())`, `self.is_allocated()` is `true` and the `page::SIZE` bytes at
/// `self.virtual_address()` are initialized to `fill` and exclusively owned by `self`.
pub fn alloc(&mut self, fill: u8) -> Result<(), Status> {
// Allocating again would leak the previously allocated page.
assert!(!self.is_allocated());
let (page, pa) = pmm::alloc_page(0)?;
// `pa == 0` is the unallocated sentinel for `is_allocated`; enforce the non-zero `pa`
// safety invariant across architectures where `pmm::alloc_page` does not guarantee it.
assert!(pa.0 != 0);
self.page = Some(page);
self.pa = pa;
// SAFETY: `page` was just allocated, so `self` has exclusive ownership of it.
unsafe { page.set_state(VmPageState::WIRED) };
// SAFETY: `virtual_address` is the physmap mapping of the page that was just allocated,
// which is `page::SIZE` bytes long and not referenced by anything else.
unsafe { ptr::write_bytes(self.virtual_address::<u8>(), fill, page::SIZE) };
Ok(())
}
/// Returns the address of the page in the physmap.
///
/// # Safety-usable invariant
///
/// When `self.is_allocated()` is `true`, returns the `page::SIZE`-aligned kernel physmap
/// address of the `page::SIZE` writable bytes owned by `self`. Must not be dereferenced when
/// `self.is_allocated()` is `false` (checked only by `debug_assert!`).
#[inline]
pub fn virtual_address<T>(&self) -> *mut T {
debug_assert!(self.pa.0 != 0);
physmap::paddr_to_physmap_mut(self.pa)
}
/// Returns the physical address of the page.
///
/// # Safety-usable invariant
///
/// When `self.is_allocated()` is `true`, returns the non-zero, `page::SIZE`-aligned physical
/// address of the wired page owned by `self`.
#[inline]
pub fn physical_address(&self) -> PAddr {
debug_assert!(self.pa.0 != 0);
self.pa
}
/// Returns whether a page has been allocated.
///
/// # Safety-usable invariant
///
/// Returns `true` if and only if `self` owns an allocated wired page mapped in the physmap.
#[inline]
pub fn is_allocated(&self) -> bool {
self.pa.0 != 0
}
}
impl Default for Page {
fn default() -> Self {
Self::new()
}
}
impl Drop for Page {
fn drop(&mut self) {
if let Some(page) = self.page.take() {
// SAFETY: By `self.page`'s safety invariant, `page` was allocated from the PMM without
// allowing loaned pages, is not in any page queue, and `self.page.take()` transfers
// exclusive ownership to `pmm::free_page`.
unsafe { pmm::free_page(page) };
}
}
}
/// Owns a wired physical page containing an in-place initialized value of type `T`.
#[derive(Debug)]
#[repr(C)]
pub struct PagePtr<T> {
page: Page,
// Safety invariant: If `Some(ptr)`, `self.page` is allocated and `ptr` points to a valid,
// properly aligned, initialized `T` exclusively owned by `self` at the start of `self.page`'s
// physmap mapping.
ptr: Option<NonNull<T>>,
}
static_assert!(size_of::<PagePtr<u8>>() == 24);
static_assert!(align_of::<PagePtr<u8>>() == 8);
// SAFETY: `PagePtr<T>` exclusively owns the backing page and `T` instance.
unsafe impl<T: Send> Send for PagePtr<T> {}
// SAFETY: Shared references to `PagePtr<T>` only permit shared access (`&T` via `Deref`, or
// `*const T` via `PagePtr::as_ptr`), which is sound because `T: Sync`. Exclusive access (`&mut T`
// via `DerefMut` or `*mut T` via `PagePtr::as_mut_ptr`) requires an exclusive `&mut self`.
unsafe impl<T: Sync> Sync for PagePtr<T> {}
impl<T> Default for PagePtr<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> PagePtr<T> {
/// Creates an unallocated `PagePtr<T>`.
pub const fn new() -> Self {
Self { page: Page::new(), ptr: None }
}
/// Allocates a zero-filled wired page and initializes `T` in place via `init`.
///
/// # Panics
///
/// Panics if `self` is already allocated (`self.ptr.is_some()`), preventing a live `T` from
/// being overwritten without dropping.
pub fn alloc_init(&mut self, init: impl Init<T>) -> Result<(), Status> {
const {
assert!(size_of::<T>() <= page::SIZE);
assert!(align_of::<T>() <= page::SIZE);
}
assert!(self.ptr.is_none());
self.page.alloc(0)?;
let raw = self.page.virtual_address::<T>();
let ptr = NonNull::new(raw).expect("physmap virtual address must be non-null");
// SAFETY: By the safety-usable invariants of `Page::alloc` and `Page::virtual_address`,
// `self.page.is_allocated()` is `true` after `self.page.alloc(0)` returns `Ok(())`, and
// `ptr.as_ptr()` is the non-null, `page::SIZE`-aligned (`align_of::<T>() <= page::SIZE`)
// physmap address of `page::SIZE` (`size_of::<T>() <= page::SIZE`) zero-initialized
// writable bytes exclusively owned by `self.page` for the duration of `__init`.
let Ok(()) = unsafe { init.__init(ptr.as_ptr()) };
self.ptr = Some(ptr);
Ok(())
}
/// Allocates a zero-filled wired page containing a zero-initialized `T`.
pub fn alloc(&mut self) -> Result<(), Status>
where
T: pin_init::Zeroable,
{
self.alloc_init(pin_init::init_zeroed())
}
/// Returns the physical address of the backing page.
#[inline]
pub fn physical_address(&self) -> PAddr {
self.page.physical_address()
}
/// Returns a const raw pointer to the contained `T`, or null if unallocated.
#[inline]
pub fn as_ptr(this: &Self) -> *const T {
this.ptr.map_or(ptr::null(), |p| p.as_ptr().cast_const())
}
/// Returns a mutable raw pointer to the contained `T`, or null if unallocated.
#[inline]
pub fn as_mut_ptr(this: &mut Self) -> *mut T {
this.ptr.map_or(ptr::null_mut(), NonNull::as_ptr)
}
}
impl<T> Deref for PagePtr<T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
// SAFETY: By `self.ptr`'s safety invariant, `ptr` is aligned and points to an initialized
// `T` exclusively owned by `self` in `self.page`, so shared borrow `&self` guarantees no
// mutable aliases exist for the returned reference's lifetime.
unsafe { self.ptr.expect("PagePtr::deref called before alloc").as_ref() }
}
}
impl<T> DerefMut for PagePtr<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: By `self.ptr`'s safety invariant, `ptr` is aligned and points to an initialized
// `T` exclusively owned by `self` in `self.page`, and `&mut self` guarantees exclusive
// access for the returned reference's lifetime.
unsafe { self.ptr.expect("PagePtr::deref_mut called before alloc").as_mut() }
}
}
impl<T> Drop for PagePtr<T> {
fn drop(&mut self) {
if let Some(ptr) = self.ptr.take() {
// SAFETY: By `self.ptr`'s safety invariant, `ptr` is aligned and points to an
// initialized `T` exclusively owned by `self`, and `self.page` is dropped only after
// `Drop::drop` returns.
unsafe {
ptr::drop_in_place(ptr.as_ptr());
}
}
}
}
/// A wired, physically contiguous run of `N` pages of physical memory, which is freed when dropped.
///
/// AMD SVM hardware strictly requires physically contiguous memory for guest permission maps:
/// the VMCB points to the 12 KiB (3-page) I/O permission map via a single 4-KiB-aligned physical
/// base address (`IOPM_BASE_PA` at offset `0x040`) and to the 8 KiB (2-page) MSR permission map
/// via a single 4-KiB-aligned physical base address (`MSRPM_BASE_PA` at offset `0x048`), which
/// the CPU indexes directly in physical memory without virtual or scatter-gather mappings (AMD
/// APM Vol. 2, Sections 15.10 and 15.11). Single-page structures (such as VMCBs, HSAVE areas,
/// and Intel VMX bitmaps) should continue to use [`Page`] or [`PagePtr`].
///
/// `ContiguousPages<N>` stores `[VmPagePtr; N]` inline (`8 * N` bytes) and constructs and returns
/// itself by value on the kernel stack, so it is intended only for small `N` (such as `2` and `3`).
#[derive(Debug)]
pub struct ContiguousPages<const N: usize> {
/// The `N` allocated pages in strictly ascending physical address order.
// Safety invariant: All `N` entries are distinct (`pages[i].paddr() == pa + i * page::SIZE`)
// pointers to valid, live, allocated (unfreed), non-loaned PMM `VmPage`s in the `WIRED` state
// that are not in any page queue or intrusive list and are exclusively owned by this
// `ContiguousPages` until freed once in `Drop::drop`.
pages: [VmPagePtr; N],
/// The physical address of the first page in the contiguous run.
// Safety invariant: `N >= 2`, `N * page::SIZE <= isize::MAX as usize`, `pa` is non-zero and
// `page::SIZE`-aligned, `pa.0 + N * page::SIZE` does not overflow `usize`, and
// `[pa, pa + N * page::SIZE)` is a physically contiguous RAM run whose kernel physmap range
// `[paddr_to_physmap(pa), paddr_to_physmap(pa) + N * page::SIZE)` is valid, non-null,
// `page::SIZE`-aligned, and does not wrap `usize`.
pa: PAddr,
}
// SAFETY: `pa` (`PAddr`) is `Send`. Every `VmPagePtr` in `pages` points to permanently resident,
// non-thread-bound PMM arena bookkeeping exclusively owned by `self`, and `Drop` frees the pages
// via `pmm::free_list`, which synchronizes deallocation into the global PMM from any thread.
unsafe impl<const N: usize> Send for ContiguousPages<N> {}
// SAFETY: `pa` (`PAddr`) is `Sync`, neither field has interior mutability or is mutated through
// `&ContiguousPages<N>`, and `#[derive(Debug)]` formats `VmPagePtr` addresses without
// dereferencing `VmPage`. Accesses to the mapped page memory go through raw pointers from
// `virtual_address`, which callers must synchronize externally.
unsafe impl<const N: usize> Sync for ContiguousPages<N> {}
impl<const N: usize> ContiguousPages<N> {
/// Total size of the contiguous run in bytes (`N * page::SIZE`).
///
/// Evaluating this constant enforces `N >= 2` (single-page allocations should use [`Page`] or
/// [`PagePtr`]) and `N * page::SIZE <= isize::MAX as usize` at compile time.
pub const SIZE: usize = {
assert!(N >= 2);
assert!(N <= (isize::MAX as usize) / page::SIZE);
N * page::SIZE
};
/// Allocates `N` wired, physically contiguous pages and fills them with `fill`.
///
/// Returns `Err(Status::NO_MEMORY)` if no contiguous run of `N` free pages is available
/// (mapping `Status::NOT_FOUND` from `pmm::alloc_contiguous` for consistency with
/// [`Page::alloc`]).
///
/// # Panics
///
/// Panics if `pmm::alloc_contiguous` returns an unaligned, zero, overflowing, or
/// non-physmap-backed physical address range, a null or unaligned physmap address, a loaned
/// page, or a non-contiguous page list whose length does not equal `N`.
///
/// # Safety-usable invariant
///
/// When this returns `Ok(pages)`, `0 < Self::SIZE <= isize::MAX as usize`, `pages` exclusively
/// owns a physically contiguous run of `N` wired, non-loaned pages at
/// `[pages.physical_address(), pages.physical_address() + Self::SIZE)` that remain live,
/// wired, and mapped in the kernel physmap until `pages` is dropped, and all `Self::SIZE`
/// bytes at `pages.virtual_address()` are initialized to `fill`.
pub fn alloc(fill: u8) -> Result<Self, Status> {
let _ = Self::SIZE;
stack_pin_init!(let list = VmPageDoublyLinkedList::new());
let pa =
pmm::alloc_contiguous(N, 0, page::SHIFT as u8, list.as_mut()).map_err(|status| {
if status == Status::NOT_FOUND { Status::NO_MEMORY } else { status }
})?;
assert!(
pa.0 != 0 && page::is_page_rounded(pa.0),
"pmm::alloc_contiguous returned invalid physical address {:#x}",
pa.0
);
let end_pa =
pa.0.checked_add(Self::SIZE)
.expect("pmm::alloc_contiguous physical range overflowed usize");
assert!(
physmap::is_physmap_phys_addr(PAddr(end_pa - 1))
&& physmap::physmap_base().checked_add(end_pa).is_some(),
"pmm::alloc_contiguous physical range [{:#x}, {:#x}) is outside valid physmap",
pa.0,
end_pa
);
let va = physmap::paddr_to_physmap(pa);
assert!(
va.0 != 0 && page::is_page_rounded(va.0),
"pmm::alloc_contiguous physmap address {:#x} is null or unaligned",
va.0
);
let pages = array::from_fn(|i| {
let page_nn = list
.as_mut()
.pop_front()
.expect("pmm::alloc_contiguous returned fewer than N pages");
let page = VmPagePtr::new(page_nn);
// SAFETY: `page` was just popped from `list` as a valid, live PMM `VmPage` exclusively
// owned by this function, so inspecting its physical address is safe.
let page_pa = unsafe { page.paddr() };
// `pa.0 + Self::SIZE` did not overflow above and `i < N`, so `pa.0 + i * page::SIZE`
// cannot overflow.
assert_eq!(page_pa.0, pa.0 + i * page::SIZE);
// SAFETY: `page` is a valid, live PMM `VmPage` exclusively owned by this function, so
// inspecting its loaned flag is safe.
let is_loaned = unsafe { page.is_loaned() };
assert!(!is_loaned, "pmm::alloc_contiguous returned a loaned page");
// SAFETY: `page` is a valid, live PMM `VmPage` exclusively owned by this function;
// transitioning it to `VmPageState::WIRED` establishes the `WIRED` state postcondition.
unsafe { page.set_state(VmPageState::WIRED) };
page
});
assert!(list.is_empty(), "pmm::alloc_contiguous returned more than N pages");
let dst: *mut u8 = physmap::paddr_to_physmap_mut(pa);
// SAFETY: `dst` has address `va`, which is verified above to be non-null and
// `page::SIZE`-aligned (and therefore aligned for `u8`). By the physmap bounds and
// overflow checks above, `[dst, dst + Self::SIZE)` lies within a single non-wrapping
// kernel physmap mapping of the `N` newly allocated pages, with
// `2 * page::SIZE <= Self::SIZE <= isize::MAX as usize` (enforced by `Self::SIZE`). No
// other reference exists before `Self` is returned, so we have exclusive write access, and
// after this call all `Self::SIZE` bytes are initialized to `fill`.
unsafe { ptr::write_bytes(dst, fill, Self::SIZE) };
Ok(Self { pages, pa })
}
/// Returns the address of the first page in the kernel physmap.
///
/// # Safety-usable invariant
///
/// Returns a non-null, `page::SIZE`-aligned pointer to the start of a single non-wrapping
/// contiguous kernel physmap mapping of `Self::SIZE` bytes (`0 < Self::SIZE <= isize::MAX as
/// usize`), corresponding to `[self.physical_address(), self.physical_address() +
/// Self::SIZE)`. The memory is valid for both reads and writes and remains live, wired, and
/// mapped until `self` is dropped. Callers accessing this memory through `&self` must
/// synchronize concurrent reads and writes externally.
#[inline]
pub fn virtual_address<T>(&self) -> *mut T {
physmap::paddr_to_physmap_mut(self.pa)
}
/// Returns the physical address of the first page.
///
/// # Safety-usable invariant
///
/// Returns a non-zero, `page::SIZE`-aligned physical address `pa` such that `pa.0 + Self::SIZE`
/// does not overflow `usize`, `0 < Self::SIZE <= isize::MAX as usize`, and
/// `[pa, pa + Self::SIZE)` is a physically contiguous run of `N` wired, non-loaned RAM pages
/// mapped in the kernel physmap that remain live and wired until `self` is dropped.
#[inline]
pub fn physical_address(&self) -> PAddr {
self.pa
}
}
impl<const N: usize> Drop for ContiguousPages<N> {
fn drop(&mut self) {
stack_pin_init!(let list = VmPageDoublyLinkedList::new());
for &page in &self.pages {
// SAFETY: By `self.pages`'s safety invariant, every `page` points to a valid, live
// `VmPage` outliving `list` that is not in any page queue or intrusive list; all `N`
// entries in `self.pages` are distinct (strictly ascending physical addresses), so no
// earlier iteration pushed the same page onto `list`; by `VmPage`'s documented
// VM-wide invariant (`zircon/kernel/vm/page.rs`), `&mut VmPage` is never formed; and
// `VmPage` is statically arena-resident and never moved or dropped.
unsafe { list.as_mut().push_back_raw(page.as_non_null()) };
}
// SAFETY: `list` started empty and now holds only the `N` valid, allocated (unfreed),
// non-loaned PMM pages exclusively owned by `self`, none of which are in any page queue;
// `Drop::drop` runs at most once, transferring exclusive ownership to `pmm::free_list`,
// which empties `list` before `list`'s `PinnedDrop` runs.
unsafe { pmm::free_list(list) };
}
}
/// Unit tests for `Page`, `PagePtr`, and `ContiguousPages`.
#[cfg(ktest)]
#[unittest::suite(name = "hypervisor_page")]
mod tests {
use super::{ContiguousPages, Page, PagePtr};
use crate::kernel::types::{PAddr, VAddr};
use crate::vm::page_state::VmPageState;
use crate::vm::{physmap, pmm};
use unittest::{
assert_ok, expect_eq, expect_false, expect_ne, expect_true, unwrap_ok, unwrap_some,
};
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ContiguousPages<2>>();
assert_send_sync::<ContiguousPages<3>>();
};
#[repr(C)]
#[derive(pin_init::Zeroable)]
struct TestStruct {
a: u64,
b: u64,
}
/// Verifies that a `Page` is only allocated after `alloc`, which fills it.
#[test]
fn alloc_fills_page() {
const FILL: u8 = 0xa5;
let mut page = Page::new();
expect_false!(page.is_allocated());
assert_ok!(page.alloc(FILL));
expect_true!(page.is_allocated());
expect_ne!(0, page.physical_address().0);
// SAFETY: `virtual_address` maps the `page::SIZE` bytes of the page `page` owns, which
// nothing else accesses while the slice is alive.
let bytes =
unsafe { core::slice::from_raw_parts(page.virtual_address::<u8>(), page::SIZE) };
expect_true!(bytes.iter().all(|&b| b == FILL));
}
/// Verifies that `PagePtr::alloc` and `PagePtr::alloc_init` initialize `T` in place.
#[test]
fn page_ptr_alloc() {
let mut ptr = PagePtr::<TestStruct>::new();
expect_true!(PagePtr::as_ptr(&ptr).is_null());
assert_ok!(ptr.alloc());
expect_false!(PagePtr::as_ptr(&ptr).is_null());
expect_false!(PagePtr::as_mut_ptr(&mut ptr).is_null());
expect_eq!(ptr.a, 0);
expect_eq!(ptr.b, 0);
ptr.a = 42;
ptr.b = 99;
expect_eq!(ptr.a, 42);
expect_eq!(ptr.b, 99);
let mut init_ptr = PagePtr::<TestStruct>::new();
assert_ok!(init_ptr.alloc_init(pin_init::init!(TestStruct { a: 123, b: 456 })));
expect_eq!(init_ptr.a, 123);
expect_eq!(init_ptr.b, 456);
}
fn verify_contiguous_pages<const N: usize>(fill: u8) -> bool {
unittest::subtest!(|| {
let pages = unwrap_ok!(ContiguousPages::<N>::alloc(fill));
let base_pa = pages.physical_address();
expect_ne!(0, base_pa.0);
expect_eq!(0, base_pa.0 % page::SIZE);
let va = pages.virtual_address::<u8>();
expect_eq!(0, va.addr() % page::SIZE);
expect_eq!(physmap::physmap_to_paddr(VAddr(va.addr())).0, base_pa.0);
// Verify every page in the run is physically contiguous and in the `WIRED` state.
for i in 0..N {
let expected_pa = PAddr(base_pa.0 + i * page::SIZE);
let vm_page = unwrap_some!(pmm::paddr_to_vm_page(expected_pa));
// SAFETY: `pages` exclusively owns the `N` wired pages in
// `[base_pa, base_pa + ContiguousPages::<N>::SIZE)`, so `vm_page` is a valid, live
// PMM `VmPage` owned by `pages` and inspecting its physical address is safe.
let actual_pa = unsafe { vm_page.paddr() };
expect_eq!(actual_pa.0, expected_pa.0);
expect_true!(vm_page.state() == VmPageState::WIRED);
}
// Verify the entire `N * page::SIZE` range was initialized with `fill`.
// SAFETY: By `ContiguousPages::alloc` and `ContiguousPages::virtual_address`'s
// safety-usable invariants, `va` is non-null and aligned for `u8` (align 1), points to
// a single non-wrapping contiguous allocation of `ContiguousPages::<N>::SIZE <=
// isize::MAX as usize` bytes initialized to `fill` and valid for reads, nothing else
// mutates this memory, and `bytes` is dropped before `drop(pages)`.
let bytes = unsafe { core::slice::from_raw_parts(va, ContiguousPages::<N>::SIZE) };
expect_true!(bytes.iter().all(|&b| b == fill));
drop(pages);
})()
}
/// Verifies `ContiguousPages<2>` allocation, fill, contiguity, alignment, and drop cleanup.
#[test]
fn contiguous_pages_two() {
for fill in [0x00, 0xff, 0xa5] {
expect_true!(verify_contiguous_pages::<2>(fill));
}
}
/// Verifies `ContiguousPages<3>` allocation, fill, contiguity, alignment, and drop cleanup.
#[test]
fn contiguous_pages_three() {
for fill in [0x00, 0xff, 0x5a] {
expect_true!(verify_contiguous_pages::<3>(fill));
}
}
}