Ashmem is excellent for sharing memory between two software processes (like an app and an audio daemon). However, it falls apart when you need to share memory with physical hardware chips (like the GPU, the Camera ISP, or the Video Decoder).
Hardware chips are incredibly picky. Some GPUs require memory to be physically contiguous (not scattered across RAM). Some Camera Image Signal Processors require memory from a very specific, secure physical zone.
To manage these complex hardware constraints, Google introduced the ION Memory Allocator.
The Purpose of ION
ION acts as a centralized memory manager for all the proprietary hardware drivers on a smartphone.
Instead of the Camera driver writing its own memory allocation code, and the Display driver writing a different memory allocator, they all ask ION for memory.
ION Heaps
ION achieves this flexibility by dividing the physical RAM into different "Heaps." A heap is a pool of memory with specific physical characteristics.
- System Heap: Standard memory. It can be scattered physically (non-contiguous) but appears contiguous to the software via the MMU (Memory Management Unit).
- Contiguous Memory Allocator (CMA) Heap: Memory that is guaranteed to be physically contiguous. Essential for older, dumb hardware drivers that do not have their own IOMMU (Input-Output Memory Management Unit) to translate scattered pages.
- Carveout Heap: A highly secure, isolated chunk of physical RAM that is "carved out" at boot time. This is often used for DRM-protected video playback (like Netflix). The main CPU is physically blocked from reading this memory to prevent screen recording, but the secure Video Decoder hardware can read it.
// Example of allocating memory from the ION System Heap
struct ion_allocation_data alloc_data;
alloc_data.len = 20 * 1024 * 1024; // 20 MB
alloc_data.heap_id_mask = ION_HEAP_SYSTEM_MASK; // Ask for the System Heap
alloc_data.flags = 0;
int ion_fd = open("/dev/ion", O_RDONLY);
ioctl(ion_fd, ION_IOC_ALLOC, &alloc_data);
// alloc_data.fd now contains a File Descriptor representing the 20MB hardware buffer!
The Buffer Sharing Model
Like Ashmem, ION uses File Descriptors (FDs) to share memory.
When the Camera app wants to record a video:
- It asks the ION driver (
/dev/ion) for a 20MB buffer from the System Heap. ION returns an FD. - The Camera app passes this FD to the Camera HAL, which tells the physical Camera sensor to write raw pixel data directly into that physical RAM address.
- The Camera app then passes the exact same FD to the Video Encoder hardware.
- The Video Encoder reads the raw pixels directly from RAM and compresses them into H.264 video.
This zero-copy pipeline between different hardware blocks is what allows a smartphone to record 4K video at 60 frames per second without overheating the main CPU.