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 --- 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