Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion docs/src/dxe_core/memory_management.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,43 @@ normal case after the allocators have run for a while and have built up a set of
Freeing a block (except for very large blocks) is also constant-time, since the procedure is the reverse of the above:

1. Round up the freed allocation size to the next block size.
2. Push the block on the front of the corresponding "free-list."
2. Push the block to the tail of the corresponding "free-list."

Freed blocks are appended to the back of the free list rather than the front so that a block is not immediately handed
back out. Recycling blocks in FIFO order maximizes the time between a block being freed and it being
reused, which increases the chance that a use-after-free accesses memory that has not yet been handed to another owner.

When every pool segmented from a page has been returned to the free lists, the page is retired and unmapped. This
catches as many use-after-free cases as we can in the pool allocator. Retired pages are re-mapped and returned to the
Comment thread
os-d marked this conversation as resolved.
Resolved
backing allocator when the allocator would otherwise have to claim more memory from the GCD. Retired pages are also
reclaimed in FIFO order to maximize the time between address reuse.

Memory claimed from the GCD starts in the retired state, so an allocator never has memory mapped that it has not
Comment thread
os-d marked this conversation as resolved.
Resolved
handed out.

```mermaid
stateDiagram-v2
direction TB

state "GCD-owned system memory" as GCD
state "Fallback allocator free memory<br/>(mapped)" as Fallback
state "Fixed-size blocks<br/>(mapped)" as FixedBlocks
state "FSB retired page<br/>(unmapped)" as Retired
state "Direct fallback allocation<br/>(mapped)" as DirectAllocation

GCD --> Fallback: FSB claims an expansion
Fallback --> FixedBlocks: Carve page into fixed-size blocks
FixedBlocks --> FixedBlocks: Allocate and free blocks
FixedBlocks --> Retired: Entire page becomes free and is retired
Retired --> Fallback: Reclaim and map page

Fallback --> DirectAllocation: Large allocation bypasses fixed-size blocks
DirectAllocation --> Fallback: Free allocation
```

The FSB retains ownership of retired pages even while they are unmapped. New expansion pages not needed immediately may
enter the retired state directly. The metadata page remains mapped, and direct fallback allocations never enter the
fixed-size block lifecycle.

If the fixed-block size list corresponding to the requested block size is empty or if the requested size is larger than
any fixed-block size, then the allocation falls back to a linked-list based allocator. This is also typically constant-
Expand Down
8 changes: 8 additions & 0 deletions patina_dxe_core/src/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ pub struct AllocationStatistics {

/// The number of pages claimed for use by this allocator.
pub claimed_pages: usize,

/// The number of pool pages that have been fully freed and unmapped.
pub retired_pages: usize,

/// The number of retired pool pages that have been re-mapped and returned to service.
pub reclaimed_pages: usize,
}

impl AllocationStatistics {
Expand All @@ -139,6 +145,8 @@ impl AllocationStatistics {
reserved_size: 0,
reserved_used: 0,
claimed_pages: 0,
retired_pages: 0,
reclaimed_pages: 0,
}
}
}
Expand Down
1,347 changes: 1,220 additions & 127 deletions patina_dxe_core/src/allocator/fixed_size_block_allocator.rs

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion patina_dxe_core/src/allocator/uefi_allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,9 @@ mod tests {
" page_free_calls: 0\r\n",
" reserved_size: 0\r\n",
" reserved_used: 0\r\n",
" claimed_pages: 0\r\n"
" claimed_pages: 0\r\n",
" retired_pages: 0\r\n",
" reclaimed_pages: 0\r\n"
)
);
});
Expand Down
1 change: 1 addition & 0 deletions patina_dxe_core/src/core_patina_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
//! SPDX-License-Identifier: Apache-2.0
//!

mod allocator_tests;
mod audit_tests;
mod mp_services_tests;
mod stability_tests;
Expand Down
142 changes: 142 additions & 0 deletions patina_dxe_core/src/core_patina_tests/allocator_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
//! DXE Core Patina Test Allocator Tests
//!
//! These tests verify the pool allocator's page retirement behavior against the live page table.
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!

use super::test_support::is_mapped;
use crate::{
GCD,
allocator::{EFI_BOOT_SERVICES_DATA_ALLOCATOR, STATIC_ALLOCATORS},
events::{raise_tpl, restore_tpl},
};
use alloc::vec::Vec;
use core::{
alloc::{Allocator, Layout},
ffi::c_void,
ops::Range,
};
use patina::{UEFI_PAGE_SIZE, pi::dxe_services::GcdMemoryType};
use patina_test::{patina_test, u_assert, u_assert_eq};
// used in the macro, but not directly referenced; causes a warning if patina tests not enabled.
#[allow(unused)]
use patina::BinaryGuid;
#[allow(unused)]
use patina::standard::efi;

fn page_attributes(address: usize) -> Result<u64, &'static str> {
GCD.get_memory_descriptor_for_address(address as efi::PhysicalAddress, |d, _| {
d.memory_type != GcdMemoryType::NonExistent
})
.map(|descriptor| descriptor.attributes)
.map_err(|_| "No GCD descriptor for pool memory")
}

/// Verifies that consecutive pool allocations return distinct addresses. The pool allocators are set up to
/// always serve new allocations in FIFO order. Interrupts are disabled in this test just to protect against the
/// rare case where event handling in the middle of the allocation could cause the free list to wrap around.
#[patina_test]
fn pool_allocations_with_interrupts_disabled_are_unique() -> patina_test::error::Result {
const ALLOCATION_SIZE: usize = 0x20;

let mut first: *mut c_void = core::ptr::null_mut();
let mut second: *mut c_void = core::ptr::null_mut();

let interrupts_enabled = patina::arch::interrupts_enabled();
patina::arch::disable_interrupts();
// SAFETY: Both out pointers refer to writable local variables.
let first_result =
unsafe { EFI_BOOT_SERVICES_DATA_ALLOCATOR.allocate_pool(ALLOCATION_SIZE, core::ptr::addr_of_mut!(first)) };
// SAFETY: The out pointer refers to a writable local variable.
let second_result =
unsafe { EFI_BOOT_SERVICES_DATA_ALLOCATOR.allocate_pool(ALLOCATION_SIZE, core::ptr::addr_of_mut!(second)) };
if interrupts_enabled {
patina::arch::enable_interrupts();
}

first_result.map_err(|_| "First pool allocation failed")?;
second_result.map_err(|_| "Second pool allocation failed")?;
u_assert!(first != second, "Consecutive pool allocations returned the same address");

// SAFETY: Both pointers were successfully allocated above by this allocator and have not yet been freed.
unsafe {
EFI_BOOT_SERVICES_DATA_ALLOCATOR.free_pool(first).map_err(|_| "Failed to free first pool allocation")?;
EFI_BOOT_SERVICES_DATA_ALLOCATOR.free_pool(second).map_err(|_| "Failed to free second pool allocation")?;
}

Ok(())
}

/// Verifies that a pool page is unmapped once every block in it has been freed.
#[patina_test]
fn fully_freed_pool_page_is_unmapped() -> patina_test::error::Result {
// A page sized block occupies an entire page on its own, so freeing it frees the whole page.
let layout = Layout::from_size_align(UEFI_PAGE_SIZE, UEFI_PAGE_SIZE).map_err(|_| "Bad layout")?;

for (allocator, memory_type) in &STATIC_ALLOCATORS {
let allocation = allocator.allocate(layout).map_err(|_| "Failed to allocate a pool page")?.cast::<u8>();
let page = allocation.addr().get();
log::info!("Checking retirement of pool page {page:#x} for memory type {memory_type:#x}");

u_assert_eq!(page % UEFI_PAGE_SIZE, 0);
u_assert_eq!(page_attributes(page)? & efi::MEMORY_RP, 0, "In use pool page is marked RP");
u_assert!(is_mapped(page as u64), "In use pool page is not mapped");

// The page is mapped, so writing to it must not fault.
// SAFETY: the allocation is a full page of memory owned by this test.
unsafe { core::ptr::write_volatile(page as *mut u8, 0xA5) };

let retired = allocator.stats().retired_pages;

// SAFETY: the allocation was returned by this allocator for this layout.
unsafe { allocator.deallocate(allocation, layout) };

u_assert!(allocator.stats().retired_pages > retired, "Freed pool page was not retired");
u_assert_eq!(page_attributes(page)? & efi::MEMORY_RP, efi::MEMORY_RP, "Freed pool page is not marked RP");
u_assert!(!is_mapped(page as u64), "Freed pool page is still mapped");
}

Ok(())
}

/// Verifies that the allocators do not have memory mapped that they have not handed out, and that the retirement
/// state tracked by the GCD matches the page table.
#[patina_test]
#[on(event = BinaryGuid(efi::EVENT_GROUP_READY_TO_BOOT))]
fn unused_pool_memory_is_unmapped() -> patina_test::error::Result {
let ranges: Vec<_> = STATIC_ALLOCATORS.iter().flat_map(|(allocator, _)| allocator.get_memory_ranges()).collect();

// Raised so that nothing can map pool memory in while the page table is being compared against the GCD.
let tpl = raise_tpl(efi::TPL_HIGH_LEVEL);
let result = check_pool_pages(&ranges);
restore_tpl(tpl);

// Pool memory is claimed from the GCD in large regions and is only mapped as it is needed, so some of the memory
// the allocators own is always unmapped.
u_assert!(result? > 0, "No pool memory is unmapped");

Ok(())
}

/// Confirms every pool page is mapped unless the GCD has it marked as retired, returning the number of retired pages.
fn check_pool_pages(ranges: &[Range<efi::PhysicalAddress>]) -> Result<usize, &'static str> {
let mut unmapped_pages = 0;

for range in ranges {
for page in (range.start as usize..range.end as usize).step_by(UEFI_PAGE_SIZE) {
let retired = page_attributes(page)? & efi::MEMORY_RP == efi::MEMORY_RP;
if retired == is_mapped(page as u64) {
log::error!("Pool page {page:#x} is out of sync with the GCD, GCD reports retired: {retired}");
return Err("Pool page mapping does not match the GCD");
}
unmapped_pages += usize::from(retired);
}
}

Ok(unmapped_pages)
}
9 changes: 4 additions & 5 deletions patina_dxe_core/src/core_patina_tests/test_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,11 @@ pub(super) fn get_pte_state(pte: u64, level: PageTableLevel) -> PteInfo {
}

pub(super) fn is_mapped(addr: u64) -> bool {
let mut next_addr = addr;
for &level in &[PageTableLevel::Level4, PageTableLevel::Level3, PageTableLevel::Level2, PageTableLevel::Level1] {
let pt = get_self_mapped_page_table(next_addr, level);
let idx = get_index(next_addr, level);
// The walk stays on `addr`: with a self mapped page table the table for the next level is addressed by the
// indexes of `addr`, and it is only guaranteed to be reachable once the entry above it is present.
let pt = get_self_mapped_page_table(addr, level);
let idx = get_index(addr, level);
let entry = pt.get(idx as usize).expect("Index out of bounds");
let pte_state = get_pte_state(*entry, level);
if !pte_state.present {
Expand All @@ -269,8 +270,6 @@ pub(super) fn is_mapped(addr: u64) -> bool {
// we are identity mapped
return true;
}
// continue down the page table levels
next_addr = pte_state.next_address;
}
unreachable!()
}
9 changes: 8 additions & 1 deletion patina_dxe_core/src/gcd/spin_locked_gcd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1131,7 +1131,14 @@ impl GCD {
active_attributes: bool,
) -> u64 {
if active_attributes {
descriptor.attributes
// Allocators unmap pool pages that have been fully freed back to them. In the GCD, this will create
// separate descriptors. However, for the EFI_MEMORY_MAP, we want to coalesce these descriptors as they
// are one contiguous block of this type.
if memory_type_for_handle(descriptor.image_handle).is_some() {
descriptor.attributes & !efi::MEMORY_RP
Comment thread
joschock marked this conversation as resolved.
Resolved
} else {
descriptor.attributes
}
} else {
// when we are building the EFI memory map, follow edk2 conventions as OSes will expect that.
// When using the capabilities, drop the runtime attribute and
Expand Down
55 changes: 29 additions & 26 deletions patina_dxe_core/src/gcd/spin_locked_gcd/paging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ impl<'a> PagingAllocator<'a> {
pub(crate) fn new(gcd: &'a SpinLockedGcd) -> Self {
Self { page_pool: Vec::with_capacity(PAGE_POOL_CAPACITY), gcd }
}

fn allocate_root_page(&self, allocate_type: AllocateType) -> Result<u64, EfiError> {
let attributes =
self.gcd.memory_protection_policy.apply_allocated_memory_protection_policy(0, GcdMemoryType::SystemMemory);
let mut gcd = self.gcd.memory.lock();
let root_page = gcd.allocate_memory_space(
allocate_type,
GcdMemoryType::SystemMemory,
UEFI_PAGE_SHIFT,
UEFI_PAGE_SIZE,
protocol_db::EFI_BOOT_SERVICES_DATA_ALLOCATOR_HANDLE,
None,
)?;
gcd.set_memory_space_attributes(root_page, UEFI_PAGE_SIZE, attributes)?;
Ok(root_page as u64)
}
}

impl PageAllocator for PagingAllocator<'_> {
Expand All @@ -38,8 +54,6 @@ impl PageAllocator for PagingAllocator<'_> {
}

if is_root {
// allocate 1 page
let len = 1;
// allocate under 4GB to support x86 MPServices
let addr: u64 = (SIZE_4GB - 1) as u64;

Expand All @@ -50,31 +64,16 @@ impl PageAllocator for PagingAllocator<'_> {
// an issue to allocate. However, some architectures may not have memory under 4GB, so if we fail here,
// simply retry with the normal allocation

let res = self.gcd.memory.lock().allocate_memory_space(
AllocateType::BottomUp(Some(addr as usize)),
GcdMemoryType::SystemMemory,
UEFI_PAGE_SHIFT,
uefi_pages_to_size!(len),
protocol_db::EFI_BOOT_SERVICES_DATA_ALLOCATOR_HANDLE,
None,
);
if let Ok(root_page) = res {
Ok(root_page as u64)
if let Ok(root_page) = self.allocate_root_page(AllocateType::BottomUp(Some(addr as usize))) {
Ok(root_page)
} else {
// if we failed, try again with normal allocation
log::error!(
"Failed to allocate root page for the page table page pool, retrying with normal allocation"
);

match self.gcd.memory.lock().allocate_memory_space(
DEFAULT_ALLOCATION_STRATEGY,
GcdMemoryType::SystemMemory,
UEFI_PAGE_SHIFT,
uefi_pages_to_size!(len),
protocol_db::EFI_BOOT_SERVICES_DATA_ALLOCATOR_HANDLE,
None,
) {
Ok(root_page) => Ok(root_page as u64),
match self.allocate_root_page(DEFAULT_ALLOCATION_STRATEGY) {
Ok(root_page) => Ok(root_page),
Err(e) => {
// okay we are good and dead now
panic!("Failed to allocate root page for the page table page pool: {e}");
Expand Down Expand Up @@ -351,10 +350,16 @@ impl SpinLockedGcd {
pub(crate) fn init_paging_with(&self, hob_list: &HobList, page_table: Box<dyn PatinaPageTable>) {
log::info!("Initializing paging for the GCD");

*self.page_table.lock() = Some(page_table);

// Do all memory allocation before we put the page table reference in the GCD. This ensures that when we
// grab the descriptors, any allocator expansion and setting unused pages as RP has already occurred. The
// GCD can change after this point, but not before we map the initial set of memory regions.
let mut mmio_res_descs: Vec<dxe_services::MemorySpaceDescriptor> =
Vec::with_capacity(self.memory_descriptor_count() + 10);
let mut descriptors: Vec<dxe_services::MemorySpaceDescriptor> =
Vec::with_capacity(self.memory_descriptor_count() + 10);

*self.page_table.lock() = Some(page_table);

self.memory
.lock()
.get_memory_descriptors(mmio_res_descs.as_mut(), |d, _| {
Expand All @@ -367,16 +372,14 @@ impl SpinLockedGcd {
// DXE Core, so that we can ensure that the DXE Core is mapped correctly and not overwritten by the allocated
// memory attrs. We also need to preallocate memory here so that we do not allocate memory after getting the
// descriptors
let mut descriptors: Vec<dxe_services::MemorySpaceDescriptor> =
Vec::with_capacity(self.memory_descriptor_count() + 10);
self.memory
.lock()
.get_memory_descriptors(&mut descriptors, |d, allocated| {
if d.memory_type == GcdMemoryType::MemoryMappedIo || d.memory_type == GcdMemoryType::Reserved {
// we've already handled MMIO and reserved memory, so skip these
return false;
}
allocated
allocated && d.attributes & efi::MEMORY_RP == 0
})
.expect("Failed to get allocated memory descriptors!");

Expand Down
Loading
Loading