Memory Allocation Demo
Description
Demonstrates different kernel memory allocation methods: kmalloc, vmalloc, and slab caches.
Features
- kmalloc: Fast, physically contiguous (1 KB)
- vmalloc: Large, virtually contiguous (1 MB)
- Slab cache: Efficient for same-size objects
- Memory initialization and cleanup
- Size information reporting
Build & Test
make
sudo insmod memory_demo.ko
# Watch the detailed output
dmesg | tail -30
sudo rmmod memory_demo
dmesg | tail -10
Expected Output
=== Memory Allocation Demo ===
1. Testing kmalloc...
✓ kmalloc: Allocated 1024 bytes at 0x...
✓ kmalloc: Memory initialized
2. Testing vmalloc...
✓ vmalloc: Allocated 1048576 bytes at 0x...
✓ vmalloc: Memory initialized
3. Testing slab cache...
✓ slab: Cache created
✓ slab: Object allocated at 0x...
✓ slab: Object initialized (id=42, name=test_object)
4. Memory information:
- kmalloc size: 1024 bytes
- PAGE_SIZE: 4096 bytes
- KMALLOC_MAX_SIZE: ...
=== Memory Demo: All allocations successful ===
Memory Types Comparison
| Type | Size Limit | Speed | Physically Contiguous | Use Case |
|---|---|---|---|---|
| kmalloc | ~4MB | Fast | Yes | Small allocations, DMA |
| vmalloc | Large | Slower | No | Large buffers |
| Slab | Any | Fast | Depends | Same-size objects |
Learning Points
- Different allocation functions for different needs
- Proper cleanup order (reverse of allocation)
- Memory debugging with ksize()
- Slab cache for performance
- Understanding physical vs virtual contiguity