linuxswapmmapvirtual-memorypagefile

How to tell Linux that a mmap()'d page does not need to be written to swap if the backing physical page is needed?


Hopefully the title is clear. I have a chunk of memory obtained via mmap(). After some time, I have concluded that I no longer need the data within this range. I still wish to keep this range, however. That is, I do not want to call mummap(). I'm trying to be a good citizen and not make the system swap more than it needs.

Is there a way to tell the Linux kernel that if the given page is backed by a physical page and if the kernel decides it needs that physical page, do not bother writing that page to swap?

I imagine under the hood this magical function call would destroy any mapping between the given virtual page and physical page, if present, without writing to swap first.


Solution

  • Your question (as stated) makes no sense.

    Let's assume that there was a way for you to tell the kernel to do what you want.

    Let's further assume that it did need the extra RAM, so it took away your page, and didn't swap it out.

    Now your program tries to read that page (since you didn't want to munmap the data, presumably you might try to access it). What is the kernel to do? The choices I see:

    1. it can give you a new page filled with 0s.
    2. it can give you SIGSEGV

    If you wanted choice 2, you could achieve the same result with munmap.

    If you wanted choice 1, you could mremap over the existing mapping with MAP_ANON (or munmap followed by new mmap).

    In either case, you can't depend on the old data being there when you need it.

    The only way your question would make sense is if there was some additional mechanism for the kernel to let you know that it is taking away your page (e.g. send you a special signal). But the situation you described is likely rare enough to warrant additional complexity.

    EDIT:

    You might be looking for madvise(..., MADV_DONTNEED)