Search code examples
memory-managementlinux-kernel

What is the "struct address_space" that backs a anonymous memory page?


In the Linux kernel, there is a field named mapping in struct page. This field may represent the file that backs the page when it's the buffer cache of the file. It could also be a page that is backed by the device swap.

My question is

What is the device mapping for an anonymous memory page? Is that some special device as well(say, swap device)? Thank you!

FYI, I'm reading Linux 5.13.


Solution

  • The ->mapping field of struct page can actually point to three different things, and weirdly enough, two of them are not a struct address_space (despite the type of the field). This is explained in a comment from include/linux/page-flags.h:

    • On an anonymous page mapped into a user virtual memory area, page->mapping points to its anon_vma, not to a struct address_space; with the PAGE_MAPPING_ANON bit set to distinguish it. See rmap.h.

    • On an anonymous page in a VM_MERGEABLE area, if CONFIG_KSM is enabled, the PAGE_MAPPING_MOVABLE bit may be set along with the PAGE_MAPPING_ANON bit; and then page->mapping points, not to an anon_vma, but to a private structure which KSM associates with that merged page. See ksm.h.

    • PAGE_MAPPING_KSM without PAGE_MAPPING_ANON is used for non-lru movable page and then page->mapping points a struct address_space.

    When a page is anonymous and mapped to userspace, page->mapping points to the corresponding struct anon_vma, not to a struct address_space. The value of the pointer itself is therefore not NULL, but trying to get ahold of it using functions such as page_mapping(page) you will get a NULL back. To get ahold of the VMA, a few checks need to be made first (including first checking and removing the flags embedded into ->mapping). See the functions page_get_anon_vma(page) or page_lock_anon_vma_read(page).