Memory Allocation: Kernel Allocators, Slab, Buddy System
How Linux 6.12 allocates kernel memory with the buddy page allocator, SLUB, kmalloc, and vmalloc, including fragmentation and GFP allocation-context rules.
How Linux 6.12 allocates kernel memory with the buddy page allocator, SLUB, kmalloc, and vmalloc, including fragmentation and GFP allocation-context rules.
Memory Allocation: Kernel Allocators, Slab, Buddy System
This article uses Linux 6.12 on x86-64 with CONFIG_SLUB. Kernel allocator details depend on the kernel version, architecture, and configuration. In particular, zone names and address ranges are not universal.
Linux uses the buddy allocator for page-sized blocks and SLUB caches for many smaller kernel objects. kmalloc() and vmalloc() serve different contiguity needs; they are kernel APIs, not user-space replacements for malloc().
Introduction
Programs use virtual address spaces managed by the operating system. A user-space allocator such as a C library’s malloc obtains and manages memory for its process; the kernel uses its own allocators for kernel objects and pages. An allocation failure is an error the caller must handle. It does not automatically mean the whole system will panic.
Kernel modules and drivers must choose an allocator that fits the size, lifetime, and calling context of the object. The same request can fail in one context and succeed in another because some allocation flags permit sleeping or reclaim while others do not.
This article covers the Linux 6.12 APIs and the configuration named above. Check the matching kernel documentation and source tree before using an example with another release or architecture.
When to Use / When Not to Use
Kernel memory allocators are used exclusively by the kernel and kernel modules — user-space code does not call kmalloc or alloc_pages(). However, understanding these allocators helps in several scenarios:
When this knowledge is relevant:
- Writing Linux kernel modules or device drivers
- Debugging kernel OOM conditions or memory leaks
- Reading kernel crash dumps (oops/panic output showing slab cache names)
- Performance tuning with
vmstat,/proc/slabinfo,slabtop - Operating system course projects
When to use user-space equivalents:
malloc/freefor C applications in user spacemmap,brkfor larger or memory-mapped allocations- High-level language allocators (Go’s
make/new, Python’s garbage collector) for managed runtime languages
Architecture or Flow Diagram
On the stated Linux 6.12 configuration, kmalloc() commonly serves small objects through SLUB caches, which obtain backing pages from the page allocator. vmalloc() maps virtually contiguous regions backed by pages that need not be physically contiguous.
flowchart TD
KMALLOC["kmalloc()<br/>small physically contiguous allocations"]
VMALLOC["vmalloc()<br/>Arbitrary size, non-contiguous"]
SLAB["Slab Allocator<br/>Object caches (task_struct, etc.)"]
SLUB["SLUB Allocator<br/>Default Linux slab implementation"]
PAGE["alloc_pages()<br/>Buddy System<br/>Physical page allocation"]
ZONES["Memory Zones<br/>DMA, Normal, HighMem"]
PHYMEM["Physical Memory<br/>DRAM"]
KMALLOC --> SLUB
KMALLOC -->|"small allocations"| SLAB
VMALLOC --> PAGE
SLUB --> SLAB
SLAB --> PAGE
PAGE --> ZONES
ZONES --> PHYMEM
Zone layout and address ranges depend on the architecture and kernel configuration. The historical 32-bit x86 ZONE_HIGHMEM layout described in older material should not be applied to this x86-64 example.
Core Concepts
The Buddy System Allocator
The buddy system is the page allocator in Linux. It tracks blocks by order, where an order-N block contains 2^N pages. The byte size depends on PAGE_SIZE, and the maximum order depends on the architecture and kernel configuration.
When a request for n pages comes in:
- Round up to the next power of two (the “order”)
- Check the free list for that order
- If a block is available, split it in half and put the halves on the next-lower free list until the correct size is reached
- If no block is available, request a larger block from the next higher order and split it
When a block is freed, the allocator can coalesce it with a free buddy of the same order. Coalescing helps recover larger blocks, but it cannot combine pages that are still allocated or pinned. Fragmentation can therefore make a large physically contiguous request fail even when the system has enough free memory in total.
The buddy system operates at the page level. Requests for arbitrary byte counts (like kmalloc) cannot be served directly by the buddy system — they need an intermediate allocator that carves page-sized chunks into smaller objects.
Slab Allocator: Motivations
The kernel allocates and frees many objects of the same type repeatedly: task_struct when a process is created, struct file when a file is opened, struct dentry for each directory entry, struct buffer_head for block I/O buffers. Allocating and freeing these through the buddy system would be prohibitively expensive:
- Fragmentation: A
task_struct(2 KB) allocated from an 8 KB buddy block leaves 6 KB wasted - Cache effects: Buddy-allocated pages are not cache-aligned — critical kernel data structures benefit from cache line alignment
- Latency: The buddy system requires searching free lists, potentially triggering page allocation from the zone allocator
SLUB maintains caches for frequently allocated object sizes and types. Caches reuse freed objects and obtain backing pages from the page allocator as needed. This reduces repeated page-level work, but cached free objects still occupy memory until the allocator can return their pages.
SLUB: The Default Slab Allocator
This article assumes CONFIG_SLUB is enabled. Other kernels may use a different slab allocator or configuration; do not infer cache behavior from this example alone.
Key SLUB concepts:
- Partial slabs: A page with some objects allocated and some free
- Per-CPU freelists: Each CPU has a private list of free objects, eliminating locking for the common case
- Object alignment: Cache alignment depends on the cache definition and allocator settings; it does not automatically eliminate false sharing.
kmalloc vs vmalloc
kmalloc() returns virtually and physically contiguous memory. Its practical maximum depends on the platform and configuration, and large contiguous allocations can fail because of fragmentation. Use it for objects that need physical contiguity, while choosing a size that is appropriate for the call context.
vmalloc() creates a virtually contiguous range backed by pages that may be physically scattered. It can sleep while setting up mappings, so it is not suitable for atomic or interrupt context. Use it only when the caller does not require physical contiguity.
| Property | kmalloc | vmalloc |
|---|---|---|
| Physical memory | Contiguous | Non-contiguous (scatter-gather) |
| Virtual address space | Contiguous | Contiguous |
| Maximum allocation | Platform/configuration dependent | Platform/configuration and address-space dependent |
| Calling context | Depends on GFP flags | May sleep; use only in sleepable context |
| Use case | Small, frequent kernel objects | Large buffers (module code, large I/O) |
| Fault context | Safe (directly mapped) | Not safe from interrupt context (may sleep) |
Memory Zones
Linux divides physical memory into zones according to architecture and configuration. These names and boundaries are not a portable memory map:
ZONE_DMA: A platform-specific region for devices with limited DMA addressing. Its size and exact use depend on architecture and configuration.
ZONE_NORMAL: Memory that the architecture can directly map for ordinary kernel use. Do not assume a fixed start or end address.
ZONE_HIGHMEM: Used by some 32-bit configurations for memory outside the kernel’s permanent mapping. It is not part of the usual x86-64 layout described here.
On NUMA systems, each node has its own set of zones. The kernel prefers allocating from the node local to the CPU making the request, falling back to remote nodes when local memory is exhausted.
For exact zones on a target machine, inspect its architecture documentation and boot-time memory map. A 32-bit x86 zone table is not a useful guide to a 64-bit kernel.
Production Failure Scenarios
Large contiguous allocation fails despite free memory
A driver requests a physically contiguous block, but free pages are split across the zone. The request can fail even when total free memory looks sufficient because the allocator cannot combine pages that remain allocated.
Response: Check /proc/buddyinfo and the target device’s DMA constraints. Prefer smaller allocations or vmalloc() when the consumer needs only virtual contiguity. Do not use compaction or reclaim as a guarantee that a large allocation will succeed.
Allocation made from a context that cannot sleep
A path running in interrupt or atomic context calls an allocation that can block. The result may be a warning or a failure, depending on the API and context.
Response: Move allocation to a sleepable path when possible. If an atomic path needs memory, use the appropriate non-sleeping allocation flags, keep the allocation bounded, and handle a null result. GFP_ATOMIC is not a promise that memory is available.
Object cache grows without returning pages
Freed objects may remain in a slab cache for reuse. A rising cache size by itself does not prove a leak; compare active objects, cache behavior, and workload over time.
Response: Use /proc/slabinfo, slabtop, and kernel leak/debug tools supported by the target configuration. Reproduce the growth pattern before changing allocator settings.
Trade-off Table
| Allocator Aspect | Buddy System | Slab/SLUB | vmalloc |
|---|---|---|---|
| Allocation unit | Power-of-2 page blocks | Cached objects / size classes | Virtual pages |
| Physical contiguity | Always guaranteed | Always (via kmalloc) | Not guaranteed |
| Fragmentation risk | Large contiguous blocks can be unavailable | Cached pages may not be immediately reclaimable | Requires virtual address space and backing pages |
| Calling context | Depends on allocation flags | Depends on allocation flags | Sleepable context only |
| Suitable for | Page-level requests | Frequent small kernel objects | Large buffers, module memory |
| NUMA awareness | Partial | Full (SLUB) | Yes |
Fragmentation and allocation context
There are two different fragmentation problems to keep in mind. External fragmentation in the page allocator means free pages exist but cannot be combined into the contiguous block a request needs. Internal fragmentation happens when a cache slot is larger than the object stored in it. SLUB can reuse freed objects, but it cannot move live objects between pages just to compact a cache.
The allocation flags also describe what the caller may do while asking for memory. In Linux 6.12, GFP_KERNEL may sleep and is for contexts where blocking is allowed. GFP_ATOMIC must not sleep, but it can still fail; use it only when an atomic path truly needs an allocation and handle failure. Neither flag removes the need to keep allocations small and lifetimes bounded. See the Linux 6.12 memory allocation guide and memory management API reference.
User-space malloc() is a separate API. A C library allocator manages its process’s heap and may request virtual memory from the kernel through mechanisms such as brk or mmap. It does not map one-to-one to kmalloc() or a particular SLUB cache.
Implementation Snippets
Small sleepable-context allocation (Linux 6.12, C)
#include <linux/errno.h>
#include <linux/gfp.h>
#include <linux/slab.h>
#include <linux/types.h>
struct my_data {
u64 id;
};
/* Call only from a context where sleeping is allowed. */
static int make_sample(void)
{
struct my_data *data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->id = 1;
kfree(data);
return 0;
}
This function illustrates allocation and release; it is not a complete loadable module. GFP_KERNEL can block, so an interrupt handler or other atomic context must not call it. The kernel 6.12 API documentation describes the flags and their constraints. I did not build this snippet against a kernel tree; compile module examples against the headers and configuration for the kernel you intend to run.
Inspecting Kernel Slab Caches (bash)
#!/bin/bash
# Show top slab caches by memory consumption
echo "=== Top 15 slab caches by memory usage ==="
# Requires root privileges to read /proc/slabinfo
cat /proc/slabinfo 2>/dev/null | \
awk 'NR==1 {print $0} NR>1 {print $0 | "sort -k3 -n -r"}' | \
head -16
echo ""
echo "=== Detailed view of specific caches ==="
echo "--- task_struct cache ---"
cat /proc/slabinfo | grep "^task_struct"
echo "--- buffer_head cache ---"
cat /proc/slabinfo | grep "^buffer_head"
echo ""
echo "=== Using slabtop (live view, needs root) ==="
echo "Run 'slabtop -o' to display once, or 'slabtop' for live updates"
Observability Checklist
- Slab cache statistics:
/proc/slabinfoorslabtop -o— shows active objects, num objects, object size per cache - Top slab caches by memory:
sudo awk 'NR==1{for(i=1;i<=NF;i++)if($i=="active_obj")a=i;if($i=="obj_sz")b=i} NR>1{print $a,$b,$0}' /proc/slabinfo | sort -rn | head -20 - Watch cache growth:
watch -n1 'cat /proc/slabinfo | grep -E "^task_struct|^buffer_head|^ext4_inode_cache"' - Kernel memory overall:
cat /proc/meminfo | grep -E "MemFree|MemAvailable|Slab|Cached|Active|Inactive" - kmalloc failures: These appear as
kernel: kmalloc: allocation failedmessages indmesg; enableCONFIG_DEBUG_SLAB_LEAKfor detailed traces - OOM killer for kernel memory:
dmesg | grep -i "out of memory\|oom" | tail - buddy info per zone:
cat /proc/buddyinfo— shows free pages per zone per NUMA node for each order - vmalloc usage:
cat /proc/vmallocinfo— shows all active vmalloc allocations (useful for tracking down a large vmalloc consumer) - Per-NUMA node memory:
numactl --hardwareorcat /proc/nodeinfo - High memory usage (32-bit only):
cat /proc/meminfo | grep High - SLUB debug features: Enable with
slub_debug=Oper-cache, orslub_debug=FZPUfor full diagnostics (poison, red zoning, stats, verify) — requiresCONFIG_SLUB_DEBUG=on
Common Pitfalls / Anti-Patterns
- Calling an allocation that may sleep from interrupt or atomic context. Check the API’s GFP constraints in the documentation for the target kernel.
- Assuming
GFP_ATOMICcannot fail. Every allocation result needs an error path. - Requesting physically contiguous pages when the consumer only needs a contiguous virtual range. Use
vmalloc()only from a sleepable context. - Treating cached free objects as proof of a leak. Inspect active objects and compare cache use under a repeatable workload.
- Copying zone boundaries, allocator limits, or debug settings from a different architecture or kernel configuration.
- Leaving cleanup paths untested. Pair each successful allocation with a release on every error and teardown path.
Quick Recap
- The kernel memory allocator is layered: SLUB → page allocator (buddy system) → memory zones
- The buddy allocator tracks page blocks by order; the byte size depends on
PAGE_SIZEand the maximum order depends on the build - With
CONFIG_SLUB, SLUB caches reuse kernel objects backed by pages from the page allocator kmalloc()returns physically contiguous memory; there is no portable fixed maximum sizevmallocallocates from the vmalloc region (virtually contiguous but physically fragmented), suitable for large buffers- Memory zones depend on architecture and configuration; do not assume fixed address boundaries
GFP_KERNELmay sleep;GFP_ATOMICcannot sleep and may fail- Kernel memory leaks from modules accumulate in slab caches — use
kmemleakto detect them - UAF vulnerabilities in kernel code are severe — use KASAN during development for detection
- Tools:
/proc/slabinfo(slab stats),/proc/buddyinfo(buddy free lists per zone),/proc/vmallocinfo(vmalloc usage)
Interview Questions
The buddy allocator manages physical page blocks by order. SLUB caches objects and obtains backing pages from that allocator. Free objects may remain cached; neither layer eliminates fragmentation.
Use `vmalloc()` when the caller needs virtual contiguity but not physical contiguity, and only from a context where sleeping is allowed. Use `kmalloc()` for physically contiguous memory when the requested size and calling context are appropriate. There is no portable 128 KB limit; practical limits depend on the build and available contiguous pages.
Zones are architecture- and configuration-specific memory regions. `ZONE_DMA`, `ZONE_NORMAL`, and `ZONE_HIGHMEM` do not have universal address boundaries; consult the target kernel documentation and boot-time map.
Linux 6.12 examples here assume `CONFIG_SLUB`. The available slab allocator depends on kernel configuration; SLOB is not an option in this version. Check the kernel source and configuration for the version you are studying.
Kernel OOM handling is not limited to the case where all physical memory and swap are exhausted. Reclaim and allocation constraints may prevent a request from succeeding, and the kernel's OOM logic can select a victim when recovery fails. The OOM score reflects factors such as a process's memory footprint and its oom_score_adj; it is not simply a measure of memory consumed over the process's lifetime. See the Linux 6.12 OOM killer documentation and verify behavior for the relevant memory cgroup and kernel configuration.
A large contiguous allocation can fail even when the system has free memory because free pages may be split among smaller blocks or because the allocation flags constrain reclaim and compaction. Check the requested order, zone, and context, then look at the target kernel's allocation diagnostics. A virtual mapping allocator may be an option only if the caller can sleep and physical contiguity is unnecessary.
Zone names and boundaries are defined by architecture-specific code and kernel configuration. Older 32-bit x86 layouts with `ZONE_HIGHMEM` should not be applied to an x86-64 build.
When a page block is freed, the allocator can combine it with a free buddy block of the same order. This can restore larger blocks, but it cannot combine pages that remain allocated, so fragmentation can still prevent a large contiguous request.
`kmalloc()` returns physically contiguous memory; `vmalloc()` maps virtually contiguous memory backed by pages that may be physically scattered. `vmalloc()` needs mapping work and may sleep. `kmalloc()` can also sleep or fail depending on its GFP flags, so do not treat it as automatically safe in atomic context.
A slab cache stores objects of a size or type and obtains backing pages from the page allocator. Caches can reuse freed objects, but a freed object does not immediately return its page to the buddy allocator. Alignment and fragmentation depend on the cache and configuration.
There is no portable fixed `kmalloc()` size limit. The practical limit depends on the kernel build, requested flags, and availability of physically contiguous pages. Use `vmalloc()` only when physical contiguity is unnecessary and the caller may sleep.
`GFP_KERNEL` may sleep and is for contexts where blocking is allowed. `GFP_ATOMIC` cannot sleep, but it can fail; use it only when required and check the result. The exact allocation constraints are documented for each kernel version.
NUMA placement affects which node supplies pages, but locality and performance costs depend on the machine and workload. Use the kernel NUMA documentation and measurements from the target system; do not apply a fixed remote-memory percentage.
The page allocator supplies pages to callers, including slab allocators. SLUB divides backing pages into objects and may retain pages after objects are freed. Page size and cache behavior depend on the build.
Use-after-free occurs when kernel code frees an object (returns it to the slab cache) but a dangling pointer in another part of the code still references it. A subsequent allocation of the same type reuses that memory, and the original code reads/writes the new object's data — corrupting kernel state or potentially escalating privileges.
KASAN (Kernel Address Sanitizer) detects UAF at runtime by poisoning freed memory with a known pattern (0x6B for each byte, called "kasan-byte"). When that memory is later allocated, KASAN saves the original shadow memory state. On any access to the poisoned region, KASAN checks whether the address is within a valid allocated object — if it was freed, the access triggers a warning. KASAN requires ~2x memory overhead and is enabled with CONFIG_KASAN=y in the kernel config. It detects out-of-bounds writes, use-after-free, and double-free bugs during development and testing.
Linux cgroups (v1 and v2) allow per-cgroup memory limits enforced by the kernel's memory controller. When a cgroup's memory usage hits its memory.limit_in_bytes, the kernel invokes the OOM killer within that cgroup — killing a process within the cgroup to reclaim memory. This is independent of the system-wide OOM killer. The cgroup OOM killer selects from among the processes in the cgroup, not system-wide. Critical system services that must never be killed should be in their own cgroup with a high oom_score_adj (-1000) or outside the memory-constrained cgroup. Container runtimes (Docker, Kubernetes) use cgroups to enforce memory limits — when a container hits its limit, the cgroup OOM killer terminates a process within that container, not elsewhere on the system.
`vmalloc()` allocates and maps pages into a virtually contiguous region. `vmap()` maps pages supplied by the caller into a virtual range. Both perform mapping work and must be used only from a context allowed by their API contracts.
The kernel's memory pool (mempool) maintains a reserve of pre-allocated objects that can be used when normal allocation fails (e.g., during memory pressure). Mempools were originally designed for block I/O where an allocation failure during an I/O operation could cause deadlock — if the system is low on memory and needs to allocate a buffer to complete the I/O that would free more memory, a deadlock is possible. Mempools solve this by always keeping a minimum pool of allocated objects. They are used in the block layer (bio pools), SCSI mid-layer, and some filesystem code. For most kernel code, mempool is overkill — a failed allocation usually means genuine memory exhaustion and the OOM killer should handle it. Using mempool for regular allocations just delays the inevitable and reduces memory available for other uses.
The page allocator can fail to find a sufficiently large contiguous block even when free pages exist. SLUB uses size/type caches for smaller objects, but cache slots and retained pages still have overhead. Actual fragmentation depends on workload and configuration.
Check every allocation result and release successful allocations on all error and teardown paths. User-space `malloc()` can also fail, and Linux may use overcommit; it is not correct to assume it always succeeds. OOM handling depends on the allocation context, memory policy, and cgroup or system limits.
Further Reading
- Cache & Buffer Management — how the CPU cache hierarchy interacts with kernel memory allocation and the page cache
- Virtual Memory — how the OS extends physical memory using disk as a backing store via demand paging
- Linux 6.12 Memory Allocation Guide — allocation flags and context guidance
- Linux 6.12 Memory Management API — kernel allocation API reference
- LWN.net: The SLUB allocator — in-depth article on SLUB design decisions and how it differs from the original Slab allocator
- LWN.net: Memory zones — explains the motivation behind memory zones and the DMA/normal/highmem split
- Kernel.org: KASAN documentation — official guide to building and using KASAN for runtime memory error detection
/proc/slabinfo— slab cache statistics — official documentation for theslabinfointerface and its fields- Linux kernel source: mm/slab.c, mm/slub.c, mm/page_alloc.c — the actual allocator implementations for reference
Conclusion
On Linux 6.12 with CONFIG_SLUB, the buddy page allocator and SLUB serve different allocation needs. The exact zone layout, available flags, and allocator configuration depend on the target architecture and kernel build.
kmalloc() returns physically contiguous memory; vmalloc() returns a virtually contiguous region backed by pages that may not be adjacent in physical memory. Choose based on the consumer’s contiguity requirement and the calling context, then check the return value. Do not assume a fixed size limit or zone map from another architecture.
Before relying on allocator behavior, check the documentation and configuration for the kernel you will run. KASAN and kmemleak are useful during debugging, but they also depend on build options.
Category
Related Posts
ASLR & Stack Protection
Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.
Assembly Language Basics: Writing Code the CPU Understands
Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.
Boolean Logic & Gates
Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.