diff --git a/Cargo.toml b/Cargo.toml index 0fbb61f357..1ae84ce620 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,7 +27,6 @@ fallible-streaming-iterator = { version = "0.1.9" } fixedbitset = { version = "0.5", default-features = false } gdbstub = { version = "0.7.10", default-features = false } goblin = { version = "0.10.7", default-features = false } -linked_list_allocator = { version = "0.10" } linkme = { version = "0.3.36" } log = { version = "0.4", default-features = false } memoffset = {version = "0.9.1" } diff --git a/docs/src/dxe_core/memory_management.md b/docs/src/dxe_core/memory_management.md index 11b8d45df2..bee5ec0eb0 100644 --- a/docs/src/dxe_core/memory_management.md +++ b/docs/src/dxe_core/memory_management.md @@ -53,16 +53,16 @@ on the [Fixed-Size Block Allocator](https://os.phil-opp.com/allocator-designs/#f presented as part of the [Writing an OS in Rust](https://os.phil-opp.com/) blog series. Each allocator tracks "free" blocks of fixed sizes that are used to satisfy allocation requests. These lists are backed -up by a linked list allocator to satisfy allocations in the event that a fixed-sized block list doesn't exist (in the -case of very large allocations) or does not have a free block. +by the GCD. This allows for a very efficient allocation procedure: 1. Round up requested allocation size to next block size. 2. Remove the first block from the corresponding "free-list" and return it. -If there are free blocks of the required size available this operation is constant-time. This should be the expected -normal case after the allocators have run for a while and have built up a set of free blocks. +If there are free blocks of the required size available this operation is constant-time (though tracking the lifecycle +requires list maintenance). This should be the expected normal case after the allocators have run for a while and have +built up a set of free blocks. Freeing a block (except for very large blocks) is also constant-time, since the procedure is the reverse of the above: @@ -76,46 +76,45 @@ reused, which increases the chance that a use-after-free accesses memory that ha 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 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. +reclaimed roughly in FIFO order. Memory claimed from the GCD starts in the retired state, so an allocator never has memory mapped that it has not -handed out. +handed out, excluding the pages that contain metadata. ```mermaid -stateDiagram-v2 - direction TB - - state "GCD-owned system memory" as GCD - state "Fallback allocator free memory
(mapped)" as Fallback - state "Fixed-size blocks
(mapped)" as FixedBlocks - state "FSB retired page
(unmapped)" as Retired - state "Direct fallback allocation
(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 +flowchart TB + GCD["GCD system memory"] + FSBFree["FSB available pages
(unmapped; metadata stays mapped)"] + FixedBlocks["Fixed-size blocks
(mapped)"] + Retired["Retired pages
(unmapped)"] + Large["Direct large allocation
(mapped)"] + Small["Small pool allocation
(mapped)"] + Medium["Medium pool allocation
(mapped page run)"] + + GCD -->|Expand| FSBFree + FSBFree -->|Carve into blocks| FixedBlocks + FixedBlocks -->|Allocate| Small + Small -->|Free| FixedBlocks + FixedBlocks -->|Last block freed| Retired + Retired -->|Reclaim| FixedBlocks + FSBFree -->|Claim contiguous pages| Medium + Retired -->|Reclaim contiguous pages| Medium + Medium -->|Free entire run| Retired + + GCD -->|Allocate| Large + Large -->|Free| GCD ``` -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. +The FSB retains ownership of retired pages even while they are unmapped. New expansion pages not needed immediately +enter the retired state directly. Metadata pages remain mapped. -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- -time, since the first block in the linked-list backing allocator is larger than all the free-list block sizes (because -blocks are only freed back to the fallback allocator if they are larger than the all free-list block sizes). This means -that allocation typically consists of simply splitting the required block off the front of the first free block in the -list. +Allocations larger than the largest fixed size block (which is 4KB) fall into one of two flows: -If the fallback linked-list allocator is _also_ not able to satisfy the request, then a new large block is fetched from -the GCD and inserted into the fallback linked-list allocator. This is a slower operation and its performance is a -function of how fragmented the GCD has become - on a typical boot this can extend to a search through hundreds of nodes. -This is a relatively rare event and the impact on overall allocator performance is negligible. +- Allocations greater than 64KB for this allocator type are directly serviced by the GCD as page allocations +- Allocations less than 64KB search retired pages for a contiguous run that is long enough for the size requested. +If one is found, that is mapped as whole pages for this and freed back to the retired pages as such. If one is not +found, an allocation is made from the GCD to add more retired pages, at the required granularity, and the required +pages are mapped and handed out. These pages are never freed back to the GCD. ### Allocation "Buckets" @@ -134,24 +133,24 @@ hibernate) where the OS assumes a stable boot-to-boot memory map. The UefiAllocator supports the following operations: -* Creating a new allocator for arbitrary memory types. A subset of well-known allocators are provided by the core to +- Creating a new allocator for arbitrary memory types. A subset of well-known allocators are provided by the core to support UEFI spec standard memory types, but the spec also allows for arbitrary OEM-defined memory types. If a caller makes an allocation request to a previously unused OEM-defined memory type, a new allocator instance is dynamically instantiated to track memory for the new memory type. -* Retrieving the `EfiMemoryType` associated with the allocator. All allocations done with this allocator instance will +- Retrieving the `EfiMemoryType` associated with the allocator. All allocations done with this allocator instance will be of this type. -* Reserving pages for the allocator. This is used to seed the allocator with an initial [bucket](memory_management.md#allocation-buckets) +- Reserving pages for the allocator. This is used to seed the allocator with an initial [bucket](memory_management.md#allocation-buckets) of memory. -* APIs for allocate and free operations of arbitrary sizes, including `impl` for [`Allocator`](https://doc.rust-lang.org/std/alloc/trait.Allocator.html) +- APIs for allocate and free operations of arbitrary sizes, including `impl` for [`Allocator`](https://doc.rust-lang.org/std/alloc/trait.Allocator.html) and [`GlobalAlloc`](https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html) traits. See [Rust `Allocator` and `GlobalAlloc` Implementations](memory_management.md#rust-allocator-and-globalalloc-implementations) below. -* APIs for allocating and freeing pages (as distinct from arbitrary sizes). These are pass-throughs to the +- APIs for allocating and freeing pages (as distinct from arbitrary sizes). These are pass-throughs to the underlying [GCD operations](memory_management.md#gcd-operations) with some logic to handle preserving ownership for allocation buckets. -* Expanding the allocator by making a call to the GCD to acquire more memory if the allocator does not have enough +- Expanding the allocator by making a call to the GCD to acquire more memory if the allocator does not have enough memory to satisfy a request. -* Locking the allocator to support exclusive access for allocation (see [Concurrency](memory_management.md#concurrency)). +- Locking the allocator to support exclusive access for allocation (see [Concurrency](memory_management.md#concurrency)). ## Global Coherency Domain (GCD) @@ -193,17 +192,17 @@ SystemMem 0000000080003000-0000000081805fff 800000000002700f 0000000000002008 0 The GCD supports the following operations: -* Adding, Removing, and Allocating and Freeing regions within the address space. The semantics for these operations +- Adding, Removing, and Allocating and Freeing regions within the address space. The semantics for these operations largely follow the Platform Initialization spec [APIs](https://uefi.org/specs/PI/1.9/V2_Services_DXE_Services.html#gcd-memory-resources) for manipulating address spaces. -* Configuring the capabilities and attributes of the memory space. The GCD uses CPU memory management hardware to +- Configuring the capabilities and attributes of the memory space. The GCD uses CPU memory management hardware to enforce these attributes where supported. See [Paging](cpu.md#paging-implementation) for details on how this hardware is configured. -* Retrieving the current address space map as a list of descriptors containing details about each memory region. -* Locking the memory space to disallow modifications to the GCD. This allows the GCD to be protected in certain +- Retrieving the current address space map as a list of descriptors containing details about each memory region. +- Locking the memory space to disallow modifications to the GCD. This allows the GCD to be protected in certain sensitive scenarios (such as during [Exit Boot Services](memory_management.md#exit-boot-services-handlers)) where modifications to the GCD are not permitted. -* Obtaining a locked instance of the GCD instance to allow for concurrency-safe modification of the memory map. (see +- Obtaining a locked instance of the GCD instance to allow for concurrency-safe modification of the memory map. (see [Concurrency](memory_management.md#concurrency)). The internal GCD implementation will ensure that a consistent map is maintained as various operations are performed to @@ -424,15 +423,15 @@ what bootloaders are) that does not have the NX_COMPAT DLL Characteristic set in Entering Compatibility Mode causes the following to occur: -* Map all memory in the legacy BIOS write back range (0x0 - 0xA000) as RWX if it is part of system memory. This is done +- Map all memory in the legacy BIOS write back range (0x0 - 0xA000) as RWX if it is part of system memory. This is done as Linux both can have null pointer dereferences and attempts to access structures in that range. -* Map all newly allocated pages as RWX. This is done as non-NX_COMPAT bootloaders will attempt to allocate pages and +- Map all newly allocated pages as RWX. This is done as non-NX_COMPAT bootloaders will attempt to allocate pages and execute from them without updating attributes. -* Map the current image that triggered Compatibility Mode as RWX. This is done as Linux will try to execute out of data +- Map the current image that triggered Compatibility Mode as RWX. This is done as Linux will try to execute out of data regions. -* Map all memory owned by the `EFI_LOADER_CODE` and `EFI_LOADER_DATA` `UefiAllocators` as RWX. This supports Linux +- Map all memory owned by the `EFI_LOADER_CODE` and `EFI_LOADER_DATA` `UefiAllocators` as RWX. This supports Linux allocating pool memory and attempting to execute from it. -* The `EFI_MEMORY_ATTRIBUTE_PROTOCOL` is uninstalled. This is done because versions of Linux bootloaders in the wild +- The `EFI_MEMORY_ATTRIBUTE_PROTOCOL` is uninstalled. This is done because versions of Linux bootloaders in the wild will use the protocol to map their entire image as non-executable, then attempt to map each section as executable, but the subsequent calls aren't page aligned, causing the protocol to return an error, which is unchecked. The bootloader then attempts to execute out of non-executable memory and crashes. diff --git a/patina_dxe_core/Cargo.toml b/patina_dxe_core/Cargo.toml index 173815a791..a14105d8d0 100644 --- a/patina_dxe_core/Cargo.toml +++ b/patina_dxe_core/Cargo.toml @@ -16,7 +16,6 @@ workspace = true bitfield-struct = { workspace = true } cfg-if = { workspace = true } goblin = { workspace = true, features = ["pe32", "pe64", "te"] } -linked_list_allocator = { workspace = true } log = { workspace = true } patina_paging = { workspace = true } rustversion = { workspace = true } diff --git a/patina_dxe_core/src/allocator.rs b/patina_dxe_core/src/allocator.rs index dc670a15fb..6c20b3760e 100644 --- a/patina_dxe_core/src/allocator.rs +++ b/patina_dxe_core/src/allocator.rs @@ -110,6 +110,9 @@ pub struct AllocationStatistics { /// The number of calls to `alloc()`. pub pool_allocation_calls: usize, + /// The number of pool allocation requests larger than, or more aligned than, the largest fixed block. + pub large_pool_allocation_calls: usize, + /// The number of calls to `dealloc()`. pub pool_free_calls: usize, @@ -139,6 +142,7 @@ impl AllocationStatistics { const fn new() -> Self { Self { pool_allocation_calls: 0, + large_pool_allocation_calls: 0, pool_free_calls: 0, page_allocation_calls: 0, page_free_calls: 0, @@ -177,9 +181,6 @@ pub trait PageAllocator { /// Returns an iterator over the memory ranges managed by this allocator. fn get_memory_ranges(&self) -> alloc::vec::IntoIter>; - /// Indicates whether the given pointer falls within a memory region managed by this allocator. - fn contains(&self, ptr: NonNull) -> bool; - /// Returns the allocator handle associated with this allocator. fn handle(&self) -> efi::Handle; @@ -2236,28 +2237,6 @@ mod tests { }); } - // This test uses an allocation request size of 0x2b2fa0 to test a specific edge case. - // - // When core_allocate_pool attempts to allocate 0x2b2fa0 bytes (aligned to 0x2b2fb8 bytes), the allocation - // will initially fail and trigger a fallback to fallback_alloc, which requests 0x2b2ff8 bytes of additional - // memory. The GCD then allocates memory with a page-aligned size of 0x2b3000 bytes. Following this, the system - // calls expand() to add the newly allocated heap, which ends up being 0x2b2fc0 bytes in size. However, the - // difference between the heap size (0x2b2fc0) and the expected memory size (0x2b2fb8) is only 8 bytes. This - // small gap is insufficient to accommodate the metadata required by HoleList::new() from the - // linked_list_allocator crate, which expects extra space for internal bookkeeping structures. - // - // This test ensures that the linked list hole list structure is accounted for correctly and that the allocation - // succeeds without panicking due to insufficient space. For this particular test, the failing additional memory - // size returned was 0x2b3000 bytes (panic) whereas now 0x2b3010 bytes is returned to account for the HoleList - // metadata. - #[test] - fn linked_list_hole_list_struct_should_be_accounted_for() { - with_locked_state(GcdInit::WithSize(0x4000000), |_physical_hob_list| { - let ptr = core_allocate_pool(efi::BOOT_SERVICES_DATA, 0x2B2FA0).unwrap(); - assert!(!ptr.is_null()); - }); - } - #[test] fn allocate_pool_should_allocate_pool() { with_locked_state(GcdInit::WithSize(0x1000000), |_physical_hob_list| { @@ -2336,6 +2315,7 @@ mod tests { assert!(!buffer_ptr.is_null()); assert!(allocator.get_memory_ranges().next().is_some()); assert!(allocator.free_pool(buffer_ptr).is_ok()); + assert!(allocator.get_memory_ranges().next().is_some()); } }); } @@ -2357,6 +2337,7 @@ mod tests { let _alloc_trait: &dyn core::alloc::Allocator = allocator; assert!(allocator.free_pool(buffer_ptr).is_ok()); + assert!(allocator.get_memory_ranges().next().is_some()); } }); } @@ -2378,6 +2359,7 @@ mod tests { let _alloc_trait: &dyn core::alloc::Allocator = allocator; assert!(allocator.free_pool(buffer_ptr).is_ok()); + assert!(allocator.get_memory_ranges().next().is_some()); } }); } diff --git a/patina_dxe_core/src/allocator/fixed_size_block_allocator.rs b/patina_dxe_core/src/allocator/fixed_size_block_allocator.rs index b5cb37b208..299c80044d 100644 --- a/patina_dxe_core/src/allocator/fixed_size_block_allocator.rs +++ b/patina_dxe_core/src/allocator/fixed_size_block_allocator.rs @@ -1,6 +1,6 @@ //! Fixed-sized block allocator. //! -//! Implements a fixed-sized block allocator backed by a linked list allocator. Based on the example fixed-sized block +//! Implements a fixed-sized block allocator backed by pages from the GCD. Based on the example fixed-sized block //! allocator presented here: . //! //! ## License @@ -22,18 +22,17 @@ use core::{ debug_assert, fmt::{self, Display}, mem::{align_of, size_of}, + num::NonZeroUsize, ops::Range, ptr::{NonNull, slice_from_raw_parts_mut}, result::Result, - sync::atomic::{AtomicBool, Ordering}, }; -use linked_list_allocator::{align_down_size, align_up_size}; use patina::standard::efi; use patina::{ error::EfiError, pi::dxe_services::GcdMemoryType, - uefi_pages_to_size, uefi_size_to_pages, writelncrlf, - {UEFI_PAGE_SHIFT, UEFI_PAGE_SIZE, align_up, page_shift_from_alignment}, + signature, uefi_pages_to_size, uefi_size_to_pages, writelncrlf, + {UEFI_PAGE_MASK, UEFI_PAGE_SHIFT, UEFI_PAGE_SIZE, align_up, page_shift_from_alignment}, }; /// Type for describing errors that this implementation can produce. @@ -41,24 +40,47 @@ use patina::{ pub enum FixedSizeBlockAllocatorError { /// Could not satisfy allocation request, and expansion failed. /// - /// Specifies how much additional memory is required to be added to the allocator through - /// [`FixedSizeBlockAllocator::expand()`] in order to fulfill the attempted allocation. + /// Could not satisfy the request from the fixed-size block lists. + /// + /// Contains the required payload size in bytes: either a fixed-block size or + /// a page-rounded medium-allocation size. The caller should attempt to reclaim + /// retired pages or expand the allocator to fulfill the request. OutOfMemory(usize), - /// The provided layout was invalid. - InvalidLayout, /// The memory region provided to extend the allocator was invalid. InvalidExpansion, /// An internal error occurred. InternalError, + /// The allocation exceeds the retained pool size or alignment limit. + ExceedsBlockSize, } -const ALIGNMENT: usize = 0x1000; +// List of fixed block sizes supported by the allocator +const BLOCK_SIZES: &[usize] = &[8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; + +// Largest allocation size we will serve from retired pages instead of going directly to the GCD +const MAX_RETAINED_POOL_SIZE: usize = patina::SIZE_64KB; + +// Returns the size we must pull from retired pages to satisfy the given layout, if it is within the +// retained pool size limit. +fn retained_pool_size(layout: Layout) -> Option { + if max(layout.size(), layout.align()) > MAX_RETAINED_POOL_SIZE { + return None; + } + align_up(layout.size().max(1), UEFI_PAGE_SIZE).ok() +} -// The block sizes that the fixed-size block allocator will manage. 16 bytes is the smallest size due to the -// restriction of the fallback allocator that hands out the backing memory for these blocks. That allocator -// has 16 bytes of metadata it stores in free regions and so at a minimum can hand out that size of memory, in -// order for us to keep track of how many free bytes are available in each page. -const BLOCK_SIZES: &[usize] = &[16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; +// Slice::get() is not const on stable Rust +#[allow(clippy::indexing_slicing)] +const fn block_sizes_divide_alignment() -> bool { + let mut index = 0; + while index < BLOCK_SIZES.len() { + if !UEFI_PAGE_SIZE.is_multiple_of(BLOCK_SIZES[index]) { + return false; + } + index += 1; + } + true +} // Returns the index in the block list for the minimum size block that will // satisfy allocation for the given layout @@ -71,12 +93,34 @@ struct BlockListNode { next: Option>, } +const _: () = assert!(size_of::() <= 8 && align_of::() <= 8); + +const LARGE_ALLOCATION_NODE_SIGNATURE: u64 = signature!('B', 'I', 'G', 'A', 'L', 'L', 'C'); + +struct LargeAllocationNode { + signature: u64, + base: usize, + size: usize, +} + +impl LargeAllocationNode { + fn allocation_size(layout: Layout, granularity: usize) -> Option { + let user_alignment = max(layout.align(), max(8, align_of::())); + layout + .size() + .checked_add(size_of::()) + .and_then(|size| size.checked_add(user_alignment - 1)) + .and_then(|size| align_up(size, granularity).ok()) + } +} + struct AllocatorListNode { next: Option<*mut AllocatorListNode>, - allocator: linked_list_allocator::Heap, + /// Size in bytes of the entire region, including the metadata header. + region_size: usize, /// The number of bytes of each whole page in this region that are currently sitting on the fixed-size block free - /// lists, along with the [`AllocatorListNode::RETIRED_PAGE`] and [`AllocatorListNode::RETIRING_PAGE`] states. + /// lists, along with the retired and retiring page states. /// /// This is stored in the metadata header at the front of the region for every page in the region. Pages containing /// metadata are never retired so that the metadata remains accessible. @@ -84,8 +128,24 @@ struct AllocatorListNode { } const _: () = assert!(AllocatorListNode::RETIRED_PAGE < AllocatorListNode::RETIRING_PAGE); +const _: () = assert!(UEFI_PAGE_SIZE.is_multiple_of(align_of::())); impl AllocatorListNode { + // Returns the total allocation size required for a free region of at least `usable_size` bytes, taking into account + // the minimum expansion and alignment granularity. This includes the size of the allocator node and page metadata. + fn allocation_size(usable_size: usize, min_expansion: usize, granularity: usize) -> Option { + let mut size = align_up(max(usable_size, min_expansion), granularity).ok()?; + loop { + let metadata_size = align_up(Self::size_for_free_region(size), UEFI_PAGE_SIZE).ok()?; + let required_size = max(min_expansion, usable_size.checked_add(metadata_size)?); + let next_size = align_up(required_size, granularity).ok()?; + if next_size == size { + return Some(size); + } + size = next_size; + } + } + // This flag is used to indicate that a page has been retired and is no longer in use by the allocator. // It represents the free bytes in a page. When the free bytes are equal to the page size, the entire page // is free and therefore retired. It contrasts with RETIRING_PAGE, which is greater than the page size and used @@ -98,11 +158,33 @@ impl AllocatorListNode { // the page is not in use, which would be represented by 0 <= free_bytes <= RETIRED_PAGE. const RETIRING_PAGE: u16 = u16::MAX; + /// Returns the size of the allocator node and page metadata required to describe `free_region_size` bytes. + fn size_for_free_region(free_region_size: usize) -> usize { + let page_count = uefi_size_to_pages!(free_region_size); + Layout::new::() + .extend(Layout::array::(page_count).expect("Failed to create layout for page metadata")) + .expect("Arithmetic error in allocator node layout") + .0 + .pad_to_align() + .size() + } + /// Returns the base address of the region containing this node and its page metadata. fn region_base(&self) -> usize { core::ptr::from_ref(self).addr() } + /// Returns the base address of the first whole page after the metadata header. + fn first_page_base(&self) -> usize { + align_up(self.region_base() + self.header_size(), UEFI_PAGE_SIZE) + .expect("Heap regions should not be at the end of memory") + } + + /// Returns the size in bytes of the metadata header + fn header_size(&self) -> usize { + Self::size_for_free_region(self.region_size) + } + /// Returns the index into `page_free_bytes` of the tracked page containing `address`, if any. fn page_index(&self, address: usize) -> Option { let index = address.checked_sub(self.region_base())? >> UEFI_PAGE_SHIFT; @@ -117,42 +199,6 @@ impl AllocatorListNode { } } -/// Describes the header that [`FixedSizeBlockAllocator::expand`] reserves at the front of an expansion region. -struct RegionHeader { - /// The total size of the header. The backing heap for the region starts immediately after it. - size: usize, - /// The offset of the per-page metadata array within the region. - meta_offset: usize, - /// The number of pages contained in the region, including the pages that contain the metadata. - page_count: usize, -} - -impl RegionHeader { - fn new(page_count: usize) -> Option { - let (layout, meta_offset) = - Layout::new::().extend(Layout::array::(page_count).ok()?).ok()?; - - Some(Self { size: layout.pad_to_align().size(), meta_offset, page_count }) - } - - /// Returns the page-aligned region size needed to hold `payload_size` bytes after the region header. - fn region_size_for_payload(payload_size: usize) -> Option { - let mut page_count = 1; - - loop { - let header = Self::new(page_count)?; - let region_size = align_up(payload_size.checked_add(header.size)?, UEFI_PAGE_SIZE).ok()?; - let required_page_count = region_size / UEFI_PAGE_SIZE; - - if required_page_count == page_count { - return Some(region_size); - } - - page_count = required_page_count; - } - } -} - struct AllocatorIterator { current: Option<*mut AllocatorListNode>, } @@ -178,10 +224,9 @@ impl Iterator for AllocatorIterator { /// Fixed Size Block Allocator /// -/// Implements an expandable memory allocator using fixed-sized blocks for speed backed by a linked-list allocator -/// implementation when an appropriate sized free block is not available. If more memory is required than can be -/// satisfied by either the block list or the linked-list, more memory is is allocated externally, then passed into -/// the allocator where a new backing linked-list is created. +/// Uses fixed-size blocks through one page and contiguous page runs for pool layouts with size and alignment +/// through 64KB. Free whole pages remain owned by the allocator but are retired and unmapped until needed again. +/// Larger layouts are allocated directly from the GCD by [`SpinLockedFixedSizeBlockAllocator`]. /// pub struct FixedSizeBlockAllocator { /// The memory type this allocator manages. @@ -195,13 +240,9 @@ pub struct FixedSizeBlockAllocator { /// recycled in FIFO order, which maximizes the time between a block being freed and it being handed out again. list_tails: [Option>; BLOCK_SIZES.len()], - /// The linked-list of allocators that this allocator uses to back allocations that are larger than the fixed-size - /// blocks or if the required fixed-size block list is empty. + /// The backing regions and permanently mapped metadata used to track pool pages. allocators: Option<*mut AllocatorListNode>, - /// Most recently used allocator node for per-page accounting. - page_accounting_node: Option>, - /// Allocator node and page index where the next retired-page search begins. This is maintained to reclaim pages /// in FIFO order, maximizing the time between a page being freed and it being reclaimed. retired_page_cursor: Option<(NonNull, usize)>, @@ -228,7 +269,6 @@ impl FixedSizeBlockAllocator { list_heads: [EMPTY; BLOCK_SIZES.len()], list_tails: [EMPTY; BLOCK_SIZES.len()], allocators: None, - page_accounting_node: None, retired_page_cursor: None, reserved_range: None, stats: AllocationStatistics::new(), @@ -244,7 +284,6 @@ impl FixedSizeBlockAllocator { self.list_heads = [EMPTY; BLOCK_SIZES.len()]; self.list_tails = [EMPTY; BLOCK_SIZES.len()]; self.allocators = None; - self.page_accounting_node = None; self.retired_page_cursor = None; self.reserved_range = None; self.stats = AllocationStatistics::new(); @@ -252,75 +291,65 @@ impl FixedSizeBlockAllocator { /// Expand the memory available to this allocator with a new contiguous region of memory, setting up a new allocator /// node to manage this range. The region is partially consumed by an `AllocatorListNode` and the per-page tracking - /// metadata for the region; the remainder is available to the allocator. + /// metadata for the region; only whole pages after the metadata are available to the allocator. /// /// Every whole page of the new region after the metadata starts retired, so the allocator does not have any memory /// mapped that it has not handed out yet. This function returns `Ok(Some(Range))` if the expansion contains any /// whole pages that must be unmapped. If the returned range cannot be mapped, it must be handed to - /// [`Self::restore_pages`]. If the expansion only contains metadata pages, `Ok(None)` is returned and the caller - /// does not need to unmap any pages. + /// [`Self::restore_pages`]. /// /// ## Errors /// - /// Returns [`FixedSizeBlockAllocatorError::InvalidExpansion`] if the new region is not larger than and aligned to - /// `AllocatorListNode`. + /// Returns [`FixedSizeBlockAllocatorError::InvalidExpansion`] if the new region is not page aligned or does not + /// contain at least one whole page after the metadata. /// Returns [`FixedSizeBlockAllocatorError::InternalError`] if the whole pages in the new region cannot be reserved /// from its backing allocator. - pub fn expand( + fn expand( &mut self, new_region: NonNull<[u8]>, ) -> core::result::Result>, FixedSizeBlockAllocatorError> { // Interpret the first part of the provided region as an AllocatorListNode let alloc_node_ptr = new_region.as_ptr().cast::(); - if !alloc_node_ptr.addr().is_multiple_of(UEFI_PAGE_SIZE) { + if !alloc_node_ptr.addr().is_multiple_of(UEFI_PAGE_SIZE) || !new_region.len().is_multiple_of(UEFI_PAGE_SIZE) { debug_assert!(false, "FSB expanded with memory region that is not page aligned."); return Err(FixedSizeBlockAllocatorError::InvalidExpansion); } // Only whole pages contained within the region are tracked for retirement. - let header = RegionHeader::new(uefi_size_to_pages!(new_region.len())).ok_or_else(|| { - debug_assert!(false, "FSB expanded with insufficiently sized memory region."); - FixedSizeBlockAllocatorError::InvalidExpansion - })?; + let page_count = uefi_size_to_pages!(new_region.len()); + let node_size = AllocatorListNode::size_for_free_region(new_region.len()); // Ensure we're expanding enough to fit the node and its page metadata - if new_region.len() <= header.size { + if new_region.len() <= node_size { debug_assert!(false, "FSB expanded with insufficiently sized memory region."); return Err(FixedSizeBlockAllocatorError::InvalidExpansion); } - // SAFETY: the header lies within the region, which was validated to be large enough above, and meta_offset is - // aligned for the page metadata by Layout::extend. + if page_count <= uefi_size_to_pages!(node_size) { + return Err(FixedSizeBlockAllocatorError::InvalidExpansion); + } + + // SAFETY: the metadata lies within the region, which was validated to be large enough above. The size of + // AllocatorListNode includes its alignment padding and u16 has no stricter alignment requirement. let page_free_bytes = unsafe { - let meta_ptr = new_region.as_ptr().cast::().add(header.meta_offset).cast::(); - for index in 0..header.page_count { + let meta_ptr = new_region.as_ptr().cast::().add(size_of::()).cast::(); + for index in 0..page_count { meta_ptr.add(index).write(0); } - core::slice::from_raw_parts_mut(meta_ptr, header.page_count) + core::slice::from_raw_parts_mut(meta_ptr, page_count) }; - let heap_region: NonNull<[u8]> = NonNull::slice_from_raw_parts( - // SAFETY: header.size is less than the region length, as validated above. - NonNull::new(unsafe { new_region.as_ptr().cast::().add(header.size) }).ok_or_else(|| { - debug_assert!(false, "FSB expanded with insufficiently sized memory region."); - FixedSizeBlockAllocatorError::InvalidExpansion - })?, - new_region.len() - header.size, - ); - //write the allocator node structure into the start of the range, initialize its heap with the remainder of //the range, and add the new allocator to the front of the allocator list. - let node = AllocatorListNode { next: None, allocator: linked_list_allocator::Heap::empty(), page_free_bytes }; + let node = AllocatorListNode { next: None, region_size: new_region.len(), page_free_bytes }; // SAFETY: alloc_node_ptr is aligned and points to valid writable memory for an AllocatorListNode. unsafe { alloc_node_ptr.write(node); - (*alloc_node_ptr).allocator.init(heap_region.cast::().as_ptr(), heap_region.len()); (*alloc_node_ptr).next = self.allocators; } self.allocators = Some(alloc_node_ptr); - self.page_accounting_node = NonNull::new(alloc_node_ptr); if self.retired_page_cursor.is_none() { self.retired_page_cursor = NonNull::new(alloc_node_ptr).map(|node| (node, 0)); } @@ -343,20 +372,23 @@ impl FixedSizeBlockAllocator { node: *mut AllocatorListNode, ) -> Result>, FixedSizeBlockAllocatorError> { // SAFETY: node was just written by expand() and its heap has been initialized. - let (heap_start, heap_end) = unsafe { ((*node).allocator.bottom() as usize, (*node).allocator.top() as usize) }; + let heap_start = unsafe { (*node).first_page_base() }; + // SAFETY: node points to the start of its region, and region_size was initialized from that region's length. + let heap_end = unsafe { node.cast::().add((*node).region_size) as usize }; + + if (heap_start & UEFI_PAGE_MASK) != 0 || (heap_end & UEFI_PAGE_MASK) != 0 { + debug_assert!(heap_start & UEFI_PAGE_MASK == 0, "Heap start is not aligned to UEFI_PAGE_SIZE."); + debug_assert!(heap_end & UEFI_PAGE_MASK == 0, "Heap end is not aligned to UEFI_PAGE_SIZE."); + return Err(FixedSizeBlockAllocatorError::InternalError); + } - let pages = align_up_size(heap_start, UEFI_PAGE_SIZE)..align_down_size(heap_end, UEFI_PAGE_SIZE); + let pages = heap_start..heap_end; if pages.is_empty() { - // The region contains no whole heap pages after its metadata, but its partial page remains usable. return Ok(None); } - let layout = Layout::from_size_align(pages.len(), UEFI_PAGE_SIZE) - .map_err(|_| FixedSizeBlockAllocatorError::InternalError)?; - // SAFETY: node is valid and its heap covers all of the whole pages in the region. unsafe { - (*node).allocator.allocate_first_fit(layout).map_err(|()| FixedSizeBlockAllocatorError::InternalError)?; for page_base in pages.clone().step_by(UEFI_PAGE_SIZE) { if let Some((_, free_bytes)) = (*node).page_free_bytes_mut(page_base) { *free_bytes = AllocatorListNode::RETIRING_PAGE; @@ -369,32 +401,6 @@ impl FixedSizeBlockAllocator { Ok(Some(pages)) } - // allocates from the linked-list backing allocator if a free block of the - // appropriate size is not available. - fn fallback_alloc(&mut self, layout: Layout) -> Result, FixedSizeBlockAllocatorError> { - for node in AllocatorIterator::new(self.allocators) { - // SAFETY: node is a valid allocator list node pointer from the iterator. - let allocator = unsafe { &mut (*node).allocator }; - if let Ok(ptr) = allocator.allocate_first_fit(layout) { - return Ok(NonNull::slice_from_raw_parts(ptr, layout.size())); - } - } - - // Determine how much additional memory is required - // - // Per the `linked_list_allocator::hole::HoleList::new` documentation, depending on the alignment of the - // hole_addr pointer, the minimum size for storing required metadata is between 2 * size_of:: and - // 3 * size_of::. The size reservation for `additional_mem_required` assumed the largest size. - let allocation_size = layout.pad_to_align().size() + 3 * size_of::(); - - let additional_mem_required = RegionHeader::region_size_for_payload(allocation_size).ok_or_else(|| { - debug_assert!(false, "FSB expanded with insufficiently sized memory region."); - FixedSizeBlockAllocatorError::InvalidExpansion - })?; - - Err(FixedSizeBlockAllocatorError::OutOfMemory(additional_mem_required)) - } - /// Allocates and returns a pointer to a memory buffer for the given layout. /// /// @@ -404,10 +410,12 @@ impl FixedSizeBlockAllocator { /// ## Errors /// /// Returns [`FixedSizeBlockAllocatorError::OutOfMemory`] when the allocator doesn't have enough memory. - /// Returns [`FixedSizeBlockAllocatorError::InvalidLayout`] when the layout provided is invalid. /// Returns [`FixedSizeBlockAllocatorError::InternalError`] when an internal error occurs. pub fn alloc(&mut self, layout: Layout) -> Result, FixedSizeBlockAllocatorError> { self.stats.pool_allocation_calls += 1; + if list_index(&layout).is_none() { + self.stats.large_pool_allocation_calls += 1; + } self.internal_alloc(layout) } @@ -429,53 +437,40 @@ impl FixedSizeBlockAllocator { self.track_block_allocated(ptr.addr().get(), block_size); Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) } else { - // no block exists in list => allocate new block + // no block exists in list => return OOM so caller can allocate new block from + // available pages (if any) let block_size = *BLOCK_SIZES.get(index).ok_or(FixedSizeBlockAllocatorError::InternalError)?; - // only works if all block sizes are a power of 2 - let block_align = block_size; - let layout = match Layout::from_size_align(block_size, block_align) { - Ok(layout) => layout, - Err(_) => return Err(FixedSizeBlockAllocatorError::InvalidLayout), - }; - self.fallback_alloc(layout) + Err(FixedSizeBlockAllocatorError::OutOfMemory(block_size)) } } - None => self.fallback_alloc(layout), + None => match retained_pool_size(layout) { + Some(size) => Err(FixedSizeBlockAllocatorError::OutOfMemory(size)), + None => Err(FixedSizeBlockAllocatorError::ExceedsBlockSize), + }, } } - // deallocates back to the linked-list backing allocator if the size of - // layout being freed is too big to be tracked as a fixed-size free block. - fn fallback_dealloc(&mut self, ptr: NonNull, layout: Layout) { - for node in AllocatorIterator::new(self.allocators) { - // SAFETY: node is produced by AllocatorIterator and points to a valid AllocatorListNode. - let allocator = unsafe { &mut (*node).allocator }; - if (allocator.bottom() <= ptr.as_ptr()) && (ptr.as_ptr() < allocator.top()) { - // SAFETY: ptr was allocated by this allocator for the given layout. - unsafe { allocator.deallocate(ptr, layout) }; - return; - } + fn allocate_from_pages( + &mut self, + layout: Layout, + pages: Range, + ) -> Result, FixedSizeBlockAllocatorError> { + if let Some(index) = list_index(&layout) { + let block_size = *BLOCK_SIZES.get(index).ok_or(FixedSizeBlockAllocatorError::InternalError)?; + self.add_page_to_fsb(pages.start, block_size)?; + self.internal_alloc(layout) + } else { + let ptr = NonNull::new(pages.start as *mut u8).ok_or(FixedSizeBlockAllocatorError::InternalError)?; + Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) } } - /// Deallocates a buffer allocated by [`Self::alloc`]. - /// - /// Returns the base address of a page that was fully returned to the free lists and has been retired. The caller - /// must unmap that page, or return it to circulation with [`Self::restore_page`] if it cannot be unmapped. - /// - /// ## Safety - /// - /// Caller must ensure that `ptr` was created by a call to [`Self::alloc`] with the same `layout`. - pub unsafe fn dealloc(&mut self, ptr: NonNull, layout: Layout) -> Option { - self.stats.pool_free_calls += 1; - - let Some(index) = list_index(&layout) else { - self.fallback_dealloc(ptr, layout); - return None; - }; - - let block_size = *BLOCK_SIZES.get(index).expect("list_index guarantees valid index"); - + fn add_blocks_to_fsb( + &mut self, + ptr: NonNull, + block_size: usize, + count: usize, + ) -> Result<(), FixedSizeBlockAllocatorError> { // Make sure we have a large enough block to write the BlockListNode into it. If we don't, // we have corruption of our data structures and we need to ignore this region. if size_of::() > block_size || align_of::() > block_size { @@ -483,44 +478,84 @@ impl FixedSizeBlockAllocator { (size_of::() <= block_size && align_of::() <= block_size), "FSB deallocating block too small to store BlockListNode." ); - return None; + return Err(FixedSizeBlockAllocatorError::InternalError); } - let new_node = ptr.cast::(); - // SAFETY: new_node points to memory returned by alloc for this layout, which is large enough and - // aligned for a BlockListNode as asserted above. - unsafe { new_node.as_ptr().write(BlockListNode { next: None }) }; - - // Append to the tail so that blocks are recycled in FIFO order. - match self.list_tails.get(index).copied().expect("list_index guarantees valid index") { - // SAFETY: tail is a node on this free list, so the page containing it is mapped. - Some(tail) => unsafe { (*tail.as_ptr()).next = Some(new_node) }, - None => { - let _ = self.list_heads.get_mut(index).expect("list_index guarantees valid index").replace(new_node); + for i in 0..count { + // SAFETY: the caller-provided span contains count blocks of block_size bytes. + let offset_ptr = unsafe { NonNull::new_unchecked(ptr.as_ptr().add(i * block_size)) }; + let new_node = offset_ptr.cast::(); + // SAFETY: new_node points to memory returned by alloc for this layout, which is large enough and + // aligned for a BlockListNode as asserted above. + unsafe { new_node.as_ptr().write(BlockListNode { next: None }) }; + + let index = + BLOCK_SIZES.iter().position(|&s| s == block_size).ok_or(FixedSizeBlockAllocatorError::InternalError)?; + + // Append to the tail so that blocks are recycled in FIFO order. + match self.list_tails.get(index).copied().expect("list_index guarantees valid index") { + // SAFETY: tail is a node on this free list, so the page containing it is mapped. + Some(tail) => unsafe { (*tail.as_ptr()).next = Some(new_node) }, + None => { + let _ = + self.list_heads.get_mut(index).expect("list_index guarantees valid index").replace(new_node); + } } + *self.list_tails.get_mut(index).expect("list_index guarantees valid index") = Some(new_node); } - *self.list_tails.get_mut(index).expect("list_index guarantees valid index") = Some(new_node); + + Ok(()) + } + + /// Records fixed-size blocks added to a page without applying deallocation or retirement semantics. + fn track_blocks_added(&mut self, address: usize, footprint: usize) -> Result<(), FixedSizeBlockAllocatorError> { + let node = self.node_for_address(address).ok_or(FixedSizeBlockAllocatorError::InternalError)?; + + // SAFETY: node_for_address returned a valid node that tracks the page containing `address`. + let (_, free_bytes) = unsafe { + (*node.as_ptr()).page_free_bytes_mut(address).ok_or(FixedSizeBlockAllocatorError::InternalError)? + }; + *free_bytes = free_bytes + .checked_add(footprint as u16) + .filter(|free| *free <= AllocatorListNode::RETIRED_PAGE) + .ok_or(FixedSizeBlockAllocatorError::InternalError)?; + + Ok(()) + } + + /// Splits a mapped page into fixed-size blocks and makes them available for allocation. + fn add_page_to_fsb(&mut self, page_base: usize, block_size: usize) -> Result<(), FixedSizeBlockAllocatorError> { + let page_ptr = NonNull::new(page_base as *mut u8).ok_or(FixedSizeBlockAllocatorError::InternalError)?; + self.add_blocks_to_fsb(page_ptr, block_size, UEFI_PAGE_SIZE / block_size)?; + self.track_blocks_added(page_base, UEFI_PAGE_SIZE) + } + + /// Deallocates a buffer allocated by [`Self::alloc`]. + /// + /// Returns the base address of a page that was fully returned to the free lists and has been retired. The caller + /// must unmap that page, or return it to circulation with [`Self::restore_page`] if it cannot be unmapped. + /// + /// ## Safety + /// + /// Caller must ensure that `ptr` was created by a call to [`Self::alloc`] with the same `index`. + pub unsafe fn dealloc(&mut self, ptr: NonNull, index: usize) -> Option { + self.stats.pool_free_calls += 1; + + let block_size = *BLOCK_SIZES.get(index).expect("dealloc caller guarantees valid index"); + + self.add_blocks_to_fsb(ptr, block_size, 1).ok()?; self.track_block_freed(ptr.addr().get(), block_size) } /// Returns the region node that tracks the page containing `address`, if any. - fn node_for_address(&mut self, address: usize) -> Option> { - if let Some(node) = self.page_accounting_node { - // SAFETY: allocator nodes remain valid for the lifetime of the allocator. - if unsafe { (*node.as_ptr()).page_index(address).is_some() } { - return Some(node); - } - } - - let node = AllocatorIterator::new(self.allocators) + fn node_for_address(&self, address: usize) -> Option> { + AllocatorIterator::new(self.allocators) .find(|&node| { // SAFETY: node is produced by AllocatorIterator and points to a valid AllocatorListNode. unsafe { (*node).page_index(address).is_some() } }) - .and_then(NonNull::new); - self.page_accounting_node = node; - node + .and_then(NonNull::new) } /// Records that a fixed-size block was taken off of the free lists. @@ -640,6 +675,10 @@ impl FixedSizeBlockAllocator { // exist a suitable run, None is returned. This function uses the retired_page_cursor to maintain FIFO order of // page reclamation. fn find_retired_pages(&mut self, count: usize) -> Option> { + self.find_aligned_retired_pages(count, UEFI_PAGE_SIZE) + } + + fn find_aligned_retired_pages(&mut self, count: usize, alignment: usize) -> Option> { if count == 0 { return None; } @@ -655,20 +694,26 @@ impl FixedSizeBlockAllocator { let current_ref = unsafe { current.as_ref() }; let begin = if !wrapped && current == start_node { start_index.min(current_ref.page_free_bytes.len()) } else { 0 }; - let end = if wrapped && current == start_node { + let candidate_end = if wrapped && current == start_node { start_index.min(current_ref.page_free_bytes.len()) } else { current_ref.page_free_bytes.len() }; + let end = current_ref.page_free_bytes.len(); let mut search_index = begin; while let Some(relative_first) = current_ref .page_free_bytes - .get(search_index..end)? + .get(search_index..candidate_end)? .iter() .position(|free_bytes| *free_bytes == AllocatorListNode::RETIRED_PAGE) { - let first = search_index + relative_first; + let first_address = current_ref.region_base() + uefi_pages_to_size!(search_index + relative_first); + let aligned_address = align_up(first_address, alignment).ok()?; + let first = (aligned_address - current_ref.region_base()) >> UEFI_PAGE_SHIFT; + if first >= candidate_end { + break; + } let run = current_ref .page_free_bytes .get(first..end)? @@ -690,18 +735,21 @@ impl FixedSizeBlockAllocator { } search_index = first + run; - if search_index < end { + if search_index >= candidate_end { + break; + } + if search_index < candidate_end { search_index += 1; } } + if wrapped && current == start_node { + break; + } node = self.next_allocator_node(current); if node == Some(start_node) { wrapped = true; } - if wrapped && current == start_node { - break; - } } None @@ -728,6 +776,21 @@ impl FixedSizeBlockAllocator { } } + #[cfg(test)] + fn pending_retirement(&self, _max_pages: usize) -> Option> { + for node in AllocatorIterator::new(self.allocators) { + // SAFETY: AllocatorIterator yields valid nodes with permanently mapped metadata. + let node = unsafe { &*node }; + if let Some(index) = + node.page_free_bytes.iter().position(|state| *state == AllocatorListNode::RETIRING_PAGE) + { + let start = node.region_base() + uefi_pages_to_size!(index); + return Some(start..start + UEFI_PAGE_SIZE); + } + } + None + } + /// Returns a range of retired pages to the backing allocators that own them, making them available for allocation /// again. /// @@ -760,12 +823,6 @@ impl FixedSizeBlockAllocator { debug_assert!(false, "FSB asked to restore a page it does not own."); return; }; - let (Some(ptr), Ok(layout)) = - (NonNull::new(page_base as *mut u8), Layout::from_size_align(UEFI_PAGE_SIZE, UEFI_PAGE_SIZE)) - else { - debug_assert!(false, "FSB asked to restore an invalid page."); - return; - }; // SAFETY: every byte of this page was handed out by this heap as fixed-size blocks and all of those blocks // have been freed and unlinked, so returning the page as a single allocation describes exactly the memory the @@ -774,7 +831,6 @@ impl FixedSizeBlockAllocator { if let Some((_, free_bytes)) = (*node.as_ptr()).page_free_bytes_mut(page_base) { *free_bytes = 0; } - (*node.as_ptr()).allocator.deallocate(ptr, layout); } self.stats.reclaimed_pages += 1; } @@ -806,19 +862,6 @@ impl FixedSizeBlockAllocator { Ok(()) } - /// Indicates whether the given pointer falls within a memory region managed by this allocator. - /// - /// Note: `true` does not indicate that the pointer corresponds to an active allocation - it may be in either - /// allocated or freed memory. `true` just means that the pointer falls within a memory region that this allocator - /// manages. - pub fn contains(&self, ptr: *mut u8) -> bool { - AllocatorIterator::new(self.allocators).any(|node| { - // SAFETY: node is produced by AllocatorIterator and points to a valid AllocatorListNode. - let allocator = unsafe { &mut (*node).allocator }; - (allocator.bottom() <= ptr) && (ptr < allocator.top()) - }) - } - /// Tracks page allocations for record keeping pub fn notify_page_allocation(&mut self, allocation: NonNull<[u8]>) { if self.in_reserved_range(allocation.addr().get() as efi::PhysicalAddress) { @@ -831,7 +874,7 @@ impl FixedSizeBlockAllocator { /// Tracks page freeing for record keeping pub fn notify_pages_freed(&mut self, address: efi::PhysicalAddress, pages: usize) { if self.in_reserved_range(address) { - self.stats.reserved_used = self.stats.reserved_used.saturating_sub(pages * ALIGNMENT); + self.stats.reserved_used = self.stats.reserved_used.saturating_sub(pages * UEFI_PAGE_SIZE); } else { self.stats.claimed_pages = self.stats.claimed_pages.saturating_sub(pages); } @@ -843,9 +886,21 @@ impl FixedSizeBlockAllocator { /// If the allocator does not own any memory, it will return an empty iterator. pub(crate) fn get_memory_ranges(&self) -> impl Iterator> { AllocatorIterator::new(self.allocators).map(|node| { + let base = node.addr(); + // SAFETY: node is produced by AllocatorIterator and points to a valid AllocatorListNode. - let allocator = unsafe { &(*node).allocator }; - allocator.bottom() as usize..allocator.top() as usize + let end = base + unsafe { (*node).region_size }; + base..end + }) + } + + /// Returns the metadata pages of a region for patina tests + #[cfg(target_os = "uefi")] + pub(crate) fn firmware_test_metadata_range(&self, base: usize) -> Option> { + AllocatorIterator::new(self.allocators).find_map(|node| { + // SAFETY: the iterator yields live nodes owned by this locked allocator. + let node = unsafe { &*node }; + (node.region_base() == base).then(|| base..node.first_page_base()) }) } @@ -861,111 +916,19 @@ impl FixedSizeBlockAllocator { } } -impl Display for FixedSizeBlockAllocator { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - writelncrlf!(f, "Memory Type: {:x?}", self.memory_type())?; - writelncrlf!(f, "Allocation Ranges:")?; - for node in AllocatorIterator::new(self.allocators) { - // SAFETY: node is produced by AllocatorIterator and points to a valid AllocatorListNode. - let (region_base, allocator) = unsafe { ((*node).region_base(), &mut (*node).allocator) }; - writelncrlf!( - f, - " PhysRange: {:#x}-{:#x}, Size: {:#x}, Used: {:#x} Free: {:#x}", - region_base, - allocator.top() as usize, - allocator.top() as usize - region_base, - allocator.used(), - allocator.free(), - )?; - } - writelncrlf!(f, "Bucket Range: {:x?}", self.reserved_range)?; - writelncrlf!(f, "Allocation Stats:")?; - writelncrlf!(f, " pool_allocation_calls: {}", self.stats.pool_allocation_calls)?; - writelncrlf!(f, " pool_free_calls: {}", self.stats.pool_free_calls)?; - writelncrlf!(f, " page_allocation_calls: {}", self.stats.page_allocation_calls)?; - writelncrlf!(f, " page_free_calls: {}", self.stats.page_free_calls)?; - writelncrlf!(f, " reserved_size: {}", self.stats.reserved_size)?; - writelncrlf!(f, " reserved_used: {}", self.stats.reserved_used)?; - writelncrlf!(f, " claimed_pages: {}", self.stats.claimed_pages)?; - writelncrlf!(f, " retired_pages: {}", self.stats.retired_pages)?; - writelncrlf!(f, " reclaimed_pages: {}", self.stats.reclaimed_pages)?; - Ok(()) - } -} - -/// Spin Locked Fixed Size Block Allocator -/// -/// A wrapper for [`FixedSizeBlockAllocator`] that allocates additional memory as needed from a GCD -/// and provides Sync/Send via means of a spin mutex. -/// -/// Note: [`SpinLockedFixedSizeBlockAllocator::alloc()`] and [`SpinLockedFixedSizeBlockAllocator::allocate()`] will call -/// `alloc()` twice when additional memory is required. -pub struct SpinLockedFixedSizeBlockAllocator { - /// The GCD instance that this allocator uses to allocate additional memory as needed. - gcd: &'static SpinLockedGcd, - - /// The handle associated with this allocator. It is used to track ownership of the memory allocated - /// by this allocator in the GCD. - handle: efi::Handle, - - /// The inner allocator that is protected by a TPL mutex. - inner: tpl_mutex::TplMutex, - - /// The minimum amount of memory to allocate when expanding the allocator. - min_expansion: usize, - - /// Set while this allocator is updating page attributes through the GCD. The GCD may allocate and free pool - /// memory, so this prevents an attribute update from recursing into another attribute update. - updating_page_attributes: AtomicBool, -} - -impl SpinLockedFixedSizeBlockAllocator { - /// Creates a new empty `FixedSizeBlockAllocator` that will request memory from `gcd` as needed to satisfy - /// requests. - pub const fn new( - gcd: &'static SpinLockedGcd, - allocator_handle: efi::Handle, - memory_type: efi::MemoryType, - page_allocation_granularity: usize, - min_expansion: usize, - ) -> Self { - SpinLockedFixedSizeBlockAllocator { - gcd, - handle: allocator_handle, - inner: tpl_mutex::TplMutex::new( - efi::TPL_HIGH_LEVEL, - FixedSizeBlockAllocator::new(memory_type, page_allocation_granularity), - "FsbLock", - ), - min_expansion, - updating_page_attributes: AtomicBool::new(false), - } - } - - // This routine resets some aspects of allocator state for testing purposes. - // Note: this does not reset the GCD nor change the page_change_callback. - #[cfg(test)] - pub fn reset(&self) { - self.lock().reset(); - } - - /// Locks the allocator - /// - /// This can be used to do several actions on the allocator atomically. - pub fn lock(&self) -> tpl_mutex::TplGuard<'_, FixedSizeBlockAllocator> { - self.inner.lock() - } - - /// Updates the attributes of a range of pool pages through the GCD, preserving the attributes that are not being - /// changed. - /// - /// Note: the FSB lock must not be held when calling this, as the GCD allocates and frees pool memory. - fn update_page_attributes(&self, pages: &Range, apply_free_policy: bool) -> Result<(), EfiError> { - match self.apply_page_attributes(pages, apply_free_policy) { +impl FixedSizeBlockAllocator { + /// Updates pool page attributes while retaining exclusive access to the allocator. + fn update_page_attributes( + &mut self, + gcd: &SpinLockedGcd, + pages: &Range, + apply_free_policy: bool, + ) -> Result<(), EfiError> { + match self.apply_page_attributes(gcd, pages, apply_free_policy) { Ok(()) => Ok(()), Err((err, failed_address)) => { if let Err((rollback_err, _)) = - self.apply_page_attributes(&(pages.start..failed_address), !apply_free_policy) + self.apply_page_attributes(gcd, &(pages.start..failed_address), !apply_free_policy) { log::error!( "Failed to roll back pool page attributes for {:#x}-{:#x}: {rollback_err:?}", @@ -978,11 +941,15 @@ impl SpinLockedFixedSizeBlockAllocator { } } - fn apply_page_attributes(&self, pages: &Range, apply_free_policy: bool) -> Result<(), (EfiError, usize)> { + fn apply_page_attributes( + &mut self, + gcd: &SpinLockedGcd, + pages: &Range, + apply_free_policy: bool, + ) -> Result<(), (EfiError, usize)> { let mut base = pages.start; while base < pages.end { - let descriptor = self - .gcd + let descriptor = gcd .get_memory_descriptor_for_address(base as efi::PhysicalAddress, |d, _| { d.memory_type != GcdMemoryType::NonExistent }) @@ -1000,11 +967,10 @@ impl SpinLockedFixedSizeBlockAllocator { GcdMemoryType::SystemMemory, ) } else { - self.gcd - .memory_protection_policy + gcd.memory_protection_policy .apply_allocated_memory_protection_policy(descriptor.attributes, GcdMemoryType::SystemMemory) }; - match self.gcd.set_memory_space_attributes(base, end - base, attributes) { + match gcd.set_memory_space_attributes(base, end - base, attributes) { Ok(()) | Err(EfiError::NotReady) => base = end, Err(err) => return Err((err, base)), } @@ -1012,60 +978,217 @@ impl SpinLockedFixedSizeBlockAllocator { Ok(()) } - /// Unmaps pages that are not currently used by pool allocations. - /// If they cannot be unmapped they are placed back into circulation instead. - fn retire_pages(&self, pages: Range) { - if self.updating_page_attributes.swap(true, Ordering::Acquire) { - // Re-entered from a GCD attribute update; leave the pages in circulation rather than recursing. - self.lock().restore_pages(pages); - return; - } - - let result = self.update_page_attributes(&pages, true); - if result.is_ok() { - self.lock().mark_pages_retired(pages.clone()); - } - self.updating_page_attributes.store(false, Ordering::Release); - + /// Completes retirement with exclusive access to the allocator. + /// Failed unmaps become retired and must be mapped successfully by a future reclaim before being published. + fn retire_pages(&mut self, gcd: &SpinLockedGcd, pages: Range) { + let result = self.update_page_attributes(gcd, &pages, true); + self.mark_pages_retired(pages.clone()); if let Err(err) = result { log::error!("Failed to unmap pool pages {:#x}-{:#x}: {err:?}", pages.start, pages.end); - self.lock().restore_pages(pages); } } - /// Maps `count` contiguous retired pages and returns them to the backing allocator. - /// - /// Returns `true` if all pages were returned to service, false if no suitable contiguous range was found. - fn reclaim_pages(&self, count: usize) -> bool { - if self.updating_page_attributes.swap(true, Ordering::Acquire) { - return false; + fn free_pages_internal( + &mut self, + gcd: &SpinLockedGcd, + handle: efi::Handle, + address: usize, + pages: usize, + ) -> Result<(), EfiError> { + if !address.is_multiple_of(self.page_allocation_granularity) { + return Err(EfiError::InvalidParameter); } - // Note: the lock is released before updating attributes, as the GCD allocates and frees pool memory. - let retired_pages = self.lock().find_retired_pages(count); + let descriptor = gcd + .get_memory_descriptor_for_address(address as efi::PhysicalAddress, |d, _| { + d.memory_type != GcdMemoryType::NonExistent + }) + .map_err(|err| match err { + EfiError::NotFound => err, + _ => EfiError::InvalidParameter, + })?; - let mut reclaimed = false; - if let Some(pages) = retired_pages { - match self.update_page_attributes(&pages, false) { - Ok(()) => { - self.lock().restore_pages(pages); - reclaimed = true; - } - Err(err) => log::error!("Failed to re-map retired pool pages {:#x}: {err:?}", pages.start), - } + if descriptor.image_handle != handle { + Err(EfiError::NotFound)?; } - self.updating_page_attributes.store(false, Ordering::Release); - reclaimed - } - - /// Indicates whether the given pointer falls within a memory region managed by this allocator. - /// - /// See [`FixedSizeBlockAllocator::contains()`] - pub fn contains(&self, ptr: NonNull) -> bool { - self.lock().contains(ptr.as_ptr()) - } - + if self.in_reserved_range(address as efi::PhysicalAddress) { + gcd.free_memory_space_preserving_ownership(address, uefi_pages_to_size!(pages)).map_err( + |err| match err { + EfiError::NotFound => err, + _ => EfiError::InvalidParameter, + }, + )?; + } else { + gcd.free_memory_space(address, uefi_pages_to_size!(pages)).map_err(|err| match err { + EfiError::NotFound => err, + _ => EfiError::InvalidParameter, + })?; + } + + Ok(()) + } + + /// Attempts to allocate from the GCD, preferring the reserved (bin) range if one exists. + /// + /// For strategies that do not exclude the bin range, this first tries to allocate within the + /// bin range so that special-type pages land in their designated bin. Specifically, bin + /// preference is attempted for: + /// - `TopDown(None)` / `BottomUp(None)`: fully unconstrained strategies. + /// - `TopDown(Some(max))` / `BottomUp(Some(max))`: constrained strategies where `max` is at + /// or above the bin range end, meaning the bin is reachable. + /// + /// `Address(addr)` strategies are never redirected because the caller requires an exact address. + /// + /// If the bin is full or no bin exists, the allocation falls through to the original strategy. + fn allocate_from_gcd( + &mut self, + gcd: &SpinLockedGcd, + handle: efi::Handle, + strategy: AllocationStrategy, + align_shift: usize, + size: usize, + ) -> Result { + let try_bin = match strategy { + AllocationStrategy::TopDown(None) | AllocationStrategy::BottomUp(None) => true, + AllocationStrategy::TopDown(Some(max)) | AllocationStrategy::BottomUp(Some(max)) => { + if let Some(ref reserved) = self.reserved_range { + max as u64 >= reserved.start + size as u64 + } else { + false + } + } + _ => false, + }; + + if try_bin + && let Some(ref reserved) = self.reserved_range + && let Ok(addr) = gcd.allocate_memory_space( + AllocationStrategy::TopDown(Some(reserved.end as usize)), + GcdMemoryType::SystemMemory, + align_shift, + size, + handle, + None, + ) + { + if addr >= reserved.start as usize { + return Ok(addr); + } + let _ = gcd.free_memory_space(addr, size); + } + + gcd.allocate_memory_space(strategy, GcdMemoryType::SystemMemory, align_shift, size, handle, None) + } +} + +impl Display for FixedSizeBlockAllocator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + writelncrlf!(f, "Memory Type: {:x?}", self.memory_type())?; + writelncrlf!(f, "Allocation Ranges:")?; + for node in AllocatorIterator::new(self.allocators) { + let base = node.addr(); + // SAFETY: node is produced by AllocatorIterator and points to a valid AllocatorListNode. + let size = unsafe { (*node).region_size }; + // SAFETY: node is produced by AllocatorIterator and points to a valid AllocatorListNode. + let free = unsafe { + (*node) + .page_free_bytes + .iter() + .map(|free_bytes| { + if *free_bytes < AllocatorListNode::RETIRED_PAGE { + *free_bytes as usize + } else { + AllocatorListNode::RETIRED_PAGE as usize + } + }) + .sum::() + }; + let used = size.saturating_sub(free); + writelncrlf!( + f, + " PhysRange: {:#x}-{:#x}, Size: {:#x}, Used: {:#x} Free: {:#x}", + base, + base + size, + size, + used, + free, + )?; + } + writelncrlf!(f, "Bucket Range: {:x?}", self.reserved_range)?; + writelncrlf!(f, "Allocation Stats:")?; + writelncrlf!(f, " pool_allocation_calls: {}", self.stats.pool_allocation_calls)?; + writelncrlf!(f, " large_pool_allocation_calls: {}", self.stats.large_pool_allocation_calls)?; + writelncrlf!(f, " pool_free_calls: {}", self.stats.pool_free_calls)?; + writelncrlf!(f, " page_allocation_calls: {}", self.stats.page_allocation_calls)?; + writelncrlf!(f, " page_free_calls: {}", self.stats.page_free_calls)?; + writelncrlf!(f, " reserved_size: {}", self.stats.reserved_size)?; + writelncrlf!(f, " reserved_used: {}", self.stats.reserved_used)?; + writelncrlf!(f, " claimed_pages: {}", self.stats.claimed_pages)?; + writelncrlf!(f, " retired_pages: {}", self.stats.retired_pages)?; + writelncrlf!(f, " reclaimed_pages: {}", self.stats.reclaimed_pages)?; + Ok(()) + } +} + +/// Spin Locked Fixed Size Block Allocator +/// +/// A wrapper for [`FixedSizeBlockAllocator`] that allocates additional memory as needed from a GCD +/// and provides Sync/Send via means of a spin mutex. +/// +/// Note: [`SpinLockedFixedSizeBlockAllocator::alloc()`] and [`SpinLockedFixedSizeBlockAllocator::allocate()`] will call +/// `alloc()` twice when additional memory is required. +pub struct SpinLockedFixedSizeBlockAllocator { + /// The GCD instance that this allocator uses to allocate additional memory as needed. + gcd: &'static SpinLockedGcd, + + /// The handle associated with this allocator. It is used to track ownership of the memory allocated + /// by this allocator in the GCD. + handle: efi::Handle, + + /// The inner allocator that is protected by a TPL mutex. + inner: tpl_mutex::TplMutex, + + /// The minimum amount of memory to allocate when expanding the allocator. + min_expansion: usize, +} + +impl SpinLockedFixedSizeBlockAllocator { + /// Creates a new empty `FixedSizeBlockAllocator` that will request memory from `gcd` as needed to satisfy + /// requests. + pub const fn new( + gcd: &'static SpinLockedGcd, + allocator_handle: efi::Handle, + memory_type: efi::MemoryType, + page_allocation_granularity: usize, + min_expansion: usize, + ) -> Self { + SpinLockedFixedSizeBlockAllocator { + gcd, + handle: allocator_handle, + inner: tpl_mutex::TplMutex::new( + efi::TPL_HIGH_LEVEL, + FixedSizeBlockAllocator::new(memory_type, page_allocation_granularity), + "FsbLock", + ), + min_expansion, + } + } + + // This routine resets some aspects of allocator state for testing purposes. + // Note: this does not reset the GCD nor change the page_change_callback. + #[cfg(test)] + pub fn reset(&self) { + self.lock().reset(); + } + + /// Locks the allocator + /// + /// This can be used to do several actions on the allocator atomically. + pub fn lock(&self) -> tpl_mutex::TplGuard<'_, FixedSizeBlockAllocator> { + self.inner.lock() + } + /// Attempts to allocate the given number of pages according to the given allocation strategy. /// Valid allocation strategies are: /// - BottomUp(None): Allocate the block of pages from the lowest available free memory. @@ -1084,8 +1207,11 @@ impl SpinLockedFixedSizeBlockAllocator { alignment: usize, ) -> Result, EfiError> { // Record this call in the FSB's stats - self.lock().stats.page_allocation_calls += 1; - let granularity = self.lock().page_allocation_granularity; + let mut allocator = self.lock(); + allocator.stats.page_allocation_calls += 1; + let granularity = allocator.page_allocation_granularity; + + page_shift_from_alignment(alignment)?; // Granularity and alignment both are powers of two, so we can use the max of the two let required_alignment = max(granularity, alignment); @@ -1106,8 +1232,14 @@ impl SpinLockedFixedSizeBlockAllocator { // Page allocations and pool allocations are disjoint; page allocations are allocated directly from the GCD and are // freed straight back to GCD. As such, a tracking allocator structure is not required. - let start_address = self - .allocate_from_gcd(allocation_strategy, align_shift, uefi_pages_to_size!(required_pages)) + let start_address = allocator + .allocate_from_gcd( + self.gcd, + self.handle, + allocation_strategy, + align_shift, + uefi_pages_to_size!(required_pages), + ) .map_err(|err| match err { EfiError::InvalidParameter | EfiError::NotFound => err, _ => EfiError::OutOfResources, @@ -1117,7 +1249,7 @@ impl SpinLockedFixedSizeBlockAllocator { let allocation = NonNull::new(allocation).ok_or(EfiError::OutOfResources)?; // Notify the FSB that additional pages were allocated for record keeping - self.lock().notify_page_allocation(allocation); + allocator.notify_page_allocation(allocation); Ok(allocation) } @@ -1128,47 +1260,17 @@ impl SpinLockedFixedSizeBlockAllocator { /// Caller must ensure that the given address corresponds to a valid block of pages that was allocated with /// [`Self::allocate_pages`] pub unsafe fn free_pages(&self, address: usize, pages: usize) -> Result<(), EfiError> { - self.lock().stats.page_free_calls += 1; - - let granularity = self.lock().page_allocation_granularity; + let mut allocator = self.lock(); + allocator.stats.page_free_calls += 1; + let granularity = allocator.page_allocation_granularity; // Ensure that the requested number of pages is a multiple of the granularity let required_pages = align_up(pages, uefi_size_to_pages!(granularity))?; - if !address.is_multiple_of(granularity) { - return Err(EfiError::InvalidParameter); - } - - let descriptor = self - .gcd - .get_memory_descriptor_for_address(address as efi::PhysicalAddress, |d, _| { - d.memory_type != GcdMemoryType::NonExistent - }) - .map_err(|err| match err { - EfiError::NotFound => err, - _ => EfiError::InvalidParameter, - })?; - - if descriptor.image_handle != self.handle { - Err(EfiError::NotFound)?; - } - - if self.lock().in_reserved_range(address as efi::PhysicalAddress) { - self.gcd.free_memory_space_preserving_ownership(address, uefi_pages_to_size!(required_pages)).map_err( - |err| match err { - EfiError::NotFound => err, - _ => EfiError::InvalidParameter, - }, - )?; - } else { - self.gcd.free_memory_space(address, uefi_pages_to_size!(required_pages)).map_err(|err| match err { - EfiError::NotFound => err, - _ => EfiError::InvalidParameter, - })?; - } + allocator.free_pages_internal(self.gcd, self.handle, address, required_pages)?; // Notify the FSB that pages were freed for record keeping - self.lock().notify_pages_freed(address as efi::PhysicalAddress, required_pages); + allocator.notify_pages_freed(address as efi::PhysicalAddress, required_pages); Ok(()) } @@ -1184,57 +1286,6 @@ impl SpinLockedFixedSizeBlockAllocator { self.lock().set_reserved_range(range) } - /// Attempts to allocate from the GCD, preferring the reserved (bin) range if one exists. - /// - /// For strategies that do not exclude the bin range, this first tries to allocate within the - /// bin range so that special-type pages land in their designated bin. Specifically, bin - /// preference is attempted for: - /// - `TopDown(None)` / `BottomUp(None)`: fully unconstrained strategies. - /// - `TopDown(Some(max))` / `BottomUp(Some(max))`: constrained strategies where `max` is at - /// or above the bin range end, meaning the bin is reachable. - /// - /// `Address(addr)` strategies are never redirected because the caller requires an exact address. - /// - /// If the bin is full or no bin exists, the allocation falls through to the original strategy. - fn allocate_from_gcd( - &self, - strategy: AllocationStrategy, - align_shift: usize, - size: usize, - ) -> Result { - let reserved_range = self.lock().reserved_range.clone(); - - // Determine whether to attempt bin-preference allocation. - let try_bin = match strategy { - AllocationStrategy::TopDown(None) | AllocationStrategy::BottomUp(None) => true, - AllocationStrategy::TopDown(Some(max)) | AllocationStrategy::BottomUp(Some(max)) => { - if let Some(ref reserved) = reserved_range { max as u64 >= reserved.start + size as u64 } else { false } - } - _ => false, - }; - - if try_bin - && let Some(ref reserved) = reserved_range - && let Ok(addr) = self.gcd.allocate_memory_space( - AllocationStrategy::TopDown(Some(reserved.end as usize)), - GcdMemoryType::SystemMemory, - align_shift, - size, - self.handle, - None, - ) - { - if addr >= reserved.start as usize { - return Ok(addr); - } - // Landed below the bin, free and fall through. - let _ = self.gcd.free_memory_space(addr, size); - } - - // Normal allocation path. - self.gcd.allocate_memory_space(strategy, GcdMemoryType::SystemMemory, align_shift, size, self.handle, None) - } - /// Returns an iterator of the ranges of memory owned by this allocator /// Returns an empty iterator if the allocator does not own any memory. pub fn get_memory_ranges(&self) -> alloc::vec::IntoIter> { @@ -1306,51 +1357,59 @@ unsafe impl GlobalAlloc for SpinLockedFixedSizeBlockAllocator { // SAFETY: SpinLockedFixedSizeBlockAllocator serializes access and delegates to the inner allocator. unsafe impl Allocator for SpinLockedFixedSizeBlockAllocator { fn allocate(&self, layout: Layout) -> core::result::Result, AllocError> { - let allocation = self.lock().alloc(layout); + let mut allocator = self.lock(); + let allocation = allocator.alloc(layout); match allocation { Ok(alloc) => Ok(alloc), - Err(FixedSizeBlockAllocatorError::OutOfMemory(additional_mem_required)) => { - // Compile-time check to ensure ALIGNMENT is compatible with the alignment requirements - // of `expand()` and `page_shift_from_alignment()` - const _: () = assert!(ALIGNMENT.is_multiple_of(align_of::())); - const _: () = assert!(ALIGNMENT.is_multiple_of(UEFI_PAGE_SIZE) && ALIGNMENT > 0); + Err(FixedSizeBlockAllocatorError::OutOfMemory(required_size)) => { + // compile time check that validates the assumption used below to add blocks to the free list. + const _: () = assert!(block_sizes_divide_alignment()); // Map enough pages to satisfy the request. - let reclaim_pages = uefi_size_to_pages!(additional_mem_required); + let required_payload_pages = uefi_size_to_pages!(required_size); // Bring a sufficient contiguous retired range back into service before claiming more memory from the // GCD. Shorter fragmented ranges remain retired. - if self.reclaim_pages(reclaim_pages) - && let Ok(alloc) = self.lock().internal_alloc(layout) - { - return Ok(alloc); + let reclaim_range = if layout.align() > UEFI_PAGE_SIZE { + allocator.find_aligned_retired_pages(required_payload_pages, layout.align()) + } else { + allocator.find_retired_pages(required_payload_pages) + }; + if let Some(pages) = reclaim_range { + let mapped = allocator.update_page_attributes(self.gcd, &pages, false); + if let Err(err) = mapped { + allocator.mark_pages_retired(pages.clone()); + log::error!("Failed to re-map retired pool pages {:#x}: {err:?}", pages.start); + } else { + allocator.restore_pages(pages.clone()); + if let Ok(alloc) = allocator.allocate_from_pages(layout, pages) { + return Ok(alloc); + } + debug_assert!(false, "Failed to allocate from internal allocator after reclaiming pages."); + } } // As a matter of policy, allocate at least the minimum expansion amount of memory and ensure the - // size is aligned to `ALIGNMENT`. - let mut allocation_size = max(additional_mem_required, self.min_expansion); - let required_alignment = self.lock().page_allocation_granularity; - - // Ensure that the requested number of pages is a multiple of the granularity - let required_pages = - align_up(uefi_size_to_pages!(allocation_size), uefi_size_to_pages!(required_alignment)).map_err( - |_| { + // size is aligned to `UEFI_PAGE_SIZE`. + let required_alignment = allocator.page_allocation_granularity; + let user_alignment = max(UEFI_PAGE_SIZE, layout.align()); + let usable_size = max(required_size, UEFI_PAGE_SIZE) + .checked_add(user_alignment - UEFI_PAGE_SIZE) + .ok_or(AllocError)?; + let allocation_size = + AllocatorListNode::allocation_size(usable_size, self.min_expansion, required_alignment) + .ok_or_else(|| { debug_assert!(false); AllocError - }, - )?; - - if RegionHeader::new(required_pages).is_none() { - log::error!("Allocator expansion metadata is invalid for {required_pages:#x} pages."); - return Err(AllocError); - } - - allocation_size = uefi_pages_to_size!(required_pages); + })?; + let required_pages = uefi_size_to_pages!(allocation_size); // Allocate additional memory through the GCD, returning AllocError // if the GCD returns an error - let start_address: usize = self + let start_address: usize = allocator .allocate_from_gcd( + self.gcd, + self.handle, DEFAULT_ALLOCATION_STRATEGY, page_shift_from_alignment(required_alignment).map_err(|_| { debug_assert!(false); @@ -1370,55 +1429,156 @@ unsafe impl Allocator for SpinLockedFixedSizeBlockAllocator { debug_assert!(false); AllocError })?; - let Ok(new_pages) = self.lock().expand(NonNull::slice_from_raw_parts(allocated_ptr, allocation_size)) + let Ok(new_pages) = allocator.expand(NonNull::slice_from_raw_parts(allocated_ptr, allocation_size)) else { debug_assert!(false); return Err(AllocError); }; - // We may only have free space in a partial page after the metadata, in which case we can allocate but - // do not have any whole pages to activate. - if let Some(new_pages) = new_pages { - let active_end = min(new_pages.end, new_pages.start + uefi_pages_to_size!(reclaim_pages)); - self.lock().activate_new_pages(new_pages.start..active_end); - - // Done outside of the lock: the GCD allocates and frees pool memory while updating attributes. - if active_end < new_pages.end { - self.retire_pages(active_end..new_pages.end); - } + let new_pages = new_pages.ok_or(AllocError)?; + let active_start = align_up(new_pages.start, user_alignment).map_err(|_| AllocError)?; + let active_end = + active_start.checked_add(uefi_pages_to_size!(required_payload_pages)).ok_or(AllocError)?; + if active_end > new_pages.end { + debug_assert!(false, "Expansion does not contain enough aligned pages."); + return Err(AllocError); } - - // The activated portion of the new region was sized to satisfy this allocation. - self.lock().internal_alloc(layout).map_err(|_| { + let active_pages = active_start..active_end; + allocator.activate_new_pages(active_pages.clone()); + let allocation = allocator.allocate_from_pages(layout, active_pages).map_err(|_| { debug_assert!(false); AllocError - }) - } - Err(e) => { - log::error!( - "Allocator failed to expand and allocate new pages for the requested layout: {layout:?} with error {e:?}" - ); - debug_assert!(false); - Err(AllocError) + }); + if new_pages.start < active_start { + allocator.retire_pages(self.gcd, new_pages.start..active_start); + } + if active_end < new_pages.end { + allocator.retire_pages(self.gcd, active_end..new_pages.end); + } + allocation } - } - } - unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { - // SAFETY: ptr came from allocate with the same layout. - let retired_page = unsafe { self.lock().dealloc(ptr, layout) }; + Err(FixedSizeBlockAllocatorError::ExceedsBlockSize) => { + // if we get a larger allocation requestion than the largest block size, we will satisfy it with pages + // from the GCD directly. The largest block is already a page in size, so we are handling a very large + // pool allocation + let alignment = allocator.page_allocation_granularity; - // Done outside of the lock: the GCD allocates and frees pool memory while updating attributes. - if let Some(page_base) = retired_page { - self.retire_pages(page_base..page_base + UEFI_PAGE_SIZE); - } - } -} + // Per UEFI spec, user pointers must be at least 8-byte aligned. Making the user alignment at least the + // node alignment also ensures the node immediately before the user pointer can be accessed normally. + let user_ptr_alignment = max(layout.align(), max(8, align_of::())); -impl Display for SpinLockedFixedSizeBlockAllocator { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.lock().fmt(f) - } -} + let size = LargeAllocationNode::allocation_size(layout, alignment).ok_or_else(|| { + debug_assert!(false); + AllocError + })?; + + let start_address: usize = allocator + .allocate_from_gcd( + self.gcd, + self.handle, + DEFAULT_ALLOCATION_STRATEGY, + page_shift_from_alignment(alignment).map_err(|_| { + debug_assert!(false); + AllocError + })?, + size, + ) + .map_err(|err| { + log::error!( + "Allocator Expansion via GCD failed: [{err:?}], {{ Alignment: {alignment:#x}, Size: {size:#x} }}", + ); + AllocError + })?; + + let user_addr = NonNull::new( + align_up(start_address + core::mem::size_of::(), user_ptr_alignment) + .expect("User addresses should not be at the top of memory") as *mut u8, + ) + .expect("User addresses should not be null"); + let large_allocation_node = + LargeAllocationNode { signature: LARGE_ALLOCATION_NODE_SIGNATURE, base: start_address, size }; + + // SAFETY: size reserves enough alignment padding for a LargeAllocationNode immediately before the + // aligned user pointer and the complete user allocation after it. + unsafe { user_addr.cast::().as_ptr().sub(1).write(large_allocation_node) }; + + let allocation = + NonNull::slice_from_raw_parts(NonNull::new(start_address as *mut u8).ok_or(AllocError)?, size); + allocator.notify_page_allocation(allocation); + + Ok(NonNull::slice_from_raw_parts(user_addr, layout.size())) + } + Err(e) => { + log::error!( + "Allocator failed to expand and allocate new pages for the requested layout: {layout:?} with error {e:?}" + ); + debug_assert!(false); + Err(AllocError) + } + } + } + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + let mut allocator = self.lock(); + let Some(index) = list_index(&layout) else { + allocator.stats.pool_free_calls += 1; + if let Some(size) = retained_pool_size(layout) { + let pages = ptr.addr().get()..ptr.addr().get() + size; + for page_base in pages.clone().step_by(UEFI_PAGE_SIZE) { + let Some(node) = allocator.node_for_address(page_base) else { + debug_assert!(false, "Pool allocation belongs to an untracked page."); + return; + }; + // SAFETY: node_for_address returned the live metadata tracking this allocation. + unsafe { + let Some((_, free_bytes)) = (*node.as_ptr()).page_free_bytes_mut(page_base) else { + debug_assert!(false); + return; + }; + debug_assert_eq!(*free_bytes, 0); + *free_bytes = AllocatorListNode::RETIRING_PAGE; + } + } + allocator.stats.retired_pages += uefi_size_to_pages!(size); + allocator.retire_pages(self.gcd, pages); + return; + } + // if this isn't in the fixed block list, we directly free the memory in the GCD + // SAFETY: large allocations place a LargeAllocationNode immediately before the returned user pointer. + let node = unsafe { NonNull::new_unchecked(ptr.cast::().as_ptr().sub(1)).as_ref() }; + if node.signature != LARGE_ALLOCATION_NODE_SIGNATURE { + debug_assert!(false, "Invalid large allocation node signature"); + return; + } + if LargeAllocationNode::allocation_size(layout, allocator.page_allocation_granularity) != Some(node.size) { + debug_assert!(false, "Large allocation size does not match layout"); + return; + } + let Some(base) = NonZeroUsize::new(node.base) else { + debug_assert!(false, "We shouldn't be deallocating page 0"); + return; + }; + let pages = uefi_size_to_pages!(node.size); + + if let Err(e) = allocator.free_pages_internal(self.gcd, self.handle, base.get(), pages) { + log::error!("Failed to free pages: {e:?}"); + debug_assert!(false, "Failed to free pages for large allocation"); + } else { + allocator.notify_pages_freed(base.get() as efi::PhysicalAddress, pages); + } + return; + }; + // SAFETY: the caller guarantees ptr was allocated with this layout, whose list index was resolved above. + if let Some(page_base) = unsafe { allocator.dealloc(ptr, index) } { + allocator.retire_pages(self.gcd, page_base..page_base + UEFI_PAGE_SIZE); + } + } +} + +impl Display for SpinLockedFixedSizeBlockAllocator { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.lock().fmt(f) + } +} // SAFETY: SpinLockedFixedSizeBlockAllocator protects internal state with a spin lock. unsafe impl Sync for SpinLockedFixedSizeBlockAllocator {} @@ -1455,10 +1615,6 @@ impl PageAllocator for SpinLockedFixedSizeBlockAllocator { Self::get_memory_ranges(self) } - fn contains(&self, ptr: NonNull) -> bool { - Self::contains(self, ptr) - } - fn handle(&self) -> efi::Handle { Self::handle(self) } @@ -1528,6 +1684,17 @@ mod tests { .unwrap(); } + #[test] + fn test_fsb_expansion_size_includes_metadata_in_minimum() { + assert_eq!(AllocatorListNode::allocation_size(UEFI_PAGE_SIZE, SIZE_64KB, SIZE_64KB), Some(SIZE_64KB)); + assert_eq!(AllocatorListNode::allocation_size(SIZE_64KB, SIZE_64KB, SIZE_64KB), Some(2 * SIZE_64KB)); + assert_eq!( + AllocatorListNode::allocation_size(UEFI_PAGE_SIZE, UEFI_PAGE_SIZE, UEFI_PAGE_SIZE), + Some(2 * UEFI_PAGE_SIZE) + ); + assert_eq!(AllocatorListNode::allocation_size(usize::MAX, SIZE_64KB, SIZE_64KB), None); + } + #[test] fn test_get_memory_ranges_returns_allocated_region() { with_granularity_modulation(|granularity| { @@ -1540,7 +1707,7 @@ mod tests { assert_eq!(fsb.get_memory_ranges().count(), 0); - let allocation_size = DEFAULT_PAGE_ALLOCATION_GRANULARITY; + let allocation_size = DEFAULT_PAGE_ALLOCATION_GRANULARITY + UEFI_PAGE_SIZE; let allocated_address = GCD .allocate_memory_space( DEFAULT_ALLOCATION_STRATEGY, @@ -1560,11 +1727,7 @@ mod tests { let ranges: Vec<_> = fsb.get_memory_ranges().collect(); assert_eq!(ranges.len(), 1); - - let header_size = RegionHeader::new(uefi_size_to_pages!(allocation_size)).unwrap().size; - let expected_start = allocated_address + header_size; - let expected_end = expected_start + allocation_size - header_size; - assert_eq!(ranges[0], expected_start..expected_end); + assert_eq!(ranges[0], allocated_address..allocated_address + allocation_size); }); }); } @@ -1609,16 +1772,16 @@ mod tests { assert_eq!(list_index(&layout), Some(0)); let layout = Layout::from_size_align(12, 8).unwrap(); - assert_eq!(list_index(&layout), Some(0)); + assert_eq!(list_index(&layout), Some(1)); let layout = Layout::from_size_align(8, 32).unwrap(); - assert_eq!(list_index(&layout), Some(1)); + assert_eq!(list_index(&layout), Some(2)); let layout = Layout::from_size_align(4096, 32).unwrap(); - assert_eq!(list_index(&layout), Some(8)); + assert_eq!(list_index(&layout), Some(9)); let layout = Layout::from_size_align(1, 4096).unwrap(); - assert_eq!(list_index(&layout), Some(8)); + assert_eq!(list_index(&layout), Some(9)); let layout = Layout::from_size_align(8192, 1).unwrap(); assert_eq!(list_index(&layout), None); @@ -1634,28 +1797,40 @@ mod tests { } #[test] - fn test_region_header_supports_metadata_larger_than_one_page() { - let page_count = UEFI_PAGE_SIZE; - let header = RegionHeader::new(page_count).unwrap(); - - assert!(header.size > UEFI_PAGE_SIZE); - assert_eq!(header.page_count, page_count); - } + fn test_allocator_node_metadata_can_span_multiple_pages() { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + let region_size = uefi_pages_to_size!(UEFI_PAGE_SIZE); + assert!(AllocatorListNode::size_for_free_region(region_size) > UEFI_PAGE_SIZE); - #[test] - fn test_region_size_accounts_for_all_page_metadata() { - const PAYLOAD_SIZE: usize = 0x1000000; + init_gcd(&GCD, region_size * 2); + let region_base = GCD + .allocate_memory_space( + DEFAULT_ALLOCATION_STRATEGY, + GcdMemoryType::SystemMemory, + UEFI_PAGE_SHIFT, + region_size, + DUMMY_HANDLE, + None, + ) + .unwrap(); + let mut fsb = FixedSizeBlockAllocator::new(efi::BOOT_SERVICES_DATA, DEFAULT_PAGE_ALLOCATION_GRANULARITY); - let region_size = RegionHeader::region_size_for_payload(PAYLOAD_SIZE).unwrap(); - let page_count = region_size / UEFI_PAGE_SIZE; - let header = RegionHeader::new(page_count).unwrap(); + let retired = fsb + .expand(NonNull::slice_from_raw_parts(NonNull::new(region_base as *mut u8).unwrap(), region_size)) + .unwrap() + .unwrap(); - assert!(header.size > UEFI_PAGE_SIZE); - assert!(region_size - header.size >= PAYLOAD_SIZE); + assert_eq!(retired.start, region_base + 3 * UEFI_PAGE_SIZE); + // SAFETY: expand installed a valid allocator node at region_base. + let node = unsafe { &*(region_base as *const AllocatorListNode) }; + assert_eq!(node.page_free_bytes[0..3], [0, 0, 0]); + assert!(node.page_free_bytes[3..].iter().all(|free_bytes| *free_bytes == AllocatorListNode::RETIRING_PAGE)); - let smaller_region_size = region_size - UEFI_PAGE_SIZE; - let smaller_header = RegionHeader::new(page_count - 1).unwrap(); - assert!(smaller_region_size - smaller_header.size < PAYLOAD_SIZE); + for &block_size in BLOCK_SIZES { + assert!(fsb.internal_alloc(Layout::from_size_align(block_size, block_size).unwrap()).is_err()); + } + }); } #[test] @@ -1666,7 +1841,7 @@ mod tests { static GCD: SpinLockedGcd = SpinLockedGcd::new(None); // Allocate some space on the heap with the global allocator (std) to be used by expand(). - let base = init_gcd(&GCD, 0x4000000); + init_gcd(&GCD, 0x4000000); //verify no allocators exist before expand. let mut fsb = FixedSizeBlockAllocator::new(efi::RUNTIME_SERVICES_DATA, granularity); @@ -1687,23 +1862,21 @@ mod tests { .unwrap(); // A single page region is entirely consumed by the region header, so there is no whole page to retire. - let retired = fsb - .expand(NonNull::slice_from_raw_parts( + assert_eq!( + fsb.expand(NonNull::slice_from_raw_parts( NonNull::new(allocated_address as *mut u8).unwrap(), allocation_size, - )) - .unwrap(); - assert_eq!(retired, None); + )), + Err(FixedSizeBlockAllocatorError::InvalidExpansion) + ); + assert!(fsb.allocators.is_none()); + assert!(fsb.retired_page_cursor.is_none()); + assert_eq!(fsb.stats.claimed_pages, 0); + assert_eq!(fsb.stats.reserved_used, 0); + assert_eq!(fsb.stats.retired_pages, 0); - assert!(fsb.allocators.is_some()); - // SAFETY: fsb.allocators points to valid list nodes after expand. - unsafe { - assert!((*fsb.allocators.unwrap()).next.is_none()); - assert!((*fsb.allocators.unwrap()).allocator.bottom() as usize > base as usize); - assert_eq!( - (*fsb.allocators.unwrap()).allocator.free(), - allocation_size - RegionHeader::new(uefi_size_to_pages!(allocation_size)).unwrap().size - ); + for &block_size in BLOCK_SIZES { + assert!(fsb.internal_alloc(Layout::from_size_align(block_size, block_size).unwrap()).is_err()); } //expand by larger than the minimum expansion. @@ -1733,15 +1906,14 @@ mod tests { assert!(fsb.allocators.is_some()); // SAFETY: fsb.allocators points to valid list nodes after expand. unsafe { - assert!((*fsb.allocators.unwrap()).next.is_some()); - assert!((*(*fsb.allocators.unwrap()).next.unwrap()).next.is_none()); - assert!((*fsb.allocators.unwrap()).allocator.bottom() as usize > base as usize); - assert_eq!( - (*fsb.allocators.unwrap()).allocator.free(), - //expected free: size of the region less the region header and the retired page. - allocation_size - - RegionHeader::new(uefi_size_to_pages!(allocation_size)).unwrap().size - - UEFI_PAGE_SIZE + let node = &*fsb.allocators.unwrap(); + assert!(node.next.is_none()); + assert_eq!(node.region_size, allocation_size); + assert_eq!(node.page_free_bytes[0], 0); + assert!( + node.page_free_bytes[1..] + .iter() + .all(|free_bytes| *free_bytes == AllocatorListNode::RETIRING_PAGE) ); } }); @@ -1761,7 +1933,7 @@ mod tests { const NUM_ALLOCATIONS: usize = 5; - const ALLOCATION_SIZE: usize = DEFAULT_PAGE_ALLOCATION_GRANULARITY; + const ALLOCATION_SIZE: usize = DEFAULT_PAGE_ALLOCATION_GRANULARITY + UEFI_PAGE_SIZE; for _ in 0..NUM_ALLOCATIONS { fsb.expand(NonNull::slice_from_raw_parts( NonNull::new( @@ -1784,84 +1956,11 @@ mod tests { assert_eq!(NUM_ALLOCATIONS, AllocatorIterator::new(fsb.allocators).count()); assert!(AllocatorIterator::new(fsb.allocators).all(|node| { // SAFETY: node pointers come from AllocatorIterator over fsb.allocators. - unsafe { - let expected_free = - ALLOCATION_SIZE - RegionHeader::new(uefi_size_to_pages!(ALLOCATION_SIZE)).unwrap().size; - (*node).allocator.free() == expected_free - } + unsafe { (*node).region_size == ALLOCATION_SIZE && (*node).page_free_bytes[0] == 0 } })); }); } - #[test] - fn test_fallback_alloc() { - with_granularity_modulation(|granularity| { - with_locked_state(|| { - // Create a static GCD - static GCD: SpinLockedGcd = SpinLockedGcd::new(None); - - // Allocate some space on the heap with the global allocator (std) to be used by expand(). - let _ = init_gcd(&GCD, 0x400000); - - let mut fsb = FixedSizeBlockAllocator::new(efi::RUNTIME_SERVICES_DATA, granularity); - - // Test fallback_alloc with size < size_of::() - let allocation_size = size_of::() / 2; - let layout = Layout::from_size_align(allocation_size, 0x10).unwrap(); - match fsb.fallback_alloc(layout) { - Err(FixedSizeBlockAllocatorError::OutOfMemory(mem_req)) => { - assert!( - mem_req - >= layout.pad_to_align().size() - + Layout::new::().pad_to_align().size(), - "fallback_alloc should request enough memory to fit aligned layout and an aligned AllocatorListNode" - ); - } - _ => { - panic!( - "fallback_alloc with no allocators should return FixedSizeBlockAllocatorError::OutOfMemory" - ) - } - } - assert!(fsb.allocators.is_none()); - - // Test fallback_alloc with size > size_of::(), but unaligned to AllocatorListNode - let allocation_size = size_of::() + align_of::() / 2; - let layout = Layout::from_size_align(allocation_size, 0x10).unwrap(); - match fsb.fallback_alloc(layout) { - Err(FixedSizeBlockAllocatorError::OutOfMemory(mem_req)) => { - assert!( - mem_req - >= layout.pad_to_align().size() - + Layout::new::().pad_to_align().size(), - "fallback_alloc should request enough memory to fit aligned layout and an aligned AllocatorListNode" - ); - } - _ => { - panic!( - "fallback_alloc with no allocators should return FixedSizeBlockAllocatorError::OutOfMemory" - ) - } - } - assert!(fsb.allocators.is_none()); - }); - }); - } - - #[test] - fn test_fallback_alloc_accounts_for_metadata_larger_than_one_page() { - let mut fsb = FixedSizeBlockAllocator::new(efi::BOOT_SERVICES_DATA, DEFAULT_PAGE_ALLOCATION_GRANULARITY); - let layout = Layout::from_size_align(0x1000000, align_of::()).unwrap(); - - let Err(FixedSizeBlockAllocatorError::OutOfMemory(region_size)) = fsb.fallback_alloc(layout) else { - panic!("fallback_alloc should request a region large enough for the allocation and its metadata"); - }; - let header = RegionHeader::new(region_size / UEFI_PAGE_SIZE).unwrap(); - - assert!(header.size > UEFI_PAGE_SIZE); - assert!(region_size - header.size >= layout.size()); - } - #[test] fn test_alloc() { with_granularity_modulation(|granularity| { @@ -1917,81 +2016,6 @@ mod tests { }); } - #[test] - fn test_allocate_with_metadata_larger_than_one_page() { - with_granularity_modulation(|granularity| { - with_locked_state(|| { - static GCD: SpinLockedGcd = SpinLockedGcd::new(None); - const ALLOCATION_SIZE: usize = 0x1000000; - - init_gcd(&GCD, ALLOCATION_SIZE * 2); - let fsb = SpinLockedFixedSizeBlockAllocator::new( - &GCD, - 1 as _, - efi::RUNTIME_SERVICES_DATA, - granularity, - DEFAULT_PAGE_ALLOCATION_GRANULARITY, - ); - let layout = Layout::from_size_align(ALLOCATION_SIZE, align_of::()).unwrap(); - - let allocation = fsb.allocate(layout).unwrap(); - let claimed_pages = fsb.stats().claimed_pages; - - assert!(RegionHeader::new(claimed_pages).unwrap().size > UEFI_PAGE_SIZE); - assert_eq!(allocation.len(), ALLOCATION_SIZE); - - // SAFETY: allocation was returned by fsb for this layout. - unsafe { fsb.deallocate(allocation.cast(), layout) }; - }); - }); - } - - #[test] - fn test_fallback_dealloc() { - with_granularity_modulation(|granularity| { - with_locked_state(|| { - // Create a static GCD - static GCD: SpinLockedGcd = SpinLockedGcd::new(None); - - // Allocate some space on the heap with the global allocator (std) to be used by expand(). - init_gcd(&GCD, 0x400000); - - let mut fsb = FixedSizeBlockAllocator::new(efi::RUNTIME_SERVICES_DATA, granularity); - - let layout = Layout::from_size_align(0x8, 0x8).unwrap(); - - // Expand the FSB by the minimum expansion to fit the allocation - let expansion_size = DEFAULT_PAGE_ALLOCATION_GRANULARITY; - let expansion_address = GCD - .allocate_memory_space( - DEFAULT_ALLOCATION_STRATEGY, - GcdMemoryType::SystemMemory, - UEFI_PAGE_SHIFT, - expansion_size, - DUMMY_HANDLE, - None, - ) - .unwrap(); - fsb.expand(NonNull::slice_from_raw_parts( - NonNull::new(expansion_address as *mut u8).unwrap(), - expansion_size, - )) - .unwrap(); - - let allocation = fsb.fallback_alloc(layout).unwrap(); - - // Finally, we can test fallback_dealloc - fsb.fallback_dealloc(allocation.cast(), layout); - let expected_free = - expansion_size - RegionHeader::new(uefi_size_to_pages!(expansion_size)).unwrap().size; - // SAFETY: fsb.allocators points to a valid allocator after expand. - unsafe { - assert_eq!((*fsb.allocators.unwrap()).allocator.free(), expected_free); - } - }); - }); - } - #[test] fn test_dealloc() { with_granularity_modulation(|granularity| { @@ -2013,22 +2037,22 @@ mod tests { let layout = Layout::from_size_align(0x8, 0x8).unwrap(); // SAFETY: fsb is initialized and used with a valid layout in tests. let allocation = unsafe { fsb.alloc(layout) }; + assert!(!allocation.is_null()); + let free_calls = fsb.stats().pool_free_calls; // SAFETY: Allocation was returned by fsb for this layout. unsafe { fsb.dealloc(allocation, layout) }; - let free_block_ptr = - fsb.lock().list_heads[list_index(&layout).unwrap()].take().unwrap().as_ptr().cast::(); - assert_eq!(free_block_ptr, allocation); + assert_eq!(fsb.stats().pool_free_calls, free_calls + 1); let layout = Layout::from_size_align(0x20, 0x20).unwrap(); // SAFETY: fsb is initialized and used with a valid layout in tests. let allocation = unsafe { fsb.alloc(layout) }; + assert!(!allocation.is_null()); + let free_calls = fsb.stats().pool_free_calls; // SAFETY: Allocation was returned by fsb for this layout. unsafe { fsb.dealloc(allocation, layout) }; - let free_block_ptr = - fsb.lock().list_heads[list_index(&layout).unwrap()].take().unwrap().as_ptr().cast::(); - assert_eq!(free_block_ptr, allocation); + assert_eq!(fsb.stats().pool_free_calls, free_calls + 1); }); }); } @@ -2053,50 +2077,23 @@ mod tests { let layout = Layout::from_size_align(0x8, 0x8).unwrap(); let allocation = fsb.allocate(layout).unwrap().cast::(); - let allocation_ptr = allocation.as_ptr(); + let free_calls = fsb.stats().pool_free_calls; // SAFETY: Allocation was returned by fsb for this layout. unsafe { fsb.deallocate(allocation, layout) }; - let free_block_ptr = - fsb.lock().list_heads[list_index(&layout).unwrap()].take().unwrap().as_ptr().cast::(); - assert_eq!(free_block_ptr, allocation_ptr); + assert_eq!(fsb.stats().pool_free_calls, free_calls + 1); let layout = Layout::from_size_align(0x20, 0x20).unwrap(); let allocation = fsb.allocate(layout).unwrap().cast::(); - let allocation_ptr = allocation.as_ptr(); + let free_calls = fsb.stats().pool_free_calls; // SAFETY: Allocation was returned by fsb for this layout. unsafe { fsb.deallocate(allocation, layout) }; - let free_block_ptr = - fsb.lock().list_heads[list_index(&layout).unwrap()].take().unwrap().as_ptr().cast::(); - assert_eq!(free_block_ptr, allocation_ptr); + assert_eq!(fsb.stats().pool_free_calls, free_calls + 1); }); }); } - #[test] - fn test_contains() { - with_locked_state(|| { - // Create a static GCD - static GCD: SpinLockedGcd = SpinLockedGcd::new(None); - - // Allocate some space on the heap with the global allocator (std) to be used by expand(). - init_gcd(&GCD, 0x400000); - - let fsb = SpinLockedFixedSizeBlockAllocator::new( - &GCD, - 1 as _, - efi::BOOT_SERVICES_DATA, - DEFAULT_PAGE_ALLOCATION_GRANULARITY, - DEFAULT_PAGE_ALLOCATION_GRANULARITY, - ); - - let layout = Layout::from_size_align(0x8, 0x8).unwrap(); - let allocation = fsb.allocate(layout).unwrap().cast::(); - assert!(fsb.contains(allocation)); - }); - } - #[test] fn test_allocate_pages() { with_granularity_modulation(|granularity| { @@ -2157,7 +2154,7 @@ mod tests { DEFAULT_PAGE_ALLOCATION_GRANULARITY, ); - let target_address = (address + 0x400000 - max(8_u64 * ALIGNMENT as u64, granularity as u64)) + let target_address = (address + 0x400000 - max(8_u64 * UEFI_PAGE_SIZE as u64, granularity as u64)) & (!(granularity as u64 - 1_u64)); let pages = 4; @@ -2194,7 +2191,7 @@ mod tests { DEFAULT_PAGE_ALLOCATION_GRANULARITY, ); - let target_address = address + 0x400000 - 8 * (ALIGNMENT as u64); + let target_address = address + 0x400000 - 8 * (UEFI_PAGE_SIZE as u64); let pages = 4; let allocation = fsb @@ -2229,7 +2226,7 @@ mod tests { DEFAULT_PAGE_ALLOCATION_GRANULARITY, ); - let target_address = address + 0x400000 - 8 * (ALIGNMENT as u64); + let target_address = address + 0x400000 - 8 * (UEFI_PAGE_SIZE as u64); let pages = 4; let allocation = fsb @@ -2288,6 +2285,13 @@ mod tests { _ => panic!("Expected INVALID_PARAMETER"), } + for alignment in [0, UEFI_PAGE_SIZE / 2, UEFI_PAGE_SIZE * 3] { + assert_eq!( + fsb.allocate_pages(DEFAULT_ALLOCATION_STRATEGY, 1, alignment), + Err(EfiError::InvalidParameter) + ); + } + // SAFETY: Invalid parameters are intentionally tested (unit test). unsafe { match fsb.free_pages(0x1001, 5) { @@ -2346,6 +2350,7 @@ mod tests { let stats = fsb.stats(); assert_eq!(stats.pool_allocation_calls, 0); + assert_eq!(stats.large_pool_allocation_calls, 0); assert_eq!(stats.pool_free_calls, 0); assert_eq!(stats.page_allocation_calls, 0); assert_eq!(stats.page_free_calls, 0); @@ -2355,14 +2360,13 @@ mod tests { //test alloc/deallocate and stats // SAFETY: fsb is initialized and used with a valid layout for testing. - let ptr = unsafe { - fsb.alloc( - Layout::from_size_align(TEST_MIN_EXPANSION_SIZE - size_of::(), 0x8).unwrap(), - ) - }; + let fixed_layout = Layout::from_size_align(0x100, 0x8).unwrap(); + // SAFETY: fsb is initialized and fixed_layout is valid. + let ptr = unsafe { fsb.alloc(fixed_layout) }; let stats = fsb.stats(); assert_eq!(stats.pool_allocation_calls, 1); + assert_eq!(stats.large_pool_allocation_calls, 0); assert_eq!(stats.pool_free_calls, 0); assert_eq!(stats.page_allocation_calls, 0); assert_eq!(stats.page_free_calls, 0); @@ -2372,11 +2376,12 @@ mod tests { // SAFETY: Allocation was returned by fsb for this layout. unsafe { - fsb.dealloc(ptr, Layout::from_size_align(0x100, 0x8).unwrap()); + fsb.dealloc(ptr, fixed_layout); } let stats = fsb.stats(); assert_eq!(stats.pool_allocation_calls, 1); + assert_eq!(stats.large_pool_allocation_calls, 0); assert_eq!(stats.pool_free_calls, 1); assert_eq!(stats.page_allocation_calls, 0); assert_eq!(stats.page_free_calls, 0); @@ -2396,12 +2401,12 @@ mod tests { let stats = fsb.stats(); assert_eq!(stats.pool_allocation_calls, 2); + assert_eq!(stats.large_pool_allocation_calls, 1); assert_eq!(stats.pool_free_calls, 1); assert_eq!(stats.page_allocation_calls, 0); assert_eq!(stats.page_free_calls, 0); assert_eq!(stats.reserved_size, 0); assert_eq!(stats.reserved_used, 0); - let claimed_after_3mb = stats.claimed_pages; // SAFETY: Allocation was returned by fsb for this layout. unsafe { @@ -2416,12 +2421,13 @@ mod tests { let stats = fsb.stats(); assert_eq!(stats.pool_allocation_calls, 2); + assert_eq!(stats.large_pool_allocation_calls, 1); assert_eq!(stats.pool_free_calls, 2); assert_eq!(stats.page_allocation_calls, 0); assert_eq!(stats.page_free_calls, 0); assert_eq!(stats.reserved_size, 0); assert_eq!(stats.reserved_used, 0); - assert_eq!(stats.claimed_pages, claimed_after_3mb); + assert_eq!(stats.claimed_pages, initial_claimed); // test that a small page allocation fits in the 1MB free reserved region. let ptr = fsb.allocate_pages(DEFAULT_ALLOCATION_STRATEGY, 0x4, UEFI_PAGE_SIZE).unwrap().as_ptr(); @@ -2440,7 +2446,7 @@ mod tests { assert_eq!(stats.page_free_calls, 0); assert_eq!(stats.reserved_size, 0); assert_eq!(stats.reserved_used, 0); - assert_eq!(stats.claimed_pages, claimed_after_3mb + 0x4); + assert_eq!(stats.claimed_pages, initial_claimed + 0x4); // SAFETY: free_pages uses a valid test allocation pointer and page count. unsafe { @@ -2460,7 +2466,7 @@ mod tests { assert_eq!(stats.page_free_calls, 1); assert_eq!(stats.reserved_size, 0); assert_eq!(stats.reserved_used, 0); - assert_eq!(stats.claimed_pages, claimed_after_3mb); + assert_eq!(stats.claimed_pages, initial_claimed); //test that a lage page allocation results in more claimed pages. let ptr = fsb.allocate_pages(DEFAULT_ALLOCATION_STRATEGY, 0x104, UEFI_PAGE_SIZE).unwrap().as_ptr(); @@ -2479,7 +2485,7 @@ mod tests { assert_eq!(stats.page_free_calls, 1); assert_eq!(stats.reserved_size, 0); assert_eq!(stats.reserved_used, 0); - assert_eq!(stats.claimed_pages, claimed_after_3mb + 0x104); + assert_eq!(stats.claimed_pages, initial_claimed + 0x104); // test that a small page allocation fits in the 1MB free reserved region. let ptr1 = fsb.allocate_pages(DEFAULT_ALLOCATION_STRATEGY, 0x4, UEFI_PAGE_SIZE).unwrap().as_ptr(); @@ -2499,7 +2505,7 @@ mod tests { assert_eq!(stats.page_free_calls, 1); assert_eq!(stats.reserved_size, 0); assert_eq!(stats.reserved_used, 0); - assert_eq!(stats.claimed_pages, claimed_after_3mb + 0x104 + 0x4); + assert_eq!(stats.claimed_pages, initial_claimed + 0x104 + 0x4); // SAFETY: free_pages uses a valid test allocation pointer and page count. unsafe { @@ -2523,7 +2529,7 @@ mod tests { assert_eq!(stats.page_free_calls, 3); assert_eq!(stats.reserved_size, 0); assert_eq!(stats.reserved_used, 0); - assert_eq!(stats.claimed_pages, claimed_after_3mb); + assert_eq!(stats.claimed_pages, initial_claimed); }); } @@ -2549,14 +2555,14 @@ mod tests { DEFAULT_ALLOCATION_STRATEGY, GcdMemoryType::SystemMemory, UEFI_PAGE_SHIFT, - DEFAULT_PAGE_ALLOCATION_GRANULARITY, + DEFAULT_PAGE_ALLOCATION_GRANULARITY + UEFI_PAGE_SIZE, DUMMY_HANDLE, None, ) .unwrap() as *mut u8, ) .unwrap(), - DEFAULT_PAGE_ALLOCATION_GRANULARITY, + DEFAULT_PAGE_ALLOCATION_GRANULARITY + UEFI_PAGE_SIZE, )) .unwrap(); } @@ -2628,6 +2634,217 @@ mod tests { .attributes } + use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + const GCD_ALLOCATE: usize = 1; + const GCD_FREE: usize = 2; + const GCD_ATTRIBUTES: usize = 4; + static CHECK_GCD_LOCK: AtomicBool = AtomicBool::new(false); + static GCD_LOCK_OBSERVATIONS: AtomicUsize = AtomicUsize::new(0); + static GCD_OBSERVED_UNLOCKED: AtomicBool = AtomicBool::new(false); + static LOCK_CHECK_GCD: SpinLockedGcd = SpinLockedGcd::new(Some(observe_fsb_guard)); + static LOCK_CHECK_FSB: SpinLockedFixedSizeBlockAllocator = SpinLockedFixedSizeBlockAllocator::new( + &LOCK_CHECK_GCD, + DUMMY_HANDLE, + efi::BOOT_SERVICES_DATA, + DEFAULT_PAGE_ALLOCATION_GRANULARITY, + HIGH_TRAFFIC_ALLOC_MIN_EXPANSION, + ); + + fn observe_fsb_guard(change: gcd::MapChangeType) { + if !CHECK_GCD_LOCK.load(Ordering::Relaxed) { + return; + } + let observation = match change { + gcd::MapChangeType::AllocateMemorySpace => GCD_ALLOCATE, + gcd::MapChangeType::FreeMemorySpace => GCD_FREE, + gcd::MapChangeType::SetMemoryAttributes => GCD_ATTRIBUTES, + _ => return, + }; + GCD_LOCK_OBSERVATIONS.fetch_or(observation, Ordering::Relaxed); + if LOCK_CHECK_FSB.inner.try_lock().is_some() { + GCD_OBSERVED_UNLOCKED.store(true, Ordering::Relaxed); + } + } + + fn init_fsb_guard_check(granularity: usize) { + CHECK_GCD_LOCK.store(false, Ordering::Relaxed); + LOCK_CHECK_FSB.reset(); + LOCK_CHECK_FSB.lock().page_allocation_granularity = granularity; + init_gcd(&LOCK_CHECK_GCD, 0x400000); + GCD_LOCK_OBSERVATIONS.store(0, Ordering::Relaxed); + GCD_OBSERVED_UNLOCKED.store(false, Ordering::Relaxed); + CHECK_GCD_LOCK.store(true, Ordering::Relaxed); + } + + fn assert_fsb_guard_observations(expected: usize) { + assert_eq!(GCD_LOCK_OBSERVATIONS.swap(0, Ordering::Relaxed), expected); + assert!(!GCD_OBSERVED_UNLOCKED.load(Ordering::Relaxed)); + } + + #[test] + fn test_fsb_pool_expansion_retirement_and_reclaim_hold_guard() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + init_fsb_guard_check(granularity); + let layout = Layout::from_size_align(UEFI_PAGE_SIZE, UEFI_PAGE_SIZE).unwrap(); + let allocation = LOCK_CHECK_FSB.allocate(layout).unwrap().cast::(); + assert_fsb_guard_observations(GCD_ALLOCATE | GCD_ATTRIBUTES); + assert_eq!(LOCK_CHECK_FSB.stats().pool_allocation_calls, 1); + assert_eq!(page_attributes(&LOCK_CHECK_GCD, allocation.addr().get()) & efi::MEMORY_RP, 0); + let retired = LOCK_CHECK_FSB.stats().retired_pages; + + // SAFETY: allocation is live and was returned by this allocator for layout. + unsafe { LOCK_CHECK_FSB.deallocate(allocation, layout) }; + assert_fsb_guard_observations(GCD_ATTRIBUTES); + assert_eq!(LOCK_CHECK_FSB.stats().retired_pages, retired + 1); + assert_eq!(LOCK_CHECK_FSB.lock().pending_retirement(usize::MAX), None); + assert_eq!(page_attributes(&LOCK_CHECK_GCD, allocation.addr().get()) & efi::MEMORY_RP, efi::MEMORY_RP); + + let reclaimed = LOCK_CHECK_FSB.stats().reclaimed_pages; + let allocation = LOCK_CHECK_FSB.allocate(layout).unwrap().cast::(); + assert_fsb_guard_observations(GCD_ATTRIBUTES); + assert_eq!(LOCK_CHECK_FSB.stats().reclaimed_pages, reclaimed + 1); + assert_eq!(page_attributes(&LOCK_CHECK_GCD, allocation.addr().get()) & efi::MEMORY_RP, 0); + // SAFETY: allocation is live and was returned by this allocator for layout. + unsafe { LOCK_CHECK_FSB.deallocate(allocation, layout) }; + assert_fsb_guard_observations(GCD_ATTRIBUTES); + CHECK_GCD_LOCK.store(false, Ordering::Relaxed); + }); + }); + } + + #[test] + fn test_fsb_large_pool_and_direct_page_calls_hold_guard() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + init_fsb_guard_check(granularity); + let layout = Layout::from_size_align(MAX_RETAINED_POOL_SIZE + 1, UEFI_PAGE_SIZE).unwrap(); + let allocation = LOCK_CHECK_FSB.allocate(layout).unwrap().cast::(); + assert_fsb_guard_observations(GCD_ALLOCATE | GCD_ATTRIBUTES); + assert_eq!(LOCK_CHECK_FSB.stats().large_pool_allocation_calls, 1); + // SAFETY: allocation is live and was returned by this allocator for layout. + unsafe { LOCK_CHECK_FSB.deallocate(allocation, layout) }; + assert_fsb_guard_observations(GCD_FREE); + assert_eq!(LOCK_CHECK_FSB.stats().claimed_pages, 0); + + let allocation = LOCK_CHECK_FSB.allocate_pages(DEFAULT_ALLOCATION_STRATEGY, 1, UEFI_PAGE_SIZE).unwrap(); + assert_fsb_guard_observations(GCD_ALLOCATE | GCD_ATTRIBUTES); + assert_eq!(LOCK_CHECK_FSB.stats().claimed_pages, uefi_size_to_pages!(granularity)); + // SAFETY: the live page allocation was returned by this allocator for one page. + unsafe { LOCK_CHECK_FSB.free_pages(allocation.addr().get(), 1).unwrap() }; + assert_fsb_guard_observations(GCD_FREE); + assert_eq!(LOCK_CHECK_FSB.stats().claimed_pages, 0); + CHECK_GCD_LOCK.store(false, Ordering::Relaxed); + }); + }); + } + + #[test] + fn test_fsb_memory_map_event_observes_final_state_after_unlock() { + use crate::events::EVENT_DB; + + struct Observation<'a> { + fsb: &'a SpinLockedFixedSizeBlockAllocator, + calls: usize, + stats: Option, + range: Option>, + pending_retirement: bool, + observed_locked: bool, + tpl: efi::Tpl, + } + + extern "efiapi" fn observe_final_state(_event: efi::Event, context: *mut c_void) { + // SAFETY: the registered context points to a live Observation until the event is closed. + let observation = unsafe { &mut *context.cast::>() }; + observation.calls += 1; + observation.tpl = crate::events::raise_tpl(efi::TPL_HIGH_LEVEL); + crate::events::restore_tpl(observation.tpl); + if let Some(allocator) = observation.fsb.inner.try_lock() { + observation.stats = Some(*allocator.stats()); + observation.range = allocator.get_memory_ranges().next(); + observation.pending_retirement = allocator.pending_retirement(usize::MAX).is_some(); + } else { + observation.observed_locked = true; + } + } + + fn assert_final_state(observation: &Observation<'_>, calls: usize) { + assert_eq!(observation.calls, calls); + assert!(!observation.observed_locked); + assert!(!observation.pending_retirement); + assert_eq!(observation.tpl, efi::TPL_CALLBACK); + assert_eq!(std::format!("{:?}", observation.stats.unwrap()), std::format!("{:?}", observation.fsb.stats())); + assert_eq!(observation.range, observation.fsb.lock().get_memory_ranges().next()); + } + + with_granularity_modulation(|granularity| { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(Some(crate::events::gcd_map_change)); + init_gcd(&GCD, 0x400000); + let fsb = SpinLockedFixedSizeBlockAllocator::new( + &GCD, + DUMMY_HANDLE, + efi::BOOT_SERVICES_DATA, + granularity, + HIGH_TRAFFIC_ALLOC_MIN_EXPANSION, + ); + let mut observation = Observation { + fsb: &fsb, + calls: 0, + stats: None, + range: None, + pending_retirement: false, + observed_locked: false, + tpl: efi::TPL_APPLICATION, + }; + let event = EVENT_DB + .create_event( + efi::EVT_NOTIFY_SIGNAL, + efi::TPL_CALLBACK, + Some(observe_final_state), + Some(core::ptr::from_mut(&mut observation).cast()), + Some(efi::EVENT_GROUP_MEMORY_MAP_CHANGE), + ) + .unwrap(); + + let allocator = fsb.lock(); + crate::events::gcd_map_change(gcd::MapChangeType::AllocateMemorySpace); + assert_eq!(observation.calls, 0); + drop(allocator); + assert_final_state(&observation, 1); + + let layout = Layout::from_size_align(UEFI_PAGE_SIZE, UEFI_PAGE_SIZE).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + assert_final_state(&observation, 2); + assert_eq!(observation.stats.unwrap().pool_allocation_calls, 1); + assert!(observation.stats.unwrap().retired_pages > 0); + assert!(observation.range.as_ref().unwrap().contains(&allocation.addr().get())); + // SAFETY: allocation is live and was returned by fsb for layout. + unsafe { fsb.deallocate(allocation, layout) }; + assert_eq!(observation.calls, 2); + + let layout = Layout::from_size_align(MAX_RETAINED_POOL_SIZE + 1, UEFI_PAGE_SIZE).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + assert_final_state(&observation, 3); + assert_eq!(observation.stats.unwrap().large_pool_allocation_calls, 1); + // SAFETY: allocation is live and was returned by fsb for layout. + unsafe { fsb.deallocate(allocation, layout) }; + assert_final_state(&observation, 4); + assert_eq!(observation.stats.unwrap().pool_free_calls, 2); + + let allocation = fsb.allocate_pages(DEFAULT_ALLOCATION_STRATEGY, 1, UEFI_PAGE_SIZE).unwrap(); + assert_final_state(&observation, 5); + assert_eq!(observation.stats.unwrap().page_allocation_calls, 1); + // SAFETY: the live page allocation was returned by fsb for one page. + unsafe { fsb.free_pages(allocation.addr().get(), 1).unwrap() }; + assert_final_state(&observation, 6); + assert_eq!(observation.stats.unwrap().page_free_calls, 1); + EVENT_DB.close_event(event).unwrap(); + }); + }); + } + #[test] fn test_free_list_recycles_blocks_in_first_in_first_out_order() { with_locked_state(|| { @@ -2654,6 +2871,237 @@ mod tests { }); } + #[test] + fn test_fsb_expansion_never_allocates_from_metadata_pages() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + init_gcd(&GCD, 0x400000); + let fsb = SpinLockedFixedSizeBlockAllocator::new( + &GCD, + DUMMY_HANDLE, + efi::BOOT_SERVICES_DATA, + granularity, + 4 * UEFI_PAGE_SIZE, + ); + let layout = Layout::from_size_align(2048, 2048).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + let (region, whole_pages) = { + let allocator = fsb.lock(); + let node = allocator.allocators.unwrap(); + // SAFETY: the lock keeps this allocator's permanently mapped region metadata accessible. + let node = unsafe { &*node }; + let region = node.region_base()..node.region_base() + node.region_size; + let whole_pages = node.first_page_base()..region.end; + assert!(whole_pages.contains(&allocation.addr().get())); + assert!(allocation.addr().get().is_multiple_of(layout.align())); + (region, whole_pages) + }; + let before = fsb.stats(); + assert_eq!(before.pool_allocation_calls, 1); + assert_eq!(before.reclaimed_pages, 0); + assert_eq!(before.retired_pages, whole_pages.len() / UEFI_PAGE_SIZE - 1); + assert!(!whole_pages.is_empty()); + assert_eq!(page_attributes(&GCD, region.start) & efi::MEMORY_RP, 0); + for page in whole_pages.clone().step_by(UEFI_PAGE_SIZE) { + let expected = if page == whole_pages.start { 0 } else { efi::MEMORY_RP }; + assert_eq!(page_attributes(&GCD, page) & efi::MEMORY_RP, expected); + } + let page_layout = Layout::from_size_align(UEFI_PAGE_SIZE, UEFI_PAGE_SIZE).unwrap(); + let reclaimed = fsb.allocate(page_layout).unwrap().cast::(); + assert!(whole_pages.contains(&reclaimed.addr().get())); + assert_eq!(page_attributes(&GCD, reclaimed.addr().get()) & efi::MEMORY_RP, 0); + assert_eq!(fsb.stats().claimed_pages, before.claimed_pages); + assert_eq!(fsb.stats().reclaimed_pages, 1); + assert_eq!(fsb.get_memory_ranges().count(), 1); + // SAFETY: both pointers are live and were returned by this allocator for their respective layouts. + unsafe { + fsb.deallocate(reclaimed, page_layout); + fsb.deallocate(allocation, layout); + } + for page in whole_pages.step_by(UEFI_PAGE_SIZE) { + assert_eq!(page_attributes(&GCD, page) & efi::MEMORY_RP, efi::MEMORY_RP); + } + assert_eq!(page_attributes(&GCD, region.start) & efi::MEMORY_RP, 0); + }); + }); + } + + #[test] + fn test_fsb_live_occupancy_matches_page_retirement_across_regions() { + fn assert_page_occupancy(fsb: &SpinLockedFixedSizeBlockAllocator, live: &[(NonNull, Layout)]) { + let allocator = fsb.lock(); + let regions: Vec<_> = allocator.get_memory_ranges().collect(); + + for (allocation, layout) in live { + let start = allocation.addr().get(); + let end = start + layout.size().max(layout.align()).max(8).next_power_of_two(); + assert!(start.is_multiple_of(layout.align())); + assert!(regions.iter().any(|region| region.start <= start && end <= region.end)); + assert_eq!(live.iter().filter(|(other, _)| other == allocation).count(), 1); + for (other, other_layout) in live { + if other != allocation { + let other_start = other.addr().get(); + let other_end = + other_start + other_layout.size().max(other_layout.align()).max(8).next_power_of_two(); + assert!(end <= other_start || other_end <= start, "live allocations overlap"); + } + } + } + + for region in regions { + let page_count = region.len() / UEFI_PAGE_SIZE; + let metadata_size = Layout::new::() + .extend(Layout::array::(page_count).unwrap()) + .unwrap() + .0 + .pad_to_align() + .size(); + let metadata_end = region.start + metadata_size; + let node = + AllocatorIterator::new(allocator.allocators).find(|node| node.addr() == region.start).unwrap(); + // SAFETY: the locked allocator owns every node yielded by its iterator. + let node = unsafe { &*node }; + + for (page_index, page_base) in region.step_by(UEFI_PAGE_SIZE).enumerate() { + let metadata = page_base < metadata_end; + let occupied = live.iter().any(|(allocation, layout)| { + let start = allocation.addr().get(); + let end = start + layout.size().max(layout.align()).max(8).next_power_of_two(); + start < page_base + UEFI_PAGE_SIZE && page_base < end + }); + let should_retire = !metadata && !occupied; + let state = node.page_free_bytes[page_index]; + assert_eq!( + page_attributes(fsb.gcd, page_base) & efi::MEMORY_RP, + if should_retire { efi::MEMORY_RP } else { 0 }, + "page {page_base:#x}: metadata={metadata}, occupied={occupied}, state={state}, live={}, granularity={}", + live.len(), + allocator.page_allocation_granularity + ); + if should_retire { + assert_eq!(state, AllocatorListNode::RETIRED_PAGE, "empty page {page_base:#x}"); + } else { + assert!(state < AllocatorListNode::RETIRED_PAGE, "active page {page_base:#x}: {state}"); + } + } + } + } + + fn allocate_live( + fsb: &SpinLockedFixedSizeBlockAllocator, + live: &mut Vec<(NonNull, Layout)>, + layout: Layout, + ) { + live.push((fsb.allocate(layout).unwrap().cast::(), layout)); + assert_page_occupancy(fsb, live); + } + + fn free_live( + fsb: &SpinLockedFixedSizeBlockAllocator, + live: &mut Vec<(NonNull, Layout)>, + index: usize, + ) -> (NonNull, Layout) { + let (allocation, layout) = live.remove(index); + // SAFETY: the independent live ledger contains this allocator's still-live pointer and original layout. + unsafe { fsb.deallocate(allocation, layout) }; + assert_page_occupancy(fsb, live); + (allocation, layout) + } + + with_granularity_modulation(|granularity| { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + init_gcd(&GCD, 0x400000); + let fsb = SpinLockedFixedSizeBlockAllocator::new( + &GCD, + DUMMY_HANDLE, + efi::BOOT_SERVICES_DATA, + granularity, + 4 * UEFI_PAGE_SIZE, + ); + let layouts: Vec<_> = [ + (8, 8), + (24, 16), + (49, 32), + (65, 32), + (129, 64), + (300, 64), + (900, 128), + (1500, 256), + (17, 2048), + (2049, 512), + (3073, 4096), + ] + .into_iter() + .map(|(size, alignment)| Layout::from_size_align(size, alignment).unwrap()) + .collect(); + let mut live = Vec::new(); + assert_page_occupancy(&fsb, &live); + for _ in 0..24 { + for layout in &layouts { + allocate_live(&fsb, &mut live, *layout); + } + } + let regions: Vec<_> = fsb.get_memory_ranges().collect(); + assert!(regions.len() >= 3, "workload must force multiple expansions"); + assert!(regions.iter().all(|region| live.iter().any(|(ptr, _)| region.contains(&ptr.addr().get())))); + + let mut freed = Vec::new(); + for index in (0..live.len()).rev().step_by(3) { + freed.push(free_live(&fsb, &mut live, index)); + } + for (_, layout) in &freed { + allocate_live(&fsb, &mut live, *layout); + } + let previously_used: Vec<_> = live.iter().map(|(ptr, _)| ptr.addr().get() & !UEFI_PAGE_MASK).collect(); + while !live.is_empty() { + let index = live.len() / 2; + free_live(&fsb, &mut live, index); + } + + let reclaimed_before = fsb.stats().reclaimed_pages; + for _ in 0..24 { + for layout in layouts.iter().rev() { + allocate_live(&fsb, &mut live, *layout); + } + } + assert!(fsb.stats().reclaimed_pages > reclaimed_before); + assert!(live.iter().any(|(ptr, _)| previously_used.contains(&(ptr.addr().get() & !UEFI_PAGE_MASK)))); + while !live.is_empty() { + free_live(&fsb, &mut live, 0); + } + }); + }); + } + + #[test] + fn test_fsb_eight_byte_blocks_fill_and_retire_page() { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + let fsb = fsb_with_gcd(&GCD); + let layout = Layout::from_size_align(8, 8).unwrap(); + let allocations: Vec<_> = + (0..UEFI_PAGE_SIZE / 8).map(|_| fsb.allocate(layout).unwrap().cast::()).collect(); + let page_base = allocations[0].addr().get(); + assert!(page_base.is_multiple_of(UEFI_PAGE_SIZE)); + for (index, allocation) in allocations.iter().enumerate() { + assert_eq!(allocation.addr().get(), page_base + index * 8); + } + let retired = fsb.stats().retired_pages; + for allocation in allocations { + // SAFETY: each allocation is live and was returned by fsb for this layout. + unsafe { fsb.deallocate(allocation, layout) }; + } + assert_eq!(fsb.stats().retired_pages, retired + 1); + assert_eq!(page_attributes(&GCD, page_base) & efi::MEMORY_RP, efi::MEMORY_RP); + let reclaimed = fsb.allocate(layout).unwrap().cast::(); + assert_eq!(reclaimed.addr().get(), page_base); + // SAFETY: reclaimed was returned by fsb for this layout and has not been freed. + unsafe { fsb.deallocate(reclaimed, layout) }; + }); + } + #[test] fn test_fully_freed_page_is_retired_and_unmapped() { with_locked_state(|| { @@ -2674,10 +3122,6 @@ mod tests { assert_eq!(fsb.stats().retired_pages, retired + 1); assert_eq!(page_attributes(&GCD, page_base) & efi::MEMORY_RP, efi::MEMORY_RP); - - // The retired page is out of circulation, so it is not handed back out. - let next = fsb.allocate(layout).unwrap().cast::(); - assert_ne!(next.addr().get(), page_base); }); } @@ -2688,15 +3132,20 @@ mod tests { let fsb = fsb_with_gcd(&GCD); let small = Layout::from_size_align(0x20, 0x20).unwrap(); - let allocation = fsb.allocate(small).unwrap().cast::(); - let page_base = align_down_size(allocation.addr().get(), UEFI_PAGE_SIZE); + let first = fsb.allocate(small).unwrap().cast::(); + let second = fsb.allocate(small).unwrap().cast::(); + let page_base = first.addr().get() & !UEFI_PAGE_MASK; + assert_eq!(second.addr().get() & !UEFI_PAGE_MASK, page_base); let retired = fsb.stats().retired_pages; - // SAFETY: allocation was returned by fsb for this layout. - unsafe { fsb.deallocate(allocation, small) }; + // SAFETY: first was returned by fsb for this layout. + unsafe { fsb.deallocate(first, small) }; assert_eq!(fsb.stats().retired_pages, retired); assert_eq!(page_attributes(&GCD, page_base) & efi::MEMORY_RP, 0); + + // SAFETY: second was returned by fsb for this layout. + unsafe { fsb.deallocate(second, small) }; }); } @@ -2706,7 +3155,7 @@ mod tests { static GCD: SpinLockedGcd = SpinLockedGcd::new(None); let fsb = fsb_with_gcd(&GCD); let allocation = fsb.allocate(Layout::from_size_align(0x20, 0x20).unwrap()).unwrap().cast::(); - let first_page = align_down_size(allocation.addr().get(), UEFI_PAGE_SIZE); + let first_page = allocation.addr().get() & !UEFI_PAGE_MASK; let second_page = first_page + UEFI_PAGE_SIZE; assert_eq!( @@ -2718,7 +3167,7 @@ mod tests { Err(EfiError::NotReady) ); - fsb.update_page_attributes(&(first_page..second_page + UEFI_PAGE_SIZE), true).unwrap(); + fsb.lock().update_page_attributes(&GCD, &(first_page..second_page + UEFI_PAGE_SIZE), true).unwrap(); assert_eq!(page_attributes(&GCD, first_page), efi::MEMORY_WB | efi::MEMORY_XP | efi::MEMORY_RP); assert_eq!(page_attributes(&GCD, second_page), efi::MEMORY_WB | efi::MEMORY_XP | efi::MEMORY_RP); @@ -2753,7 +3202,11 @@ mod tests { GCD.memory_protection_policy.apply_allocated_memory_protection_policy(0, GcdMemoryType::SystemMemory); assert_eq!(page_attributes(&GCD, allocation), allocated_attributes); - let result = fsb.update_page_attributes(&(allocation..allocation + uefi_pages_to_size!(pages + 1)), true); + let result = fsb.lock().update_page_attributes( + &GCD, + &(allocation..allocation + uefi_pages_to_size!(pages + 1)), + true, + ); assert!(result.is_err()); assert_eq!(page_attributes(&GCD, allocation), allocated_attributes); @@ -2761,22 +3214,308 @@ mod tests { } #[test] - fn test_page_holding_a_large_allocation_is_not_retired() { + fn test_fsb_large_allocation_size() { + for (size, alignment, expected) in [ + (UEFI_PAGE_SIZE + 1, 8, 2 * UEFI_PAGE_SIZE), + (2 * UEFI_PAGE_SIZE, UEFI_PAGE_SIZE, 4 * UEFI_PAGE_SIZE), + (UEFI_PAGE_SIZE + 1, SIZE_64KB, SIZE_64KB + 2 * UEFI_PAGE_SIZE), + ] { + let layout = Layout::from_size_align(size, alignment).unwrap(); + assert_eq!(LargeAllocationNode::allocation_size(layout, UEFI_PAGE_SIZE), Some(expected)); + } + let layout = Layout::from_size_align(isize::MAX as usize, 1).unwrap(); + assert_eq!(LargeAllocationNode::allocation_size(layout, 1usize << (usize::BITS - 1)), None); + } + + #[test] + fn test_fsb_large_allocation_rejects_corrupted_size() { with_locked_state(|| { static GCD: SpinLockedGcd = SpinLockedGcd::new(None); let fsb = fsb_with_gcd(&GCD); + let layout = Layout::from_size_align(MAX_RETAINED_POOL_SIZE + 1, 8).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + let claimed = fsb.stats().claimed_pages; + // SAFETY: this live large allocation has a writable header immediately before its user pointer. + let node = unsafe { allocation.cast::().as_ptr().sub(1) }; + // SAFETY: node points to the live header, and the allocator is not accessed concurrently. + let original_size = unsafe { + let original_size = (*node).size; + (*node).size += UEFI_PAGE_SIZE; + original_size + }; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + // SAFETY: allocation is live and layout is the original allocation layout. + unsafe { fsb.deallocate(allocation, layout) }; + })); + assert_eq!(result.is_err(), cfg!(debug_assertions)); + assert_eq!(fsb.stats().claimed_pages, claimed); + // SAFETY: rejected deallocation left the allocation and its header live. + unsafe { + (*node).size = original_size; + fsb.deallocate(allocation, layout); + } + assert_eq!(fsb.stats().claimed_pages, 0); + }); + } - // Allocations larger than the largest block size are not tracked for retirement. - let large = Layout::from_size_align(UEFI_PAGE_SIZE * 2, UEFI_PAGE_SIZE).unwrap(); + #[test] + fn test_large_allocation_is_freed_directly_to_gcd() { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + let fsb = fsb_with_gcd(&GCD); + + let large = Layout::from_size_align(MAX_RETAINED_POOL_SIZE + 1, UEFI_PAGE_SIZE).unwrap(); let allocation = fsb.allocate(large).unwrap().cast::(); let page_base = allocation.addr().get(); let retired = fsb.stats().retired_pages; + assert_eq!(fsb.stats().large_pool_allocation_calls, 1); + assert!(fsb.stats().claimed_pages > 0); + assert_eq!(page_attributes(&GCD, page_base) & efi::MEMORY_RP, 0); // SAFETY: allocation was returned by fsb for this layout. unsafe { fsb.deallocate(allocation, large) }; assert_eq!(fsb.stats().retired_pages, retired); - assert_eq!(page_attributes(&GCD, page_base) & efi::MEMORY_RP, 0); + assert_eq!(fsb.stats().claimed_pages, 0); + assert_eq!(page_attributes(&GCD, page_base) & efi::MEMORY_RP, efi::MEMORY_RP); + }); + } + + #[test] + fn test_large_allocations_support_user_alignment() { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + let fsb = fsb_with_gcd(&GCD); + + for alignment in [8, UEFI_PAGE_SIZE, SIZE_64KB, SIZE_64KB * 2] { + let layout = Layout::from_size_align(MAX_RETAINED_POOL_SIZE + 1, alignment).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + + assert!(allocation.addr().get().is_multiple_of(alignment)); + + // SAFETY: allocation was returned by fsb for this layout. + unsafe { fsb.deallocate(allocation, layout) }; + assert_eq!(fsb.stats().claimed_pages, 0); + } + + assert_eq!(fsb.stats().large_pool_allocation_calls, 4); + }); + } + + #[test] + fn test_fsb_medium_pool_packs_retires_and_reuses_page_runs() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + init_gcd(&GCD, 0x400000); + let fsb = SpinLockedFixedSizeBlockAllocator::new( + &GCD, + DUMMY_HANDLE, + efi::RUNTIME_SERVICES_DATA, + granularity, + SIZE_64KB, + ); + let layout = Layout::from_size_align(9 * 1024, 8).unwrap(); + let allocations: Vec<_> = (0..5).map(|_| fsb.allocate(layout).unwrap().cast::()).collect(); + let region = fsb.get_memory_ranges().next().unwrap(); + assert_eq!(region.len(), SIZE_64KB); + assert_eq!(fsb.get_memory_ranges().count(), 1); + assert_eq!(fsb.stats().retired_pages - fsb.stats().reclaimed_pages, 0); + assert_eq!(fsb.stats().claimed_pages, 16); + for pair in allocations.windows(2) { + assert_eq!(pair[1].addr().get() - pair[0].addr().get(), 3 * UEFI_PAGE_SIZE); + } + let retired = fsb.stats().retired_pages; + // SAFETY: both allocations are live and were returned for layout. + unsafe { + fsb.deallocate(allocations[0], layout); + fsb.deallocate(allocations[1], layout); + } + assert_eq!(fsb.stats().retired_pages, retired + 6); + for page in (allocations[0].addr().get()..allocations[2].addr().get()).step_by(UEFI_PAGE_SIZE) { + assert_eq!(page_attributes(&GCD, page) & efi::MEMORY_RP, efi::MEMORY_RP); + } + for allocation in &allocations[2..] { + for offset in (0..3 * UEFI_PAGE_SIZE).step_by(UEFI_PAGE_SIZE) { + assert_eq!(page_attributes(&GCD, allocation.addr().get() + offset) & efi::MEMORY_RP, 0); + } + } + let combined_layout = Layout::from_size_align(6 * UEFI_PAGE_SIZE, UEFI_PAGE_SIZE).unwrap(); + let combined = fsb.allocate(combined_layout).unwrap().cast::(); + assert_eq!(combined, allocations[0]); + assert_eq!(fsb.stats().claimed_pages, 16); + assert_eq!(fsb.stats().retired_pages - fsb.stats().reclaimed_pages, 0); + // SAFETY: combined and the remaining allocations are live with their original layouts. + unsafe { + fsb.deallocate(combined, combined_layout); + for allocation in &allocations[2..] { + fsb.deallocate(*allocation, layout); + } + } + assert_eq!(fsb.stats().retired_pages - fsb.stats().reclaimed_pages, 15); + assert_eq!(fsb.lock().pending_retirement(usize::MAX), None); + assert!(fsb.lock().list_heads.iter().all(Option::is_none)); + }); + }); + } + + #[test] + fn test_fsb_medium_pool_reuses_run_crossing_retired_cursor() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + init_gcd(&GCD, 0x400000); + let fsb = SpinLockedFixedSizeBlockAllocator::new( + &GCD, + DUMMY_HANDLE, + efi::RUNTIME_SERVICES_DATA, + granularity, + SIZE_64KB, + ); + let layout = Layout::from_size_align(9 * 1024, 8).unwrap(); + let first = fsb.allocate(layout).unwrap().cast::(); + let second = fsb.allocate(layout).unwrap().cast::(); + let claimed = fsb.stats().claimed_pages; + // SAFETY: both allocations are live and were returned for layout. + unsafe { + fsb.deallocate(first, layout); + fsb.deallocate(second, layout); + } + let layout = Layout::from_size_align(15 * UEFI_PAGE_SIZE, 8).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + assert_eq!(allocation, first); + assert_eq!(fsb.stats().claimed_pages, claimed); + assert_eq!(fsb.get_memory_ranges().count(), 1); + // SAFETY: allocation is live and was returned for layout. + unsafe { fsb.deallocate(allocation, layout) }; + }); + }); + } + + #[test] + fn test_fsb_medium_pool_maps_only_requested_pages() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + init_gcd(&GCD, 0x400000); + let fsb = SpinLockedFixedSizeBlockAllocator::new( + &GCD, + DUMMY_HANDLE, + efi::RUNTIME_SERVICES_DATA, + granularity, + SIZE_64KB, + ); + let layout = Layout::from_size_align(UEFI_PAGE_SIZE + 1, 8).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + let region = fsb.get_memory_ranges().next().unwrap(); + assert_eq!(region.len(), SIZE_64KB); + assert_eq!(fsb.stats().retired_pages, 13); + for page in (region.start..region.end).step_by(UEFI_PAGE_SIZE) { + let mapped = page == region.start + || (allocation.addr().get()..allocation.addr().get() + 2 * UEFI_PAGE_SIZE).contains(&page); + assert_eq!(page_attributes(&GCD, page) & efi::MEMORY_RP == 0, mapped); + } + // SAFETY: allocation is live and was returned for layout. + unsafe { fsb.deallocate(allocation, layout) }; + assert_eq!(fsb.stats().retired_pages, 15); + assert_eq!(fsb.stats().claimed_pages, 16); + }); + }); + } + + #[test] + fn test_fsb_medium_pool_respects_alignment_on_expansion_and_reclaim() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + init_gcd(&GCD, 0x400000); + let fsb = SpinLockedFixedSizeBlockAllocator::new( + &GCD, + DUMMY_HANDLE, + efi::RUNTIME_SERVICES_DATA, + granularity, + SIZE_64KB, + ); + for alignment in [8, UEFI_PAGE_SIZE, 2 * UEFI_PAGE_SIZE, SIZE_64KB] { + let layout = Layout::from_size_align(UEFI_PAGE_SIZE + 1, alignment).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + assert!(allocation.addr().get().is_multiple_of(alignment)); + let claimed = fsb.stats().claimed_pages; + // SAFETY: allocation is live and was returned for layout. + unsafe { fsb.deallocate(allocation, layout) }; + let allocation = fsb.allocate(layout).unwrap().cast::(); + assert!(allocation.addr().get().is_multiple_of(alignment)); + assert_eq!(fsb.stats().claimed_pages, claimed); + // SAFETY: allocation is live and was returned for layout. + unsafe { fsb.deallocate(allocation, layout) }; + } + }); + }); + } + + #[test] + fn test_fsb_retained_pool_size_and_alignment_boundaries() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + init_gcd(&GCD, 0x400000); + let fsb = SpinLockedFixedSizeBlockAllocator::new( + &GCD, + DUMMY_HANDLE, + efi::RUNTIME_SERVICES_DATA, + granularity, + SIZE_64KB, + ); + let layout = Layout::from_size_align(SIZE_64KB, UEFI_PAGE_SIZE).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + let region = fsb.get_memory_ranges().next().unwrap(); + assert!(region.contains(&allocation.addr().get())); + assert_eq!(region.len(), SIZE_64KB + granularity); + for offset in (0..SIZE_64KB).step_by(UEFI_PAGE_SIZE) { + assert_eq!(page_attributes(&GCD, allocation.addr().get() + offset) & efi::MEMORY_RP, 0); + } + let claimed = fsb.stats().claimed_pages; + // SAFETY: allocation is live and was returned for layout. + unsafe { fsb.deallocate(allocation, layout) }; + for offset in (0..SIZE_64KB).step_by(UEFI_PAGE_SIZE) { + assert_eq!( + page_attributes(&GCD, allocation.addr().get() + offset) & efi::MEMORY_RP, + efi::MEMORY_RP + ); + } + assert_eq!(fsb.stats().claimed_pages, claimed); + let layout = Layout::from_size_align(UEFI_PAGE_SIZE + 1, 2 * SIZE_64KB).unwrap(); + let allocation = fsb.allocate(layout).unwrap().cast::(); + assert!(allocation.addr().get().is_multiple_of(layout.align())); + assert!(!region.contains(&allocation.addr().get())); + assert!(fsb.stats().claimed_pages > claimed); + // SAFETY: allocation is live and was returned for layout. + unsafe { fsb.deallocate(allocation, layout) }; + assert_eq!(fsb.stats().claimed_pages, claimed); + }); + }); + } + + #[test] + fn test_fsb_medium_pool_retirement_and_reclaim_hold_guard() { + with_granularity_modulation(|granularity| { + with_locked_state(|| { + init_fsb_guard_check(granularity); + let layout = Layout::from_size_align(9 * 1024, 8).unwrap(); + let allocation = LOCK_CHECK_FSB.allocate(layout).unwrap().cast::(); + assert_fsb_guard_observations(GCD_ALLOCATE | GCD_ATTRIBUTES); + let retired = LOCK_CHECK_FSB.stats().retired_pages; + // SAFETY: allocation is live and was returned for layout. + unsafe { LOCK_CHECK_FSB.deallocate(allocation, layout) }; + assert_fsb_guard_observations(GCD_ATTRIBUTES); + assert_eq!(LOCK_CHECK_FSB.stats().retired_pages, retired + 3); + let allocation = LOCK_CHECK_FSB.allocate(layout).unwrap().cast::(); + assert_fsb_guard_observations(GCD_ATTRIBUTES); + // SAFETY: allocation is live and was returned for layout. + unsafe { LOCK_CHECK_FSB.deallocate(allocation, layout) }; + assert_fsb_guard_observations(GCD_ATTRIBUTES); + CHECK_GCD_LOCK.store(false, Ordering::Relaxed); + }); }); } @@ -2821,31 +3560,12 @@ mod tests { unsafe { fsb.deallocate(allocation, layout) }; assert_eq!(page_attributes(&GCD, page_base) & efi::MEMORY_RP, efi::MEMORY_RP); - // The freed page is the lowest retired page, so it is the next one brought back into service. + // The freed page is the lowest retired page, so the next allocation brings it back into service. let reclaimed = fsb.stats().reclaimed_pages; - assert!(fsb.reclaim_pages(1)); + let next = fsb.allocate(layout).unwrap().cast::(); assert_eq!(fsb.stats().reclaimed_pages, reclaimed + 1); assert_eq!(page_attributes(&GCD, page_base) & efi::MEMORY_RP, 0); - - // The reclaimed memory is available again. - assert_eq!(fsb.allocate(layout).unwrap().cast::().addr().get(), page_base); - }); - } - - #[test] - fn test_reclaim_pages_restores_all_requested_pages() { - with_locked_state(|| { - static GCD: SpinLockedGcd = SpinLockedGcd::new(None); - let fsb = fsb_with_gcd(&GCD); - - let layout = Layout::from_size_align(0x20, 0x20).unwrap(); - let _allocation = fsb.allocate(layout).unwrap(); - let retired_pages = fsb.stats().retired_pages; - assert!(retired_pages > 1); - - let reclaimed = fsb.stats().reclaimed_pages; - assert!(fsb.reclaim_pages(retired_pages)); - assert_eq!(fsb.stats().reclaimed_pages, reclaimed + retired_pages); + assert_eq!(next.addr().get(), page_base); }); } @@ -2905,8 +3625,9 @@ mod tests { fsb.mark_pages_retired(pages.clone()); assert_eq!(fsb.find_retired_pages(uefi_size_to_pages!(pages.len())), Some(pages.clone())); - // Restoring them puts them back into the backing allocator. - fsb.restore_pages(pages); + // Restoring and splitting one page makes it available to the fixed-size allocator again. + fsb.restore_pages(pages.start..pages.start + UEFI_PAGE_SIZE); + fsb.add_page_to_fsb(pages.start, UEFI_PAGE_SIZE).unwrap(); assert_eq!(fsb.find_retired_pages(usize::MAX), None); assert!(fsb.alloc(Layout::from_size_align(UEFI_PAGE_SIZE, UEFI_PAGE_SIZE).unwrap()).is_ok()); }); diff --git a/patina_dxe_core/src/allocator/uefi_allocator.rs b/patina_dxe_core/src/allocator/uefi_allocator.rs index ae55a86b08..71ce7208a9 100644 --- a/patina_dxe_core/src/allocator/uefi_allocator.rs +++ b/patina_dxe_core/src/allocator/uefi_allocator.rs @@ -57,14 +57,6 @@ where self.allocator.reset(); } - /// Indicates whether the given pointer falls within a memory region managed by this allocator. - /// - /// See [`SpinLockedFixedSizeBlockAllocator::contains`] - #[allow(dead_code)] - pub fn contains(&self, ptr: NonNull) -> bool { - self.allocator.contains(ptr) - } - /// Returns the UEFI memory type associated with this allocator. pub fn memory_type(&self) -> efi::MemoryType { self.memory_type @@ -597,30 +589,6 @@ mod tests { }); } - #[test] - fn test_contains() { - with_locked_state(|| { - // Create a static GCD - static GCD: SpinLockedGcd = SpinLockedGcd::new(None); - - // Allocate some space on the heap with the global allocator (std) to be used by expand(). - init_gcd(&GCD, 0x400000); - - let fsb = SpinLockedFixedSizeBlockAllocator::new( - &GCD, - 1 as _, - efi::BOOT_SERVICES_DATA, - DEFAULT_PAGE_ALLOCATION_GRANULARITY, - HIGH_TRAFFIC_ALLOC_MIN_EXPANSION, - ); - let ua = UefiAllocator::new(fsb, efi::BOOT_SERVICES_DATA); - - let layout = Layout::from_size_align(0x8, 0x8).unwrap(); - let allocation = ua.allocate(layout).unwrap().cast::(); - assert!(ua.contains(allocation)); - }); - } - #[test] fn test_uefi_allocator_fn_conformance() { with_locked_state(|| { @@ -650,6 +618,7 @@ mod tests { "Bucket Range: None\r\n", "Allocation Stats:\r\n", " pool_allocation_calls: 0\r\n", + " large_pool_allocation_calls: 0\r\n", " pool_free_calls: 0\r\n", " page_allocation_calls: 0\r\n", " page_free_calls: 0\r\n", diff --git a/patina_dxe_core/src/config_tables/memory_attributes_table.rs b/patina_dxe_core/src/config_tables/memory_attributes_table.rs index f68b155b57..146980983c 100644 --- a/patina_dxe_core/src/config_tables/memory_attributes_table.rs +++ b/patina_dxe_core/src/config_tables/memory_attributes_table.rs @@ -351,8 +351,10 @@ mod tests { let mat = &*(mat_ptr.as_ptr() as *const efi::MemoryAttributesTable); assert_eq!(mat.version, efi::MEMORY_ATTRIBUTES_TABLE_VERSION); - // we have one extra entry here because init_system_table allocates runtime pages - assert_eq!(mat.number_of_entries, entry_count as u32 + 1); + // init_system_table contributes at least one entry. Runtime-pool retirement can split allocator-owned + // ranges into additional descriptors, so validate the requested allocations below instead of requiring + // an exact descriptor count. + assert!(mat.number_of_entries > entry_count as u32); assert_eq!(mat.descriptor_size, size_of::() as u32); let entry_slice = slice::from_raw_parts(mat.entry.as_ptr(), mat.number_of_entries as usize); diff --git a/patina_dxe_core/src/core_patina_tests/allocator_tests.rs b/patina_dxe_core/src/core_patina_tests/allocator_tests.rs index 744cdc20af..e8980ea0f6 100644 --- a/patina_dxe_core/src/core_patina_tests/allocator_tests.rs +++ b/patina_dxe_core/src/core_patina_tests/allocator_tests.rs @@ -37,6 +37,293 @@ fn page_attributes(address: usize) -> Result { .map_err(|_| "No GCD descriptor for pool memory") } +#[cfg(target_os = "uefi")] +mod isolated { + use super::{ + Allocator, GCD, Layout, UEFI_PAGE_SIZE, Vec, efi, is_mapped, page_attributes, patina_test, raise_tpl, + restore_tpl, u_assert, u_assert_eq, + }; + use crate::allocator::{DEFAULT_PAGE_ALLOCATION_GRANULARITY, SpinLockedFixedSizeBlockAllocator}; + use core::ptr::NonNull; + + struct RaisedTpl(efi::Tpl); + + impl RaisedTpl { + fn new() -> Self { + Self(raise_tpl(efi::TPL_HIGH_LEVEL)) + } + } + + impl Drop for RaisedTpl { + fn drop(&mut self) { + restore_tpl(self.0); + } + } + + struct LiveBlock { + pointer: NonNull, + layout: Layout, + live: bool, + } + + struct Fixture<'owner> { + allocator: Option, + blocks: Vec, + _owner: &'owner u8, + } + + impl<'owner> Fixture<'owner> { + fn new(owner: &'owner u8) -> Self { + Self { + allocator: Some(SpinLockedFixedSizeBlockAllocator::new( + &GCD, + core::ptr::from_ref(owner).cast_mut().cast(), + efi::BOOT_SERVICES_DATA, + DEFAULT_PAGE_ALLOCATION_GRANULARITY, + 16 * UEFI_PAGE_SIZE, + )), + blocks: Vec::new(), + _owner: owner, + } + } + + fn allocator(&self) -> &SpinLockedFixedSizeBlockAllocator { + self.allocator.as_ref().expect("Fixture allocator exists until cleanup") + } + + fn allocate(&mut self, size: usize) -> Result { + let layout = Layout::from_size_align(size, size).map_err(|_| "Bad isolated layout")?; + self.blocks.try_reserve(1).map_err(|_| "Could not reserve test bookkeeping")?; + let pointer = self.allocator().allocate(layout).map_err(|_| "Isolated allocation failed")?.cast::(); + let index = self.blocks.len(); + self.blocks.push(LiveBlock { pointer, layout, live: true }); + Ok(index) + } + + fn page(&self, index: usize) -> usize { + self.blocks.get(index).expect("Index belongs to fixture ledger").pointer.addr().get() + & !(UEFI_PAGE_SIZE - 1) + } + + fn free(&mut self, index: usize) { + let block = self.blocks.get(index).expect("Index belongs to fixture ledger"); + if block.live { + // SAFETY: bookkeeping retains the original pointer and layout, and prevents double frees. + unsafe { self.allocator().deallocate(block.pointer, block.layout) }; + self.blocks.get_mut(index).expect("Index belongs to fixture ledger").live = false; + } + } + + fn check_pages(&self) -> patina_test::error::Result { + for region in self.allocator().get_memory_ranges() { + let metadata = self + .allocator() + .lock() + .firmware_test_metadata_range(region.start) + .ok_or("Missing isolated region metadata")?; + for page in (region.start..region.end).step_by(UEFI_PAGE_SIZE) { + let occupied = metadata.contains(&page) + || self.blocks.iter().any(|block| { + let start = block.pointer.addr().get() & !(UEFI_PAGE_SIZE - 1); + let end = + (block.pointer.addr().get() + block.layout.size()).next_multiple_of(UEFI_PAGE_SIZE); + block.live && (start..end).contains(&page) + }); + u_assert_eq!(is_mapped(page as u64), occupied, "Page table does not match live block occupancy"); + u_assert_eq!( + (page_attributes(page)? & efi::MEMORY_RP == 0), + occupied, + "GCD does not match live block occupancy" + ); + } + } + Ok(()) + } + + fn check_live_bytes(&self) -> patina_test::error::Result { + for block in self.blocks.iter().filter(|block| block.live) { + u_assert!(is_mapped(block.pointer.addr().get() as u64), "Live neighbor is unmapped"); + // SAFETY: the block remains live and writable; its page was checked before access. + unsafe { + core::ptr::write_volatile(block.pointer.as_ptr(), 0xA5); + core::ptr::write_volatile(block.pointer.as_ptr().add(block.layout.size() - 1), 0x5A); + u_assert_eq!(core::ptr::read_volatile(block.pointer.as_ptr()), 0xA5); + u_assert_eq!(core::ptr::read_volatile(block.pointer.as_ptr().add(block.layout.size() - 1)), 0x5A); + } + } + Ok(()) + } + + fn cleanup(&mut self) -> Result<(), &'static str> { + if self.allocator.is_none() { + return Ok(()); + } + for index in 0..self.blocks.len() { + self.free(index); + } + let regions = self.allocator().get_memory_ranges(); + self.allocator = None; + let mut result = Ok(()); + for region in regions { + if GCD.free_memory_space(region.start, region.end - region.start).is_err() { + result = Err("Failed to release isolated allocator backing region"); + } + } + result + } + } + + impl Drop for Fixture<'_> { + fn drop(&mut self) { + if let Err(error) = self.cleanup() { + log::error!("{error}"); + } + } + } + + fn with_fixture(test: impl FnOnce(&mut Fixture<'_>) -> patina_test::error::Result) -> patina_test::error::Result { + let _tpl = RaisedTpl::new(); + let owner = 0u8; + let mut fixture = Fixture::new(&owner); + let result = test(&mut fixture); + fixture.cleanup()?; + result + } + + /// A partially freed small-block page stays accessible until its last live block is freed. + #[patina_test] + fn small_block_page_retires_only_after_last_free() -> patina_test::error::Result { + with_fixture(|fixture| { + let first = loop { + let index = fixture.allocate(32)?; + let page = fixture.page(index); + let metadata_page = fixture.allocator().get_memory_ranges().any(|region| { + region.contains(&page) + && fixture + .allocator() + .lock() + .firmware_test_metadata_range(region.start) + .is_some_and(|metadata| metadata.contains(&page)) + }); + if !metadata_page { + break index; + } + }; + let page = fixture.page(first); + for _ in 1..UEFI_PAGE_SIZE / 32 { + let index = fixture.allocate(32)?; + u_assert_eq!(fixture.page(index), page, "Small blocks did not fill one page"); + } + let neighbor = fixture.allocate(32)?; + u_assert_eq!(fixture.page(neighbor).abs_diff(page), UEFI_PAGE_SIZE, "Expected an adjacent live page"); + for index in first..neighbor - 1 { + fixture.free(index); + } + fixture.check_pages()?; + fixture.check_live_bytes()?; + fixture.free(neighbor - 1); + u_assert!(!is_mapped(page as u64), "Last free did not unmap the small-block page"); + fixture.check_pages()?; + fixture.check_live_bytes()?; + fixture.free(neighbor); + fixture.check_pages() + }) + } + + /// Every nonmetadata page is mapped exactly when independently tracked live blocks occupy it. + #[patina_test] + fn whole_regions_match_live_block_occupancy() -> patina_test::error::Result { + with_fixture(|fixture| { + for _ in 0..20 { + fixture.allocate(UEFI_PAGE_SIZE)?; + } + u_assert!(fixture.allocator().get_memory_ranges().count() > 1, "Expected multiple backing regions"); + fixture.check_pages()?; + for index in (0..fixture.blocks.len()).step_by(2) { + fixture.free(index); + } + fixture.check_pages()?; + fixture.check_live_bytes()?; + for index in 0..fixture.blocks.len() { + fixture.free(index); + } + fixture.check_pages() + }) + } + + /// Retired pages can change block class without keeping empty pages mapped or harming live neighbors. + #[patina_test] + fn mixed_classes_reuse_and_retire_pages() -> patina_test::error::Result { + with_fixture(|fixture| { + let mut original_pages = Vec::new(); + for _ in 0..15 { + let index = fixture.allocate(UEFI_PAGE_SIZE)?; + original_pages.push(fixture.page(index)); + } + let neighbor = fixture.allocate(UEFI_PAGE_SIZE)?; + for index in 0..neighbor { + fixture.free(index); + } + fixture.check_pages()?; + let mut groups = Vec::new(); + for size in [16, 32, 64, 128, 256, 512, 1024, 2048] { + let first = fixture.blocks.len(); + let mut reused = false; + for _ in 0..UEFI_PAGE_SIZE / size { + let index = fixture.allocate(size)?; + reused |= original_pages.contains(&fixture.page(index)); + } + u_assert!(reused, "Block class did not reuse a retired page from another class"); + groups.push(first..fixture.blocks.len()); + fixture.check_pages()?; + fixture.check_live_bytes()?; + } + for group in &groups { + for index in group.clone().step_by(2) { + fixture.free(index); + } + } + fixture.check_pages()?; + fixture.check_live_bytes()?; + for group in groups { + for index in group { + fixture.free(index); + } + fixture.check_pages()?; + fixture.check_live_bytes()?; + } + fixture.free(neighbor); + fixture.check_pages() + }) + } + + /// Multi-page pool allocations unmap every freed page while adjacent allocations remain accessible. + #[patina_test] + fn medium_pool_runs_retire_independently() -> patina_test::error::Result { + with_fixture(|fixture| { + let first = fixture.allocate(2 * UEFI_PAGE_SIZE)?; + let second = fixture.allocate(2 * UEFI_PAGE_SIZE)?; + let third = fixture.allocate(4 * UEFI_PAGE_SIZE)?; + fixture.check_pages()?; + fixture.check_live_bytes()?; + let first_page = fixture.page(first); + fixture.free(first); + for page in (first_page..first_page + 2 * UEFI_PAGE_SIZE).step_by(UEFI_PAGE_SIZE) { + u_assert!(!is_mapped(page as u64), "Freed multi-page allocation is still mapped"); + } + fixture.check_pages()?; + fixture.check_live_bytes()?; + let small = fixture.allocate(32)?; + fixture.check_pages()?; + fixture.check_live_bytes()?; + fixture.free(second); + fixture.free(third); + fixture.free(small); + fixture.check_pages() + }) + } +} + /// 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. diff --git a/patina_dxe_core/src/event_db.rs b/patina_dxe_core/src/event_db.rs index 7f919274c3..46e58191cc 100644 --- a/patina_dxe_core/src/event_db.rs +++ b/patina_dxe_core/src/event_db.rs @@ -21,6 +21,7 @@ use core::{ ffi::c_void, fmt, ops::{Deref, DerefMut}, + sync::atomic::{AtomicBool, Ordering as AtomicOrdering}, }; use patina::standard::efi; use patina::{error::EfiError, log_debug_assert}; @@ -649,6 +650,8 @@ impl Drop for EventGuard<'_> { pub struct SpinLockedEventDb { inner: tpl_mutex::TplMutex, pending_signals: tpl_mutex::TplMutex>, + memory_map_change_pending: AtomicBool, + cache_attribute_change_pending: AtomicBool, } impl Default for SpinLockedEventDb { @@ -663,6 +666,8 @@ impl SpinLockedEventDb { SpinLockedEventDb { inner: tpl_mutex::TplMutex::new(efi::TPL_HIGH_LEVEL, EventDb::new(), "EventLock"), pending_signals: tpl_mutex::TplMutex::new(efi::TPL_HIGH_LEVEL, Vec::new(), "pendingSignalsLock"), + memory_map_change_pending: AtomicBool::new(false), + cache_attribute_change_pending: AtomicBool::new(false), } } @@ -735,7 +740,21 @@ impl SpinLockedEventDb { /// This routine signals all events in the given event group. There isn't an equivalent UEFI spec API for this; the /// equivalent would need to be accomplished by creating a dummy event that is a member of the group and signalling /// that event. + /// + /// Memory map and cache attribute change groups only set pending flags and will get triggered on the next TPL + /// restore because they are signaled by the memory management code and cannot allocate. pub fn signal_group(&self, group: efi::Guid) { + let deferred = if group == efi::EVENT_GROUP_MEMORY_MAP_CHANGE { + Some(&self.memory_map_change_pending) + } else if group == patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner() { + Some(&self.cache_attribute_change_pending) + } else { + None + }; + if let Some(pending) = deferred { + pending.store(true, AtomicOrdering::Release); + return; + } if let Some(mut guard) = self.try_lock() { guard.signal_group(group); } else { @@ -748,6 +767,26 @@ impl SpinLockedEventDb { } } + /// Queues deferred memory map and cache attribute changes during TPL restoration. + /// + /// Leaves the signal pending if the database is locked. The caller must prevent + /// recursive flushing while releasing the database lock. + pub(crate) fn flush_deferred_group_signals(&self) { + if !(self.memory_map_change_pending.load(AtomicOrdering::Acquire) + || self.cache_attribute_change_pending.load(AtomicOrdering::Acquire)) + { + return; + } + if let Some(mut guard) = self.try_lock() { + if self.cache_attribute_change_pending.swap(false, AtomicOrdering::AcqRel) { + guard.signal_group(patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner()); + } + if self.memory_map_change_pending.swap(false, AtomicOrdering::AcqRel) { + guard.signal_group(efi::EVENT_GROUP_MEMORY_MAP_CHANGE); + } + } + } + /// Returns the event type for the given event /// /// ## Errors @@ -907,6 +946,174 @@ mod tests { extern "efiapi" fn test_notify_function(_: efi::Event, _: *mut core::ffi::c_void) {} + #[test] + fn test_event_allocator_groups_deferred_at_low_tpl() { + with_locked_state(|| { + for group in [ + efi::EVENT_GROUP_MEMORY_MAP_CHANGE, + patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner(), + ] { + let db = SpinLockedEventDb::new(); + let event = db + .create_event( + efi::EVT_NOTIFY_SIGNAL, + efi::TPL_NOTIFY, + Some(test_notify_function), + None, + Some(group), + ) + .unwrap(); + let old_tpl = crate::events::raise_tpl(efi::TPL_HIGH_LEVEL); + crate::events::restore_tpl(old_tpl); + assert_eq!(old_tpl, efi::TPL_APPLICATION); + db.signal_group(group); + db.signal_group(group); + { + let guard = db.lock(); + assert!(guard.pending_notifies.is_empty()); + assert_eq!(guard.notify_tags, 0); + assert!(!guard.events.get(&(event as usize)).unwrap().signaled); + assert_eq!(db.pending_signals.lock().capacity(), 0); + } + db.flush_deferred_group_signals(); + let mut guard = db.lock(); + assert_eq!(guard.pending_notifies.len(), 1); + assert_eq!(guard.consume_next_event_notify(efi::TPL_APPLICATION).unwrap().event, event); + assert!(guard.consume_next_event_notify(efi::TPL_APPLICATION).is_none()); + assert!(!db.memory_map_change_pending.load(AtomicOrdering::Acquire)); + assert!(!db.cache_attribute_change_pending.load(AtomicOrdering::Acquire)); + } + }); + } + + #[test] + fn test_event_allocator_groups_deferred_without_queueing() { + with_locked_state(|| { + for group in [ + efi::EVENT_GROUP_MEMORY_MAP_CHANGE, + patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner(), + ] { + let db = SpinLockedEventDb::new(); + let event = db + .create_event( + efi::EVT_NOTIFY_SIGNAL, + efi::TPL_NOTIFY, + Some(test_notify_function), + None, + Some(group), + ) + .unwrap(); + let old_tpl = crate::events::raise_tpl(efi::TPL_HIGH_LEVEL); + for _ in 0..3 { + db.signal_group(group); + } + { + let guard = db.lock(); + assert!(guard.pending_notifies.is_empty()); + assert_eq!(guard.notify_tags, 0); + assert!(!guard.events.get(&(event as usize)).unwrap().signaled); + db.signal_group(group); + let pending = db.pending_signals.lock(); + assert!(pending.is_empty()); + assert_eq!(pending.capacity(), 0); + } + crate::events::restore_tpl(old_tpl); + db.flush_deferred_group_signals(); + db.flush_deferred_group_signals(); + let mut guard = db.lock(); + assert_eq!(guard.pending_notifies.len(), 1); + assert_eq!(guard.notify_tags, 1); + assert_eq!(guard.consume_next_event_notify(efi::TPL_APPLICATION).unwrap().event, event); + assert!(guard.consume_next_event_notify(efi::TPL_APPLICATION).is_none()); + assert!(!db.memory_map_change_pending.load(AtomicOrdering::Acquire)); + assert!(!db.cache_attribute_change_pending.load(AtomicOrdering::Acquire)); + } + }); + } + + #[test] + fn test_event_allocator_groups_flush_while_db_held() { + with_locked_state(|| { + for group in [ + efi::EVENT_GROUP_MEMORY_MAP_CHANGE, + patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner(), + ] { + let db = SpinLockedEventDb::new(); + let old_tpl = crate::events::raise_tpl(efi::TPL_HIGH_LEVEL); + db.signal_group(group); + crate::events::restore_tpl(old_tpl); + let guard = db.lock(); + crate::events::restore_tpl(old_tpl); + db.flush_deferred_group_signals(); + db.signal_group(group); + assert!( + db.memory_map_change_pending.load(AtomicOrdering::Acquire) + || db.cache_attribute_change_pending.load(AtomicOrdering::Acquire) + ); + assert!(guard.pending_notifies.is_empty()); + assert_eq!(db.pending_signals.lock().capacity(), 0); + crate::events::raise_tpl(efi::TPL_HIGH_LEVEL); + drop(guard); + db.flush_deferred_group_signals(); + assert!(!db.memory_map_change_pending.load(AtomicOrdering::Acquire)); + assert!(!db.cache_attribute_change_pending.load(AtomicOrdering::Acquire)); + } + }); + } + + #[test] + fn test_event_allocator_groups_flush_independently() { + with_locked_state(|| { + let db = SpinLockedEventDb::new(); + let groups = [ + efi::EVENT_GROUP_MEMORY_MAP_CHANGE, + patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner(), + ]; + let events = groups.map(|group| { + db.create_event( + efi::EVT_NOTIFY_SIGNAL, + efi::TPL_CALLBACK, + Some(test_notify_function), + None, + Some(group), + ) + .unwrap() + }); + let old_tpl = crate::events::raise_tpl(efi::TPL_HIGH_LEVEL); + for group in groups { + db.signal_group(group); + db.signal_group(group); + } + assert!(db.lock().pending_notifies.is_empty()); + assert_eq!(db.pending_signals.lock().capacity(), 0); + crate::events::restore_tpl(old_tpl); + db.flush_deferred_group_signals(); + let mut guard = db.lock(); + assert_eq!(guard.pending_notifies.len(), 2); + let first = guard.consume_next_event_notify(efi::TPL_APPLICATION).unwrap().event; + let second = guard.consume_next_event_notify(efi::TPL_APPLICATION).unwrap().event; + assert!(events.contains(&first)); + assert!(events.contains(&second)); + assert_ne!(first, second); + assert!(guard.consume_next_event_notify(efi::TPL_APPLICATION).is_none()); + }); + } + + #[test] + fn test_event_ordinary_group_still_queues_at_high_tpl() { + with_locked_state(|| { + let db = SpinLockedEventDb::new(); + let group = efi::EVENT_GROUP_EXIT_BOOT_SERVICES; + db.create_event(efi::EVT_NOTIFY_SIGNAL, efi::TPL_NOTIFY, Some(test_notify_function), None, Some(group)) + .unwrap(); + let old_tpl = crate::events::raise_tpl(efi::TPL_HIGH_LEVEL); + db.signal_group(group); + assert_eq!(db.lock().pending_notifies.len(), 1); + assert!(!db.memory_map_change_pending.load(AtomicOrdering::Acquire)); + crate::events::restore_tpl(old_tpl); + }); + } + #[test] fn create_event_should_create_event() { with_locked_state(|| { diff --git a/patina_dxe_core/src/events.rs b/patina_dxe_core/src/events.rs index 58a42437e2..51355909bf 100644 --- a/patina_dxe_core/src/events.rs +++ b/patina_dxe_core/src/events.rs @@ -315,6 +315,7 @@ pub extern "efiapi" fn restore_tpl(new_tpl: efi::Tpl) { let event = match EVENT_NOTIFIES_IN_PROGRESS.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) { Ok(_) => { + EVENT_DB.flush_deferred_group_signals(); let result = EVENT_DB.consume_next_event_notify(new_tpl); EVENT_NOTIFIES_IN_PROGRESS.store(false, Ordering::Release); result @@ -435,6 +436,49 @@ mod tests { extern "efiapi" fn test_notify(_event: efi::Event, _context: *mut c_void) {} + #[test] + fn test_event_allocator_groups_dispatch_after_unlock() { + with_locked_state(|| { + static CALLS: AtomicUsize = AtomicUsize::new(0); + static OUTER_LOCK: crate::tpl_mutex::TplMutex<()> = + crate::tpl_mutex::TplMutex::new(efi::TPL_HIGH_LEVEL, (), "event test outer lock"); + + extern "efiapi" fn notify(_event: efi::Event, _context: *mut c_void) { + assert!(OUTER_LOCK.try_lock().is_some()); + CALLS.fetch_add(1, Ordering::SeqCst); + } + + for group in [ + efi::EVENT_GROUP_MEMORY_MAP_CHANGE, + patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner(), + ] { + CALLS.store(0, Ordering::SeqCst); + let event = EVENT_DB + .create_event(efi::EVT_NOTIFY_SIGNAL, efi::TPL_NOTIFY, Some(notify), None, Some(group)) + .unwrap(); + { + let _guard = OUTER_LOCK.lock(); + for _ in 0..3 { + EVENT_DB.signal_group(group); + } + restore_tpl(efi::TPL_HIGH_LEVEL); + assert_eq!(CALLS.load(Ordering::SeqCst), 0); + assert!(!EVENT_DB.is_signaled(event)); + } + assert_eq!(CALLS.load(Ordering::SeqCst), 1); + let old_tpl = raise_tpl(efi::TPL_HIGH_LEVEL); + restore_tpl(old_tpl); + assert_eq!(CALLS.load(Ordering::SeqCst), 1); + { + let _guard = OUTER_LOCK.lock(); + EVENT_DB.signal_group(group); + } + assert_eq!(CALLS.load(Ordering::SeqCst), 2); + EVENT_DB.close_event(event).unwrap(); + } + }); + } + // Track if notification was called static NOTIFY_CALLED: AtomicBool = AtomicBool::new(false); extern "efiapi" fn tracking_notify(_event: efi::Event, _context: *mut c_void) { diff --git a/patina_dxe_core/src/gcd/memory_block.rs b/patina_dxe_core/src/gcd/memory_block.rs index 4f66ea7873..63c8a1252e 100644 --- a/patina_dxe_core/src/gcd/memory_block.rs +++ b/patina_dxe_core/src/gcd/memory_block.rs @@ -246,23 +246,25 @@ impl MemoryBlock { } } + /// Returns whether this block can be allocated by the image, optionally respecting its existing owner. + pub fn can_allocate(&self, image_handle: efi::Handle, respect_ownership: bool) -> bool { + matches!(self, Self::Unallocated(descriptor) + if !matches!(descriptor.memory_type, + dxe_services::GcdMemoryType::NonExistent | dxe_services::GcdMemoryType::Unaccepted) + && (!respect_ownership || descriptor.image_handle.is_null() || descriptor.image_handle == image_handle)) + } + pub fn allocate_transition( &mut self, image_handle: efi::Handle, device_handle: Option, respect_ownership: bool, ) -> Result<(), Error> { + if !self.can_allocate(image_handle, respect_ownership) { + return Err(Error::InvalidStateTransition); + } match self { - Self::Unallocated(md) - if !matches!( - md.memory_type, - dxe_services::GcdMemoryType::NonExistent | dxe_services::GcdMemoryType::Unaccepted - ) => - { - if respect_ownership && !(md.image_handle == 0 as efi::Handle || md.image_handle == image_handle) { - //block has an owner that isn't the requester. - Err(Error::InvalidStateTransition)?; - } + Self::Unallocated(md) => { md.image_handle = image_handle; if let Some(device_handle) = device_handle { md.device_handle = device_handle; @@ -271,7 +273,7 @@ impl MemoryBlock { *self = Self::Allocated(*md); Ok(()) } - _ => Err(Error::InvalidStateTransition), + Self::Allocated(_) => Err(Error::InvalidStateTransition), } } @@ -390,6 +392,53 @@ mod memory_block_tests { use super::*; use dxe_services::{GcdMemoryType, MemorySpaceDescriptor}; + #[test] + fn test_gcd_allocation_eligibility_matches_transition() { + for memory_type in [ + GcdMemoryType::NonExistent, + GcdMemoryType::Unaccepted, + GcdMemoryType::SystemMemory, + GcdMemoryType::Reserved, + GcdMemoryType::MemoryMappedIo, + ] { + for allocated in [false, true] { + for owner in [0, 1, 2] { + for respect_ownership in [false, true] { + let descriptor = MemorySpaceDescriptor { + base_address: 0x1000, + length: 0x1000, + memory_type, + attributes: 0, + capabilities: 0, + device_handle: 3 as efi::Handle, + image_handle: owner as efi::Handle, + }; + let block = if allocated { + MemoryBlock::Allocated(descriptor) + } else { + MemoryBlock::Unallocated(descriptor) + }; + let expected = !allocated + && !matches!(memory_type, GcdMemoryType::NonExistent | GcdMemoryType::Unaccepted) + && (!respect_ownership || owner == 0 || owner == 1); + assert_eq!(block.can_allocate(1 as efi::Handle, respect_ownership), expected); + let mut transitioned = block; + let result = transitioned.allocate_transition(1 as efi::Handle, None, respect_ownership); + if expected { + assert_eq!(result, Ok(())); + assert!(matches!(transitioned, MemoryBlock::Allocated(_))); + assert_eq!(transitioned.as_ref().image_handle, 1 as efi::Handle); + assert_eq!(transitioned.as_ref().device_handle, descriptor.device_handle); + } else { + assert_eq!(result, Err(Error::InvalidStateTransition)); + assert_eq!(transitioned, block); + } + } + } + } + } + } + #[test] fn test_transition_types() { let block = MemoryBlock::Unallocated(MemorySpaceDescriptor { diff --git a/patina_dxe_core/src/gcd/spin_locked_gcd.rs b/patina_dxe_core/src/gcd/spin_locked_gcd.rs index 12d5e2bf69..3a982c1b54 100644 --- a/patina_dxe_core/src/gcd/spin_locked_gcd.rs +++ b/patina_dxe_core/src/gcd/spin_locked_gcd.rs @@ -30,7 +30,6 @@ use patina::{ dxe_services::{self, GcdMemoryType, MemorySpaceDescriptor}, guid as pi_guids, hob, }, - uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID, uefi_pages_to_size, uefi_size_to_pages, writelncrlf, {SIZE_4GB, UEFI_PAGE_MASK, UEFI_PAGE_SHIFT, UEFI_PAGE_SIZE, align_up}, }; @@ -40,7 +39,6 @@ use crate::{ GCD, allocator::{DEFAULT_ALLOCATION_STRATEGY, memory_type_for_handle}, ensure, error, - events::EVENT_DB, gcd::MemoryProtectionPolicy, protocol_db, protocol_db::INVALID_HANDLE, @@ -633,7 +631,7 @@ impl GCD { } ensure!(addr + len <= max_address, EfiError::NotFound); - if mb.as_ref().memory_type != memory_type { + if mb.as_ref().memory_type != memory_type || !mb.can_allocate(image_handle, true) { current = memory_blocks.next_idx(idx); continue; } @@ -722,7 +720,7 @@ impl GCD { continue; } - if mb.as_ref().memory_type != memory_type { + if mb.as_ref().memory_type != memory_type || !mb.can_allocate(image_handle, true) { current = memory_blocks.prev_idx(idx); continue; } diff --git a/patina_dxe_core/src/gcd/spin_locked_gcd/paging.rs b/patina_dxe_core/src/gcd/spin_locked_gcd/paging.rs index 8b7dba56e1..25053e0e8a 100644 --- a/patina_dxe_core/src/gcd/spin_locked_gcd/paging.rs +++ b/patina_dxe_core/src/gcd/spin_locked_gcd/paging.rs @@ -9,11 +9,13 @@ //! SPDX-License-Identifier: Apache-2.0 //! use super::{ - AllocateType, Box, CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID, CacheAttributeSource, DEFAULT_ALLOCATION_STRATEGY, - EVENT_DB, EfiError, GCD, GcdMemoryType, Hob, HobList, MemoryAttributes, MemoryProtectionPolicy, PageAllocator, - PatinaPageTable, PtError, SIZE_4GB, SpinLockedGcd, UEFI_PAGE_MASK, UEFI_PAGE_SHIFT, UEFI_PAGE_SIZE, UefiPeInfo, - Vec, align_up, base_guids, dxe_services, efi, hob, pi_guids, protocol_db, uefi_pages_to_size, + AllocateType, Box, CacheAttributeSource, DEFAULT_ALLOCATION_STRATEGY, EfiError, GCD, GcdMemoryType, Hob, HobList, + MemoryAttributes, MemoryProtectionPolicy, PageAllocator, PatinaPageTable, PtError, SIZE_4GB, SpinLockedGcd, + UEFI_PAGE_MASK, UEFI_PAGE_SHIFT, UEFI_PAGE_SIZE, UefiPeInfo, Vec, align_up, base_guids, dxe_services, efi, hob, + pi_guids, protocol_db, uefi_pages_to_size, }; +use crate::events::EVENT_DB; +use patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID; use patina_internal_cpu::paging::PagingError; const PAGE_POOL_CAPACITY: usize = 512; @@ -134,10 +136,6 @@ impl SpinLockedGcd { let cache_attribute_source = page_table.cache_attribute_source(); - // The cache attribute change event only needs to be sent if the platform needs to communicate - // processor state external to the page table to APs. - let should_signal_event = cache_attribute_source == CacheAttributeSource::Processor; - // As long as cache attributes are supported, let arch specific actions occur on update let should_handle_cache_attributes = cache_attribute_source != CacheAttributeSource::Unsupported; @@ -213,43 +211,28 @@ impl SpinLockedGcd { let old_cache_attributes = region_attributes.map(|attrs| attrs & MemoryAttributes::CacheAttributesMask); - // if the cache attributes changed, we need to publish an event, as some architectures - // (such as x86) need to populate APs with the caching information - if new_cache_attributes != MemoryAttributes::empty() { - if let Some(old_cache_attrs) = old_cache_attributes - && old_cache_attrs != new_cache_attributes - { - if should_handle_cache_attributes { - // Some cache maintenance may be required after all attributes have been applied to clean - // up any stale cache entries before the memory is accessed. This is done after the attributes - // were applied to ensure no new unexpected cache lines are created. - page_table.handle_cacheability_change( - base_address as u64, - len as u64, - old_cache_attrs, - new_cache_attributes, - ); - } - - if should_signal_event { - // in this case, we had caching attributes for this region and they do not match the newly - // set attributes - log::trace!( - target: "paging", - "Cache attributes for memory region {base_address:#x?} of length {len:#x?} were updated to {new_cache_attributes:#x?} from {old_cache_attrs:#x?}, sending cache attributes changed event", - ); - - EVENT_DB.signal_group(CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner()); - } - } else if unmapped && old_cache_attributes.is_none() && should_signal_event { - // in this case the region was unmapped and we had no caching attributes set up - log::trace!( - target: "paging", - "Cache attributes for memory region {base_address:#x?} of length {len:#x?} were updated to {new_cache_attributes:#x?} from an unmapped state, sending cache attributes changed event", - ); - - EVENT_DB.signal_group(CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner()); - } + if new_cache_attributes != MemoryAttributes::empty() + && let Some(old_cache_attrs) = old_cache_attributes + && old_cache_attrs != new_cache_attributes + && should_handle_cache_attributes + { + // Some cache maintenance may be required after all attributes have been applied to clean + // up any stale cache entries before the memory is accessed. This is done after the attributes + // were applied to ensure no new unexpected cache lines are created. + page_table.handle_cacheability_change( + base_address as u64, + len as u64, + old_cache_attrs, + new_cache_attributes, + ); + } + + if new_cache_attributes != MemoryAttributes::empty() + && cache_attribute_source == CacheAttributeSource::Processor + && (old_cache_attributes.is_some_and(|old| old != new_cache_attributes) + || (unmapped && old_cache_attributes.is_none())) + { + EVENT_DB.signal_group(CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner()); } log::trace!( diff --git a/patina_dxe_core/src/gcd/spin_locked_gcd/tests.rs b/patina_dxe_core/src/gcd/spin_locked_gcd/tests.rs index 9c0abfa46b..4707a3a2a4 100644 --- a/patina_dxe_core/src/gcd/spin_locked_gcd/tests.rs +++ b/patina_dxe_core/src/gcd/spin_locked_gcd/tests.rs @@ -764,6 +764,46 @@ fn test_allocate_memory_space_with_all_memory_type() { }); } +#[test] +fn test_gcd_directional_allocation_skips_ineligible_candidates() { + with_locked_state(|| { + for top_down in [false, true] { + let (mut gcd, _) = create_gcd(); + // SAFETY: The initialized test GCD tracks this controlled address range without dereferencing it. + unsafe { gcd.add_memory_space(GcdMemoryType::SystemMemory, 0x1000, 0x5000, 0) }.unwrap(); + for address in [0x1000, 0x2000, 0x4000, 0x5000] { + gcd.allocate_memory_space( + AllocateType::Address(address), + GcdMemoryType::SystemMemory, + 12, + 0x1000, + 1 as _, + None, + ) + .unwrap(); + } + for address in [0x2000, 0x4000] { + gcd.free_memory_space(address, 0x1000, MemoryStateTransition::FreePreservingOwnership).unwrap(); + } + let strategy = if top_down { AllocateType::TopDown(None) } else { AllocateType::BottomUp(None) }; + assert_eq!( + gcd.allocate_memory_space(strategy, GcdMemoryType::SystemMemory, 12, 0x1000, 2 as _, None), + Ok(0x3000), + ); + let snapshot = copy_memory_block(&gcd); + assert_eq!( + gcd.allocate_memory_space(strategy, GcdMemoryType::SystemMemory, 12, 0x1000, 2 as _, None), + Err(EfiError::OutOfResources), + ); + assert_eq!(snapshot, copy_memory_block(&gcd)); + assert_eq!( + gcd.allocate_memory_space(strategy, GcdMemoryType::SystemMemory, 12, 0x1000, 1 as _, None), + Ok(if top_down { 0x4000 } else { 0x2000 }), + ); + } + }); +} + #[test] fn test_allocate_memory_space_with_no_memory_space_available() { with_locked_state(|| { @@ -2796,6 +2836,139 @@ fn test_set_paging_attributes_no_page_table() { }); } +fn assert_paging_cache_change_notification( + source: CacheAttributeSource, + old_attributes: Option, + new_attributes: MemoryAttributes, + expected_notifications: usize, +) { + use crate::events::{self, EVENT_DB}; + use core::sync::atomic::{AtomicUsize, Ordering}; + + static GCD: SpinLockedGcd = SpinLockedGcd::new(None); + static NOTIFICATIONS: AtomicUsize = AtomicUsize::new(0); + static CALLBACK_AFTER_UNLOCK: AtomicBool = AtomicBool::new(false); + + extern "efiapi" fn notify(_: efi::Event, _: *mut core::ffi::c_void) { + let old_tpl = events::raise_tpl(efi::TPL_HIGH_LEVEL); + events::restore_tpl(old_tpl); + CALLBACK_AFTER_UNLOCK + .store(old_tpl == efi::TPL_NOTIFY && GCD.page_table.try_lock().is_some(), Ordering::SeqCst); + NOTIFICATIONS.fetch_add(1, Ordering::SeqCst); + } + + with_locked_state(|| { + let old_tpl = events::raise_tpl(efi::TPL_HIGH_LEVEL); + events::restore_tpl(old_tpl); + assert_eq!(old_tpl, efi::TPL_APPLICATION); + NOTIFICATIONS.store(0, Ordering::SeqCst); + CALLBACK_AFTER_UNLOCK.store(false, Ordering::SeqCst); + + let mock_table = Rc::new(RefCell::new(MockPageTable::new())); + mock_table.borrow_mut().set_cache_attribute_source(source); + if let Some(attributes) = old_attributes { + mock_table.borrow_mut().map_memory_region(0x1000, 0x1000, attributes).unwrap(); + } + *GCD.page_table.lock() = Some(Box::new(MockPageTableWrapper::new(Rc::clone(&mock_table)))); + let _page_table_cleanup = test_support::StateGuard::new(|| { + *GCD.page_table.lock() = None; + }); + + let event = EVENT_DB + .create_event( + efi::EVT_NOTIFY_SIGNAL, + efi::TPL_NOTIFY, + Some(notify), + None, + Some(patina::uefi::event::CACHE_ATTRIBUTE_CHANGE_EVENT_GROUP_GUID.into_inner()), + ) + .unwrap(); + let _event_cleanup = test_support::StateGuard::new(|| { + EVENT_DB.close_event(event).unwrap(); + }); + + let high_lock = tpl_mutex::TplMutex::new(efi::TPL_HIGH_LEVEL, (), "cache_change_test"); + let high_guard = high_lock.lock(); + assert_eq!(GCD.set_paging_attributes(0x1000, 0x1000, new_attributes.bits()), Ok(())); + assert_eq!(events::raise_tpl(efi::TPL_HIGH_LEVEL), efi::TPL_HIGH_LEVEL); + assert_eq!(NOTIFICATIONS.load(Ordering::SeqCst), 0); + drop(high_guard); + + let old_tpl = events::raise_tpl(efi::TPL_HIGH_LEVEL); + events::restore_tpl(old_tpl); + assert_eq!(old_tpl, efi::TPL_APPLICATION); + assert_eq!(NOTIFICATIONS.load(Ordering::SeqCst), expected_notifications); + assert_eq!(CALLBACK_AFTER_UNLOCK.load(Ordering::SeqCst), expected_notifications != 0); + assert_eq!( + mock_table.borrow().get_mapped_regions().len(), + usize::from(old_attributes.is_some()) + usize::from(old_attributes != Some(new_attributes)), + ); + }); +} + +#[test] +fn test_set_paging_attributes_cache_event_processor_changed() { + assert_paging_cache_change_notification( + CacheAttributeSource::Processor, + Some(MemoryAttributes::Uncached), + MemoryAttributes::Writeback, + 1, + ); +} + +#[test] +fn test_set_paging_attributes_cache_event_processor_unmapped() { + assert_paging_cache_change_notification(CacheAttributeSource::Processor, None, MemoryAttributes::Writeback, 1); +} + +#[test] +fn test_set_paging_attributes_cache_event_unchanged() { + for attributes in [MemoryAttributes::Writeback, MemoryAttributes::Writeback | MemoryAttributes::ExecuteProtect] { + assert_paging_cache_change_notification( + CacheAttributeSource::Processor, + Some(MemoryAttributes::Writeback), + attributes, + 0, + ); + } +} + +#[test] +fn test_set_paging_attributes_cache_event_page_table() { + for old_attributes in [None, Some(MemoryAttributes::Uncached)] { + assert_paging_cache_change_notification( + CacheAttributeSource::PageTable, + old_attributes, + MemoryAttributes::Writeback | MemoryAttributes::ExecuteProtect, + 0, + ); + } +} + +#[test] +fn test_set_paging_attributes_cache_event_unsupported() { + for old_attributes in [None, Some(MemoryAttributes::Uncached)] { + assert_paging_cache_change_notification( + CacheAttributeSource::Unsupported, + old_attributes, + MemoryAttributes::Writeback | MemoryAttributes::ExecuteProtect, + 0, + ); + } +} + +#[test] +fn test_set_paging_attributes_cache_event_empty_cache_attributes() { + for old_attributes in [None, Some(MemoryAttributes::Writeback)] { + assert_paging_cache_change_notification( + CacheAttributeSource::Processor, + old_attributes, + MemoryAttributes::ExecuteProtect, + 0, + ); + } +} + #[test] fn test_set_memory_space_attributes_preserves_requested_cache_attributes() { with_locked_state(|| {