Side note: set_huge_pmd() wins the award of "ugliest mm function of early
2023". I was briefly concerned how do_set_pmd() decides whether the PMD can be
writable or not. Turns out it's communicated via vm_fault->flags. Just
horrible.
My first Linux award! :) At least it's not "worst mm security issue of
early 2023". I'll take it!
For example: why even *care* about the complexity of installing a PMD in
collapse_pte_mapped_thp() using set_huge_pmd() just for MADV_COLLAPSE?
Sure, we avoid a single page fault afterwards, but is this *really*
worth the extra code here? I mean, after we installed the PMD, the page
could just get reclaimed either way, so there is no guarantee that we
have a PMD mapped once we return to user space IIUC.
A valid question. The first reason is just semantic symmetry for
MADV_COLLAPSE called on anon vs file/shmem memory. It would be nice to
say that "on success, the memory range provided will be backed by
PMD-mapped hugepages", rather than special-casing file/shmem.
The second reason has a more practical use case. In userfaultfd-based
live migration (using UFFDIO_REGISTER_MODE_MINOR) pages are migrated
at 4KiB granularity, and it may take a long (O(many minutes)) for the
transfer of all pages to complete. To avoid severe performance
degradation on the target guest, the vmm wants to MADV_COLLAPSE
hugepage-sized regions as they fill up. Since the guest memory is
still uffd-registered, requiring refault post-MADV_COLLAPSE won't
work, since the uffd machinery will intercept the fault, and no PMD
will be mapped. As such, either uffd needs to be taught to install PMD
mappings, or the PMD mapping already must be in-place.