Skip to contentSkip to conversation

mm: PMD-level swap entries for anonymous THPs

PATCH Superseded Usama Arif 6 participants 29 messages Jul 22 – Aug 7

Subsystems (23)

v5 of 9 Superseded Latest is v9 →

lore
Share & tools
lore

Usama Arif

author reviewer
#0 lore raw

v5 cover mm: PMD-level swap entries for anonymous THPs

This is the PMD swap entry core series. The preparatory PMD softleaf [1] cleanup series has been merged in akpm/mm-new. I got enough feedback from sashiko to send a new revision. Hopefully sashiko will be happier with this one.

When reclaim swaps out a PMD-mapped anonymous THP today, the PMD is split into HPAGE_PMD_NR PTE-level swap entries via TTU_SPLIT_HUGE_PMD before unmap. This series introduces a PMD-level swap entry so the huge mapping can survive the swap round-trip and do_huge_pmd_swap_page() can restore the PMD mapping directly on swap-in, without waiting for khugepaged to collapse the range later.

The PMD swap entry is a compact page-table encoding for HPAGE_PMD_NR consecutive swap slots. swap_map accounting remains per-slot and is unchanged. Importantly, a PMD swap entry does not promise that the swap cache always contains one PMD-sized folio. While the cache is empty or contains one PMD-sized folio, PMD-level handling can proceed. Once the cache has split/per-slot state, users either inspect the individual slots directly (mincore) or split the PMD swap entry and retry through the PTE path (fault, swapoff, MADV_WILLNEED, UFFDIO_MOVE). Likewise, if any slot is still backed by zswap's per-page store, PMD-order swap-in consumers split and let the PTE path load the range page by page; an all-on-disk range can still be read back as one PMD-sized folio.

The series is ordered so every consumer can handle PMD swap entries before the swap-out producer starts installing them. The swap-out patch is the last functional change.

Patch breakdown:

1. mm: add PMD swap entry detection support
Add pmd_is_swap_entry(), teach the softleaf layer that PMD swap entries are valid PMD softleaf entries, prevent non-PFN entries from reaching softleaf_to_folio(), and add per-arch pmd_swp_*exclusive helpers.

2. mm: add PMD swap entry splitting support
Teach __split_huge_pmd_locked() to split a PMD swap entry into HPAGE_PMD_NR PTE swap entries. This is the common fallback path whenever PMD-level handling is unsafe or unavailable. PMD swap entries preserve their software flags and do not enter the migration-entry freeze path.

3. mm: handle PMD swap entries in fork path
Copy a PMD swap entry in fork via one swap_dup_entries_direct(HPAGE_PMD_NR) operation, with the same swapoff/mmlist preparation rules used by PTE entries. Extend-table allocation retries cover the full PMD-sized slot range.

4. mm: zswap: add range lookup for large-folio swapin Teach zswap_load() to let all-on-disk large folio reads proceed to the backing swap device, and add zswap_is_present() so PMD swap-entry consumers can split only when a specific range has per-page zswap state.

5. mm: swap in PMD swap entries as whole THPs during swapoff Add swap_pmd_cache_lookup() and use it from swapoff. Empty cache and PMD-sized cache state can be handled at PMD order; split cache state, zswap-backed slots, allocation/read failures, and non-uptodate or hardware-poisoned folios force a split and fallback to unuse_pte_range(). Restoring a UFFD marker in an RWP VMA also restores PAGE_NONE.

6. mm: handle PMD swap entries in non-present PMD walkers Teach zap, mprotect, soft-dirty, uffd-wp, smaps, mincore, mempolicy, khugepaged, HMM, and madvise walkers about PMD swap entries. mincore reports PMD-sized cache state directly and checks per-page slots after the cache has split; smaps calculates SwapPss from each slot's own swap count.

7. mm: handle PMD swap entries in MADV_WILLNEED
Let MADV_WILLNEED prefetch a PMD swap entry at PMD order when safe, treat an already cached PMD-sized folio as complete, and split/retry through PTEs for split cache state, zswap-backed slots, or races with per-slot cache population. If per-page zswap state appears during the read, remove the failed PMD-sized cache folio after revalidating its association with the swap entry.

8. mm: handle PMD swap entries in UFFDIO_MOVE
Move PMD swap entries whole when the covered range is empty or backed by one PMD-sized folio. Split/per-slot cache state returns -EAGAIN after splitting so retry can use the PTE move path and update per-page rmap metadata. An RWP-registered destination gets the UFFD marker on the moved PMD swap entry.

9. mm: handle PMD swap entry faults on swap-in
Add do_huge_pmd_swap_page(). It maps a PMD-sized cached folio directly, or allocates/reads at PMD order when the cache is empty and the range has no zswap entries. Split cache state, zswap-backed slots, hardware poison, and PMD-order resource failures fall back to the PTE path. UFFD RWP state is restored with PAGE_NONE, and write faults retain their original write state through swap-slot release and any required COW handling.

10. mm: install PMD swap entries on swap-out
Stop forcing TTU_SPLIT_HUGE_PMD for PMD-mappable swapcache folios and install one PMD swap entry instead. Zswap still stores the THP as per-page compressed entries; PMD-order swap-in consumers preserve a PMD-sized cached folio or read an all-on-disk range as a whole THP, and split before reading per-page zswap state. Add thp_swpout_pmd to count each PMD mapping replaced by a PMD-level swap entry.

11. selftests/mm: add PMD swap entry tests
Add pmd_swap selftests covering swap-out/in, fork, fork+COW, repeated cycles, write fault, UFFD RWP restoration, munmap, mprotect, mremap, pagemap, mincore, MADV_FREE, MADV_WILLNEED, UFFDIO_MOVE, and swapoff. Register the 15-test suite with run_vmtests.sh and the default kselftest runner.

Notes on zswap:

Native PMD-order zswap load/store is intentionally left for a follow-up. Alexandre Ghiti is currently working this.
This series can still preserve PMD swap entries while zswap is enabled:
zswap stores the THP as order-0 entries, and PMD-order swap-in consumers split any range that has zswap entries before reading it. If zswap has written the whole range back to disk, or the swap cache still contains one PMD-sized folio, PMD-level handling can proceed.

v4 -> v5: https://lore.kernel.org/all/[email protected]/
- Commit message improvements for almost all patches (Yosry for zswap patch)
- Patch 1: make pmd_to_softleaf_folio() reject softleaf entries that do not encode a PFN, so a PMD swap offset is never interpreted as one. PMD swap entries remain valid softleaf entries for classification. (sashiko)
- Patch 2: use the existing pmd_swp_uffd() helper and force freeze=false for PMD swap entries, which have no struct page for the migration-entry freeze path. (sashiko)
- Patch 3: document that the caller's page-table or swap-cache reference pins every source slot while a partial PMD-sized duplication is rolled back. Keep the pre-existing PTE fork retry behavior outside this series. (sashiko)
- Patch 5: split to the PTE path rather than mapping a PMD-sized folio containing a hardware-poisoned subpage, and restore PAGE_NONE when swapoff restores a UFFD marker in an RWP VMA. (sashiko)
- Patch 6: account SwapPss for a PMD swap entry one slot at a time because the slots can have different swap reference counts.
- Patch 7: if PMD-order MADV_WILLNEED encounters newly populated per-page zswap state, revalidate and remove the failed clean PMD-sized cache folio before retrying through PTEs.
- Patch 8: mark a moved PMD swap entry for UFFD when the UFFDIO_MOVE destination VMA is RWP-registered. (sashiko)
- Patch 9: restore PAGE_NONE for UFFD RWP swap-in, preserve the original write-fault state through swap-slot release and COW handling, remove the unnecessary LRU drain, and prevent PTE batching from mapping a poisoned subpage. (sashiko)
- Patch 10: add and document thp_swpout_pmd, which counts PMD mappings replaced by PMD-level swap entries rather than swapped folios.
- Patch 11: register pmd_swap with the default mm selftest runner, preserve errno across UFFDIO_MOVE cleanup, check swapoff residency before the first memory access, add a parent-side write and verification to the fork+COW test, and add RWP regression coverage for swap-in, UFFDIO_MOVE, and swapoff. (sashiko)
- Keep do_huge_pmd_swap_page() in patch 9. Patches 6 and 7 only add consumers; patch 10 remains the first producer, so no PMD swap entry can reach those paths before the fault handler is present. (sashiko)
- Rebase onto latest akpm/mm-new from 22 July (5e0603ba185a)

v3 -> v4: https://lore.kernel.org/all/[email protected]/
- Patch 1: guard the new arch-specific pmd_swp_mkexclusive / pmd_swp_exclusive / pmd_swp_clear_exclusive helpers on arm64, loongarch, powerpc, riscv, s390, and x86 with CONFIG_ARCH_HAS_PMD_SOFTLEAVES, matching the pattern already
used for pmd_swp_soft_dirty. Also fixes the redefinition-vs- generic-fallback build errors kernel test robot reported on i386-allnoconfig-bpf and riscv-allnoconfig-bpf, and rewraps
the patch 1 commit message paragraphs to ~75 columns.
(sashiko, kernel test robot, Usama Arif)
- Patch 2: switch the trailing folio_remove_rmap_pmd() gate in __split_huge_pmd_locked() from *pmd to old_pmd, old_pmd retains
the original present-or-non-present classification for every
branch above. (sashiko)
- Patch 3: teach swap_retry_table_alloc() (and the underlying swap_extend_table_alloc()) to accept an nr parameter and scan
every slot in [ci_off, ci_off + nr) before committing an extend-table allocation. (sashiko)
- Patch 4: rename zswap_range_has_entry() to zswap_is_present() so
the same helper serves both single-slot (nr=1) and range queries, and switch the implementation from XA_STATE + xas_find() to xa_find(), which handles RCU locking and internal-retry markers itself. Rename the callers in patches 5, 7, 9. (Yosry)
- Patch 9: refuse to map a swap-cache folio in do_huge_pmd_swap_page() when folio_contain_hwpoisoned_page() reports a poisoned subpage; split the PMD swap entry so do_swap_page() can return VM_FAULT_HWPOISON per subpage instead of the PMD handler mapping
the corrupted memory as one THP. Mirrors the PageHWPoison check
the PTE swap-in path already performs. (sashiko)
- Patch 9: note explicitly in the commit message that PMD-order swap-in deliberately skips the order-0 readahead paths, order-0 readahead would populate per-page swap-cache state and force the
PMD swap entry to split before the fault could finish. (Kairui)
- Patch 10: move mm_prepare_for_swap_entries() into set_pmd_swap_entry() between folio_dup_swap() and set_pmd_at()
so this mm is on init_mm.mmlist before any swap PMD referencing slots with a non-zero swap_map becomes visible. Matches the PTE swap-out ordering. (sashiko)
- rebase onto latest akpm/mm-new (61cccb8363fcc282d4ae0555b8739dd227f5ad0b)

v2 -> v3: https://lore.kernel.org/all/[email protected]/
- Clarified the PMD swap entry rule: it is a compact encoding for HPAGE_PMD_NR swap slots, not a guarantee that swap cache always has one PMD-sized folio. (Lance Yang)
- Swapoff, fault, MADV_WILLNEED, and UFFDIO_MOVE now classify the whole PMD swap-cache range and split/retry through the PTE path for split/per-slot cache state. (Lance Yang)
- mincore handles PMD swap entries without assuming one lookup covers a split swap-cache range. (Lance Yang)
- UFFDIO_MOVE rechecks all HPAGE_PMD_NR slots before moving an empty PMD swap-cache range, avoiding stale rmap metadata for per-slot cached folios.
- Added a standalone zswap prerequisite patch from Alexandre that distinguishes all-on-disk large-folio ranges from ranges with per-page zswap entries.
- Replaced the global zswap-ever-enabled policy with per-range zswap
checks: PMD swap entries can still be installed while zswap is enabled, and PMD-order swap-in consumers split when the range has per-page zswap state.
- Added a mincore selftest and updated MADV_WILLNEED coverage so the test checks that the PMD swap entry remains in place until first touch. Total pmd_swap coverage is now 14 tests.

v1 -> v2: https://lore.kernel.org/all/[email protected]/
- Patch 1: convert two additional softleaf_to_pmd() callers that landed in mm-unstable since v1 (mm/debug_vm_pgtable.c, mm/migrate_device.c) (Dev)
- Patch 2: rename helper ensure_on_mmlist() to mm_prepare_for_swap_entries() to better describe its purpose
(David)
- Patch 3: drop VM_WARN_ON_ONCE(!pmd_is_migration_entry) as
Dev posted it as a separate patch.
- Patch 5 (new): move softleaf_to_folio() inside the device-private branch in migrate_vma_collect_pmd(); same class of fix as patch 4 but for the migrate-device PMD walker.
- Patch 6 (new): rename CONFIG_ARCH_ENABLE_THP_MIGRATION to CONFIG_ARCH_HAS_PMD_SOFTLEAVES so the gate that now drives swap-entry support too is named for what it actually controls
(PMD softleaf entries), not just migration. (Dev)
- Patch 7: add the missing pmd_swp_exclusive / mkexclusive / clear_exclusive helpers for powerpc.
- Patches 10 and 14: use upstream swapin_sync() (bundles swap_cache_alloc_folio + swap_read_folio + the -EEXIST race
retry) instead of the bespoke swapin_alloc_pmd_folio() helper
from v1; do_swap_page and shmem_swapin_folio use the same
helper (Kairui)
- Patch 10: construct a stack vm_fault for the swapoff swap-in so
the allocator can resolve a mempolicy, mirroring how the PTE
swapoff path (unuse_pte_range) already does it.
- Patch 11: extend coverage to check_pmd_state() in khugepaged so a swapped-out PMD-mapped THP is treated as SCAN_PMD_MAPPED (matches the existing migration-entry handling). Route the pmd_trans_huge_lock() branch of mincore_pte_range() through mincore_swap() so a swapped-out PMD-mapped THP isn't reported as resident.
- Patch 12 (new): handle PMD swap entries in MADV_WILLNEED via swapin_sync(BIT(HPAGE_PMD_ORDER)); a naive order-0 read-ahead
would force the subsequent fault to split.
- Patch 13: refuse UFFDIO_MOVE with -EBUSY if the swap-cache folio
was split between swap-out and the move, matching
move_pages_pte()'s rejection of large folios; otherwise only one
of the 512 anon-rmaps would be re-anchored to dst_vma.
- Patch 16: alloc_fill_swap_thp() now uses the existing mmap_pmd_aligned() helper so tests don't flake/skip based on VA placement; new MADV_WILLNEED test that watches the PMD-order
mTHP swpin counter; swapoff test restructured to use the kselftest_harness ASSERT cleanup blocks (no double swapoff, no verify-after-munmap).
- Collected Acks and Reviews.

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

Alexandre Ghiti (1):
mm: zswap: add range lookup for large-folio swapin

Usama Arif (10):
mm: add PMD swap entry detection support
mm: add PMD swap entry splitting support
mm: handle PMD swap entries in fork path
mm: swap in PMD swap entries as whole THPs during swapoff
mm: handle PMD swap entries in non-present PMD walkers
mm: handle PMD swap entries in MADV_WILLNEED
mm: handle PMD swap entries in UFFDIO_MOVE
mm: handle PMD swap entry faults on swap-in
mm: install PMD swap entries on swap-out selftests/mm: add PMD swap entry tests

 Documentation/admin-guide/mm/transhuge.rst   |   5 +
 arch/arm64/include/asm/pgtable.h             |   6 +
 arch/loongarch/include/asm/pgtable.h         |  19 +
 arch/powerpc/include/asm/book3s/64/pgtable.h |  17 +
 arch/riscv/include/asm/pgtable.h             |  15 +
 arch/s390/include/asm/pgtable.h              |  17 +
 arch/x86/include/asm/pgtable.h               |  17 +
 fs/proc/task_mmu.c                           |  46 +-
 include/linux/huge_mm.h                      |  16 +
 include/linux/leafops.h                      |  26 +-
 include/linux/pgtable.h                      |  17 +
 include/linux/swap.h                         |   4 +-
 include/linux/vm_event_item.h                |   1 +
 include/linux/zswap.h                        |   6 +
 mm/hmm.c                                     |   3 +-
 mm/huge_memory.c                             | 581 +++++++++++-
 mm/internal.h                                |  34 +
 mm/khugepaged.c                              |   6 +
 mm/madvise.c                                 | 101 ++-
 mm/memory.c                                  |  45 +-
 mm/mincore.c                                 |  45 +-
 mm/rmap.c                                    |  19 +
 mm/swap.h                                    |  22 +-
 mm/swap_state.c                              |  44 +
 mm/swapfile.c                                | 202 ++++-
 mm/vmscan.c                                  |   9 +-
 mm/vmstat.c                                  |   1 +
 mm/zswap.c                                   |  42 +-
 tools/testing/selftests/mm/Makefile          |   2 +
 tools/testing/selftests/mm/ksft_pmd_swap.sh  |   4 +
 tools/testing/selftests/mm/pmd_swap.c        | 874 +++++++++++++++++++
 tools/testing/selftests/mm/run_vmtests.sh    |   4 +
 32 files changed, 2139 insertions(+), 111 deletions(-)
 create mode 100755 tools/testing/selftests/mm/ksft_pmd_swap.sh
 create mode 100644 tools/testing/selftests/mm/pmd_swap.c
Signature · 1 line
2.53.0-Meta
author reviewer
#1 lore raw

PATCH v5 1/11 mm: add PMD swap entry detection support

Currently when a PMD-mapped THP is swapped out, the PMD is always split into HPAGE_PMD_NR PTE-level swap entries. To preserve huge page information across swap cycles, later patches will install a single PMD-level swap entry instead. Add the infrastructure to detect those entries.

Teach the softleaf layer to recognise PMD swap entries:
pmd_is_swap_entry() detects them and softleaf_is_valid_pmd_entry() accepts them as a valid non-present type. Because swap entries do not encode a PFN, make pmd_to_softleaf_folio() return NULL for them instead of passing the swap offset to softleaf_to_folio(). Clear the exclusive overlay bit in softleaf_from_pmd() before decoding, matching how soft_dirty and uffd bits are already stripped.

Add pmd_swp_mkexclusive(), pmd_swp_exclusive(), and pmd_swp_clear_exclusive() helpers to each architecture that supports PMD softleaf entries (x86, arm64, s390, riscv, loongarch, powerpc), mirroring the existing PTE swap exclusive helpers in each arch's pgtable.h. Provide generic no-op PMD swap exclusive fallbacks for architectures without PMD softleaf support, matching the generic PMD swap soft-dirty fallbacks.

---
 arch/arm64/include/asm/pgtable.h             |  6 +++++
 arch/loongarch/include/asm/pgtable.h         | 19 ++++++++++++++
 arch/powerpc/include/asm/book3s/64/pgtable.h | 17 +++++++++++++
 arch/riscv/include/asm/pgtable.h             | 15 +++++++++++
 arch/s390/include/asm/pgtable.h              | 17 +++++++++++++
 arch/x86/include/asm/pgtable.h               | 17 +++++++++++++
 include/linux/leafops.h                      | 26 ++++++++++++++++----
 include/linux/pgtable.h                      | 17 +++++++++++++
 8 files changed, 129 insertions(+), 5 deletions(-)
arch/arm64/include/asm/pgtable.h +6 -0
index a2681d755358..860f95573d1f 100644
@@ -598,6 +598,12 @@ static inline int pmd_protnone(pmd_t pmd)
 #define pmd_swp_clear_uffd(pmd) \
 				pte_pmd(pte_swp_clear_uffd(pmd_pte(pmd)))
 #endif /* CONFIG_HAVE_ARCH_USERFAULTFD_WP */
+#ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+#define pmd_swp_exclusive(pmd)	pte_swp_exclusive(pmd_pte(pmd))
+#define pmd_swp_mkexclusive(pmd)	pte_pmd(pte_swp_mkexclusive(pmd_pte(pmd)))
+#define pmd_swp_clear_exclusive(pmd) \
+				pte_pmd(pte_swp_clear_exclusive(pmd_pte(pmd)))
+#endif
 
 #define pmd_write(pmd)		pte_write(pmd_pte(pmd))
 
arch/loongarch/include/asm/pgtable.h +19 -0
index 1952e34bc8ee..aa8e1223d397 100644
@@ -357,6 +357,25 @@ static inline pte_t pte_swp_clear_exclusive(pte_t pte)
 	return pte;
 }
 
+#ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+static inline pmd_t pmd_swp_mkexclusive(pmd_t pmd)
+{
+	pmd_val(pmd) |= _PAGE_SWP_EXCLUSIVE;
+	return pmd;
+}
+
+static inline bool pmd_swp_exclusive(pmd_t pmd)
+{
+	return pmd_val(pmd) & _PAGE_SWP_EXCLUSIVE;
+}
+
+static inline pmd_t pmd_swp_clear_exclusive(pmd_t pmd)
+{
+	pmd_val(pmd) &= ~_PAGE_SWP_EXCLUSIVE;
+	return pmd;
+}
+#endif
+
 #define pte_none(pte)		(!(pte_val(pte) & ~_PAGE_GLOBAL))
 #define pte_present(pte)	(pte_val(pte) & (_PAGE_PRESENT | _PAGE_PROTNONE))
 #define pte_no_exec(pte)	(pte_val(pte) & _PAGE_NO_EXEC)
arch/powerpc/include/asm/book3s/64/pgtable.h +17 -0
index f4db7d7fbd5c..6a899d0793b3 100644
@@ -699,6 +699,23 @@ static inline pte_t pte_swp_clear_exclusive(pte_t pte)
 	return __pte_raw(pte_raw(pte) & cpu_to_be64(~_PAGE_SWP_EXCLUSIVE));
 }
 
+#ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+static inline pmd_t pmd_swp_mkexclusive(pmd_t pmd)
+{
+	return __pmd_raw(pmd_raw(pmd) | cpu_to_be64(_PAGE_SWP_EXCLUSIVE));
+}
+
+static inline bool pmd_swp_exclusive(pmd_t pmd)
+{
+	return !!(pmd_raw(pmd) & cpu_to_be64(_PAGE_SWP_EXCLUSIVE));
+}
+
+static inline pmd_t pmd_swp_clear_exclusive(pmd_t pmd)
+{
+	return __pmd_raw(pmd_raw(pmd) & cpu_to_be64(~_PAGE_SWP_EXCLUSIVE));
+}
+#endif
+
 static inline bool check_pte_access(unsigned long access, unsigned long ptev)
 {
 	/*
arch/riscv/include/asm/pgtable.h +15 -0
index 7f21742b2b6a..5f53b158a95c 100644
@@ -1206,6 +1206,21 @@ static inline pte_t pte_swp_clear_exclusive(pte_t pte)
 }
 
 #ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+static inline bool pmd_swp_exclusive(pmd_t pmd)
+{
+	return pte_swp_exclusive(pmd_pte(pmd));
+}
+
+static inline pmd_t pmd_swp_mkexclusive(pmd_t pmd)
+{
+	return pte_pmd(pte_swp_mkexclusive(pmd_pte(pmd)));
+}
+
+static inline pmd_t pmd_swp_clear_exclusive(pmd_t pmd)
+{
+	return pte_pmd(pte_swp_clear_exclusive(pmd_pte(pmd)));
+}
+
 #define __pmd_to_swp_entry(pmd) ((swp_entry_t) { pmd_val(pmd) })
 #define __swp_entry_to_pmd(swp) __pmd((swp).val)
 #endif /* CONFIG_ARCH_HAS_PMD_SOFTLEAVES */
arch/s390/include/asm/pgtable.h +17 -0
index e882663a58e7..490e4a3464b1 100644
@@ -870,6 +870,23 @@ static inline pte_t pte_swp_clear_exclusive(pte_t pte)
 	return clear_pte_bit(pte, __pgprot(_PAGE_SWP_EXCLUSIVE));
 }
 
+#ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+static inline pmd_t pmd_swp_mkexclusive(pmd_t pmd)
+{
+	return set_pmd_bit(pmd, __pgprot(_PAGE_SWP_EXCLUSIVE));
+}
+
+static inline bool pmd_swp_exclusive(pmd_t pmd)
+{
+	return pmd_val(pmd) & _PAGE_SWP_EXCLUSIVE;
+}
+
+static inline pmd_t pmd_swp_clear_exclusive(pmd_t pmd)
+{
+	return clear_pmd_bit(pmd, __pgprot(_PAGE_SWP_EXCLUSIVE));
+}
+#endif
+
 static inline int pte_soft_dirty(pte_t pte)
 {
 	return pte_val(pte) & _PAGE_SOFT_DIRTY;
arch/x86/include/asm/pgtable.h +17 -0
index 8e0018fadd14..b5da5447e83d 100644
@@ -1525,6 +1525,23 @@ static inline pte_t pte_swp_clear_exclusive(pte_t pte)
 	return pte_clear_flags(pte, _PAGE_SWP_EXCLUSIVE);
 }
 
+#ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+static inline pmd_t pmd_swp_mkexclusive(pmd_t pmd)
+{
+	return pmd_set_flags(pmd, _PAGE_SWP_EXCLUSIVE);
+}
+
+static inline int pmd_swp_exclusive(pmd_t pmd)
+{
+	return pmd_flags(pmd) & _PAGE_SWP_EXCLUSIVE;
+}
+
+static inline pmd_t pmd_swp_clear_exclusive(pmd_t pmd)
+{
+	return pmd_clear_flags(pmd, _PAGE_SWP_EXCLUSIVE);
+}
+#endif
+
 #ifdef CONFIG_HAVE_ARCH_SOFT_DIRTY
 static inline pte_t pte_swp_mksoft_dirty(pte_t pte)
 {
include/linux/leafops.h +21 -5
index 4c1476ae3234..8397193ba399 100644
@@ -102,6 +102,8 @@ static inline softleaf_t softleaf_from_pmd(pmd_t pmd)
 		pmd = pmd_swp_clear_soft_dirty(pmd);
 	if (pmd_swp_uffd(pmd))
 		pmd = pmd_swp_clear_uffd(pmd);
+	if (pmd_swp_exclusive(pmd))
+		pmd = pmd_swp_clear_exclusive(pmd);
 	arch_entry = __pmd_to_swp_entry(pmd);
 
 	/* Temporary until swp_entry_t eliminated. */
@@ -634,18 +636,30 @@ static inline bool pmd_is_migration_entry(pmd_t pmd)
  */
 static inline bool softleaf_is_valid_pmd_entry(softleaf_t entry)
 {
-	/* Only device private, migration entries valid for PMD. */
+	/* Device private, migration, and swap entries valid for PMD. */
 	return softleaf_is_device_private(entry) ||
-		softleaf_is_migration(entry);
+		softleaf_is_migration(entry) ||
+		softleaf_is_swap(entry);
+}
+
+/**
+ * pmd_is_swap_entry() - Does this PMD entry encode an actual swap entry?
+ * @pmd: PMD entry.
+ *
+ * Returns: true if the PMD encodes a swap entry, otherwise false.
+ */
+static inline bool pmd_is_swap_entry(pmd_t pmd)
+{
+	return softleaf_is_swap(softleaf_from_pmd(pmd));
 }
 
 /**
  * pmd_is_valid_softleaf() - Is this PMD entry a valid softleaf entry?
  * @pmd: PMD entry.
  *
- * PMD leaf entries are valid only if they are device private or migration
- * entries. This function asserts that a PMD leaf entry is valid in this
- * respect.
+ * PMD leaf entries are valid only if they are device private, migration,
+ * or swap entries. This function asserts that a PMD leaf entry is valid
+ * in this respect.
  *
  * Returns: true if the PMD entry is a valid leaf entry, otherwise false.
  */
@@ -673,6 +687,8 @@ static inline struct folio *pmd_to_softleaf_folio(pmd_t pmd)
 		VM_WARN_ON_ONCE(true);
 		return NULL;
 	}
+	if (!softleaf_has_pfn(entry))
+		return NULL;
 	return softleaf_to_folio(entry);
 }
 
include/linux/pgtable.h +17 -0
index 8c093c119e5a..e10a7e91e426 100644
@@ -1917,6 +1917,23 @@ static inline pmd_t pmd_swp_clear_soft_dirty(pmd_t pmd)
 }
 #endif
 
+#ifndef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+static inline pmd_t pmd_swp_mkexclusive(pmd_t pmd)
+{
+	return pmd;
+}
+
+static inline bool pmd_swp_exclusive(pmd_t pmd)
+{
+	return false;
+}
+
+static inline pmd_t pmd_swp_clear_exclusive(pmd_t pmd)
+{
+	return pmd;
+}
+#endif
+
 #ifndef __HAVE_PFNMAP_TRACKING
 /*
  * Interfaces that can be used by architecture code to keep track of
Signature · 1 line
2.53.0-Meta
reviewer
#2 lore raw

Re: [PATCH v5 01/11] mm: add PMD swap entry detection support

[------]

include/linux/leafops.h static inline struct folio *pmd_to_softleaf_folio(pmd_t pmd)

Quoted 50 lines
include/linux/leafops.h +19 -5
index 4c1476ae3234..8397193ba399 100644
@@ -102,6 +102,8 @@ static inline softleaf_t softleaf_from_pmd(pmd_t pmd)
 		pmd = pmd_swp_clear_soft_dirty(pmd);
 	if (pmd_swp_uffd(pmd))
 		pmd = pmd_swp_clear_uffd(pmd);
+	if (pmd_swp_exclusive(pmd))
+		pmd = pmd_swp_clear_exclusive(pmd);
 	arch_entry = __pmd_to_swp_entry(pmd);
 
 	/* Temporary until swp_entry_t eliminated. */
@@ -634,18 +636,30 @@ static inline bool pmd_is_migration_entry(pmd_t pmd)
  */
 static inline bool softleaf_is_valid_pmd_entry(softleaf_t entry)
 {
-	/* Only device private, migration entries valid for PMD. */
+	/* Device private, migration, and swap entries valid for PMD. */
 	return softleaf_is_device_private(entry) ||
-		softleaf_is_migration(entry);
+		softleaf_is_migration(entry) ||
+		softleaf_is_swap(entry);
+}
+
+/**
+ * pmd_is_swap_entry() - Does this PMD entry encode an actual swap entry?
+ * @pmd: PMD entry.
+ *
+ * Returns: true if the PMD encodes a swap entry, otherwise false.
+ */
+static inline bool pmd_is_swap_entry(pmd_t pmd)
+{
+	return softleaf_is_swap(softleaf_from_pmd(pmd));
 }
 
 /**
  * pmd_is_valid_softleaf() - Is this PMD entry a valid softleaf entry?
  * @pmd: PMD entry.
  *
- * PMD leaf entries are valid only if they are device private or migration
- * entries. This function asserts that a PMD leaf entry is valid in this
- * respect.
+ * PMD leaf entries are valid only if they are device private, migration,
+ * or swap entries. This function asserts that a PMD leaf entry is valid
+ * in this respect.
  *
  * Returns: true if the PMD entry is a valid leaf entry, otherwise false.
  */
@@ -673,6 +687,8 @@ static inline struct folio *pmd_to_softleaf_folio(pmd_t pmd)

Nit: This function really should have been named "softleaf_pmd_to_folio", or "pmd_softleaf_to_folio", perhaps throw in a patch to rename?

include/linux/leafops.h static inline struct folio *pmd_to_softleaf_folio(pmd_t pmd) · line 691

Quoted 5 lines
include/linux/leafops.h +2 -0
 		VM_WARN_ON_ONCE(true);
 		return NULL;
 	}
+	if (!softleaf_has_pfn(entry))
+		return NULL;

I am guessing that after the later patches add swp support, we should never reach pmd_to_softleaf_folio() with a swap entry, in which case, we could add a WARN_ON_ONCE() here. (didn't check if you have done that later, just writing this here)

Quoted 31 lines
include/linux/leafops.h +0 -0
 	return softleaf_to_folio(entry);
 }
 
include/linux/pgtable.h +17 -0
index 8c093c119e5a..e10a7e91e426 100644
@@ -1917,6 +1917,23 @@ static inline pmd_t pmd_swp_clear_soft_dirty(pmd_t pmd)
 }
 #endif
 
+#ifndef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+static inline pmd_t pmd_swp_mkexclusive(pmd_t pmd)
+{
+	return pmd;
+}
+
+static inline bool pmd_swp_exclusive(pmd_t pmd)
+{
+	return false;
+}
+
+static inline pmd_t pmd_swp_clear_exclusive(pmd_t pmd)
+{
+	return pmd;
+}
+#endif
+
 #ifndef __HAVE_PFNMAP_TRACKING
 /*
  * Interfaces that can be used by architecture code to keep track of
author reviewer
#3 lore raw

Re: [PATCH v5 01/11] mm: add PMD swap entry detection support

Quoted 47 lines · Dev Jain

[------]

Quoted 45 lines
include/linux/leafops.h +18 -5
index 4c1476ae3234..8397193ba399 100644
@@ -102,6 +102,8 @@ static inline softleaf_t softleaf_from_pmd(pmd_t pmd)
 		pmd = pmd_swp_clear_soft_dirty(pmd);
 	if (pmd_swp_uffd(pmd))
 		pmd = pmd_swp_clear_uffd(pmd);
+	if (pmd_swp_exclusive(pmd))
+		pmd = pmd_swp_clear_exclusive(pmd);
 	arch_entry = __pmd_to_swp_entry(pmd);
 
 	/* Temporary until swp_entry_t eliminated. */
@@ -634,18 +636,30 @@ static inline bool pmd_is_migration_entry(pmd_t pmd)
  */
 static inline bool softleaf_is_valid_pmd_entry(softleaf_t entry)
 {
-	/* Only device private, migration entries valid for PMD. */
+	/* Device private, migration, and swap entries valid for PMD. */
 	return softleaf_is_device_private(entry) ||
-		softleaf_is_migration(entry);
+		softleaf_is_migration(entry) ||
+		softleaf_is_swap(entry);
+}
+
+/**
+ * pmd_is_swap_entry() - Does this PMD entry encode an actual swap entry?
+ * @pmd: PMD entry.
+ *
+ * Returns: true if the PMD encodes a swap entry, otherwise false.
+ */
+static inline bool pmd_is_swap_entry(pmd_t pmd)
+{
+	return softleaf_is_swap(softleaf_from_pmd(pmd));
 }
 
 /**
  * pmd_is_valid_softleaf() - Is this PMD entry a valid softleaf entry?
  * @pmd: PMD entry.
  *
- * PMD leaf entries are valid only if they are device private or migration
- * entries. This function asserts that a PMD leaf entry is valid in this
- * respect.
+ * PMD leaf entries are valid only if they are device private, migration,
+ * or swap entries. This function asserts that a PMD leaf entry is valid
Quoted 9 lines

include/linux/leafops.h static inline struct folio *pmd_to_softleaf_folio(pmd_t pmd)

Quoted 5 lines
include/linux/leafops.h +1 -0
+ * in this respect.
  *
  * Returns: true if the PMD entry is a valid leaf entry, otherwise false.
  */
@@ -673,6 +687,8 @@ static inline struct folio *pmd_to_softleaf_folio(pmd_t pmd)

Nit: This function really should have been named "softleaf_pmd_to_folio", or "pmd_softleaf_to_folio", perhaps throw in a patch to rename?

Sounds good, will add a patch to rename. Lorenzo any preferences here for the name?>

Quoted 11 lines

include/linux/leafops.h static inline struct folio *pmd_to_softleaf_folio(pmd_t pmd) · line 691

Quoted 5 lines
include/linux/leafops.h +2 -0
 		VM_WARN_ON_ONCE(true);
 		return NULL;
 	}
+	if (!softleaf_has_pfn(entry))
+		return NULL;

I am guessing that after the later patches add swp support, we should never reach pmd_to_softleaf_folio() with a swap entry, in which case, we could add a WARN_ON_ONCE() here. (didn't check if you have done that later, just writing this here)

Will add a warn. This was one of things sashiko pointed out to add.

Quoted 32 lines
Quoted 31 lines
include/linux/leafops.h +0 -0
 	return softleaf_to_folio(entry);
 }
 
include/linux/pgtable.h +17 -0
index 8c093c119e5a..e10a7e91e426 100644
@@ -1917,6 +1917,23 @@ static inline pmd_t pmd_swp_clear_soft_dirty(pmd_t pmd)
 }
 #endif
 
+#ifndef CONFIG_ARCH_HAS_PMD_SOFTLEAVES
+static inline pmd_t pmd_swp_mkexclusive(pmd_t pmd)
+{
+	return pmd;
+}
+
+static inline bool pmd_swp_exclusive(pmd_t pmd)
+{
+	return false;
+}
+
+static inline pmd_t pmd_swp_clear_exclusive(pmd_t pmd)
+{
+	return pmd;
+}
+#endif
+
 #ifndef __HAVE_PFNMAP_TRACKING
 /*
  * Interfaces that can be used by architecture code to keep track of
author reviewer
#4 lore raw

PATCH v5 2/11 mm: add PMD swap entry splitting support

In reply to Usama Arif

Add a swap branch in __split_huge_pmd_locked() that splits a PMD swap entry into 512 PTE swap entries. Unlike migration splits, no folio reference is needed because swap entries point to swap slots, not pages. Each PTE inherits the correct sub-slot offset and preserves soft_dirty, uffd_wp, and exclusive flags.

The folio_remove_rmap_pmd() gate at the end must inspect old_pmd rather than *pmd: for a present THP split, *pmd has already been cleared by pmdp_invalidate(), and that invalidated bit pattern can decode as a plausible swap entry.

This branch is reached from the explicit __split_huge_pmd() callers that hit a non-present PMD: partial-range mprotect / munmap, the wp_huge_pmd() PMD-COW fallback, and the swap-in / swapoff fallbacks added in later patches when the cached folio is no longer PMD-sized. page_vma_mapped_walk() does not iterate PMD swap entries, so try_to_unmap_one() and try_to_migrate_one() do not reach this branch and freeze=true cannot occur in this branch today. page and folio are therefore left uninitialized in the swap branch; a VM_WARN_ON_ONCE(freeze) catches any future caller that breaks this invariant before the freeze path dereferences page_to_pfn(page + i) or put_page(page).

---
 mm/huge_memory.c | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)
mm/huge_memory.c +28 -1
index 04e8a6b55343..9819c0ae228a 100644
@@ -3210,6 +3210,14 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 			folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR,
 						 vma, haddr, rmap_flags);
 		}
+	} else if (pmd_is_swap_entry(*pmd)) {
+		VM_WARN_ON_ONCE(freeze);
+		/* Swap entries have no page for the migration freeze path. */
+		freeze = false;
+		old_pmd = *pmd;
+		soft_dirty = pmd_swp_soft_dirty(old_pmd);
+		uffd_wp = pmd_swp_uffd(old_pmd);
+		anon_exclusive = pmd_swp_exclusive(old_pmd);
 	} else {
 		/*
 		 * Up to this point the pmd is present and huge and userland has
@@ -3346,6 +3354,25 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
 			set_pte_at(mm, addr, pte + i, entry);
 		}
+	} else if (pmd_is_swap_entry(old_pmd)) {
+		softleaf_t sl_entry = softleaf_from_pmd(old_pmd);
+		pte_t swp_pte;
+		swp_entry_t sub_entry;
+
+		for (i = 0, addr = haddr; i < HPAGE_PMD_NR;
+		     i++, addr += PAGE_SIZE) {
+			sub_entry = swp_entry(swp_type(sl_entry),
+					      swp_offset(sl_entry) + i);
+			swp_pte = swp_entry_to_pte(sub_entry);
+			if (soft_dirty)
+				swp_pte = pte_swp_mksoft_dirty(swp_pte);
+			if (uffd_wp)
+				swp_pte = pte_swp_mkuffd(swp_pte);
+			if (anon_exclusive)
+				swp_pte = pte_swp_mkexclusive(swp_pte);
+			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
+			set_pte_at(mm, addr, pte + i, swp_pte);
+		}
 	} else {
 		pte_t entry;
 
@@ -3373,7 +3400,7 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 	}
 	pte_unmap(pte);
 
-	if (!pmd_is_migration_entry(*pmd))
+	if (!pmd_is_migration_entry(old_pmd) && !pmd_is_swap_entry(old_pmd))
 		folio_remove_rmap_pmd(folio, page, vma);
 	if (freeze)
 		put_page(page);
Signature · 1 line
2.53.0-Meta
reviewer
#5 lore raw

Re: [PATCH v5 02/11] mm: add PMD swap entry splitting support

Quoted 3 lines · Usama Arif

Add a swap branch in __split_huge_pmd_locked() that splits a PMD swap entry into 512 PTE swap entries. Unlike migration splits, no folio reference is needed because swap entries point to swap slots, not

Confusing wording. swap entries need reference of swap slots instead of folios. I would drop the mention of migration here.

Quoted 57 lines

pages. Each PTE inherits the correct sub-slot offset and preserves soft_dirty, uffd_wp, and exclusive flags.

The folio_remove_rmap_pmd() gate at the end must inspect old_pmd rather than *pmd: for a present THP split, *pmd has already been cleared by pmdp_invalidate(), and that invalidated bit pattern can decode as a plausible swap entry.

This branch is reached from the explicit __split_huge_pmd() callers that hit a non-present PMD: partial-range mprotect / munmap, the wp_huge_pmd() PMD-COW fallback, and the swap-in / swapoff fallbacks added in later patches when the cached folio is no longer PMD-sized. page_vma_mapped_walk() does not iterate PMD swap entries, so try_to_unmap_one() and try_to_migrate_one() do not reach this branch and freeze=true cannot occur in this branch today. page and folio are therefore left uninitialized in the swap branch; a VM_WARN_ON_ONCE(freeze) catches any future caller that breaks this invariant before the freeze path dereferences page_to_pfn(page + i) or put_page(page).

---
 mm/huge_memory.c | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)
mm/huge_memory.c +17 -0
index 04e8a6b55343..9819c0ae228a 100644
@@ -3210,6 +3210,14 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 			folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR,
 						 vma, haddr, rmap_flags);
 		}
+	} else if (pmd_is_swap_entry(*pmd)) {
+		VM_WARN_ON_ONCE(freeze);
+		/* Swap entries have no page for the migration freeze path. */
+		freeze = false;
+		old_pmd = *pmd;
+		soft_dirty = pmd_swp_soft_dirty(old_pmd);
+		uffd_wp = pmd_swp_uffd(old_pmd);
+		anon_exclusive = pmd_swp_exclusive(old_pmd);
 	} else {
 		/*
 		 * Up to this point the pmd is present and huge and userland has
@@ -3346,6 +3354,25 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
 			set_pte_at(mm, addr, pte + i, entry);
 		}
+	} else if (pmd_is_swap_entry(old_pmd)) {
+		softleaf_t sl_entry = softleaf_from_pmd(old_pmd);
+		pte_t swp_pte;
+		swp_entry_t sub_entry;
+
+		for (i = 0, addr = haddr; i < HPAGE_PMD_NR;
+		     i++, addr += PAGE_SIZE) {
+			sub_entry = swp_entry(swp_type(sl_entry),
+					      swp_offset(sl_entry) + i);

mm/huge_memory.c static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, · line 3375

Quoted 10 lines
mm/huge_memory.c +10 -0
+			swp_pte = swp_entry_to_pte(sub_entry);
+			if (soft_dirty)
+				swp_pte = pte_swp_mksoft_dirty(swp_pte);
+			if (uffd_wp)
+				swp_pte = pte_swp_mkuffd(swp_pte);
+			if (anon_exclusive)
+				swp_pte = pte_swp_mkexclusive(swp_pte);
+			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
+			set_pte_at(mm, addr, pte + i, swp_pte);
+		}

All these for loops could later benefit from the set_softleaf_ptes() helper:
https://lore.kernel.org/all/[email protected]/

Quoted 12 lines
mm/huge_memory.c +1 -1
 	} else {
 		pte_t entry;
 
@@ -3373,7 +3400,7 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 	}
 	pte_unmap(pte);
 
-	if (!pmd_is_migration_entry(*pmd))
+	if (!pmd_is_migration_entry(old_pmd) && !pmd_is_swap_entry(old_pmd))
 		folio_remove_rmap_pmd(folio, page, vma);
 	if (freeze)
 		put_page(page);
author reviewer
#6 lore raw

Re: [PATCH v5 02/11] mm: add PMD swap entry splitting support

Quoted 9 lines · Dev Jain
Quoted 3 lines · Usama Arif

Add a swap branch in __split_huge_pmd_locked() that splits a PMD swap entry into 512 PTE swap entries. Unlike migration splits, no folio reference is needed because swap entries point to swap slots, not

Confusing wording. swap entries need reference of swap slots instead of folios. I would drop the mention of migration here.

I added about migration because its the other if part of the if else and was a good comparison. Will remove it. Thanks!

Quoted 86 lines
Quoted 58 lines

pages. Each PTE inherits the correct sub-slot offset and preserves soft_dirty, uffd_wp, and exclusive flags.

The folio_remove_rmap_pmd() gate at the end must inspect old_pmd rather than *pmd: for a present THP split, *pmd has already been cleared by pmdp_invalidate(), and that invalidated bit pattern can decode as a plausible swap entry.

This branch is reached from the explicit __split_huge_pmd() callers that hit a non-present PMD: partial-range mprotect / munmap, the wp_huge_pmd() PMD-COW fallback, and the swap-in / swapoff fallbacks added in later patches when the cached folio is no longer PMD-sized. page_vma_mapped_walk() does not iterate PMD swap entries, so try_to_unmap_one() and try_to_migrate_one() do not reach this branch and freeze=true cannot occur in this branch today. page and folio are therefore left uninitialized in the swap branch; a VM_WARN_ON_ONCE(freeze) catches any future caller that breaks this invariant before the freeze path dereferences page_to_pfn(page + i) or put_page(page).

---
 mm/huge_memory.c | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)
mm/huge_memory.c +17 -0
index 04e8a6b55343..9819c0ae228a 100644
@@ -3210,6 +3210,14 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 			folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR,
 						 vma, haddr, rmap_flags);
 		}
+	} else if (pmd_is_swap_entry(*pmd)) {
+		VM_WARN_ON_ONCE(freeze);
+		/* Swap entries have no page for the migration freeze path. */
+		freeze = false;
+		old_pmd = *pmd;
+		soft_dirty = pmd_swp_soft_dirty(old_pmd);
+		uffd_wp = pmd_swp_uffd(old_pmd);
+		anon_exclusive = pmd_swp_exclusive(old_pmd);
 	} else {
 		/*
 		 * Up to this point the pmd is present and huge and userland has
@@ -3346,6 +3354,25 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
 			set_pte_at(mm, addr, pte + i, entry);
 		}
+	} else if (pmd_is_swap_entry(old_pmd)) {
+		softleaf_t sl_entry = softleaf_from_pmd(old_pmd);
+		pte_t swp_pte;
+		swp_entry_t sub_entry;
+
+		for (i = 0, addr = haddr; i < HPAGE_PMD_NR;
+		     i++, addr += PAGE_SIZE) {
+			sub_entry = swp_entry(swp_type(sl_entry),
+					      swp_offset(sl_entry) + i);

mm/huge_memory.c static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, · line 3375

Quoted 10 lines
mm/huge_memory.c +10 -0
+			swp_pte = swp_entry_to_pte(sub_entry);
+			if (soft_dirty)
+				swp_pte = pte_swp_mksoft_dirty(swp_pte);
+			if (uffd_wp)
+				swp_pte = pte_swp_mkuffd(swp_pte);
+			if (anon_exclusive)
+				swp_pte = pte_swp_mkexclusive(swp_pte);
+			VM_WARN_ON(!pte_none(ptep_get(pte + i)));
+			set_pte_at(mm, addr, pte + i, swp_pte);
+		}

All these for loops could later benefit from the set_softleaf_ptes() helper:
https://lore.kernel.org/all/[email protected]/

Quoted 12 lines
mm/huge_memory.c +1 -1
 	} else {
 		pte_t entry;
 
@@ -3373,7 +3400,7 @@ static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd,
 	}
 	pte_unmap(pte);
 
-	if (!pmd_is_migration_entry(*pmd))
+	if (!pmd_is_migration_entry(old_pmd) && !pmd_is_swap_entry(old_pmd))
 		folio_remove_rmap_pmd(folio, page, vma);
 	if (freeze)
 		put_page(page);
author reviewer
#7 lore raw

PATCH v5 3/11 mm: handle PMD swap entries in fork path

In reply to Usama Arif

Teach copy_huge_pmd()/copy_huge_non_present_pmd() about swap entries, mirroring copy_nonpresent_pte().

swap_dup_entry_direct() gains a nr parameter (and is renamed to swap_dup_entries_direct()) so it can duplicate a contiguous range of swap slots in one call, matching the existing swap_put_entries_direct(entry, nr) API. Existing callers pass 1.

swap_retry_table_alloc() likewise gains a nr parameter so the outer retry knows how many slots the caller was trying to duplicate. The underlying swap_extend_table_alloc() now scans every slot in [ci_off, ci_off + nr) to confirm that at least one still needs the per-cluster extend table before committing an allocation.

copy_huge_non_present_pmd() "copies" PMD swap entries during fork instead of splitting, preserving the THP. This mirrors copy_nonpresent_pte() which duplicates the swap slot refcount, clears the exclusive bit on the source, and adds the destination mm to mmlist. If swap_dup_entries_direct() fails (GFP_ATOMIC table alloc), copy_huge_pmd() retries after swap_retry_table_alloc(entry, HPAGE_PMD_NR, GFP_KERNEL), matching the PTE retry in copy_pte_range(). The PMD is stable across the retry because dup_mmap() holds write mmap_lock on both mm_structs.

---
 include/linux/swap.h |  4 ++--
 mm/huge_memory.c     | 54 ++++++++++++++++++++++++++++++++++++++------
 mm/memory.c          |  4 ++--
 mm/swap.h            |  5 ++--
 mm/swapfile.c        | 40 ++++++++++++++++++++------------
 5 files changed, 80 insertions(+), 27 deletions(-)
include/linux/swap.h +2 -2
index 32da5647171d..e8ad2741142c 100644
@@ -390,7 +390,7 @@ sector_t swap_folio_sector(struct folio *folio);
  * All entries must be allocated by folio_alloc_swap(). And they must have
  * a swap count > 1. See comments of folio_*_swap helpers for more info.
  */
-int swap_dup_entry_direct(swp_entry_t entry);
+int swap_dup_entries_direct(swp_entry_t entry, int nr);
 void swap_put_entries_direct(swp_entry_t entry, int nr);
 
 /*
@@ -434,7 +434,7 @@ static inline void free_swap_cache(struct folio *folio)
 {
 }
 
-static inline int swap_dup_entry_direct(swp_entry_t ent)
+static inline int swap_dup_entries_direct(swp_entry_t ent, int nr)
 {
 	return 0;
 }
mm/huge_memory.c +47 -7

85 lines not on this page · raw message

mm/memory.c +2 -2
index a620d425ec95..c64e11fc7180 100644
@@ -1012,7 +1012,7 @@ copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
 	struct page *page;
 
 	if (likely(softleaf_is_swap(entry))) {
-		if (swap_dup_entry_direct(entry) < 0)
+		if (swap_dup_entries_direct(entry, 1) < 0)
 			return -EIO;
 
 		mm_prepare_for_swap_entries(dst_mm);
@@ -1427,7 +1427,7 @@ copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
 
 	if (ret == -EIO) {
 		VM_WARN_ON_ONCE(!entry.val);
-		if (swap_retry_table_alloc(entry, GFP_KERNEL) < 0) {
+		if (swap_retry_table_alloc(entry, 1, GFP_KERNEL) < 0) {
 			ret = -ENOMEM;
 			goto out;
 		}
mm/swap.h +3 -2
index abd26588abd2..326bbb7ef831 100644
@@ -229,7 +229,7 @@ static inline void swap_cluster_unlock_irq(struct swap_cluster_info *ci)
 	spin_unlock_irq(&ci->lock);
 }
 
-extern int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp);
+int swap_retry_table_alloc(swp_entry_t entry, unsigned int nr, gfp_t gfp);
 
 /*
  * Below are the core routines for doing swap for a folio.
@@ -435,7 +435,8 @@ static inline int swap_writeout(struct swap_io_ctx *ctx, struct folio *folio)
 	return 0;
 }
 
-static inline int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp)
+static inline int swap_retry_table_alloc(swp_entry_t entry, unsigned int nr,
+					 gfp_t gfp)
 {
 	return -EINVAL;
 }
mm/swapfile.c +26 -14
index 5d15913dcf86..1292c6bfe8c0 100644
@@ -1462,9 +1462,11 @@ static bool swap_sync_discard(void)
 
 static int swap_extend_table_alloc(struct swap_info_struct *si,
 				   struct swap_cluster_info *ci,
-				   unsigned int ci_off, gfp_t gfp)
+				   unsigned int ci_off, unsigned int nr,
+				   gfp_t gfp)
 {
 	int count;
+	unsigned int i;
 	void *table;
 
 	table = kzalloc(sizeof(ci->extend_table[0]) * SWAPFILE_CLUSTER, gfp);
@@ -1480,15 +1482,21 @@ static int swap_extend_table_alloc(struct swap_info_struct *si,
 	 */
 	if (!cluster_table_is_alloced(ci))
 		goto out_free;
-	count = swp_tb_get_count(__swap_table_get(ci, ci_off));
-	if (count < (SWP_TB_COUNT_MAX - 1))
-		goto out_free;
 	if (ci->extend_table)
 		goto out_free;
-
-	ci->extend_table = table;
-	spin_unlock(&ci->lock);
-	return 0;
+	/*
+	 * The caller may not know which slot in [ci_off, ci_off + nr) hit
+	 * SWP_TB_COUNT_MAX - 1. Confirm at least one slot in the range still
+	 * needs the extend table before committing the allocation.
+	 */
+	for (i = 0; i < nr; i++) {
+		count = swp_tb_get_count(__swap_table_get(ci, ci_off + i));
+		if (count >= (SWP_TB_COUNT_MAX - 1)) {
+			ci->extend_table = table;
+			spin_unlock(&ci->lock);
+			return 0;
+		}
+	}
 
 out_free:
 	spin_unlock(&ci->lock);
@@ -1496,7 +1504,7 @@ static int swap_extend_table_alloc(struct swap_info_struct *si,
 	return 0;
 }
 
-int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp)
+int swap_retry_table_alloc(swp_entry_t entry, unsigned int nr, gfp_t gfp)
 {
 	int ret;
 	struct swap_info_struct *si;
@@ -1508,7 +1516,8 @@ int swap_retry_table_alloc(swp_entry_t entry, gfp_t gfp)
 		return 0;
 
 	ci = __swap_offset_to_cluster(si, offset);
-	ret = swap_extend_table_alloc(si, ci, swp_cluster_offset(entry), gfp);
+	ret = swap_extend_table_alloc(si, ci, swp_cluster_offset(entry), nr,
+				      gfp);
 
 	put_swap_device(si);
 	return ret;
@@ -1709,7 +1718,8 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 		if (unlikely(err)) {
 			if (err == -ENOMEM) {
 				spin_unlock(&ci->lock);
-				err = swap_extend_table_alloc(si, ci, ci_off, GFP_ATOMIC);
+				err = swap_extend_table_alloc(si, ci, ci_off, 1,
+							      GFP_ATOMIC);
 				spin_lock(&ci->lock);
 				if (!err)
 					goto restart;
@@ -1720,6 +1730,7 @@ static int swap_dup_entries_cluster(struct swap_info_struct *si,
 	swap_cluster_unlock(ci);
 	return 0;
 failed:
+	/* The caller's page-table or swap-cache reference pins every slot. */
 	while (ci_off-- > ci_start)
 		__swap_cluster_put_entry(ci, ci_off);
 	swap_extend_table_try_free(ci);
@@ -3911,8 +3922,9 @@ void si_swapinfo(struct sysinfo *val)
 }
 
 /*
- * swap_dup_entry_direct() - Increase reference count of a swap entry by one.
+ * swap_dup_entries_direct() - Increase reference count of swap entries by one.
  * @entry: first swap entry from which we want to increase the refcount.
+ * @nr: number of contiguous swap entries to duplicate.
  *
  * Returns 0 for success, or -ENOMEM if the extend table is required
  * but could not be atomically allocated.  Returns -EINVAL if the swap
@@ -3924,7 +3936,7 @@ void si_swapinfo(struct sysinfo *val)
  * Also the swap entry must have a count >= 1. Otherwise folio_dup_swap should
  * be used.
  */
-int swap_dup_entry_direct(swp_entry_t entry)
+int swap_dup_entries_direct(swp_entry_t entry, int nr)
 {
 	struct swap_info_struct *si;
 
@@ -3941,7 +3953,7 @@ int swap_dup_entry_direct(swp_entry_t entry)
 	 */
 	VM_WARN_ON_ONCE(!swap_entry_swapped(si, entry));
 
-	return swap_dup_entries_cluster(si, swp_offset(entry), 1);
+	return swap_dup_entries_cluster(si, swp_offset(entry), nr);
 }
 
 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
Signature · 1 line
2.53.0-Meta
author reviewer
#8 lore raw

PATCH v5 4/11 mm: zswap: add range lookup for large-folio swapin

In reply to Usama Arif

From: Alexandre Ghiti <[email protected]>

A large folio reaches zswap_load() only when the caller expects the whole range to be on disk. Zswap still stores large folios as independent order-0 entries, so reconstructing a large folio from zswap entries would risk returning partially initialized data.

Teach zswap_load() to scan the covered range. If no slot is in zswap, return -ENOENT so swap_read_folio() reads the backing device. If any slot is still in zswap, fail the large-folio read so the caller can fall back to per-page swapin.

Return -EIO rather than -EINVAL for that conflict. Large-folio loads are now valid requests; the error means zswap cannot safely satisfy the request from partial per-page compressed state, not that the request is unsupported. Existing callers only distinguish -ENOENT, so this is a semantic clarification rather than a behavioral change.

Add zswap_is_present() so PMD swap-entry consumers can make the same range decision before attempting PMD-order swapin.

---
 include/linux/zswap.h |  6 ++++++
 mm/zswap.c            | 42 ++++++++++++++++++++++++++++++++----------
 2 files changed, 38 insertions(+), 10 deletions(-)
include/linux/zswap.h +6 -0
index 30c193a1207e..cd9efcf9dec9 100644
@@ -35,6 +35,7 @@ void zswap_lruvec_state_init(struct lruvec *lruvec);
 void zswap_folio_swapin(struct folio *folio);
 bool zswap_is_enabled(void);
 bool zswap_never_enabled(void);
+bool zswap_is_present(swp_entry_t entry, unsigned int nr);
 #else
 
 struct zswap_lruvec_state {};
@@ -69,6 +70,11 @@ static inline bool zswap_never_enabled(void)
 	return true;
 }
 
+static inline bool zswap_is_present(swp_entry_t entry, unsigned int nr)
+{
+	return false;
+}
+
 #endif
 
 #endif /* _LINUX_ZSWAP_H */
mm/zswap.c +32 -10

61 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
maintainer
#9 lore raw

Re: [PATCH v5 04/11] mm: zswap: add range lookup for large-folio swapin

Quoted 103 lines · Usama Arif

From: Alexandre Ghiti <[email protected]>

A large folio reaches zswap_load() only when the caller expects the whole range to be on disk. Zswap still stores large folios as independent order-0 entries, so reconstructing a large folio from zswap entries would risk returning partially initialized data.

Teach zswap_load() to scan the covered range. If no slot is in zswap, return -ENOENT so swap_read_folio() reads the backing device. If any slot is still in zswap, fail the large-folio read so the caller can fall back to per-page swapin.

Return -EIO rather than -EINVAL for that conflict. Large-folio loads are now valid requests; the error means zswap cannot safely satisfy the request from partial per-page compressed state, not that the request is unsupported. Existing callers only distinguish -ENOENT, so this is a semantic clarification rather than a behavioral change.

Add zswap_is_present() so PMD swap-entry consumers can make the same range decision before attempting PMD-order swapin.

---
 include/linux/zswap.h |  6 ++++++
 mm/zswap.c            | 42 ++++++++++++++++++++++++++++++++----------
 2 files changed, 38 insertions(+), 10 deletions(-)
include/linux/zswap.h +6 -0
index 30c193a1207e..cd9efcf9dec9 100644
@@ -35,6 +35,7 @@ void zswap_lruvec_state_init(struct lruvec *lruvec);
 void zswap_folio_swapin(struct folio *folio);
 bool zswap_is_enabled(void);
 bool zswap_never_enabled(void);
+bool zswap_is_present(swp_entry_t entry, unsigned int nr);
 #else
 
 struct zswap_lruvec_state {};
@@ -69,6 +70,11 @@ static inline bool zswap_never_enabled(void)
 	return true;
 }
 
+static inline bool zswap_is_present(swp_entry_t entry, unsigned int nr)
+{
+	return false;
+}
+
 #endif
 
 #endif /* _LINUX_ZSWAP_H */
mm/zswap.c +22 -7
index 4e76a4a87cdc..384492f1f696 100644
@@ -1561,6 +1561,23 @@ bool zswap_store(struct folio *folio)
 	return ret;
 }
 
+/**
+ * zswap_is_present() - is any slot in [entry, entry + nr) in zswap?
+ * @entry: base swap entry of the range
+ * @nr: number of contiguous slots to check (pass 1 for a single-slot query)
+ */
+bool zswap_is_present(swp_entry_t entry, unsigned int nr)
+{
+	pgoff_t offset = swp_offset(entry);
+	struct xarray *tree = swap_zswap_tree(entry);
+	unsigned long index = offset;
+
+	if (!nr || zswap_never_enabled())
+		return false;
+
+	return xa_find(tree, &index, offset + nr - 1, XA_PRESENT);
+}
+
 /**
  * zswap_load() - load a folio from zswap
  * @folio: folio to load
@@ -1573,10 +1590,9 @@ bool zswap_store(struct folio *folio)
  *  NOT marked up-to-date, so that an IO error is emitted (e.g. do_swap_page()
  *  will SIGBUS).
  *
- *  -EINVAL: if the swapped out content was in zswap, but the page belongs
- *  to a large folio, which is not supported by zswap. The folio is unlocked,
- *  but NOT marked up-to-date, so that an IO error is emitted (e.g.
- *  do_swap_page() will SIGBUS).
+ *  -EIO: if a slot in a large-folio range is unexpectedly still in zswap.
+ *  The folio is unlocked, but NOT marked up-to-date, so that an IO
+ *  error is emitted (e.g. do_swap_page() will SIGBUS).
  *
  *  -ENOENT: if the swapped out content was not in zswap. The folio remains
  *  locked on return.
@@ -1595,13 +1611,19 @@ int zswap_load(struct folio *folio)
 		return -ENOENT;
 
 	/*
-	 * Large folios should not be swapped in while zswap is being used, as
-	 * they are not properly handled. Zswap does not properly load large
-	 * folios, and a large folio may only be partially in zswap.
+	 * A large folio reaches zswap_load() only when its whole range is
+	 * expected to be on disk: PMD swap-entry consumers split before

mm/zswap.c int zswap_load(struct folio *folio) · line 1622

Quoted 10 lines
mm/zswap.c +6 -3
+	 * calling into PMD-order swapin whenever any slot is still in zswap.
+	 * Confirm the range is entirely absent from zswap and return -ENOENT
+	 * so the caller reads it from disk; if a slot is unexpectedly still in
+	 * zswap, fail the read rather than return partially-initialized data.
 	 */
-	if (WARN_ON_ONCE(folio_test_large(folio))) {
-		folio_unlock(folio);
-		return -EINVAL;
+	if (folio_test_large(folio)) {
+		if (zswap_is_present(swp, folio_nr_pages(folio))) {

Is dropping the warning here intentional (for the folio_test_large() && zswap_is_present() case)?

Quoted 10 lines
mm/zswap.c +4 -0
+			folio_unlock(folio);
+			return -EIO;
+		}
+		return -ENOENT;
 	}
 
 	entry = xa_load(tree, offset);
Signature · 1 line
2.53.0-Meta
author reviewer
#10 lore raw

Re: [PATCH v5 04/11] mm: zswap: add range lookup for large-folio swapin

Quoted 109 lines · Yosry Ahmed
Quoted 108 lines · Usama Arif

From: Alexandre Ghiti <[email protected]>

A large folio reaches zswap_load() only when the caller expects the whole range to be on disk. Zswap still stores large folios as independent order-0 entries, so reconstructing a large folio from zswap entries would risk returning partially initialized data.

Teach zswap_load() to scan the covered range. If no slot is in zswap, return -ENOENT so swap_read_folio() reads the backing device. If any slot is still in zswap, fail the large-folio read so the caller can fall back to per-page swapin.

Return -EIO rather than -EINVAL for that conflict. Large-folio loads are now valid requests; the error means zswap cannot safely satisfy the request from partial per-page compressed state, not that the request is unsupported. Existing callers only distinguish -ENOENT, so this is a semantic clarification rather than a behavioral change.

Add zswap_is_present() so PMD swap-entry consumers can make the same range decision before attempting PMD-order swapin.

---
 include/linux/zswap.h |  6 ++++++
 mm/zswap.c            | 42 ++++++++++++++++++++++++++++++++----------
 2 files changed, 38 insertions(+), 10 deletions(-)
include/linux/zswap.h +6 -0
index 30c193a1207e..cd9efcf9dec9 100644
@@ -35,6 +35,7 @@ void zswap_lruvec_state_init(struct lruvec *lruvec);
 void zswap_folio_swapin(struct folio *folio);
 bool zswap_is_enabled(void);
 bool zswap_never_enabled(void);
+bool zswap_is_present(swp_entry_t entry, unsigned int nr);
 #else
 
 struct zswap_lruvec_state {};
@@ -69,6 +70,11 @@ static inline bool zswap_never_enabled(void)
 	return true;
 }
 
+static inline bool zswap_is_present(swp_entry_t entry, unsigned int nr)
+{
+	return false;
+}
+
 #endif
 
 #endif /* _LINUX_ZSWAP_H */
mm/zswap.c +26 -7
index 4e76a4a87cdc..384492f1f696 100644
@@ -1561,6 +1561,23 @@ bool zswap_store(struct folio *folio)
 	return ret;
 }
 
+/**
+ * zswap_is_present() - is any slot in [entry, entry + nr) in zswap?
+ * @entry: base swap entry of the range
+ * @nr: number of contiguous slots to check (pass 1 for a single-slot query)
+ */
+bool zswap_is_present(swp_entry_t entry, unsigned int nr)
+{
+	pgoff_t offset = swp_offset(entry);
+	struct xarray *tree = swap_zswap_tree(entry);
+	unsigned long index = offset;
+
+	if (!nr || zswap_never_enabled())
+		return false;
+
+	return xa_find(tree, &index, offset + nr - 1, XA_PRESENT);
+}
+
 /**
  * zswap_load() - load a folio from zswap
  * @folio: folio to load
@@ -1573,10 +1590,9 @@ bool zswap_store(struct folio *folio)
  *  NOT marked up-to-date, so that an IO error is emitted (e.g. do_swap_page()
  *  will SIGBUS).
  *
- *  -EINVAL: if the swapped out content was in zswap, but the page belongs
- *  to a large folio, which is not supported by zswap. The folio is unlocked,
- *  but NOT marked up-to-date, so that an IO error is emitted (e.g.
- *  do_swap_page() will SIGBUS).
+ *  -EIO: if a slot in a large-folio range is unexpectedly still in zswap.
+ *  The folio is unlocked, but NOT marked up-to-date, so that an IO
+ *  error is emitted (e.g. do_swap_page() will SIGBUS).
  *
  *  -ENOENT: if the swapped out content was not in zswap. The folio remains
  *  locked on return.
@@ -1595,13 +1611,19 @@ int zswap_load(struct folio *folio)
 		return -ENOENT;
 
 	/*
-	 * Large folios should not be swapped in while zswap is being used, as
-	 * they are not properly handled. Zswap does not properly load large
-	 * folios, and a large folio may only be partially in zswap.
+	 * A large folio reaches zswap_load() only when its whole range is
+	 * expected to be on disk: PMD swap-entry consumers split before
+	 * calling into PMD-order swapin whenever any slot is still in zswap.
+	 * Confirm the range is entirely absent from zswap and return -ENOENT
+	 * so the caller reads it from disk; if a slot is unexpectedly still in
+	 * zswap, fail the read rather than return partially-initialized data.
 	 */
Quoted 9 lines

mm/zswap.c int zswap_load(struct folio *folio) · line 1622

Quoted 5 lines
mm/zswap.c +2 -3
-	if (WARN_ON_ONCE(folio_test_large(folio))) {
-		folio_unlock(folio);
-		return -EINVAL;
+	if (folio_test_large(folio)) {
+		if (zswap_is_present(swp, folio_nr_pages(folio))) {

Is dropping the warning here intentional (for the folio_test_large() && zswap_is_present() case)?

Yes, so we can end up in a race, which should be handled gracefully.

For example, lets say we have zswap writeback enabled, which means we can end up in a state where we have a PMD swap entry and 511 of the 512 slots have been written to disk, but 1 slot (slot X) is still in zswap.

We can then have the following race:

CPU A: PMD swap-in CPU B: split-PTE swap-in
------------------ ------------------------

Checks swap cache: empty

Faults slot X Adds order-0 folio F zswap_load(F):
removes X from zswap marks F dirty

Checks zswap range: empty
A is preempted

Unmaps/reclaims F zswap_store(F):
puts X back in zswap
Removes F from swap cache

A resumes
Allocates large swap-cache folio G
zswap_load(G) finds X in zswap

The correct action would be to reject the PMD order read and fall back to per-page loading.

I am bit torn about what to do for zswap here. The series is quite big already. Alexandre is looking at adding support for PMD swap, but will send patches once this series gets merged. My initial versions 1 and 2, basically stopped installing PMD swap entry if zswap was ever enabled. From v3, I used Alexandre's suggestion to do zswap_is_present() test so that PMD swap entry can keep on working.

Both of these paths are temporary till Alex sends his series. I do feel my initial version was simpler but will basically stop working if zswap is ever enabled. Do you have any suggestions on what your preference is for zswap?

Thanks!
Usama

Quoted 10 lines
Quoted 10 lines
mm/zswap.c +4 -0
+			folio_unlock(folio);
+			return -EIO;
+		}
+		return -ENOENT;
 	}
 
 	entry = xa_load(tree, offset);
Signature · 1 line
2.53.0-Meta
maintainer
#11 lore raw

Re: [PATCH v5 04/11] mm: zswap: add range lookup for large-folio swapin

Quoted 48 lines
Quoted 14 lines
Quoted 14 lines
mm/zswap.c +6 -3
@@ -1595,13 +1611,19 @@ int zswap_load(struct folio *folio)
             return -ENOENT;
 
     /*
-     * Large folios should not be swapped in while zswap is being used, as
-     * they are not properly handled. Zswap does not properly load large
-     * folios, and a large folio may only be partially in zswap.
+     * A large folio reaches zswap_load() only when its whole range is
+     * expected to be on disk: PMD swap-entry consumers split before
+     * calling into PMD-order swapin whenever any slot is still in zswap.
+     * Confirm the range is entirely absent from zswap and return -ENOENT
+     * so the caller reads it from disk; if a slot is unexpectedly still in
+     * zswap, fail the read rather than return partially-initialized data.
      */
Quoted 9 lines

mm/zswap.c int zswap_load(struct folio *folio) · line 1622

Quoted 5 lines
mm/zswap.c +2 -3
-    if (WARN_ON_ONCE(folio_test_large(folio))) {
-            folio_unlock(folio);
-            return -EINVAL;
+    if (folio_test_large(folio)) {
+            if (zswap_is_present(swp, folio_nr_pages(folio))) {

Is dropping the warning here intentional (for the folio_test_large() && zswap_is_present() case)?

Yes, so we can end up in a race, which should be handled gracefully.

For example, lets say we have zswap writeback enabled, which means we can end up in a state where we have a PMD swap entry and 511 of the 512 slots have been written to disk, but 1 slot (slot X) is still in zswap.

We can then have the following race:

CPU A: PMD swap-in CPU B: split-PTE swap-in
------------------ ------------------------

Checks swap cache: empty

Faults slot X Adds order-0 folio F zswap_load(F):
removes X from zswap marks F dirty

Checks zswap range: empty
A is preempted

Quoted 8 lines

Unmaps/reclaims F zswap_store(F):
puts X back in zswap
Removes F from swap cache

A resumes
Allocates large swap-cache folio G
zswap_load(G) finds X in zswap

Why don't we check the zswap range after allocating a folio in the swap cache? I am assuming at this point we have the folio locked and the result should be stable?

Quoted 11 lines

The correct action would be to reject the PMD order read and fall back to per-page loading.

I am bit torn about what to do for zswap here. The series is quite big already. Alexandre is looking at adding support for PMD swap, but will send patches once this series gets merged. My initial versions 1 and 2, basically stopped installing PMD swap entry if zswap was ever enabled. From v3, I used Alexandre's suggestion to do zswap_is_present() test so that PMD swap entry can keep on working.

Quoted 4 lines

Both of these paths are temporary till Alex sends his series. I do feel my initial version was simpler but will basically stop working if zswap is ever enabled. Do you have any suggestions on what your preference is for zswap?

Even with PMD zswap load support, we still have to deal with the case where some order-0 pages are in zswap and some are on disk, right? I don't see how that would eliminate the case you mentioned above.

maintainer
#12 lore raw

Re: [PATCH v5 04/11] mm: zswap: add range lookup for large-folio swapin

Quoted 54 lines · Yosry Ahmed
Quoted 54 lines
Quoted 15 lines
Quoted 15 lines
mm/zswap.c +6 -3
@@ -1595,13 +1611,19 @@ int zswap_load(struct folio *folio)
             return -ENOENT;
 
     /*
-     * Large folios should not be swapped in while zswap is being used, as
-     * they are not properly handled. Zswap does not properly load large
-     * folios, and a large folio may only be partially in zswap.
+     * A large folio reaches zswap_load() only when its whole range is
+     * expected to be on disk: PMD swap-entry consumers split before
+     * calling into PMD-order swapin whenever any slot is still in zswap.
+     * Confirm the range is entirely absent from zswap and return -ENOENT
+     * so the caller reads it from disk; if a slot is unexpectedly still in
+     * zswap, fail the read rather than return partially-initialized data.
      */
Quoted 9 lines

mm/zswap.c int zswap_load(struct folio *folio) · line 1622

Quoted 5 lines
mm/zswap.c +2 -3
-    if (WARN_ON_ONCE(folio_test_large(folio))) {
-            folio_unlock(folio);
-            return -EINVAL;
+    if (folio_test_large(folio)) {
+            if (zswap_is_present(swp, folio_nr_pages(folio))) {

Is dropping the warning here intentional (for the folio_test_large() && zswap_is_present() case)?

Yes, so we can end up in a race, which should be handled gracefully.

For example, lets say we have zswap writeback enabled, which means we can end up in a state where we have a PMD swap entry and 511 of the 512 slots have been written to disk, but 1 slot (slot X) is still in zswap.

We can then have the following race:

CPU A: PMD swap-in CPU B: split-PTE swap-in
------------------ ------------------------

Checks swap cache: empty

Faults slot X Adds order-0 folio F zswap_load(F):
removes X from zswap marks F dirty

Checks zswap range: empty
A is preempted

Unmaps/reclaims F zswap_store(F):
puts X back in zswap
Removes F from swap cache

Quoted 8 lines
Quoted 3 lines

A resumes
Allocates large swap-cache folio G
zswap_load(G) finds X in zswap

Why don't we check the zswap range after allocating a folio in the swap cache? I am assuming at this point we have the folio locked and the result should be stable?

+1. Is it possible to perform the check in __swap_cache_add_check?

That's what I did for vswap, per Kairui's suggestions. The cluster lock is held from that point all the way to after the folio is locked-and-loaded into swap cache, at which point no one can change the backend under you.

author reviewer
#13 lore raw

Re: [PATCH v5 04/11] mm: zswap: add range lookup for large-folio swapin

In reply to Yosry Ahmed
Quoted 53 lines · Yosry Ahmed
Quoted 53 lines
Quoted 14 lines
Quoted 14 lines
(quoted diff) +6 -3
@@ -1595,13 +1611,19 @@ int zswap_load(struct folio *folio)
             return -ENOENT;
 
     /*
-     * Large folios should not be swapped in while zswap is being used, as
-     * they are not properly handled. Zswap does not properly load large
-     * folios, and a large folio may only be partially in zswap.
+     * A large folio reaches zswap_load() only when its whole range is
+     * expected to be on disk: PMD swap-entry consumers split before
+     * calling into PMD-order swapin whenever any slot is still in zswap.
+     * Confirm the range is entirely absent from zswap and return -ENOENT
+     * so the caller reads it from disk; if a slot is unexpectedly still in
+     * zswap, fail the read rather than return partially-initialized data.
      */
Quoted 9 lines

Review int zswap_load(struct folio *folio) · line 1622

Quoted 5 lines
(quoted diff) +2 -3
-    if (WARN_ON_ONCE(folio_test_large(folio))) {
-            folio_unlock(folio);
-            return -EINVAL;
+    if (folio_test_large(folio)) {
+            if (zswap_is_present(swp, folio_nr_pages(folio))) {

Is dropping the warning here intentional (for the folio_test_large() && zswap_is_present() case)?

Yes, so we can end up in a race, which should be handled gracefully.

For example, lets say we have zswap writeback enabled, which means we can end up in a state where we have a PMD swap entry and 511 of the 512 slots have been written to disk, but 1 slot (slot X) is still in zswap.

We can then have the following race:

CPU A: PMD swap-in CPU B: split-PTE swap-in
------------------ ------------------------

Checks swap cache: empty

Faults slot X Adds order-0 folio F zswap_load(F):
removes X from zswap marks F dirty

Checks zswap range: empty
A is preempted

Unmaps/reclaims F zswap_store(F):
puts X back in zswap
Removes F from swap cache

Quoted 8 lines
Quoted 3 lines

A resumes
Allocates large swap-cache folio G
zswap_load(G) finds X in zswap

Why don't we check the zswap range after allocating a folio in the swap cache? I am assuming at this point we have the folio locked and the result should be stable?

Yes that makes sense. The folio is locked and the result will be stable. How about something like below?

mm/swap_state.c +12 -0
index 1f08fb522036..41f168377cb1 100644
@@ -12,6 +12,7 @@
 #include <linux/kernel_stat.h>
 #include <linux/mempolicy.h>
 #include <linux/swap.h>
+#include <linux/zswap.h>
 #include <linux/leafops.h>
 #include <linux/init.h>
 #include <linux/pagemap.h>
@@ -500,6 +501,17 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
        __folio_set_locked(folio);
        __folio_set_swapbacked(folio);
        __swap_cache_do_add_folio(ci, folio, entry);
+       /*
+        * Reject mixed zswap/disk backing before starting the read.
+        */
+       if (order && zswap_is_present(entry, nr_pages)) {
+               __swap_cache_do_del_folio(ci, folio, entry, shadow);
+               spin_unlock(&ci->lock);
+               folio_unlock(folio);
+               /* nr_pages refs from swap cache, 1 from allocation */
+               folio_put_refs(folio, nr_pages + 1);
+               return ERR_PTR(-EBUSY);
+       }
        spin_unlock(&ci->lock);
 
        if (mem_cgroup_swapin_charge_folio(folio, memcg_id,
Quoted 11 lines
Quoted 11 lines

The correct action would be to reject the PMD order read and fall back to per-page loading.

I am bit torn about what to do for zswap here. The series is quite big already. Alexandre is looking at adding support for PMD swap, but will send patches once this series gets merged. My initial versions 1 and 2, basically stopped installing PMD swap entry if zswap was ever enabled. From v3, I used Alexandre's suggestion to do zswap_is_present() test so that PMD swap entry can keep on working.

Quoted 8 lines
Quoted 4 lines

Both of these paths are temporary till Alex sends his series. I do feel my initial version was simpler but will basically stop working if zswap is ever enabled. Do you have any suggestions on what your preference is for zswap?

Even with PMD zswap load support, we still have to deal with the case where some order-0 pages are in zswap and some are on disk, right? I don't see how that would eliminate the case you mentioned above.

Ack, yeah writeback will still mess with things. I will keep the current implementation.

maintainer
#14 lore raw

Re: [PATCH v5 04/11] mm: zswap: add range lookup for large-folio swapin

Quoted 86 lines · Usama Arif
Quoted 53 lines · Yosry Ahmed
Quoted 53 lines
Quoted 14 lines
Quoted 14 lines
(quoted diff) +6 -3
@@ -1595,13 +1611,19 @@ int zswap_load(struct folio *folio)
             return -ENOENT;
 
     /*
-     * Large folios should not be swapped in while zswap is being used, as
-     * they are not properly handled. Zswap does not properly load large
-     * folios, and a large folio may only be partially in zswap.
+     * A large folio reaches zswap_load() only when its whole range is
+     * expected to be on disk: PMD swap-entry consumers split before
+     * calling into PMD-order swapin whenever any slot is still in zswap.
+     * Confirm the range is entirely absent from zswap and return -ENOENT
+     * so the caller reads it from disk; if a slot is unexpectedly still in
+     * zswap, fail the read rather than return partially-initialized data.
      */
Quoted 9 lines

Review int zswap_load(struct folio *folio) · line 1622

Quoted 5 lines
(quoted diff) +2 -3
-    if (WARN_ON_ONCE(folio_test_large(folio))) {
-            folio_unlock(folio);
-            return -EINVAL;
+    if (folio_test_large(folio)) {
+            if (zswap_is_present(swp, folio_nr_pages(folio))) {

Is dropping the warning here intentional (for the folio_test_large() && zswap_is_present() case)?

Yes, so we can end up in a race, which should be handled gracefully.

For example, lets say we have zswap writeback enabled, which means we can end up in a state where we have a PMD swap entry and 511 of the 512 slots have been written to disk, but 1 slot (slot X) is still in zswap.

We can then have the following race:

CPU A: PMD swap-in CPU B: split-PTE swap-in
------------------ ------------------------

Checks swap cache: empty

Faults slot X Adds order-0 folio F zswap_load(F):
removes X from zswap marks F dirty

Checks zswap range: empty
A is preempted

Unmaps/reclaims F zswap_store(F):
puts X back in zswap
Removes F from swap cache

Quoted 8 lines
Quoted 3 lines

A resumes
Allocates large swap-cache folio G
zswap_load(G) finds X in zswap

Why don't we check the zswap range after allocating a folio in the swap cache? I am assuming at this point we have the folio locked and the result should be stable?

Yes that makes sense. The folio is locked and the result will be stable. How about something like below?

mm/swap_state.c +2 -0
index 1f08fb522036..41f168377cb1 100644
@@ -12,6 +12,7 @@
 #include <linux/kernel_stat.h>
 #include <linux/mempolicy.h>
 #include <linux/swap.h>
+#include <linux/zswap.h>
 #include <linux/leafops.h>
 #include <linux/init.h>
 #include <linux/pagemap.h>
@@ -500,6 +501,17 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
        __folio_set_locked(folio);
        __folio_set_swapbacked(folio);
        __swap_cache_do_add_folio(ci, folio, entry);
+       /*

mm/swap_state.c static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci, · line 514

Quoted 10 lines
mm/swap_state.c +10 -0
+        * Reject mixed zswap/disk backing before starting the read.
+        */
+       if (order && zswap_is_present(entry, nr_pages)) {
+               __swap_cache_do_del_folio(ci, folio, entry, shadow);
+               spin_unlock(&ci->lock);
+               folio_unlock(folio);
+               /* nr_pages refs from swap cache, 1 from allocation */
+               folio_put_refs(folio, nr_pages + 1);
+               return ERR_PTR(-EBUSY);
+       }

If you move it to __swap_cache_add_check(), you can potentially backoff even before the folio allocation? :)

author reviewer
#15 lore raw

Re: [PATCH v5 04/11] mm: zswap: add range lookup for large-folio swapin

Quoted 92 lines · Nhat Pham
Quoted 91 lines · Usama Arif
Quoted 53 lines · Yosry Ahmed
Quoted 53 lines
Quoted 14 lines
Quoted 14 lines
(quoted diff) +6 -3
@@ -1595,13 +1611,19 @@ int zswap_load(struct folio *folio)
             return -ENOENT;
 
     /*
-     * Large folios should not be swapped in while zswap is being used, as
-     * they are not properly handled. Zswap does not properly load large
-     * folios, and a large folio may only be partially in zswap.
+     * A large folio reaches zswap_load() only when its whole range is
+     * expected to be on disk: PMD swap-entry consumers split before
+     * calling into PMD-order swapin whenever any slot is still in zswap.
+     * Confirm the range is entirely absent from zswap and return -ENOENT
+     * so the caller reads it from disk; if a slot is unexpectedly still in
+     * zswap, fail the read rather than return partially-initialized data.
      */
Quoted 9 lines

Review int zswap_load(struct folio *folio) · line 1622

Quoted 5 lines
(quoted diff) +2 -3
-    if (WARN_ON_ONCE(folio_test_large(folio))) {
-            folio_unlock(folio);
-            return -EINVAL;
+    if (folio_test_large(folio)) {
+            if (zswap_is_present(swp, folio_nr_pages(folio))) {

Is dropping the warning here intentional (for the folio_test_large() && zswap_is_present() case)?

Yes, so we can end up in a race, which should be handled gracefully.

For example, lets say we have zswap writeback enabled, which means we can end up in a state where we have a PMD swap entry and 511 of the 512 slots have been written to disk, but 1 slot (slot X) is still in zswap.

We can then have the following race:

CPU A: PMD swap-in CPU B: split-PTE swap-in
------------------ ------------------------

Checks swap cache: empty

Faults slot X Adds order-0 folio F zswap_load(F):
removes X from zswap marks F dirty

Checks zswap range: empty
A is preempted

Unmaps/reclaims F zswap_store(F):
puts X back in zswap
Removes F from swap cache

Quoted 8 lines
Quoted 3 lines

A resumes
Allocates large swap-cache folio G
zswap_load(G) finds X in zswap

Why don't we check the zswap range after allocating a folio in the swap cache? I am assuming at this point we have the folio locked and the result should be stable?

Yes that makes sense. The folio is locked and the result will be stable. How about something like below?

mm/swap_state.c +7 -0
index 1f08fb522036..41f168377cb1 100644
@@ -12,6 +12,7 @@
 #include <linux/kernel_stat.h>
 #include <linux/mempolicy.h>
 #include <linux/swap.h>
+#include <linux/zswap.h>
 #include <linux/leafops.h>
 #include <linux/init.h>
 #include <linux/pagemap.h>
@@ -500,6 +501,17 @@ static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci,
        __folio_set_locked(folio);
        __folio_set_swapbacked(folio);
        __swap_cache_do_add_folio(ci, folio, entry);
+       /*
+        * Reject mixed zswap/disk backing before starting the read.
+        */
+       if (order && zswap_is_present(entry, nr_pages)) {
+               __swap_cache_do_del_folio(ci, folio, entry, shadow);
+               spin_unlock(&ci->lock);
Quoted 8 lines

mm/swap_state.c static struct folio *__swap_cache_alloc(struct swap_cluster_info *ci, · line 514

Quoted 5 lines
mm/swap_state.c +5 -0
+               folio_unlock(folio);
+               /* nr_pages refs from swap cache, 1 from allocation */
+               folio_put_refs(folio, nr_pages + 1);
+               return ERR_PTR(-EBUSY);
+       }

If you move it to __swap_cache_add_check(), you can potentially backoff even before the folio allocation? :)

Thanks Nhat! Yes, this looks much much better as well:

@@ -190,6 +191,15 @@ static int __swap_cache_add_check(struct swap_cluster_info *ci,

        if (nr == 1)
                return 0;

+ /*

+        * The cluster lock serializes swap-cache insertion with zswap
+        * writeback. Reject mixed zswap/disk backing before allocating a
+        * large folio and recheck it before adding the folio to swap cache.
+        */

+ if (zswap_is_present(swp_entry(swp_type(targ_entry),
+ round_down(swp_offset(targ_entry), nr)), nr))
+ return -EBUSY;

author reviewer
#16 lore raw

PATCH v5 5/11 mm: swap in PMD swap entries as whole THPs during swapoff

In reply to Usama Arif

Add swap_pmd_cache_lookup() to classify the swap cache behind a PMD swap entry as empty, backed by one PMD-sized folio, or requiring per-page handling because at least one covered slot has a smaller folio in the swap cache. PMD swap entries are handled at PMD granularity only while the covered cache range is empty or backed by a PMD-sized folio; a split cache forces the entry to be split and retried through the PTE path.

Add unuse_pmd() and call it from unuse_pmd_range() to swap in PMD-level swap entries as whole THPs during swapoff. This mirrors the existing unuse_pte_range() but operates at PMD granularity. Preserve soft-dirty, exclusive, and UFFD state when installing the present PMD. If an RWP VMA has a UFFD-marked swap entry, also restore PAGE_NONE so the first subsequent access still generates a userfault.

If the PMD-order folio cannot be allocated or read, the swap cache already contains per-page folios in the covered range (e.g. split in the swap cache by deferred_split_scan() or memory_failure() while the PMD swap entry was installed), the folio is not uptodate, or any subpage is hardware-poisoned, the PMD swap entry is split into PTE-level entries via __split_huge_pmd() and a non-zero error is returned so unuse_pmd_range() falls through to unuse_pte_range(), which handles the individual entries at order-0.

---
 mm/swap.h       |  17 +++++
 mm/swap_state.c |  44 +++++++++++++
 mm/swapfile.c   | 162 ++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 223 insertions(+)
mm/swap.h +17 -0
index 326bbb7ef831..855e793bf17a 100644
@@ -318,6 +318,23 @@ static inline bool folio_matches_swap_entry(const struct folio *folio,
 bool swap_cache_has_folio(swp_entry_t entry);
 struct folio *swap_cache_get_folio(swp_entry_t entry);
 void *swap_cache_get_shadow(swp_entry_t entry);
+enum swap_pmd_cache {
+	SWAP_PMD_CACHE_EMPTY,
+	SWAP_PMD_CACHE_HUGE,
+	SWAP_PMD_CACHE_SPLIT,
+};
+
+#ifdef CONFIG_THP_SWAP
+enum swap_pmd_cache swap_pmd_cache_lookup(swp_entry_t entry,
+					  struct folio **foliop);
+#else
+static inline enum swap_pmd_cache swap_pmd_cache_lookup(swp_entry_t entry,
+							struct folio **foliop)
+{
+	*foliop = NULL;
+	return SWAP_PMD_CACHE_EMPTY;
+}
+#endif
 void swap_cache_del_folio(struct folio *folio);
 struct folio *swap_cache_alloc_folio(swp_entry_t target_entry, gfp_t gfp_mask,
 				     unsigned long orders, struct vm_fault *vmf,
mm/swap_state.c +44 -0

50 lines not on this page · raw message

mm/swapfile.c +162 -0

180 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author reviewer
#17 lore raw

PATCH v5 6/11 mm: handle PMD swap entries in non-present PMD walkers

In reply to Usama Arif

Teach the remaining non-present PMD walkers about swap entries, mirroring the PTE-level equivalents.

smaps_pmd_entry() accounts swap and swap_pss via a new shared smaps_account_swap() helper used by both PTE and PMD paths. For a PMD range, it accounts each covered slot separately because their swap reference counts can differ.

move_soft_dirty_pmd(), clear_soft_dirty_pmd(), and make_uffd_wp_pmd(), pagemap_pmd_range_thp() and change_huge_pmd() handle swap entries alongside migration entries.

hmm_vma_handle_absent_pmd() faults in PMD swap entries via hmm_vma_fault() instead of returning -EFAULT. The first per-page handle_mm_fault() call triggers do_huge_pmd_swap_page(), which maps the entire folio; subsequent calls become harmless huge_pmd_set_accessed() and the walker retries with a present PMD.

madvise_free_huge_pmd() handles PMD swap entries directly: for a full-range MADV_FREE it clears the PMD, frees the deposited page table, and releases the swap slots; for a partial range it splits to PTE swap entries. Without this, MADV_FREE silently becomes a no-op on swapped-out THPs, leaking swap slots.

zap_huge_pmd() frees swap slots via swap_put_entries_direct(), matching zap_nonpresent_ptes().

change_non_present_huge_pmd() skips write-permission changes for swap entries and only updates uffd_wp, matching change_softleaf_pte().

madvise_cold_or_pageout_pte_range() skips PMD swap entries early. MADV_COLD and MADV_PAGEOUT operate on resident folios, so a swapped-out THP has nothing to deactivate or reclaim; skipping also prevents the walker from descending into or splitting the PMD swap entry. The locked THP path also treats a racing PMD swap entry as handled before checking for other non-present PMD types.

mincore_pte_range() routes the pmd_trans_huge_lock() branch through mincore_swap() for non-present PMDs, matching how the PTE path already calls mincore_swap() for non-present PTEs. Without this a swapped-out PMD-mapped THP would be reported as resident, because pmd_is_huge() (and therefore pmd_trans_huge_lock()) accepts any non-present non-none PMD and the old branch unconditionally did memset(vec, 1, nr). mincore_swap() returns 1 for migration / device-private entries (preserving the prior behavior for those) and checks swap-cache residency for swap entries.

queue_folios_pmd() in mempolicy silently skips swap entries, matching the PTE walker which only counts migration entries as failures. Without this, mbind(MPOL_MF_STRICT) would spuriously return -EIO on a swapped-out THP.

check_pmd_state() in khugepaged returns SCAN_PMD_MAPPED for PMD swap entries, treating a swapped-out THP as still being a THP from khugepaged's perspective and matching the existing migration-entry handling.

---
 fs/proc/task_mmu.c | 46 ++++++++++++++++++++++++-------------
 mm/hmm.c           |  3 ++-
 mm/huge_memory.c   | 56 ++++++++++++++++++++++++++++++++++++----------
 mm/khugepaged.c    |  6 +++++
 mm/madvise.c       | 14 +++++++++++-
 mm/mincore.c       | 45 ++++++++++++++++++++++++++++++++++++-
 6 files changed, 139 insertions(+), 31 deletions(-)
fs/proc/task_mmu.c +30 -16
index 817e3e0f9194..77e591f0eec6 100644
@@ -1046,6 +1046,27 @@ static void smaps_pte_hole_lookup(unsigned long addr, struct mm_walk *walk)
 #endif
 }
 
+static void smaps_account_swap(struct mem_size_stats *mss,
+			       softleaf_t entry, unsigned long size)
+{
+	unsigned long nr_pages = size >> PAGE_SHIFT;
+
+	mss->swap += size;
+	do {
+		int mapcount = swp_swapcount(entry);
+
+		if (mapcount >= 2) {
+			u64 pss_delta = (u64)PAGE_SIZE << PSS_SHIFT;
+
+			do_div(pss_delta, mapcount);
+			mss->swap_pss += pss_delta;
+		} else {
+			mss->swap_pss += (u64)PAGE_SIZE << PSS_SHIFT;
+		}
+		entry.val++;
+	} while (--nr_pages);
+}
+
 static void smaps_pte_entry(pte_t *pte, unsigned long addr,
 		struct mm_walk *walk)
 {
@@ -1067,18 +1088,7 @@ static void smaps_pte_entry(pte_t *pte, unsigned long addr,
 		const softleaf_t entry = softleaf_from_pte(ptent);
 
 		if (softleaf_is_swap(entry)) {
-			int mapcount;
-
-			mss->swap += PAGE_SIZE;
-			mapcount = swp_swapcount(entry);
-			if (mapcount >= 2) {
-				u64 pss_delta = (u64)PAGE_SIZE << PSS_SHIFT;
-
-				do_div(pss_delta, mapcount);
-				mss->swap_pss += pss_delta;
-			} else {
-				mss->swap_pss += (u64)PAGE_SIZE << PSS_SHIFT;
-			}
+			smaps_account_swap(mss, entry, PAGE_SIZE);
 		} else if (softleaf_has_pfn(entry)) {
 			if (softleaf_is_device_private(entry))
 				present = true;
@@ -1108,9 +1118,13 @@ static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr,
 	if (pmd_present(*pmd)) {
 		page = vm_normal_page_pmd(vma, addr, *pmd);
 		present = true;
-	} else if (unlikely(thp_migration_supported())) {
+	} else {
 		const softleaf_t entry = softleaf_from_pmd(*pmd);
 
+		if (softleaf_is_swap(entry)) {
+			smaps_account_swap(mss, entry, HPAGE_PMD_SIZE);
+			return;
+		}
 		if (softleaf_has_pfn(entry))
 			page = softleaf_to_page(entry);
 	}
@@ -1755,7 +1769,7 @@ static inline void clear_soft_dirty_pmd(struct vm_area_struct *vma,
 		pmd = pmd_clear_soft_dirty(pmd);
 
 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
-	} else if (pmd_is_migration_entry(pmd)) {
+	} else if (pmd_is_migration_entry(pmd) || pmd_is_swap_entry(pmd)) {
 		pmd = pmd_swp_clear_soft_dirty(pmd);
 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
 	}
@@ -2115,7 +2129,7 @@ static int pagemap_pmd_range_thp(pmd_t *pmdp, unsigned long addr,
 			flags |= PM_UFFD_WP;
 		if (pm->show_pfn)
 			frame = pmd_pfn(pmd) + idx;
-	} else if (thp_migration_supported()) {
+	} else if (pmd_is_valid_softleaf(pmd)) {
 		const softleaf_t entry = softleaf_from_pmd(pmd);
 		unsigned long offset;
 
@@ -2581,7 +2595,7 @@ static void make_uffd_wp_pmd(struct vm_area_struct *vma,
 		old = pmdp_invalidate_ad(vma, addr, pmdp);
 		pmd = pmd_mkuffd(old);
 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
-	} else if (pmd_is_migration_entry(pmd)) {
+	} else if (pmd_is_migration_entry(pmd) || pmd_is_swap_entry(pmd)) {
 		pmd = pmd_swp_mkuffd(pmd);
 		set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
 	}
mm/hmm.c +2 -1
index fc2e1cd0cb22..6da069c0dbfd 100644
@@ -376,7 +376,8 @@ static int hmm_vma_handle_absent_pmd(struct mm_walk *walk, unsigned long start,
 	required_fault = hmm_range_need_fault(hmm_vma_walk, hmm_pfns,
 					      npages, 0);
 	if (required_fault) {
-		if (softleaf_is_device_private(entry))
+		if (softleaf_is_device_private(entry) ||
+		    softleaf_is_swap(entry))
 			return hmm_record_fault(addr, end, required_fault, walk);
 		else
 			return -EFAULT;
mm/huge_memory.c +44 -12

98 lines not on this page · raw message

mm/khugepaged.c +6 -0
index 27e8f3077e80..f9c00f5ef2e3 100644
@@ -1101,6 +1101,12 @@ static inline enum scan_result check_pmd_state(pmd_t *pmd)
 	 */
 	if (pmd_is_migration_entry(pmde))
 		return SCAN_PMD_MAPPED;
+	/*
+	 * A PMD-mapped THP that has been swapped out is still a THP from
+	 * khugepaged's perspective; treat it like a present huge PMD.
+	 */
+	if (pmd_is_swap_entry(pmde))
+		return SCAN_PMD_MAPPED;
 	if (!pmd_present(pmde))
 		return SCAN_NO_PTE_TABLE;
 	if (pmd_trans_huge(pmde))
mm/madvise.c +13 -1
index 07a21ca31bad..81ccdd6a5140 100644
@@ -374,6 +374,15 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 					!can_do_file_pageout(vma);
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
+	/*
+	 * Swapped-out THPs have no resident folio to deactivate or reclaim.
+	 * Avoid descending into or splitting a PMD swap entry.
+	 */
+	if (pmd_is_swap_entry(*pmd)) {
+		walk->action = ACTION_CONTINUE;
+		return 0;
+	}
+
 	if (pmd_trans_huge(*pmd)) {
 		pmd_t orig_pmd;
 		unsigned long next = pmd_addr_end(addr, end);
@@ -384,6 +393,9 @@ static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,
 			return 0;
 
 		orig_pmd = *pmd;
+		if (pmd_is_swap_entry(orig_pmd))
+			goto huge_unlock;
+
 		if (is_huge_zero_pmd(orig_pmd))
 			goto huge_unlock;
 
@@ -665,7 +677,7 @@ static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
 	int nr, max_nr;
 
 	next = pmd_addr_end(addr, end);
-	if (pmd_trans_huge(*pmd))
+	if (pmd_trans_huge(*pmd) || pmd_is_swap_entry(*pmd))
 		if (madvise_free_huge_pmd(tlb, vma, pmd, addr, next))
 			return 0;
 
mm/mincore.c +44 -1

57 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author reviewer
#18 lore raw

PATCH v5 7/11 mm: handle PMD swap entries in MADV_WILLNEED

In reply to Usama Arif

swapin_walk_pmd_entry() walks PTEs and skips non-present PMDs, so MADV_WILLNEED is a no-op on a PMD swap entry.

Handle PMD swap entries under pmd_trans_huge_lock(). If the covered swap-cache range already has a PMD-sized folio, there is nothing left to prefetch. If the range has split cache state, or any covered slot currently has a zswap entry, split the PMD swap entry and ask the walker to retry so the PTE path can handle the individual slots.

Otherwise pin the swap device and read the folio in at PMD order via swapin_sync(BIT(HPAGE_PMD_ORDER)). This keeps the subsequent fault on the do_huge_pmd_swap_page() path and avoids order-0 readahead needlessly splitting the PMD swap entry. If PMD-order swapin races with per-slot swap-cache population after dropping the PMD lock, split and retry through the PTE path instead. If per-page zswap state reappears during the read, remove the failed clean PMD-sized folio from swap cache before splitting so the PTE path can load each slot.

---
 mm/madvise.c | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 87 insertions(+)
mm/madvise.c +87 -0
index 81ccdd6a5140..1d5154b10dfc 100644
@@ -32,6 +32,7 @@
 #include <linux/leafops.h>
 #include <linux/shmem_fs.h>
 #include <linux/mmu_notifier.h>
+#include <linux/zswap.h>
 
 #include <asm/tlb.h>
 
@@ -193,6 +194,91 @@ static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
 	spinlock_t *ptl;
 	unsigned long addr;
 
+	ptl = pmd_trans_huge_lock(pmd, vma);
+	if (ptl) {
+		pmd_t pmdval = *pmd;
+
+		if (pmd_is_swap_entry(pmdval)) {
+			softleaf_t entry = softleaf_from_pmd(pmdval);
+			struct vm_fault vmf = {
+				.vma = vma,
+				.address = start,
+				.real_address = start,
+				.pmd = pmd,
+			};
+			struct swap_info_struct *si;
+			struct folio *folio;
+			enum swap_pmd_cache cache_state;
+			bool split = false;
+
+			cache_state = swap_pmd_cache_lookup(entry, &folio);
+			if (cache_state == SWAP_PMD_CACHE_HUGE) {
+				folio_put(folio);
+				spin_unlock(ptl);
+				goto ret;
+			}
+			if (cache_state == SWAP_PMD_CACHE_SPLIT ||
+			    zswap_is_present(entry, HPAGE_PMD_NR)) {
+				spin_unlock(ptl);
+				__split_huge_pmd(vma, pmd, start, false);
+				walk->action = ACTION_AGAIN;
+				goto ret;
+			}
+
+			/*
+			 * Pin the swap device under the PMD lock so the
+			 * PMD-swap-entry observation keeps the entry valid for
+			 * swapin_sync().
+			 */
+			si = get_swap_device(entry);
+			spin_unlock(ptl);
+			if (!si)
+				goto ret;
+
+			folio = swapin_sync(entry, GFP_HIGHUSER_MOVABLE,
+					    BIT(HPAGE_PMD_ORDER), &vmf,
+					    NULL, 0);
+			/*
+			 * The empty-cache observation was made under the PMD
+			 * lock, but swap cache can change after dropping it. If
+			 * PMD-order swapin lost a race to per-slot cache state,
+			 * retry through the PTE path.
+			 */
+			if (IS_ERR(folio)) {
+				if (PTR_ERR(folio) == -EBUSY)
+					split = true;
+			} else if (folio) {
+				if (folio_nr_pages(folio) != HPAGE_PMD_NR) {
+					split = true;
+				} else if (!folio_test_locked(folio) &&
+					 !folio_test_uptodate(folio) &&
+					 zswap_is_present(entry, HPAGE_PMD_NR)) {
+					folio_lock(folio);
+					/*
+					 * A failed PMD-order zswap load leaves the
+					 * folio clean and not uptodate, but another
+					 * thread can remove it from swap cache before
+					 * we acquire the lock. Revalidate the
+					 * association before deleting it so the PTE
+					 * retry can load the per-page state.
+					 */
+					if (folio_matches_swap_entry(folio, entry))
+						swap_cache_del_folio(folio);
+					folio_unlock(folio);
+					split = true;
+				}
+				folio_put(folio);
+			}
+			put_swap_device(si);
+			if (split) {
+				__split_huge_pmd(vma, pmd, start, false);
+				walk->action = ACTION_AGAIN;
+			}
+			goto ret;
+		}
+		spin_unlock(ptl);
+	}
+
 	for (addr = start; addr < end; addr += PAGE_SIZE) {
 		pte_t pte;
 		softleaf_t entry;
@@ -221,6 +307,7 @@ static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
 	if (ptep)
 		pte_unmap_unlock(ptep, ptl);
 	swap_read_submit(&ctx);
+ret:
 	cond_resched();
 
 	return 0;
Signature · 1 line
2.53.0-Meta
author reviewer
#19 lore raw

PATCH v5 8/11 mm: handle PMD swap entries in UFFDIO_MOVE

In reply to Usama Arif

move_pages_huge_pmd() returned -ENOENT for any non-trans_huge, non-migration PMD, which fails aligned UFFDIO_MOVE on a swapped-out THP -- the PMD swap entry is a perfectly valid mapping that should move whole. Splitting via the move_pages_ptes() fallback isn't a substitute either: __split_huge_pmd_locked() splits a PMD swap entry into HPAGE_PMD_NR PTE swap entries pointing at the same swap-cache folio, but move_swap_pte() refuses any swap-cache folio that is still large and returns -EBUSY.

Add move_swap_pmd(), modeled on move_swap_pte(), that moves the swap entry whole-PMD and re-anchors a PMD-sized swap-cache folio's anon rmap to the destination VMA. Reject !pmd_swp_exclusive() entries with -EBUSY to preserve UFFDIO_MOVE's single-owner semantics, propagate soft-dirty, set the UFFD marker for an RWP-registered destination, and carry the deposited page table across with the entry.

The dispatcher in move_pages_huge_pmd() now waits for migration on a PMD migration entry (matching the PTE path) and routes PMD swap entries through move_swap_pmd() after pinning the swap device and arming an mmu_notifier range so secondary MMUs see the move.

Before moving, classify the whole PMD swap-cache range with swap_pmd_cache_lookup(). A PMD swap entry can be moved whole only if the covered range is empty or backed by one PMD-sized folio. If the range already has per-slot cache state, split the PMD swap entry and return -EAGAIN so the caller retries through the PTE path.

If a PMD-sized folio is cached, lock and revalidate that it still matches the PMD swap entry. If no folio is cached, recheck all HPAGE_PMD_NR slots under both PMD locks before moving the entry; any per-slot folio that appears needs the PTE move path to update its rmap metadata. This avoids moving the PMD while cached folios still point at the old anon_vma/index.

---
 mm/huge_memory.c | 135 ++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 134 insertions(+), 1 deletion(-)
mm/huge_memory.c +134 -1
index eb2a66030438..07c421a16fda 100644
@@ -2865,6 +2865,74 @@ int change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
 #endif
 
 #ifdef CONFIG_USERFAULTFD
+/*
+ * Move a PMD-level swap entry from src_pmd to dst_pmd. Both PMD locks are
+ * acquired here; src_folio (if present) must already be locked. The deposited
+ * page table backing the source THP is moved across with the entry.
+ */
+static int move_swap_pmd(struct mm_struct *mm, struct vm_area_struct *dst_vma,
+			 unsigned long dst_addr, unsigned long src_addr,
+			 pmd_t *dst_pmd, pmd_t *src_pmd,
+			 pmd_t orig_dst_pmd, pmd_t orig_src_pmd,
+			 spinlock_t *dst_ptl, spinlock_t *src_ptl,
+			 struct folio *src_folio, swp_entry_t entry)
+{
+	pgtable_t src_pgtable;
+	pmd_t moved_pmd;
+
+	/*
+	 * The folio may have been freed and reused for a different swap entry
+	 * while it was unlocked. Re-verify the association.
+	 */
+	if (src_folio && unlikely(!folio_matches_swap_entry(src_folio, entry) ||
+				  folio_nr_pages(src_folio) != HPAGE_PMD_NR))
+		return -EAGAIN;
+
+	double_pt_lock(dst_ptl, src_ptl);
+
+	if (!pmd_same(*src_pmd, orig_src_pmd) ||
+	    !pmd_same(*dst_pmd, orig_dst_pmd)) {
+		double_pt_unlock(dst_ptl, src_ptl);
+		return -EAGAIN;
+	}
+
+	/*
+	 * If the folio is in the swap cache, re-anchor its anon rmap to the
+	 * destination VMA so a future swap-in fault at dst_addr finds it.
+	 * Otherwise, re-check the whole PMD swap range: a PMD swap entry is
+	 * only a compact encoding for 512 swap slots, and any per-slot cached
+	 * folio would need the PTE move path to update its rmap metadata.
+	 */
+	if (src_folio) {
+		folio_move_anon_rmap(src_folio, dst_vma);
+		src_folio->index = linear_page_index(dst_vma, dst_addr);
+	} else {
+		unsigned int type = swp_type(entry);
+		pgoff_t offset = swp_offset(entry);
+		int i;
+
+		for (i = 0; i < HPAGE_PMD_NR; i++) {
+			if (swap_cache_has_folio(swp_entry(type, offset + i))) {
+				double_pt_unlock(dst_ptl, src_ptl);
+				return -EAGAIN;
+			}
+		}
+	}
+
+	moved_pmd = pmdp_huge_get_and_clear(mm, src_addr, src_pmd);
+	if (pgtable_supports_soft_dirty())
+		moved_pmd = pmd_swp_mksoft_dirty(moved_pmd);
+	if (userfaultfd_rwp(dst_vma))
+		moved_pmd = pmd_swp_mkuffd(moved_pmd);
+	set_pmd_at(mm, dst_addr, dst_pmd, moved_pmd);
+
+	src_pgtable = pgtable_trans_huge_withdraw(mm, src_pmd);
+	pgtable_trans_huge_deposit(mm, dst_pmd, src_pgtable);
+
+	double_pt_unlock(dst_ptl, src_ptl);
+	return 0;
+}
+
 /*
  * The PT lock for src_pmd and dst_vma/src_vma (for reading) are locked by
  * the caller, but it must return after releasing the page_table_lock.
@@ -2899,11 +2967,76 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 	}
 
 	if (!pmd_trans_huge(src_pmdval)) {
-		spin_unlock(src_ptl);
 		if (pmd_is_migration_entry(src_pmdval)) {
+			spin_unlock(src_ptl);
 			pmd_migration_entry_wait(mm, src_pmd);
 			return -EAGAIN;
 		}
+		if (pmd_is_swap_entry(src_pmdval)) {
+			swp_entry_t entry;
+			struct swap_info_struct *si;
+			enum swap_pmd_cache cache_state;
+
+			/*
+			 * UFFDIO_MOVE on anon mappings requires single-owner
+			 * semantics; refuse to move a shared swap entry.
+			 */
+			if (!pmd_swp_exclusive(src_pmdval)) {
+				spin_unlock(src_ptl);
+				return -EBUSY;
+			}
+
+			entry = softleaf_from_pmd(src_pmdval);
+			spin_unlock(src_ptl);
+
+			/* Pin the swap device against a racing swapoff. */
+			si = get_swap_device(entry);
+			if (unlikely(!si))
+				return -EAGAIN;
+
+			src_folio = NULL;
+			cache_state = swap_pmd_cache_lookup(entry, &src_folio);
+			if (cache_state == SWAP_PMD_CACHE_SPLIT) {
+				put_swap_device(si);
+				__split_huge_pmd(src_vma, src_pmd, src_addr, false);
+				return -EAGAIN;
+			}
+
+			mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0,
+						mm, src_addr,
+						src_addr + HPAGE_PMD_SIZE);
+			mmu_notifier_invalidate_range_start(&range);
+
+			if (src_folio) {
+				folio_lock(src_folio);
+				if (!folio_matches_swap_entry(src_folio, entry) ||
+				    folio_nr_pages(src_folio) != HPAGE_PMD_NR) {
+					err = -EAGAIN;
+					folio_unlock(src_folio);
+					folio_put(src_folio);
+					mmu_notifier_invalidate_range_end(&range);
+					put_swap_device(si);
+					__split_huge_pmd(src_vma, src_pmd,
+							 src_addr, false);
+					return err;
+				}
+			}
+
+			dst_ptl = pmd_lockptr(mm, dst_pmd);
+			err = move_swap_pmd(mm, dst_vma, dst_addr, src_addr,
+					    dst_pmd, src_pmd, dst_pmdval,
+					    src_pmdval, dst_ptl, src_ptl,
+					    src_folio, entry);
+
+			mmu_notifier_invalidate_range_end(&range);
+			if (src_folio) {
+				folio_unlock(src_folio);
+				folio_put(src_folio);
+			}
+			put_swap_device(si);
+			return err;
+		}
+		spin_unlock(src_ptl);
 		return -ENOENT;
 	}
 
Signature · 1 line
2.53.0-Meta
author reviewer
#20 lore raw

PATCH v5 9/11 mm: handle PMD swap entry faults on swap-in

In reply to Usama Arif

Add do_huge_pmd_swap_page() and dispatch to it from __handle_mm_fault() when vmf->orig_pmd encodes a swap entry. The handler resolves the entire 2 MB mapping in one shot, mirroring do_swap_page() (PTE path) at PMD granularity:

- Look up the folio in the swap cache; on a miss, allocate a PMD-order folio via swapin_sync(BIT(HPAGE_PMD_ORDER)) and read from swap. This deliberately skips the existing order-0 swap readahead paths: the fault already asks for the whole PMD range, while order-0 readahead would populate per-page swap cache state and force the PMD swap entry to split. If the range already has per-page swap-cache or zswap state, split and retry through PTEs.

- After locking, re-validate that the folio still corresponds to our entry and is still PMD-sized. Between the unlocked cache lookup and the lock, a racing swap-in on the same entry may have removed it from the cache via folio_free_swap(), or reclaim / memory_failure / deferred-split may have split the folio into smaller folios.

- Refuse to map a folio that contains a hardware-poisoned subpage. On a hit, split the PMD swap entry so do_swap_page() can return VM_FAULT_HWPOISON per subpage, matching the PTE swap-in PageHWPoison check. Disable large-folio PTE batching for such a folio so the fallback cannot map the poisoned subpage as part of a batch.

- Restore soft_dirty and uffd_wp from the swap PMD. For an RWP VMA, also restore PAGE_NONE so the next access reaches userfaultfd. Map writable only when the entry was exclusive, the VMA permits writes, and uffd-wp is not armed. Drop the exclusive marker when the cached folio is under writeback to an SWP_STABLE_WRITES backend (zram) so the PMD is mapped read-only; a later write COWs into a fresh folio rather than corrupting the in-flight writeback. Mirrors do_swap_page().

- When the resulting PMD is read-only but the fault was a write, update vmf->orig_pmd and call wp_huge_pmd() in the same handler to COW immediately rather than forcing a second fault. Leave an RWP-restored PMD for userfaultfd instead. Mask VM_FAULT_FALLBACK from the return: a PMD-COW that splits to PTE-level is normal, but the bit is part of VM_FAULT_ERROR and arch fault handlers BUG() on it without SIGBUS/HWPOISON/SIGSEGV.

- Free the swap slot via should_try_to_free_swap() (hoisted from mm/memory.c into mm/internal.h so PTE- and PMD-level swap-in share the heuristic). Preserve FAULT_FLAG_WRITE until this check so an exclusive write fault can release its swap slot.

When PMD-order resources are unavailable (folio allocation fails, the cached folio was split, memcg charge fails, or swap-cache insertion races) split the PMD swap entry into 512 PTE swap entries via __split_huge_pmd() and return 0. The fault retries and do_swap_page() takes over per-PTE. This avoids returning VM_FAULT_OOM for transient PMD-order allocation failures.

---
 include/linux/huge_mm.h |  14 +++
 mm/huge_memory.c        | 227 ++++++++++++++++++++++++++++++++++++++++
 mm/internal.h           |  34 ++++++
 mm/memory.c             |  41 ++------
 4 files changed, 281 insertions(+), 35 deletions(-)
include/linux/huge_mm.h +14 -0
index c745f7ad2298..e7107e0991ad 100644
@@ -552,6 +552,15 @@ vm_fault_t do_huge_pmd_uffd_rwp(struct vm_fault *vmf);
 
 vm_fault_t do_huge_pmd_device_private(struct vm_fault *vmf);
 
+#ifdef CONFIG_THP_SWAP
+vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf);
+#else
+static inline vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf)
+{
+	return 0;
+}
+#endif
+
 extern struct folio *huge_zero_folio;
 extern unsigned long huge_zero_pfn;
 
@@ -754,6 +763,11 @@ static inline vm_fault_t do_huge_pmd_device_private(struct vm_fault *vmf)
 	return 0;
 }
 
+static inline vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf)
+{
+	return 0;
+}
+
 static inline bool is_huge_zero_folio(const struct folio *folio)
 {
 	return false;
mm/huge_memory.c +227 -0

239 lines not on this page · raw message

mm/internal.h +34 -0
index 51ee4c131090..b303b5d6162e 100644
@@ -581,6 +581,40 @@ static inline vm_fault_t vmf_anon_prepare(struct vm_fault *vmf)
 }
 
 vm_fault_t do_swap_page(struct vm_fault *vmf);
+vm_fault_t wp_huge_pmd(struct vm_fault *vmf);
+
+/*
+ * Check if we should call folio_free_swap to free the swap cache.
+ * folio_free_swap only frees the swap cache to release the slot if swap
+ * count is zero, so we don't need to check the swap count here.
+ */
+static inline bool should_try_to_free_swap(struct swap_info_struct *si,
+					   struct folio *folio,
+					   struct vm_area_struct *vma,
+					   bool exclusive,
+					   unsigned int fault_flags)
+{
+	if (!folio_test_swapcache(folio))
+		return false;
+	/*
+	 * Always try to free swap cache for SWP_SYNCHRONOUS_IO devices. Swap
+	 * cache can help save some IO or memory overhead, but these devices
+	 * are fast, and meanwhile, swap cache pinning the slot deferring the
+	 * release of metadata or fragmentation is a more critical issue.
+	 */
+	if (data_race(si->flags & SWP_SYNCHRONOUS_IO))
+		return true;
+	if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
+	    folio_test_mlocked(folio))
+		return true;
+
+	/*
+	 * Free the swapcache only if we are the exclusive user and
+	 * this is a write fault.
+	 */
+	return (fault_flags & FAULT_FLAG_WRITE) && exclusive;
+}
+
 void folio_rotate_reclaimable(struct folio *folio);
 bool __folio_end_writeback(struct folio *folio);
 void deactivate_file_folio(struct folio *folio);
mm/memory.c +6 -35

65 lines not on this page · raw message

Signature · 1 line
2.53.0-Meta
author reviewer
#21 lore raw

PATCH v5 10/11 mm: install PMD swap entries on swap-out

In reply to Usama Arif

Reclaim today splits a PMD-mapped anonymous THP into 512 PTE swap entries before unmap, losing the huge mapping across the swap round-trip and forcing khugepaged to rebuild it later. The contiguous swap range was already secured when the folio was added to the swap cache (a non-contiguous allocation would have split the folio earlier), so the PMD can be replaced by a single PMD-level swap entry instead.

This patch mirrors the existing PTE swap-out path at PMD granularity:
- shrink_folio_list() drops TTU_SPLIT_HUGE_PMD for PMD-mappable swapcache folios. zswap is handled by the PMD swap-in users: if any covered slot currently has a zswap entry, they split the PMD swap entry and fall back to the per-PTE path.
- try_to_unmap_one() now has a PMD branch that calls set_pmd_swap_entry() and adjusts MM_ANONPAGES / MM_SWAPENTS by HPAGE_PMD_NR before walk_done. TTU_SPLIT_HUGE_PMD remains the fallback.
- set_pmd_swap_entry() is the installer. Mirroring the PTE swap-out sequence at PMD granularity, it clears the present mapping (keeping the original for rollback), bumps the swap_map refcount for the folio's 512 slots, transfers the exclusive state in the swap entry, propagates the dirty bit to the folio so writeback is not lost, and installs a swap PMD that preserves the original soft-dirty / uffd-wp / exclusive bits. Any failing step rolls back the present mapping.

The swap entry value matches what 512 PTE swap entries would encode, so swap_map refcounting is unchanged: each of the 512 slots carries a count of 1, released individually on later split or together on swap-in.

Add thp_swpout_pmd to count each PMD mapping replaced by a PMD-level swap entry. Unlike the folio-level thp_swpout counter, a fork-shared THP can increment this counter once for each mapping; document that distinction.

---
 Documentation/admin-guide/mm/transhuge.rst |  5 ++
 include/linux/huge_mm.h                    |  2 +
 include/linux/vm_event_item.h              |  1 +
 mm/huge_memory.c                           | 80 ++++++++++++++++++++++
 mm/rmap.c                                  | 19 +++++
 mm/vmscan.c                                |  9 ++-
 mm/vmstat.c                                |  1 +
 7 files changed, 116 insertions(+), 1 deletion(-)
Documentation/admin-guide/mm/transhuge.rst +5 -0
index 16f37135ed80..b421d7982db6 100644
@@ -630,6 +630,11 @@ thp_swpout
 	is incremented every time a huge page is swapout in one
 	piece without splitting.
 
+thp_swpout_pmd
+	is incremented every time a PMD mapping is replaced by a PMD-level
+	swap entry. A fork-shared THP can increment this counter once for each
+	PMD mapping that is swapped out.
+
 thp_swpout_fallback
 	is incremented if a huge page has to be split before swapout.
 	Usually because failed to allocate some continuous swap space
include/linux/huge_mm.h +2 -0
index e7107e0991ad..41cf643a3f55 100644
@@ -554,6 +554,8 @@ vm_fault_t do_huge_pmd_device_private(struct vm_fault *vmf);
 
 #ifdef CONFIG_THP_SWAP
 vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf);
+int set_pmd_swap_entry(struct page_vma_mapped_walk *pvmw,
+		       struct folio *folio);
 #else
 static inline vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf)
 {
include/linux/vm_event_item.h +1 -0
index 2628ccda076a..f8fd4e13698c 100644
@@ -108,6 +108,7 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,
 		THP_ZERO_PAGE_ALLOC_FAILED,
 		THP_SWPOUT,
 		THP_SWPOUT_FALLBACK,
+		THP_SWPOUT_PMD,
 #endif
 #ifdef CONFIG_BALLOON
 		BALLOON_INFLATE,
mm/huge_memory.c +80 -0

83 lines not on this page · raw message

mm/rmap.c +19 -0
index b7ead3e9f064..4574f7b969b6 100644
@@ -2282,6 +2282,25 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 				goto walk_abort;
 			}
 
+#ifdef CONFIG_THP_SWAP
+			/*
+			 * If the folio is in the swap cache and we're not
+			 * asked to split, install a PMD-level swap entry.
+			 */
+			if (!(flags & TTU_SPLIT_HUGE_PMD) &&
+			    folio_test_anon(folio) &&
+			    folio_test_swapcache(folio)) {
+				if (set_pmd_swap_entry(&pvmw, folio))
+					goto walk_abort;
+
+				add_mm_counter(mm, MM_ANONPAGES,
+					       -HPAGE_PMD_NR);
+				add_mm_counter(mm, MM_SWAPENTS,
+					       HPAGE_PMD_NR);
+				goto walk_done;
+			}
+#endif
+
 			if (flags & TTU_SPLIT_HUGE_PMD) {
 				/*
 				 * We temporarily have to drop the PTL and
mm/vmscan.c +8 -1
index 9b8ee902f972..83bb34403e42 100644
@@ -1333,7 +1333,14 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 			enum ttu_flags flags = TTU_BATCH_FLUSH;
 			bool was_swapbacked = folio_test_swapbacked(folio);
 
-			if (folio_test_pmd_mappable(folio))
+			/*
+			 * With THP_SWAP, PMD-mappable folios already in the
+			 * swap cache can be unmapped with a PMD-level swap
+			 * entry, avoiding the cost of splitting the PMD.
+			 */
+			if (folio_test_pmd_mappable(folio) &&
+			    !(IS_ENABLED(CONFIG_THP_SWAP) &&
+			      folio_test_swapcache(folio)))
 				flags |= TTU_SPLIT_HUGE_PMD;
 			/*
 			 * Without TTU_SYNC, try_to_unmap will only begin to
mm/vmstat.c +1 -0
index 4e26e5fd6666..68e6efc0dabd 100644
@@ -1422,6 +1422,7 @@ const char * const vmstat_text[] = {
 	[I(THP_ZERO_PAGE_ALLOC_FAILED)]		= "thp_zero_page_alloc_failed",
 	[I(THP_SWPOUT)]				= "thp_swpout",
 	[I(THP_SWPOUT_FALLBACK)]		= "thp_swpout_fallback",
+	[I(THP_SWPOUT_PMD)]			= "thp_swpout_pmd",
 #endif
 #ifdef CONFIG_BALLOON
 	[I(BALLOON_INFLATE)]			= "balloon_inflate",
Signature · 1 line
2.53.0-Meta
maintainer
#22 lore raw

Re: [PATCH v5 10/11] mm: install PMD swap entries on swap-out

Quoted 17 lines · Usama Arif

+++ b/mm/rmap.c

mm/rmap.c +12 -0
@@ -2282,6 +2282,25 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 				goto walk_abort;
 			}
 
+#ifdef CONFIG_THP_SWAP
+			/*
+			 * If the folio is in the swap cache and we're not
+			 * asked to split, install a PMD-level swap entry.
+			 */
+			if (!(flags & TTU_SPLIT_HUGE_PMD) &&
+			    folio_test_anon(folio) &&
+			    folio_test_swapcache(folio)) {
+				if (set_pmd_swap_entry(&pvmw, folio))
+					goto walk_abort;
+
+				add_mm_counter(mm, MM_ANONPAGES,

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

Quoted 10 lines
mm/rmap.c +7 -0
+					       -HPAGE_PMD_NR);
+				add_mm_counter(mm, MM_SWAPENTS,
+					       HPAGE_PMD_NR);
+				goto walk_done;
+			}
+#endif
+
 			if (flags & TTU_SPLIT_HUGE_PMD) {
 				/*
 				 * We temporarily have to drop the PTL and

This makes me sad. It feels like we're bolting more complexity onto try_to_unmap() instead of removing TTU_SPLIT_HUGE_PMD entirely.

Ideally we'd just cope with folios of whatever size (including PMD and PUD mapped folios) and only handle hugetlb weirdness when we absolutely have to. Similarly, we could split PUDs to PMDs and PMDs to PTEs when we need to, without the caller specifying TTU_SPLIT_anything.

Is there a reason we can't do that?

author reviewer
#23 lore raw

Re: [PATCH v5 10/11] mm: install PMD swap entries on swap-out

Quoted 32 lines · Matthew Wilcox
Quoted 17 lines · Usama Arif

+++ b/mm/rmap.c

mm/rmap.c +12 -0
@@ -2282,6 +2282,25 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 				goto walk_abort;
 			}
 
+#ifdef CONFIG_THP_SWAP
+			/*
+			 * If the folio is in the swap cache and we're not
+			 * asked to split, install a PMD-level swap entry.
+			 */
+			if (!(flags & TTU_SPLIT_HUGE_PMD) &&
+			    folio_test_anon(folio) &&
+			    folio_test_swapcache(folio)) {
+				if (set_pmd_swap_entry(&pvmw, folio))
+					goto walk_abort;
+
+				add_mm_counter(mm, MM_ANONPAGES,

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

Quoted 10 lines
mm/rmap.c +7 -0
+					       -HPAGE_PMD_NR);
+				add_mm_counter(mm, MM_SWAPENTS,
+					       HPAGE_PMD_NR);
+				goto walk_done;
+			}
+#endif
+
 			if (flags & TTU_SPLIT_HUGE_PMD) {
 				/*
 				 * We temporarily have to drop the PTL and

This makes me sad. It feels like we're bolting more complexity onto try_to_unmap() instead of removing TTU_SPLIT_HUGE_PMD entirely.

Quoted 7 lines

Ideally we'd just cope with folios of whatever size (including PMD and PUD mapped folios) and only handle hugetlb weirdness when we absolutely have to. Similarly, we could split PUDs to PMDs and PMDs to PTEs when we need to, without the caller specifying TTU_SPLIT_anything.

Is there a reason we can't do that?

I will prototype what the code would look like without TTU_SPLIT_HUGE_PMD and get back to you on this. Looking at the code right now, I feel like I would be shifting complexity, but let me try and do something about this.

author reviewer
#24 lore raw

Re: [PATCH v5 10/11] mm: install PMD swap entries on swap-out

In reply to Matthew Wilcox
Quoted 32 lines · Matthew Wilcox
Quoted 17 lines · Usama Arif

+++ b/mm/rmap.c

(quoted diff) +12 -0
@@ -2282,6 +2282,25 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
 				goto walk_abort;
 			}
 
+#ifdef CONFIG_THP_SWAP
+			/*
+			 * If the folio is in the swap cache and we're not
+			 * asked to split, install a PMD-level swap entry.
+			 */
+			if (!(flags & TTU_SPLIT_HUGE_PMD) &&
+			    folio_test_anon(folio) &&
+			    folio_test_swapcache(folio)) {
+				if (set_pmd_swap_entry(&pvmw, folio))
+					goto walk_abort;
+
+				add_mm_counter(mm, MM_ANONPAGES,

Review static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma, · line 2306

Quoted 10 lines
(quoted diff) +7 -0
+					       -HPAGE_PMD_NR);
+				add_mm_counter(mm, MM_SWAPENTS,
+					       HPAGE_PMD_NR);
+				goto walk_done;
+			}
+#endif
+
 			if (flags & TTU_SPLIT_HUGE_PMD) {
 				/*
 				 * We temporarily have to drop the PTL and

This makes me sad. It feels like we're bolting more complexity onto try_to_unmap() instead of removing TTU_SPLIT_HUGE_PMD entirely.

Quoted 7 lines

Ideally we'd just cope with folios of whatever size (including PMD and PUD mapped folios) and only handle hugetlb weirdness when we absolutely have to. Similarly, we could split PUDs to PMDs and PMDs to PTEs when we need to, without the caller specifying TTU_SPLIT_anything.

Is there a reason we can't do that?

Hi Matthew,

So I have been looking into this over the past few days, and I can't come up with a way to do this without having another rmap walk, which is expensive.

I tried to prototype this (code at the end of the series).
Removing the flag required an additional rmap walk (split_folio_pmd_mappings below), MMU notifier handling and different fallback behavior on architectures without PMD softleaf support (see #ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES below). It makes the code more complicated and expensive.

It also changes the behavior of every try_to_unmap() and try_to_migrate() caller, while this series only needs reclaim to preserve a PMD when it can install a PMD swap entry. I would therefore prefer to keep this series scoped to PMD swap entries and handle removal of TTU_SPLIT_HUGE_PMD independently with the broader rmap, migration, architecture, and THP-splitting review and testing it requires.

Untested prototype below:

include/linux/rmap.h +0 -1
index a174758f7777..0e0172c0c852 100644
@@ -93,7 +93,6 @@ struct anon_vma_chain {
 
 enum ttu_flags {
 	TTU_USE_SHARED_ZEROPAGE	= 0x2,	/* for unused pages of large folios */
-	TTU_SPLIT_HUGE_PMD	= 0x4,	/* split huge PMD if any */
 	TTU_IGNORE_MLOCK	= 0x8,	/* ignore mlock */
 	TTU_SYNC		= 0x10,	/* avoid racy checks with PVMW_SYNC */
 	TTU_HWPOISON		= 0x20,	/* do convert pte to hwpoison entry */
mm/huge_memory.c +37 -5

61 lines not on this page · raw message

mm/rmap.c +17 -31

83 lines not on this page · raw message

mm/truncate.c +0 -1
index b58ba940be47..12e1fea5cf50 100644
@@ -182,7 +182,6 @@ static int folio_split_or_unmap(struct folio *folio, struct page *split_at,
 {
 	enum ttu_flags ttu_flags =
 		TTU_SYNC |
-		TTU_SPLIT_HUGE_PMD |
 		TTU_IGNORE_MLOCK;
 	int ret;
 
mm/vmscan.c +0 -2
index 9b8ee902f972..90751b384a5d 100644
@@ -1333,8 +1333,6 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
 			enum ttu_flags flags = TTU_BATCH_FLUSH;
 			bool was_swapbacked = folio_test_swapbacked(folio);
 
-			if (folio_test_pmd_mappable(folio))
-				flags |= TTU_SPLIT_HUGE_PMD;
 			/*
 			 * Without TTU_SYNC, try_to_unmap will only begin to
 			 * hold PTL from the first present PTE within a large
Signature · 1 line
2.53.0-Meta
#25 lore raw

Re: [PATCH v5 10/11] mm: install PMD swap entries on swap-out

In reply to Usama Arif
Quoted 112 lines · Usama Arif

Reclaim today splits a PMD-mapped anonymous THP into 512 PTE swap entries before unmap, losing the huge mapping across the swap round-trip and forcing khugepaged to rebuild it later. The contiguous swap range was already secured when the folio was added to the swap cache (a non-contiguous allocation would have split the folio earlier), so the PMD can be replaced by a single PMD-level swap entry instead.

This patch mirrors the existing PTE swap-out path at PMD granularity:
- shrink_folio_list() drops TTU_SPLIT_HUGE_PMD for PMD-mappable swapcache folios. zswap is handled by the PMD swap-in users: if any covered slot currently has a zswap entry, they split the PMD swap entry and fall back to the per-PTE path.
- try_to_unmap_one() now has a PMD branch that calls set_pmd_swap_entry() and adjusts MM_ANONPAGES / MM_SWAPENTS by HPAGE_PMD_NR before walk_done. TTU_SPLIT_HUGE_PMD remains the fallback.
- set_pmd_swap_entry() is the installer. Mirroring the PTE swap-out sequence at PMD granularity, it clears the present mapping (keeping the original for rollback), bumps the swap_map refcount for the folio's 512 slots, transfers the exclusive state in the swap entry, propagates the dirty bit to the folio so writeback is not lost, and installs a swap PMD that preserves the original soft-dirty / uffd-wp / exclusive bits. Any failing step rolls back the present mapping.

The swap entry value matches what 512 PTE swap entries would encode, so swap_map refcounting is unchanged: each of the 512 slots carries a count of 1, released individually on later split or together on swap-in.

Add thp_swpout_pmd to count each PMD mapping replaced by a PMD-level swap entry. Unlike the folio-level thp_swpout counter, a fork-shared THP can increment this counter once for each mapping; document that distinction.

---
  Documentation/admin-guide/mm/transhuge.rst |  5 ++
  include/linux/huge_mm.h                    |  2 +
  include/linux/vm_event_item.h              |  1 +
  mm/huge_memory.c                           | 80 ++++++++++++++++++++++
  mm/rmap.c                                  | 19 +++++
  mm/vmscan.c                                |  9 ++-
  mm/vmstat.c                                |  1 +
  7 files changed, 116 insertions(+), 1 deletion(-)
Documentation/admin-guide/mm/transhuge.rst +5 -0
index 16f37135ed80..b421d7982db6 100644
@@ -630,6 +630,11 @@ thp_swpout
  	is incremented every time a huge page is swapout in one
  	piece without splitting.
 
+thp_swpout_pmd
+	is incremented every time a PMD mapping is replaced by a PMD-level
+	swap entry. A fork-shared THP can increment this counter once for each
+	PMD mapping that is swapped out.
+
  thp_swpout_fallback
  	is incremented if a huge page has to be split before swapout.
  	Usually because failed to allocate some continuous swap space
include/linux/huge_mm.h +2 -0
index e7107e0991ad..41cf643a3f55 100644
@@ -554,6 +554,8 @@ vm_fault_t do_huge_pmd_device_private(struct vm_fault *vmf);
 
  #ifdef CONFIG_THP_SWAP
  vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf);
+int set_pmd_swap_entry(struct page_vma_mapped_walk *pvmw,
+		       struct folio *folio);
  #else
  static inline vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf)
  {
include/linux/vm_event_item.h +1 -0
index 2628ccda076a..f8fd4e13698c 100644
@@ -108,6 +108,7 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,
  		THP_ZERO_PAGE_ALLOC_FAILED,
  		THP_SWPOUT,
  		THP_SWPOUT_FALLBACK,
+		THP_SWPOUT_PMD,
  #endif
  #ifdef CONFIG_BALLOON
  		BALLOON_INFLATE,
mm/huge_memory.c +18 -0
index 6ef56936ced4..c014631e5a26 100644
@@ -5561,3 +5561,83 @@ void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
  	trace_remove_migration_pmd(address, pmd_val(pmde));
  }
  #endif
+
+#ifdef CONFIG_THP_SWAP
+/**
+ * set_pmd_swap_entry() - Replace a PMD mapping with a PMD-level swap entry.
+ * @pvmw: Page vma mapped walk context, must have pvmw->pmd set and
+ *        pvmw->pte NULL (i.e. PMD-mapped).
+ * @folio: The folio being swapped out. Must be in the swap cache.
+ *
+ * This installs a PMD-level swap entry in place of a present PMD mapping,
+ * avoiding the need to split the PMD into PTE-level swap entries.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int set_pmd_swap_entry(struct page_vma_mapped_walk *pvmw,
+		       struct folio *folio)
+{
+	struct vm_area_struct *vma = pvmw->vma;
+	struct mm_struct *mm = vma->vm_mm;

mm/huge_memory.c void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new) · line 5591

Quoted 10 lines
mm/huge_memory.c +10 -0
+	unsigned long address = pvmw->address;
+	unsigned long haddr = address & HPAGE_PMD_MASK;
+	struct page *page = folio_page(folio, 0);
+	bool anon_exclusive;
+	pmd_t pmdval;
+	swp_entry_t entry;
+	pmd_t pmdswp;
+
+	if (!(pvmw->pmd && !pvmw->pte))
+		return 0;

Should we call VM_WARN_ON_ONCE() and return an error instead? This function is only called by try_to_unmap_one() under this condition. In addition, returning zero would cause try_to_unmap_one() to assume that the PMD swap entry was installed, which is not the case.

Quoted 114 lines
mm/huge_memory.c +52 -0
+
+	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio);
+	VM_BUG_ON_FOLIO(!folio_test_anon(folio), folio);
+
+	if (unlikely(folio_test_swapbacked(folio) !=
+			folio_test_swapcache(folio))) {
+		WARN_ON_ONCE(1);
+		return -EBUSY;
+	}
+
+	flush_cache_range(vma, haddr, haddr + HPAGE_PMD_SIZE);
+
+	pmdval = pmdp_invalidate(vma, haddr, pvmw->pmd);
+
+	/* Update high watermark before we lower rss */
+	update_hiwater_rss(mm);
+
+	if (folio_dup_swap(folio, NULL) < 0) {
+		set_pmd_at(mm, haddr, pvmw->pmd, pmdval);
+		return -ENOMEM;
+	}
+
+	/* See folio_try_share_anon_rmap_pmd(): invalidate PMD first. */
+	anon_exclusive = PageAnonExclusive(page);
+	if (anon_exclusive && folio_try_share_anon_rmap_pmd(folio, page)) {
+		folio_put_swap(folio, NULL);
+		set_pmd_at(mm, haddr, pvmw->pmd, pmdval);
+		return -EBUSY;
+	}
+
+	mm_prepare_for_swap_entries(mm);
+
+	if (pmd_dirty(pmdval))
+		folio_mark_dirty(folio);
+
+	entry = folio->swap;
+	pmdswp = softleaf_to_pmd(entry);
+	if (pmd_soft_dirty(pmdval))
+		pmdswp = pmd_swp_mksoft_dirty(pmdswp);
+	if (pmd_uffd(pmdval))
+		pmdswp = pmd_swp_mkuffd(pmdswp);
+	if (anon_exclusive)
+		pmdswp = pmd_swp_mkexclusive(pmdswp);
+	set_pmd_at(mm, haddr, pvmw->pmd, pmdswp);
+
+	folio_remove_rmap_pmd(folio, page, vma);
+	folio_put(folio);
+
+	count_vm_event(THP_SWPOUT_PMD);
+	return 0;
+}
+#endif /* CONFIG_THP_SWAP */
mm/rmap.c +19 -0
index b7ead3e9f064..4574f7b969b6 100644
@@ -2282,6 +2282,25 @@ static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
  				goto walk_abort;
  			}
 
+#ifdef CONFIG_THP_SWAP
+			/*
+			 * If the folio is in the swap cache and we're not
+			 * asked to split, install a PMD-level swap entry.
+			 */
+			if (!(flags & TTU_SPLIT_HUGE_PMD) &&
+			    folio_test_anon(folio) &&
+			    folio_test_swapcache(folio)) {
+				if (set_pmd_swap_entry(&pvmw, folio))
+					goto walk_abort;
+
+				add_mm_counter(mm, MM_ANONPAGES,
+					       -HPAGE_PMD_NR);
+				add_mm_counter(mm, MM_SWAPENTS,
+					       HPAGE_PMD_NR);
+				goto walk_done;
+			}
+#endif
+
  			if (flags & TTU_SPLIT_HUGE_PMD) {
  				/*
  				 * We temporarily have to drop the PTL and
mm/vmscan.c +8 -1
index 9b8ee902f972..83bb34403e42 100644
@@ -1333,7 +1333,14 @@ static unsigned int shrink_folio_list(struct list_head *folio_list,
  			enum ttu_flags flags = TTU_BATCH_FLUSH;
  			bool was_swapbacked = folio_test_swapbacked(folio);
 
-			if (folio_test_pmd_mappable(folio))
+			/*
+			 * With THP_SWAP, PMD-mappable folios already in the
+			 * swap cache can be unmapped with a PMD-level swap
+			 * entry, avoiding the cost of splitting the PMD.
+			 */
+			if (folio_test_pmd_mappable(folio) &&
+			    !(IS_ENABLED(CONFIG_THP_SWAP) &&
+			      folio_test_swapcache(folio)))
  				flags |= TTU_SPLIT_HUGE_PMD;
  			/*
  			 * Without TTU_SYNC, try_to_unmap will only begin to
mm/vmstat.c +1 -0
index 4e26e5fd6666..68e6efc0dabd 100644
@@ -1422,6 +1422,7 @@ const char * const vmstat_text[] = {
  	[I(THP_ZERO_PAGE_ALLOC_FAILED)]		= "thp_zero_page_alloc_failed",
  	[I(THP_SWPOUT)]				= "thp_swpout",
  	[I(THP_SWPOUT_FALLBACK)]		= "thp_swpout_fallback",
+	[I(THP_SWPOUT_PMD)]			= "thp_swpout_pmd",
  #endif
  #ifdef CONFIG_BALLOON
  	[I(BALLOON_INFLATE)]			= "balloon_inflate",
author reviewer
#26 lore raw

Re: [PATCH v5 10/11] mm: install PMD swap entries on swap-out

Quoted 118 lines · Luiz Capitulino
Quoted 117 lines · Usama Arif

Reclaim today splits a PMD-mapped anonymous THP into 512 PTE swap entries before unmap, losing the huge mapping across the swap round-trip and forcing khugepaged to rebuild it later. The contiguous swap range was already secured when the folio was added to the swap cache (a non-contiguous allocation would have split the folio earlier), so the PMD can be replaced by a single PMD-level swap entry instead.

This patch mirrors the existing PTE swap-out path at PMD granularity:
- shrink_folio_list() drops TTU_SPLIT_HUGE_PMD for PMD-mappable swapcache folios. zswap is handled by the PMD swap-in users: if any covered slot currently has a zswap entry, they split the PMD swap entry and fall back to the per-PTE path.
- try_to_unmap_one() now has a PMD branch that calls set_pmd_swap_entry() and adjusts MM_ANONPAGES / MM_SWAPENTS by HPAGE_PMD_NR before walk_done. TTU_SPLIT_HUGE_PMD remains the fallback.
- set_pmd_swap_entry() is the installer. Mirroring the PTE swap-out sequence at PMD granularity, it clears the present mapping (keeping the original for rollback), bumps the swap_map refcount for the folio's 512 slots, transfers the exclusive state in the swap entry, propagates the dirty bit to the folio so writeback is not lost, and installs a swap PMD that preserves the original soft-dirty / uffd-wp / exclusive bits. Any failing step rolls back the present mapping.

The swap entry value matches what 512 PTE swap entries would encode, so swap_map refcounting is unchanged: each of the 512 slots carries a count of 1, released individually on later split or together on swap-in.

Add thp_swpout_pmd to count each PMD mapping replaced by a PMD-level swap entry. Unlike the folio-level thp_swpout counter, a fork-shared THP can increment this counter once for each mapping; document that distinction.

---
  Documentation/admin-guide/mm/transhuge.rst |  5 ++ include/linux/huge_mm.h                    |  2 + include/linux/vm_event_item.h              |  1 + mm/huge_memory.c                           | 80 ++++++++++++++++++++++ mm/rmap.c                                  | 19 +++++ mm/vmscan.c                                |  9 ++- mm/vmstat.c                                |  1 +

  7 files changed, 116 insertions(+), 1 deletion(-)
Documentation/admin-guide/mm/transhuge.rst +0 -0
index 16f37135ed80..b421d7982db6 100644
@@ -630,6 +630,11 @@ thp_swpout

      is incremented every time a huge page is swapout in one piece without splitting.
  +thp_swpout_pmd
+    is incremented every time a PMD mapping is replaced by a PMD-level +    swap entry. A fork-shared THP can increment this counter once for each +    PMD mapping that is swapped out.
+
  thp_swpout_fallback
      is incremented if a huge page has to be split before swapout. Usually because failed to allocate some continuous swap space

include/linux/huge_mm.h +2 -0
index e7107e0991ad..41cf643a3f55 100644
@@ -554,6 +554,8 @@ vm_fault_t do_huge_pmd_device_private(struct vm_fault *vmf);
     #ifdef CONFIG_THP_SWAP
   vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf);
+int set_pmd_swap_entry(struct page_vma_mapped_walk *pvmw,
+               struct folio *folio);
   #else
   static inline vm_fault_t do_huge_pmd_swap_page(struct vm_fault *vmf)
   {
include/linux/vm_event_item.h +1 -0
index 2628ccda076a..f8fd4e13698c 100644
@@ -108,6 +108,7 @@ enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,
           THP_ZERO_PAGE_ALLOC_FAILED,
           THP_SWPOUT,
           THP_SWPOUT_FALLBACK,
+        THP_SWPOUT_PMD,
   #endif
   #ifdef CONFIG_BALLOON
           BALLOON_INFLATE,
mm/huge_memory.c +25 -0
index 6ef56936ced4..c014631e5a26 100644
@@ -5561,3 +5561,83 @@ void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
       trace_remove_migration_pmd(address, pmd_val(pmde));
   }
   #endif
+
+#ifdef CONFIG_THP_SWAP
+/**
+ * set_pmd_swap_entry() - Replace a PMD mapping with a PMD-level swap entry.
+ * @pvmw: Page vma mapped walk context, must have pvmw->pmd set and
+ *        pvmw->pte NULL (i.e. PMD-mapped).
+ * @folio: The folio being swapped out. Must be in the swap cache.
+ *
+ * This installs a PMD-level swap entry in place of a present PMD mapping,
+ * avoiding the need to split the PMD into PTE-level swap entries.
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int set_pmd_swap_entry(struct page_vma_mapped_walk *pvmw,
+               struct folio *folio)
+{
+    struct vm_area_struct *vma = pvmw->vma;
+    struct mm_struct *mm = vma->vm_mm;
+    unsigned long address = pvmw->address;
+    unsigned long haddr = address & HPAGE_PMD_MASK;
+    struct page *page = folio_page(folio, 0);
+    bool anon_exclusive;
+    pmd_t pmdval;
+    swp_entry_t entry;
+    pmd_t pmdswp;
Quoted 9 lines

mm/huge_memory.c void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new) · line 5591

Quoted 3 lines
mm/huge_memory.c +3 -0
+
+    if (!(pvmw->pmd && !pvmw->pte))
+        return 0;

Should we call VM_WARN_ON_ONCE() and return an error instead? This function is only called by try_to_unmap_one() under this condition. In addition, returning zero would cause try_to_unmap_one() to assume that the PMD swap entry was installed, which is not the case.

Thanks for review!

It makes sense, I will add a warning and return -EINVAL.

author reviewer
#27 lore raw

PATCH v5 11/11 selftests/mm: add PMD swap entry tests

In reply to Usama Arif

Exercise the PMD swap entry paths. The tests allocate a PMD-mapped THP, write a known pattern, swap it out via MADV_PAGEOUT, and then exercise different code paths:

- swap-out / swap-in round-trip with data verification
- fork with read-only access from both parent and child
- fork with writes in both processes to verify COW isolation
- repeated swap cycles to catch reference counting issues
- write fault on a swapped PMD to verify dirty handling and PMD mapping restoration
- userfaultfd RWP preservation across PMD-order swap-in
- munmap of a swapped PMD (zap_huge_pmd swap slot cleanup)
- mprotect on a swapped PMD (change_non_present_huge_pmd)
- UFFDIO_MOVE on a swapped PMD, including destination RWP preservation
- mremap of a swapped PMD (move_soft_dirty_pmd)
- pagemap reading (pagemap_pmd_range_thp softleaf_has_pfn guard)
- mincore on a swapped PMD without faulting it in
- MADV_FREE on a swapped PMD: verifies swap slots are freed via pagemap and the memory reads back as zero
- MADV_WILLNEED on a swapped PMD
- swapoff with active PMD swap entries, including RWP preservation

Add a pmd_swap category and ksft_pmd_swap.sh wrapper so the default mm selftest invocation and CI execute the test. PMD_SWAP_DEVICE remains optional for the destructive swapoff case.

When zswap is enabled, PMD-order consumers may split a PMD swap entry and retry through the PTE path because zswap stores the range as per-page entries. In that configuration, the tests still verify data correctness and log that the PMD mapping assertion is skipped. With zswap disabled, the tests assert that write faults, UFFDIO_MOVE, MADV_WILLNEED, and swapoff restore a PMD-mapped THP where expected.

---
 tools/testing/selftests/mm/Makefile         |   2 +
 tools/testing/selftests/mm/ksft_pmd_swap.sh |   4 +
 tools/testing/selftests/mm/pmd_swap.c       | 874 ++++++++++++++++++++
 tools/testing/selftests/mm/run_vmtests.sh   |   4 +
 4 files changed, 884 insertions(+)
 create mode 100755 tools/testing/selftests/mm/ksft_pmd_swap.sh
 create mode 100644 tools/testing/selftests/mm/pmd_swap.c
tools/testing/selftests/mm/Makefile +2 -0
index eae504bd94c8..25af4d7b633e 100644
@@ -104,6 +104,7 @@ TEST_GEN_FILES += guard-regions
 TEST_GEN_FILES += merge
 TEST_GEN_FILES += rmap
 TEST_GEN_FILES += folio_split_race_test
+TEST_GEN_FILES += pmd_swap
 
 ifneq ($(ARCH),arm64)
 TEST_GEN_FILES += soft-dirty
@@ -165,6 +166,7 @@ TEST_PROGS += ksft_mremap.sh
 TEST_PROGS += ksft_pagemap.sh
 TEST_PROGS += ksft_pfnmap.sh
 TEST_PROGS += ksft_pkey.sh
+TEST_PROGS += ksft_pmd_swap.sh
 TEST_PROGS += ksft_process_madv.sh
 TEST_PROGS += ksft_process_mrelease.sh
 TEST_PROGS += ksft_rmap.sh
tools/testing/selftests/mm/ksft_pmd_swap.sh new file +4 -0
new file mode 100755
index 000000000000..0f070b4729a8
@@ -0,0 +1,4 @@
+#!/bin/sh -e
+# SPDX-License-Identifier: GPL-2.0
+
+./run_vmtests.sh -t pmd_swap
tools/testing/selftests/mm/pmd_swap.c new file +874 -0

874 lines not on this page · raw message

tools/testing/selftests/mm/run_vmtests.sh +4 -0
index 687d115e3bd8..0a860c4852f2 100755
@@ -69,6 +69,8 @@ separated by spaces:
 	test pagemap_scan IOCTL
 - pfnmap
 	tests for VM_PFNMAP handling
+- pmd_swap
+	tests for PMD-level swap entries
 - process_madv
 	test for process_madv
 - cow
@@ -399,6 +401,8 @@ CATEGORY="pagemap" run_test ./pagemap_ioctl
 
 CATEGORY="pfnmap" run_test ./pfnmap
 
+CATEGORY="pmd_swap" run_test ./pmd_swap
+
 # COW tests
 CATEGORY="cow" run_test ./cow
 
Signature · 1 line
2.53.0-Meta
#28 lore raw

Re: [PATCH v5 11/11] selftests/mm: add PMD swap entry tests

Quoted 158 lines · Usama Arif

Exercise the PMD swap entry paths. The tests allocate a PMD-mapped THP, write a known pattern, swap it out via MADV_PAGEOUT, and then exercise different code paths:

- swap-out / swap-in round-trip with data verification
- fork with read-only access from both parent and child
- fork with writes in both processes to verify COW isolation
- repeated swap cycles to catch reference counting issues
- write fault on a swapped PMD to verify dirty handling and PMD mapping restoration
- userfaultfd RWP preservation across PMD-order swap-in
- munmap of a swapped PMD (zap_huge_pmd swap slot cleanup)
- mprotect on a swapped PMD (change_non_present_huge_pmd)
- UFFDIO_MOVE on a swapped PMD, including destination RWP preservation
- mremap of a swapped PMD (move_soft_dirty_pmd)
- pagemap reading (pagemap_pmd_range_thp softleaf_has_pfn guard)
- mincore on a swapped PMD without faulting it in
- MADV_FREE on a swapped PMD: verifies swap slots are freed via pagemap and the memory reads back as zero
- MADV_WILLNEED on a swapped PMD
- swapoff with active PMD swap entries, including RWP preservation

Add a pmd_swap category and ksft_pmd_swap.sh wrapper so the default mm selftest invocation and CI execute the test. PMD_SWAP_DEVICE remains optional for the destructive swapoff case.

When zswap is enabled, PMD-order consumers may split a PMD swap entry and retry through the PTE path because zswap stores the range as per-page entries. In that configuration, the tests still verify data correctness and log that the PMD mapping assertion is skipped. With zswap disabled, the tests assert that write faults, UFFDIO_MOVE, MADV_WILLNEED, and swapoff restore a PMD-mapped THP where expected.

---
  tools/testing/selftests/mm/Makefile         |   2 +
  tools/testing/selftests/mm/ksft_pmd_swap.sh |   4 +
  tools/testing/selftests/mm/pmd_swap.c       | 874 ++++++++++++++++++++
  tools/testing/selftests/mm/run_vmtests.sh   |   4 +
  4 files changed, 884 insertions(+)

create mode 100755 tools/testing/selftests/mm/ksft_pmd_swap.sh create mode 100644 tools/testing/selftests/mm/pmd_swap.c

tools/testing/selftests/mm/Makefile +2 -0
index eae504bd94c8..25af4d7b633e 100644
@@ -104,6 +104,7 @@ TEST_GEN_FILES += guard-regions
  TEST_GEN_FILES += merge
  TEST_GEN_FILES += rmap
  TEST_GEN_FILES += folio_split_race_test
+TEST_GEN_FILES += pmd_swap
 
  ifneq ($(ARCH),arm64)
  TEST_GEN_FILES += soft-dirty
@@ -165,6 +166,7 @@ TEST_PROGS += ksft_mremap.sh
  TEST_PROGS += ksft_pagemap.sh
  TEST_PROGS += ksft_pfnmap.sh
  TEST_PROGS += ksft_pkey.sh
+TEST_PROGS += ksft_pmd_swap.sh
  TEST_PROGS += ksft_process_madv.sh
  TEST_PROGS += ksft_process_mrelease.sh
  TEST_PROGS += ksft_rmap.sh
tools/testing/selftests/mm/ksft_pmd_swap.sh new file +4 -0
new file mode 100755
index 000000000000..0f070b4729a8
@@ -0,0 +1,4 @@
+#!/bin/sh -e
+# SPDX-License-Identifier: GPL-2.0
+
+./run_vmtests.sh -t pmd_swap
tools/testing/selftests/mm/pmd_swap.c new file +79 -0
new file mode 100644
index 000000000000..7cf9ac074e96
@@ -0,0 +1,874 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test PMD-level swap entries.
+ *
+ * Verifies that when a PMD-mapped THP is swapped out the kernel installs
+ * a single PMD-level swap entry (instead of splitting into 512 PTE-level
+ * entries), and that operations on the swapped region behave correctly:
+ *   basic         - swap out + swap in preserves data
+ *   fork          - parent and child both see the data
+ *   fork_cow      - COW after fork keeps parent's data isolated
+ *   cycles        - repeated swap out/in does not corrupt data
+ *   write         - faulting in via a write restores a PMD-mapped THP
+ *   rwp_swapin    - userfaultfd RWP survives PMD-order swap-in
+ *   munmap        - munmap on a PMD swap entry frees swap slots cleanly
+ *   mprotect      - mprotect on a PMD swap entry preserves data
+ *   mremap        - mremap on a PMD swap entry preserves data
+ *   pagemap        - pagemap reports the entries as swapped
+ *   mincore        - mincore walks a PMD swap entry without faulting it in
+ *   madvise_free   - MADV_FREE on a PMD swap entry does not crash
+ *   madvise_willneed - MADV_WILLNEED handles a PMD swap entry
+ *   uffdio_move    - UFFDIO_MOVE moves a PMD swap entry
+ *   swapoff        - swapoff handles PMD swap entries (needs PMD_SWAP_DEVICE)
+ */
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <sys/wait.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stdint.h>
+#include <sys/random.h>
+#include <sys/swap.h>
+#include <sys/syscall.h>
+#include <sys/ioctl.h>
+#include <poll.h>
+#include <pthread.h>
+#include <linux/userfaultfd.h>
+#include <time.h>
+
+#include "kselftest_harness.h"
+#include "vm_util.h"
+
+#define ZSWAP_ENABLED_PATH "/sys/module/zswap/parameters/enabled"
+
+static bool check_swapped(int pagemap_fd, char *addr, unsigned long size)
+{
+	unsigned long off;
+
+	for (off = 0; off < size; off += getpagesize())
+		if (!pagemap_is_swapped(pagemap_fd, addr + off))
+			return false;
+	return true;
+}
+
+static bool zswap_enabled(void)
+{
+	char enabled = 0;
+	FILE *f;
+
+	f = fopen(ZSWAP_ENABLED_PATH, "r");
+	if (!f)
+		return false;
+
+	if (fscanf(f, " %c", &enabled) != 1)
+		enabled = 0;
+	fclose(f);
+
+	return enabled == 'Y' || enabled == 'y' || enabled == '1';
+}
+
+static bool swap_available(int pagemap_fd)
+{
+	char *p;
+	bool ret;
+
+	p = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE,

tools/testing/selftests/mm/pmd_swap.c line 89

Quoted 10 lines
tools/testing/selftests/mm/pmd_swap.c new file +10 -0
+		 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+	if (p == MAP_FAILED)
+		return false;
+
+	memset(p, 0xab, getpagesize());
+	madvise(p, getpagesize(), MADV_PAGEOUT);
+	ret = pagemap_is_swapped(pagemap_fd, p);
+	munmap(p, getpagesize());
+	return ret;
+}

Why not check /proc/swaps instead? We're performing the first test-case here, if this fails because of a bug the test would be skipped.

Quoted 83 lines
tools/testing/selftests/mm/pmd_swap.c new file +83 -0
+
+static unsigned long read_vm_event(const char *name)
+{
+	char line[256];
+	size_t name_len = strlen(name);
+	unsigned long val = 0;
+	FILE *f;
+
+	f = fopen("/proc/vmstat", "r");
+	if (!f)
+		return 0;
+	while (fgets(line, sizeof(line), f)) {
+		if (!strncmp(line, name, name_len) && line[name_len] == ' ') {
+			val = strtoul(line + name_len + 1, NULL, 10);
+			break;
+		}
+	}
+	fclose(f);
+	return val;
+}
+
+static unsigned int random_seed(void)
+{
+	unsigned int seed;
+
+	if (getrandom(&seed, sizeof(seed), 0) != sizeof(seed))
+		seed = (unsigned int)time(NULL);
+	return seed;
+}
+
+static unsigned char pattern_byte(unsigned int seed, unsigned long off)
+{
+	return (unsigned char)(seed + off);
+}
+
+static void fill_pattern(char *buf, unsigned long size, unsigned int seed)
+{
+	unsigned long i;
+
+	for (i = 0; i < size; i++)
+		buf[i] = (char)pattern_byte(seed, i);
+}
+
+static bool verify_pattern(char *buf, unsigned long size, unsigned int seed)
+{
+	unsigned long i;
+
+	for (i = 0; i < size; i++)
+		if ((unsigned char)buf[i] != pattern_byte(seed, i))
+			return false;
+	return true;
+}
+
+/*
+ * mmap an anonymous PMD-aligned region of pmd_size bytes. Over-allocates
+ * by one PMD and trims the unaligned head/tail so the returned address is
+ * PMD-aligned (required for whole-PMD UFFDIO_MOVE).
+ */
+static char *mmap_pmd_aligned(unsigned long pmd_size)
+{
+	unsigned long pad = pmd_size;
+	char *raw, *aligned;
+
+	raw = mmap(NULL, pmd_size + pad, PROT_READ | PROT_WRITE,
+		   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+	if (raw == MAP_FAILED)
+		return MAP_FAILED;
+
+	aligned = (char *)(((uintptr_t)raw + pmd_size - 1) & ~(pmd_size - 1));
+	if (aligned != raw)
+		munmap(raw, aligned - raw);
+	if (aligned + pmd_size != raw + pmd_size + pad)
+		munmap(aligned + pmd_size,
+		       (raw + pmd_size + pad) - (aligned + pmd_size));
+	return aligned;
+}
+
+/*
+ * mmap a PMD-aligned PMD-sized region, request THP, fill with a pattern,
+ * and swap it out. Verifies via the thp_swpout_pmd vmstat counter that
+ * the swap-out installed a PMD swap entry rather than splitting to PTEs.
+ */
+static char *alloc_fill_swap_thp(unsigned long pmd_size, int pagemap_fd,

tools/testing/selftests/mm/pmd_swap.c line 182

Quoted 10 lines
tools/testing/selftests/mm/pmd_swap.c new file +10 -0
+				 unsigned int seed)
+{
+	unsigned long pmd_before, pmd_after;
+	char *mem;
+
+	mem = mmap_pmd_aligned(pmd_size);
+	if (mem == MAP_FAILED)
+		return MAP_FAILED;
+
+	madvise(mem, pmd_size, MADV_HUGEPAGE);

This is minor, but I'd check madvise() return.

tools/testing/selftests/mm/pmd_swap.c line 194

Quoted 12 lines
tools/testing/selftests/mm/pmd_swap.c new file +12 -0
+	fill_pattern(mem, pmd_size, seed);
+
+	pmd_before = read_vm_event("thp_swpout_pmd");
+
+	if (madvise(mem, pmd_size, MADV_PAGEOUT) ||
+	    !check_swapped(pagemap_fd, mem, pmd_size)) {
+		munmap(mem, pmd_size);
+		return MAP_FAILED;
+	}
+
+	pmd_after = read_vm_event("thp_swpout_pmd");
+	printf("# thp_swpout_pmd: %lu -> %lu\n", pmd_before, pmd_after);

Should we use ksft_print_msg() instead?

Quoted 135 lines
tools/testing/selftests/mm/pmd_swap.c new file +135 -0
+	if (pmd_after - pmd_before < 1) {
+		munmap(mem, pmd_size);
+		return MAP_FAILED;
+	}
+	return mem;
+}
+
+struct rwp_access_args {
+	unsigned char *addr;
+	unsigned char expected;
+	bool write;
+	bool ok;
+};
+
+static void *rwp_access_thread(void *data)
+{
+	struct rwp_access_args *args = data;
+
+	if (args->write)
+		*args->addr = args->expected;
+	args->ok = *args->addr == args->expected;
+	return NULL;
+}
+
+static int register_rwp(char *addr, unsigned long size, bool protect)
+{
+	struct uffdio_register reg = {};
+	struct uffdio_rwprotect rwp = {};
+	struct uffdio_api api = {};
+	int uffd;
+
+	uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
+	if (uffd < 0)
+		return -1;
+
+	api.api = UFFD_API;
+	api.features = UFFD_FEATURE_RWP;
+	if (ioctl(uffd, UFFDIO_API, &api) ||
+	    !(api.features & UFFD_FEATURE_RWP))
+		goto error;
+
+	reg.range.start = (unsigned long)addr;
+	reg.range.len = size;
+	reg.mode = UFFDIO_REGISTER_MODE_RWP;
+	if (ioctl(uffd, UFFDIO_REGISTER, &reg))
+		goto error;
+
+	if (!protect)
+		return uffd;
+
+	rwp.range.start = (unsigned long)addr;
+	rwp.range.len = size;
+	rwp.mode = UFFDIO_RWPROTECT_MODE_RWP;
+	if (!ioctl(uffd, UFFDIO_RWPROTECT, &rwp))
+		return uffd;
+
+error:
+	close(uffd);
+	return -1;
+}
+
+static bool expect_rwp_fault(int uffd, char *addr, unsigned long size,
+			     unsigned char expected, bool write)
+{
+	struct rwp_access_args args = {
+		.addr = (unsigned char *)addr,
+		.expected = expected,
+		.write = write,
+	};
+	struct uffdio_rwprotect rwp = {
+		.range = {
+			.start = (unsigned long)addr,
+			.len = size,
+		},
+	};
+	struct pollfd pollfd = {
+		.fd = uffd,
+		.events = POLLIN,
+	};
+	struct uffd_msg msg = {};
+	pthread_t thread;
+	bool saw_rwp = false;
+	int ret;
+
+	if (pthread_create(&thread, NULL, rwp_access_thread, &args))
+		return false;
+
+	ret = poll(&pollfd, 1, 5000);
+	if (ret == 1 && (pollfd.revents & POLLIN) &&
+	    read(uffd, &msg, sizeof(msg)) == (ssize_t)sizeof(msg)) {
+		saw_rwp = msg.event == UFFD_EVENT_PAGEFAULT &&
+			  (msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_RWP);
+	}
+
+	/* Resolve the access even on failure so the worker cannot remain blocked. */
+	ioctl(uffd, UFFDIO_RWPROTECT, &rwp);
+	if (pthread_join(thread, NULL))
+		return false;
+	return saw_rwp && args.ok;
+}
+
+FIXTURE(pmd_swap)
+{
+	unsigned long pmd_size;
+	int pagemap_fd;
+	unsigned int seed;
+	bool zswap_enabled;
+};
+
+FIXTURE_SETUP(pmd_swap)
+{
+	self->pagemap_fd = -1;
+
+	self->pmd_size = read_pmd_pagesize();
+	if (!self->pmd_size)
+		SKIP(return, "Cannot determine PMD size\n");
+
+	self->pagemap_fd = open("/proc/self/pagemap", O_RDONLY);
+	if (self->pagemap_fd < 0)
+		SKIP(return, "Cannot open /proc/self/pagemap\n");
+
+	if (!swap_available(self->pagemap_fd))
+		SKIP(return, "Swap not available or not working\n");
+
+	self->seed = random_seed();
+	self->zswap_enabled = zswap_enabled();
+}
+
+FIXTURE_TEARDOWN(pmd_swap)
+{
+	if (self->pagemap_fd >= 0)
+		close(self->pagemap_fd);
+}
+
+/*

tools/testing/selftests/mm/pmd_swap.c line 339

Quoted 10 lines
tools/testing/selftests/mm/pmd_swap.c new file +10 -0
+ * Allocate a PMD-sized THP, write a pattern, swap it out, read it back,
+ * verify the pattern.
+ */
+TEST_F(pmd_swap, basic)
+{
+	char *mem;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, self->seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");

I think that skipping on failure may hide potential regressions. If the intent is to skip when you don't get a PMD THP, then you could return different error codes but do fail the test if swapping fails. Note that this applies to all the tests calling alloc_fill_swap_thp().

Quoted 90 lines
tools/testing/selftests/mm/pmd_swap.c new file +90 -0
+
+	ASSERT_TRUE(verify_pattern(mem, self->pmd_size, self->seed));
+
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * Allocate a THP, swap it out, fork, verify both parent and child see
+ * the correct data.
+ */
+TEST_F(pmd_swap, fork)
+{
+	char *mem;
+	pid_t pid;
+	int status;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, self->seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	pid = fork();
+	ASSERT_GE(pid, 0);
+
+	if (pid == 0)
+		_exit(verify_pattern(mem, self->pmd_size, self->seed) ? 0 : 1);
+
+	ASSERT_TRUE(verify_pattern(mem, self->pmd_size, self->seed));
+
+	ASSERT_EQ(waitpid(pid, &status, 0), pid);
+	ASSERT_TRUE(WIFEXITED(status));
+	ASSERT_EQ(WEXITSTATUS(status), 0);
+
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * Swap out, fork, then have parent and child write different patterns.
+ * Exercises COW on shared PMD swap entries: writes after fork must
+ * trigger copy-on-write so the parent's data stays isolated from the
+ * child's.  Both processes write and then verify their own pattern so
+ * the parent-side COW path is exercised too (a parent-only-read variant
+ * only proves the swap entry survived fork).
+ */
+TEST_F(pmd_swap, fork_cow)
+{
+	unsigned int parent_seed = self->seed;
+	unsigned int child_seed = ~self->seed;
+	unsigned int post_seed = self->seed ^ 0xa5a5a5a5;
+	char *mem;
+	pid_t pid;
+	int status;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, parent_seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	pid = fork();
+	ASSERT_GE(pid, 0);
+
+	if (pid == 0) {
+		fill_pattern(mem, self->pmd_size, child_seed);
+		_exit(verify_pattern(mem, self->pmd_size, child_seed) ? 0 : 1);
+	}
+
+	ASSERT_EQ(waitpid(pid, &status, 0), pid);
+
+	/* Child's writes must not leak back into the parent. */
+	ASSERT_TRUE(verify_pattern(mem, self->pmd_size, parent_seed));
+	ASSERT_TRUE(WIFEXITED(status));
+	ASSERT_EQ(WEXITSTATUS(status), 0);
+
+	/* Now trigger the parent-side COW and confirm the write sticks. */
+	fill_pattern(mem, self->pmd_size, post_seed);
+	ASSERT_TRUE(verify_pattern(mem, self->pmd_size, post_seed));
+
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * Swap a THP out and in repeatedly without data corruption.
+ */
+TEST_F(pmd_swap, cycles)
+{
+	const int num_cycles = 5;
+	char *mem;
+	int cycle;
+
+	for (cycle = 0; cycle < num_cycles; cycle++) {
+		unsigned int seed = self->seed + cycle;
+

tools/testing/selftests/mm/pmd_swap.c line 439

Quoted 10 lines
tools/testing/selftests/mm/pmd_swap.c new file +10 -0
+		mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, seed);
+		if (mem == MAP_FAILED)
+			SKIP(return, "Could not create swapped THP at cycle %d\n",
+			     cycle);
+
+		ASSERT_TRUE(verify_pattern(mem, self->pmd_size, seed));
+
+		munmap(mem, self->pmd_size);
+	}
+}

Since all the tests already swap-out a single PMD page, I think we could improve coverage by swapping out multiple PMD pages or maybe a PMD page and a base page.

Quoted 63 lines
tools/testing/selftests/mm/pmd_swap.c new file +63 -0
+
+/*
+ * Swap out, fault in via a write to the first page, verify the write
+ * reinstates a THP mapping and the rest of the THP is preserved.
+ */
+TEST_F(pmd_swap, write)
+{
+	unsigned int seed = self->seed;
+	char *mem;
+	unsigned long i;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	mem[0] = 0xbb;
+	ASSERT_EQ(mem[0], (char)0xbb);
+
+	if (self->zswap_enabled) {
+		TH_LOG("zswap is enabled, so PMD mapping is not checked");
+	} else {
+		ASSERT_TRUE(check_huge_anon(mem, 1, self->pmd_size));
+	}
+
+	for (i = 1; i < self->pmd_size; i++)
+		ASSERT_EQ((unsigned char)mem[i], pattern_byte(seed, i));
+
+	munmap(mem, self->pmd_size);
+}
+
+/* RWP protection on a swap PMD must survive PMD-order swap-in. */
+TEST_F(pmd_swap, rwp_swapin)
+{
+	unsigned int seed = self->seed;
+	char *mem;
+	int uffd;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	uffd = register_rwp(mem, self->pmd_size, true);
+	if (uffd < 0) {
+		munmap(mem, self->pmd_size);
+		SKIP(return, "Userfaultfd RWP unsupported\n");
+	}
+
+	ASSERT_TRUE(expect_rwp_fault(uffd, mem, self->pmd_size,
+				     pattern_byte(seed, 0), false)) {
+		close(uffd);
+		munmap(mem, self->pmd_size);
+	}
+	ASSERT_TRUE(verify_pattern(mem, self->pmd_size, seed));
+
+	close(uffd);
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * munmap while the folio is swapped out. Exercises zap_huge_pmd() on a
+ * PMD swap entry — must free the swap slots without trying to look up
+ * a folio.
+ */

tools/testing/selftests/mm/pmd_swap.c line 512

Quoted 10 lines
tools/testing/selftests/mm/pmd_swap.c new file +10 -0
+TEST_F(pmd_swap, munmap)
+{
+	char *mem;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, self->seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	munmap(mem, self->pmd_size);
+}

Should we check munmap() return since that's the purpose of the test?

Quoted 208 lines
tools/testing/selftests/mm/pmd_swap.c new file +208 -0
+
+/*
+ * Change protection on a swapped PMD entry, then fault back in and
+ * verify data. Exercises change_non_present_huge_pmd().
+ */
+TEST_F(pmd_swap, mprotect)
+{
+	unsigned int seed = self->seed;
+	char *mem;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	ASSERT_EQ(mprotect(mem, self->pmd_size, PROT_READ), 0);
+	ASSERT_EQ(mprotect(mem, self->pmd_size, PROT_READ | PROT_WRITE), 0);
+
+	ASSERT_TRUE(verify_pattern(mem, self->pmd_size, seed));
+
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * UFFDIO_MOVE a PMD swap entry from src to a registered dst. Exercises
+ * move_pages_huge_pmd() handling of pmd_is_swap_entry: the whole PMD swap
+ * entry must move to dst without splitting, and the destination must
+ * read back the original pattern after a swap-in fault.
+ */
+TEST_F(pmd_swap, uffdio_move)
+{
+	unsigned int seed = self->seed;
+	struct uffdio_register reg = {};
+	struct uffdio_move move = {};
+	struct uffdio_api api = {};
+	char *src, *dst;
+	bool rwp;
+	int uffd;
+
+	dst = mmap_pmd_aligned(self->pmd_size);
+	if (dst == MAP_FAILED)
+		SKIP(return, "Could not mmap aligned dst\n");
+
+	src = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, seed);
+	if (src == MAP_FAILED) {
+		munmap(dst, self->pmd_size);
+		SKIP(return, "Could not create swapped THP\n");
+	}
+	if ((uintptr_t)src & (self->pmd_size - 1)) {
+		munmap(src, self->pmd_size);
+		munmap(dst, self->pmd_size);
+		SKIP(return, "src not PMD-aligned\n");
+	}
+
+	uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
+	if (uffd < 0) {
+		munmap(src, self->pmd_size);
+		munmap(dst, self->pmd_size);
+		SKIP(return, "userfaultfd unavailable\n");
+	}
+
+	api.api = UFFD_API;
+	api.features = UFFD_FEATURE_MOVE | UFFD_FEATURE_RWP;
+	if (ioctl(uffd, UFFDIO_API, &api) ||
+	    !(api.features & UFFD_FEATURE_MOVE)) {
+		close(uffd);
+		munmap(src, self->pmd_size);
+		munmap(dst, self->pmd_size);
+		SKIP(return, "UFFD_FEATURE_MOVE unsupported\n");
+	}
+	rwp = api.features & UFFD_FEATURE_RWP;
+
+	reg.range.start = (unsigned long)dst;
+	reg.range.len = self->pmd_size;
+	reg.mode = UFFDIO_REGISTER_MODE_MISSING |
+		   (rwp ? UFFDIO_REGISTER_MODE_RWP : 0);
+	if (ioctl(uffd, UFFDIO_REGISTER, &reg)) {
+		close(uffd);
+		munmap(src, self->pmd_size);
+		munmap(dst, self->pmd_size);
+		SKIP(return, "UFFDIO_REGISTER failed\n");
+	}
+
+	move.dst = (unsigned long)dst;
+	move.src = (unsigned long)src;
+	move.len = self->pmd_size;
+	if (ioctl(uffd, UFFDIO_MOVE, &move)) {
+		int saved_errno = errno;
+
+		close(uffd);
+		munmap(src, self->pmd_size);
+		munmap(dst, self->pmd_size);
+		ASSERT_EQ(saved_errno, 0);
+	}
+	ASSERT_EQ(move.move, self->pmd_size);
+
+	/* dst inherits the PMD swap entry; reading it must restore the data. */
+	ASSERT_TRUE(check_swapped(self->pagemap_fd, dst, self->pmd_size));
+	if (rwp) {
+		ASSERT_TRUE(expect_rwp_fault(uffd, dst, self->pmd_size,
+					     pattern_byte(seed, 0), false)) {
+			close(uffd);
+			munmap(src, self->pmd_size);
+			munmap(dst, self->pmd_size);
+		}
+	}
+	ASSERT_TRUE(verify_pattern(dst, self->pmd_size, seed));
+	if (self->zswap_enabled) {
+		TH_LOG("zswap is enabled, so PMD mapping is not checked");
+	} else {
+		/* The whole-PMD path must reinstate a THP, not 512 PTE folios. */
+		ASSERT_TRUE(check_huge_anon(dst, 1, self->pmd_size));
+	}
+
+	close(uffd);
+	munmap(src, self->pmd_size);
+	munmap(dst, self->pmd_size);
+}
+
+/*
+ * Move a swapped PMD entry to a new address, fault in, verify data.
+ * Exercises move_huge_pmd() and move_soft_dirty_pmd().
+ */
+TEST_F(pmd_swap, mremap)
+{
+	unsigned int seed = self->seed;
+	char *mem, *new_mem;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	new_mem = mremap(mem, self->pmd_size, self->pmd_size, MREMAP_MAYMOVE);
+	if (new_mem == MAP_FAILED) {
+		munmap(mem, self->pmd_size);
+		ASSERT_NE(new_mem, MAP_FAILED);
+	}
+
+	ASSERT_TRUE(verify_pattern(new_mem, self->pmd_size, seed));
+
+	munmap(new_mem, self->pmd_size);
+}
+
+/*
+ * Read /proc/self/pagemap on a PMD swap entry. Exercises the pagemap
+ * PMD walker which must handle PMD swap entries without trying to
+ * convert them to a page via softleaf_to_page().
+ */
+TEST_F(pmd_swap, pagemap)
+{
+	char *mem;
+	uint64_t entry;
+	unsigned long off;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, self->seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	for (off = 0; off < self->pmd_size; off += getpagesize()) {
+		entry = pagemap_get_entry(self->pagemap_fd, mem + off);
+		/* Bit 62 = swapped */
+		ASSERT_TRUE(entry & (1ULL << 62));
+	}
+
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * mincore() on a swapped-out PMD-mapped THP must handle the non-present PMD
+ * entry in place. The call must not fault the PMD back in or split the entry.
+ */
+TEST_F(pmd_swap, mincore)
+{
+	unsigned long pages = self->pmd_size / getpagesize();
+	unsigned char *vec;
+	char *mem;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, self->seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	vec = calloc(pages, sizeof(*vec));
+	ASSERT_NE(vec, NULL) {
+		munmap(mem, self->pmd_size);
+	}
+
+	ASSERT_EQ(mincore(mem, self->pmd_size, vec), 0) {
+		free(vec);
+		munmap(mem, self->pmd_size);
+	}
+	ASSERT_TRUE(check_swapped(self->pagemap_fd, mem, self->pmd_size)) {
+		free(vec);
+		munmap(mem, self->pmd_size);
+	}
+
+	free(vec);
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * MADV_FREE on a swapped-out PMD must free the swap slots and clear the
+ * entry. After the call, pagemap must no longer report the pages as
+ * swapped, and accessing the region must yield zero pages.
+ */
+TEST_F(pmd_swap, madvise_free)
+{
+	char *mem;
+	unsigned long i;
+

tools/testing/selftests/mm/pmd_swap.c line 730

Quoted 10 lines
tools/testing/selftests/mm/pmd_swap.c new file +10 -0
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, self->seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	ASSERT_TRUE(check_swapped(self->pagemap_fd, mem, self->pmd_size));
+	ASSERT_EQ(madvise(mem, self->pmd_size, MADV_FREE), 0);
+	ASSERT_FALSE(check_swapped(self->pagemap_fd, mem, self->pmd_size));
+
+	for (i = 0; i < self->pmd_size; i += getpagesize())
+		ASSERT_EQ(mem[i], 0);

This is checking only the first byte, no? Is this intentional?

Quoted 62 lines
tools/testing/selftests/mm/pmd_swap.c new file +62 -0
+
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * MADV_WILLNEED on a swapped-out PMD-mapped THP may schedule PMD-order
+ * swapin I/O, find the PMD-sized folio already resident in the swap cache,
+ * or split to the PTE path when zswap has per-page state for the range.
+ */
+TEST_F(pmd_swap, madvise_willneed)
+{
+	char *mem;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, self->seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+
+	ASSERT_EQ(madvise(mem, self->pmd_size, MADV_WILLNEED), 0);
+	ASSERT_TRUE(check_swapped(self->pagemap_fd, mem, self->pmd_size));
+
+	/* First touch faults the data back in. */
+	ASSERT_TRUE(verify_pattern(mem, self->pmd_size, self->seed));
+
+	if (self->zswap_enabled)
+		TH_LOG("zswap is enabled, so PMD mapping is not checked");
+	else
+		ASSERT_TRUE(check_huge_anon(mem, 1, self->pmd_size));
+
+	munmap(mem, self->pmd_size);
+}
+
+/*
+ * swapoff requires a dedicated swap device path. Use a separate fixture
+ * that picks the device up from the PMD_SWAP_DEVICE environment variable
+ * and skips when unset.
+ */
+FIXTURE(pmd_swap_swapoff)
+{
+	unsigned long pmd_size;
+	int pagemap_fd;
+	const char *swap_dev;
+	unsigned int seed;
+	bool zswap_enabled;
+};
+
+FIXTURE_SETUP(pmd_swap_swapoff)
+{
+	self->pagemap_fd = -1;
+	self->swap_dev = getenv("PMD_SWAP_DEVICE");
+	if (!self->swap_dev)
+		SKIP(return, "PMD_SWAP_DEVICE env var not set\n");
+
+	self->pmd_size = read_pmd_pagesize();
+	if (!self->pmd_size)
+		SKIP(return, "Cannot determine PMD size\n");
+
+	self->pagemap_fd = open("/proc/self/pagemap", O_RDONLY);
+	if (self->pagemap_fd < 0)
+		SKIP(return, "Cannot open /proc/self/pagemap\n");
+
+	if (!swap_available(self->pagemap_fd))
+		SKIP(return, "Swap not available or not working\n");

tools/testing/selftests/mm/pmd_swap.c line 802

Quoted 10 lines
tools/testing/selftests/mm/pmd_swap.c new file +10 -0
+
+	self->seed = random_seed();
+	self->zswap_enabled = zswap_enabled();
+}
+
+FIXTURE_TEARDOWN(pmd_swap_swapoff)
+{
+	if (self->pagemap_fd >= 0)
+		close(self->pagemap_fd);
+}

Should swapoff() be moved here? I think it would avoid the repeated swapoff() calls in the test.

Quoted 94 lines
tools/testing/selftests/mm/pmd_swap.c new file +72 -0
+
+/*
+ * Swap out a THP, then turn off swap. Verify data is intact. When zswap is
+ * not active, the PMD-order swapoff path should preserve the huge mapping.
+ */
+TEST_F(pmd_swap_swapoff, basic)
+{
+	unsigned int seed = self->seed;
+	char *mem;
+	int uffd, ret, err;
+
+	mem = alloc_fill_swap_thp(self->pmd_size, self->pagemap_fd, seed);
+	if (mem == MAP_FAILED)
+		SKIP(return, "Could not create swapped THP\n");
+	uffd = register_rwp(mem, self->pmd_size, true);
+
+	ret = swapoff(self->swap_dev);
+	err = errno;
+	ASSERT_EQ(ret, 0) {
+		TH_LOG("swapoff(%s) failed: %s", self->swap_dev, strerror(err));
+		if (uffd >= 0)
+			close(uffd);
+		munmap(mem, self->pmd_size);
+	}
+
+	/*
+	 * Check the PMD residency before touching the memory.  If we read
+	 * first, a bug that left a PMD swap entry in place after swapoff
+	 * would silently trigger do_huge_pmd_swap_page() and reinstall a
+	 * PMD mapping, masking the regression.
+	 */
+	if (self->zswap_enabled) {
+		TH_LOG("zswap is enabled, so PMD mapping is not checked");
+	} else {
+		ASSERT_TRUE(check_huge_anon(mem, 1, self->pmd_size)) {
+			swapon(self->swap_dev, 0);
+			if (uffd >= 0)
+				close(uffd);
+			munmap(mem, self->pmd_size);
+		}
+	}
+	if (uffd >= 0) {
+		ASSERT_TRUE(expect_rwp_fault(uffd, mem, self->pmd_size,
+					     pattern_byte(seed, 0), false)) {
+			swapon(self->swap_dev, 0);
+			close(uffd);
+			munmap(mem, self->pmd_size);
+		}
+	}
+
+	ASSERT_TRUE(verify_pattern(mem, self->pmd_size, seed)) {
+		swapon(self->swap_dev, 0);
+		if (uffd >= 0)
+			close(uffd);
+		munmap(mem, self->pmd_size);
+	}
+
+	ret = swapon(self->swap_dev, 0);
+	err = errno;
+	ASSERT_EQ(ret, 0) {
+		TH_LOG("swapon(%s) failed: %s", self->swap_dev, strerror(err));
+		if (uffd >= 0)
+			close(uffd);
+		munmap(mem, self->pmd_size);
+	}
+
+	if (uffd >= 0)
+		close(uffd);
+	munmap(mem, self->pmd_size);
+}
+
+TEST_HARNESS_MAIN
tools/testing/selftests/mm/run_vmtests.sh +4 -0
index 687d115e3bd8..0a860c4852f2 100755
@@ -69,6 +69,8 @@ separated by spaces:
  	test pagemap_scan IOCTL
  - pfnmap
  	tests for VM_PFNMAP handling
+- pmd_swap
+	tests for PMD-level swap entries
  - process_madv
  	test for process_madv
  - cow
@@ -399,6 +401,8 @@ CATEGORY="pagemap" run_test ./pagemap_ioctl
 
  CATEGORY="pfnmap" run_test ./pfnmap
 
+CATEGORY="pmd_swap" run_test ./pmd_swap
+
  # COW tests
  CATEGORY="cow" run_test ./cow