📚 AOS Docs

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:

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

  1. Calculate required size (with metadata)
  2. Find first free block large enough
  3. Split block if larger than needed
  4. Mark block as allocated
  5. Return pointer to user data

Freeing

  1. Find block metadata from pointer
  2. Mark block as free
  3. Coalesce with adjacent free blocks (optional)
  4. 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