Skip to content

Day89 - Kernel Memory Allocation

Overview

This lab introduces the fundamental Linux kernel memory allocation APIs and the relationship between memory allocation policy and execution context.

A simplified Linux-style memory allocator is implemented to demonstrate how kernel memory allocation works without relying on the actual Linux kernel memory management subsystem.

Learning Goals

After completing this lab, you should understand:

  • Why kernel memory allocation differs from userspace allocation.
  • How a simple kernel memory pool allocator works.
  • How memory blocks are allocated and reused.
  • The difference between kmalloc(), kzalloc(), and kcalloc().
  • Why kcalloc() performs integer overflow checking.
  • The purpose of GFP allocation flags.
  • Why GFP_KERNEL and GFP_ATOMIC are selected according to execution context.

Lab1 - Simplified kmalloc()

Objective

Implement a simplified Linux-style kmalloc() using a fixed-size memory pool.

Implemented

  • Fixed-size memory pool
  • Memory block metadata
  • Sequential allocation
  • Memory block reuse
  • Pool boundary checking

Verified

  • Multiple memory allocations
  • Memory reuse after kfree()
  • Allocation failure when the pool is exhausted

Lab2 - Simplified kzalloc()

Objective

Implement zero-initialized memory allocation.

Implemented

  • kmalloc()
  • Automatic memory zero initialization

Verified

  • Newly allocated memory is zero initialized.
  • Reused memory is cleared before being returned.

Lab3 - Simplified kcalloc()

Objective

Implement array allocation with integer overflow protection.

Implemented

  • Overflow detection
  • Zero-initialized array allocation

Verified

  • Array allocation
  • Integer overflow detection
  • Allocation failure when multiplication overflows

Lab4 - GFP Allocation Policy

Objective

Simulate Linux GFP allocation policy and execution context validation.

Implemented

  • Process Context simulation
  • IRQ Context simulation
  • GFP_KERNEL
  • GFP_ATOMIC

Verified

Execution Context GFP Flag Expected Result
Process Context GFP_KERNEL Success
Process Context GFP_ATOMIC Success
IRQ Context GFP_KERNEL Fail
IRQ Context GFP_ATOMIC Success

Summary

This lab demonstrates the core concepts behind Linux kernel memory allocation.

Although the allocator is greatly simplified compared to the Linux Buddy and SLUB allocators, it captures the essential ideas required for driver development:

  • Dynamic memory allocation
  • Memory lifetime management
  • Memory reuse
  • Zero initialization
  • Integer overflow protection
  • Execution-context-aware allocation policy