From my understanding, when Linux swaps a physical page frame in/out RAM, it needs to set valid bit for all virtual pages mapping into this physical page. Mapping a virtual page to physical page frame seems to be well explained in textbooks, but how does the kernel find all virtual pages from a physical page frame? Actual implementation in Linux source code would be appreciated.
Each physical page of memory is tracked in the kernel using struct page. This allows the kernel to describe how each page is used; in particular, for anonymous and file-backed mappings, the mapping field points to the
address_space structure used to describe the mapped object.
For code which needs to find virtual mappings using a given physical page, the kernel provides a set of reverse mapping functions. These allow the reverse mappings for anonymous mappings and file-backed mappings to be walked. For example,
try_to_unmap walks the maps looking for any use of a given physical page, so that it can unmap it.
try_to_unmap when it decides it needs to unmap a page which is mapped into processes.