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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
105 changes: 52 additions & 53 deletions docs/src/dxe_core/memory_management.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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<br/>(mapped)" as Fallback
state "Fixed-size blocks<br/>(mapped)" as FixedBlocks
state "FSB retired page<br/>(unmapped)" as Retired
state "Direct fallback allocation<br/>(mapped)" as DirectAllocation

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

Fallback --> DirectAllocation: Large allocation bypasses fixed-size blocks
DirectAllocation --> Fallback: Free allocation
flowchart TB
GCD["GCD system memory"]
FSBFree["FSB available pages<br/>(unmapped; metadata stays mapped)"]
FixedBlocks["Fixed-size blocks<br/>(mapped)"]
Retired["Retired pages<br/>(unmapped)"]
Large["Direct large allocation<br/>(mapped)"]
Small["Small pool allocation<br/>(mapped)"]
Medium["Medium pool allocation<br/>(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"

Expand All @@ -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)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
1 change: 0 additions & 1 deletion patina_dxe_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
32 changes: 7 additions & 25 deletions patina_dxe_core/src/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<Range<usize>>;

/// Indicates whether the given pointer falls within a memory region managed by this allocator.
fn contains(&self, ptr: NonNull<u8>) -> bool;

/// Returns the allocator handle associated with this allocator.
fn handle(&self) -> efi::Handle;

Expand Down Expand Up @@ -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| {
Expand Down Expand Up @@ -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());
}
});
}
Expand All @@ -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());
}
});
}
Expand All @@ -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());
}
});
}
Expand Down
Loading
Loading