Designing slab allocator with coalescing and sbrk release
Planning a slab allocator for fixed object sizes (32B/64B/128B) that allocates pages via sbrk, tracks free objects per page, and frees entire empty pages by merging adjacent free pages at the heap top to release memory with sbrk calls. The code will maintain sorted free page lists for coalescing and only release memory back to OS if it's contiguous at the heap end, acknowledging sbrk's limitations on non-top memory.
Below is an example of a basic slab-style allocator in C that supports fixed-size objects (32, 64, and 128 bytes) and tries to avoid fragmentation by keeping dedicated slabs for each size class. It also includes simple “coalescing” logic for returning empty pages to the OS using sbrk (or mmap if you adapt it). Note that this is demonstration code intended for educational purposes—real-world allocators are more complex and must handle concurrency, error-checking, and system-specific details.
/*
* slab_allocator.c
*
* A simple slab allocator for fixed-size objects (32, 64, 128 bytes).
* Uses sbrk() to obtain and release pages (4 KB). When an entire page
* becomes free, we attempt to release it. Includes a simplistic
* coalescing step for adjacent free pages at the top of the heap.
*
* NOTES:
* - This is educational/example code. Not production-ready.
* - On some embedded systems, sbrk may not be available or may behave
* differently. Replace with mmap or other OS-specific mechanism as needed.
* - Coalescing/backing memory to the OS via sbrk only works if the free
* chunk is at the end of the heap (the “top”).
* - No thread-safety is implemented.
*/
#include <unistd.h> // sbrk
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define PAGE_SIZE 4096
/* You can add more size classes if needed */
typedef enum {
SIZE_32 = 32,
SIZE_64 = 64,
SIZE_128 = 128
} slab_object_size;
/* Forward declarations */
static void *page_alloc();
static void page_free(void *page);
static void coalesce_free_pages();
/* Node for linking free objects */
typedef struct free_node {
struct free_node *next;
} free_node_t;
/* Represents one slab page */
typedef struct slab_page {
struct slab_page *next; /* next page in this cache */
free_node_t *free_list; /* free objects in this page */
size_t free_count; /* number of free objects */
slab_object_size obj_size;
int total_objects; /* how many objects fit in one page */
/* The actual data area follows this struct in memory */
} slab_page_t;
/* Each size class has its own cache */
typedef struct slab_cache {
slab_page_t *pages; /* list of allocated pages for this cache */
slab_object_size obj_size;
} slab_cache_t;
/* Global caches for 32B, 64B, 128B objects */
static slab_cache_t cache32 = { NULL, SIZE_32 };
static slab_cache_t cache64 = { NULL, SIZE_64 };
static slab_cache_t cache128 = { NULL, SIZE_128 };
/* For coalescing logic, keep a linked list of completely free pages */
typedef struct free_page_entry {
struct free_page_entry *next;
void *page_addr;
} free_page_entry_t;
static free_page_entry_t *g_free_pages = NULL;
/* Allocate a new page from OS via sbrk; returns page-aligned pointer */
static void *page_alloc() {
void *p = sbrk(PAGE_SIZE);
if (p == (void*)-1) {
return NULL; // out of memory
}
return p;
}
/* Return a page to OS if it is at top of heap; simple attempt to shrink. */
static void page_free(void *page) {
/* We only release memory if page is at the program break. */
void *current_brk = sbrk(0);
uintptr_t page_addr = (uintptr_t)page;
uintptr_t brk_addr = (uintptr_t)current_brk;
/* If this page sits exactly at the top (brk_addr == page_addr + PAGE_SIZE),
we can move the break down by PAGE_SIZE. */
if (page_addr + PAGE_SIZE == brk_addr) {
// move brk down by PAGE_SIZE
sbrk(-PAGE_SIZE);
} else {
// store in free list for potential coalescing
free_page_entry_t *entry = (free_page_entry_t*)page;
entry->page_addr = page;
entry->next = g_free_pages;
g_free_pages = entry;
}
}
/* Attempt to coalesce free pages at the top of the heap. */
static void coalesce_free_pages() {
void *top = sbrk(0); // current program break
uintptr_t top_addr = (uintptr_t)top;
int merged = 1;
while (merged) {
merged = 0;
/* Iterate through the free list to see if any free page is right below top_addr */
free_page_entry_t **pprev = &g_free_pages;
free_page_entry_t *cur = g_free_pages;
while (cur) {
uintptr_t page_addr = (uintptr_t)cur->page_addr;
if (page_addr + PAGE_SIZE == top_addr) {
/* This page is exactly one page below the break; release it. */
sbrk(-PAGE_SIZE);
top_addr -= PAGE_SIZE;
*pprev = cur->next;
cur = cur->next;
merged = 1;
/* continue scanning from the start */
break;
} else {
pprev = &cur->next;
cur = cur->next;
}
}
}
}
/* Initialize a slab page for a given cache */
static slab_page_t *slab_page_init(slab_cache_t *cache) {
slab_page_t *page = (slab_page_t*)page_alloc();
if (!page) return NULL;
page->next = NULL;
page->obj_size = cache->obj_size;
/* how many objects fit in page after metadata */
size_t header_size = sizeof(slab_page_t);
size_t usable = PAGE_SIZE - header_size;
page->total_objects = (int)(usable / cache->obj_size);
page->free_count = page->total_objects;
page->free_list = NULL;
/* build free list */
char *data_area = (char*)page + header_size;
for (int i = 0; i < page->total_objects; i++) {
free_node_t *node = (free_node_t*)(data_area + i * cache->obj_size);
node->next = page->free_list;
page->free_list = node;
}
return page;
}
/* Return a pointer to a cache for the requested size */
static slab_cache_t *get_cache(size_t size) {
if (size <= SIZE_32) return &cache32;
if (size <= SIZE_64) return &cache64;
if (size <= SIZE_128) return &cache128;
/* For bigger sizes, you could add more caches or fallback to direct sbrk. */
return NULL;
}
/* Allocate an object of given size (up to 128). */
void *slab_alloc(size_t size) {
slab_cache_t *cache = get_cache(size);
if (!cache) return NULL;
/* find a page with free objects */
slab_page_t *page = cache->pages;
while (page && page->free_count == 0) {
page = page->next;
}
/* if none found, allocate a new one */
if (!page) {
page = slab_page_init(cache);
if (!page) return NULL;
/* add to front of page list */
page->next = cache->pages;
cache->pages = page;
}
/* pop from free list */
free_node_t *node = page->free_list;
if (!node) return NULL; // should not happen
page->free_list = node->next;
page->free_count--;
return (void*)node;
}
/* Free an object allocated from slab_alloc */
void slab_free(void *ptr) {
if (!ptr) return;
/* Locate page header: slab_page_t sits at start of page */
uintptr_t addr = (uintptr_t)ptr;
uintptr_t page_base = addr & ~((uintptr_t)PAGE_SIZE - 1);
slab_page_t *page = (slab_page_t*)page_base;
/* push node back to free list */
free_node_t *node = (free_node_t*)ptr;
node->next = page->free_list;
page->free_list = node;
page->free_count++;
/* if page is fully free, detach from cache and attempt to return to OS */
if (page->free_count == (size_t)page->total_objects) {
/* remove from cache's page list */
slab_cache_t *cache = get_cache(page->obj_size);
if (cache) {
slab_page_t **pprev = &cache->pages;
slab_page_t *cur = cache->pages;
while (cur) {
if (cur == page) {
*pprev = cur->next;
break;
}
pprev = &cur->next;
cur = cur->next;
}
}
/* Now attempt to release the page */
page_free(page);
coalesce_free_pages();
}
}
/* Example usage */
#ifdef TEST_SLAB
int main(void) {
void *a = slab_alloc(20); // from 32B cache
void *b = slab_alloc(60); // from 64B cache
void *c = slab_alloc(100); // from 128B cache
void *d = slab_alloc(128); // also from 128B cache
slab_free(a);
slab_free(b);
slab_free(c);
slab_free(d);
/* If all objects in a page are freed, the page is returned. */
printf("Custom slab allocator test complete.\n");
return 0;
}
#endif
How It Works (High Level)
- Caches: There are three slab caches—one each for 32B, 64B, and 128B objects.
- Slab Page: A page (4 KB) is partitioned into a header plus many fixed-size objects. Free objects are kept on a singly linked list.
- Allocation:
- The allocator picks the cache matching the requested size.
- It looks for a page with free objects; if none exist, it allocates a new page via
sbrk.
- Returns the next free object from that page’s free list.
- Free:
- Puts the object back on its page’s free list and increments
free_count.
- If the page is fully free, it’s unlinked from the cache and we attempt to return it to the OS.
- Coalescing:
- This simple version only merges free pages that happen to be at the top of the heap (since
sbrk can only shrink from the top).
- It also tracks other free pages in a list and tries to coalesce them if the heap “top” moves past them.
You can adapt this to use mmap instead of sbrk or to add more size classes, concurrency controls, and better page coalescing for your particular embedded environment.