Zack
Zack

Reputation: 1245

how to make sure an allocate buffer is in memory

Let's say I allocate a buffer using mmap in C. Is there any linux operation I can use to make sure that this buffer has been paged into memory and there is an entry for this buffer in page table. I want this because I see some page faults with my application even my memory is much larger than the application requirement. I am using CentOS 7.

Upvotes: 0

Views: 149

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155744

Pass MAP_POPULATE as a flag to the mmap call. That's precisely what it's there for. It won't guarantee the pages don't page out later under memory pressure, but it will page them in at mmap time if possible. Quoting the man page:

MAP_POPULATE (since Linux 2.5.46)

Populate (prefault) page tables for a mapping. For a file mapping, this causes read-ahead on the file. Later accesses to the mapping will not be blocked by page faults. MAP_POPULATE is only supported for private mappings since Linux 2.6.23.

If you really wanted to force stuff to be locked into memory, you could also try passing the MAP_LOCKED flag (which mlocks the memory preventing page out), but this is dangerous since it thwarts memory management and as a result, the cap on mlock-ed pages is often quite low to avoid causing problems.

Upvotes: 2

Related Questions