A zap can race with a page fault that installs a PUD leaf, for example with device-dax or VFIO huge pfnmaps: MADV_DONTNEED only holds the VMA lock in read mode, and unmap_mapping_range() only the i_mmap_rwsem in read mode. zap_pud_range() reads the PUD entry multiple times without holding the PUD lock. If it first observes an empty entry, but a concurrent fault installs a leaf before pud_none_or_clear_bad(), pud_bad() will be true for the leaf, and pud_clear_bad() will clear it: zap_pud_range() __handle_mm_fault() =============== =================== pud_trans_huge(*pud) is false create_huge_pud() insert_pud() set_pud_at() pud_none_or_clear_bad() pud_bad(*pud) is true pud_clear_bad() Consequently, this leaves a stale TLB entry behind, leaks the folio reference, etc. Worse, a concurrent zap_huge_pud() or __split_huge_pud() can then read the cleared entry, and drop the mapcount and a reference of an unrelated folio. Let's fix it by reading the PUD entry once, and by reading it again only after we split the leaf or failed to zap it. Skip a PUD leaf just like an empty entry. Note that, in contrast to zap_pmd_range(), there is no need to retry if we find a PUD leaf after we split the leaf or failed to zap it: there is no collapse that could move mapped PTEs into a PUD leaf, so such a leaf was installed by a concurrent fault. Keep falling through after splitting a PUD leaf, so we would zap any page table that a split might install in the future. This has medium urgency, as it can result in a use-after-free, but requires PUD mappings, such as device-dax or VFIO huge pfnmaps. Fixes: a00cc7d9dd93 ("mm, x86: add support for PUD-sized transparent hugepages") Cc: stable@vger.kernel.org Reported-by: Chris Mason Signed-off-by: David Hildenbrand (Arm) --- mm/memory.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/mm/memory.c b/mm/memory.c index dfa307a9228c1..1bc450cc359ca 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -2144,21 +2144,27 @@ static inline unsigned long zap_pud_range(struct mmu_gather *tlb, unsigned long addr, unsigned long end, struct zap_details *details) { - pud_t *pud; + pud_t *pud, pudval; unsigned long next; pud = pud_offset(p4d, addr); do { next = pud_addr_end(addr, end); - if (pud_trans_huge(*pud)) { + pudval = pudp_get(pud); + if (pud_trans_huge(pudval)) { if (next - addr != HPAGE_PUD_SIZE) split_huge_pud(vma, pud, addr); else if (zap_huge_pud(tlb, vma, pud, addr)) goto next; + pudval = pudp_get(pud); /* fall through */ } - if (pud_none_or_clear_bad(pud)) + if (pud_none(pudval) || pud_trans_huge(pudval)) continue; + if (unlikely(pud_bad(pudval))) { + pud_clear_bad(pud); + continue; + } next = zap_pmd_range(tlb, vma, pud, addr, next, details); next: cond_resched(); -- 2.56.1