[Linux] mmap and memory...

Domain/Linux 2013.10.07 10:53

Some notable points when using mmap 

- mapping with MAP_PRIVATE doesn't carry updates through to the underlying file.

- mmap writing to file is deferred.

=> use msync to write back to file at certain time.

- See also, mprotect, madvise ...

mmap and memory(smaps).

protection argument and flag of mmap matches vma flags (ex. MAP_PRIVATE + PROT_READ | PROT_EXEC <=> r-xp )

* mmap to generic file
Writing to mapped memory doesn't increase process's memory usage(RSS) - doesn't request process's memory page.(I think just memory for disk cache is affected by this operation.)

* mmap to anonymous - MAP_PRIVATE
Demanded pages are treated as PrivateDirty (just like malloc)

map = mmap(NULL, mapsz, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

there is only one VMA(size = mapsz) - Virtual Memory Area - for this map. And it's flag will be ---p.

mprotect(map, mapsz / 3, PROT_WRITE);

Now, two VMAs are used for this map.
One(vma0) is VMA(-w-p) whose size is mapsz / 3. The other(vma1) is VMA(---p) whose size is mapsz / 3 * 2.

sz = mapsz / 3; while (sz--) map[sz] = 0xff;

Now, vma0 has PrivateDirty (size = mapsz / 3) because pages are demanded and written.

* mmap to anonymous - MAP_SHARED   
Same with above. But, shared flag is used instead of private flag.
And in case of shared memory, PSS is very valuable information along with RSS.

(to be continued...)

Trackback 0 : Comment 0