Kernel Memory Management¶
Purpose¶
The Linux kernel manages physical memory through multiple allocation layers.
Rather than allocating memory directly from physical RAM, the kernel organizes memory into pages and builds higher-level allocators on top of them.
Understanding these layers explains how APIs such as kmalloc() ultimately obtain memory.
Memory Management Layers¶
Each layer has a different responsibility.
| Layer | Responsibility |
|---|---|
| Kernel Driver | Requests kernel memory |
kmalloc() |
Kernel allocation API |
| SLUB | Allocates fixed-size objects |
| Buddy Allocator | Allocates contiguous physical pages |
| Physical Pages | Basic allocation unit |
| Physical RAM | Actual hardware memory |
Physical Pages¶
Linux manages physical memory in units of pages.
Typical page size:
- 4 KB
Every physical page has a corresponding struct page containing metadata used by the kernel memory manager.
Buddy Allocator¶
The Buddy Allocator manages contiguous page blocks whose sizes are powers of two.
Allocation sizes are represented by allocation orders.
| Order | Pages |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
| 6 | 64 |
Page Split¶
If the requested allocation order is unavailable, the Buddy Allocator recursively splits a larger block.
Example:
Only enough splits are performed to satisfy the requested allocation.
Buddy Merge¶
When a page block is freed, the allocator checks whether its buddy block is also free.
If 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¶
The buddy block can be located directly using the Page Frame Number (PFN).
This works because buddy blocks are always aligned to powers of two.
Memory Fragmentation¶
Repeated split and merge operations modify allocator metadata rather than moving actual page contents.
The Buddy Allocator prefers maintaining larger contiguous free blocks, even if it means performing additional split and merge operations.
This reduces memory fragmentation and improves the success rate of higher-order allocations.
Relationship with SLUB¶
The Buddy Allocator manages physical pages.
SLUB requests page blocks from the Buddy Allocator and divides them into fixed-size objects.
Most small allocations made through kmalloc() are served directly from SLUB caches without invoking the Buddy Allocator.
Summary¶
The Buddy Allocator forms the foundation of Linux physical memory management.
It provides contiguous page blocks through recursive split and merge operations, while higher-level allocators such as SLUB build on top of it to provide efficient object allocation.