Kernel Memory Management¶
Purpose¶
alloc_pages() allocates a contiguous block of physical pages from the Buddy Allocator.
free_pages() releases a previously allocated page block and attempts to merge it with its free buddy block.
These APIs form the foundation of Linux physical page allocation and are used by higher-level allocators such as SLUB.
Simplified Prototype¶
Parameters¶
order¶
Allocation order.
The allocator returns a contiguous block containing:
| Order | Pages |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
| 6 | 64 |
Allocation Flow¶
When the requested order is unavailable, the Buddy Allocator recursively splits a larger block.
Only the required number of splits is performed.
Free Flow¶
When a page block is released, the allocator attempts to merge it with its buddy block.
If:
- both blocks are free
- both blocks have the same order
they are merged into the next higher order.
This process repeats recursively until no further merge is possible.
Buddy Address Calculation¶
Buddy blocks are located using the Page Frame Number (PFN).
This calculation works because buddy blocks are always aligned to powers of two.
Relationship with kmalloc()¶
Most drivers do not call alloc_pages() directly.
Instead, memory allocation typically follows this path:
Large kernel subsystems and memory allocators use alloc_pages() internally to obtain physical pages.
Common Characteristics¶
- Allocates contiguous physical pages
- Allocation size is always a power of two
- Supports recursive block splitting
- Supports recursive buddy merging
- Reduces memory fragmentation
- Serves as the physical page provider for SLUB