Skip to contentSkip to conversation

Re-enable discarding lazyfree PMD THPs and transient none PMD fixes

PATCH In review Zi Yan 7 participants 27 messages Dec 4 – Dec 5

Subsystems (10)
lore
Share & tools
lore

Zi Yan

author reviewer
#0 lore raw

v2 cover Re-enable discarding lazyfree PMD THPs and transient none PMD fixes

Patch 1 can be picked up separately if more work is needed for the rest of the patches.

For maintainers, Patch 7 and 9 use pmdp_invalidate() in place of PMD clearing, so they need the arch fixes from Patch 2 to 6. It might be better to get ack from arch maintainers for Patch 2 to 6 and merge the series via mm tree.

Motivation
===

A bug was found in the PMD-level discard of lazyfree THPs [1]. The proposed fix keeps the PMD invalidated with pmdp_invalidate() instead of clearing it, but that does not work on every architecture:

1. riscv, LoongArch and s390 let GUP-fast follow an invalidated PMD;
2. powerpc/book3s64 page table check counts an invalidated PMD as mapped;
3. sparc64's thp_pte_count becomes unbalanced around pmdp_invalidate().

So the PMD-level discard was disabled instead [2]. This series fixes the arch code and re-enables it.

The discard decides from the folio refcount, so GUP-fast must not take a reference through an invalidated PMD, and arch accounting must stay balanced when an invalidated PMD is set again or cleared.

Details
===
Patch 1 fixes set_pmd_migration_entry() when migrating a device private folio. set_pmd_migration_entry() clears the device private PMD unnecessarily and the transient none PMD can be skipped by a concurrent zap. It can cause lost deposited page table, RSS stats mismatch, or data loss.

Patches 2-6 fix the arch code, patch 7 from Kyle keeps the PMD invalidated instead of cleared until the discard is committed, and patch 8 enables the PMD-level discard again:

2. powerpc/book3s64: page table check counts an invalidated PMD as a live mapping, so setting it again or clearing it decrements the map count a second time and hits BUG_ON(). This is already reachable via mprotect(), and via MADV_COLD before v7.4, with CONFIG_PAGE_TABLE_CHECK.

3. riscv: an invalidated PMD still passes pmd_present() and the generic pmd_access_permitted(), so GUP-fast follows it. The generic helpers also let GUP-fast read execute-only entries and write shadow stack entries. Require _PAGE_PRESENT and _PAGE_READ in pte_access_permitted() and use it for PMDs and PUDs too. This patch was posted on its own [3] and has Cc: stable; it is carried here because the series depends on it.

4. LoongArch: an invalidated PMD passes the generic pmd_access_permitted() too. Add a pmd_access_permitted() that requires _PAGE_PRESENT.

5. s390: _SEGMENT_ENTRY_INVALID also marks an old PMD, so GUP-fast follows an invalidated PMD. Always clear _SEGMENT_ENTRY_READ in pmdp_invalidate(), which makes it pmd_protnone(), so GUP-fast rejects it.

6. sparc64: pmdp_invalidate() decrements thp_pte_count assuming a THP split follows, so setting the PMD again loses a count. Move the decrement to pmd_set(), which THP split uses to replace the huge PMD with a page table, and initialize the split's on-stack _pmd to none.

7. mm/huge_memory: use pmdp_invalidate() in the discard, so munmap() and mremap() wait on the PMD lock instead of skipping a none PMD.

8. mm/rmap: discard lazyfree THPs at PMD level again.

Patch 9 fixes a similar transient none PMD issue using pmdp_invalidate() in UFFDIO_MOVE.

Note
===

1. x86, arm64 and powerpc already make GUP-fast reject an invalidated PMD, and sparc64 has no GUP-fast. 32-bit MIPS would not reject it, but it cannot have THP: _PAGE_HUGE makes PFN_PTE_SHIFT exceed PAGE_SHIFT, so the BUILD_BUG_ON() in arch_mm_preinit() fires, which is why Ingenic dropped huge pages in commit 69b686ddd579 ("MIPS: ingenic: Remove CPU_SUPPORTS_HUGEPAGES").

2. A follow-up patch to remove on-stack _pmd in PMD split code can get rid of the for-sparc64 _pmd initialization code

---
Changes in v2:
- Patch 1: new. Do not clear a device private PMD in set_pmd_migration_entry(), since a concurrent zap can skip the
transient none PMD.
- Patch 2: cite riscv commit bdda2887cbf39 instead of its subject; added Usama's Acked-by.
- Patch 3: replaced "riscv: mm: don't let GUP-fast follow invalidated THP PMDs" with the standalone "riscv: mm: don't let GUP-fast follow entries without _PAGE_READ" [3], which also rejects execute-only and shadow
stack entries (Sashiko); added Jisheng's Reviewed-by.
- Patch 4: revised the commit message.
- Patch 5: revised the commit message.
- Patch 6: move the decrement to pmd_set() instead of counting only valid
huge PMDs: _PAGE_VALID is also the referenced bit (_PAGE_R), so v1
dropped old THPs from the count.
- Patch 7: dropped the dependency note.
- Patch 8: call update_hiwater_rss() before the PMD-level discard, as the
PTE path does (Sashiko).
- Patch 9: new. Use pmdp_invalidate() instead of clearing the PMD in UFFDIO_MOVE.
- Dropped the Assisted-by tags; Claude and Codex were used to analyze the
code and review the patches.
- Link to v1: https://patch.msgid.link/[email protected]

---
Kyle Zeng (1):
mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

Zi Yan (8):
mm/migrate: do not clear device private entry in set_pmd_migration_entry() powerpc/book3s64/mm: don't count invalidated PMDs in page table check
riscv: mm: don't let GUP-fast follow entries without _PAGE_READ
LoongArch: mm: don't let GUP-fast follow invalidated THP PMDs s390/mm: always clear _SEGMENT_ENTRY_READ in pmdp_invalidate()
sparc64: mm: fix thp_pte_count accounting around pmdp_invalidate() mm/rmap: re-enable discarding lazyfree THPs at PMD level
userfaultfd: avoid transient none PMDs during UFFDIO_MOVE

 arch/loongarch/include/asm/pgtable.h         |  6 ++++++
 arch/powerpc/include/asm/book3s/64/pgtable.h |  7 +++----
 arch/riscv/include/asm/pgtable.h             | 27 ++++++++++++++++++++++++++
 arch/s390/include/asm/pgtable.h              |  8 ++++++--
 arch/sparc/include/asm/pgtable_64.h          |  7 +++++++
 arch/sparc/mm/tlb.c                          | 27 ++++++++++++++------------
 mm/huge_memory.c                             | 29 ++++++++++++++++++++++------
 mm/rmap.c                                    | 13 +++++++++++++
 8 files changed, 100 insertions(+), 24 deletions(-)

---
base-commit: c6952260203fadee8e9f96c3f999f03b301d6f6d
change-id: 20261007-anon_vma_uaf_fix-e7accd1d2ee1

Best regards,

Signature · 1 line
Yan, Zi
author reviewer
#1 lore raw

PATCH v2 1/9 mm/migrate: do not clear device private entry in set_pmd_migration_entry()

A device private entry is never followed by GUP-fast, so there is no need to clear the entry to avoid it. Furthermore, clearing the entry creates a none PMD and a concurrent zap skips it. set_pmd_migration_entry() might not hold a VMA lock nor a mmap lock. As a result:

1. When racing with munmap(), a "bad pmd" can appear, deposited page table can be lost, and RSS stats can be off.
2. When racing with mremap(), the PMD is not moved, so the new address faults and sees zeros instead of the original data.

Fix it by not clearing device private entry.

Fixes 65edfda6f3f2e ("mm/rmap: extend rmap and migration support device-private entries")

To: David Hildenbrand <[email protected]>
To: Zi Yan <[email protected]>
To: Andrew Morton <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>
Cc: Lance Yang <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Balbir Singh <[email protected]>
Cc: Alistair Popple <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 mm/huge_memory.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
mm/huge_memory.c +6 -1
index 6305b4e2a6b68..91f3c7e7a044a 100644
@@ -5223,7 +5223,12 @@ int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
 	} else {
 		softleaf_t old_entry;
 
-		pmdval = pmdp_huge_get_and_clear(vma->vm_mm, address, pvmw->pmd);
+		/*
+		 * The device private entry stays as is since GUP-fast
+		 * never follows it and folio_try_share_anon_rmap_pmd()
+		 * below never fails for it.
+		 */
+		pmdval = pmdp_get(pvmw->pmd);
 		old_entry = softleaf_from_pmd(pmdval);
 
 		writable = softleaf_is_device_private_write(old_entry);
Signature · 1 line
2.53.0
reviewer Reviewed-by on v2 1/9
#2 lore raw

Re: [PATCH v2 1/9] mm/migrate: do not clear device private entry in set_pmd_migration_entry()

Quoted 3 lines · Zi Yan

A device private entry is never followed by GUP-fast, so there is no need to clear the entry to avoid it. Furthermore, clearing the entry creates a none PMD and a concurrent zap skips it. set_pmd_migration_entry() might not

Nit: maybe "a concurrent zap or mremap" here :)

Quoted 8 lines

hold a VMA lock nor a mmap lock. As a result:

1. When racing with munmap(), a "bad pmd" can appear, deposited page table can be lost, and RSS stats can be off.
2. When racing with mremap(), the PMD is not moved, so the new address faults and sees zeros instead of the original data.

Fix it by not clearing device private entry.

Right. Going straight to the migration entry without that none PMD in between:

before: device-private PMD -> none PMD -> migration PMD
after:  device-private PMD -------------> migration PMD

And, took a quick look at GUP-fast and folio_try_share_anon_rmap_pmd() too, and neither cares about keeping the entry around :D

Quoted 28 lines
Fixes 65edfda6f3f2e ("mm/rmap: extend rmap and migration support device-private entries")

To: David Hildenbrand <[email protected]>
To: Zi Yan <[email protected]>
To: Andrew Morton <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>
Cc: Lance Yang <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Balbir Singh <[email protected]>
Cc: Alistair Popple <[email protected]>
Cc: [email protected]
Cc: [email protected]
---
mm/huge_memory.c | 7 ++++++-

1 file changed, 6 insertions(+), 1 deletion(-)
mm/huge_memory.c +0 -0
index 6305b4e2a6b68..91f3c7e7a044a 100644

mm/huge_memory.c int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw, · line 5231

Quoted 10 lines
mm/huge_memory.c +6 -1
@@ -5223,7 +5223,12 @@ int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw,
 	} else {
 		softleaf_t old_entry;
 
-		pmdval = pmdp_huge_get_and_clear(vma->vm_mm, address, pvmw->pmd);
+		/*
+		 * The device private entry stays as is since GUP-fast
+		 * never follows it and folio_try_share_anon_rmap_pmd()
+		 * below never fails for it.
+		 */
+		pmdval = pmdp_get(pvmw->pmd);

LGTM!

author reviewer
#3 lore raw

PATCH v2 2/9 powerpc/book3s64/mm: don't count invalidated PMDs in page table check

In reply to Zi Yan

pmdp_invalidate() replaces a huge PMD with an invalidated one (_PAGE_PRESENT cleared and _PAGE_INVALID set) and calls page_table_check_pmd_clear() on the old entry. This decreases the page table check map count. When the invalidated entry is later replaced with set_pmd_at(), page_table_check_pmds_set() in set_pmd_at() decreases the map count again because pmd_user_accessible_page() still counts it as a live user mapping. The same happens when it is cleared with pmdp_huge_get_and_clear(). Then the map count underflows and hits BUG_ON() in page_table_check_clear().

Found by code inspection and confirmed in QEMU (pseries, POWER9, 64K pages, CONFIG_PAGE_TABLE_CHECK_ENFORCED=y): MADV_COLD (before v7.4) or mprotect() on an anonymous THP hits the BUG_ON() with both the radix and the hash MMU.

Fix it by only counting entries that are hardware valid, so an invalidated entry is skipped, as commit bdda2887cbf39 ("riscv: mm: exclude invalid THP PMDs from page table check") did for riscv.

While at it, remove the migrate_vma_collect_huge_pmd() item from the comment in pmdp_huge_get_and_clear(): set_pmd_migration_entry() no longer clears device private PMDs.

Fixes 641d47d4c963 ("powerpc/mm: support page table check")

To: Madhavan Srinivasan <[email protected]>
To: Andrew Donnellan <[email protected]>
To: Rohan McLure <[email protected]>
To: Pasha Tatashin <[email protected]>
To: Andrew Morton <[email protected]>

Cc Michael Ellerman <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc "Christophe Leroy (CS GROUP)" <[email protected]>
Cc "Ritesh Harjani (IBM)" <[email protected]>
Cc Shrikanth Hegde <[email protected]>
---
 arch/powerpc/include/asm/book3s/64/pgtable.h | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
arch/powerpc/include/asm/book3s/64/pgtable.h +3 -4
index dff8790a047db..d3808c3560703 100644
@@ -1091,7 +1091,8 @@ static inline bool pmd_access_permitted(pmd_t pmd, bool write)
 #define pmd_user_accessible_page pmd_user_accessible_page
 static inline bool pmd_user_accessible_page(struct mm_struct *mm, unsigned long addr, pmd_t pmd)
 {
-	return pmd_leaf(pmd) && pte_user_accessible_page(mm, addr, pmd_pte(pmd));
+	return pmd_leaf(pmd) && pte_hw_valid(pmd_pte(pmd)) &&
+	       pte_user_accessible_page(mm, addr, pmd_pte(pmd));
 }
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
@@ -1331,11 +1332,9 @@ static inline pmd_t pmdp_huge_get_and_clear(struct mm_struct *mm,
 
 	/*
 	 * Non-present PMDs can be migration entries or device-private THP
-	 * entries. This can happen at 2 places:
+	 * entries. This can happen at:
 	 * - When the address space is being unmapped zap_huge_pmd(), and we
 	 *   encounter non-present pmds.
-	 * - migrate_vma_collect_huge_pmd() could calls this during migration
-	 *   of device-private pmd entries.
 	 */
 	if (!pmd_present(*pmdp)) {
 		old_pmd = READ_ONCE(*pmdp);
Signature · 1 line
2.53.0
author reviewer
#4 lore raw

PATCH v2 3/9 riscv: mm: don't let GUP-fast follow entries without _PAGE_READ

In reply to Zi Yan

riscv maps PROT_EXEC alone as PAGE_EXEC, which has _PAGE_EXEC but not _PAGE_READ, and a writable shadow stack entry is XWR = 010, which has _PAGE_WRITE but not _PAGE_READ. riscv uses the generic pte_access_permitted(), pmd_access_permitted() and pud_access_permitted(), which only check that the entry is present and, for a write, writable. So GUP-fast follows both kinds of entries:

- a read, e.g. from vmsplice() or an O_DIRECT write, can read an execute-only page, which userspace cannot load from;
- a write, e.g. from an O_DIRECT read, can modify a shadow stack page, as pte_write() is true for it.

Slow GUP rejects both: check_vma_flags() fails a read from a VMA without VM_READ and a write to a VM_SHADOW_STACK VMA, unless FOLL_FORCE is set.

Fix it by requiring both _PAGE_PRESENT and _PAGE_READ in pte_access_permitted(), and using it for pmd_access_permitted() and pud_access_permitted() too.

Requiring _PAGE_PRESENT also stops GUP-fast from following a THP PMD invalidated by pmdp_invalidate(), whose pmd_present() is still true. Code that invalidates a PMD and then decides, from the folio refcount, whether it may drop the mapping relies on that. x86, arm64, and powerpc do the same thing.

Fixes 3f910b7a522e ("riscv: enable HAVE_FAST_GUP if MMU")
Fixes c68c2ef9d641 ("riscv/mm: teach pte_mkwrite to manufacture shadow stack PTEs")

To: Paul Walmsley <[email protected]>
To: Palmer Dabbelt <[email protected]>
To: Albert Ou <[email protected]>
Cc: Alexandre Ghiti <[email protected]>
Cc: Jisheng Zhang <[email protected]>
Cc: Zong Li <[email protected]>
Cc: Deepak Gupta <[email protected]>
Cc: Palmer Dabbelt <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 arch/riscv/include/asm/pgtable.h | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)
arch/riscv/include/asm/pgtable.h +27 -0
index 07ccacd51ab54..dcbcfa38a27c2 100644
@@ -373,6 +373,21 @@ static inline int pte_write(pte_t pte)
 	return pte_val(pte) & _PAGE_WRITE;
 }
 
+/*
+ * GUP-fast only follows entries that are present and have _PAGE_READ,
+ * and leaves the rest to slow GUP, which checks the VMA: an execute-only
+ * entry and a writable shadow stack entry (XWR = 010) lack _PAGE_READ, a
+ * PROT_NONE or invalidated entry lacks _PAGE_PRESENT. Any other writable
+ * entry is readable too.
+ */
+#define pte_access_permitted pte_access_permitted
+static inline bool pte_access_permitted(pte_t pte, bool write)
+{
+	const unsigned long need = _PAGE_PRESENT | _PAGE_READ;
+
+	return (pte_val(pte) & need) == need && (!write || pte_write(pte));
+}
+
 static inline int pte_exec(pte_t pte)
 {
 	return pte_val(pte) & _PAGE_EXEC;
@@ -817,12 +832,24 @@ static inline int pmd_write(pmd_t pmd)
 	return pte_write(pmd_pte(pmd));
 }
 
+#define pmd_access_permitted pmd_access_permitted
+static inline bool pmd_access_permitted(pmd_t pmd, bool write)
+{
+	return pte_access_permitted(pmd_pte(pmd), write);
+}
+
 #define pud_write pud_write
 static inline int pud_write(pud_t pud)
 {
 	return pte_write(pud_pte(pud));
 }
 
+#define pud_access_permitted pud_access_permitted
+static inline bool pud_access_permitted(pud_t pud, bool write)
+{
+	return pte_access_permitted(pud_pte(pud), write);
+}
+
 #define pmd_dirty pmd_dirty
 static inline int pmd_dirty(pmd_t pmd)
 {
Signature · 1 line
2.53.0
author reviewer
#5 lore raw

PATCH v2 4/9 LoongArch: mm: don't let GUP-fast follow invalidated THP PMDs

In reply to Zi Yan

pmdp_invalidate() does not change a PMD to make pmd_present() returns false. So the generic pmd_access_permitted() returns true for an invalidated PMD. This allows GUP-fast to grab a reference on the folio.

Code that invalidates a PMD and then decides whether it may drop the mapping relies on GUP-fast backing off from an invalidated PMD. x86, arm64 and powerpc already reject invalidated PMDs in pmd_access_permitted().

Provide a LoongArch pmd_access_permitted() that requires _PAGE_PRESENT, so invalidated (and PROT_NONE) PMDs are not followed by GUP-fast.

To: Huacai Chen <[email protected]>
Cc: WANG Xuerui <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 arch/loongarch/include/asm/pgtable.h | 6 ++++++
 1 file changed, 6 insertions(+)
arch/loongarch/include/asm/pgtable.h +6 -0
index 9a62b87c246de..ac2178fad0952 100644
@@ -522,6 +522,12 @@ static inline int pmd_write(pmd_t pmd)
 	return !!(pmd_val(pmd) & _PAGE_WRITE);
 }
 
+#define pmd_access_permitted pmd_access_permitted
+static inline bool pmd_access_permitted(pmd_t pmd, bool write)
+{
+	return (pmd_val(pmd) & _PAGE_PRESENT) && (!write || pmd_write(pmd));
+}
+
 static inline pmd_t pmd_mkwrite_novma(pmd_t pmd)
 {
 	pmd_val(pmd) |= _PAGE_WRITE;
Signature · 1 line
2.53.0
#6 lore raw

Re: [PATCH v2 4/9] LoongArch: mm: don't let GUP-fast follow invalidated THP PMDs

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] LoongArch: mm: missing Fixes trailer for commit ddc1729b07cc --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] LoongArch: mm: missing Fixes trailer for commit ddc1729b07cc --

commit 58bf1239853f23352ee5f954933f2c215b85b155
Author: Zi Yan <[email protected]>

Quoted 13 lines

LoongArch: mm: don't let GUP-fast follow invalidated THP PMDs

pmdp_invalidate() does not change a PMD to make pmd_present() returns false. So the generic pmd_access_permitted() returns true for an invalidated PMD. This allows GUP-fast to grab a reference on the folio.

Code that invalidates a PMD and then decides whether it may drop the mapping relies on GUP-fast backing off from an invalidated PMD. x86, arm64 and powerpc already reject invalidated PMDs in pmd_access_permitted().

Provide a LoongArch pmd_access_permitted() that requires _PAGE_PRESENT, so invalidated (and PROT_NONE) PMDs are not followed by GUP-fast.

Quoted 8 lines

To: Huacai Chen <[email protected]>
Cc: WANG Xuerui <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]

[Severity: Low]
This fixes a bug introduced when pmd_mkinvalid() and pmd_present() started using _PAGE_PRESENT_INVALID without an arch-specific pmd_access_permitted(). Should this include:

Fixes ddc1729b07cc ("LoongArch: Let pmd_present() return true when splitting pmd")
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author reviewer
#7 lore raw

PATCH v2 5/9 s390/mm: always clear _SEGMENT_ENTRY_READ in pmdp_invalidate()

In reply to Zi Yan

pmdp_invalidate() sets _SEGMENT_ENTRY_INVALID, but that bit alone does not make the entry pmd_protnone(). Also clear the _SEGMENT_ENTRY_READ bit to achieve it, so that GUP-fast can no longer grab a reference on the folio mapped by the invalidated pmd.

Code can invalidate a PMD and then based on folio refcount decides whether it may drop the mapping. That relies on GUP-fast backing off from an invalidated PMD, as it does on x86, arm64, and powerpc. For example, lazyfree THP discard is about to use pmdp_invalidate() to prevent GUP-fast before dropping a lazyfree folio.

With CONFIG_PAGE_TABLE_CHECK, pmdp_invalidate() already clears _SEGMENT_ENTRY_READ, which makes the entry pmd_protnone(), so GUP-fast does not follow it. Do that unconditionally. As noted in commit 7b4dde5e40ad6 ("s390/pgtable: Add s390 support for page table check"), an invalidated PMD that is pmd_protnone() is fine for the remaining pmd_protnone() users, which run under the page table lock or are lockless walkers that should not follow it anyway.

To: Alexander Gordeev <[email protected]>
To: Gerald Schaefer <[email protected]>
To: Heiko Carstens <[email protected]>
To: Vasily Gorbik <[email protected]>

Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc John Hubbard <[email protected]>
Cc Peter Xu <[email protected]>
---
 arch/s390/include/asm/pgtable.h | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
arch/s390/include/asm/pgtable.h +6 -2
index 2d5c2ab06de98..fe1ba746203ab 100644
@@ -1781,10 +1781,14 @@ static inline pmd_t pmdp_invalidate(struct vm_area_struct *vma,
 	pmd_t pmd = *pmdp;
 
 	VM_WARN_ON_ONCE(!pmd_present(pmd));
+	/*
+	 * _SEGMENT_ENTRY_INVALID alone also marks an old (not young) entry,
+	 * which lockless walkers like GUP-fast may follow. Clear
+	 * _SEGMENT_ENTRY_READ too, so the invalidated entry is pmd_protnone()
+	 * and is not followed, and page table check does not count it.
+	 */
 	pmd = set_pmd_bit(pmd, __pgprot(_SEGMENT_ENTRY_INVALID));
-#ifdef CONFIG_PAGE_TABLE_CHECK
 	pmd = clear_pmd_bit(pmd, __pgprot(_SEGMENT_ENTRY_READ));
-#endif
 	page_table_check_pmd_set(vma->vm_mm, addr, pmdp, pmd);
 	pmd = pmdp_xchg_direct(vma->vm_mm, addr, pmdp, pmd);
 	return pmd;
Signature · 1 line
2.53.0
maintainer Reviewed-by on v2 5/9
#8 lore raw

Re: [PATCH v2 5/9] s390/mm: always clear _SEGMENT_ENTRY_READ in pmdp_invalidate()

Quoted 47 lines · Zi Yan

pmdp_invalidate() sets _SEGMENT_ENTRY_INVALID, but that bit alone does not make the entry pmd_protnone(). Also clear the _SEGMENT_ENTRY_READ bit to achieve it, so that GUP-fast can no longer grab a reference on the folio mapped by the invalidated pmd.

Code can invalidate a PMD and then based on folio refcount decides whether it may drop the mapping. That relies on GUP-fast backing off from an invalidated PMD, as it does on x86, arm64, and powerpc. For example, lazyfree THP discard is about to use pmdp_invalidate() to prevent GUP-fast before dropping a lazyfree folio.

With CONFIG_PAGE_TABLE_CHECK, pmdp_invalidate() already clears _SEGMENT_ENTRY_READ, which makes the entry pmd_protnone(), so GUP-fast does not follow it. Do that unconditionally. As noted in commit 7b4dde5e40ad6 ("s390/pgtable: Add s390 support for page table check"), an invalidated PMD that is pmd_protnone() is fine for the remaining pmd_protnone() users, which run under the page table lock or are lockless walkers that should not follow it anyway.

To: Alexander Gordeev <[email protected]>
To: Gerald Schaefer <[email protected]>
To: Heiko Carstens <[email protected]>
To: Vasily Gorbik <[email protected]>

Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc John Hubbard <[email protected]>
Cc Peter Xu <[email protected]>
---
 arch/s390/include/asm/pgtable.h | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
arch/s390/include/asm/pgtable.h +3 -0
index 2d5c2ab06de98..fe1ba746203ab 100644
@@ -1781,10 +1781,14 @@ static inline pmd_t pmdp_invalidate(struct vm_area_struct *vma,
 	pmd_t pmd = *pmdp;
 
 	VM_WARN_ON_ONCE(!pmd_present(pmd));
+	/*
+	 * _SEGMENT_ENTRY_INVALID alone also marks an old (not young) entry,
+	 * which lockless walkers like GUP-fast may follow. Clear

arch/s390/include/asm/pgtable.h static inline pmd_t pmdp_invalidate(struct vm_area_struct *vma, · line 1794

Quoted 10 lines
arch/s390/include/asm/pgtable.h +3 -2
+	 * _SEGMENT_ENTRY_READ too, so the invalidated entry is pmd_protnone()
+	 * and is not followed, and page table check does not count it.
+	 */
 	pmd = set_pmd_bit(pmd, __pgprot(_SEGMENT_ENTRY_INVALID));
-#ifdef CONFIG_PAGE_TABLE_CHECK
 	pmd = clear_pmd_bit(pmd, __pgprot(_SEGMENT_ENTRY_READ));
-#endif
 	page_table_check_pmd_set(vma->vm_mm, addr, pmdp, pmd);
 	pmd = pmdp_xchg_direct(vma->vm_mm, addr, pmdp, pmd);
 	return pmd;
author reviewer
#9 lore raw

PATCH v2 6/9 sparc64: mm: fix thp_pte_count accounting around pmdp_invalidate()

In reply to Zi Yan

thp_pte_count is maintained in __set_pmd_acct() whenever _PAGE_PMD_HUGE flips. pmdp_invalidate() only clears _PAGE_VALID, so it does not flip that bit. But it decrements thp_pte_count on its own, because THP split replaces the invalidated PMD with a page table via pmd_populate(), which does not change thp_pte_count.

This only accounts for the PMD split case, where a PMD is invalidated and then replaced by a page table, but other cases exist:

1. Several callers invalidate a huge PMD and then install a valid one again with set_pmd_at(): MADV_FREE, page_mkclean_one(), and change_huge_pmd(). The valid PMD is not counted, as _PAGE_PMD_HUGE did not flip, so each such call loses one count.

2. When an invalidated PMD is cleared, _PAGE_PMD_HUGE flips and the count is decreased again.

Eventually, thp_pte_count can wrap around and cause wrong TSB sizing.

Fix it by moving the decrement from pmdp_invalidate() to pmd_set(), which backs pmd_populate(): THP split replaces the invalidated huge PMD with a page table through it, so pmd_set() decrements the count when the entry it overwrites is a huge PMD. Other pmd_populate() callers overwrite a none PMD.

THP split also calls pmd_populate() on a local pmd_t to fill in the PTEs before installing the page table. Initialize it to none, so pmd_set() does not read an uninitialized value.

Fixes 1e953d846ac0 ("sparc64 mm: Fix more TSB sizing issues")

To: "David S. Miller" <[email protected]>
To: Andreas Larsson <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 arch/sparc/include/asm/pgtable_64.h |  7 +++++++
 arch/sparc/mm/tlb.c                 | 27 +++++++++++++++------------
 mm/huge_memory.c                    |  4 ++--
 3 files changed, 24 insertions(+), 14 deletions(-)
arch/sparc/include/asm/pgtable_64.h +7 -0
index 44d1333065a6a..141c204975219 100644
@@ -803,19 +803,26 @@ static inline int pmd_present(pmd_t pmd)
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
 void set_pmd_at(struct mm_struct *mm, unsigned long addr,
 		pmd_t *pmdp, pmd_t pmd);
+void pmd_set_acct(struct mm_struct *mm, pmd_t old);
 #else
 static inline void set_pmd_at(struct mm_struct *mm, unsigned long addr,
 			      pmd_t *pmdp, pmd_t pmd)
 {
 	*pmdp = pmd;
 }
+
+static inline void pmd_set_acct(struct mm_struct *mm, pmd_t old)
+{
+}
 #endif
 
 static inline void pmd_set(struct mm_struct *mm, pmd_t *pmdp, pte_t *ptep)
 {
 	unsigned long val = __pa((unsigned long) (ptep));
+	pmd_t old = *pmdp;
 
 	pmd_val(*pmdp) = val;
+	pmd_set_acct(mm, old);
 }
 
 #define pud_set(pudp, pmdp)	\
arch/sparc/mm/tlb.c +15 -12
index 6d9dd5eb13287..909db4f7b6389 100644
@@ -228,6 +228,21 @@ static void __set_pmd_acct(struct mm_struct *mm, unsigned long addr,
 	}
 }
 
+/*
+ * Called by pmd_set() and thus pmd_populate(). THP split uses pmd_populate()
+ * on an invalidated huge PMD and needs the accounting.
+ */
+void pmd_set_acct(struct mm_struct *mm, pmd_t old)
+{
+	if (mm == &init_mm || !(pmd_val(old) & _PAGE_PMD_HUGE))
+		return;
+
+	if (is_huge_zero_pmd(old))
+		mm->context.hugetlb_pte_count--;
+	else
+		mm->context.thp_pte_count--;
+}
+
 void set_pmd_at(struct mm_struct *mm, unsigned long addr,
 		pmd_t *pmdp, pmd_t pmd)
 {
@@ -250,9 +265,6 @@ static inline pmd_t pmdp_establish(struct vm_area_struct *vma,
 	return old;
 }
 
-/*
- * This routine is only called when splitting a THP
- */
 pmd_t pmdp_invalidate(struct vm_area_struct *vma, unsigned long address,
 		     pmd_t *pmdp)
 {
@@ -263,15 +275,6 @@ pmd_t pmdp_invalidate(struct vm_area_struct *vma, unsigned long address,
 	old = pmdp_establish(vma, address, pmdp, entry);
 	flush_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
 
-	/*
-	 * set_pmd_at() will not be called in a way to decrement
-	 * thp_pte_count when splitting a THP, so do it now.
-	 * Sanity check pmd before doing the actual decrement.
-	 */
-	if ((pmd_val(entry) & _PAGE_PMD_HUGE) &&
-	    !is_huge_zero_pmd(entry))
-		(vma->vm_mm)->context.thp_pte_count--;
-
 	return old;
 }
 
mm/huge_memory.c +2 -2
index 91f3c7e7a044a..716bcf6873656 100644
@@ -3170,7 +3170,7 @@ static void __split_huge_zero_page_pmd(struct vm_area_struct *vma,
 {
 	struct mm_struct *mm = vma->vm_mm;
 	pgtable_t pgtable;
-	pmd_t _pmd, old_pmd;
+	pmd_t _pmd = __pmd(0), old_pmd;
 	unsigned long addr;
 	pte_t *pte;
 	int i;
@@ -3218,7 +3218,7 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 	struct folio *folio;
 	struct page *page;
 	pgtable_t pgtable;
-	pmd_t old_pmd, _pmd;
+	pmd_t old_pmd, _pmd = __pmd(0);
 	bool soft_dirty, uffd_wp = false, young = false, write = false;
 	bool anon_exclusive = false, dirty = false;
 	unsigned long addr;
Signature · 1 line
2.53.0
author reviewer
#10 lore raw

PATCH v2 7/9 mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

In reply to Zi Yan

From: Kyle Zeng <[email protected]>

__discard_anon_folio_pmd_locked() clears and flushes a huge PMD before checking whether the folio can be discarded. If the folio was redirtied or has unexpected references, it restores the original PMD. Reclaim holds the PMD lock and the anon_vma read lock, but not the owning mmap_lock.

Both zap_pmd_range() and mremap's get_old_pmd() can skip a none PMD without taking its lock. A concurrent munmap() or whole-VMA MREMAP_DONTUNMAP can therefore miss the PMD and later unlink the source VMA from its anon_vma, leaving a restored mapping behind. The anon_vma write lock taken by unlink_anon_vmas() waits for reclaim to finish, but does not repeat the skipped page-table walk. Once the remaining VMA links are removed, the folio's positive mapcount no longer guarantees a live anon_vma. Racing lazyfree reclaim against MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free in folio_lock_anon_vma_read().

Use pmdp_invalidate() to keep a recognizable, non-none huge PMD while the discard can still fail. Concurrent unmap and move operations then have to synchronize on the PMD lock instead of skipping the mapping. Clear the invalidated PMD only after the dirty and reference checks have succeeded, before removing the rmap and withdrawing the deposited page table. The full invalidation retains the TLB flush required for the dirty and GUP-fast checks.

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lance Yang <[email protected]>
Cc: Zi Yan <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 mm/huge_memory.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/huge_memory.c +3 -2
index 716bcf6873656..72322bb86ff4f 100644
@@ -3660,11 +3660,11 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
-	orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
+	orig_pmd = pmdp_invalidate(vma, addr, pmdp);
 
 	/*
 	 * Syncing against concurrent GUP-fast:
-	 * - clear PMD; barrier; read refcount
+	 * - invalidate PMD; barrier; read refcount
 	 * - inc refcount; barrier; read PMD
 	 */
 	smp_mb();
@@ -3699,6 +3699,7 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
+	pmdp_huge_get_and_clear(mm, addr, pmdp);
 	folio_remove_rmap_pmd(folio, pmd_page(orig_pmd), vma);
 	zap_deposited_table(mm, pmdp);
 	add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR);
Signature · 1 line
2.53.0
reviewer Acked-by on v2 7/9
#11 lore raw

Re: [PATCH v2 7/9] mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

Quoted 37 lines · Zi Yan

From: Kyle Zeng <[email protected]>

__discard_anon_folio_pmd_locked() clears and flushes a huge PMD before checking whether the folio can be discarded. If the folio was redirtied or has unexpected references, it restores the original PMD. Reclaim holds the PMD lock and the anon_vma read lock, but not the owning mmap_lock.

Both zap_pmd_range() and mremap's get_old_pmd() can skip a none PMD without taking its lock. A concurrent munmap() or whole-VMA MREMAP_DONTUNMAP can therefore miss the PMD and later unlink the source VMA from its anon_vma, leaving a restored mapping behind. The anon_vma write lock taken by unlink_anon_vmas() waits for reclaim to finish, but does not repeat the skipped page-table walk. Once the remaining VMA links are removed, the folio's positive mapcount no longer guarantees a live anon_vma. Racing lazyfree reclaim against MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free in folio_lock_anon_vma_read().

Use pmdp_invalidate() to keep a recognizable, non-none huge PMD while the discard can still fail. Concurrent unmap and move operations then have to synchronize on the PMD lock instead of skipping the mapping. Clear the invalidated PMD only after the dirty and reference checks have succeeded, before removing the rmap and withdrawing the deposited page table. The full invalidation retains the TLB flush required for the dirty and GUP-fast checks.

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lance Yang <[email protected]>
Cc: Zi Yan <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>

Quoted 8 lines

Cc: Barry Song <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]

Quoted 34 lines
---
 mm/huge_memory.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/huge_memory.c +3 -2
index 716bcf6873656..72322bb86ff4f 100644
@@ -3660,11 +3660,11 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
-	orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
+	orig_pmd = pmdp_invalidate(vma, addr, pmdp);
 
 	/*
 	 * Syncing against concurrent GUP-fast:
-	 * - clear PMD; barrier; read refcount
+	 * - invalidate PMD; barrier; read refcount
 	 * - inc refcount; barrier; read PMD
 	 */
 	smp_mb();
@@ -3699,6 +3699,7 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
+	pmdp_huge_get_and_clear(mm, addr, pmdp);
 	folio_remove_rmap_pmd(folio, pmd_page(orig_pmd), vma);
 	zap_deposited_table(mm, pmdp);
 	add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR);
Signature · 2 lines
-- 
2.53.0
reviewer Reviewed-by on v2 7/9
#12 lore raw

Re: [PATCH v2 7/9] mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

In reply to Zi Yan
Quoted 38 lines · Zi Yan

From: Kyle Zeng <[email protected]>

__discard_anon_folio_pmd_locked() clears and flushes a huge PMD before checking whether the folio can be discarded. If the folio was redirtied or has unexpected references, it restores the original PMD. Reclaim holds the PMD lock and the anon_vma read lock, but not the owning mmap_lock.

Both zap_pmd_range() and mremap's get_old_pmd() can skip a none PMD without taking its lock. A concurrent munmap() or whole-VMA MREMAP_DONTUNMAP can therefore miss the PMD and later unlink the source VMA from its anon_vma, leaving a restored mapping behind. The anon_vma write lock taken by unlink_anon_vmas() waits for reclaim to finish, but does not repeat the skipped page-table walk. Once the remaining VMA links are removed, the folio's positive mapcount no longer guarantees a live anon_vma. Racing lazyfree reclaim against MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free in folio_lock_anon_vma_read().

Use pmdp_invalidate() to keep a recognizable, non-none huge PMD while the discard can still fail. Concurrent unmap and move operations then have to synchronize on the PMD lock instead of skipping the mapping. Clear the invalidated PMD only after the dirty and reference checks have succeeded, before removing the rmap and withdrawing the deposited page table. The full invalidation retains the TLB flush required for the dirty and GUP-fast checks.

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lance Yang <[email protected]>
Cc: Zi Yan <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>

Quoted 8 lines

Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]
---

Make sense to me.

maintainer Reviewed-by on v2 7/9
#13 lore raw

Re: [PATCH v2 7/9] mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

In reply to Zi Yan
Quoted 7 lines · Zi Yan

From: Kyle Zeng <[email protected]>

__discard_anon_folio_pmd_locked() clears and flushes a huge PMD before checking whether the folio can be discarded. If the folio was redirtied or has unexpected references, it restores the original PMD. Reclaim holds the PMD lock and the anon_vma read lock, but not the owning mmap_lock.

Quoted 10 lines

Both zap_pmd_range() and mremap's get_old_pmd() can skip a none PMD without taking its lock. A concurrent munmap() or whole-VMA MREMAP_DONTUNMAP can therefore miss the PMD and later unlink the source VMA from its anon_vma, leaving a restored mapping behind. The anon_vma write lock taken by unlink_anon_vmas() waits for reclaim to finish, but does not repeat the skipped page-table walk. Once the remaining VMA links are removed, the folio's positive mapcount no longer guarantees a live anon_vma. Racing lazyfree reclaim against MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free in folio_lock_anon_vma_read().

As usual, have to say that MREMAP_DONTUNMAP was probably a mistake :))

Quoted 11 lines

Use pmdp_invalidate() to keep a recognizable, non-none huge PMD while the discard can still fail. Concurrent unmap and move operations then have to synchronize on the PMD lock instead of skipping the mapping. Clear the invalidated PMD only after the dirty and reference checks have succeeded, before removing the rmap and withdrawing the deposited page table. The full invalidation retains the TLB flush required for the dirty and GUP-fast checks.

LGTM so:

Quoted 28 lines

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lance Yang <[email protected]>
Cc: Zi Yan <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 mm/huge_memory.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/huge_memory.c +0 -0
index 716bcf6873656..72322bb86ff4f 100644
@@ -3660,11 +3660,11 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}

mm/huge_memory.c static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma, · line 3669

Quoted 10 lines
mm/huge_memory.c +2 -2
 
-	orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
+	orig_pmd = pmdp_invalidate(vma, addr, pmdp);
 
 	/*
 	 * Syncing against concurrent GUP-fast:
-	 * - clear PMD; barrier; read refcount
+	 * - invalidate PMD; barrier; read refcount
 	 * - inc refcount; barrier; read PMD
 	 */

Similar to comment on other patch, could we have a 'paired with' and ref. to the GUP-fast function to keep with memory barrier convention? I think in try_grab_folio_fast().

Quoted 11 lines
mm/huge_memory.c +1 -1
 	smp_mb();
@@ -3699,6 +3699,7 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
+	pmdp_huge_get_and_clear(mm, addr, pmdp);
 	folio_remove_rmap_pmd(folio, pmd_page(orig_pmd), vma);
 	zap_deposited_table(mm, pmdp);
 	add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR);
 
--
Quoted 2 lines

2.53.0

--
Cheers, Lorenzo

#14 lore raw

Re: [PATCH v2 7/9] mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

In reply to Zi Yan
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] mm/huge_memory: pmdp_invalidate() breaks GUP-fast sync on 32-bit MIPS - [Medium] mm: doubled…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] mm/huge_memory: pmdp_invalidate() breaks GUP-fast sync on 32-bit MIPS
- [Medium] mm: doubled flush_hash_hugepage() on PowerPC64 Hash MMU in lazyfree discard
- [Medium] mm: doubled SMP TLB cross-calls on sparc64 in lazyfree THP discard
- [Low] mm/huge_memory: commit message omits that PMD discard is currently unused
--

commit eac5b1c8b38dc617c570fb7825525d02213dcb00
Author: Kyle Zeng <[email protected]>

mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

This commit changes __discard_anon_folio_pmd_locked() to invalidate the huge PMD with pmdp_invalidate() instead of clearing it with pmdp_huge_clear_flush(), deferring pmdp_huge_get_and_clear() until after the dirty and reference count checks succeed.

Quoted 5 lines

Once the remaining VMA
links are removed, the folio's positive mapcount no longer guarantees a live anon_vma. Racing lazyfree reclaim against MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free in folio_lock_anon_vma_read().

[Severity: Low]
Is the present-tense description of the use-after-free accurate at this commit?

Commit 984c0700854e ("mm/rmap: don't discard lazyfree THPs at PMD level") already removed the sole call to unmap_huge_pmd_locked(), leaving __discard_anon_folio_pmd_locked() unused until a follow-up patch re-enables PMD-level lazyfree discard. Mentioning that context would help reviewers and explain why Fixes and Cc: stable trailers are omitted.

Quoted 8 lines
mm/huge_memory.c +0 -0
index 716bcf6873656..72322bb86ff4f 100644
@@ -3660,11 +3660,11 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 

mm/huge_memory.c static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma, · line 3670

Quoted 10 lines
mm/huge_memory.c +2 -2
-	orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
+	orig_pmd = pmdp_invalidate(vma, addr, pmdp);
 
 	/*
 	 * Syncing against concurrent GUP-fast:
-	 * - clear PMD; barrier; read refcount
+	 * - invalidate PMD; barrier; read refcount
 	 * - inc refcount; barrier; read PMD
 	 */
 	smp_mb();

[Severity: High]
Can switching to pmdp_invalidate() break GUP-fast synchronization on 32-bit MIPS?

On MIPS, pmd_mkinvalid() clears _PAGE_PRESENT, _PAGE_VALID, and _PAGE_DIRTY, leaving _PAGE_HUGE, _PAGE_WRITE, and PFN bits set. Unlike 64-bit MIPS, 32-bit MIPS pmd_present() in arch/mips/include/asm/pgtable-32.h only checks
pmd_val(pmd) != (unsigned long) invalid_pte_table and ignores _PAGE_PRESENT. Because MIPS uses the generic pmd_access_permitted(), gup_fast_pmd_leaf() still treats the invalidated huge PMD as present and writable on 32-bit SMP kernels with THP and GUP-fast enabled:

CPU0 CPU1
__discard_anon_folio_pmd_locked()
pmdp_invalidate(vma, addr, pmdp)
smp_mb()
folio_ref_count() == map_count + 1
gup_fast_pmd_leaf()
pmd_access_permitted() -> true try_grab_folio_fast() <-- pins folio pmd_val() recheck passes
pmdp_huge_get_and_clear()
folio_remove_rmap_pmd()

An O_DIRECT read racing against MADV_FREE reclaim can then pin and write to the detached folio while subsequent userspace accesses fault in a fresh zero page, causing silent data loss once PMD-level lazyfree discard is re-enabled.

A prerequisite MIPS fix is needed before this change, either checking _PAGE_PRESENT for _PAGE_HUGE entries in 32-bit pmd_present() or defining a MIPS pmd_access_permitted() that requires _PAGE_PRESENT.

mm/huge_memory.c static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma, · line 3705

Quoted 8 lines
mm/huge_memory.c +1 -0
@@ -3699,6 +3699,7 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
+	pmdp_huge_get_and_clear(mm, addr, pmdp);
 	folio_remove_rmap_pmd(folio, pmd_page(orig_pmd), vma);
 	zap_deposited_table(mm, pmdp);
 	add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR);

[Severity: Medium]
Does calling pmdp_huge_get_and_clear() after pmdp_invalidate() double flush_hash_hugepage() calls on PowerPC64 Hash MMU?

On Book3S 64-bit Hash MMU, pmdp_invalidate() clears _PAGE_PRESENT and sets _PAGE_INVALID while leaving H_PAGE_HASHPTE set in *pmdp and leaving hpte_slot_array intact after running flush_hash_hugepage(). When pmdp_huge_get_and_clear() runs next, pmd_present(*pmdp) is still true due to _PAGE_INVALID, so hash__pmdp_huge_get_and_clear() calls hash__pmd_hugepage_update() before zeroing hpte_slot_array and runs a second full flush_hash_hugepage().

This doubles the 16MB HPTE and TLB invalidations on every discarded lazyfree THP, adding redundant broadcast tlbie instructions with IRQs disabled or repeated H_BULK_REMOVE/H_BLOCK_REMOVE hypercalls on pSeries LPARs.

[Severity: Medium]
Does this also double synchronous SMP TLB cross-calls on sparc64?

In __set_pmd_acct(), sparc64 checks !pmd_none(orig) and pmd_trans_huge(orig) without testing _PAGE_VALID. Because try_to_unmap_one() does not activate lazy_mmu_mode, pmdp_invalidate() triggers two immediate flush_tsb_user_page() and smp_flush_tlb_page() cross-calls (one per REAL_HPAGE_SIZE half). Clearing the invalidated PMD in pmdp_huge_get_and_clear() (or restoring orig_pmd on abort) then runs __set_pmd_acct() over the non-none invalidated entry and triggers two more flush_tsb_user_page() and smp_flush_tlb_page() cross-calls.

Every lazyfree THP discard or abort on SMP sparc64 therefore pays 4 synchronous TLB shootdown IPIs and mm->context.lock acquisitions instead of 2.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
reviewer Reviewed-by on v2 7/9
#15 lore raw

Re: [PATCH v2 7/9] mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

In reply to Zi Yan
Quoted 68 lines · Zi Yan

From: Kyle Zeng <[email protected]>

__discard_anon_folio_pmd_locked() clears and flushes a huge PMD before checking whether the folio can be discarded. If the folio was redirtied or has unexpected references, it restores the original PMD. Reclaim holds the PMD lock and the anon_vma read lock, but not the owning mmap_lock.

Both zap_pmd_range() and mremap's get_old_pmd() can skip a none PMD without taking its lock. A concurrent munmap() or whole-VMA MREMAP_DONTUNMAP can therefore miss the PMD and later unlink the source VMA from its anon_vma, leaving a restored mapping behind. The anon_vma write lock taken by unlink_anon_vmas() waits for reclaim to finish, but does not repeat the skipped page-table walk. Once the remaining VMA links are removed, the folio's positive mapcount no longer guarantees a live anon_vma. Racing lazyfree reclaim against MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free in folio_lock_anon_vma_read().

Use pmdp_invalidate() to keep a recognizable, non-none huge PMD while the discard can still fail. Concurrent unmap and move operations then have to synchronize on the PMD lock instead of skipping the mapping. Clear the invalidated PMD only after the dirty and reference checks have succeeded, before removing the rmap and withdrawing the deposited page table. The full invalidation retains the TLB flush required for the dirty and GUP-fast checks.

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lance Yang <[email protected]>
Cc: Zi Yan <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]
---
mm/huge_memory.c | 5 +++--

1 file changed, 3 insertions(+), 2 deletions(-)
mm/huge_memory.c +2 -2
index 716bcf6873656..72322bb86ff4f 100644
@@ -3660,11 +3660,11 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
-	orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
+	orig_pmd = pmdp_invalidate(vma, addr, pmdp);
 
 	/*
 	 * Syncing against concurrent GUP-fast:
-	 * - clear PMD; barrier; read refcount
+	 * - invalidate PMD; barrier; read refcount
 	 * - inc refcount; barrier; read PMD
 	 */
 	smp_mb();

mm/huge_memory.c static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma, · line 3702

Quoted 4 lines
mm/huge_memory.c +1 -0
@@ -3699,6 +3699,7 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
+	pmdp_huge_get_and_clear(mm, addr, pmdp);

Right. Clearing the PMD while we could still bail out was kinda asking for trouble without mmap_lock (that one's on me ...) ;) Thanks!

I would assume the arch issues Sashiko flagged [1] aren't hard to fix :P

Invalidate first, then clear once we're sure. That's how it should work anyway.

[1] https://lore.kernel.org/all/[email protected]/

reviewer
#16 lore raw

Re: [PATCH v2 7/9] mm/huge_memory: avoid transient none PMDs during lazyfree reclaim

Quoted 59 lines · Lance Yang
Quoted 57 lines · Zi Yan

From: Kyle Zeng <[email protected]>

__discard_anon_folio_pmd_locked() clears and flushes a huge PMD before checking whether the folio can be discarded. If the folio was redirtied or has unexpected references, it restores the original PMD. Reclaim holds the PMD lock and the anon_vma read lock, but not the owning mmap_lock.

Both zap_pmd_range() and mremap's get_old_pmd() can skip a none PMD without taking its lock. A concurrent munmap() or whole-VMA MREMAP_DONTUNMAP can therefore miss the PMD and later unlink the source VMA from its anon_vma, leaving a restored mapping behind. The anon_vma write lock taken by unlink_anon_vmas() waits for reclaim to finish, but does not repeat the skipped page-table walk. Once the remaining VMA links are removed, the folio's positive mapcount no longer guarantees a live anon_vma. Racing lazyfree reclaim against MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free in folio_lock_anon_vma_read().

Use pmdp_invalidate() to keep a recognizable, non-none huge PMD while the discard can still fail. Concurrent unmap and move operations then have to synchronize on the PMD lock instead of skipping the mapping. Clear the invalidated PMD only after the dirty and reference checks have succeeded, before removing the rmap and withdrawing the deposited page table. The full invalidation retains the TLB flush required for the dirty and GUP-fast checks.

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lance Yang <[email protected]>
Cc: Zi Yan <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Jason Gunthorpe <[email protected]>
Cc: John Hubbard <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]
---
mm/huge_memory.c | 5 +++--

1 file changed, 3 insertions(+), 2 deletions(-)
mm/huge_memory.c +0 -0
index 716bcf6873656..72322bb86ff4f 100644
@@ -3660,11 +3660,11 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
Quoted 2 lines

mm/huge_memory.c static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma, · line 3663

Quoted 2 lines
mm/huge_memory.c +1 -1
-	orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
+	orig_pmd = pmdp_invalidate(vma, addr, pmdp);

Ouch ... Sashiko has a point on flush_cache_range() in patch #08 [1].

Just like set_pmd_migration_entry(), we should call flush_cache_range() before pmdp_invalidate() in __discard_anon_folio_pmd_locked() so caches get flushed while the mapping is still valid (on archs where it isn't a no-op) ...

Something like:

- orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp);
+ flush_cache_range(vma, addr, addr + HPAGE_PMD_SIZE);
+ orig_pmd = pmdp_invalidate(vma, addr, pmdp);

[1] https://lore.kernel.org/all/[email protected]/

Quoted 26 lines

mm/huge_memory.c static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma, · line 3702

Quoted 13 lines
mm/huge_memory.c +2 -1
 	/*
 	 * Syncing against concurrent GUP-fast:
-	 * - clear PMD; barrier; read refcount
+	 * - invalidate PMD; barrier; read refcount
 	 * - inc refcount; barrier; read PMD
 	 */
 	smp_mb();
@@ -3699,6 +3699,7 @@ static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma,
 		return false;
 	}
 
+	pmdp_huge_get_and_clear(mm, addr, pmdp);

Right. Clearing the PMD while we could still bail out was kinda asking for trouble without mmap_lock (that one's on me ...) ;) Thanks!

I would assume the arch issues Sashiko flagged [1] aren't hard to fix :P

Invalidate first, then clear once we're sure. That's how it should work anyway.

[1] https://lore.kernel.org/all/[email protected]/

author reviewer
#17 lore raw

PATCH v2 8/9 mm/rmap: re-enable discarding lazyfree THPs at PMD level

In reply to Zi Yan

The patch "mm/rmap: don't discard lazyfree THPs at PMD level" disabled the PMD-level discard, because it cleared the PMD before checking whether the folio could be discarded, and munmap() or mremap() could skip that transiently none PMD.

__discard_anon_folio_pmd_locked() now keeps the PMD invalidated, not cleared, until the discard is committed, GUP-fast no longer follows an invalidated PMD on any architecture, powerpc page table check no longer counts an invalidated PMD as mapped, and sparc64 keeps thp_pte_count balanced when an invalidated PMD is set again or cleared. Discard lazyfree THPs at PMD level again.

Also call update_hiwater_rss() before unmap_huge_pmd_locked(), as the PTE path does before lowering RSS. The PMD path has skipped it since the PMD-level discard was added in commit 735ecdfaf4e8 ("mm/vmscan: avoid split lazyfree THP during shrink_folio_list()"), so a discard could lower RSS without recording the high watermark first, and VmHWM could be under-reported.

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lorenzo Stoakes <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Harry Yoo <[email protected]>
Cc: Jann Horn <[email protected]>
Cc: Lance Yang <[email protected]>
Cc: Kyle Zeng <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 mm/rmap.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
mm/rmap.c +13 -0
index f0c17d2e04847..32acae9efc313 100644
@@ -2285,6 +2285,19 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 		}
 
 		if (!pvmw.pte) {
+			if (folio_test_lazyfree(folio)) {
+				/* Update high watermark before we lower rss */
+				update_hiwater_rss(mm);
+				if (unmap_huge_pmd_locked(vma, pvmw.address, pvmw.pmd, folio))
+					goto walk_done;
+				/*
+				 * unmap_huge_pmd_locked has either already marked
+				 * the folio as swap-backed or decided to retain it
+				 * due to GUP or speculative references.
+				 */
+				goto walk_abort;
+			}
+
 			if (flags & TTU_SPLIT_HUGE_PMD) {
 				/*
 				 * We temporarily have to drop the PTL and
Signature · 1 line
2.53.0
reviewer Acked-by on v2 8/9
#18 lore raw

Re: [PATCH v2 8/9] mm/rmap: re-enable discarding lazyfree THPs at PMD level

Quoted 1 line · Zi Yan

The patch "mm/rmap: don't discard lazyfree THPs at PMD level" disabled

Nit, the hash for the disabling patch would be useful here.

Quoted 21 lines

the PMD-level discard, because it cleared the PMD before checking whether the folio could be discarded, and munmap() or mremap() could skip that transiently none PMD.

__discard_anon_folio_pmd_locked() now keeps the PMD invalidated, not cleared, until the discard is committed, GUP-fast no longer follows an invalidated PMD on any architecture, powerpc page table check no longer counts an invalidated PMD as mapped, and sparc64 keeps thp_pte_count balanced when an invalidated PMD is set again or cleared. Discard lazyfree THPs at PMD level again.

Also call update_hiwater_rss() before unmap_huge_pmd_locked(), as the PTE path does before lowering RSS. The PMD path has skipped it since the PMD-level discard was added in commit 735ecdfaf4e8 ("mm/vmscan: avoid split lazyfree THP during shrink_folio_list()"), so a discard could lower RSS without recording the high watermark first, and VmHWM could be under-reported.

Quoted 12 lines

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lorenzo Stoakes <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Harry Yoo <[email protected]>
Cc: Jann Horn <[email protected]>
Cc: Lance Yang <[email protected]>
Cc: Kyle Zeng <[email protected]>
Cc: [email protected]
Cc: [email protected]

Quoted 32 lines
---
 mm/rmap.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
mm/rmap.c +13 -0
index f0c17d2e04847..32acae9efc313 100644
@@ -2285,6 +2285,19 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 		}
 
 		if (!pvmw.pte) {
+			if (folio_test_lazyfree(folio)) {
+				/* Update high watermark before we lower rss */
+				update_hiwater_rss(mm);
+				if (unmap_huge_pmd_locked(vma, pvmw.address, pvmw.pmd, folio))
+					goto walk_done;
+				/*
+				 * unmap_huge_pmd_locked has either already marked
+				 * the folio as swap-backed or decided to retain it
+				 * due to GUP or speculative references.
+				 */
+				goto walk_abort;
+			}
+
 			if (flags & TTU_SPLIT_HUGE_PMD) {
 				/*
 				 * We temporarily have to drop the PTL and
Signature · 2 lines
-- 
2.53.0
reviewer Reviewed-by on v2 8/9
#19 lore raw

Re: [PATCH v2 8/9] mm/rmap: re-enable discarding lazyfree THPs at PMD level

In reply to Zi Yan
Quoted 22 lines · Zi Yan

The patch "mm/rmap: don't discard lazyfree THPs at PMD level" disabled the PMD-level discard, because it cleared the PMD before checking whether the folio could be discarded, and munmap() or mremap() could skip that transiently none PMD.

__discard_anon_folio_pmd_locked() now keeps the PMD invalidated, not cleared, until the discard is committed, GUP-fast no longer follows an invalidated PMD on any architecture, powerpc page table check no longer counts an invalidated PMD as mapped, and sparc64 keeps thp_pte_count balanced when an invalidated PMD is set again or cleared. Discard lazyfree THPs at PMD level again.

Also call update_hiwater_rss() before unmap_huge_pmd_locked(), as the PTE path does before lowering RSS. The PMD path has skipped it since the PMD-level discard was added in commit 735ecdfaf4e8 ("mm/vmscan: avoid split lazyfree THP during shrink_folio_list()"), so a discard could lower RSS without recording the high watermark first, and VmHWM could be under-reported.

Quoted 13 lines

To: Andrew Morton <[email protected]>
To: David Hildenbrand <[email protected]>
To: Lorenzo Stoakes <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Harry Yoo <[email protected]>
Cc: Jann Horn <[email protected]>
Cc: Lance Yang <[email protected]>
Cc: Kyle Zeng <[email protected]>
Cc: [email protected]
Cc: [email protected]
---

Make sense to me.

#20 lore raw

Re: [PATCH v2 8/9] mm/rmap: re-enable discarding lazyfree THPs at PMD level

In reply to Zi Yan
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] mm/rmap: 32-bit MIPS GUP-fast still follows invalidated THP PMDs on discard - [High] mm/rmap…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] mm/rmap: 32-bit MIPS GUP-fast still follows invalidated THP PMDs on discard
- [High] mm/rmap: lazyfree THP PMD discard skips flush_cache_range() --

commit 479154fc094b2551853b0d7d30d7d879d05e867b
Author: Zi Yan <[email protected]>

mm/rmap: re-enable discarding lazyfree THPs at PMD level

This commit re-enables PMD-level discarding of lazyfree THPs in try_to_unmap_one() via unmap_huge_pmd_locked(), and calls update_hiwater_rss() before lowering RSS.

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2292

Quoted 13 lines
mm/rmap.c +5 -0
index f0c17d2e04847..32acae9efc313 100644
@@ -2285,6 +2285,19 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 		}
 
 		if (!pvmw.pte) {
+			if (folio_test_lazyfree(folio)) {
+				/* Update high watermark before we lower rss */
+				update_hiwater_rss(mm);
+				if (unmap_huge_pmd_locked(vma, pvmw.address, pvmw.pmd, folio))
+					goto walk_done;

[Severity: High]
Can 32-bit MIPS GUP-fast still follow the invalidated PMD during unmap_huge_pmd_locked()?

__discard_anon_folio_pmd_locked() keeps the invalidated PMD in place across the folio_ref_count() check until pmdp_huge_get_and_clear(), relying on GUP-fast to back off. On 32-bit MIPS with THP enabled, pmd_mkinvalid() clears _PAGE_PRESENT, but pmd_present() ignores it:

arch/mips/include/asm/pgtable-32.h:pmd_present() {
	return pmd_val(pmd) != (unsigned long) invalid_pte_table;
}

Because MIPS uses the generic pmd_access_permitted() and has no pmd_protnone(), gup_fast_pmd_leaf() still accepts the invalidated PMD:

CPU0 (reclaim) CPU1 (GUP-fast on 32-bit MIPS)
__discard_anon_folio_pmd_locked()
pmdp_invalidate()
smp_mb()
folio_ref_count() == mapcount+1

                                   gup_fast_pmd_leaf()
                                     pmd_access_permitted() -> true
                                     try_grab_folio_fast()  <-- grabs folio
                                     pmd_val(orig) == *pmdp -> true

pmdp_huge_get_and_clear()
folio_remove_rmap_pmd()

Reclaim then discards and unmaps the THP while GUP-fast holds a live reference or DMA write pin on the detached folio. Later faults allocate a fresh zero page while the GUP-fast caller reads or writes the old folio.

Checking _PAGE_PRESENT for _PAGE_HUGE entries in 32-bit MIPS pmd_present(), matching arch/mips/include/asm/pgtable-64.h, would close this race.

[Severity: High]
Does this path skip flush_cache_range() before unmapping the huge PMD?

Unlike the PTE path in try_to_unmap_one() and other PMD unmap paths such as set_pmd_migration_entry(), __discard_anon_folio_pmd_locked() calls pmdp_invalidate() and pmdp_huge_get_and_clear() without calling flush_cache_range(vma, addr, addr + HPAGE_PMD_SIZE) first.

A MAP_DROPPABLE THP can be discarded while dirty without madvise(MADV_FREE) ever flushing it. On MIPS R4K with cpu_has_dc_aliases, flush_tlb_range() assumes flush_cache_range() already flushed aliasing VIPT dcache lines, so delayed writeback after folio reuse can corrupt reallocated pages.

Executable mappings on MIPS and 32-bit ARM LPAE and user register windows on SPARC64 also rely on flush_cache_range(). Calling flush_cache_range() before pmdp_invalidate() in __discard_anon_folio_pmd_locked() would match set_pmd_migration_entry().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
reviewer Reviewed-by on v2 8/9
#21 lore raw

Re: [PATCH v2 8/9] mm/rmap: re-enable discarding lazyfree THPs at PMD level

In reply to Zi Yan

On Thu, Dec 03, 2026 at 11:17:56PM -0500, Zi Yan wrote:
[...]

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2288

Quoted 9 lines
mm/rmap.c +1 -0
index f0c17d2e04847..32acae9efc313 100644
@@ -2285,6 +2285,19 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 		}
 
 		if (!pvmw.pte) {
+			if (folio_test_lazyfree(folio)) {

Good to have PMD-level lazyfree discard back :D

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2290

Quoted 2 lines
mm/rmap.c +2 -0
+				/* Update high watermark before we lower rss */
+				update_hiwater_rss(mm);

And, thanks (x1024) for picking up the update_hiwater_rss() bit I missed back then :)

mm/rmap.c static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2300

Quoted 10 lines
mm/rmap.c +10 -0
+				if (unmap_huge_pmd_locked(vma, pvmw.address, pvmw.pmd, folio))
+					goto walk_done;
+				/*
+				 * unmap_huge_pmd_locked has either already marked
+				 * the folio as swap-backed or decided to retain it
+				 * due to GUP or speculative references.
+				 */
+				goto walk_abort;
+			}
+

Assuming the flush_cache_range() piece from patch 7 is sorted out, LGTM!

author reviewer
#22 lore raw

PATCH v2 9/9 userfaultfd: avoid transient none PMDs during UFFDIO_MOVE

In reply to Zi Yan

UFFDIO_MOVE under the page table lock clears a PMD, checks if the folio is DMA pinned, and restores it if that is the case. A concurrent zap can skip a none PMD without taking the page table lock. Since UFFDIO_MOVE holds the VMA or mmap read lock, those taking the read lock can race with it, e.g., MADV_DONTNEED. In the MADV_DONTNEED case, the affected memory can be neither discarded nor zeroed.

Fix it by invalidating the PMD with pmdp_invalidate() instead. Also add smp_mb() between pmdp_invalidate() and reading folio pincount to pair with GUP-fast.

Fixes adef440691bab ("userfaultfd: UFFDIO_MOVE uABI")

To: David Hildenbrand <[email protected]>
To: Zi Yan <[email protected]>
To: Andrew Morton <[email protected]>
To: Andrea Arcangeli <[email protected]>
To: Suren Baghdasaryan <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>
Cc: Lance Yang <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 mm/huge_memory.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
mm/huge_memory.c +12 -1
index 72322bb86ff4f..6a9635c7e0b48 100644
@@ -2993,7 +2993,17 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 			goto unlock_ptls;
 		}
 
-		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
+		/*
+		 * Invalidate the PMD so that a concurrent zap does not skip it
+		 * in case a restore is needed afterwards.
+		 */
+		src_pmdval = pmdp_invalidate(src_vma, src_addr, src_pmd);
+		/*
+		 * Syncing against concurrent GUP-fast:
+		 * - invalidate PMD; barrier; read pincount
+		 * - inc pincount; barrier; read PMD
+		 */
+		smp_mb();
 		/* Folio got pinned from under us. Put it back and fail the move. */
 		if (folio_maybe_dma_pinned(src_folio)) {
 			set_pmd_at(mm, src_addr, src_pmd, src_pmdval);
@@ -3004,6 +3014,7 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 		folio_move_anon_rmap(src_folio, dst_vma);
 		src_folio->index = linear_anon_page_index(dst_vma, dst_addr);
 
+		pmdp_huge_get_and_clear(mm, src_addr, src_pmd);
 		_dst_pmd = folio_mk_pmd(src_folio, dst_vma->vm_page_prot);
 		/* Follow mremap() behavior and treat the entry dirty after the move */
 		_dst_pmd = pmd_mkwrite(pmd_mkdirty(_dst_pmd), dst_vma);
Signature · 1 line
2.53.0
maintainer Reviewed-by on v2 9/9
#23 lore raw

Re: [PATCH v2 9/9] userfaultfd: avoid transient none PMDs during UFFDIO_MOVE

Quoted 7 lines · Zi Yan

UFFDIO_MOVE under the page table lock clears a PMD, checks if the folio is DMA pinned, and restores it if that is the case. A concurrent zap can skip a none PMD without taking the page table lock. Since UFFDIO_MOVE holds the VMA or mmap read lock, those taking the read lock can race with it, e.g., MADV_DONTNEED. In the MADV_DONTNEED case, the affected memory can be neither discarded nor zeroed.

Quoted 5 lines

Fix it by invalidating the PMD with pmdp_invalidate() instead. Also add smp_mb() between pmdp_invalidate() and reading folio pincount to pair with GUP-fast.

Fixes adef440691bab ("userfaultfd: UFFDIO_MOVE uABI")

No Cc: stable, on purpose?

Quoted 1 line

With nits addressed, LGTM, so:

Quoted 26 lines

To: David Hildenbrand <[email protected]>
To: Zi Yan <[email protected]>
To: Andrew Morton <[email protected]>
To: Andrea Arcangeli <[email protected]>
To: Suren Baghdasaryan <[email protected]>
Cc: Baolin Wang <[email protected]>
Cc: "Liam R. Howlett" <[email protected]>
Cc: Nico Pache <[email protected]>
Cc: Ryan Roberts <[email protected]>
Cc: Dev Jain <[email protected]>
Cc: Barry Song <[email protected]>
Cc: Lance Yang <[email protected]>
Cc: Usama Arif <[email protected]>
Cc: Kiryl Shutsemau <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Cc: [email protected]

---
 mm/huge_memory.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
mm/huge_memory.c +0 -0
index 72322bb86ff4f..6a9635c7e0b48 100644

mm/huge_memory.c int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm · line 2999

Quoted 8 lines
mm/huge_memory.c +4 -1
@@ -2993,7 +2993,17 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 			goto unlock_ptls;
 		}
 
-		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
+		/*
+		 * Invalidate the PMD so that a concurrent zap does not skip it
+		 * in case a restore is needed afterwards.
+		 */

OK had to read it a few times to get it - it being cleared would result in zap skipping it (+ thus not blocking on PMD PTL) + potentially a restore would then leave an unzapped entry.

Maybe slightly rephrase like:

/*
* A concurrent zap skips none entries without taking the PTL, so
* invalidate rather than clear. The zap then blocks on the PTL until
* the move has either completed or been aborted and the entry restored. */

mm/huge_memory.c int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm · line 3004

Quoted 5 lines
mm/huge_memory.c +5 -0
+		src_pmdval = pmdp_invalidate(src_vma, src_addr, src_pmd);
+		/*
+		 * Syncing against concurrent GUP-fast:
+		 * - invalidate PMD; barrier; read pincount
+		 * - inc pincount; barrier; read PMD

Worth saying specifically 'pairs with' and the relevant function by convention.

mm/huge_memory.c int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm · line 3006

Quoted 2 lines
mm/huge_memory.c +2 -0
+		 */
+		smp_mb();

Real nitty but maybe newline here to highlight that you have a fence here :)

Quoted 13 lines
mm/huge_memory.c +1 -1
 		/* Folio got pinned from under us. Put it back and fail the move. */
 		if (folio_maybe_dma_pinned(src_folio)) {
 			set_pmd_at(mm, src_addr, src_pmd, src_pmdval);
@@ -3004,6 +3014,7 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 		folio_move_anon_rmap(src_folio, dst_vma);
 		src_folio->index = linear_anon_page_index(dst_vma, dst_addr);
 
+		pmdp_huge_get_and_clear(mm, src_addr, src_pmd);
 		_dst_pmd = folio_mk_pmd(src_folio, dst_vma->vm_page_prot);
 		/* Follow mremap() behavior and treat the entry dirty after the move */
 		_dst_pmd = pmd_mkwrite(pmd_mkdirty(_dst_pmd), dst_vma);
 
--
Quoted 2 lines

2.53.0

--
Cheers, Lorenzo

#24 lore raw

Re: [PATCH v2 9/9] userfaultfd: avoid transient none PMDs during UFFDIO_MOVE

In reply to Zi Yan
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] mm: move_pages_huge_pmd() lets 32-bit MIPS GUP-fast pin invalidated PMDs - [Medium] mm: double…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] mm: move_pages_huge_pmd() lets 32-bit MIPS GUP-fast pin invalidated PMDs
- [Medium] mm: double HPTE/TLB flush in move_pages_huge_pmd() on powerpc hash MMU
- [Medium] mm: redundant sparc64 TLB/TSB IPI shootdowns in move_pages_huge_pmd()
--

commit 620660dab391564b04de30b5d319a5382bec8aeb
Author: Zi Yan <[email protected]>

userfaultfd: avoid transient none PMDs during UFFDIO_MOVE

This commit changes move_pages_huge_pmd() to invalidate the source PMD with pmdp_invalidate() and an smp_mb() before checking folio_maybe_dma_pinned(), deferring pmdp_huge_get_and_clear() until after the pin check so concurrent zaps do not skip a transiently cleared PMD.

Quoted 13 lines
mm/huge_memory.c +4 -1
index 72322bb86ff4f..6a9635c7e0b48 100644
@@ -2993,7 +2993,17 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 			goto unlock_ptls;
 		}
 
-		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
+		/*
+		 * Invalidate the PMD so that a concurrent zap does not skip it
+		 * in case a restore is needed afterwards.
+		 */

mm/huge_memory.c int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm · line 3009

Quoted 10 lines
mm/huge_memory.c +7 -0
+		src_pmdval = pmdp_invalidate(src_vma, src_addr, src_pmd);
+		/*
+		 * Syncing against concurrent GUP-fast:
+		 * - invalidate PMD; barrier; read pincount
+		 * - inc pincount; barrier; read PMD
+		 */
+		smp_mb();
 		/* Folio got pinned from under us. Put it back and fail the move. */
 		if (folio_maybe_dma_pinned(src_folio)) {
 			set_pmd_at(mm, src_addr, src_pmd, src_pmdval);

[Severity: High]
Can 32-bit MIPS GUP-fast still pin src_folio through the invalidated PMD before pmdp_huge_get_and_clear() runs?

On MIPS, pmd_mkinvalid() clears _PAGE_PRESENT, _PAGE_VALID, and _PAGE_DIRTY while leaving _PAGE_HUGE, _PAGE_WRITE, and the PFN intact. Unlike 64-bit MIPS, 32-bit MIPS pmd_present() in arch/mips/include/asm/pgtable-32.h only checks against invalid_pte_table.

As a result, pmd_present() and the generic pmd_access_permitted() both return true for an invalidated huge PMD, allowing a concurrent pin_user_pages_fast() (such as O_DIRECT) to race with move_pages_huge_pmd():

CPU0 CPU1
move_pages_huge_pmd()
pmdp_invalidate(..., src_pmd)
smp_mb()
folio_maybe_dma_pinned(src_folio)

    -> false
                                       gup_fast_pmd_leaf()
                                         pmd_present(orig) -> true
                                         pmd_access_permitted() -> true
                                         try_grab_folio_fast() <-- pins folio
                                         pmd_val(orig) == *src_pmd -> ok

folio_move_anon_rmap()
pmdp_huge_get_and_clear(..., src_pmd)

UFFDIO_MOVE then unmaps src_folio from src_addr and remaps it at dst_addr with a new anon_vma and index while DMA holds a pin on it, risking silent memory corruption. Checking _PAGE_PRESENT for _PAGE_HUGE entries in 32-bit MIPS pmd_present() (matching arch/mips/include/asm/pgtable-64.h) would close this race.

mm/huge_memory.c int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm · line 3017

Quoted 5 lines
mm/huge_memory.c +1 -0
@@ -3004,6 +3014,7 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 		folio_move_anon_rmap(src_folio, dst_vma);
 		src_folio->index = linear_anon_page_index(dst_vma, dst_addr);
 
+		pmdp_huge_get_and_clear(mm, src_addr, src_pmd);

[Severity: Medium]
Does calling pmdp_huge_get_and_clear() after pmdp_invalidate() perform a redundant hash page table flush on PowerPC Book3S64 Hash MMU?

On PowerPC Book3S64 Hash MMU, pmdp_invalidate() runs hash__pmd_hugepage_update() to clear _PAGE_PRESENT and set _PAGE_INVALID, which calls hpte_do_hugepage_flush() while leaving H_PAGE_HASHPTE set in *src_pmd and the valid bits set in hpte_slot_array.

When the success path reaches pmdp_huge_get_and_clear(), pmd_present() is still true because it checks _PAGE_INVALID, so hash__pmd_hugepage_update() sees H_PAGE_HASHPTE still set and runs hpte_do_hugepage_flush() a second time before zeroing hpte_slot_array.

Every successful huge-PMD UFFDIO_MOVE therefore doubles the IRQ-off tlbie() broadcasts on bare metal or batched hypercalls on pSeries LPARs. Skipping hpte_do_hugepage_flush() in hash__pmd_hugepage_update() when _PAGE_INVALID is already set would avoid the extra flush.

[Severity: Medium]
Will this also double TSB and SMP TLB shootdowns on sparc64?

On sparc64, pmdp_invalidate() clears _PAGE_VALID while leaving _PAGE_PMD_HUGE set and calls __set_pmd_acct(). Because lazy_mmu_mode is not active in move_pages_huge_pmd(), tlb_batch_add_one() immediately issues two synchronous flush_tsb_user_page() and smp_flush_tlb_page() IPIs.

When pmdp_huge_get_and_clear() (or set_pmd_at() on the DMA-pinned restore path) then overwrites the invalidated PMD, __set_pmd_acct() in arch/sparc/mm/tlb.c checks !pmd_none(orig) and pmd_trans_huge(orig) without testing _PAGE_VALID, issuing two more redundant TSB and TLB IPIs.

Checking pmd_val(orig) & _PAGE_VALID before calling tlb_batch_add_one() in __set_pmd_acct() would avoid doubling the shootdowns per moved THP.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
reviewer Reviewed-by on v2 9/9
#25 lore raw

Re: [PATCH v2 9/9] userfaultfd: avoid transient none PMDs during UFFDIO_MOVE

In reply to Zi Yan

On Thu, Dec 03, 2026 at 11:17:57PM -0500, Zi Yan wrote:
[...]

Quoted 8 lines
mm/huge_memory.c +1 -1
@@ -2993,7 +2993,17 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 			goto unlock_ptls;
 		}
 
-		src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd);
+		/*

mm/huge_memory.c int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm · line 3006

Quoted 10 lines
mm/huge_memory.c +10 -0
+		 * Invalidate the PMD so that a concurrent zap does not skip it
+		 * in case a restore is needed afterwards.
+		 */
+		src_pmdval = pmdp_invalidate(src_vma, src_addr, src_pmd);
+		/*
+		 * Syncing against concurrent GUP-fast:
+		 * - invalidate PMD; barrier; read pincount
+		 * - inc pincount; barrier; read PMD
+		 */
+		smp_mb();

Wait ... we didn't even have the smp_mb() against GUP-fast here before ... good catch fixing that too!

Just thinking aloud, since we now have the same pmdp_invalidate() + smp_mb() dance here and elsewhere (and it's pretty easy to forget the barrier), wonder if it's worth wrapping that in a small helper like pmdp_invalidate_sync_gup() (not a blocker though) :D

mm/huge_memory.c int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm · line 3017

Quoted 8 lines
mm/huge_memory.c +1 -0
 		/* Folio got pinned from under us. Put it back and fail the move. */
 		if (folio_maybe_dma_pinned(src_folio)) {
 			set_pmd_at(mm, src_addr, src_pmd, src_pmdval);
@@ -3004,6 +3014,7 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 		folio_move_anon_rmap(src_folio, dst_vma);
 		src_folio->index = linear_anon_page_index(dst_vma, dst_addr);
 
+		pmdp_huge_get_and_clear(mm, src_addr, src_pmd);

LGTM!

#26 lore raw
In reply to Zi Yan
Sashiko has finished reviewing this 9-patch series:

Sashiko has finished reviewing this 9-patch series:

- Patches 1-3, 5, and 6: no issues found.
- Patch 4 ("LoongArch: mm: don't let GUP-fast follow invalidated..."): 1 potential issue (1 Low)
- Patch 7 ("mm/huge_memory: avoid transient none PMDs during laz..."): 4 potential issues (1 High, 2 Medium, 1 Low)
- Patch 8 ("mm/rmap: re-enable discarding lazyfree THPs at PMD l..."): 2 potential issues (2 High)
- Patch 9 ("userfaultfd: avoid transient none PMDs during UFFDIO..."): 3 potential issues (1 High, 2 Medium)

Detailed reviews have been sent as separate replies to patches 4 and 7-9.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]