Re: [PATCH] mm/madvise: fix MADV_FREE handling for PMD-mapped THPs

From: Baolin Wang

Date: Mon Nov 23 2026 - 02:44:29 EST




On 11/20/26 12:04 AM, David Hildenbrand (Arm) wrote:
After MADV_FREE cleared the dirty flag of an anonymous folio, reclaim will
later free the folio without writing it back if no mappings are dirty.

If our folio is still in the swap cache, the swap entries then point at
swap slots that were never written, exposing stale content of the swap
device. Bad.

madvise_free_pte_range() therefore frees the swap slots first, and skips
the folio if that is impossible. madvise_free_huge_pmd() does not, and a
PMD-mapped THP can be in the swap cache if try_to_unmap() failed during
reclaim, for example due to a racing mlock().

Further, madvise_free_huge_pmd() checks whether the THP is mapped by
other processes before taking the folio lock. Another process that still
has swap entries for the THP can concurrently map it from the swap cache,
and we might end up clearing the dirty flag of a shared folio.

Fix it by factoring out the folio handling of madvise_free_pte_range()
into madvise_free_try_prepare_folio(), and using it for PMD-mapped THPs
as well. Hopefully this prevents further bugs.

For PMD-mapped THPs, this change implies:

1. We free the swap slots of a THP in the swap cache, and skip the THP if
that is impossible.
2. We check the mapcount under the folio lock.
3. We no longer lock and check THPs that are neither dirty nor in the
swap cache, just like for PTE-mapped folios.

For PTE-mapped folios, this means:

4. We check the mapcount once before taking the folio lock, to not lock
folios that are mapped by other processes.

Only compile madvise_free_huge_pmd() with CONFIG_ADVISE_SYSCALLS to keep
!CONFIG_ADVISE_SYSCALLS builds working.

Chris and Sashiko reported the missing swap cache handling for PMD-mapped
THPs, the other issue was found by code inspection.

This has medium urgency.

Fixes: bd4c82c22c36 ("mm, THP, swap: delay splitting THP after swapped out")
Cc: stable@xxxxxxxxxxxxxxx
Reported-by: Chris Mason <mason@xxxxxxxxxx>
Reported-by: Sashiko <sashiko-bot@xxxxxxxxxx>
Closes: https://lore.kernel.org/sashiko-outbox-202086@xxxxxxxxxx/
Signed-off-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>
---

Make sense to me.
Reviewed-by: Baolin Wang <baolin.wang@xxxxxxxxxxxxxxxxx>