Skip to contentSkip to conversation

mm: various (urgent?) fixes, part 3

PATCH In review David Hildenbrand (Arm) 3 participants 39 messages Dec 4 – Dec 5

Subsystems (19)
lore
Share & tools
lore

David Hildenbrand (Arm)

author maintainer
#0 lore raw

v2 cover mm: various (urgent?) fixes, part 3

Hi,

this is actually part 3. I didn't indicate part 2 properly, and it caused confusion for people monitoring these fixes :)

So, here is another set of fixes for core MM that I will pick up once reviewed. This time it's mostly shmem, khugepaged and some nasty, nasty KSM things.

Mostly AI-reported fixes, with some fixes found while redoing some of them properly.

1 fix has high urgency, 12 have medium urgency and 17 have low urgency.

The last patch is not a fix; for a while I thought it would be one. It's all confusing. But it's a reasonable locking consistency change in migration code.

The really critical ones IMHO are:

- "mm/khugepaged: check the VMA before walking page tables when collapsing" (high)
- "mm/ksm: copy KSM folios at swap-in without VM_MERGEABLE" (medium)
- "mm/ksm: don't convert a shared anon folio into a KSM folio" (medium)
- "mm/memory: don't clear a PUD leaf as bad in a zap" (medium)
- "mm/migrate_device: don't collect KSM folios" (medium)

I might pick these early to send them to Linus before the merge window. OTOH, the merge window is just around the corner ... and the KSM things require systems with KSM enabled.

Most fixes are reviewed by now. The following two are still missing review and are more involved, so I would appreciate some extra careful eyes:

- "mm/ksm: don't convert a shared anon folio into a KSM folio"
- "mm: taint device sections before setting subsections valid"

This is based on mm-core/for-next. I did a bunch of testing (selftests, some targeted reproducers/tests), but more testing will be highly appreciated.

Again, thanks to everyone helping out with moving the flood of fixes forward :)

---
Changes in v2:
- Rebased on top of mm-core/for-next.
- Collected tags (thanks!).
- Dropped "mm/mempolicy: don't wait for mems_allowed_seq in kmalloc_nolock()".
- "mm/shmem: reject userfaultfd fills during hole punch"
- Drop the comment above __shmem_faults_blocked().
- "mm/khugepaged: don't wait for userfaultfd"
- Clarify in the description that MISSING mode is required as well.
- "mm/khugepaged: check PMD support with the folios locked"
- Also check shmem and drop the outdated comment.
- Update the patch description.
- "mm/migrate_device: don't collect secretmem pages"
- Refuse secretmem VMAs in migrate_vma_setup() instead.
- "mm/ksm: don't convert a shared anon folio into a KSM folio"
- Document that some shared pages might not get merged.
- "mm/migrate: fix KSM oddity by checking expected refcount without mappings"
- Clarify the description.
- Link to v1: https://patch.msgid.link/[email protected]

---
Chris Mason (10):
mm/khugepaged: flush file after unlocking folios in collapse_file() mm/khugepaged: store new folio before adding it to LRU mm/khugepaged: check PMD support with the folios locked mm/memory: drop the swap device ref before do_wp_page() mm/migrate_device: don't collect secretmem pages mm/mempolicy: check access under exec_update_lock mm/mempolicy: reject an empty set of allowed nodes mm/ksm: look up the folio again in cmp_and_merge_page() mm/ksm: copy KSM folios at swap-in without VM_MERGEABLE mm/migrate_device: don't collect KSM folios

David Hildenbrand (Arm) (21):
mm/shmem: count only the swapped pages in the requested range mm/shmem: don't skip parts of a split swap entry when punching holes mm/shmem: reject userfaultfd fills during hole punch mm/shmem: fix commit limit bypass with very large shmem sizes mm/shmem: don't pin inodes with eviction held off in the huge shrinker mm/shmem: seal the size of SysV and shared anon files mm/khugepaged: check the VMA before walking page tables when collapsing mm/khugepaged: check for uffd outside the i_pages lock mm/khugepaged: don't wait for userfaultfd
mm/khugepaged: stop MADV_COLLAPSE on a fatal signal mm/huge_memory: split huge zero PMDs on unshare faults mm/huge_memory: don't map huge PFN entries if the arch restricts PFNs mm/memory: don't clear a PUD leaf as bad in a zap
mm: consistently check MMF_UNSTABLE when populating in CoW mappings mm/gup: check for fatal signals in memfd_pin_folios() mm/migrate_device: mark folios leaving device memory dirty
mm: taint device sections before setting subsections valid mm/ksm: don't convert a shared anon folio into a KSM folio mm/ksm: use a migration counter to detect KSM folio migration mm/migrate: fix KSM oddity by checking expected refcount without mappings mm/migrate: use consistent folio locking logic

 Documentation/admin-guide/mm/ksm.rst |   3 +
 include/linux/mm.h                   |  62 +++++++++------
 include/linux/mmzone.h               |   9 +++
 include/linux/oom.h                  |  48 +++++++++---
 include/linux/shmem_fs.h             |  11 +++
 ipc/shm.c                            |   2 +
 mm/filemap.c                         |   9 +++
 mm/gup.c                             |   5 ++
 mm/huge_memory.c                     |  34 ++++++++-
 mm/khugepaged.c                      | 119 ++++++++++++++++++-----------
 mm/ksm.c                             | 143 +++++++++++++++++++++++++++--------
 mm/memory.c                          |  46 +++++++----
 mm/memory_hotplug.c                  |  34 ++-------
 mm/mempolicy.c                       |  30 +++++---
 mm/migrate.c                         |  73 +++++++++---------
 mm/migrate_device.c                  |  30 +++++++-
 mm/rmap.c                            |   6 +-
 mm/shmem.c                           |  96 +++++++++++++++++++----
 mm/sparse-vmemmap.c                  |  39 +++++++---
 mm/userfaultfd.c                     |  37 +++++++++
 20 files changed, 611 insertions(+), 225 deletions(-)

---
base-commit: 9ae069c329809d5206bd03470d033bd899970087
change-id: 20261110-fixes_core_3-701ac25d6d72

Best regards,

Signature · 1 line
David Hildenbrand (Arm) <[email protected]>
author maintainer
#1 lore raw

PATCH v2 1/31 mm/shmem: count only the swapped pages in the requested range

shmem_partial_swap_usage() counts whole swap entries even when only part of an entry falls within the requested range. Further, when a walk starts inside a large entry, xas_pause() can resume beyond its end and skip subsequent entries.

Consequently, we can overcount "Swap" in /proc/<pid>/smaps and smaps_rollup, especially for private writable mappings where the function can be called once per empty PTE, but we can also undercount it.

Let's fix it by clamping each entry to the remaining range and advancing "start" to avoid counting pages twice, and by using xas_set() to resume at the first uncounted index after cond_resched_rcu().

This has low urgency, as it only affects the "Swap" statistics in /proc/<pid>/smaps and smaps_rollup. No need to CC stable.

Fixes 50f381eccefd ("mm: shmem: extend shmem_partial_swap_usage() to support large folio swap")
---
 mm/shmem.c | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)
mm/shmem.c +21 -3
index 9bc4388e38c6b..57eaa867028ef 100644
@@ -1256,14 +1256,32 @@ unsigned long shmem_partial_swap_usage(struct address_space *mapping,
 
 	rcu_read_lock();
 	xas_for_each(&xas, folio, max) {
+		unsigned long nr_pages;
+		pgoff_t first, last;
+
 		if (xas_retry(&xas, folio))
 			continue;
+
+		/* Obtain the range of the spanned entry. */
+		nr_pages = 1UL << xas_get_order(&xas);
+		first = round_down(xas.xa_index, nr_pages);
+		last = first + nr_pages - 1;
+
+		/* Clamp to the remaining range of interest. */
+		first = max(first, start);
+		last = min(last, max);
+		if (first > last)
+			continue;
+
+		/* Account only clamped range as swapped. */
 		if (xa_is_value(folio))
-			swapped += 1 << xas_get_order(&xas);
-		if (xas.xa_index == max)
+			swapped += last - first + 1;
+		if (last == max)
 			break;
+		start = last + 1;
 		if (need_resched()) {
-			xas_pause(&xas);
+			/* Resume at the first index that is not counted yet. */
+			xas_set(&xas, start);
 			cond_resched_rcu();
 		}
 	}
Signature · 1 line
2.56.1
author maintainer
#2 lore raw

PATCH v2 2/31 mm/shmem: don't skip parts of a split swap entry when punching holes

In reply to David Hildenbrand (Arm)

The final loop in shmem_undo_range() looks up a batch of entries and calls shmem_free_swap() for each swap entry. Concurrently swapping in a folio that is smaller than the swap entry splits the entry. The first piece keeps the value of the original entry, so shmem_free_swap() only frees that piece and reports success. The loop then continues with the next entry of the batch, skipping the remaining pieces:

    hole punch                        read()
    ==========                        ======
    find_get_entries()
      index 192: swap, order 6
      index 256: swap, order 6
                                      shmem_swapin_folio(), index 200
                                        shmem_split_large_entry()
    shmem_free_swap(), index 192
      order 0 by now: frees 1 page
    shmem_free_swap(), index 256
      /* 193 to 255 are left behind */

While truncate scans again until nothing is left, a hole punch only makes a single pass and does not revisit these entries.

Consequently, punching a hole into a shmem/tmpfs file with large swap entries can leave old data behind if it races with a read of that range:
fallocate() succeeds, but later reads return the old data instead of zeroes, and the swap space stays in use.

Let's fix it by letting shmem_free_swap() return the number of pages the swap entry covered, and looking up the remaining entries again starting at the first index that was not freed.

As the first loop in shmem_undo_range() already frees all swap entries within the range, these additional lookups are rare.

This has low urgency, as the race is hard to hit.

---
 mm/shmem.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)
mm/shmem.c +16 -5
index 57eaa867028ef..a302ec07b36fd 100644
@@ -1207,9 +1207,11 @@ static void shmem_delete_from_page_cache(struct folio *folio, void *radswap)
 
 /*
  * Remove a swap entry or swapin-error marker wholly within [index, end].
- * Return whether it was removed, counting freed swap pages in nr_swaps_freed.
+ * Return the number of pages the entry covered, or 0 if it was not removed.
+ * Only a swap entry holds swap slots: their number is added to
+ * nr_swaps_freed.
  */
-static bool shmem_free_swap(struct address_space *mapping,
+static unsigned int shmem_free_swap(struct address_space *mapping,
 		pgoff_t index, pgoff_t end, void *radswap, long *nr_swaps_freed)
 {
 	XA_STATE(xas, &mapping->i_pages, index);
@@ -1474,12 +1476,15 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,
 			folio = fbatch.folios[i];
 
 			if (xa_is_value(folio)) {
+				unsigned int nr_pages;
 				int order;
 
 				if (unfalloc)
 					continue;
-				if (!shmem_free_swap(mapping, indices[i], end - 1,
-						     folio, &nr_swaps_freed)) {
+				nr_pages = shmem_free_swap(mapping, indices[i],
+							   end - 1, folio,
+							   &nr_swaps_freed);
+				if (!nr_pages) {
 					pgoff_t base = indices[i];
 
 					order = shmem_confirm_swap(mapping, indices[i],
@@ -1500,7 +1505,13 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,
 					index = base;
 					break;
 				}
-				continue;
+				/*
+				 * A swapin may have split the entry after the
+				 * lookup, so only a part of it might have been
+				 * removed. Look up the rest.
+				 */
+				index = indices[i] + nr_pages;
+				break;
 			}
 
 			folio_lock(folio);
Signature · 1 line
2.56.1
author maintainer
#3 lore raw

PATCH v2 3/31 mm/shmem: reject userfaultfd fills during hole punch

In reply to David Hildenbrand (Arm)

While punching a shmem/tmpfs hole, regular page faults in the range wait for the hole punch to finish, but UFFDIO_COPY, UFFDIO_ZEROPAGE and UFFDIO_CONTINUE keep mapping pages into it. The hole punch must then repeatedly walk the file's VMAs to unmap these pages, while holding i_rwsem.

Consequently, punching a hole can become very slow if userfaultfd keeps filling the range, blocking other writers. Any user that can read the file can trigger that through a MAP_PRIVATE mapping and UFFDIO_CONTINUE.

Let's fix it by making UFFDIO_COPY, UFFDIO_ZEROPAGE and UFFDIO_CONTINUE return -EAGAIN when faults in the range are blocked, so user space can retry, instead of waiting in the uffd code.

Returning -EAGAIN simplifies the implementation. These ioctls already return -EAGAIN, including before making any progress: for example, UFFDIO_CONTINUE can encounter this when khugepaged removes a shmem page table concurrently.

QEMU, for example, prevents concurrent RAM discards and page placement during incoming postcopy entirely. Applications that allow concurrent hole punching and do not handle -EAGAIN could be affected, although existing races would already require proper -EAGAIN handling.

The existing uffd code already handles partial progress and wakes resolved faults properly.

Share the range check with shmem_falloc_wait() and preserve -EAGAIN from the filesystem in the UFFDIO_CONTINUE path.

This has medium urgency, as unprivileged users can make a hole punch, and writers of the file, stall for minutes.

---
 mm/shmem.c       | 33 +++++++++++++++++++++++++++++----
 mm/userfaultfd.c |  3 +++
 2 files changed, 32 insertions(+), 4 deletions(-)
mm/shmem.c +29 -4
index a302ec07b36fd..7dfef65cfdbc4 100644
@@ -2973,6 +2973,15 @@ static int synchronous_wake_function(wait_queue_entry_t *wait,
 	return ret;
 }
 
+static bool __shmem_faults_blocked(struct inode *inode, pgoff_t pgoff)
+{
+	struct shmem_falloc *falloc = inode->i_private;
+
+	lockdep_assert_held(&inode->i_lock);
+	return falloc && falloc->waitq &&
+	       pgoff >= falloc->start && pgoff < falloc->next;
+}
+
 /*
  * Trinity finds that probing a hole which tmpfs is punching can
  * prevent the hole-punch from ever completing: which in turn
@@ -2998,10 +3007,7 @@ static vm_fault_t shmem_falloc_wait(struct vm_fault *vmf, struct inode *inode)
 
 	spin_lock(&inode->i_lock);
 	shmem_falloc = inode->i_private;
-	if (shmem_falloc &&
-	    shmem_falloc->waitq &&
-	    vmf->pgoff >= shmem_falloc->start &&
-	    vmf->pgoff < shmem_falloc->next) {
+	if (__shmem_faults_blocked(inode, vmf->pgoff)) {
 		wait_queue_head_t *shmem_falloc_waitq;
 		DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
 
@@ -3492,6 +3498,19 @@ static struct folio *shmem_mfill_folio_alloc(struct vm_area_struct *vma,
 	return folio;
 }
 
+static bool shmem_faults_blocked(struct inode *inode, pgoff_t pgoff)
+{
+	bool blocked;
+
+	if (likely(!READ_ONCE(inode->i_private)))
+		return false;
+
+	spin_lock(&inode->i_lock);
+	blocked = __shmem_faults_blocked(inode, pgoff);
+	spin_unlock(&inode->i_lock);
+	return blocked;
+}
+
 static int shmem_mfill_filemap_add(struct folio *folio,
 				   struct vm_area_struct *vma,
 				   unsigned long addr)
@@ -3502,6 +3521,9 @@ static int shmem_mfill_filemap_add(struct folio *folio,
 	gfp_t gfp = mapping_gfp_mask(mapping);
 	int err;
 
+	if (shmem_faults_blocked(inode, pgoff))
+		return -EAGAIN;
+
 	__folio_set_locked(folio);
 	__folio_set_swapbacked(folio);
 
@@ -3541,6 +3563,9 @@ static struct folio *shmem_get_folio_noalloc(struct inode *inode, pgoff_t pgoff)
 	struct folio *folio;
 	int err;
 
+	if (shmem_faults_blocked(inode, pgoff))
+		return ERR_PTR(-EAGAIN);
+
 	err = shmem_get_folio(inode, pgoff, 0, &folio, SGP_NOALLOC);
 	if (err)
 		return ERR_PTR(err);
mm/userfaultfd.c +3 -0
index 65f7399e79b65..d7a9ca70fb954 100644
@@ -683,6 +683,9 @@ static int mfill_atomic_pte_continue(struct mfill_state *state)
 	}
 
 	folio = ops->get_folio_noalloc(inode, pgoff);
+	/* Preserve retry requests from the filesystem. */
+	if (IS_ERR(folio) && PTR_ERR(folio) == -EAGAIN)
+		return -EAGAIN;
 	/* Our caller expects us to return -EFAULT if we failed to find folio */
 	if (IS_ERR_OR_NULL(folio))
 		return -EFAULT;
Signature · 1 line
2.56.1
author maintainer
#4 lore raw

PATCH v2 4/31 mm/shmem: fix commit limit bypass with very large shmem sizes

In reply to David Hildenbrand (Arm)

VM_ACCT() uses PAGE_ALIGN() on a loff_t, a signed type, which overflows for sizes in the last page up to LLONG_MAX (MAX_LFS_FILESIZE on 64-bit).

With the default shmmax and shmall, userspace can trigger this through shmget(IPC_PRIVATE, LLONG_MAX, IPC_CREAT).

Consequently, the resulting negative count makes __vm_enough_memory() succeed and lowers vm_committed_as such that it will go negative. This effectively disables the commit limit with vm.overcommit_memory = 2 for as long as the shmem file exists.

Let's fix it by avoiding PAGE_ALIGN() and just using DIV_ROUND_UP_POW2(), which cannot overflow. We now reject such problematic sizes with ENOMEM, like any other size above the limit.

On 32-bit, VM_ACCT() can still return numbers that don't fit into the long that __vm_enough_memory() consumes. However, only ftruncate() to 8 TiB or more, through an fd obtained via /proc/$PID/map_files for a shared anonymous mapping, can trigger that, which requires CAP_SYS_ADMIN or CAP_CHECKPOINT_RESTORE. So we'll leave that alone for now.

This has low urgency, as it only affects systems with vm.overcommit_memory = 2.

Fixes 09cbfeaf1a5a ("mm, fs: get rid of PAGE_CACHE_* and page_cache_{get,release} macros")
---
 mm/shmem.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/shmem.c +1 -1
index 7dfef65cfdbc4..58b337efe7b02 100644
@@ -88,7 +88,7 @@ static struct vfsmount *shm_mnt __ro_after_init;
 
 #include "internal.h"
 
-#define VM_ACCT(size)    (PAGE_ALIGN(size) >> PAGE_SHIFT)
+#define VM_ACCT(size)    DIV_ROUND_UP_POW2(size, PAGE_SIZE)
 
 /* Pretend that each entry is of this size in directory's i_size */
 #define BOGO_DIRENT_SIZE 20
Signature · 1 line
2.56.1
author maintainer
#5 lore raw

PATCH v2 5/31 mm/shmem: don't pin inodes with eviction held off in the huge shrinker

In reply to David Hildenbrand (Arm)

shmem_unuse() disallows eviction of an inode while swapping in its pages, and shmem_evict_inode() waits until eviction is allowed again.

However, swapping in folios will end up allocating memory with __GFP_FS, possibly triggering direct reclaim, where the superblock shrinkers can drop the last reference to that very inode.

For example, shmem_unused_huge_shrink() takes and drops an inode reference to split large folios beyond i_size:

    swapoff                             another task
    =======                             ============
    shmem_unuse()
      shmem_disallow_eviction()
      shmem_swapin_folio()
        direct reclaim
          shmem_unused_huge_shrink()
            igrab()
                                        unlink(), close()
            iput()
              shmem_evict_inode()
                waits for eviction to be allowed

Consequently, swapoff can deadlock against itself.

Let's fix it by not pinning inodes whose eviction is disallowed in shmem_unused_huge_shrink(), effectively skipping them in this reclaim pass. Within shmem, shmem_unused_huge_shrink() is the only place where reclaim takes and drops a temporary reference to a shmem inode.

We could also avoid the deadlock by swapping in under NOFS scope in shmem_unuse(). However, allocating a lot of folios under NOFS does not sound like the right approach.

This has low urgency, as the race is hard to hit and swapoff is privileged.

Fixes af53d3e9e040 ("mm: swapoff: shmem_unuse() stop eviction without igrab()")
---
 mm/shmem.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
mm/shmem.c +10 -0
index 58b337efe7b02..798581db29853 100644
@@ -884,6 +884,16 @@ static enum lru_status shmem_unused_huge_isolate(struct list_head *item,
 	if (!spin_trylock(&info->lock))
 		return LRU_SKIP;
 
+	/*
+	 * Do not grab temporary inode references if eviction is disallowed, as
+	 * we might later put the last remaining one and deadlock (e.g.,
+	 * swapoff).
+	 */
+	if (atomic_read(&info->stop_eviction)) {
+		spin_unlock(&info->lock);
+		return LRU_SKIP;
+	}
+
 	/* pin the inode */
 	inode = igrab(&info->vfs_inode);
 	/* inode is about to be evicted */
Signature · 1 line
2.56.1
author maintainer
#6 lore raw

PATCH v2 6/31 mm/shmem: seal the size of SysV and shared anon files

In reply to David Hildenbrand (Arm)

A process can resize the underlying shmem file of a SysV shm segment or of a shared anonymous mapping through /proc/<pid>/map_files.

We account these files by their size when creating them and unaccount them by their size when destroying them, so resizing them can underflow vm_committed_as and the RLIMIT_MEMLOCK count of SHM_LOCK, and add pages that are charged to neither.

Consequently, an underflowed vm_committed_as lets the whole system commit memory beyond the limit of vm.overcommit_memory=2, and the RLIMIT_MEMLOCK underflow triggers a WARN_ON_ONCE().

Since commit 77142517990f ("shmem: update memory reservation on truncate") we adjust the commit charge on truncation, but not when writing or fallocating beyond EOF, and we never adjust the RLIMIT_MEMLOCK count.

Let's fix it by sealing these files against growing and shrinking when creating them instead, similar to what is being done for SysV segments on hugetlbfs [1].

Truncating such files and writing or fallocating to them beyond EOF will now fail with EPERM, and F_GET_SEALS will now report these two seals. As udmabuf requires F_SEAL_SHRINK, it will now accept these files, which shouldn't matter, as obtaining an fd for them requires CAP_CHECKPOINT_RESTORE.

It's highly unlikely that any user would rely on this: e.g., CRIU only maps and reads these files through /proc/<pid>/map_files, and only resizes memfds. A search didn't reveal any other relevant cases.

This has low urgency, as it requires CAP_CHECKPOINT_RESTORE.

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

---
 include/linux/shmem_fs.h | 11 +++++++++++
 ipc/shm.c                |  2 ++
 mm/shmem.c               |  6 +++++-
 3 files changed, 18 insertions(+), 1 deletion(-)
include/linux/shmem_fs.h +11 -0
index f89b4b1511332..9dc9956852dac 100644
@@ -3,6 +3,7 @@
 #define __SHMEM_FS_H
 
 #include <linux/file.h>
+#include <linux/fcntl.h>
 #include <linux/swap.h>
 #include <linux/mempolicy.h>
 #include <linux/pagemap.h>
@@ -119,6 +120,11 @@ extern int shmem_lock(struct file *file, int lock, struct ucounts *ucounts);
 #ifdef CONFIG_SHMEM
 bool shmem_file(struct file *file);
 bool shmem_mapping(const struct address_space *mapping);
+
+static inline void shmem_seal_file_size(struct file *file)
+{
+	SHMEM_I(file_inode(file))->seals |= F_SEAL_GROW | F_SEAL_SHRINK;
+}
 #else
 static inline bool shmem_file(struct file *file)
 {
@@ -129,7 +135,12 @@ static inline bool shmem_mapping(const struct address_space *mapping)
 {
 	return false;
 }
+
+static inline void shmem_seal_file_size(struct file *file)
+{
+}
 #endif /* CONFIG_SHMEM */
+
 void shmem_unlock_mapping(struct address_space *mapping);
 struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
 					pgoff_t index, gfp_t gfp_mask);
ipc/shm.c +2 -0
index 83ac223352ba5..d868d1daa45d9 100644
@@ -762,6 +762,8 @@ static int newseg(struct ipc_namespace *ns, struct ipc_params *params)
 		if  (has_no_reserve && sysctl_overcommit_memory != OVERCOMMIT_NEVER)
 			vma_flags_set(&acctflag, VMA_NORESERVE_BIT);
 		file = shmem_kernel_file_setup(name, size, acctflag);
+		if (!IS_ERR(file))
+			shmem_seal_file_size(file);
 	}
 	error = PTR_ERR(file);
 	if (IS_ERR(file))
mm/shmem.c +5 -1
index 798581db29853..5536371e344ac 100644
@@ -6290,6 +6290,7 @@ static struct file *__shmem_zero_setup(unsigned long start, unsigned long end,
 		vma_flags_t flags)
 {
 	loff_t size = end - start;
+	struct file *file;
 
 	/*
 	 * Cloning a new file under mmap_lock leads to a lock ordering conflict
@@ -6297,7 +6298,10 @@ static struct file *__shmem_zero_setup(unsigned long start, unsigned long end,
 	 * accessible to the user through its mapping, use S_PRIVATE flag to
 	 * bypass file security, in the same way as shmem_kernel_file_setup().
 	 */
-	return shmem_kernel_file_setup("dev/zero", size, flags);
+	file = shmem_kernel_file_setup("dev/zero", size, flags);
+	if (!IS_ERR(file))
+		shmem_seal_file_size(file);
+	return file;
 }
 
 /**
Signature · 1 line
2.56.1
author maintainer
#7 lore raw

PATCH v2 7/31 mm/khugepaged: check the VMA before walking page tables when collapsing

In reply to David Hildenbrand (Arm)

MADV_COLLAPSE and khugepaged can end up traversing page tables of a VMA through find_pmd_or_thp_or_none() before verifying that the VMA is still as expected.

Calling find_pmd_or_thp_or_none() on a mapping with PUDs (hugetlb/dax/PFNMAP) is invalid, as it treats every present PUD entry as a pointer to a PMD table.

Consequently, we can end up interpreting the memory mapped by a PUD leaf as a PMD table.

Let's fix it by performing the thp_vma_allowable_order() check before the page table walk.

Further, let's also make find_pmd_or_thp_or_none() harder to get wrong by rejecting any pgd/p4d/pud leaves.

This has high urgency, as unprivileged users can trigger it, although getting relevant PUD mappings (e.g., hugetlb) should be rather uncommon in most setups.

---
 mm/khugepaged.c | 10 +++++-----
 mm/rmap.c       |  6 +++---
 2 files changed, 8 insertions(+), 8 deletions(-)
mm/khugepaged.c +5 -5
index d7fd5e4717832..6658c1da02903 100644
@@ -1895,11 +1895,6 @@ static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsign
 	    !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE))
 		return SCAN_VMA_CHECK;
 
-	/* Fast check before locking page if already PMD-mapped */
-	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
-	if (result == SCAN_PMD_MAPPED)
-		return result;
-
 	/*
 	 * If we are here, we've succeeded in replacing all the native pages
 	 * in the page cache with a single hugepage. If a mm were to fault-in
@@ -1910,6 +1905,11 @@ static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsign
 	if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_FORCED_COLLAPSE, PMD_ORDER))
 		return SCAN_VMA_CHECK;
 
+	/* Quick check if already PMD-mapped before locking the folio. */
+	result = find_pmd_or_thp_or_none(mm, haddr, &pmd);
+	if (result == SCAN_PMD_MAPPED)
+		return result;
+
 	/*
 	 * Keep pmd pgtable while the uffd bit is in use; see comment in
 	 * retract_page_tables().
mm/rmap.c +3 -3
index 06dcc83e72d10..1a96b072e37b9 100644
@@ -888,15 +888,15 @@ pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
 	pmd_t *pmd = NULL;
 
 	pgd = pgd_offset(mm, address);
-	if (!pgd_present(*pgd))
+	if (!pgd_present(*pgd) || pgd_leaf(*pgd))
 		goto out;
 
 	p4d = p4d_offset(pgd, address);
-	if (!p4d_present(*p4d))
+	if (!p4d_present(*p4d) || p4d_leaf(*p4d))
 		goto out;
 
 	pud = pud_offset(p4d, address);
-	if (!pud_present(*pud))
+	if (!pud_present(*pud) || pud_leaf(*pud))
 		goto out;
 
 	pmd = pmd_offset(pud, address);
Signature · 1 line
2.56.1
author maintainer
#8 lore raw

PATCH v2 8/31 mm/khugepaged: flush file after unlocking folios in collapse_file()

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

collapse_file() calls filemap_flush() when it encounters a dirty folio in a file that is not open for writing. At that point, source folios earlier in the range are still locked. The writable-open check is racy: a writer can open the file after the check.

On ext4, the flush may need a journal handle, while EXT4_IOC_MOVE_EXT takes a journal handle before locking folios, and a journal commit blocks new handles while waiting for existing handles to be released.

Consequently, we can deadlock: collapse_file() waits for a handle, the commit waits for extent movement to finish, and extent movement waits for a source folio lock.

Let's fix it by deferring filemap_flush() until rollback has unlocked all source folios.

This has medium urgency, as it can deadlock ext4 in some scenarios.

Fixes 75f360696ce9 ("mm/thp: flush file for !is_shmem PageDirty() case in collapse_file()")
[ david: rework code; simplify comments and description ]
---
 mm/khugepaged.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
mm/khugepaged.c +6 -2
index 6658c1da02903..83471396bd996 100644
@@ -2273,6 +2273,7 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	int nr_none = 0;
 	bool do_readahead = false;
 	bool readahead_done = false;
+	bool any_non_shmem_dirty = false;
 
 	/*
 	 * MADV_COLLAPSE ignores shmem huge config, so do not check shmem
@@ -2377,8 +2378,7 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 				 * forcing writeback in loop.
 				 */
 				xas_unlock_irq(&xas);
-				if (!inode_is_open_for_write(mapping->host))
-					filemap_flush(mapping);
+				any_non_shmem_dirty = true;
 				result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
 				goto xa_unlocked;
 			} else if (folio_test_writeback(folio)) {
@@ -2712,6 +2712,10 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	}
 out_put:
 	folio_put(new_folio);
+
+	/* Flush after unlocking all folios. */
+	if (any_non_shmem_dirty && !inode_is_open_for_write(mapping->host))
+		filemap_flush(mapping);
 out:
 	VM_BUG_ON(!list_empty(&pagelist));
 	trace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
Signature · 1 line
2.56.1
author maintainer
#9 lore raw

PATCH v2 9/31 mm/khugepaged: check for uffd outside the i_pages lock

In reply to David Hildenbrand (Arm)

collapse_file() walks the VMAs mapping a shmem range to check for UFFD missing registrations before filling holes. It does this with the i_pages lock held and interrupts disabled.

Consequently, a large number of mappings can cause excessive interrupt latency.

Let's fix it by moving the walk before taking the i_pages lock. Hold i_mmap_rwsem for read until the retry entries are stored, and take it for write when registering UFFD missing mode on a file-backed VMA. This prevents new missing-mode registrations between checking the VMAs and installing the retry entries.

Move hole counting and retry-entry insertion into
collapse_file_mark_holes().

Also pass end - 1 to mapping_rmap_tree_foreach(), which takes an inclusive last index. Otherwise, a UFFD missing-mode registration immediately beyond the collapse range can incorrectly prevent collapse.

This has medium urgency, as unprivileged users can trigger it.

---
 mm/khugepaged.c  | 61 ++++++++++++++++++++++++++++++++------------------------
 mm/userfaultfd.c | 12 +++++++++++
 2 files changed, 47 insertions(+), 26 deletions(-)
mm/khugepaged.c +35 -26
index 83471396bd996..1c439b88879d3 100644
@@ -2233,6 +2233,25 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
 	i_mmap_unlock_read(mapping);
 }
 
+static int collapse_file_mark_holes(struct xa_state *xas,
+		pgoff_t start, pgoff_t end)
+{
+	pgoff_t index;
+	int nr_none = 0;
+
+	xas_set(xas, start);
+	for (index = start; index < end; index++) {
+		if (xas_next(xas))
+			continue;
+		xas_store(xas, XA_RETRY_ENTRY);
+		if (xas_error(xas))
+			return xas_error(xas);
+		nr_none++;
+	}
+
+	return nr_none;
+}
+
 /**
  * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
  *
@@ -2248,8 +2267,8 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
  *    + swap/gup in pages if necessary;
  *  - copy data to new page
  *  - handle shmem holes
- *    + re-validate that holes weren't filled by someone else
  *    + check for userfaultfd
+ *    + re-validate that holes weren't filled by someone else
  *  - finalize updates to the page cache;
  *  - if replacing succeeds:
  *    + unlock huge page;
@@ -2556,27 +2575,9 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 
 	if (nr_none) {
 		struct vm_area_struct *vma;
-		int nr_none_check = 0;
+		int nr_none_check;
 
 		i_mmap_lock_read(mapping);
-		xas_lock_irq(&xas);
-
-		xas_set(&xas, start);
-		for (index = start; index < end; index++) {
-			if (!xas_next(&xas)) {
-				xas_store(&xas, XA_RETRY_ENTRY);
-				if (xas_error(&xas)) {
-					result = SCAN_STORE_FAILED;
-					goto immap_locked;
-				}
-				nr_none_check++;
-			}
-		}
-
-		if (nr_none != nr_none_check) {
-			result = SCAN_PAGE_FILLED;
-			goto immap_locked;
-		}
 
 		/*
 		 * If userspace observed a missing page in a VMA with
@@ -2587,19 +2588,27 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 		 * guarantees that the kernel doesn't fill a missing
 		 * page with a zero page, so they don't matter here.
 		 *
-		 * Any userfaultfds registered after this point will
-		 * not be able to observe any missing pages due to the
-		 * previously inserted retry entries.
+		 * i_mmap_rwsem syncs against concurrent userfaultfd MISSING
+		 * registration in userfaultfd_set_ctx(). We replace holes with
+		 * retry entries before dropping i_mmap_rwsem, so later
+		 * registrations cannot observe missing pages.
 		 */
-		mapping_rmap_tree_foreach(vma, mapping, start, end) {
+		mapping_rmap_tree_foreach(vma, mapping, start, end - 1) {
 			if (userfaultfd_missing(vma)) {
+				i_mmap_unlock_read(mapping);
 				result = SCAN_EXCEED_NONE_PTE;
-				goto immap_locked;
+				goto rollback;
 			}
+			cond_resched();
 		}
 
-immap_locked:
+		xas_lock_irq(&xas);
+		nr_none_check = collapse_file_mark_holes(&xas, start, end);
 		i_mmap_unlock_read(mapping);
+		if (nr_none_check < 0)
+			result = SCAN_STORE_FAILED;
+		else if (nr_none != nr_none_check)
+			result = SCAN_PAGE_FILLED;
 		if (result != SCAN_SUCCEED) {
 			xas_set(&xas, start);
 			for (index = start; index < end; index++) {
mm/userfaultfd.c +12 -0
index d7a9ca70fb954..af94600086213 100644
@@ -2194,10 +2194,22 @@ static void userfaultfd_set_ctx(struct vm_area_struct *vma,
 				struct userfaultfd_ctx *ctx,
 				vm_flags_t vm_flags)
 {
+	struct address_space *mapping = NULL;
+
 	vma_start_write(vma);
+
+	/* Sync with collapse_file() scanning for VM_UFFD_MISSING VMAs. */
+	if (vma->vm_file && (vm_flags & VM_UFFD_MISSING)) {
+		mapping = vma->vm_file->f_mapping;
+		i_mmap_lock_write(mapping);
+	}
+
 	vma->vm_userfaultfd_ctx = (struct vm_userfaultfd_ctx){ctx};
 	userfaultfd_set_vm_flags(vma,
 				 (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags);
+
+	if (mapping)
+		i_mmap_unlock_write(mapping);
 }
 
 static void userfaultfd_reset_ctx(struct vm_area_struct *vma)
Signature · 1 line
2.56.1
author maintainer
#10 lore raw

PATCH v2 10/31 mm/khugepaged: don't wait for userfaultfd

In reply to David Hildenbrand (Arm)

khugepaged and MADV_COLLAPSE can end up triggering userfaultfd faults if MADV_DONTNEED + UFFDIO_WRITEPROTECT races with collapse on a VMA registered for both MISSING and WP mode. The fault flags are FAULT_FLAG_ALLOW_RETRY alone, so handle_userfault() sleeps in TASK_UNINTERRUPTIBLE.

Consequently, khugepaged or the MADV_COLLAPSE caller can sleep forever, if user space never resolves the fault.

Let's fix it by rejecting anything non-present that is uffd related by checking pte_swp_uffd_any(), just like in collapse_scan_anon().

This has medium urgency, as unprivileged users can make khugepaged sleep forever.

---
 mm/khugepaged.c | 7 +++++++
 1 file changed, 7 insertions(+)
mm/khugepaged.c +7 -0
index 1c439b88879d3..2e8e5b94ce8fc 100644
@@ -1185,6 +1185,13 @@ static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm,
 			goto out;
 		}
 
+		if (pte_swp_uffd_any(vmf.orig_pte)) {
+			pte_unmap(pte);
+			mmap_read_unlock(mm);
+			result = SCAN_PTE_UFFD;
+			goto out;
+		}
+
 		vmf.pte = pte;
 		vmf.ptl = ptl;
 		ret = do_swap_page(&vmf);
Signature · 1 line
2.56.1
author maintainer
#11 lore raw

PATCH v2 11/31 mm/khugepaged: store new folio before adding it to LRU

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

collapse_file() adds the new folio to the LRU before adding it to the page cache. If SHM_LOCKed, the folio will be added to the unevictable LRU. A concurrent SHM_UNLOCK walks the page cache to make all folios evictable again, and can miss the new folio:

    collapse_file()                  SHM_UNLOCK
    ===============                  ==========
    folio_add_lru(new_folio)
      /* unevictable */
                                     shmem_unlock_mapping()
                                       /* misses new_folio */
    xas_store(&xas, new_folio)

Consequently, if SHM_UNLOCK races with a collapse in a SHM_LOCKed SysV shared memory segment, the new folio can get stranded on the unevictable LRU.

Let's improve it by adding the new folio to the LRU only after adding it to the page cache.

There is a more fundamental race that must be sorted out to fix this
completely: check_move_unevictable_folios() skips folios that are not on the LRU without taking the lruvec lock, while lru_add() checks evictability before marking the folio as being on the LRU. That affects all folios that are added to the LRU, and requires a more generic fix.

This has low urgency, as it only strands a folio on the unevictable LRU. No need to CC stable.

Fixes a2e17cc2efc7 ("mm/khugepaged: maintain page cache uptodate flag")
[ david: simplify description and comment ]
---
 mm/khugepaged.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
mm/khugepaged.c +7 -1
index 2e8e5b94ce8fc..a2d13d989a558 100644
@@ -2648,7 +2648,6 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 
 	if (is_shmem)
 		folio_mark_dirty(new_folio);
-	folio_add_lru(new_folio);
 
 	/* Join all the small entries into a single multi-index entry. */
 	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
@@ -2656,6 +2655,13 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	WARN_ON_ONCE(xas_error(&xas));
 	xas_unlock_irq(&xas);
 
+	/*
+	 * If SHM_LOCKed, the folio will be added to the unevictable LRU. Do
+	 * that after adding it to the page cache, so a concurrent SHM_UNLOCK
+	 * reliably finds it to make it evictable again.
+	 */
+	folio_add_lru(new_folio);
+
 	/*
 	 * Remove pte page tables, so we can re-fault the page as huge.  A
 	 * caller that wants the PMD mapped now is told to go and do that.
Signature · 1 line
2.56.1
author maintainer
#12 lore raw

PATCH v2 12/31 mm/khugepaged: check PMD support with the folios locked

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

A collapse that races with chattr +j on an ext4 file can store a PMD folio in a mapping whose maximum folio order no longer allows it, as the maximum folio order can change once the page cache is empty.

ext4_change_inode_journal_flag() empties the page cache and then lowers the maximum folio order under the invalidate_lock. But collapsing only checks early, in file_thp_enabled() under the mmap_lock, and collapse_file() merely has a VM_WARN_ON_ONCE() that the same race triggers:

    madvise_collapse()                ext4_change_inode_journal_flag()
    ==================                ================================
    mmap_read_lock()
    file_thp_enabled()
    mmap_read_unlock()
                                      filemap_invalidate_lock()
                                      truncate_pagecache()
                                      ext4_set_inode_mapping_order()
                                      filemap_invalidate_unlock()
    collapse_file()
      page_cache_sync_readahead()
      xas_store(new_folio)

Consequently, on a nodelalloc mount, a write fault on that PMD folio runs out of journal credits, resulting in SIGBUS and an ext4 file system error.

Let's fix it by checking again once we have the page cache folios locked, stabilizing the maximum supported folio order. A MADV_COLLAPSE that loses the race now fails with -EINVAL, like one that starts after the chattr.

While at it, drop the shmem related TODO+comment and just check shmem as well, as proposed by [1]. This change was made possible by commit eb92d97f7e6a ("Revert "tmpfs: don't enable large folios if not supported""), which went into 7.2 along with the commit we are fixing.

This has low urgency, as chattr +j requires CAP_SYS_RESOURCE.

---
 mm/khugepaged.c | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)
mm/khugepaged.c +11 -10
index a2d13d989a558..de00e0d2a6d5f 100644
@@ -2301,13 +2301,6 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	bool readahead_done = false;
 	bool any_non_shmem_dirty = false;
 
-	/*
-	 * MADV_COLLAPSE ignores shmem huge config, so do not check shmem
-	 *
-	 * TODO: once shmem always calls mapping_set_large_folios() on its
-	 * mapping, the shmem check can be removed.
-	 */
-	VM_WARN_ON_ONCE(!is_shmem && !mapping_pmd_folio_support(mapping));
 	VM_WARN_ON_ONCE(start & (HPAGE_PMD_NR - 1));
 
 	result = alloc_charge_folio(&new_folio, mm, cc, HPAGE_PMD_ORDER);
@@ -2543,9 +2536,17 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	 */
 	try_to_unmap_flush();
 
-	if (result == SCAN_SUCCEED && nr_none &&
-	    !shmem_charge(mapping->host, nr_none))
-		result = SCAN_FAIL;
+	if (result == SCAN_SUCCEED) {
+		/*
+		 * A filesystem can lower the maximum folio order only once the
+		 * page cache is empty. Recheck now that all old folios are
+		 * locked and still in the page cache.
+		 */
+		if (!mapping_pmd_folio_support(mapping))
+			result = SCAN_FAIL;
+		else if (nr_none && !shmem_charge(mapping->host, nr_none))
+			result = SCAN_FAIL;
+	}
 	if (result != SCAN_SUCCEED) {
 		nr_none = 0;
 		goto rollback;
Signature · 1 line
2.56.1
author maintainer
#13 lore raw

PATCH v2 13/31 mm/khugepaged: stop MADV_COLLAPSE on a fatal signal

In reply to David Hildenbrand (Arm)

A task that gets a fatal signal during MADV_COLLAPSE keeps collapsing the rest of the range. Consequently, the exit of the task can be delayed for a while for a large range.

Let's fix it by checking for a fatal signal before each PMD, simply breaking out of the loop. User space will never see the return value, so no need to return -EINTR.

This has low urgency, as it only delays the exit of the task. No need to CC stable.

---
 mm/khugepaged.c | 4 ++++
 1 file changed, 4 insertions(+)
mm/khugepaged.c +4 -0
index de00e0d2a6d5f..1c9fb79abd627 100644
@@ -4,6 +4,7 @@
 #include <linux/mm.h>
 #include <linux/sched.h>
 #include <linux/sched/mm.h>
+#include <linux/sched/signal.h>
 #include <linux/mmu_notifier.h>
 #include <linux/rmap.h>
 #include <linux/swap.h>
@@ -3368,6 +3369,9 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
 	for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
 		enum scan_result result = SCAN_FAIL;
 
+		if (fatal_signal_pending(current))
+			break;
+
 		if (mmap_unlocked) {
 			cond_resched();
 			mmap_read_lock(mm);
Signature · 1 line
2.56.1
author maintainer
#14 lore raw

PATCH v2 14/31 mm/huge_memory: split huge zero PMDs on unshare faults

In reply to David Hildenbrand (Arm)

FAULT_FLAG_UNSHARE breaks COW without making the mapping writable. Unlike FAULT_FLAG_WRITE, it must leave write protection in place so that a later write still faults.

A read-only long-term pin can trigger an unshare fault on a huge zero PMD. do_huge_zero_wp_pmd() treats it as a write fault: it marks the replacement THP dirty, makes it writable if the VMA allows writes, and drops any UFFD write protection.

Consequently, a later write no longer faults, which, for example, bypasses UFFD write protection.

Let's fix it by returning VM_FAULT_FALLBACK for unshare faults, so the caller splits the PMD. The PTE fault path already handles unsharing while keeping the mapping read-only and preserving UFFD write protection and soft-dirty state.

This has low urgency, as it requires a read-only long-term pin of a huge zero PMD. No need to CC stable.

---
 mm/huge_memory.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
mm/huge_memory.c +5 -1
index f40875208b193..2c6dea7ac8354 100644
@@ -2186,6 +2186,10 @@ static vm_fault_t do_huge_zero_wp_pmd(struct vm_fault *vmf)
 	struct folio *folio;
 	vm_fault_t ret = 0;
 
+	/* map_anon_folio_pmd_pf() does not handle unsharing correctly yet. */
+	if (vmf->flags & FAULT_FLAG_UNSHARE)
+		return VM_FAULT_FALLBACK;
+
 	folio = vma_alloc_anon_folio_pmd(vma, vmf->address);
 	if (unlikely(!folio))
 		return VM_FAULT_FALLBACK;
@@ -2228,7 +2232,7 @@ vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf)
 		if (!(ret & VM_FAULT_FALLBACK))
 			return ret;
 
-		/* Fallback to splitting PMD if THP cannot be allocated */
+		/* Fall back to PTE level. */
 		goto fallback;
 	}
 
Signature · 1 line
2.56.1
author maintainer
#15 lore raw

PATCH v2 15/31 mm/huge_memory: don't map huge PFN entries if the arch restricts PFNs

In reply to David Hildenbrand (Arm)

change_huge_pmd() and change_huge_pud() temporarily invalidate huge entries, for example during mprotect(). The invalidated entry is not present, but still contains the PFN.

On x86 with L1TF, we invert the PFN of a not-present entry, which for a PFN at or above l1tf_pfn_limit() points into the lower half of the physical address space, where RAM might be. That's why pfn_modify_allowed() forbids such entries for unprivileged users. But we never check it when mapping huge PFN entries.

This was not a problem as long as only DAX used huge PFN mappings, where all PFNs have a memory map. But vfio-pci now maps BARs, which can be at or above the limit, with huge entries.

Consequently, an unprivileged user with access to such a BAR can make us temporarily create not-present entries that point at RAM, which is what the L1TF mitigation is supposed to prevent.

Let's fix it by not mapping huge PFN entries at all in vmf_insert_pfn_pmd() and vmf_insert_pfn_pud() if the architecture restricts PFN modifications, and fall back to PTEs instead. We clear PTEs instead of invalidating them when modifying them, and mprotect() already checks for PROT_NONE PTEs.

This only affects old CPUs that suffer from L1TF; not worth optimizing for.

This has low urgency, as it requires a CPU affected by L1TF and access to a vfio-pci device.

Fixes f9e54c3a2f5b ("vfio/pci: implement huge_fault support")
---
 mm/huge_memory.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
mm/huge_memory.c +14 -0
index 2c6dea7ac8354..1b8e90624299d 100644
@@ -1736,6 +1736,13 @@ vm_fault_t vmf_insert_pfn_pmd(struct vm_fault *vmf, unsigned long pfn,
 	if (unlikely(is_huge_zero_pfn(pfn)))
 		return VM_FAULT_SIGBUS;
 
+	/*
+	 * Disallow huge mappings if we cannot reliably temporarily invalidate
+	 * them later.
+	 */
+	if (arch_has_pfn_modify_check())
+		return VM_FAULT_FALLBACK;
+
 	pfnmap_setup_cachemode_pfn(pfn, &pgprot);
 
 	return insert_pmd(vma, addr, vmf->pmd, fop, pgprot, write);
@@ -1852,6 +1859,13 @@ vm_fault_t vmf_insert_pfn_pud(struct vm_fault *vmf, unsigned long pfn,
 	VM_WARN_ON_ONCE(vma_test_all(vma, VMA_PFNMAP_BIT, VMA_MIXEDMAP_BIT));
 	VM_WARN_ON_ONCE(vma_test(vma, VMA_PFNMAP_BIT) && vma_is_cow_mapping(vma));
 
+	/*
+	 * Disallow huge mappings if we cannot reliably temporarily invalidate
+	 * them later.
+	 */
+	if (arch_has_pfn_modify_check())
+		return VM_FAULT_FALLBACK;
+
 	pfnmap_setup_cachemode_pfn(pfn, &pgprot);
 
 	return insert_pud(vma, addr, vmf->pud, fop, pgprot, write);
Signature · 1 line
2.56.1
author maintainer
#16 lore raw

PATCH v2 16/31 mm/memory: don't clear a PUD leaf as bad in a zap

In reply to David Hildenbrand (Arm)

A zap can race with a page fault that installs a PUD leaf, for example with device-dax or VFIO huge pfnmaps: MADV_DONTNEED only holds the VMA lock in read mode, and unmap_mapping_range() only the i_mmap_rwsem in read mode.

zap_pud_range() reads the PUD entry multiple times without holding the PUD lock. If it first observes an empty entry, but a concurrent fault installs a leaf before pud_none_or_clear_bad(), pud_bad() will be true for the leaf, and pud_clear_bad() will clear it:

    zap_pud_range()                   __handle_mm_fault()
    ===============                   ===================
    pud_trans_huge(*pud) is false
                                      create_huge_pud()
                                        insert_pud()
                                          set_pud_at()
    pud_none_or_clear_bad()
      pud_bad(*pud) is true
      pud_clear_bad()

Consequently, this leaves a stale TLB entry behind, leaks the folio reference, etc. Worse, a concurrent zap_huge_pud() or __split_huge_pud() can then read the cleared entry, and drop the mapcount and a reference of an unrelated folio.

Let's fix it by reading the PUD entry once, and by reading it again only after we split the leaf or failed to zap it. Skip a PUD leaf just like an empty entry.

Note that, in contrast to zap_pmd_range(), there is no need to retry if we find a PUD leaf after we split the leaf or failed to zap it: there is no collapse that could move mapped PTEs into a PUD leaf, so such a leaf was installed by a concurrent fault.

Keep falling through after splitting a PUD leaf, so we would zap any page table that a split might install in the future.

This has medium urgency, as it can result in a use-after-free, but requires PUD mappings, such as device-dax or VFIO huge pfnmaps.

Fixes a00cc7d9dd93 ("mm, x86: add support for PUD-sized transparent hugepages")
---
 mm/memory.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
mm/memory.c +9 -3
index b794444db449f..60e07ab3306bc 100644
@@ -2147,21 +2147,27 @@ static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
 				unsigned long addr, unsigned long end,
 				struct zap_details *details)
 {
-	pud_t *pud;
+	pud_t *pud, pudval;
 	unsigned long next;
 
 	pud = pud_offset(p4d, addr);
 	do {
 		next = pud_addr_end(addr, end);
-		if (pud_trans_huge(*pud)) {
+		pudval = pudp_get(pud);
+		if (pud_trans_huge(pudval)) {
 			if (next - addr != HPAGE_PUD_SIZE)
 				split_huge_pud(vma, pud, addr);
 			else if (zap_huge_pud(tlb, vma, pud, addr))
 				goto next;
+			pudval = pudp_get(pud);
 			/* fall through */
 		}
-		if (pud_none_or_clear_bad(pud))
+		if (pud_none(pudval) || pud_trans_huge(pudval))
 			continue;
+		if (unlikely(pud_bad(pudval))) {
+			pud_clear_bad(pud);
+			continue;
+		}
 		next = zap_pmd_range(tlb, vma, pud, addr, next, details);
 next:
 		cond_resched();
Signature · 1 line
2.56.1
author maintainer
#17 lore raw

PATCH v2 17/31 mm/memory: drop the swap device ref before do_wp_page()

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

swapoff kills si->users and waits for the last put_swap_device() with wait_for_completion(). do_swap_page() currently holds its reference to the swap device until it returns to the caller. If it ends up calling into do_wp_page() and triggers uffd-wp, we will sleep in handle_userfault() until the user space handler has processed the event and woken up the thread:

    do_swap_page()                 swapoff
    ==============                 =======
    get_swap_device()
    set_ptes()
    folio_unlock()
    do_wp_page()
      handle_userfault()
        schedule()
                                   try_to_unuse() returns 0
                                   percpu_ref_kill(&p->users)
                                   wait_for_completion(&p->comp)
    put_swap_device()

Consequently, swapoff hangs until the user space handler resolves the fault.

Let's fix it by dropping the swap device reference before calling do_wp_page().

This has medium urgency, as an unprivileged process can make swapoff hang for as long as it likes, using a UFFD_USER_MODE_ONLY userfaultfd.

Fixes 2799e77529c2 ("swap: fix do_swap_page() race with swapoff")
[ david: minor code cleanups, adjust comment and description ]
---
 mm/memory.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/memory.c +3 -1
index 60e07ab3306bc..ec98704eb2202 100644
@@ -5396,10 +5396,12 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 	 * drop the marker for a non-exclusive page.
 	 */
 	if ((vmf->flags & FAULT_FLAG_WRITE) && !pte_write(pte) && !rwp_restore) {
+		/* do_wp_page() may wait for uffd, clean up first. */
+		put_swap_device(si);
 		ret |= do_wp_page(vmf);
 		if (ret & VM_FAULT_ERROR)
 			ret &= VM_FAULT_ERROR;
-		goto out;
+		return ret;
 	}
 
 	/* No need to invalidate - it was non-present before */
Signature · 1 line
2.56.1
author maintainer
#18 lore raw

PATCH v2 18/31 mm: consistently check MMF_UNSTABLE when populating in CoW mappings

In reply to David Hildenbrand (Arm)

The OOM reaper and process_mrelease() zap private mappings of a target MM, including CoW'ed anonymous folios. Re-populating these page table entries is bad: it will look like a memory corruption to anybody still accessing the MM. For example, a read fault could map a pagecache folio where the process previously mapped a CoW'ed anon folio.

We must consistently disallow populating page table entries in CoW mappings if MMF_UNSTABLE is set, and we must check under the page table lock.

We are still missing checks when populating empty page table entries in CoW mappings in:
- filemap_map_pages() (fault-around)
- do_set_pmd() (fault-around, MADV_COLLAPSE)
- the vmf_insert_*() helpers (fs DAX, drivers)
- UFFDIO_COPY, UFFDIO_ZEROPAGE, UFFDIO_CONTINUE and UFFDIO_MOVE

Let's fix it by adding these checks. To avoid duplicating code, add vma_may_populate_pgtable() and document it properly. Also extend the documentation of check_stable_address_space().

Also fix the check in finish_fault(), which must really happen under the page table lock to handle races with the OOM reaping correctly.

After reaping, populating page table entries in CoW mappings now consistently fails (e.g., with SIGBUS or -EFAULT).

At some point we should probably consistently just use vma_may_populate_pgtable() when populating; also, we can think about checking for the existence of an anon_vma instead of checking for CoW mappings. We should also make __oom_reap_task_mm() check for vma_is_cow_mapping() instead.

This has low urgency, as the target MM is about to go away anyway. No need to CC stable.

---
 include/linux/oom.h | 48 ++++++++++++++++++++++++++++++++++++++----------
 mm/filemap.c        |  9 +++++++++
 mm/huge_memory.c    | 14 ++++++++++++++
 mm/memory.c         | 30 ++++++++++++++++++++----------
 mm/userfaultfd.c    | 22 ++++++++++++++++++++++
 5 files changed, 103 insertions(+), 20 deletions(-)
include/linux/oom.h +38 -10
index 00da05d227e66..a3c16565160a5 100644
@@ -76,18 +76,28 @@ static inline bool tsk_is_oom_victim(struct task_struct * tsk)
 	return tsk->signal->oom_mm;
 }
 
-/*
- * Checks whether a page fault on the given mm is still reliable.
- * This is no longer true if the oom reaper started to reap the
- * address space which is reflected by MMF_UNSTABLE flag set in
- * the mm. At that moment any !shared mapping would lose the content
- * and could cause a memory corruption (zero pages instead of the
- * original content).
+/**
+ * check_stable_address_space - check whether the address space of an mm is
+ *				still stable
+ * @mm: the mm to check
+ *
+ * Checks whether a page fault on the given mm is still reliable. This is no
+ * longer true once the OOM reaper or process_mrelease() started reaping the
+ * address space, which is reflected by MMF_UNSTABLE being set in the mm. At
+ * that moment, any CoW mapping might have lost content, and populating an
+ * empty page table entry could cause memory corruption (for example, zero
+ * pages instead of the original content).
+ *
+ * Before populating an empty page table entry, use
+ * vma_may_populate_pgtable(), which performs this check only for CoW
+ * mappings. Call this function directly only where the mapping is guaranteed
+ * to be a CoW mapping, such as a private anonymous mapping, or where the
+ * check does not relate to a specific mapping.
  *
- * User should call this before establishing a page table entry for
- * a !shared mapping and under the proper page table lock.
+ * When populating a page table entry, call this under the page table lock,
+ * after checking that the entry is empty and before populating it.
  *
- * Return 0 when the PF is safe VM_FAULT_SIGBUS otherwise.
+ * Return: 0 if the address space is stable, VM_FAULT_SIGBUS otherwise.
  */
 static inline vm_fault_t check_stable_address_space(struct mm_struct *mm)
 {
@@ -96,6 +106,24 @@ static inline vm_fault_t check_stable_address_space(struct mm_struct *mm)
 	return 0;
 }
 
+/**
+ * vma_may_populate_pgtable - check whether empty page table entries may be
+ *			      populated
+ * @vma: the VMA to check
+ *
+ * Like check_stable_address_space(), but only performs the check for CoW
+ * mappings, as only these may have lost CoW'ed anonymous folios.
+ *
+ * Return: true if the empty page table entries may be populated, false
+ * otherwise.
+ */
+static inline bool vma_may_populate_pgtable(struct vm_area_struct *vma)
+{
+	if (!vma_is_cow_mapping(vma))
+		return true;
+	return !check_stable_address_space(vma->vm_mm);
+}
+
 long oom_badness(struct task_struct *p,
 		unsigned long totalpages);
 
mm/filemap.c +9 -0
index 5807271a7f668..97a43f7750442 100644
@@ -49,6 +49,7 @@
 #include <linux/sched/mm.h>
 #include <linux/sysctl.h>
 #include <linux/pgalloc.h>
+#include <linux/oom.h>
 
 #include <asm/tlbflush.h>
 #include "internal.h"
@@ -3971,6 +3972,14 @@ vm_fault_t filemap_map_pages(struct vm_fault *vmf,
 		goto out;
 	}
 
+	if (unlikely(!vma_may_populate_pgtable(vma))) {
+		ret = VM_FAULT_SIGBUS;
+		pte_unmap_unlock(vmf->pte, vmf->ptl);
+		folio_unlock(folio);
+		folio_put(folio);
+		goto out;
+	}
+
 	folio_type = mm_counter_file(folio);
 	do {
 		unsigned long end;
mm/huge_memory.c +14 -0
index 1b8e90624299d..5cc21030aa6c1 100644
@@ -1665,6 +1665,11 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr,
 		goto out_unlock;
 	}
 
+	if (!vma_may_populate_pgtable(vma)) {
+		ret = VM_FAULT_SIGBUS;
+		goto out_unlock;
+	}
+
 	if (fop.is_folio) {
 		entry = folio_mk_pmd(fop.folio, vma->vm_page_prot);
 
@@ -1805,6 +1810,11 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr,
 		goto out_unlock;
 	}
 
+	if (!vma_may_populate_pgtable(vma)) {
+		ret = VM_FAULT_SIGBUS;
+		goto out_unlock;
+	}
+
 	if (fop.is_folio) {
 		entry = folio_mk_pud(fop.folio, vma->vm_page_prot);
 
@@ -3023,6 +3033,10 @@ int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pm
 		err = -EAGAIN;
 		goto unlock_ptls;
 	}
+	if (!vma_may_populate_pgtable(dst_vma)) {
+		err = -EFAULT;
+		goto unlock_ptls;
+	}
 	if (src_folio) {
 		if (folio_maybe_dma_pinned(src_folio) ||
 		    !PageAnonExclusive(&src_folio->page)) {
mm/memory.c +20 -10
index ec98704eb2202..1ee9ed248e0ed 100644
@@ -2531,6 +2531,9 @@ static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
 		return 0;
 	}
 
+	if (!vma_may_populate_pgtable(vma))
+		return -EFAULT;
+
 	/* Ok, finally just insert the thing.. */
 	pteval = mk_pte(page, prot);
 	if (unlikely(is_zero_folio(folio))) {
@@ -2926,6 +2929,7 @@ static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
 			unsigned long pfn, pgprot_t prot)
 {
 	struct mm_struct *mm = vma->vm_mm;
+	vm_fault_t ret = VM_FAULT_NOPAGE;
 	pte_t *pte, entry;
 	spinlock_t *ptl;
 	int err;
@@ -2940,6 +2944,11 @@ static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
 	if (!pte_none(entry))
 		goto out_unlock;
 
+	if (!vma_may_populate_pgtable(vma)) {
+		ret = VM_FAULT_SIGBUS;
+		goto out_unlock;
+	}
+
 	/* Ok, finally just insert the thing.. */
 	entry = pte_mkspecial(pfn_pte(pfn, prot));
 
@@ -2948,7 +2957,7 @@ static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
 
 out_unlock:
 	pte_unmap_unlock(pte, ptl);
-	return VM_FAULT_NOPAGE;
+	return ret;
 }
 
 /**
@@ -5839,6 +5848,11 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *pa
 	if (unlikely(!pmd_none(*vmf->pmd)))
 		goto out;
 
+	if (!vma_may_populate_pgtable(vma)) {
+		ret = VM_FAULT_SIGBUS;
+		goto out;
+	}
+
 	flush_icache_pages(vma, page, HPAGE_PMD_NR);
 
 	entry = folio_mk_pmd(folio, vma->vm_page_prot);
@@ -5975,15 +5989,6 @@ vm_fault_t finish_fault(struct vm_fault *vmf)
 		page = vmf->page;
 
 	folio = page_folio(page);
-	/*
-	 * check even for read faults because we might have lost our CoWed
-	 * page
-	 */
-	if (!(vma->vm_flags & VM_SHARED)) {
-		ret = check_stable_address_space(vma->vm_mm);
-		if (ret)
-			return ret;
-	}
 
 	/* A poisoned page must take its own fault */
 	if (folio_contain_hwpoisoned_page(folio))
@@ -6067,6 +6072,11 @@ vm_fault_t finish_fault(struct vm_fault *vmf)
 		goto fallback;
 	}
 
+	if (!vma_may_populate_pgtable(vma)) {
+		ret = VM_FAULT_SIGBUS;
+		goto unlock;
+	}
+
 	if (!is_cow && unlikely(folio_ref_count_over_limit(folio))) {
 		ret = VM_FAULT_SIGBUS;
 		goto unlock;
mm/userfaultfd.c +22 -0
index af94600086213..4bcf18a2188b5 100644
@@ -32,6 +32,7 @@
 #include <linux/uio.h>
 #include <linux/file.h>
 #include <linux/cleanup.h>
+#include <linux/oom.h>
 #include <asm/tlbflush.h>
 #include <asm/tlb.h>
 #include "internal.h"
@@ -372,6 +373,11 @@ static int mfill_atomic_install_pte(pmd_t *dst_pmd,
 	if (!pte_none(dst_ptep) && !pte_is_uffd_marker(dst_ptep))
 		goto out_unlock;
 
+	if (!vma_may_populate_pgtable(dst_vma)) {
+		ret = -EFAULT;
+		goto out_unlock;
+	}
+
 	if (page_in_cache) {
 		if (unlikely(folio_ref_count_over_limit(folio))) {
 			ret = -ENOMEM;
@@ -653,6 +659,10 @@ static int mfill_atomic_pte_zeropage(struct mfill_state *state)
 	ret = -EEXIST;
 	if (!pte_none(ptep_get(dst_pte)))
 		goto out_unlock;
+	if (!vma_may_populate_pgtable(dst_vma)) {
+		ret = -EFAULT;
+		goto out_unlock;
+	}
 	set_pte_at(dst_vma->vm_mm, dst_addr, dst_pte, _dst_pte);
 	/* No need to invalidate - it was non-present before */
 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
@@ -1288,6 +1298,10 @@ static long move_present_ptes(struct mm_struct *mm,
 		err = -EAGAIN;
 		goto out;
 	}
+	if (!vma_may_populate_pgtable(dst_vma)) {
+		err = -EFAULT;
+		goto out;
+	}
 	if (folio_test_large(src_folio) ||
 	    folio_maybe_dma_pinned(src_folio) ||
 	    !PageAnonExclusive(&src_folio->page)) {
@@ -1377,6 +1391,10 @@ static int move_swap_pte(struct mm_struct *mm, struct vm_area_struct *dst_vma,
 		double_pt_unlock(dst_ptl, src_ptl);
 		return -EAGAIN;
 	}
+	if (!vma_may_populate_pgtable(dst_vma)) {
+		double_pt_unlock(dst_ptl, src_ptl);
+		return -EFAULT;
+	}
 
 	/*
 	 * The src_folio resides in the swapcache, requiring an update to its
@@ -1433,6 +1451,10 @@ static int move_zeropage_pte(struct mm_struct *mm,
 		double_pt_unlock(dst_ptl, src_ptl);
 		return -EAGAIN;
 	}
+	if (!vma_may_populate_pgtable(dst_vma)) {
+		double_pt_unlock(dst_ptl, src_ptl);
+		return -EFAULT;
+	}
 
 	zero_pte = pte_mkspecial(pfn_pte(zero_pfn(dst_addr),
 					 dst_vma->vm_page_prot));
Signature · 1 line
2.56.1
author maintainer
#19 lore raw

PATCH v2 19/31 mm/gup: check for fatal signals in memfd_pin_folios()

In reply to David Hildenbrand (Arm)

memfd_pin_folios() retries on -EAGAIN until it can isolate all folios that are not longterm pinnable, which can take an unbounded time.

Consequently, as it never checks for fatal signals, UDMABUF_CREATE, for example, cannot be killed while it holds the inode lock of the memfd, blocking a fallocate() of the file.

Let's fix it by checking for fatal signals before each attempt, like __get_user_pages() does for __gup_longterm_locked().

This has medium urgency, as permanently failing isolation, as recently seen with hugetlb, makes the task hang forever.

Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")
---
 mm/gup.c | 5 +++++
 1 file changed, 5 insertions(+)
mm/gup.c +5 -0
index ec0bc99202169..a50463672f803 100644
@@ -3623,6 +3623,11 @@ long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end,
 	flags = memalloc_pin_save();
 	do {
 		nr_folios = 0;
+		if (fatal_signal_pending(current)) {
+			ret = -EINTR;
+			goto err;
+		}
+
 		start_idx = start >> pgshift;
 		end_idx = end >> pgshift;
 		if (is_file_hugepages(memfd)) {
Signature · 1 line
2.56.1
author maintainer
#20 lore raw

PATCH v2 20/31 mm/migrate_device: don't collect secretmem pages

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

secretmem folios are removed from the directmap. GUP refuses secretmem VMAs for that reason, but migrate_vma_setup() hands out secretmem folios to drivers.

Consequently, drivers that are not aware of this might access these folios through the directmap, resulting in a kernel page fault. For example, test_hmm copies the folio content using copy_highpage(), and nouveau and amdkfd use dma_map_page(), where swiotlb bounce buffering reads the folio through the directmap.

Note that migrate_vma_pages() refuses to migrate file folios to device memory, but only after the driver already copied the folio content.

Let's fix it by refusing secretmem VMAs in migrate_vma_setup(), just like GUP refuses them.

This has low urgency, as it requires a driver to migrate secretmem to device memory.

Fixes 1507f51255c9 ("mm: introduce memfd_secret system call to create "secret" memory areas")
[ david: adjust description and comment ]
---
 mm/migrate_device.c | 4 ++++
 1 file changed, 4 insertions(+)
mm/migrate_device.c +4 -0
index a953e7acbea61..578a4419bb083 100644
@@ -13,6 +13,7 @@
 #include <linux/oom.h>
 #include <linux/pagewalk.h>
 #include <linux/rmap.h>
+#include <linux/secretmem.h>
 #include <linux/leafops.h>
 #include <linux/pgalloc.h>
 #include <asm/tlbflush.h>
@@ -772,6 +773,9 @@ int migrate_vma_setup(struct migrate_vma *args)
 		return -EINVAL;
 	if (vma_test_single_mask(vma, VMA_SHADOW_STACK))
 		return -EINVAL;
+	/* secretmem folios have no directmap; GUP refuses them as well. */
+	if (vma_is_secretmem(args->vma))
+		return -EINVAL;
 	if (nr_pages <= 0)
 		return -EINVAL;
 	if (args->start < vma->vm_start || args->start >= vma->vm_end)
Signature · 1 line
2.56.1
author maintainer
#21 lore raw

PATCH v2 21/31 mm/migrate_device: mark folios leaving device memory dirty

In reply to David Hildenbrand (Arm)

Device-private page table entries are weird: they are non-present page table entries, and the device can write to the memory without the CPU noticing or the CPU page tables reflecting it.

So there is no dirty bit on the PTE we could sync to the folio. And usually, nobody cares about the dirty bit for these folios, as these folios are not on the LRU. Device-coherent memory has the same problem:
it is mapped through present PTEs, but the device writes through its own page tables and does not set the PTE dirty bit.

There is one problem, though: when we migrate such a clean folio back to system RAM, the new folio will be clean, and will be mapped through clean PTEs.

Consequently, reclaim can discard the data if the folio is lazyfree:

(1) MADV_FREE on an ordinary anonymous folio makes the folio lazyfree and clean.
(2) We migrate the folio to device memory. The new (device) folio is lazyfree and clean.
(3) The device writes to the folio.
(4) We migrate the folio back to system RAM. The new folio is still lazyfree, and clean just like the PTE that now maps it.
(5) Reclaim discards the folio, and the data the device wrote is lost.

Similarly, after fork(), a child that shares such a clean folio can call MADV_FREE, which does not check a clean folio for other mappings.

So let's fix it by simply marking folios dirty when migrating them out of device memory.

This has low urgency, as it requires MADV_FREE on memory that is migrated to device memory and written by the device.

Fixes a5430dda8a3a ("mm/migrate: support un-addressable ZONE_DEVICE page in migration")
Fixes 8315ada7f095 ("mm/migrate: allow migrate_vma() to alloc new page on empty entry")
Fixes f25cbb7a95a2 ("mm: add zone device coherent type memory support")
Fixes a30b48bf1b24 ("mm/migrate_device: implement THP migration of zone device pages")
---
 mm/migrate_device.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
mm/migrate_device.c +11 -3
index 578a4419bb083..964549222ed7c 100644
@@ -1289,10 +1289,18 @@ static void __migrate_device_pages(unsigned long *src_pfns,
 			mapping = folio_mapping(folio);
 
 			r = folio_migrate_mapping(mapping, newfolio, folio, extra_cnt);
-			if (r)
+			if (r) {
 				src_pfns[i+j] &= ~MIGRATE_PFN_MIGRATE;
-			else
-				folio_migrate_flags(newfolio, folio);
+				continue;
+			}
+			folio_migrate_flags(newfolio, folio);
+			/*
+			 * A device can write to device memory without setting
+			 * any dirty bit, so just consider folios that leave
+			 * device memory dirty.
+			 */
+			if (folio_is_zone_device(folio))
+				folio_mark_dirty(newfolio);
 		}
 next:
 		i += nr;
Signature · 1 line
2.56.1
author maintainer
#22 lore raw

PATCH v2 22/31 mm: taint device sections before setting subsections valid

In reply to David Hildenbrand (Arm)

Adding ZONE_DEVICE memory to an online section can make the new subsections valid before the section is tainted.

Consequently, a concurrent pfn_to_online_page() can return an uninitialized device page, triggering a BUG with CONFIG_DEBUG_VM.

Let's fix it by tainting the section in fill_subsection_map() before setting the validity bits. Pair the write barrier with test_bit_acquire() in pfn_to_online_page() by introducing a new pfn_section_valid_acquire().

This has low urgency, as it requires racing with hotplug of ZONE_DEVICE memory, which is privileged.

Fixes 1f90a3477df3 ("mm: teach pfn_to_online_page() about ZONE_DEVICE section collisions")
---
 include/linux/mmzone.h |  9 +++++++++
 mm/memory_hotplug.c    | 34 +++++++---------------------------
 mm/sparse-vmemmap.c    | 39 +++++++++++++++++++++++++++++----------
 3 files changed, 45 insertions(+), 37 deletions(-)
include/linux/mmzone.h +9 -0
index 6442e662aa4f4..8cbe7e28040a5 100644
@@ -2235,6 +2235,15 @@ static inline int pfn_section_valid(struct mem_section *ms, unsigned long pfn)
 	return usage ? test_bit(idx, usage->subsection_map) : 0;
 }
 
+static inline int pfn_section_valid_acquire(struct mem_section *ms,
+		unsigned long pfn)
+{
+	const int idx = subsection_map_index(pfn);
+	struct mem_section_usage *usage = READ_ONCE(ms->usage);
+
+	return usage ? test_bit_acquire(idx, usage->subsection_map) : 0;
+}
+
 static inline bool pfn_section_first_valid(struct mem_section *ms, unsigned long *pfn)
 {
 	struct mem_section_usage *usage = READ_ONCE(ms->usage);
mm/memory_hotplug.c +7 -27
index a156de90236c1..2db2df0e70fe0 100644
@@ -353,7 +353,13 @@ struct page *pfn_to_online_page(unsigned long pfn)
 	if (!online_section(ms))
 		return NULL;
 
-	if (!pfn_section_valid(ms, pfn))
+	/*
+	 * ZONE_DEVICE subsections in an online section can only become valid
+	 * after the corresponding pgmap was registered and the sections were
+	 * tainted. Look at the subsection first. The acquire pairs with
+	 * smp_wmb() in section_taint_zone_device().
+	 */
+	if (!pfn_section_valid_acquire(ms, pfn))
 		return NULL;
 
 	if (!online_device_section(ms))
@@ -713,19 +719,6 @@ static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned lon
 
 }
 
-#ifdef CONFIG_ZONE_DEVICE
-static void section_taint_zone_device(unsigned long pfn)
-{
-	struct mem_section *ms = __pfn_to_section(pfn);
-
-	ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
-}
-#else
-static inline void section_taint_zone_device(unsigned long pfn)
-{
-}
-#endif
-
 /*
  * Associate the pfn range with the given zone, initializing the memmaps
  * and resizing the pgdat/zone data to span the added pages. After this
@@ -748,19 +741,6 @@ void move_pfn_range_to_zone(struct zone *zone, unsigned long start_pfn,
 	resize_zone_range(zone, start_pfn, nr_pages);
 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
 
-	/*
-	 * Subsection population requires care in pfn_to_online_page().
-	 * Set the taint to enable the slow path detection of
-	 * ZONE_DEVICE pages in an otherwise  ZONE_{NORMAL,MOVABLE}
-	 * section.
-	 */
-	if (zone_is_zone_device(zone)) {
-		if (!IS_ALIGNED(start_pfn, PAGES_PER_SECTION))
-			section_taint_zone_device(start_pfn);
-		if (!IS_ALIGNED(start_pfn + nr_pages, PAGES_PER_SECTION))
-			section_taint_zone_device(start_pfn + nr_pages);
-	}
-
 	/*
 	 * TODO now we have a visible range of pages which are not associated
 	 * with their zone properly. Not nice but set_pfnblock_migratetype()
mm/sparse-vmemmap.c +29 -10
index 5d7e982f94d0a..643d9d1bfa39f 100644
@@ -629,26 +629,45 @@ static bool is_subsection_map_empty(struct mem_section *ms)
 			    SUBSECTIONS_PER_SECTION);
 }
 
-static int fill_subsection_map(unsigned long pfn, unsigned long nr_pages)
+#ifdef CONFIG_ZONE_DEVICE
+static void section_taint_zone_device(struct mem_section *ms,
+		struct dev_pagemap *pgmap, unsigned long nr_pages)
+{
+	if (!pgmap || nr_pages == PAGES_PER_SECTION)
+		return;
+
+	ms->section_mem_map |= SECTION_TAINT_ZONE_DEVICE;
+	/* Pairs with pfn_section_valid_acquire() in pfn_to_online_page(). */
+	smp_wmb();
+}
+#else
+static void section_taint_zone_device(struct mem_section *ms,
+		struct dev_pagemap *pgmap, unsigned long nr_pages)
+{
+}
+#endif
+
+static int fill_subsection_map(unsigned long pfn, unsigned long nr_pages,
+		struct dev_pagemap *pgmap)
 {
 	struct mem_section *ms = __pfn_to_section(pfn);
 	DECLARE_BITMAP(map, SUBSECTIONS_PER_SECTION) = { 0 };
 	unsigned long *subsection_map;
-	int rc = 0;
 
 	subsection_mask_set(map, pfn, nr_pages);
 
 	subsection_map = &ms->usage->subsection_map[0];
 
 	if (bitmap_empty(map, SUBSECTIONS_PER_SECTION))
-		rc = -EINVAL;
-	else if (bitmap_intersects(map, subsection_map, SUBSECTIONS_PER_SECTION))
-		rc = -EEXIST;
-	else
-		bitmap_or(subsection_map, map, subsection_map,
-				SUBSECTIONS_PER_SECTION);
+		return -EINVAL;
+	if (bitmap_intersects(map, subsection_map, SUBSECTIONS_PER_SECTION))
+		return -EEXIST;
+
+	/* Taint the sections before marking the subsection map valid. */
+	section_taint_zone_device(ms, pgmap, nr_pages);
+	bitmap_or(subsection_map, map, subsection_map, SUBSECTIONS_PER_SECTION);
 
-	return rc;
+	return 0;
 }
 
 /*
@@ -733,7 +752,7 @@ static struct page * __meminit section_activate(int nid, unsigned long pfn,
 		ms->usage = usage;
 	}
 
-	rc = fill_subsection_map(pfn, nr_pages);
+	rc = fill_subsection_map(pfn, nr_pages, pgmap);
 	if (rc) {
 		if (usage)
 			ms->usage = NULL;
Signature · 1 line
2.56.1
reviewer Reviewed-by on v2 22/31
#23 lore raw

Re: [PATCH v2 22/31] mm: taint device sections before setting subsections valid

Quoted 16 lines · David Hildenbrand (Arm)

Adding ZONE_DEVICE memory to an online section can make the new subsections valid before the section is tainted.

Consequently, a concurrent pfn_to_online_page() can return an uninitialized device page, triggering a BUG with CONFIG_DEBUG_VM.

Let's fix it by tainting the section in fill_subsection_map() before setting the validity bits. Pair the write barrier with test_bit_acquire()
in pfn_to_online_page() by introducing a new pfn_section_valid_acquire().

This has low urgency, as it requires racing with hotplug of ZONE_DEVICE
memory, which is privileged.

Quoted 6 lines
Fixes 1f90a3477df3 ("mm: teach pfn_to_online_page() about

ZONE_DEVICE section collisions")

Signature · 1 line
All Rights Reversed.
author maintainer
#24 lore raw

PATCH v2 23/31 mm/mempolicy: check access under exec_update_lock

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

The access check in migrate_pages() can race with concurrent execve(): if the target task execs a setuid binary, migrate_pages() can migrate the pages of the new mm, which the checks would otherwise deny. The impact is limited, but we should just handle it consistently.

kernel_migrate_pages() calls ptrace_may_access() on the target and takes its mm with get_task_mm() later, so the credentials that the check sees have to belong to that mm. execve() replaces the mm in exec_mmap() and the credentials in commit_creds(), and holds signal->exec_update_lock for writing across both.

Let's fix it by holding the target's exec_update_lock for reading until we have grabbed the mm, as move_pages() does ever since commit 13f77972b94c ("mm/migrate: find_mm_struct: fix race between security checks and suid exec").

Regarding dropping the RCU read lock earlier, as explained by Oleg:

"kernel_migrate_pages() calls ptrace_may_access() under rcu_read_lock() for no reason. This is a leftover from before the commit 313674661925 ("Unify migrate_pages and move_pages access checks"), where rcu_read_lock() was needed to protect __task_cred(task).

So we can drop the RCU lock right after get_task_struct()."

Waiting for concurrent execve() is not really relevant, and move_pages() already does the same.

This has low urgency, as the impact is limited. No need to CC stable.

Fixes 313674661925 ("Unify migrate_pages and move_pages access checks")
[ david: simplify description and comment ]
---
 mm/mempolicy.c | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)
mm/mempolicy.c +14 -6
index 9e4e8ecd7e69a..8c1fe94a08971 100644
@@ -1981,6 +1981,12 @@ static int kernel_migrate_pages(pid_t pid, unsigned long maxnode,
 		goto out;
 	}
 	get_task_struct(task);
+	rcu_read_unlock();
+
+	/* Exclude execve() until we have grabbed the MM from this task. */
+	err = down_read_killable(&task->signal->exec_update_lock);
+	if (err)
+		goto out_put;
 
 	err = -EINVAL;
 
@@ -1989,28 +1995,28 @@ static int kernel_migrate_pages(pid_t pid, unsigned long maxnode,
 	 * Use the regular "ptrace_may_access()" checks.
 	 */
 	if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) {
-		rcu_read_unlock();
 		err = -EPERM;
-		goto out_put;
+		goto out_unlock;
 	}
-	rcu_read_unlock();
 
 	task_nodes = cpuset_mems_allowed(task);
 	/* Is the user allowed to access the target nodes? */
 	if (!nodes_subset(*new, task_nodes) && !capable(CAP_SYS_NICE)) {
 		err = -EPERM;
-		goto out_put;
+		goto out_unlock;
 	}
 
 	task_nodes = cpuset_mems_allowed(current);
 	if (!nodes_and(*new, *new, task_nodes))
-		goto out_put;
+		goto out_unlock;
 
 	err = security_task_movememory(task);
 	if (err)
-		goto out_put;
+		goto out_unlock;
 
 	mm = get_task_mm(task);
+	up_read(&task->signal->exec_update_lock);
+
 	put_task_struct(task);
 
 	if (!mm) {
@@ -2027,6 +2033,8 @@ static int kernel_migrate_pages(pid_t pid, unsigned long maxnode,
 
 	return err;
 
+out_unlock:
+	up_read(&task->signal->exec_update_lock);
 out_put:
 	put_task_struct(task);
 	goto out;
Signature · 1 line
2.56.1
reviewer Reviewed-by on v2 23/31
#25 lore raw

Re: [PATCH v2 23/31] mm/mempolicy: check access under exec_update_lock

Quoted 43 lines · David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

The access check in migrate_pages() can race with concurrent execve(): if
the target task execs a setuid binary, migrate_pages() can migrate the
pages of the new mm, which the checks would otherwise deny. The impact
is limited, but we should just handle it consistently.

kernel_migrate_pages() calls ptrace_may_access() on the target and takes
its mm with get_task_mm() later, so the credentials that the check sees
have to belong to that mm. execve() replaces the mm in exec_mmap() and
the credentials in commit_creds(), and holds signal->exec_update_lock for writing across both.

Let's fix it by holding the target's exec_update_lock for reading until
we have grabbed the mm, as move_pages() does ever since commit 13f77972b94c ("mm/migrate: find_mm_struct: fix race between security checks and suid exec").

Regarding dropping the RCU read lock earlier, as explained by Oleg:

  "kernel_migrate_pages() calls ptrace_may_access() under rcu_read_lock()
  for no reason. This is a leftover from before the commit 313674661925
  ("Unify migrate_pages and move_pages access checks"), where rcu_read_lock() was needed to protect __task_cred(task).

  So we can drop the RCU lock right after get_task_struct()."

Waiting for concurrent execve() is not really relevant, and move_pages()
already does the same.

This has low urgency, as the impact is limited. No need to CC stable.

Fixes 313674661925 ("Unify migrate_pages and move_pages access
Quoted 9 lines

checks")

Signature · 1 line
All Rights Reversed.
author maintainer
#26 lore raw

PATCH v2 24/31 mm/mempolicy: reject an empty set of allowed nodes

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

Installing a mempolicy with MPOL_F_RELATIVE_NODES can trigger a division by zero when racing with memory offlining. I managed to reproduce this in a small VM with excessive set_mempolicy() calls while offlining memory:

  Oops: divide error: 0000 [#1] SMP
  RIP: 0010:bitmap_fold+0x43/0x60
  Call Trace:
   ? mpol_relative_nodemask+0x26/0x40
   ? mpol_set_nodemask+0x43/0x90
   ? do_set_mempolicy+0x5e/0xe0
   ? __x64_sys_set_mempolicy+0x6c/0x80

mpol_set_nodemask() intersects current->mems_allowed with N_MEMORY, and mpol_relative_nodemask() folds the user's nodemask modulo the weight of the result.

If memory offlining just cleared the task's only allowed node in N_MEMORY, but cpuset did not update mems_allowed yet, the intersection is empty and nodes_fold() divides by zero.

do_mbind() and mpol_shared_policy_init() call mpol_set_nodemask() as well.

Let's fix it by failing with -EINVAL early if there is no allowed node with memory, just like ->create() would later fail for an empty nodemask.

The same division by zero was originally reported by syzkaller for mpol_rebind_mm() [1]. The discussion of Yury's fix attempt [2] also identified this path in mpol_set_nodemask() [3], but only the rebind path got fixed, by commit b983c5642638 ("cgroup/cpuset: rebind mm mempolicy to effective_mems, not mems_allowed").

This has low urgency, as it is extremely unlikely to hit in practice.

---
 mm/mempolicy.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
mm/mempolicy.c +7 -3
index 8c1fe94a08971..7ca8d9f4375f1 100644
@@ -491,9 +491,13 @@ static int mpol_set_nodemask(struct mempolicy *pol,
 	if (!pol || pol->mode == MPOL_LOCAL)
 		return 0;
 
-	/* Check N_MEMORY */
-	nodes_and(nsc->mask1,
-		  cpuset_current_mems_allowed, node_states[N_MEMORY]);
+	/*
+	 * If we just offlined the last memory on a node, it might be gone from
+	 * N_MEMORY before cpuset updates mems_allowed. Just fail in that case.
+	 */
+	if (!nodes_and(nsc->mask1,
+		       cpuset_current_mems_allowed, node_states[N_MEMORY]))
+		return -EINVAL;
 
 	VM_BUG_ON(!nodes);
 
Signature · 1 line
2.56.1
reviewer Reviewed-by on v2 24/31
#27 lore raw

Re: [PATCH v2 24/31] mm/mempolicy: reject an empty set of allowed nodes

Quoted 58 lines · David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

Installing a mempolicy with MPOL_F_RELATIVE_NODES can trigger a division
by zero when racing with memory offlining. I managed to reproduce this
in a small VM with excessive set_mempolicy() calls while offlining memory:

  Oops: divide error: 0000 [#1] SMP
  RIP: 0010:bitmap_fold+0x43/0x60
  Call Trace:
   ? mpol_relative_nodemask+0x26/0x40
   ? mpol_set_nodemask+0x43/0x90
   ? do_set_mempolicy+0x5e/0xe0
   ? __x64_sys_set_mempolicy+0x6c/0x80

mpol_set_nodemask() intersects current->mems_allowed with N_MEMORY, and
mpol_relative_nodemask() folds the user's nodemask modulo the weight of
the result.

If memory offlining just cleared the task's only allowed node in N_MEMORY,
but cpuset did not update mems_allowed yet, the intersection is empty and
nodes_fold() divides by zero.

do_mbind() and mpol_shared_policy_init() call mpol_set_nodemask() as well.

Let's fix it by failing with -EINVAL early if there is no allowed node
with memory, just like ->create() would later fail for an empty nodemask.

The same division by zero was originally reported by syzkaller for mpol_rebind_mm() [1]. The discussion of Yury's fix attempt [2] also identified this path in mpol_set_nodemask() [3], but only the rebind path got fixed, by commit b983c5642638 ("cgroup/cpuset: rebind mm mempolicy
to effective_mems, not mems_allowed").

This has low urgency, as it is extremely unlikely to hit in practice.

Fixes 8fe23e057172 ("mm: clear node in N_HIGH_MEMORY and stop kswapd

when all memory is offlined")

Closes:
https://lore.kernel.org/all/[email protected]/
 [3]
Link:
https://lore.kernel.org/all/CA+0ovCgxbZkXa+OU8w3s84R3KNPNxxRfmsNR-udh+afQBbGNmw@mail.gmail.com/
 [1]
Link:
https://lore.kernel.org/all/[email protected]/

Quoted 8 lines
 [2]
[ david: update description and comment; add reproduction details ]
Signature · 1 line
All Rights Reversed.
author maintainer
#28 lore raw

PATCH v2 25/31 mm/ksm: look up the folio again in cmp_and_merge_page()

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

try_to_merge_two_pages() gets a page (not a folio) passed and can end up splitting a large folio in try_to_merge_one_page().

However, cmp_and_merge_page() does not look up the page's folio again after possibly splitting it, but compares the stale folio against tree_folio since commit a35d8872dae7 ("mm: remove PageTransCompound()").

Consequently, we can end up locking a folio we hold no reference on and never unlocking it, but unlocking another folio that someone else might have locked instead.

Let's fix it by looking up the folio after calling try_to_merge_two_pages().

This has medium urgency, as ksmd can leave a folio locked.

Fixes a35d8872dae7 ("mm: remove PageTransCompound()")
[ david: simplify comment and description ]
---
 mm/ksm.c | 2 ++
 1 file changed, 2 insertions(+)
mm/ksm.c +2 -0
index 444bb7bb62cfe..90cc83275764d 100644
@@ -2361,6 +2361,8 @@ static void cmp_and_merge_page(struct page *page, struct ksm_rmap_item *rmap_ite
 
 		kfolio = try_to_merge_two_pages(rmap_item, page,
 						tree_rmap_item, tree_page);
+		/* We might have split the folio. */
+		folio = page_folio(page);
 		tree_folio = page_folio(tree_page);
 		/*
 		 * If both pages we tried to merge belong to the same (large)
Signature · 1 line
2.56.1
reviewer Reviewed-by on v2 25/31
#29 lore raw

Re: [PATCH v2 25/31] mm/ksm: look up the folio again in cmp_and_merge_page()

Quoted 21 lines · David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

try_to_merge_two_pages() gets a page (not a folio) passed and can end up splitting a large folio in try_to_merge_one_page().

However, cmp_and_merge_page() does not look up the page's folio again after possibly splitting it, but compares the stale folio against tree_folio since commit a35d8872dae7 ("mm: remove PageTransCompound()").

Consequently, we can end up locking a folio we hold no reference on and
never unlocking it, but unlocking another folio that someone else might
have locked instead.

Let's fix it by looking up the folio after calling try_to_merge_two_pages().

This has medium urgency, as ksmd can leave a folio locked.

Quoted 9 lines
Fixes a35d8872dae7 ("mm: remove PageTransCompound()")
[ david: simplify comment and description ]
Signature · 1 line
All Rights Reversed.
author maintainer
#30 lore raw

PATCH v2 26/31 mm/ksm: copy KSM folios at swap-in without VM_MERGEABLE

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

So far we were under the assumption that only VM_MERGEABLE VMAs may contain KSM folios, because we unmerge when clearing VM_MERGEABLE, and KSM only merges within VM_MERGEABLE VMAs. Various infrastructure (e.g., rmap walks) relies on related properties: for example that a KSM folio is always mapped at rmap_item->address, also in child processes.

We ignored one scenario: when unmerging, break_ksm() skips swap entries. If the KSM folio is still in the swap cache, swapping it in after clearing VM_MERGEABLE will map the KSM folio in a VMA without VM_MERGEABLE.

Consequently, rmap walks can miss such folio mappings, resulting in the KSM folio no longer being reclaimable or migratable.

Worse, until ksmd notices that VM_MERGEABLE was cleared and drops the rmap_item of the process, rmap walks still look for the KSM folio at the old address. If the rmap_item belongs to the parent process instead, that will never happen. If the process calls mremap() while the kernel is migrating the KSM folio, mremap() moves the migration entry that try_to_migrate() installed, and remove_migration_ptes() will not find it at its new address. Once migration frees the source folio, the moved PTE still holds a migration entry that refers to the freed, and possibly already reused, folio: the next access through that PTE will hang, or worse.

Let's fix it by copying KSM folios during swap-in if the VMA lacks VM_MERGEABLE, like we already do while KSM_RUN_UNMERGE is set.

Note that mremap() in a VM_MERGEABLE VMA can similarly move a swap entry of a KSM folio, as break_ksm() skips swap entries. But in that case, rmap walks will find the KSM folio again once ksmd scanned the new address, and we cannot end up with a stale migration entry, so we'll leave that for another day.

This has medium urgency, as an unprivileged process can trigger a use-after-free if KSM is enabled.

Fixes 5ad6468801d2 ("ksm: let shared pages be swappable")
[ david: code cleanups; clarify comment and description ]
---
 mm/ksm.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/ksm.c +3 -2
index 90cc83275764d..509bd78156583 100644
@@ -3211,8 +3211,9 @@ struct folio *ksm_might_need_to_copy(struct folio *folio, struct page *page,
 	 * So test, and copy, the page of the slot.
 	 */
 	if (folio_test_ksm(folio)) {
-		if (folio_stable_node(folio) &&
-		    !(ksm_run & KSM_RUN_UNMERGE))
+		/* Never place KSM folios into VMAs without VM_MERGEABLE. */
+		if (folio_stable_node(folio) && !(ksm_run & KSM_RUN_UNMERGE) &&
+		    (vma->vm_flags & VM_MERGEABLE))
 			return folio;	/* no need to copy it */
 	} else if (folio_anon_rmap_compatible(folio, page, vma, addr)) {
 		return folio;		/* still no need to copy it */
Signature · 1 line
2.56.1
maintainer Reviewed-by on v2 26/31
#31 lore raw

Re: [PATCH v2 26/31] mm/ksm: copy KSM folios at swap-in without VM_MERGEABLE

Quoted 39 lines · David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

So far we were under the assumption that only VM_MERGEABLE VMAs may contain KSM folios, because we unmerge when clearing VM_MERGEABLE, and KSM only merges within VM_MERGEABLE VMAs. Various infrastructure (e.g., rmap walks) relies on related properties: for example that a KSM folio is always mapped at rmap_item->address, also in child processes.

We ignored one scenario: when unmerging, break_ksm() skips swap entries. If the KSM folio is still in the swap cache, swapping it in after clearing VM_MERGEABLE will map the KSM folio in a VMA without VM_MERGEABLE.

Consequently, rmap walks can miss such folio mappings, resulting in the KSM folio no longer being reclaimable or migratable.

Worse, until ksmd notices that VM_MERGEABLE was cleared and drops the rmap_item of the process, rmap walks still look for the KSM folio at the old address. If the rmap_item belongs to the parent process instead, that will never happen. If the process calls mremap() while the kernel is migrating the KSM folio, mremap() moves the migration entry that try_to_migrate() installed, and remove_migration_ptes() will not find it at its new address. Once migration frees the source folio, the moved PTE still holds a migration entry that refers to the freed, and possibly already reused, folio: the next access through that PTE will hang, or worse.

Let's fix it by copying KSM folios during swap-in if the VMA lacks VM_MERGEABLE, like we already do while KSM_RUN_UNMERGE is set.

Note that mremap() in a VM_MERGEABLE VMA can similarly move a swap entry of a KSM folio, as break_ksm() skips swap entries. But in that case, rmap walks will find the KSM folio again once ksmd scanned the new address, and we cannot end up with a stale migration entry, so we'll leave that for another day.

This has medium urgency, as an unprivileged process can trigger a use-after-free if KSM is enabled.

Quoted 7 lines
Fixes 5ad6468801d2 ("ksm: let shared pages be swappable")
[ david: code cleanups; clarify comment and description ]

Oops send the tag while you were respinning I think, so:

Quoted 22 lines
---
 mm/ksm.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/ksm.c +3 -3
index 90cc83275764d..509bd78156583 100644
@@ -3211,8 +3211,9 @@ struct folio *ksm_might_need_to_copy(struct folio *folio, struct page *page,
 	 * So test, and copy, the page of the slot.
 	 */
 	if (folio_test_ksm(folio)) {
-		if (folio_stable_node(folio) &&
-		    !(ksm_run & KSM_RUN_UNMERGE))
+		/* Never place KSM folios into VMAs without VM_MERGEABLE. */
+		if (folio_stable_node(folio) && !(ksm_run & KSM_RUN_UNMERGE) &&
+		    (vma->vm_flags & VM_MERGEABLE))
 			return folio;	/* no need to copy it */
 	} else if (folio_anon_rmap_compatible(folio, page, vma, addr)) {
 		return folio;		/* still no need to copy it */
 
--
Quoted 2 lines

2.56.1

--
Cheers, Lorenzo

author maintainer
#32 lore raw

Re: [PATCH v2 26/31] mm/ksm: copy KSM folios at swap-in without VM_MERGEABLE

Quoted 48 lines · Lorenzo Stoakes (ARM)
Quoted 39 lines · David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

So far we were under the assumption that only VM_MERGEABLE VMAs may contain KSM folios, because we unmerge when clearing VM_MERGEABLE, and KSM only merges within VM_MERGEABLE VMAs. Various infrastructure (e.g., rmap walks) relies on related properties: for example that a KSM folio is always mapped at rmap_item->address, also in child processes.

We ignored one scenario: when unmerging, break_ksm() skips swap entries. If the KSM folio is still in the swap cache, swapping it in after clearing VM_MERGEABLE will map the KSM folio in a VMA without VM_MERGEABLE.

Consequently, rmap walks can miss such folio mappings, resulting in the KSM folio no longer being reclaimable or migratable.

Worse, until ksmd notices that VM_MERGEABLE was cleared and drops the rmap_item of the process, rmap walks still look for the KSM folio at the old address. If the rmap_item belongs to the parent process instead, that will never happen. If the process calls mremap() while the kernel is migrating the KSM folio, mremap() moves the migration entry that try_to_migrate() installed, and remove_migration_ptes() will not find it at its new address. Once migration frees the source folio, the moved PTE still holds a migration entry that refers to the freed, and possibly already reused, folio: the next access through that PTE will hang, or worse.

Let's fix it by copying KSM folios during swap-in if the VMA lacks VM_MERGEABLE, like we already do while KSM_RUN_UNMERGE is set.

Note that mremap() in a VM_MERGEABLE VMA can similarly move a swap entry of a KSM folio, as break_ksm() skips swap entries. But in that case, rmap walks will find the KSM folio again once ksmd scanned the new address, and we cannot end up with a stale migration entry, so we'll leave that for another day.

This has medium urgency, as an unprivileged process can trigger a use-after-free if KSM is enabled.

Quoted 7 lines
Fixes 5ad6468801d2 ("ksm: let shared pages be swappable")
[ david: code cleanups; clarify comment and description ]
Quoted 3 lines

Oops send the tag while you were respinning I think, so:

Thanks! :)

Signature · 3 lines
Cheers,

David
author maintainer
#33 lore raw

PATCH v2 27/31 mm/ksm: don't convert a shared anon folio into a KSM folio

In reply to David Hildenbrand (Arm)

So far we were under the assumption that only VM_MERGEABLE VMAs may contain KSM folios, because we unmerge when clearing VM_MERGEABLE, and KSM only merges within VM_MERGEABLE VMAs. Various infrastructure (e.g., rmap walks) relies on related properties: for example that a KSM folio is always mapped at rmap_item->address, also in child processes.

We ignored one scenario: turning a COW-shared folio into a KSM folio in one process will make all processes mapping it suddenly see a KSM folio, even if VM_MERGEABLE is not set for them.

Consequently, rmap walks can miss such folio mappings, resulting in the KSM folio no longer being reclaimable or migratable.

Worse, if such a process calls mremap() while the kernel is migrating a KSM folio, mremap() moves the migration entry that try_to_migrate() installed, and remove_migration_ptes() will not find it at its new address. Once migration frees the source folio, the moved PTE still holds a migration entry that refers to the freed, and possibly already reused, folio: the next access through that PTE will hang, or worse.

Further, if ksmd scans the child, rmap walks will not even find the parent's VMA: the child's rmap_item references the child's anon_vma, which the parent's VMA is not linked into.

Let's fix it all by refusing to convert a folio into a KSM folio if it might be shared with another mm. When merging two folios that are not KSM folios yet, try both directions: as long as one folio is not shared, we can merge.

Shared folios can still be merged into an existing KSM folio, the shared zeropage or an identical folio that is not shared. Only identical folios that are all shared will no longer be merged, which should be fine for the known use cases.

Note that other processes might only hold a swap entry for the folio, and map it after swapping it in. As the previous commit only copies KSM folios at swap-in into VMAs without VM_MERGEABLE, also refuse to convert a folio that is in the swap cache, unless we can free the swap entry.

This has medium urgency, as an unprivileged process can trigger a use-after-free if KSM is enabled.

Fixes 80e148226028 ("ksm: share anon page without allocating")
Fixes 5beb49305251 ("mm: change anon_vma linking to fix multi-process server scalability issue")
---
 Documentation/admin-guide/mm/ksm.rst |  3 +++
 mm/ksm.c                             | 47 ++++++++++++++++++++++++++++++++----
 2 files changed, 45 insertions(+), 5 deletions(-)
Documentation/admin-guide/mm/ksm.rst +3 -0
index 8968ae3f55c0a..079db28bfc5b4 100644
@@ -27,6 +27,9 @@ KSM's merged pages were originally locked into kernel memory, but can now
 be swapped out just like other user pages (but sharing is broken when they
 are swapped back in: ksmd must rediscover their identity and merge again).
 
+Note that KSM might not merge identical pages if each of them is already
+shared between processes as a result of fork().
+
 Controlling KSM with madvise
 ============================
 
mm/ksm.c +42 -5

103 lines not on this page · raw message

Signature · 1 line
2.56.1
reviewer Reviewed-by on v2 27/31
#34 lore raw

Re: [PATCH v2 27/31] mm/ksm: don't convert a shared anon folio into a KSM folio

Quoted 35 lines · David Hildenbrand (Arm)

So far we were under the assumption that only VM_MERGEABLE VMAs may contain KSM folios, because we unmerge when clearing VM_MERGEABLE, and
KSM only merges within VM_MERGEABLE VMAs. Various infrastructure (e.g.,
rmap walks) relies on related properties: for example that a KSM folio
is always mapped at rmap_item->address, also in child processes.

We ignored one scenario: turning a COW-shared folio into a KSM folio in
one process will make all processes mapping it suddenly see a KSM folio, even if VM_MERGEABLE is not set for them.

Consequently, rmap walks can miss such folio mappings, resulting in the KSM folio no longer being reclaimable or migratable.

Worse, if such a process calls mremap() while the kernel is migrating a
KSM folio, mremap() moves the migration entry that try_to_migrate() installed, and remove_migration_ptes() will not find it at its new address. Once migration frees the source folio, the moved PTE still holds a migration entry that refers to the freed, and possibly already
reused, folio: the next access through that PTE will hang, or worse.

Further, if ksmd scans the child, rmap walks will not even find the parent's VMA: the child's rmap_item references the child's anon_vma, which the parent's VMA is not linked into.

Let's fix it all by refusing to convert a folio into a KSM folio if it
might be shared with another mm.

Quoted 6 lines
Fixes 80e148226028 ("ksm: share anon page without allocating")
Fixes 5beb49305251 ("mm: change anon_vma linking to fix multi-

process server scalability issue")

Safe from simultaneous fork because dup_mm() takes the mmap_lock for write, while ksmd takes the mmap_lock for read.

Signature · 1 line
All Rights Reversed.
author maintainer
#35 lore raw

PATCH v2 28/31 mm/ksm: use a migration counter to detect KSM folio migration

In reply to David Hildenbrand (Arm)

ksm_get_folio() holds no reference on the folio referenced by stable_node->kpfn. If the folio at stable_node->kpfn is no longer our KSM folio, it was either freed or migrated. When freed, we can drop the stable node; when migrated, we have to look again for the migrated folio.

However, a second migration might have migrated the KSM folio back to the very same page in the meantime: stable_node->kpfn would be effectively unchanged and the KSM folio is still alive.

Consequently, we might remove the stable node of a KSM folio that is still mapped, resulting in a use-after-free of the stable node, for example, in rmap_walk_ksm().

Let's fix it by storing a migration counter in the upper bits of stable_node->kpfn, incremented on each migration of the KSM folio. The existing check whether the value changed will then also detect a KSM folio that migrated back, and a freed KSM folio will still be detected as such.

As a pfn never needs more than 64 - PAGE_SHIFT bits, convert stable_node->kpfn to a u64, and use the remaining PAGE_SHIFT bits (at least 12) for the counter. A wrap-around would require 4096 migrations of the KSM folio while ksmd is between two reads in ksm_get_folio():
not relevant in practice, because even two migrations back and forth would be hard to hit.

This change doesn't grow the size of a stable node on 64-bit, which is what we care about. We don't care about 32-bit and likely we should make KSM 64-bit-only soon.

Note that on 32-bit, the pfn will always reside in the lower 32 bits, and every update changes the upper 32 bits, which hold the counter. So even if we read a value torn by a concurrent update (2x32-bit accesses), the pfn will be valid, and due to the existing barriers, the value cannot look unchanged after a migration.

Rename stable_node->kpfn to stable_node->kpfn_seq to catch all users, and add helpers to access the pfn.

This has low urgency, as it should be extremely hard to hit in practice. As this was not reproducible and wasn't reported so far, and the change is not trivial to backport, let's not CC stable.

---
 mm/ksm.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++-----------------
 1 file changed, 66 insertions(+), 23 deletions(-)
mm/ksm.c +66 -23
index fe7b3b60540db..33c270aae3285 100644
@@ -152,10 +152,11 @@ struct ksm_scan {
  * @hlist_dup: linked into the stable_node->hlist with a stable_node chain
  * @list: linked into migrate_nodes, pending placement in the proper node tree
  * @hlist: hlist head of rmap_items using this ksm page
- * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid)
+ * @kpfn_seq: page frame number of this ksm page (perhaps temporarily on wrong
+ *	      nid), with a migration counter in the upper bits
  * @chain_prune_time: time of the last full garbage collection
  * @rmap_hlist_len: number of rmap_item entries in hlist or STABLE_NODE_CHAIN
- * @nid: NUMA node id of stable tree in which linked (may not match kpfn)
+ * @nid: NUMA node id of stable tree in which linked (may not match the pfn)
  */
 struct ksm_stable_node {
 	union {
@@ -170,7 +171,7 @@ struct ksm_stable_node {
 	};
 	struct hlist_head hlist;
 	union {
-		unsigned long kpfn;
+		u64 kpfn_seq;
 		unsigned long chain_prune_time;
 	};
 	/*
@@ -844,6 +845,39 @@ static struct page *get_mergeable_page(struct ksm_rmap_item *rmap_item)
 	return page;
 }
 
+/*
+ * The upper bits of stable_node->kpfn_seq count migrations of the ksm page, so
+ * ksm_get_folio() can detect a ksm page that migrated back to the same pfn.
+ */
+#define KSM_KPFN_SEQ_SHIFT	(64 - PAGE_SHIFT)
+#define KSM_KPFN_PFN_MASK	((1ULL << KSM_KPFN_SEQ_SHIFT) - 1)
+
+static inline unsigned long ksm_kpfn_pfn(u64 kpfn_seq)
+{
+	return kpfn_seq & KSM_KPFN_PFN_MASK;
+}
+
+static inline unsigned long stable_node_pfn(const struct ksm_stable_node *node)
+{
+	return ksm_kpfn_pfn(READ_ONCE(node->kpfn_seq));
+}
+
+static inline void stable_node_init_pfn(struct ksm_stable_node *node,
+		unsigned long pfn)
+{
+	node->kpfn_seq = pfn;
+}
+
+static inline void stable_node_migrate_pfn(struct ksm_stable_node *node,
+		unsigned long pfn)
+{
+	u64 kpfn_seq = node->kpfn_seq;
+
+	kpfn_seq &= ~KSM_KPFN_PFN_MASK;
+	kpfn_seq += 1ULL << KSM_KPFN_SEQ_SHIFT;
+	WRITE_ONCE(node->kpfn_seq, kpfn_seq | pfn);
+}
+
 /*
  * This helper is used for getting right index into array of tree roots.
  * When merge_across_nodes knob is set to 1, there are only two rb-trees for
@@ -855,6 +889,11 @@ static inline int get_kpfn_nid(unsigned long kpfn)
 	return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn));
 }
 
+static inline bool stable_node_nid_consistent(const struct ksm_stable_node *node)
+{
+	return get_kpfn_nid(stable_node_pfn(node)) == NUMA(node->nid);
+}
+
 static struct ksm_stable_node *alloc_stable_node_chain(struct ksm_stable_node *dup,
 						   struct rb_root *root)
 {
@@ -906,7 +945,8 @@ static void remove_node_from_stable_tree(struct ksm_stable_node *stable_node)
 	hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) {
 		if (rmap_item->hlist.next) {
 			ksm_pages_sharing--;
-			trace_ksm_remove_rmap_item(stable_node->kpfn, rmap_item, rmap_item->mm);
+			trace_ksm_remove_rmap_item(stable_node_pfn(stable_node),
+						   rmap_item, rmap_item->mm);
 		} else {
 			ksm_pages_shared--;
 		}
@@ -932,7 +972,7 @@ static void remove_node_from_stable_tree(struct ksm_stable_node *stable_node)
 	BUILD_BUG_ON(STABLE_NODE_DUP_HEAD <= &migrate_nodes);
 	BUILD_BUG_ON(STABLE_NODE_DUP_HEAD >= &migrate_nodes + 1);
 
-	trace_ksm_remove_ksm_page(stable_node->kpfn);
+	trace_ksm_remove_ksm_page(stable_node_pfn(stable_node));
 	if (stable_node->head == &migrate_nodes)
 		list_del(&stable_node->list);
 	else
@@ -969,13 +1009,13 @@ static struct folio *ksm_get_folio(struct ksm_stable_node *stable_node,
 {
 	struct folio *folio;
 	void *expected_mapping;
-	unsigned long kpfn;
+	u64 kpfn_seq;
 
 	expected_mapping = (void *)((unsigned long)stable_node |
 					FOLIO_MAPPING_KSM);
 again:
-	kpfn = READ_ONCE(stable_node->kpfn); /* Address dependency. */
-	folio = pfn_folio(kpfn);
+	kpfn_seq = READ_ONCE(stable_node->kpfn_seq); /* Address dependency. */
+	folio = pfn_folio(ksm_kpfn_pfn(kpfn_seq));
 	if (READ_ONCE(folio->mapping) != expected_mapping)
 		goto stale;
 
@@ -1031,10 +1071,12 @@ static struct folio *ksm_get_folio(struct ksm_stable_node *stable_node,
 	 * We come here from above when folio->mapping or the swapcache flag
 	 * suggests that the node is stale; but it might be under migration.
 	 * We need smp_rmb(), matching the smp_wmb() in folio_migrate_ksm(),
-	 * before checking whether node->kpfn has been changed.
+	 * before checking whether node->kpfn_seq has been changed. Due to the
+	 * migration counter, a ksm page that migrated back to the same pfn
+	 * changes node->kpfn_seq as well.
 	 */
 	smp_rmb();
-	if (READ_ONCE(stable_node->kpfn) != kpfn)
+	if (READ_ONCE(stable_node->kpfn_seq) != kpfn_seq)
 		goto again;
 	remove_node_from_stable_tree(stable_node);
 	return NULL;
@@ -1984,8 +2026,7 @@ static struct folio *stable_tree_search(struct page *page)
 				goto again;
 			folio_unlock(tree_folio);
 
-			if (get_kpfn_nid(stable_node_dup->kpfn) !=
-			    NUMA(stable_node_dup->nid)) {
+			if (!stable_node_nid_consistent(stable_node_dup)) {
 				folio_put(tree_folio);
 				goto replace;
 			}
@@ -2149,7 +2190,7 @@ static struct ksm_stable_node *stable_tree_insert(struct folio *kfolio)
 		return NULL;
 
 	INIT_HLIST_HEAD(&stable_node_dup->hlist);
-	stable_node_dup->kpfn = kpfn;
+	stable_node_init_pfn(stable_node_dup, kpfn);
 	stable_node_dup->rmap_hlist_len = 0;
 	DO_NUMA(stable_node_dup->nid = nid);
 	if (!need_chain) {
@@ -2316,8 +2357,7 @@ static void cmp_and_merge_page(struct page *page, struct ksm_rmap_item *rmap_ite
 	stable_node = folio_stable_node(folio);
 	if (stable_node) {
 		if (stable_node->head != &migrate_nodes &&
-		    get_kpfn_nid(READ_ONCE(stable_node->kpfn)) !=
-		    NUMA(stable_node->nid)) {
+		    !stable_node_nid_consistent(stable_node)) {
 			stable_node_dup_del(stable_node);
 			stable_node->head = &migrate_nodes;
 			list_add(&stable_node->list, stable_node->head);
@@ -3416,11 +3456,12 @@ void folio_migrate_ksm(struct folio *newfolio, struct folio *folio)
 
 	stable_node = folio_stable_node(folio);
 	if (stable_node) {
-		VM_BUG_ON_FOLIO(stable_node->kpfn != folio_pfn(folio), folio);
-		WRITE_ONCE(stable_node->kpfn, folio_pfn(newfolio));
+		VM_BUG_ON_FOLIO(stable_node_pfn(stable_node) !=
+				folio_pfn(folio), folio);
+		stable_node_migrate_pfn(stable_node, folio_pfn(newfolio));
 		/*
 		 * newfolio->mapping was set in advance; now we need smp_wmb()
-		 * to make sure that the new stable_node->kpfn is visible
+		 * to make sure that the new stable_node->kpfn_seq is visible
 		 * to ksm_get_folio() before it can see that folio->mapping
 		 * has gone stale (or that the swapcache flag has been cleared).
 		 */
@@ -3445,11 +3486,12 @@ static bool stable_node_dup_remove_range(struct ksm_stable_node *stable_node,
 					 unsigned long start_pfn,
 					 unsigned long end_pfn)
 {
-	if (stable_node->kpfn >= start_pfn &&
-	    stable_node->kpfn < end_pfn) {
+	const unsigned long pfn = stable_node_pfn(stable_node);
+
+	if (pfn >= start_pfn && pfn < end_pfn) {
 		/*
 		 * Don't ksm_get_folio, page has already gone:
-		 * which is why we keep kpfn instead of page*
+		 * which is why we keep the pfn instead of page*
 		 */
 		remove_node_from_stable_tree(stable_node);
 		return true;
@@ -3505,8 +3547,9 @@ static void ksm_check_stable_tree(unsigned long start_pfn,
 		}
 	}
 	list_for_each_entry_safe(stable_node, next, &migrate_nodes, list) {
-		if (stable_node->kpfn >= start_pfn &&
-		    stable_node->kpfn < end_pfn)
+		const unsigned long pfn = stable_node_pfn(stable_node);
+
+		if (pfn >= start_pfn && pfn < end_pfn)
 			remove_node_from_stable_tree(stable_node);
 		cond_resched();
 	}
Signature · 1 line
2.56.1
author maintainer
#36 lore raw

PATCH v2 29/31 mm/migrate: fix KSM oddity by checking expected refcount without mappings

In reply to David Hildenbrand (Arm)

KSM can add page table mappings to a folio that the migration code has locked and unmapped. While that is completely inconsistent with everything else in MM and should be reworked, changing that is a bigger task.

When ksmd establishes a new page table mapping, it holds a reference on the KSM folio from stable_tree_search() to stable_tree_append(), and relies on migration to back off due to the raised reference. However, __migrate_folio() considers the mapcount as well, assuming that it is simply 0. A mapping that goes away after the mapcount is read and before the refcount is read can hide ksmd's reference:

refcount mapcount
unmapped, held by migration and ksmd 2 0
replace_page() 3 1
expected_count = mapcount + 1 = 2
write fault, COW 2 0
folio_ref_count() == expected_count

Consequently, folio_migrate_ksm() clears the stable node of the old folio, crashing ksmd when dereferencing a NULL pointer.

Let's fix it for now by not considering page table mappings in __migrate_folio().

This has medium urgency, as ksmd can crash due to a NULL pointer dereference, although the race should be very hard to hit.

Fixes 86ebd50224c0 ("mm: add folio_expected_ref_count() for reference count calculation")
---
 include/linux/mm.h | 62 ++++++++++++++++++++++++++++++++++--------------------
 mm/migrate.c       |  2 +-
 2 files changed, 40 insertions(+), 24 deletions(-)
include/linux/mm.h +39 -23
index 62c720c2d4542..3826e51b1bc59 100644
@@ -3217,6 +3217,42 @@ static inline bool folio_maybe_mapped_shared(struct folio *folio)
 	return test_bit(FOLIO_MM_IDS_SHARED_BITNUM, &folio->_mm_ids);
 }
 
+/**
+ * folio_expected_unmapped_ref_count - expected refcount ignoring page table
+ *				       mappings
+ * @folio: the folio
+ *
+ * Like folio_expected_ref_count(), but without references from page table
+ * mappings: any page table mapping will be detected as an unexpected reference.
+ *
+ * Returns: the expected folio refcount, excluding page table mappings.
+ */
+static inline int folio_expected_unmapped_ref_count(const struct folio *folio)
+{
+	const int order = folio_order(folio);
+	int ref_count = 0;
+
+	if (WARN_ON_ONCE(page_has_type(&folio->page) && !folio_test_hugetlb(folio)))
+		return 0;
+
+	/* One reference per page from the swapcache. */
+	ref_count += folio_test_swapcache(folio) << order;
+
+	if (!folio_test_anon(folio)) {
+		/*
+		 * One reference per page from the pagecache.
+		 * Use data_race() since folio might not be locked.
+		 */
+		ref_count += !!data_race(folio->mapping) << order;
+		/*
+		 * One reference from filesystem private data.
+		 */
+		ref_count += folio_has_attached_private(folio);
+	}
+
+	return ref_count;
+}
+
 /**
  * folio_expected_ref_count - calculate the expected folio refcount
  * @folio: the folio
@@ -3231,7 +3267,8 @@ static inline bool folio_maybe_mapped_shared(struct folio *folio)
  * the LRU cache does not apply.
  *
  * Calling this function on an unmapped folio -- !folio_mapped() -- that is
- * locked will return a stable result.
+ * locked will return a stable result, unless it is a KSM folio: KSM can map
+ * these without the folio lock.
  *
  * Calling this function on a mapped folio will not result in a stable result,
  * because nothing stops additional page table mappings from coming (e.g.,
@@ -3252,29 +3289,8 @@ static inline bool folio_maybe_mapped_shared(struct folio *folio)
  */
 static inline int folio_expected_ref_count(const struct folio *folio)
 {
-	const int order = folio_order(folio);
-	int ref_count = 0;
-
-	if (WARN_ON_ONCE(page_has_type(&folio->page) && !folio_test_hugetlb(folio)))
-		return 0;
-
-	/* One reference per page from the swapcache. */
-	ref_count += folio_test_swapcache(folio) << order;
-
-	if (!folio_test_anon(folio)) {
-		/*
-		 * One reference per page from the pagecache.
-		 * Use data_race() since folio might not be locked.
-		 */
-		ref_count += !!data_race(folio->mapping) << order;
-		/*
-		 * One reference from filesystem private data.
-		 */
-		ref_count += folio_has_attached_private(folio);
-	}
-
 	/* One reference per page table mapping. */
-	return ref_count + folio_mapcount(folio);
+	return folio_expected_unmapped_ref_count(folio) + folio_mapcount(folio);
 }
 
 #ifndef HAVE_ARCH_MAKE_FOLIO_ACCESSIBLE
mm/migrate.c +1 -1
index 2fe4cd936e71b..4743bd76e93f4 100644
@@ -917,7 +917,7 @@ static int __migrate_folio(struct address_space *mapping, struct folio *dst,
 			   struct folio *src, void *src_private,
 			   enum migrate_mode mode)
 {
-	int rc, expected_count = folio_expected_ref_count(src) + 1;
+	int rc, expected_count = folio_expected_unmapped_ref_count(src) + 1;
 
 	/* Check whether src does not have extra refs before we do more work */
 	if (folio_ref_count(src) != expected_count)
Signature · 1 line
2.56.1
author maintainer
#37 lore raw

PATCH v2 30/31 mm/migrate_device: don't collect KSM folios

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

KSM can add page table mappings to a KSM folio without holding the folio lock, and only makes them visible to rmap walks afterwards, when adding the rmap_item to the stable node in stable_tree_append().

migrate_vma_collect_pmd() finds such a fresh mapping through its page table walk, locks the folio and replaces the PTE by a migration entry.

But when restoring the migration entries, remove_migration_ptes() relies on an rmap walk, and rmap_walk_ksm() might not yet find that PTE:

ksmd migrate_vma_setup()
==== ===================
try_to_merge_with_ksm_page()
replace_page()
PTE maps kfolio
migrate_vma_collect_pmd()
folio_trylock(kfolio) PTE = migration entry
migrate_device_unmap()
remove_migration_ptes()
rmap_walk_ksm() misses it
folio_unlock(kfolio)
folio_lock(kfolio)
stable_tree_append()

Consequently, we can leave a stale migration entry behind. If migration succeeded, the migration entry will refer to the freed source folio, and waiting on that migration entry will trigger a use-after-free.

Let's fix it by not collecting KSM folios in migrate_vma_collect_pmd().

This has medium urgency, as it can result in a use-after-free, but might be hard to trigger in practice.

Fixes 8c3328f1f36a ("mm/migrate: migrate_vma() unmap page from vma while collecting pages")
[ david: clarify comment; simplify and clarify description ]
---
 mm/migrate_device.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
mm/migrate_device.c +12 -0
index 964549222ed7c..40deb7722e8ac 100644
@@ -411,6 +411,18 @@ static int migrate_vma_collect_pmd(pmd_t *pmdp,
 			bool anon_exclusive;
 			pte_t swp_pte;
 
+			/*
+			 * rmap_walk_ksm() may not find this PTE to restore
+			 * the migration entry later.
+			 */
+			if (folio_test_ksm(folio)) {
+				if (fault_folio != folio)
+					folio_unlock(folio);
+				folio_put(folio);
+				mpfn = 0;
+				goto next;
+			}
+
 			if (pte_present(pte))
 				flush_cache_page(vma, addr, pte_pfn(pte));
 			anon_exclusive = folio_test_anon(folio) &&
Signature · 1 line
2.56.1
author maintainer
#38 lore raw

PATCH v2 31/31 mm/migrate: use consistent folio locking logic

In reply to David Hildenbrand (Arm)

migrate_folio_unmap() never blocks on the folio lock during direct compaction to prevent deadlocks, as the allocating task might hold that folio lock itself. Further, in MIGRATE_SYNC_LIGHT mode, it does not wait for the folio lock of folios that are not uptodate, as that would effectively wait for I/O.

However, try_split_folio() blocks on the folio lock in any mode except MIGRATE_ASYNC. Consequently, a task that holds the folio lock of a large folio while allocating memory could deadlock when direct compaction tries splitting that very folio:

folio_lock(A)
high-order allocation
direct compaction
migrate_pages_batch()
try_split_folio(A)
folio_lock(A)

For example, shmem_swapin_folio() can call shmem_replace_folio() with the folio lock of a large swapcache folio held, where it will try allocating a folio of the same order. Some conditions make this deadlock currently impossible: direct compaction skips folios that are not smaller than the requested order.

There are no known cases where we could currently deadlock. But it should be the right thing to do to make this locking logic consistent in migration code.

Let's make it consistent by factoring the locking logic of migrate_folio_unmap() out into migrate_try_lock_folio() and using it in try_split_folio() as well.

---
 mm/migrate.c | 71 ++++++++++++++++++++++++++++++------------------------------
 1 file changed, 35 insertions(+), 36 deletions(-)
mm/migrate.c +35 -36
index 4743bd76e93f4..4bd10c6170d42 100644
@@ -1255,6 +1255,37 @@ static void migrate_folio_done(struct folio *src,
 		folio_put(src);
 }
 
+static bool migrate_try_lock_folio(struct folio *folio, enum migrate_mode mode)
+{
+	if (folio_trylock(folio))
+		return true;
+	if (mode == MIGRATE_ASYNC)
+		return false;
+
+	/*
+	 * It's not safe for direct compaction to call lock_page. For example,
+	 * during page readahead pages are added locked to the LRU. Later, when
+	 * the IO completes the pages are marked uptodate and unlocked. However,
+	 * the queueing could be merging multiple pages for one bio (e.g.
+	 * mpage_readahead). If an allocation happens for the second or third
+	 * page, the process can end up locking the same page twice and
+	 * deadlocking. Rather than trying to be clever about what pages can be
+	 * locked, avoid the use of lock_page for direct compaction altogether.
+	 */
+	if (current->flags & PF_MEMALLOC)
+		return false;
+
+	/*
+	 * In "light" mode, we can wait for transient locks (eg inserting a page
+	 * into the page table), but it's not worth waiting for I/O.
+	 */
+	if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(folio))
+		return false;
+
+	folio_lock(folio);
+	return true;
+}
+
 /* Obtain the lock on page, remove all ptes. */
 static int migrate_folio_unmap(struct folio *src, struct folio *dst,
 		enum migrate_mode mode, struct list_head *ret)
@@ -1265,36 +1296,8 @@ static int migrate_folio_unmap(struct folio *src, struct folio *dst,
 	bool locked = false;
 	bool dst_locked = false;
 
-	if (!folio_trylock(src)) {
-		if (mode == MIGRATE_ASYNC)
-			goto out;
-
-		/*
-		 * It's not safe for direct compaction to call lock_page.
-		 * For example, during page readahead pages are added locked
-		 * to the LRU. Later, when the IO completes the pages are
-		 * marked uptodate and unlocked. However, the queueing
-		 * could be merging multiple pages for one bio (e.g.
-		 * mpage_readahead). If an allocation happens for the
-		 * second or third page, the process can end up locking
-		 * the same page twice and deadlocking. Rather than
-		 * trying to be clever about what pages can be locked,
-		 * avoid the use of lock_page for direct compaction
-		 * altogether.
-		 */
-		if (current->flags & PF_MEMALLOC)
-			goto out;
-
-		/*
-		 * In "light" mode, we can wait for transient locks (eg
-		 * inserting a page into the page table), but it's not
-		 * worth waiting for I/O.
-		 */
-		if (mode == MIGRATE_SYNC_LIGHT && !folio_test_uptodate(src))
-			goto out;
-
-		folio_lock(src);
-	}
+	if (!migrate_try_lock_folio(src, mode))
+		goto out;
 	locked = true;
 	if (folio_test_mlocked(src))
 		old_folio_state |= FOLIO_WAS_MLOCKED;
@@ -1630,12 +1633,8 @@ static inline int try_split_folio(struct folio *folio, struct list_head *split_f
 {
 	int rc;
 
-	if (mode == MIGRATE_ASYNC) {
-		if (!folio_trylock(folio))
-			return -EAGAIN;
-	} else {
-		folio_lock(folio);
-	}
+	if (!migrate_try_lock_folio(folio, mode))
+		return -EAGAIN;
 	rc = split_folio_to_list(folio, split_folios);
 	folio_unlock(folio);
 	if (!rc)
Signature · 1 line
2.56.1