Linux Documentation
 help / color / mirror / Atom feed
* [RFC PATCH 0/5] mm/mglru: walk page tables under per-VMA locks
@ 2026-12-01 13:11 Chuanhua Han
  2026-12-01 13:11 ` [RFC PATCH 1/5] mm/mmap_lock: add vma_start_read_rcu() helper Chuanhua Han
                   ` (4 more replies)
  0 siblings, 5 replies; 7+ messages in thread
From: Chuanhua Han @ 2026-12-01 13:11 UTC (permalink / raw)
  To: Andrew Morton, linux-mm
  Cc: Kairui Song, Barry Song, Qi Zheng, Shakeel Butt, Axel Rasmussen,
	Yuanchu Xie, Wei Xu, Baoquan He, Baolin Wang, David Hildenbrand,
	Liam R. Howlett, Vlastimil Babka, Mike Rapoport, Michal Hocko,
	Lorenzo Stoakes, Suren Baghdasaryan, Pedro Falcato, Jann Horn,
	Johannes Weiner, Jonathan Corbet, Shuah Khan, Randy Dunlap,
	linux-doc, Michal Hocko, Matthew Wilcox, Yu Zhao, Kalesh Singh,
	Hugh Dickins, Ridong Chen, linux-kernel, Chuanhua Han,
	Chuanhua Han

The MGLRU aging walk holds mmap_lock for read while it walks the page
tables of an mm. A writer to that mm, such as mmap() or mprotect(),
waits for the walk, and page faults that fall back to mmap_lock queue
behind the writer. When mmap_read_trylock() fails, the walk skips the
whole mm. The admin guide already warns that the page table walk "can
theoretically worsen lock contention (mmap_lock)".

This series walks the page tables under per-VMA read locks instead. A
writer then waits only while the walk holds the lock of the VMA it
modifies, and a VMA that cannot be locked is skipped on its own rather
than with the rest of the mm.

On Android, these waits make the foreground app drop frames. kswapd
often ages the mm of the foreground app, because the walk visits only
the mms whose tasks have run since the last walk, and the app keeps
running and mapping memory while it scrolls. On a Pixel 6 running a
daily-use script, the main thread or render thread of the foreground
app waited 9-30 ms for the walk in frames that missed their deadline.
With this series, the walk takes no mmap_lock, and in a
microbenchmark, mprotect() drops from 41.2 ms to 0.14 ms on average.

How the walk works
==================

Before this series, walk_mm() holds mmap_lock from the start of a
round until a PUD boundary where need_resched() is true or the batch
is full, or until the end of the mm. Within a PTE, PMD or PUD table,
get_next_vma() moves to the next VMA without walking down from the
PGD again. A writer waits until the round ends.

With this series, each round finds the next VMA under RCU, skips it if
its flags rule it out, tries to read-lock it, and walks it with
walk_page_range_vma(). No lock is held between rounds. Within a table,
the walk hands the VMA lock off to the next VMA in the same table: it
locks the next one, then unlocks the current one:

  walk        |---- VMA A ----|---- VMA B ----|---- VMA C ----|
  A locked    [===============]
  B locked                 [===================]
  C locked                                  [==================]
  writer to C                                     ^ waits for C
  writer to A                         ^ no wait

Design
======

 - Page table lifetime. As long as a locked VMA maps part of a PUD or
   PMD table, free_pgtables() keeps that table, so the handoff locks
   the next VMA before releasing the current one, and looks for it
   only within the current table. Patch 3 shows the race with munmap()
   this prevents. PTE tables can be freed without a VMA write lock, so
   patch 3 maps them again and revalidates them after a handoff, and
   patch 4 keeps the PTE lock across it instead.

 - mm lifetime. exit_mmap() frees the VMA tree without waiting for RCU,
   so the walk pins mm_users with mmget_not_zero() and drops it with
   mmput_async(). It stops before the next PTE table once it holds the
   last reference. See question 4.

Alternatives considered
=======================

 1. Turning off the page table walk, LRU_GEN_MM_WALK in
    /sys/kernel/mm/lru_gen/enabled. Aging then finds young PTEs only
    through the rmap, which commit bd74fdaea146 ("mm: multi-gen LRU:
    support page table walks") found more costly.

 2. Yielding mmap_lock when it is contended. A writer would still wait
    until the walk reaches its next check, the walk would compete with
    writers for mmap_lock again, and an mm whose trylock fails would
    still be skipped whole.

 3. Falling back to mmap_lock for a VMA that cannot be locked, as
    /proc/PID/maps does. Aging does not need to scan every VMA in every
    walk, and it would make reclaim wait for writers again, which this
    series avoids.

Series layout
=============

 1-2. Preparation, no functional change. Patch 1 adds
      vma_start_read_rcu(), which, unlike vma_start_read(), stays in
      the RCU read side critical section and does not mmdrop() when it
      fails. Patch 2 splits out the VMA flag checks that can be done
      before the VMA is locked.

 3.   Walk each mm under per-VMA locks instead of mmap_lock.

 4.   Keep the PTE lock across a handoff at the PTE level. This is an
      optimization: patches 1-3 are complete without it.

 5.   Update the MGLRU design doc and admin guide.

Questions for reviewers
=======================

 1. Skipping VMAs that cannot be locked. A VMA that is modified often
    may be skipped by several consecutive walks, while the base kernel
    skips the whole mm only when mmap_read_trylock() fails. The walk
    could retry the skipped VMAs once at its end. Is skipping acceptable
    for aging?

 2. Patch 4 searches the VMA tree and tries to lock the next VMA while
    holding the PTE lock. Is its gain worth the extra locking
    complexity, or should the series keep the handoff of patch 3?

 3. vma_start_read_rcu() returns the mm of a recycled VMA through
    @drop_mm, for the caller to mmdrop() outside RCU. Is an out
    parameter acceptable?

 4. Pinning mm_users. Commit d14514c66cb9 ("mm/vmscan: prevent MGLRU
    reclaim from pinning address space") stopped the walk from pinning
    mm_users, so that reclaim would not delay the freeing of an exiting
    process's memory. This series pins it again for the whole walk of
    each mm, across the cond_resched() between rounds, and stops before
    the next PTE table once the process exits. Until that walk ends, the
    OOM reaper and process_mrelease() still see the elevated mm_users
    and skip the mm. Two alternatives avoid the pin:

     a. Take mmap_read_trylock() around each lookup of the next VMA,
        and drop it once the VMA is locked.

     b. Keep one VMA locked from the end of one round to the start of
        the next, so that only the first lookup in each mm needs
        mmap_read_trylock() or a pin.

Testing
=======

Unless noted otherwise, all tests ran on a Pixel 6 (Google Tensor,
arm64, 39-bit VA, 8 CPUs, 8 GB of memory, 90 Hz display) with an
Android mainline kernel based on v7.2, comparing it with and without
this series backported.

 - Daily-use script: 30 apps launched cold and scrolled, the camera
   every 5 apps, and 2 games, about 10 minutes per run. Lock waits
   were traced with the mmap_lock tracepoints in 18 runs on the base
   kernel.

   The app must finish each frame within 16.6 ms of its start, longer
   than the 11.1 ms refresh period at 90 Hz because frames are
   pipelined. A frame finished later is shown late, and the user sees
   a stutter. In 5 of the 18 runs, 6 frames, all during scrolling,
   were late mainly because the main thread or render thread of the
   foreground app waited for the walk, for at least half of the time by
   which the frame was late:

     thread  lock   wait   missed by   missed by      walk held
                    (ms)   (ms)        without wait   (ms)
     main    read   14.0   13.3        on time        14.8
     main    read   20.7   12.0        on time        32.6
     main    read   21.5   14.2        on time        34.3
     render  write  29.9   35.3        5.4 ms         36.5
     render  write   8.9   10.6        1.7 ms         26.9
     main    write  17.1   34.0        16.9 ms        33.9

   The render threads waited in mmap() while drawing. Each main thread
   that waited for the read lock queued behind a writer in the same
   process. These frames normally took 5-11 ms, so a wait first used
   up the slack, which is why a wait can be longer than the miss.

   Preemption makes the waits longer: on the loaded phone, kswapd spent
   about as much time waiting for a CPU as running, and it keeps
   holding mmap_lock while it waits. In one case it held mmap_lock for
   39.1 ms, 22.9 ms of it runnable but not running.

   With this series, the walk takes no mmap_lock, so none of these
   waits remain, and a preempted walk holds the lock of one VMA only.

 - Lock contention microbenchmark, with the CPU governor at
   performance. The benchmark maps two adjacent 512 MB anonymous VMAs
   that fill one PUD-aligned 1 GB range, and a separate 10 MB VMA, C.
   In each of 100 iterations, it reads every page of the three VMAs,
   then one thread ages the memcg, and 1 ms later another thread calls
   mprotect() on C:

                              base       patched
     mprotect() avg (ms)      41.2       0.14
     mprotect() max (ms)      50.8       0.18

   On the base kernel, the walk drops mmap_lock only at a PUD
   boundary, after it has walked both 512 MB VMAs. The aging time is
   about the same on both kernels.

 - Aging cost, with the CPU governor at performance. Each case maps a
   fixed VMA layout in its own memcg, reads all of its pages, and times
   one write of "+ memcg 0 max_seq" to /sys/kernel/debug/lru_gen.
   Each kernel was booted 3 times, alternating, with 4 sets of 30
   agings per case on each boot.

   Some sets ran slower, on both kernels and also with the memory
   controller frequency pinned.

     mean of 12 sets                    base  patched
     Typical layouts:
     5000 VMAs, mixed, app-like      16.9 ms  18.2 ms
     one 512 MB VMA                  18.7 ms  20.4 ms
     Worst case, one PTE walked per VMA boundary:
     512 x 4 KB VMAs, one PTE table   137 us   151 us
     512 x 4 KB VMAs, one per PMD     249 us   297 us

   For the typical layouts, the change is within the run-to-run
   variation, which the slow sets make large: the 90% confidence
   intervals of the difference include zero. The single 512 MB VMA has
   no VMA boundary, so the page table walk itself is not measurably
   slower.

   The worst cases consist of single-page VMAs, so the walk does
   little but hand off, and they bound the cost of the per-VMA lock:
   about 25 ns per VMA boundary at the PTE level and 90 ns at the PMD
   level. The PTE level costs less because its handoff continues the
   VMA iterator, instead of searching the tree from the root for each
   boundary as the base kernel does. On x86_64 (i7-14700, v7.4-rc3),
   the PTE level shows no measurable cost, the PMD level about 70 ns,
   and the PUD level, which is folded on the Pixel 6, about 80 ns. With
   5000 app-like VMAs, this would add at most 0.5 ms to a 16.9 ms walk.

Chuanhua Han (5):
  mm/mmap_lock: add vma_start_read_rcu() helper
  mm/mglru: split the VMA flag checks out of should_skip_vma()
  mm/mglru: walk page tables under per-VMA locks
  mm/mglru: hand off VMA locks without dropping the PTE lock
  mm/mglru: update the docs for the per-VMA lock walk

 Documentation/admin-guide/mm/multigen_lru.rst |   3 +-
 Documentation/mm/multigen_lru.rst             |  22 +-
 include/linux/mmap_lock.h                     |   3 +
 include/linux/mmzone.h                        |   3 +
 mm/mmap_lock.c                                |  75 +++-
 mm/vmscan.c                                   | 373 +++++++++++++++---
 6 files changed, 405 insertions(+), 74 deletions(-)


base-commit: 7d1a16abe4cc5dccd21e3d6262e44433a5885d27
-- 
2.34.1


^ permalink raw reply	[flat|nested] 7+ messages in thread

* [RFC PATCH 1/5] mm/mmap_lock: add vma_start_read_rcu() helper
  2026-12-01 13:11 [RFC PATCH 0/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
@ 2026-12-01 13:11 ` Chuanhua Han
  2026-12-01 13:24   ` Lorenzo Stoakes (ARM)
  2026-12-01 13:11 ` [RFC PATCH 2/5] mm/mglru: split the VMA flag checks out of should_skip_vma() Chuanhua Han
                   ` (3 subsequent siblings)
  4 siblings, 1 reply; 7+ messages in thread
From: Chuanhua Han @ 2026-12-01 13:11 UTC (permalink / raw)
  To: Andrew Morton, linux-mm
  Cc: Kairui Song, Barry Song, Qi Zheng, Shakeel Butt, Axel Rasmussen,
	Yuanchu Xie, Wei Xu, Baoquan He, Baolin Wang, David Hildenbrand,
	Liam R. Howlett, Vlastimil Babka, Mike Rapoport, Michal Hocko,
	Lorenzo Stoakes, Suren Baghdasaryan, Pedro Falcato, Jann Horn,
	Johannes Weiner, Jonathan Corbet, Shuah Khan, Randy Dunlap,
	linux-doc, Michal Hocko, Matthew Wilcox, Yu Zhao, Kalesh Singh,
	Hugh Dickins, Ridong Chen, linux-kernel, Chuanhua Han,
	Chuanhua Han

A later patch makes the MGLRU aging walk lock VMAs one at a time instead
of holding mmap_lock for the whole mm. The walk only tries to read-lock
each VMA it finds under RCU, and skips the VMA if its lock is held for
write, rather than waiting for the writer. It does so in two places:

 - While iterating the VMA tree under RCU.

 - While holding a PTE lock, inside the RCU read side critical section
   of pte_offset_map(), to hand the VMA lock off to the next VMA in
   the same PTE table without dropping the PTE lock. Waiting there
   could deadlock: a writer such as mprotect() takes the PTE lock
   after the VMA write lock.

vma_start_read() does not fit the second place, and is awkward in the
first. When it fails, it leaves the RCU read side critical section,
which the PTE table mapped by pte_offset_map() depends on, and the
iteration has to look the next VMA up again. If the VMA has been
recycled for another mm, it also mmdrop()s that mm, and __mmdrop() is
heavy enough that vma_start_read() already defers it until after RCU;
it should not run under a PTE lock either. lock_vma_under_rcu() and
lock_next_vma() build on vma_start_read() and, on failure, retry or
fall back to mmap_lock. The walk cannot open code the locking, which
relies on helpers private to mm/mmap_lock.c.

Move the body of vma_start_read() into __vma_start_read(), which stays
in the RCU read side critical section and returns the other mm through
@drop_mm instead of dropping it, and rebuild vma_start_read() on top
of it with the same behavior.

Add vma_start_read_rcu() on top of __vma_start_read(). It returns NULL
both when the VMA cannot be locked and when it is detached, since the
walk skips it either way. The caller mmdrop()s the mm returned in
@drop_mm after dropping its spinlocks and leaving RCU, and, as with
any VMA found under RCU, checks that the locked VMA still covers the
range it expects.

No functional change.

Signed-off-by: Chuanhua Han <hanchuanhua@xiaomi.com>
---
 include/linux/mmap_lock.h |  3 ++
 mm/mmap_lock.c            | 75 ++++++++++++++++++++++++++++-----------
 2 files changed, 58 insertions(+), 20 deletions(-)

diff --git a/include/linux/mmap_lock.h b/include/linux/mmap_lock.h
index bada7a03ddf4..04bab16e3de2 100644
--- a/include/linux/mmap_lock.h
+++ b/include/linux/mmap_lock.h
@@ -536,6 +536,9 @@ static inline void vma_mark_detached(struct vm_area_struct *vma)
 
 struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm,
 					  unsigned long address);
+struct vm_area_struct *vma_start_read_rcu(struct mm_struct *mm,
+					  struct vm_area_struct *vma,
+					  struct mm_struct **drop_mm);
 
 static inline void vma_rcu_iter_init(struct vma_rcu_iter *rvmi,
 		struct mm_struct *mm, struct vma_iterator *vmi,
diff --git a/mm/mmap_lock.c b/mm/mmap_lock.c
index 073c5125b424..028a41d6804a 100644
--- a/mm/mmap_lock.c
+++ b/mm/mmap_lock.c
@@ -220,11 +220,13 @@ static bool vma_seqcount_is_write_locked(unsigned int vma_seq, unsigned int mm_s
  * Returns the vma on success, NULL on failure to lock and EAGAIN if vma got
  * detached.
  *
- * IMPORTANT: RCU lock must be held upon entering the function, but upon error
- *            IT IS RELEASED. The caller must handle this correctly.
+ * RCU lock must be held, and is kept held. The function does not sleep. If the
+ * vma got attached to another mm, that mm is grabbed and returned in @drop_mm,
+ * and the caller must mmdrop() it, outside the RCU read side critical section.
  */
-static struct vm_area_struct *vma_start_read(struct mm_struct *mm,
-					     struct vm_area_struct *vma)
+static struct vm_area_struct *__vma_start_read(struct mm_struct *mm,
+					       struct vm_area_struct *vma,
+					       struct mm_struct **drop_mm)
 {
 	unsigned int vma_seq;
 	unsigned int mm_seq;
@@ -232,6 +234,7 @@ static struct vm_area_struct *vma_start_read(struct mm_struct *mm,
 	int oldcnt;
 
 	RCU_LOCKDEP_WARN(!rcu_read_lock_held(), "no rcu lock held");
+	*drop_mm = NULL;
 	/*
 	 * Check before locking. A race might cause false locked result.
 	 * We can use READ_ONCE() for the mm_lock_seq here, and don't need
@@ -241,10 +244,8 @@ static struct vm_area_struct *vma_start_read(struct mm_struct *mm,
 	 */
 	vma_seq = READ_ONCE(vma->vm_lock_seq);
 	mm_seq = READ_ONCE(mm->mm_lock_seq.sequence);
-	if (vma_seqcount_is_write_locked(vma_seq, mm_seq)) {
-		vma = NULL;
-		goto err;
-	}
+	if (vma_seqcount_is_write_locked(vma_seq, mm_seq))
+		return NULL;
 
 	/*
 	 * If VM_REFCNT_EXCLUDE_READERS_FLAG is set,
@@ -257,8 +258,7 @@ static struct vm_area_struct *vma_start_read(struct mm_struct *mm,
 	if (unlikely(!__refcount_inc_not_zero_limited_acquire(&vma->vm_refcnt, &oldcnt,
 							      VM_REFCNT_LIMIT))) {
 		/* return EAGAIN if vma got detached from under us */
-		vma = oldcnt ? NULL : ERR_PTR(-EAGAIN);
-		goto err;
+		return oldcnt ? NULL : ERR_PTR(-EAGAIN);
 	}
 
 	__vma_lockdep_acquire_read(vma);
@@ -288,14 +288,9 @@ static struct vm_area_struct *vma_start_read(struct mm_struct *mm,
 	mm_seq = raw_read_seqcount(&mm->mm_lock_seq);
 	if (unlikely(vma_seqcount_is_write_locked(vma_seq, mm_seq))) {
 		vma_refcount_put(vma);
-		vma = NULL;
-		goto err;
+		return NULL;
 	}
 
-	return vma;
-err:
-	rcu_read_unlock();
-
 	return vma;
 err_unstable:
 	/*
@@ -305,16 +300,56 @@ static struct vm_area_struct *vma_start_read(struct mm_struct *mm,
 	 * releasing vma->vm_refcnt.
 	 */
 	other_mm = vma->vm_mm; /* use a copy as vma can be freed after we drop vm_refcnt */
-
-	/* __mmdrop() is a heavy operation, do it after dropping RCU lock. */
-	rcu_read_unlock();
 	mmgrab(other_mm);
 	vma_refcount_put(vma);
-	mmdrop(other_mm);
+	/* __mmdrop() is a heavy operation, leave it to the caller. */
+	*drop_mm = other_mm;
 
 	return NULL;
 }
 
+/*
+ * As __vma_start_read(), but upon error the RCU lock IS RELEASED. The caller
+ * must handle this correctly.
+ */
+static struct vm_area_struct *vma_start_read(struct mm_struct *mm,
+					     struct vm_area_struct *vma)
+{
+	struct mm_struct *drop_mm;
+
+	vma = __vma_start_read(mm, vma, &drop_mm);
+	if (IS_ERR_OR_NULL(vma)) {
+		rcu_read_unlock();
+		if (drop_mm)
+			mmdrop(drop_mm);
+	}
+
+	return vma;
+}
+
+/**
+ * vma_start_read_rcu() - Read-lock a VMA found under RCU, staying under RCU.
+ * @mm: the mm_struct the VMA is expected to belong to
+ * @vma: the VMA, found under the RCU lock held by the caller
+ * @drop_mm: set to an mm the caller must mmdrop() after dropping its spinlocks
+ *           and leaving the RCU read side critical section, or NULL
+ *
+ * Unlike vma_start_read(), this does not leave the RCU read side critical
+ * section on failure, nor mmdrop() a recycled VMA's mm, so it may be called
+ * with a spinlock, e.g., a page table lock, held. Failures are not retried.
+ *
+ * Return: @vma read-locked, or NULL if it could not be locked or got detached.
+ * The caller must check that the VMA still covers the range it expects.
+ */
+struct vm_area_struct *vma_start_read_rcu(struct mm_struct *mm,
+					  struct vm_area_struct *vma,
+					  struct mm_struct **drop_mm)
+{
+	vma = __vma_start_read(mm, vma, drop_mm);
+
+	return IS_ERR(vma) ? NULL : vma;
+}
+
 /*
  * Lookup and lock a VMA under RCU protection. Returned VMA is guaranteed to be
  * stable and not isolated. If the VMA is not found or is being modified the
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [RFC PATCH 2/5] mm/mglru: split the VMA flag checks out of should_skip_vma()
  2026-12-01 13:11 [RFC PATCH 0/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
  2026-12-01 13:11 ` [RFC PATCH 1/5] mm/mmap_lock: add vma_start_read_rcu() helper Chuanhua Han
@ 2026-12-01 13:11 ` Chuanhua Han
  2026-12-01 13:11 ` [RFC PATCH 3/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
                   ` (2 subsequent siblings)
  4 siblings, 0 replies; 7+ messages in thread
From: Chuanhua Han @ 2026-12-01 13:11 UTC (permalink / raw)
  To: Andrew Morton, linux-mm
  Cc: Kairui Song, Barry Song, Qi Zheng, Shakeel Butt, Axel Rasmussen,
	Yuanchu Xie, Wei Xu, Baoquan He, Baolin Wang, David Hildenbrand,
	Liam R. Howlett, Vlastimil Babka, Mike Rapoport, Michal Hocko,
	Lorenzo Stoakes, Suren Baghdasaryan, Pedro Falcato, Jann Horn,
	Johannes Weiner, Jonathan Corbet, Shuah Khan, Randy Dunlap,
	linux-doc, Michal Hocko, Matthew Wilcox, Yu Zhao, Kalesh Singh,
	Hugh Dickins, Ridong Chen, linux-kernel, Chuanhua Han,
	Chuanhua Han

In preparation for walking each mm under per-VMA locks, move the checks
that depend only on the VMA flags into should_skip_vma_flags(), so that
the walk can skip a VMA before trying to lock it, instead of locking and
unlocking VMAs it skips anyway.

Before the VMA is locked, its flags are the only field that is safe to
read. vm_area_cachep is SLAB_TYPESAFE_BY_RCU, so as long as the walk
stays in the RCU read side critical section in which it found the VMA,
the memory stays a vm_area_struct and the flags word can be read, though
the value may be stale. The checks that follow pointers, such as vm_file
and its mapping, need the VMA lock. A stale flags value only makes the
walk skip a VMA it could have walked, or try to lock one it will skip,
and should_skip_vma() checks the VMA again once it is locked.

vma_has_recency() tests both the flags and vm_file, and is also used by
the rmap path, so open code its two halves here instead of splitting the
shared helper.

Change should_skip_vma() to take the VMA and the walk, instead of the
(start, end, mm_walk) arguments of a test_walk callback, so that the
new walk can call it directly. Add test_walk_skip_vma() as the
test_walk callback of the existing walk, which the next patch removes.

No functional change.

Signed-off-by: Chuanhua Han <hanchuanhua@xiaomi.com>
---
 mm/vmscan.c | 37 +++++++++++++++++++++++++++----------
 1 file changed, 27 insertions(+), 10 deletions(-)

diff --git a/mm/vmscan.c b/mm/vmscan.c
index bc7579d47f9b..5820d6fdb452 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -3361,22 +3361,33 @@ static void reset_batch_size(struct lru_gen_mm_walk *walk)
 	lruvec_unlock_irq(lruvec);
 }
 
-static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
+/* The checks of should_skip_vma() that only need the VMA flags. */
+static inline bool should_skip_vma_flags(const vma_flags_t *flags)
 {
-	struct address_space *mapping;
-	struct vm_area_struct *vma = args->vma;
-	struct lru_gen_mm_walk *walk = args->private;
+	if (!vma_flags_test_any_mask(flags, VMA_ACCESS_FLAGS))
+		return true;
 
-	if (!vma_is_accessible(vma))
+	if (vma_flags_is_hugetlb(flags))
 		return true;
 
-	if (vma_is_hugetlb(vma))
+	/* the flags half of vma_has_recency() */
+	if (vma_flags_test_any(flags, VMA_SEQ_READ_BIT, VMA_RAND_READ_BIT))
 		return true;
 
-	if (!vma_has_recency(vma))
+	return vma_flags_test(flags, VMA_LOCKED_BIT) ||
+	       !vma_flags_is_mm_backed(flags);
+}
+
+static inline bool should_skip_vma(struct vm_area_struct *vma,
+				   struct lru_gen_mm_walk *walk)
+{
+	struct address_space *mapping;
+
+	if (should_skip_vma_flags(&vma->flags))
 		return true;
 
-	if (vma_test(vma, VMA_LOCKED_BIT) || !vma_is_mm_backed(vma))
+	/* the vm_file half of vma_has_recency() */
+	if (vma->vm_file && (vma->vm_file->f_mode & FMODE_NOREUSE))
 		return true;
 
 	if (vma == get_gate_vma(vma->vm_mm))
@@ -3402,6 +3413,12 @@ static int should_skip_vma(unsigned long start, unsigned long end, struct mm_wal
 	return !mapping->a_ops->read_folio;
 }
 
+static int test_walk_skip_vma(unsigned long start, unsigned long end,
+			      struct mm_walk *args)
+{
+	return should_skip_vma(args->vma, args->private);
+}
+
 /*
  * Some userspace memory allocators map many single-page VMAs. Instead of
  * returning back to the PGD table for each of such VMAs, finish an entire PMD
@@ -3421,7 +3438,7 @@ static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk
 		if (end && end <= args->vma->vm_start)
 			return false;
 
-		if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
+		if (should_skip_vma(args->vma, args->private))
 			continue;
 
 		*vm_start = max(start, args->vma->vm_start);
@@ -3826,7 +3843,7 @@ static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
 static void walk_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
 {
 	static const struct mm_walk_ops mm_walk_ops = {
-		.test_walk = should_skip_vma,
+		.test_walk = test_walk_skip_vma,
 		.p4d_entry = walk_pud_range,
 		.walk_lock = PGWALK_RDLOCK,
 	};
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [RFC PATCH 3/5] mm/mglru: walk page tables under per-VMA locks
  2026-12-01 13:11 [RFC PATCH 0/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
  2026-12-01 13:11 ` [RFC PATCH 1/5] mm/mmap_lock: add vma_start_read_rcu() helper Chuanhua Han
  2026-12-01 13:11 ` [RFC PATCH 2/5] mm/mglru: split the VMA flag checks out of should_skip_vma() Chuanhua Han
@ 2026-12-01 13:11 ` Chuanhua Han
  2026-12-01 13:11 ` [RFC PATCH 4/5] mm/mglru: hand off VMA locks without dropping the PTE lock Chuanhua Han
  2026-12-01 13:11 ` [RFC PATCH 5/5] mm/mglru: update the docs for the per-VMA lock walk Chuanhua Han
  4 siblings, 0 replies; 7+ messages in thread
From: Chuanhua Han @ 2026-12-01 13:11 UTC (permalink / raw)
  To: Andrew Morton, linux-mm
  Cc: Kairui Song, Barry Song, Qi Zheng, Shakeel Butt, Axel Rasmussen,
	Yuanchu Xie, Wei Xu, Baoquan He, Baolin Wang, David Hildenbrand,
	Liam R. Howlett, Vlastimil Babka, Mike Rapoport, Michal Hocko,
	Lorenzo Stoakes, Suren Baghdasaryan, Pedro Falcato, Jann Horn,
	Johannes Weiner, Jonathan Corbet, Shuah Khan, Randy Dunlap,
	linux-doc, Michal Hocko, Matthew Wilcox, Yu Zhao, Kalesh Singh,
	Hugh Dickins, Ridong Chen, linux-kernel, Chuanhua Han,
	Chuanhua Han

Since commit bd74fdaea146 ("mm: multi-gen LRU: support page table
walks"), the aging path of MGLRU walks the page tables of each mm on
the mm list with mmap_lock held for read. walk_mm() takes the lock
with mmap_read_trylock() and keeps it until the walk finishes, or
until a PUD boundary where it needs to reschedule or the batch is
full. This causes two problems:

 - A writer such as mmap(), munmap() or mprotect() that arrives during
   a walk waits until the walk drops the lock, and page faults that
   fall back to mmap_lock queue behind that writer.

 - When the trylock fails because a writer holds or waits for the lock,
   the whole mm is skipped for this walk, even if only one VMA is being
   modified.

On Android, this makes the foreground app drop frames: its main or
render thread waits for an aging walk of the same mm in kswapd, either
for the write lock in mmap(), or for the read lock behind such a
writer. On a Pixel 6 running a daily-use script, these threads waited
9-30 ms for the walk in frames that missed their deadline. In a
microbenchmark, mprotect() on one VMA waits 41.2 ms on average for an
aging walk that also covers two 512 MB VMAs. With this change, the
walk takes no mmap_lock, and mprotect() takes 0.14 ms on average.

Walk the page tables under per-VMA read locks instead:

 - walk_mm_per_vma() finds the next VMA under RCU, filters it by its
   flags, tries to read-lock it, and walks it with
   walk_page_range_vma(). A VMA that cannot be locked is skipped,
   and the rest of the mm is still walked.

 - Within a page table, the walk hands the VMA lock off to the next
   walkable VMA in the same table, instead of walking down from the
   PGD for each small VMA, as get_next_vma() did under mmap_lock.

 - No lock is held between two rounds, which is where batches are
   flushed and cond_resched() is called. walk_pmd_range_locked() ages
   the PMD entries recorded in a bitmap using the VMA they were found
   in. A handoff in the last PTE table of the range may release that
   VMA, so the bitmap is flushed before walking that table.

 - The walk pins mm_users with mmget_not_zero(), which
   commit d14514c66cb9 ("mm/vmscan: prevent MGLRU reclaim from pinning
   address space") had replaced with mmgrab(). mmgrab() does not keep
   the maple tree nodes, which exit_mmap() frees without waiting for
   RCU. The mmap_lock walk was safe because exit_mmap() takes mmap_lock
   for write first; this walk does not hold mmap_lock. To bound the
   delay that commit removed, the walk stops before the next PTE table
   once it holds the last reference, and drops it with mmput_async(), so
   that reclaim never runs exit_mmap(). The pin is held for the whole
   walk of the mm, across the cond_resched() between rounds, so until
   the walk ends the OOM reaper and process_mrelease() still see the
   elevated mm_users and skip the mm.

walk_pmd_range() and walk_pud_range() compute the table pointer once,
and keep using it after get_next_vma() moves on to the next VMA in
the same table. free_pgtables() frees a table only when no remaining
VMA maps any part of it, so the table stays valid as long as the walk
holds the lock of a VMA inside it. If the walk released the current
VMA before locking the next one, munmap() could free the table in
between:

  CPU 0 (aging)                     CPU 1
  walk_pmd_range()
    holds A, pmd points into T
    get_next_vma()
      unlock A
                                    munmap() of all VMAs in T
                                      free_pgtables() frees T
                                    mmap(MAP_FIXED) of C
                                      maps C in a new table T'
      lock C
    goto restart
    pmdp_get_lockless(pmd + i)
      use-after-free of T

So the handoff follows two rules:

 - walk_trylock_next_vma() locks the next VMA before it releases the
   current one, so no VMA in the table is unlocked in between.

 - get_next_vma() looks for the next VMA only up to the end of the
   current table, so the VMA locked still maps part of the table.

With both, munmap() waits for the walk, and then keeps the table:

  CPU 0 (aging)                     CPU 1
  walk_pmd_range()
    holds A, pmd points into T
                                    munmap(A)
                                      vma_start_write(A) waits
    get_next_vma()
      lock B, which is in T
      unlock A
                                      free_pgtables(): T is kept,
                                      B still maps part of it
    goto restart
    pmdp_get_lockless(pmd + i)

If B is unmapped as well, the writer waits for B until the walk is
done with T.

The same applies to the PUD table in walk_pud_range(), where the
handoff is bounded by the P4D entry. A VMA within the current table
also lies within every table above it, so those stay valid too. The
walk does not hold rcu_read_lock() while it uses these pointers, so
freeing page tables after an RCU grace period would not cover it.

PTE tables are different: retract_page_tables(), since
commit 1d65b771bc08 ("mm/khugepaged: retract_page_tables() without mmap
or vma lock"), and MADV_DONTNEED with CONFIG_PT_RECLAIM, since
commit 6375e95f381e ("mm: pgtable: reclaim empty PTE page in
madvise(MADV_DONTNEED)"), can free them without any VMA write lock,
after an RCU grace period. So at the PTE level the walk drops the PTE
lock, hands the VMA lock off, and maps the table again. As for any PTE
table walk, pte_offset_map_rw_nolock() maps it under RCU, and
walk_pte_range() rechecks the PMD entry with pmd_same() once it holds
the PTE lock.

This trades one mmap_lock acquisition per round for one VMA lock per
VMA walked, so a writer waits at most for the walk of the VMA it
modifies, not of the whole mm. The extra locking is only measurable in
a contrived worst case: 512 one-page VMAs, one per PMD entry, where
the walk does little but take and drop VMA locks. There it costs
about 90 ns per VMA boundary at the PMD level on a Pixel 6. With the
next patch, aging typical layouts takes as long as before, within
run-to-run variation. At the PTE level this patch also drops and
retakes the PTE lock at each handoff, which the next patch avoids.

Signed-off-by: Chuanhua Han <hanchuanhua@xiaomi.com>
---
 include/linux/mmzone.h |   3 +
 mm/vmscan.c            | 291 ++++++++++++++++++++++++++++++++++-------
 2 files changed, 248 insertions(+), 46 deletions(-)

diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h
index 6a2ad0cff795..04b46b5ae163 100644
--- a/include/linux/mmzone.h
+++ b/include/linux/mmzone.h
@@ -507,6 +507,7 @@ enum lruvec_flags {
 
 struct lruvec;
 struct page_vma_mapped_walk;
+struct vm_area_struct;
 
 #ifdef CONFIG_LRU_GEN
 
@@ -613,6 +614,8 @@ struct lru_gen_mm_walk {
 	int batched;
 	int swappiness;
 	bool force_scan;
+	/* the VMA read-locked by the walk, which may change mid-walk */
+	struct vm_area_struct *locked_vma;
 };
 
 /*
diff --git a/mm/vmscan.c b/mm/vmscan.c
index 5820d6fdb452..9235006442b6 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -3413,41 +3413,149 @@ static inline bool should_skip_vma(struct vm_area_struct *vma,
 	return !mapping->a_ops->read_folio;
 }
 
-static int test_walk_skip_vma(unsigned long start, unsigned long end,
-			      struct mm_walk *args)
+/*
+ * Continue @vmi and lock the first VMA in [@addr, @limit) (0: no limit) that
+ * passes should_skip_vma_flags(), skipping VMAs whose lock cannot be taken.
+ *
+ * vm_flags is read without the VMA lock: vm_area_cachep is
+ * SLAB_TYPESAFE_BY_RCU, so the read is safe under RCU, and a stale value at
+ * worst skips a VMA in this walk.
+ *
+ * Return the VMA locked, which the caller checks with should_skip_vma(), or
+ * NULL. On NULL, *drop_mm may be set to an mm the caller must mmdrop() outside
+ * RCU; @vmi is already reset to continue after it.
+ *
+ * Context: RCU read side critical section. Does not sleep.
+ */
+static struct vm_area_struct *walk_trylock_next_vma_rcu(struct mm_struct *mm,
+							struct vma_iterator *vmi,
+							unsigned long addr,
+							unsigned long limit,
+							struct mm_struct **drop_mm)
 {
-	return should_skip_vma(args->vma, args->private);
+	struct vm_area_struct *vma, *locked;
+	unsigned long next;
+	vma_flags_t flags;
+
+	*drop_mm = NULL;
+
+	while ((vma = vma_find(vmi, limit ? limit : ULONG_MAX))) {
+		/* unlocked, may be stale; only the first flags word is read */
+		flags = legacy_to_vma_flags(data_race(READ_ONCE(vma->vm_flags)));
+		if (should_skip_vma_flags(&flags))
+			continue;
+
+		next = vma_iter_end(vmi);
+		locked = vma_start_read_rcu(mm, vma, drop_mm);
+		if (!locked) {
+			if (unlikely(*drop_mm)) {
+				vma_iter_set(vmi, next);
+				return NULL;
+			}
+			continue;
+		}
+
+		/* stable now, but it may have changed since it was found */
+		if (likely(locked->vm_end > addr &&
+			   (!limit || locked->vm_start < limit))) {
+			/* it may have shrunk or grown: resync @vmi */
+			if (unlikely(vma_iter_end(vmi) != locked->vm_end))
+				vma_iter_set(vmi, locked->vm_end);
+			return locked;
+		}
+
+		vma_end_read(locked);
+	}
+
+	return NULL;
+}
+
+/*
+ * Lock the first walkable VMA in [@addr, @limit) (0: no limit), or return NULL.
+ *
+ * Each VMA locked takes over walk->locked_vma, locked before the previous one
+ * is released. With @limit set, it lies in the page table bounded by @limit,
+ * so the table stays pinned. On return walk->locked_vma may be a skipped VMA.
+ *
+ * Context: no page table lock held, outside any RCU read side critical section.
+ */
+static struct vm_area_struct *walk_trylock_next_vma(struct mm_struct *mm,
+						    struct lru_gen_mm_walk *walk,
+						    unsigned long addr,
+						    unsigned long limit)
+{
+	VMA_ITERATOR(vmi, mm, addr);
+	struct vm_area_struct *vma;
+	struct mm_struct *drop_mm;
+
+	rcu_read_lock();
+	for (;;) {
+		vma = walk_trylock_next_vma_rcu(mm, &vmi, addr, limit, &drop_mm);
+		if (!vma) {
+			if (likely(!drop_mm))
+				break;
+
+			rcu_read_unlock();
+			mmdrop(drop_mm);
+			rcu_read_lock();
+			continue;
+		}
+
+		if (walk->locked_vma)
+			vma_end_read(walk->locked_vma);
+		walk->locked_vma = vma;
+
+		if (!should_skip_vma(vma, walk))
+			break;
+	}
+	rcu_read_unlock();
+
+	return vma;
 }
 
 /*
- * Some userspace memory allocators map many single-page VMAs. Instead of
- * returning back to the PGD table for each of such VMAs, finish an entire PMD
- * table to reduce zigzags and improve cache performance.
+ * Hand the VMA lock off to the next walkable VMA in the page table containing
+ * *vm_start, bounded by @mask, without walking down from the PGD again.
+ *
+ * Upper level tables stay valid: they are freed only once no VMA maps them, and
+ * the VMA held lies within them. retract_page_tables() may free PTE tables
+ * without any VMA lock, so walk_pte_range() revalidates the PMD entry.
+ *
+ * Return true with walk->locked_vma and args->vma set to the next VMA and
+ * *vm_start, *vm_end set to its range here. Otherwise return false, with them
+ * set to the VMA still held.
  */
-static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
-			 unsigned long *vm_start, unsigned long *vm_end)
+static bool get_next_vma(unsigned long mask, unsigned long size,
+			 struct mm_walk *args, unsigned long *vm_start,
+			 unsigned long *vm_end)
 {
+	struct lru_gen_mm_walk *walk = args->private;
+	struct vm_area_struct *next = walk->locked_vma;
 	unsigned long start = round_up(*vm_end, size);
-	unsigned long end = (start | ~mask) + 1;
-	VMA_ITERATOR(vmi, args->mm, start);
+	unsigned long end = (*vm_start | ~mask) + 1;
 
 	VM_WARN_ON_ONCE(mask & size);
-	VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
-
-	for_each_vma(vmi, args->vma) {
-		if (end && end <= args->vma->vm_start)
-			return false;
+	VM_WARN_ON_ONCE(!next || next != args->vma);
 
-		if (should_skip_vma(args->vma, args->private))
-			continue;
+	/* this page table is already fully covered */
+	if (end && start >= end)
+		return false;
 
-		*vm_start = max(start, args->vma->vm_start);
-		*vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
+	VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
 
-		return true;
+	/* keep walking a VMA left locked below, unless it was skipped */
+	if (next->vm_end <= start || should_skip_vma(next, walk)) {
+		next = walk_trylock_next_vma(args->mm, walk,
+					     max(start, next->vm_end), end);
+		args->vma = walk->locked_vma;
+		if (!next)
+			return false;
 	}
 
-	return false;
+	*vm_start = max(start, next->vm_start);
+	*vm_end = min(end - 1, next->vm_end - 1) + 1;
+
+	return true;
 }
 
 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr,
@@ -3567,6 +3675,7 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
 	unsigned int nr;
 	pmd_t pmdval;
 
+remap:
 	pte = pte_offset_map_rw_nolock(args->mm, pmd, start & PMD_MASK, &pmdval, &ptl);
 	if (!pte)
 		return false;
@@ -3582,7 +3691,6 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
 	}
 
 	lazy_mmu_mode_enable();
-restart:
 	for (i = pte_index(start), addr = start; addr != end; i += nr, addr += nr * PAGE_SIZE) {
 		unsigned long pfn;
 		struct folio *folio;
@@ -3630,12 +3738,17 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
 	walk_update_folio(walk, args->vma, walk->lruvec, last, dirty);
 	last = NULL;
 
-	if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
-		goto restart;
-
 	lazy_mmu_mode_disable();
 	pte_unmap_unlock(pte, ptl);
 
+	/*
+	 * Hand the VMA lock off to the next VMA in this PTE table. The table
+	 * may be retracted while the PTE lock is not held: map it again.
+	 */
+	if (i < PTRS_PER_PTE &&
+	    get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
+		goto remap;
+
 	return suitable_to_scan(total, young);
 }
 
@@ -3725,6 +3838,15 @@ static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area
 	*first = -1;
 }
 
+/*
+ * The walk pins mm_users, so if it holds the last reference, the mm is
+ * exiting and only waits for the walk to drop it: stop as soon as possible.
+ */
+static __always_inline bool walk_mm_exiting(struct mm_struct *mm)
+{
+	return atomic_read(&mm->mm_users) <= 1;
+}
+
 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
 			   struct mm_walk *args)
 {
@@ -3747,11 +3869,16 @@ static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
 	 */
 	pmd = pmd_offset(pud, start & PUD_MASK);
 restart:
-	/* walk_pte_range() may call get_next_vma() */
+	/* walk_pte_range() may hand args->vma off to a later VMA */
 	vma = args->vma;
 	for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
-		pmd_t val = pmdp_get_lockless(pmd + i);
+		pmd_t val;
 
+		/* the mm is exiting: stop before the next PTE table */
+		if (walk_mm_exiting(args->mm))
+			break;
+
+		val = pmdp_get_lockless(pmd + i);
 		next = pmd_addr_end(addr, end);
 
 		if (!pmd_present(val) || is_huge_zero_pmd(val)) {
@@ -3783,6 +3910,13 @@ static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
 
 		walk->mm_stats[MM_NONLEAF_FOUND]++;
 
+		/*
+		 * walk_pte_range() may release @vma on its last entry: flush
+		 * the PMD batch, which uses @vma, first.
+		 */
+		if (next == end)
+			walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first);
+
 		if (!walk_pte_range(pmd + i, addr, next, args))
 			continue;
 
@@ -3792,9 +3926,14 @@ static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
 		update_bloom_filter(mm_state, walk->seq + 1, pmd + i);
 	}
 
+	/*
+	 * Flush the rest. If the last walk_pte_range() handed @vma off, the
+	 * batch was flushed before it, so @vma is not used.
+	 */
 	walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first);
 
-	if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
+	if (i < PTRS_PER_PMD && !walk_mm_exiting(args->mm) &&
+	    get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
 		goto restart;
 }
 
@@ -3821,13 +3960,15 @@ static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
 
 		walk_pmd_range(pud + i, addr, next, args);
 
-		if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
+		if (need_resched() || walk->batched >= MAX_LRU_BATCH ||
+		    walk_mm_exiting(args->mm)) {
 			end = (addr | ~PUD_MASK) + 1;
 			goto done;
 		}
 	}
 
-	if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
+	if (i < PTRS_PER_PUD && !walk_mm_exiting(args->mm) &&
+	    get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
 		goto restart;
 
 	end = round_up(end, P4D_SIZE);
@@ -3840,39 +3981,97 @@ static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
 	return -EAGAIN;
 }
 
-static void walk_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
+static const struct mm_walk_ops vma_walk_ops = {
+	.p4d_entry = walk_pud_range,
+	.walk_lock = PGWALK_VMA_RDLOCK_VERIFY,
+};
+
+static void walk_unlock_vma(struct lru_gen_mm_walk *walk)
+{
+	if (walk->locked_vma) {
+		vma_end_read(walk->locked_vma);
+		walk->locked_vma = NULL;
+	}
+}
+
+/*
+ * Walk @mm under per-VMA locks. Each round starts from one locked VMA and may
+ * hand the lock off to later VMAs sharing a page table with it. VMAs that
+ * cannot be locked are skipped. No lock is held between rounds, which is where
+ * cond_resched() and batch flushes happen.
+ */
+static void walk_mm_per_vma(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
 {
-	static const struct mm_walk_ops mm_walk_ops = {
-		.test_walk = test_walk_skip_vma,
-		.p4d_entry = walk_pud_range,
-		.walk_lock = PGWALK_RDLOCK,
-	};
-	int err;
 	struct lruvec *lruvec = walk->lruvec;
+	unsigned long addr = walk->next_addr;
+	struct vm_area_struct *vma;
 
-	walk->next_addr = FIRST_USER_ADDRESS;
+	VM_WARN_ON_ONCE(walk->locked_vma);
 
-	do {
-		DEFINE_MAX_SEQ(lruvec);
+	while (addr < ULONG_MAX) {
+		unsigned long start;
+		int err;
 
-		err = -EBUSY;
+		DEFINE_MAX_SEQ(lruvec);
 
 		/* another thread might have called inc_max_seq() */
 		if (walk->seq != max_seq)
 			break;
 
-		/* the caller might be holding the lock for write */
-		if (mmap_read_trylock(mm)) {
-			err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
+		/* all users are gone: let mmput_async() tear @mm down */
+		if (walk_mm_exiting(mm))
+			break;
 
-			mmap_read_unlock(mm);
+		vma = walk_trylock_next_vma(mm, walk, addr, 0);
+		if (!vma) {
+			/* the lock may have been handed off to a skipped VMA */
+			walk_unlock_vma(walk);
+			break;
 		}
 
+		start = max(addr, vma->vm_start);
+		walk->next_addr = start;
+
+		err = walk_page_range_vma(vma, start, vma->vm_end,
+					  &vma_walk_ops, walk);
+
+		/*
+		 * Resume where a round cut short stopped, else past the last VMA
+		 * walked, to which the lock may have been handed off.
+		 */
+		if (err == -EAGAIN && walk->next_addr > start)
+			addr = walk->next_addr;
+		else
+			addr = walk->locked_vma->vm_end;
+
+		/* a writer waiting for this lock holds mmap_lock for write */
+		walk_unlock_vma(walk);
+
+		/* flush after each page table walk */
 		if (walk->batched)
 			reset_batch_size(walk);
 
 		cond_resched();
-	} while (err == -EAGAIN);
+	}
+}
+
+static void walk_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
+{
+	DEFINE_MAX_SEQ(walk->lruvec);
+
+	if (walk->seq != max_seq)
+		return;
+
+	walk->next_addr = FIRST_USER_ADDRESS;
+
+	/* pin the VMA tree: exit_mmap() frees its nodes without RCU */
+	if (!mmget_not_zero(mm))
+		return;
+
+	walk_mm_per_vma(mm, walk);
+
+	/* might be the last user: don't run exit_mmap() in reclaim */
+	mmput_async(mm);
 }
 
 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [RFC PATCH 4/5] mm/mglru: hand off VMA locks without dropping the PTE lock
  2026-12-01 13:11 [RFC PATCH 0/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
                   ` (2 preceding siblings ...)
  2026-12-01 13:11 ` [RFC PATCH 3/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
@ 2026-12-01 13:11 ` Chuanhua Han
  2026-12-01 13:11 ` [RFC PATCH 5/5] mm/mglru: update the docs for the per-VMA lock walk Chuanhua Han
  4 siblings, 0 replies; 7+ messages in thread
From: Chuanhua Han @ 2026-12-01 13:11 UTC (permalink / raw)
  To: Andrew Morton, linux-mm
  Cc: Kairui Song, Barry Song, Qi Zheng, Shakeel Butt, Axel Rasmussen,
	Yuanchu Xie, Wei Xu, Baoquan He, Baolin Wang, David Hildenbrand,
	Liam R. Howlett, Vlastimil Babka, Mike Rapoport, Michal Hocko,
	Lorenzo Stoakes, Suren Baghdasaryan, Pedro Falcato, Jann Horn,
	Johannes Weiner, Jonathan Corbet, Shuah Khan, Randy Dunlap,
	linux-doc, Michal Hocko, Matthew Wilcox, Yu Zhao, Kalesh Singh,
	Hugh Dickins, Ridong Chen, linux-kernel, Chuanhua Han,
	Chuanhua Han

Under mmap_lock, walk_pte_range() moved on to the next VMA in the same
PTE table while holding the PTE lock. Since the previous patch, it
drops the PTE lock at each such handoff, looks the next VMA up from
the root of the VMA tree, locks it, and then maps, locks and
revalidates the table again. Userspace allocators often map many
small adjacent VMAs, for example Scudo [1], the default allocator on
Android, so one PTE table can span many VMAs, and the walk pays this
for each of them.

In the worst case, 512 one-page VMAs in one PTE table, the walk does
little but hand off. On a Pixel 6, aging this layout takes about 40%
less time with this patch, about 220 ns less per VMA boundary.

The handoff does not need to drop the PTE lock:

 - The current VMA stays locked until the next one is, and the next
   one lies in the same PTE table, so munmap() cannot free the table,
   as at the other levels.

 - khugepaged collapses an anonymous PMD range under the write lock of
   the VMA that covers it, and collapse_pte_mapped_thp(),
   retract_page_tables() and MADV_DONTNEED with CONFIG_PT_RECLAIM take
   the PTE lock to clear the PMD entry, so none of them can free the
   table while the walk holds the current VMA lock and the PTE lock.

So keep the PTE lock, continue a VMA iterator from the current VMA
within the RCU read side critical section of pte_offset_map(), and
read-lock the next walkable VMA with vma_start_read_rcu() before
releasing the current one. A VMA that should_skip_vma() rejects is
unlocked right away: the table is protected by the lock of the
current VMA, not by the skipped one.

The lock is only tried, never waited for. A writer such as mprotect()
holds the VMA write lock and then takes the PTE lock in
change_pte_range(). If the walk waited for the VMA lock while holding
the PTE lock, the two would deadlock. A VMA that cannot be locked is
skipped, as at the other levels.

If the VMA was recycled for another mm, that mm must be dropped
outside the PTE lock and RCU. Fall back to the previous path in that
case: drop the PTE lock, mmdrop(), hand off, and map the table again.

[1] https://llvm.org/docs/ScudoHardenedAllocator.html

Signed-off-by: Chuanhua Han <hanchuanhua@xiaomi.com>
---
 mm/vmscan.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++----
 1 file changed, 72 insertions(+), 5 deletions(-)

diff --git a/mm/vmscan.c b/mm/vmscan.c
index 9235006442b6..34ddddab9935 100644
--- a/mm/vmscan.c
+++ b/mm/vmscan.c
@@ -3558,6 +3558,58 @@ static bool get_next_vma(unsigned long mask, unsigned long size,
 	return true;
 }
 
+/*
+ * PTE level variant of get_next_vma() that keeps the PTE lock, so the table
+ * needs no remap. The PTE lock pins the tables, so skipped VMAs are not kept
+ * locked, and the VMA lock is only tried, so it cannot deadlock against a writer.
+ *
+ * @vmi must be at *vm_end, and is only valid within the RCU read side
+ * critical section of pte_offset_map(). On success, it is left at the end
+ * of the VMA handed off to, where the next call continues.
+ *
+ * Return false if nothing is left, or if a recycled VMA left *drop_mm, which
+ * must be mmdrop()ed after dropping the PTE lock and leaving RCU.
+ */
+static bool get_next_vma_rcu(struct mm_walk *args, struct vma_iterator *vmi,
+			     unsigned long *vm_start, unsigned long *vm_end,
+			     struct mm_struct **drop_mm)
+{
+	struct lru_gen_mm_walk *walk = args->private;
+	unsigned long start = *vm_end;
+	unsigned long end = (*vm_start | ~PMD_MASK) + 1;
+	struct vm_area_struct *vma;
+
+	VM_WARN_ON_ONCE(walk->locked_vma != args->vma);
+
+	/*
+	 * Nothing is left in this PTE table, or this is the last table in the
+	 * address space and end wrapped to 0, which means no limit below. No
+	 * user memory lies in that table.
+	 */
+	if (!end || start >= end)
+		return false;
+
+	for (;;) {
+		vma = walk_trylock_next_vma_rcu(args->mm, vmi, start, end, drop_mm);
+		if (!vma)
+			return false;
+
+		if (!should_skip_vma(vma, walk))
+			break;
+
+		vma_end_read(vma);
+	}
+
+	vma_end_read(walk->locked_vma);
+	walk->locked_vma = vma;
+	args->vma = vma;
+
+	*vm_start = max(start, vma->vm_start);
+	*vm_end = min(end - 1, vma->vm_end - 1) + 1;
+
+	return true;
+}
+
 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr,
 				 struct pglist_data *pgdat)
 {
@@ -3674,6 +3726,8 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
 	struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
 	unsigned int nr;
 	pmd_t pmdval;
+	struct mm_struct *drop_mm = NULL;
+	struct vma_iterator vmi;
 
 remap:
 	pte = pte_offset_map_rw_nolock(args->mm, pmd, start & PMD_MASK, &pmdval, &ptl);
@@ -3690,7 +3744,11 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
 		return false;
 	}
 
+	/* only valid in the RCU section of pte_offset_map(): reset on remap */
+	vma_iter_init(&vmi, args->mm, end);
+
 	lazy_mmu_mode_enable();
+restart:
 	for (i = pte_index(start), addr = start; addr != end; i += nr, addr += nr * PAGE_SIZE) {
 		unsigned long pfn;
 		struct folio *folio;
@@ -3738,16 +3796,25 @@ static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
 	walk_update_folio(walk, args->vma, walk->lruvec, last, dirty);
 	last = NULL;
 
+	if (i < PTRS_PER_PTE &&
+	    get_next_vma_rcu(args, &vmi, &start, &end, &drop_mm))
+		goto restart;
+
 	lazy_mmu_mode_disable();
 	pte_unmap_unlock(pte, ptl);
 
 	/*
-	 * Hand the VMA lock off to the next VMA in this PTE table. The table
-	 * may be retracted while the PTE lock is not held: map it again.
+	 * The handoff above stopped at a recycled VMA. Drop its mm now that
+	 * neither the PTE lock nor RCU is held, then hand off and map the
+	 * table again, which may have been retracted meanwhile.
 	 */
-	if (i < PTRS_PER_PTE &&
-	    get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
-		goto remap;
+	if (unlikely(drop_mm)) {
+		mmdrop(drop_mm);
+		drop_mm = NULL;
+
+		if (get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
+			goto remap;
+	}
 
 	return suitable_to_scan(total, young);
 }
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [RFC PATCH 5/5] mm/mglru: update the docs for the per-VMA lock walk
  2026-12-01 13:11 [RFC PATCH 0/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
                   ` (3 preceding siblings ...)
  2026-12-01 13:11 ` [RFC PATCH 4/5] mm/mglru: hand off VMA locks without dropping the PTE lock Chuanhua Han
@ 2026-12-01 13:11 ` Chuanhua Han
  4 siblings, 0 replies; 7+ messages in thread
From: Chuanhua Han @ 2026-12-01 13:11 UTC (permalink / raw)
  To: Andrew Morton, linux-mm
  Cc: Kairui Song, Barry Song, Qi Zheng, Shakeel Butt, Axel Rasmussen,
	Yuanchu Xie, Wei Xu, Baoquan He, Baolin Wang, David Hildenbrand,
	Liam R. Howlett, Vlastimil Babka, Mike Rapoport, Michal Hocko,
	Lorenzo Stoakes, Suren Baghdasaryan, Pedro Falcato, Jann Horn,
	Johannes Weiner, Jonathan Corbet, Shuah Khan, Randy Dunlap,
	linux-doc, Michal Hocko, Matthew Wilcox, Yu Zhao, Kalesh Singh,
	Hugh Dickins, Ridong Chen, linux-kernel, Chuanhua Han,
	Chuanhua Han

The aging walk no longer takes mmap_lock, and walks each VMA under
its per-VMA read lock instead.

Update the design doc, which says the walk calls walk_page_range()
with each mm_struct, and describe the VMA lock handoff. Drop the
warning in the admin guide that the page table walk can worsen
mmap_lock contention, which no longer applies.

Signed-off-by: Chuanhua Han <hanchuanhua@xiaomi.com>
---
 Documentation/admin-guide/mm/multigen_lru.rst |  3 +--
 Documentation/mm/multigen_lru.rst             | 22 +++++++++++++------
 2 files changed, 16 insertions(+), 9 deletions(-)

diff --git a/Documentation/admin-guide/mm/multigen_lru.rst b/Documentation/admin-guide/mm/multigen_lru.rst
index 9cb54b4ff5d9..5bab313284ed 100644
--- a/Documentation/admin-guide/mm/multigen_lru.rst
+++ b/Documentation/admin-guide/mm/multigen_lru.rst
@@ -37,8 +37,7 @@ Values Components
 ====== ===============================================================
 0x0001 The main switch for the multi-gen LRU.
 0x0002 Clearing the accessed bit in leaf page table entries in large
-       batches, when MMU sets it (e.g., on x86). This behavior can
-       theoretically worsen lock contention (mmap_lock). If it is
+       batches, when MMU sets it (e.g., on x86). If this feature is
        disabled, the multi-gen LRU will suffer a minor performance
        degradation for workloads that contiguously map hot pages,
        whose accessed bits can be otherwise cleared by fewer larger
diff --git a/Documentation/mm/multigen_lru.rst b/Documentation/mm/multigen_lru.rst
index b532ce961371..f7d01ca152fc 100644
--- a/Documentation/mm/multigen_lru.rst
+++ b/Documentation/mm/multigen_lru.rst
@@ -118,8 +118,8 @@ generation when it finds them accessed through page tables; the
 demotion of cold pages happens consequently when it increments
 ``max_seq``. The aging uses page table walks and rmap walks to find
 young PTEs. For the former, it iterates ``lruvec_memcg()->mm_list``
-and calls ``walk_page_range()`` with each ``mm_struct`` on this list
-to scan PTEs, and after each iteration, it increments ``max_seq``. For
+and walks the page tables of each ``mm_struct`` on this list to scan
+PTEs, and after each iteration, it increments ``max_seq``. For
 the latter, when the eviction walks the rmap and finds a young PTE,
 the aging scans the adjacent PTEs. For both, on finding a young PTE,
 the aging clears the accessed bit and updates the gen counter of the
@@ -163,11 +163,19 @@ An ``mm_struct`` list is maintained for each memcg, and an
 ``mm_struct`` follows its owner task to the new memcg when this task
 is migrated.
 
-A page table walker iterates ``lruvec_memcg()->mm_list`` and calls
-``walk_page_range()`` with each ``mm_struct`` on this list to scan
-PTEs. When multiple page table walkers iterate the same list, each of
-them gets a unique ``mm_struct``, and therefore they can run in
-parallel.
+A page table walker iterates ``lruvec_memcg()->mm_list`` and walks
+each ``mm_struct`` on this list one VMA at a time, calling
+``walk_page_range_vma()`` on each VMA it locks to scan PTEs. When
+multiple page table walkers iterate the same list, each of them gets a
+unique ``mm_struct``, and therefore they can run in parallel.
+
+A page table walker holds the per-VMA read lock of the VMA it walks,
+not ``mmap_lock``, so a writer to an ``mm_struct`` only waits for the
+walk of the VMA it modifies. It skips a VMA that it cannot lock
+instead of waiting for it, and a later walk ages its pages. Within a
+page table, it hands the VMA lock off to the next VMA in that table:
+it locks the next VMA before it releases the current one, so the
+page table stays valid.
 
 Page table walkers ignore any misplaced pages, e.g., if an
 ``mm_struct`` was migrated, pages left in the previous memcg will be
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* Re: [RFC PATCH 1/5] mm/mmap_lock: add vma_start_read_rcu() helper
  2026-12-01 13:11 ` [RFC PATCH 1/5] mm/mmap_lock: add vma_start_read_rcu() helper Chuanhua Han
@ 2026-12-01 13:24   ` Lorenzo Stoakes (ARM)
  0 siblings, 0 replies; 7+ messages in thread
From: Lorenzo Stoakes (ARM) @ 2026-12-01 13:24 UTC (permalink / raw)
  To: Chuanhua Han
  Cc: Andrew Morton, linux-mm, Kairui Song, Barry Song, Qi Zheng,
	Shakeel Butt, Axel Rasmussen, Yuanchu Xie, Wei Xu, Baoquan He,
	Baolin Wang, David Hildenbrand, Liam R. Howlett, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Suren Baghdasaryan, Pedro Falcato,
	Jann Horn, Johannes Weiner, Jonathan Corbet, Shuah Khan,
	Randy Dunlap, linux-doc, Michal Hocko, Matthew Wilcox, Yu Zhao,
	Kalesh Singh, Hugh Dickins, Ridong Chen, linux-kernel,
	Chuanhua Han

NAK. You're not doing this. Any of it, sorry.

On Tue, Dec 01, 2026 at 09:11:31PM +0800, Chuanhua Han wrote:
> A later patch makes the MGLRU aging walk lock VMAs one at a time instead
> of holding mmap_lock for the whole mm. The walk only tries to read-lock
> each VMA it finds under RCU, and skips the VMA if its lock is held for
> write, rather than waiting for the writer. It does so in two places:

No.

>
>  - While iterating the VMA tree under RCU.
>
>  - While holding a PTE lock, inside the RCU read side critical section
>    of pte_offset_map(), to hand the VMA lock off to the next VMA in
>    the same PTE table without dropping the PTE lock. Waiting there
>    could deadlock: a writer such as mprotect() takes the PTE lock
>    after the VMA write lock.
>

No.

> vma_start_read() does not fit the second place, and is awkward in the
> first. When it fails, it leaves the RCU read side critical section,
> which the PTE table mapped by pte_offset_map() depends on, and the
> iteration has to look the next VMA up again. If the VMA has been
> recycled for another mm, it also mmdrop()s that mm, and __mmdrop() is
> heavy enough that vma_start_read() already defers it until after RCU;
> it should not run under a PTE lock either. lock_vma_under_rcu() and
> lock_next_vma() build on vma_start_read() and, on failure, retry or
> fall back to mmap_lock. The walk cannot open code the locking, which
> relies on helpers private to mm/mmap_lock.c.

NO.

>
> Move the body of vma_start_read() into __vma_start_read(), which stays
> in the RCU read side critical section and returns the other mm through
> @drop_mm instead of dropping it, and rebuild vma_start_read() on top
> of it with the same behavior.

No.

>
> Add vma_start_read_rcu() on top of __vma_start_read(). It returns NULL
> both when the VMA cannot be locked and when it is detached, since the
> walk skips it either way. The caller mmdrop()s the mm returned in
> @drop_mm after dropping its spinlocks and leaving RCU, and, as with
> any VMA found under RCU, checks that the locked VMA still covers the
> range it expects.

No.

>
> No functional change.

Not true, you're creating a brand new API and expecting VMA maintainers to
maintain it indefinitely.

Also to give you free review time.

>
> Signed-off-by: Chuanhua Han <hanchuanhua@xiaomi.com>

No thanks.

As VMA co-maintainer let me just make this simple - I am not interested in
changes like this from unknown people, at all. Sorry.

LLMs have changed the landscape. Do smaller changes first. I have no
confidence you understand any of it.

--
Cheers, Lorenzo

^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2026-12-01 13:24 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01 13:11 [RFC PATCH 0/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
2026-12-01 13:11 ` [RFC PATCH 1/5] mm/mmap_lock: add vma_start_read_rcu() helper Chuanhua Han
2026-12-01 13:24   ` Lorenzo Stoakes (ARM)
2026-12-01 13:11 ` [RFC PATCH 2/5] mm/mglru: split the VMA flag checks out of should_skip_vma() Chuanhua Han
2026-12-01 13:11 ` [RFC PATCH 3/5] mm/mglru: walk page tables under per-VMA locks Chuanhua Han
2026-12-01 13:11 ` [RFC PATCH 4/5] mm/mglru: hand off VMA locks without dropping the PTE lock Chuanhua Han
2026-12-01 13:11 ` [RFC PATCH 5/5] mm/mglru: update the docs for the per-VMA lock walk Chuanhua Han

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox