Home > Mobile >  Linux kernel: is a re-assigned page frame cleared?
Linux kernel: is a re-assigned page frame cleared?

Time:05-05

When a process ends, the Linux kernel can re-assign the user-space page frames (the pages in physical memory) to the user-space pages (in virtual memory) of another process.

Are the page frames cleared before the re-assignment? Otherwise old content might be visible to another process, I can't imagine that this would be allowed. One situation would be assigning page frames to a growing heap where old content may be visible in allocated memory.

CodePudding user response:

Yes, "re-assigned" physical memory is cleared, but how and when exactly is a bit tricky. The page is not cleared right away, but rather on the first write page fault after another process maps it.

Assuming an anonymous "zero-fill on demand" page:

  1. User program A is using a memory page with physical address PA.
  2. User program A terminates execution, kernel claims memory back, physical memory contents are still unchanged.
  3. User program B (or even A again, doesn't matter) starts and requests a page of memory through mmap().
  4. Kernel creates a virtual mapping for the requested page.
  5. User program B writes to the mapping, causing a write page fault.
  6. Kernel allocates memory, and gets a physical page with physical address PA, same as point 1 (very plausible scenario as recently released pages sit in the page cache to be reused).
  7. Kernel clears the page (zeroing-out any previous content) and updates the virtual mapping accordingly (page tables, etc.).

So the actual clearing happens "lazily", potentially a lot later (step 7) than when the memory was released and claimed back by the kernel (step 2).

NOTE that for the first read page fault on a newly created anonymous mapping, the behavior is slightly different: the kernel always keeps a physical page that is completely zeroed out (called the "zero page"), and creates a virtual mapping to this page. This happens for every process that needs it, so the zero page is mapped a lot of times in multiple VMAs of different processes. This is done for performance (no need to zero-out anything) and to save memory (no need to allocate a new page until a write occurs).


Regarding the write fault, which is when the page is actually cleared, one of the possible code paths in the kernel is:

  • Related