I'm trying to implement a file backed memory allocator for a swapless system.
For each new allocation, I use mkstemp
to create a temporary file as backstore, mmap
it as MAP_SHARED
to allow pages to be swapped to the backstore when system's memory pressure is hight. I think I've got this part working.
However I'm having difficulty implementing the deallocation case.
Since at the moment of deallocation, neither the content of the back store, nor the content the resident pages or dirty pages matters any more, the quickest way to do this is to drop and free all resident pages and leave the backstore unchanged. However I didn't find a madvice
flags that can do this.
MADV_DONTNEED
seems excessive because it will commit the dirty pages to back store. (Not true, see answer below)
MADV_DONTNEED
After a successful MADV_DONTNEED operation, the semantics of memory access in the specified region are changed: subsequent accesses of pages in the range will succeed, but will result in either repopulating the memory contents from the up-to-date contents of the underlying mapped file (for shared file mappings, shared anonymous mappings, and shmem-based techniques such as System V shared memory segments) or zero-fill-on-demand pages for anonymous private mappings.
MADV_REMOVE
seems excessive as well because not only does it drops resident pages, it also drops the backstore itself.
MADV_REMOVE
Free up a given range of pages and its associated backing store. This is equivalent to punching a hole in the corresponding byte range of the backing store (see fallocate(2)). Subsequent accesses in the specified address range will see bytes containing zero.
So what steps are the quickest path of unmap/close/delete a mmap
ed file?
Maybe mmap
the same region again as MAP_PRIVATE
(like this) and then munmap
it?