Skip to contentSkip to conversation

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

PATCH In review Zi Yan 5 participants 17 messages Dec 4

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
author reviewer
#2 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
#3 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
#4 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
author reviewer
#5 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
#6 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
#7 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
#8 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
#9 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
#10 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
#11 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

author reviewer
#12 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
#13 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
#14 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.

author reviewer
#15 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
#16 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