The error you're encountering is because the code is trying to allocate huge pages using MAP_HUGETLB, but your system either doesn't have huge pages configured or doesn't have enough available. Additionally, the code comment mentions "CMA memory," but this isn't actually allocating CMA (Contiguous Memory Allocator) memory - it's attempting to allocate huge pages.
Here's what's happening and how to fix it:
Understanding the Issue
MAP_HUGETLB: This flag requests huge pages (typically 2MB or 1GB instead of the standard 4KB pages). Huge pages must be pre-allocated by the system administrator.
CMA vs Huge Pages: CMA (Contiguous Memory Allocator) is a Linux kernel feature for allocating physically contiguous memory, typically used for DMA operations. The code shown doesn't actually allocate CMA memory - it's trying to allocate huge pages.
Solutions
Solution 1: Remove MAP_HUGETLB
If you don't specifically need huge pages, simply remove the flag:
If you actually need huge pages, you must configure them first:
Check current huge page configuration:
bash
cat /proc/meminfo | grep Huge
Allocate huge pages (as root):
bash
# Allocate 10 huge pages of 2MB each
echo 10 > /proc/sys/vm/nr_hugepages
Verify allocation:
bash
cat /proc/meminfo | grep Huge
Solution 3: Use Explicit Huge Page Size
You can specify the huge page size explicitly:
c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <linux/mman.h> // For MAP_HUGE_2MB
int main() {
// Try to allocate 2MB huge page
void* mem = mmap(NULL, 2 * 1024 * 1024, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB,
-1, 0);
if (mem == MAP_FAILED) {
perror("mmap with huge pages failed");
// Fallback to regular pages
printf("Falling back to regular pages...\n");
mem = mmap(NULL, 2 * 1024 * 1024, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (mem == MAP_FAILED) {
perror("mmap");
exit(1);
}
}
printf("Memory allocated: %p\n", mem);
*(int*)mem = 0x12345678;
printf("Memory contents: %x\n", *(int*)mem);
munmap(mem, 2 * 1024 * 1024);
return 0;
}
If You Actually Need CMA Memory
CMA memory allocation requires kernel-level access and is typically done through device drivers. User-space programs cannot directly allocate CMA memory through mmap. If you need CMA memory for DMA operations, you would typically:
Use a device driver that allocates CMA memory
Access it through a device file (e.g., /dev/your_device)
The most likely solution for your immediate needs is to simply remove MAP_HUGETLB from your mmap flags, unless you specifically require huge pages for performance reasons.