From db38b902307e687219ec765ef51a6ef459746c87 Mon Sep 17 00:00:00 2001 From: Josef Bacik Date: Sat, 31 Oct 2026 10:39:45 +0100 Subject: [PATCH] mm/khugepaged: fix PMD table lock leak in try_collapse_pte_mapped_thp() For a private mapping with userfaultfd, try_collapse_pte_mapped_thp() takes the PMD table lock before it maps the page table for the second time. If that (pte_offset_map_rw_nolock) fails, because the page table vanished in the meantime due to concurrent page table reclaim, it leaves through the abort label, where the PMD table lock is unlocked if it differs from PTE table lock. In case the PMD table lock and the PTE table lock match, which is the case without CONFIG_SPLIT_PTE_PTLOCKS after pte_offset_map_rw_nolock() failed, we miss to unlock the PMD table. To fix it, forget the PTE table lock when we unmap+unlock the PTE table. Fix generated by an LLM and sent by Josef Bacik in private. Fixes: 6375e95f381e ("mm: pgtable: reclaim empty PTE page in madvise(MADV_DONTNEED)") Cc: stable@vger.kernel.org Signed-off-by: Josef Bacik [ david: move the ptl = NULL handling; rewrite description, drop wrong comments ] Reviewed-by: Gregory Price (Meta) Tested-by: Gregory Price (Meta) Tested-by: Muhammad Usama Anjum Link: https://patch.msgid.link/20261031-fixes_core-v3-16-d6437171ecc3@kernel.org Reviewed-by: Lance Yang Reviewed-by: Baolin Wang Signed-off-by: David Hildenbrand (Arm) --- mm/khugepaged.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mm/khugepaged.c b/mm/khugepaged.c index 81496887d827..34ebb37c862c 100644 --- a/mm/khugepaged.c +++ b/mm/khugepaged.c @@ -1904,7 +1904,7 @@ static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsign result = SCAN_FAIL; start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl); - if (!start_pte) /* mmap_lock + page lock should prevent this */ + if (!start_pte) goto drop_folio; /* step 1: check all mapped PTEs are to the right huge page */ @@ -1935,6 +1935,7 @@ static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsign } pte_unmap_unlock(start_pte, ptl); + ptl = NULL; mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, haddr, haddr + HPAGE_PMD_SIZE); mmu_notifier_invalidate_range_start(&range); @@ -1952,7 +1953,7 @@ static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsign pml = pmd_lock(mm, pmd); start_pte = pte_offset_map_rw_nolock(mm, pmd, haddr, &pgt_pmd, &ptl); - if (!start_pte) /* mmap_lock + page lock should prevent this */ + if (!start_pte) goto abort; if (!pml) spin_lock(ptl);