Why can't mmap allocate memory?

I ran the program with root privilege, but it continues to complain that mmap cannot allocate memory. The following is a snippet of code:

#define PROTECTION (PROT_READ | PROT_WRITE) #define LENGTH (4*1024) #ifndef MAP_HUGETLB #define MAP_HUGETLB 0x40000 #endif #define ADDR (void *) (0x0UL) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB) int main (int argc, char *argv[]){ ... // allocate a buffer with the same size as the LLC using huge pages buf = mmap(ADDR, LENGTH, PROTECTION, FLAGS, 0, 0); if (buf == MAP_FAILED) { perror("mmap"); exit(1); } ...} 

Hardware: I have 8G RAM. Processor - ivybridge

Uname output:

 Linux mymachine 3.13.0-43-generic #72-Ubuntu SMP Mon Dec 8 19:35:06 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux 

EDIT 1: perror output

 mmap: Cannot allocate memory 

Also added one line to print errno

 printf("something is wrong: %d\n", errno); 

But the way out:

 something is wrong: 12 

EDIT 2: huge tlb related information from / proc / meminfo

 HugePages_Total: 0 HugePages_Free: 0 HugePages_Rsvd: 0 HugePages_Surp: 0 Hugepagesize: 2048 kB 
+5
source share
2 answers

Well, as suggested by Documentation / vm / hugetlspage.txt , do

 echo 20 > /proc/sys/vm/nr_hugepages 

solved a problem. Tested on ubuntu 14.04. Check Why I cannot map memory to mmap .

+12
source

When you use MAP_HUGETLB , the mmap (2) call may fail (for example, if your system does not have huge pages configured or if some resource is exhausted), you should almost always call mmap without MAP_HUGETLB as a failure. In addition, you should not define MAP_HUGETLB . If it is not defined (internal system headers for <sys/mman.h> , it may differ depending on the architecture or kernel versions), do not use it!

 // allocate a buffer with the same size as the LLC using huge pages buf = mmap(NULL, LENGTH, PROTECTION, #ifdef MAP_HUGETLB MAP_HUGETLB | #endif MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); #ifdef MAP_HUGETLB if (buf == MAP_FAILED) { // try again without huge pages: buf = mmap(NULL, LENGTH, PROTECTION, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); }; #endif if (buf == MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); } 

The core Documentation / vm / hugetlspage.txt mentions that huge pages are or may be limited (for example, if you pass hugepages=N to the kernel, or if you do something through /proc/ or /sys/ , or if it doesn't was configured in the kernel, etc.). Therefore, you are not sure to receive them. And using huge pages for a small display of only 4 Kbytes is a mistake (or, possibly, a failure). Huge pages deserve attention only when requesting many megabytes (for example, gigabytes or more) and are always optimization (for example, you want your application to be able to run on the kernel without them).

+1
source

Source: https://habr.com/ru/post/1209821/


All Articles