Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

15.2 Memory Allocation Algorithms

Previously, we introduced the block memory allocation strategy adopted during the early boot phase. This method is relatively simple and does not represent an efficient approach to memory management. Once boot initialization is complete, Linux transitions to highly efficient memory management mechanisms.

Memory allocation in Linux is executed hierarchically. The vmalloc() memory allocation function leverages the page allocator to allocate memory spaces larger than a single memory page, ensuring that the virtual addresses are contiguous even if the physical addresses are non-contiguous. The page memory allocator employs the buddy system to partition contiguous physical memory into 4096-byte pages, performing memory allocation on a page-level granularity. [[1], [2], [3]]

Various kmalloc() functions operate on top of the memory pages allocated by the page allocator. They leverage the SLOB, SLAB, or SLUB memory allocators to manage memory spaces smaller than a single page. The kmalloc() memory allocation functions primarily serve the internal memory allocation needs of the kernel. [[1], [2]]

  • SLOB (Simple List of Blocks) was adopted in early versions. It has been deprecated in desktop systems and is currently utilized primarily in embedded operating systems. [[1], [2]]

  • SLAB is a relatively complex algorithm. Its primary advantage is minimal memory fragmentation, but its disadvantage is the requirement to preserve a massive amount of management metadata. As of the [Linux 6.8] release, the legacy SLAB allocator has been completely removed from the kernel. [[1], [2], [3]]

  • SLUB improves upon the SLAB algorithm by mitigating the disadvantage of storing substantial amounts of management metadata. [[1]]

The buddy system is utilized inside the page allocator, primarily to allocate physical memory spaces larger than a single page. Both the SLAB and SLUB allocators request memory blocks from the buddy allocator to form their slabs. The hierarchical relationships among these distinct memory management modules are illustrated in Figure 15-1. [[1], [2]]

Figure 15-1 Hierarchical Relationship among Memory Management Modules

15.2.1 SLOB Allocation Algorithm

SLOB is one of the earliest memory management algorithms adopted by Linux. It is primarily utilized to allocate memory spaces smaller than a single page from the SLOB heap. Its minimum allocation granularity can reach 2 bytes, though it typically evaluates to 4 bytes. When the requested memory space is smaller than a single page, kmalloc()-type functions leverage the SLOB allocator to carve out memory from the SLOB heap. Conversely, when the requested space reaches the size of a single page, kmalloc() bypasses the heap and directly invokes alloc_pages() to acquire the memory. [[1], [2], [3]{.underline}]

The SLOB heap is structurally composed of three independent linked lists, with each list consisting of multiple memory pages: [[1]]

  • The first linked list is utilized to allocate memory requests smaller than 256 bytes. [[1]]

  • The second list is utilized to allocate memory requests smaller than 1024 bytes. [[1]]

  • The final list is reserved for all other standard allocation cases. [[1]]

Each page corresponding to these three linked lists maintains its own sub-list composed of the available free memory blocks within that page. This sub-list is arranged in ascending order based on the physical starting addresses of the individual blocks. When a memory block is released, it is inserted into the appropriate sorted position within the linked list according to its address, rather than simply being appended to the end of the list. [[1]]

When executing a memory allocation request, the algorithm first identifies the first page with sufficient free space within the appropriate page linked list. It then traverses that page's internal sub-list to locate the first free memory block that satisfies the requested capacity constraint and assigns it to the requesting context. The primary advantage of the SLOB algorithm is its simplicity and its minimal requirement for storing management metadata. However, the disadvantages of this algorithm are also conspicuous: it introduces exceptionally severe memory fragmentation, resulting in relatively low overall memory utilization efficiency.

15.2.2 SLAB Memory Allocation Algorithm

Memory allocation and deallocation are the most universal operations within the kernel, making rapid and effective allocation strategies paramount to overall operating system performance. To optimize these paths, Linux adopted the SLAB memory allocator starting with version 2.1.23. The SLAB architecture was originally designed and implemented within the Solaris operating system.

The defining characteristic of the SLAB allocator is that the data structures required to manage kernel memory are cached as "objects" within dedicated high-speed lookaside caches. When allocating memory, if a required data object does not exist, it is instantiated. If the object already resides within the lookaside cache, the allocator merely retrieves the memory from the cache and increments the data object's reference count. Under this paradigm, if the existing cache footprint is insufficient, the allocator can request additional backing pages without needing to re-instantiate or re-initialize the underlying object structures. Conversely, during memory deallocation, if an object's reference count is greater than 1, the memory is returned to the lookaside cache and the reference count is decremented. Only when the reference count drops to 1 will the memory be fully released and the tracking object destroyed.

Memory reclamation refers to the explicit process of freeing memory blocks owned by the lookaside caches and destroying the allocator data objects within them. Because objects are only initialized and destroyed during large-scale reclamation sweeps rather than on a per-allocation basis, the kernel avoids repetitive allocation, initialization, and breakdown routines. This drastically minimizes computational overhead and accelerates individual memory allocation and deallocation cycles.

The SLAB allocator infrastructure within Linux is structured as a collection of caches implemented by struct kmem_cache objects, with each cache tuned to service a specific size and type of memory. The managed slots scale logarithmically across intervals spanning 0-1, 1-2^2^-1, 2^2^-2^3^-1, …, 2^25^-2^26^-1 bytes. The primary allocation types encompass KMALLOC_NORMAL, KMALLOC_RECLAIM, and KMALLOC_DMA. These individual caches are woven together via the list field of struct kmem_cache to form a global, doubly linked circular list designated as slab_caches. Every cache within this list operates independently to manage objects belonging to a specific functional category. Each cache contains an array of pointers referencing localized cache nodes (struct kmem_cache_node), where each array index corresponds to a unique NUMA node.

Figure 15-2 Data Structures of the SLAB Allocator

The kmem_cache_node structure contains three distinct list heads: slabs_full, slabs_partial, and slabs_free. These point respectively to linked lists composed of entirely allocated slabs, partially allocated slabs, and completely vacant slabs. These lists are threaded together using the slab_list field inside the corresponding struct page structures. The page structure serves as the core physical descriptor canvas adopted by the SLAB allocator to track backing physical memory.

Every kmem_cache instance manages multiple underlying slabs, with each individual slab consisting of 2^n^ physically contiguous memory pages. Slabs spanning more than a single page are structurally managed as compound pages. Each slab is partitioned into equally sized chunks designated as objects. To prevent ambiguity within this architectural context, these objects are referred to as memory blocks. The baseline dimension of these blocks is dictated by the size field of kmem_cache, while the total count of blocks per slab is governed by the num field.

The struct page utilized for this category of memory allocation incorporates an s_mem pointer, which references the starting memory address of the first block within that slab. Because a slab is guaranteed to consist of physically contiguous pages, this base pointer provides access to all individual blocks across all pages within the slab. The precise memory address of a given block is derived as:

$$p = s_{_}mem + size*(idx - 1)$$

Where p represents the target address of the idx-th block, and idx represents the sequential block index number.

The page structure also encloses a pointer named slab_cache that references the parent kmem_cache instance managing that backing page. Concurrently, the slabs_full, slabs_partial, and slabs_free lists inside kmem_cache_node are populated by threading together the slab_list fields of the active memory pages. This dual linkage enables the kmem_cache manager to seamlessly locate any memory page under its jurisdiction, while enabling any given memory page to resolve its managing cache via the s_mem mapping.

To fulfill a request, the SLAB allocator first selects the appropriate kmem_cache lookup slot from the slab_caches pool based on the requested block magnitude and the execution flags (GFP masks) passed by the calling thread. It then evaluates the target NUMA node via per-CPU topological variables to locate the matching kmem_cache_node. Following this, it traverses the slab_list chains across the slabs_full, slabs_partial, and slabs_free lists to select a candidate slab, ultimately deriving the exact destination memory block via the page's s_mem pointer and the target block index $idx$. This multi-stage address resolution workflow is detailed in Figure 15-3.

Figure 15-3 Resolution of Memory Block Addresses within the SLAB Allocator

The kmem_cache object is defined within the header file git/include/linux/slab_def.h, where its leading field is the cpu_cache pointer. This pointer maps to a per-CPU private variable (per_cpu), ensuring that its evaluated target remains unique to each individual processor core. The pointer references a structure of type array_cache, whose internal entry pointer array caches the specific block indices allocated locally to that CPU core.

When a processor core requests memory, it first queries its local array_cache to see if a free object is readily available. If a vacant slot exists, the memory block is instantly fulfilled from this local cache. If the local cache is exhausted, the allocator evaluates whether a shared array_cache is configured with available objects. If the shared tier is also empty, the engine falls back to inspect the slabs_partial and slabs_free chains hosted inside the node's kmem_cache_node. If a vacant object is discovered at this tier, the indices of the acquired blocks are pulled up to populate the CPU's local array_cache entry array. Finally, if no vacant space can be harvested from these lists, the allocator invokes the low-level page allocator (alloc_pages()) to carve a fresh backing page from virtual memory and append it to the kmem_cache tracking lists. If the underlying page allocator cannot fulfill the raw page request, an out-of-memory (OOM) error is triggered.

The SLAB mechanism is heavily optimized to service memory allocations that fall below a single-page threshold. The comprehensive suite of core kernel kmalloc() routines relies entirely on this underlying allocation logic.

15.2.3 SLUB Memory Allocation Algorithm

The kmem_cache object used by the SLAB allocator maintains a significant volume of metadata. For each NUMA node, a corresponding kmem_cache_node structure is present, and each kmem_cache_node manages three independent linked lists. Managing this metadata is inherently complex and consumes a considerable amount of CPU cycles. To further enhance memory allocation efficiency, Christoph Lameter implemented the SLUB memory allocation algorithm in 2008 within kernel version v2.6.23. Today, SLUB has become the primary memory allocator for Linux, and the widely utilized kmalloc subsystem is built directly upon the SLUB algorithm.

The SLUB allocator optimizes several shortcomings of the SLAB memory allocator. It redefines the kmem_cache and kmem_cache_node structures, removing much of the superfluous management metadata. At runtime, it only utilizes a single partial list, while the full list is exclusively enabled when debugging is required. In the SLUB allocator, individual CPU cores no longer rely on arrays; instead, they utilize the local partial list and a freelist pointer to manage their active slabs and the internal memory objects within those slabs, respectively. When a CPU releases an active object, it puts it back onto its local freelist chain to facilitate immediate, lockless reuse.

SLUB still manages memory blocks using the slab as a fundamental unit, and the layout dimension of a slab is dictated by the size field of the kmem_cache structure. Every individual slab is partitioned into multiple equally sized memory modules, designated as objects, whose baseline footprint is defined by the object_size field of the structure. In contrast to the SLAB allocation algorithm, each slab within SLUB can encapsulate supplemental debugging information; however, these tracking fields are entirely optional. Figure 15-4 illustrates the structural layout of a single object utilized within SLUB. The RED zone left padding, RED zone, SLUB allocation information, and KASAN allocation information segments are completely optional components that are only enabled by kernel or driver developers during debugging sessions. The precise physical positioning of each segment is governed by the individual fields within the kmem_cache structure.

Figure 15-4 Composition of a Slab within the SLUB Allocator

The RED zone Left Padding ensures that the physical starting address of the active memory object strictly satisfies alignment criteria. The Red Zone is partitioned into a left zone and a right zone; it is utilized to execute memory out-of-bounds validation by filling a specific memory region with a dedicated magic number (such as 0xBB). The left zone is positioned immediately preceding the object payload, while the right zone succeeds the object payload. The Object Content represents the actual usable memory footprint granted to the user or kernel application request. When the object resides in a vacant state, the Free Pointer stores the memory address referencing the subsequent free object down the chain. The SLUB Allocation Information logs the specific function call or call stack responsible for allocating or freeing the object, a tracking capability typically exposed via CONFIG_SLUB_DEBUG. The KASAN Allocation Information represents metadata reserved exclusively for KASAN (Kernel Address Sanitizer), which logs highly precise call stacks for asynchronous allocations and deallocations to troubleshoot advanced vulnerabilities such as Use-After-Free (UAF). Finally, the Padding segment trails all metadata structures to align the total physical size of the unified object to a specific hardware alignment boundary.

A slab is still fundamentally backed by the page structure. The page structure configuration adopted by the SLUB allocator encloses tracking fields such as slab_list, partial, next, pages, and counters. The next pointer of the slab_list field chains the individual slabs together to form a linked list. The explicit next pointer shares an identical memory slot with the next sub-field of slab_list, referencing the subsequent slab down the chain. The tracking fields pages and pobjects overlay the memory slot typically reserved for the prev pointer of slab_list, and are leveraged to log the cumulative number of slabs attached to the CPU's local partial list along with the total count of vacant objects contained within them. freelist is a standalone pointer that references the memory location preserving the starting address of the next free object within that specific slab. The counters variable shares its memory alignment with a trailing anonymous union; structurally, counters can be interpreted as a composite element composed of three sections: inuse, objects, and frozen. inuse occupies the upper 16 bits, tracking the number of memory objects that are currently allocated. The lower 16 bits are split between objects and frozen. objects utilizes the upper 15 bits of this lower half to represent the absolute count of objects partitioned within the slab. frozen utilizes the least significant bit (b0) to signify the structural condition of the slab; when this bit evaluates to 1, the slab is frozen, meaning only the specific CPU core that froze it possesses authorization to manipulate its object links.

Each CPU maintains a local tracking variable of type struct kmem_cache_cpu, whose fields are mapped out as follows:

  • The freelist pointer references the memory address preserving the next available free object.

  • The partial pointer references the linked list head capturing the partially vacant slabs.

  • The page pointer references the active slab currently being consumed, which the CPU leverages to fulfill real-time memory allocations.

When allocating memory, the CPU first attempts to harvest a vacant object directly from its local freelist. If a free object cannot be located within the active CPU's freelist, the allocator falls back to fetch a partially vacant slab from its local partial list and subsequently extracts the required memory chunk from that slab. If no free space can be harvested from the local partial list, the engine queries the global partial list hosted inside the node's kmem_cache_node. If this path also fails, the allocator invokes the underlying page allocator (page_allocator) to carve a fresh slab out of system memory.

Both the CPU's local partial list and the cache node's global partial list enforce strict capacity thresholds that are defined inside the parent kmem_cache structure. When the total number of slabs attached to a list surpasses this specified limit, the list is evaluated as full. When a CPU attempts to fetch a slab from its local partial list and finds it full, it flushes and releases all slabs residing on that local list back over to the node's global partial list. If the node's global list is also full during this synchronization pass, the surplus slabs are completely released back to the system memory allocator.

Upon successfully acquiring a fresh slab, if the CPU's local page field evaluates to null, the slab is assigned directly to the page field. Conversely, if the page field is already occupied, the incoming slab is appended onto the CPU's local partial list. Figure 15-5 illustrates the list structure of partial slabs utilized by SLUB.

Figure 15-5 Structural Arrangement of the Partial Slab Linked List

Figure 15-6 details the operational tracking chains utilized locally by each individual CPU core.

Figure 15-6 Per-CPU Linked List Infrastructure inside the SLUB Allocator

15.2.4 Buddy Memory Allocation Algorithm

During the continuous process of allocating and freeing memory modules of varying sizes, the physical memory inevitably fragments into dispersed blocks of arbitrary capacities—a phenomenon known as memory fragmentation. Contiguous physical memory addresses not only accelerate memory read/write cycles but also represent a hard architectural constraint for certain operations such as Direct Memory Access (DMA). When fragmentation becomes severe, it increases access latency and can cause memory allocation failures even when aggregate free space is mathematically sufficient. Mitigating memory fragmentation is a fundamental requirement for any memory allocator. The buddy allocator is specifically designed to address memory fragmentation. Operating at the lowest layer of the core memory management hierarchy, it enforces a minimum allocation granularity of one page and handles the allocation of single or multi-page physical memory chunks. Its core design philosophy is to maximize the size of physically contiguous free memory spaces.

As established in previous chapters, the Linux buddy allocator partitions the physical memory of each NUMA node into 11 distinct groups (orders), where each group is composed of equally sized, physically contiguous memory blocks. The capacities of these memory blocks scale across orders of 1 page, 2 pages, 4 pages, 8 pages, 16 pages, 32 pages, and so forth, with the final group managing block chunks of 1024 pages. These groups are explicitly utilized to service allocation demands of 1 page, 2 pages, 4 pages, up to 1024 pages, respectively. The struct zone configuration for each individual NUMA node manages an array named free_area composed of 11 elements (spanning Order-0 to Order-10) of type struct free_area, which preserves the allocation metadata for these 11 explicit orders. The free_area structure encloses an array of linked list heads named free_list with a capacity of MIGRATE_TYPES, alongside an nr_free tracking field that records the cumulative number of vacant memory blocks available within that specific order. Each element within the free_list array corresponds to a discrete migration type, tracking the available free blocks classified under that type. The migration types supported by Linux are defined within the header file git/include/linux/mmzone.h. Figure 15-7 illustrates the memory grouping topology utilized by the buddy allocator inside the page allocator subsystem.

Figure 15-7 Memory Grouping Topology of the Buddy Allocator

The core buddy memory management engine is implemented within the source file git/mm/page_alloc.c. Full page allocations are dispatched via the interface alloc_pages(), which is declared within git/include/linux/gfp.h. When NUMA support is enabled in the system, alloc_pages() routes the request to alloc_pages_current(). This routine first reads the memory allocation policy constraint specified by the current process within struct task_struct->mempolicy. If the calling thread specifies explicit policies such as MPOL_BIND (forcing allocation to a strict subset of specific nodes), MPOL_INTERLEAVE (alternating allocations across nodes in a round-robin loop), or MPOL_PREFERRED (preferring local node allocation), alloc_pages_current() evaluates these criteria to derive an ordered list of candidate zones (Zonelist) before requesting pages from the buddy infrastructure. Depending on the resolved memory allocation policy, alloc_pages_current() triggers either alloc_page_interleave() or __alloc_pages_nodemask(), with alloc_page_interleave() ultimately falling back to invoke __alloc_pages_nodemask().

Conversely, if NUMA support is disabled, alloc_pages() routes the request to alloc_pages_node(). Because multi-node concepts are absent under this constraint, numa_node_id() permanently returns the index of the singular, local physical node (typically Node 0). The kernel bypasses all policy verification execution paths and directly leverages the globally unique node zone list to execute lockless or locked buddy allocation passes. Under this uniprocessor constraint, alloc_pages_node() calls __alloc_pages_node(), which likewise resolves to invoke __alloc_pages_nodemask().

The function __alloc_pages_nodemask() represents the definitive core routine for memory allocation workloads. It evaluates real-time memory availability by calling either get_page_from_freelist() or __alloc_pages_slowpath(). Depending on the gravity of the allocation constraints, __alloc_pages_slowpath() triggers paths including get_page_from_freelist(), __alloc_pages_direct_compact() (direct memory compaction), __alloc_pages_direct_reclaim() (direct page reclamation), or __alloc_pages_may_oom() (Out-Of-Memory execution). It can fulfill the request directly, or invoke iterative compaction and reclamation sweeps before attempting allocation. The primary task of get_page_from_freelist() is core allocation orchestration, and it serves as the ultimate execution funnel for all alternative allocation handlers; structurally, it is get_page_from_freelist() that executes the physical page acquisition. Throughout the allocation attempt, get_page_from_freelist() manages memory pools via node_reclaim() and extracts page blocks from the target lists via rmqueue().

When extracting pages, rmqueue() leverages the mathematical buddy relationship to first attempt allocation from the smallest order group that can fully satisfy the requested capacity constraint. If free space is unavailable within the current order group, the routine searches upward through larger order groups. Upon a successful match in a higher order, the algorithm splits the block to satisfy the request while preserving the largest possible contiguous address spaces, shunting the residual split chunks down into the appropriate lower-order groups.

The inverse process of releasing a page block back to the allocator is handled by the function __free_one_page(). Throughout this deallocation path, if the algorithm detects two physically contiguous memory blocks belonging to the same order, it combines them into a single larger block and moves the merged entity up into the subsequent higher-order group. Physically contiguous memory blocks of identical order that can be merged in this manner are designated as buddies. Figure 15-8 provides an execution example of a buddy memory allocation sequence. In this scenario, we assume a calling context requests a single page of memory (Order-0), while the system can only discover sufficient free blocks at Order-5 (the 32-page group).

Figure 15-8 Execution Workflow of Buddy Memory Allocation

The allocation engine first identifies an available high-order block buddy5-0 containing sufficient tracking space via the appropriate free_list. It splits buddy5-0 in half, generating two distinct Order-4 buddies designated as buddy4-0 and buddy4-1. The routine inserts buddy4-0 directly into an Order-4 free_list chain, while further bisecting buddy4-1 into two Order-3 buddies designated as buddy3-0 and buddy3-1. This algorithmic bisection loops continuously until the block is successfully broken down into two Order-0 buddies named buddy0-0 and buddy0-1. Finally, the engine appends buddy0-0 onto an Order-0 free_list tracking chain and fulfills the request by returning buddy0-1 to the calling user context.

The inverse memory consolidation pipeline operates conversely to the allocation workflow, as demonstrated by the step-by-step example in Figure 15-8. When a physical page frame is released back to the allocator, the subsystem first evaluates whether its corresponding companion block (buddy) is currently vacant and eligible for consolidation. If the criteria are met, the released block merges with its companion to compose a single unified block of the subsequent higher order. This merging tracking loop executes recursively until it encounters a companion block that is active or ineligible for consolidation. Figure 15-9 details the complete consolidation workflow for a single physical page. Similarly, we assume a calling context releases an Order-0 page frame measuring 4096 bytes; upon reaching Order-5, the consolidated block encounters a companion that cannot be further merged, concluding the deallocation pass.

Figure 15-9 Companion Block Consolidation Workflow within the Buddy Allocator

Throughout allocation passes, the system references a predefined fallback tracking topology formatted as follows:

static int fallbacks[MIGRATE_TYPES][3] = { /* fallback list */
	[MIGRATE_UNMOVABLE]   = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE,   
      MIGRATE_TYPES },
	[MIGRATE_MOVABLE]     = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, 
      MIGRATE_TYPES },
	[MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE,   MIGRATE_MOVABLE,   
      MIGRATE_TYPES },
#ifdef CONFIG_CMA
	[MIGRATE_CMA]         = { MIGRATE_TYPES }, /* Never used */
#endif
#ifdef CONFIG_MEMORY_ISOLATION
	[MIGRATE_ISOLATE]     = { MIGRATE_TYPES }, /* Never used */
#endif
};

Each explicit row within this fallback matrix maps out a prioritized search hierarchy (Fallback List) to guide allocation borrowing when the primary requested migration type faces exhaustion. The values defined inside the array establish the descending precedence sequence for cross-type borrowing, which terminates upon encountering the MIGRATE_TYPES marker boundary.

Fulfilling an allocation request demands the resolution of a topologically suitable memory node. A candidate node is classified as unsuitable if it is explicitly bound to a separate CPU thread context that prohibits external allocation, if its internal dirty page volume surpasses permitted system thresholds, or if its real-time residual capacity drops beneath safety watermarks. If a target node's allocation metrics breach these safety watermarks, the engine first evaluates whether it can harvest fresh memory blocks by pulling in pages whose initialization was deferred during early boot. If this path is exhausted, it ultimately determines if the free block count can be replenished by triggering active page reclamation (including invoking cross-node memory reclamation passes) alongside targeted compaction passes. Once an eligible node passes these validation blocks, the physical allocation is committed within its boundaries.

Copyright © 2026 Guangzhou eSmart Information Technology Co., Ltd. All Rights Reserved.
All content in this book is copyrighted by the author. For personal learning and exchange only. Commercial use without authorization is strictly prohibited. Email:

✉ 3348194517@qq.com | hai616878@gmail.com