Kernel Memory Allocator (Kmalloc)
Dynamic Heap Allocation for Kernel Structures
Overview
The kernel memory allocator (Kmalloc) provides dynamic memory allocation for kernel data structures. Unlike user-space malloc, Kmalloc is simpler and optimized for kernel-only use.
Purpose
Kmalloc enables the kernel to allocate memory for:
- Dynamically sized data structures
- Filesystem buffers and caches
- Process control blocks and task stacks
- Driver data structures
- Network buffers
- Any runtime-determined allocations
Design Principles
Simplicity
Kernel allocator doesn't need to be as general-purpose as user-space malloc.
Fixed Upper Limit
AOS allocates a fixed heap size (starting at 1GB, expandable). If heap runs out, allocation fails.
Efficient Freeing
Track allocations to support both malloc and free operations.
Heap Structure
// Heap layout
[Heap Start: 0xFFFF800008000000]
│
├─ [Metadata]
│ ├─ Allocation bitmap/list
│ └─ Free block tracking
│
└─ [Data Region]
├─ Allocated block 1
├─ Allocated block 2
├─ Free block 1
├─ Allocated block 3
└─ ... more blocks
[Heap End: Expandable]
Core Operations
Allocation
- Calculate required size (with metadata)
- Find first free block large enough
- Split block if larger than needed
- Mark block as allocated
- Return pointer to user data
Freeing
- Find block metadata from pointer
- Mark block as free
- Coalesce with adjacent free blocks (optional)
- Return to pool of free memory
Key Takeaways
- ✓ Provides dynamic allocation for kernel
- ✓ Simpler than user-space allocators
- ✓ Supports both malloc and free
- ✓ Can expand heap as needed
- ✓ Tracks allocated blocks