mm: Unconditional per-VMA locks and cleanups
Subsystems (25)
Suren Baghdasaryan
maintainerv4 cover mm: Unconditional per-VMA locks and cleanups
v2 version of this patchset [1] was written by Dave Hansen and per his request, I'm taking over this series.
tl;dr: Make per-VMA locks available in all configs. Simplify some of the per-VMA lock users now that they can rely on them being always available.
Binder and networking folks: Your code is the target of the cleanups. I'm cc'ing you now on v2 because there's emerging consensus on the mm side that the approach here is sane. I'm not quite sure how this pile would get merged, but ack/review tags would be appreciated if this looks good to you.
Longer version:
When working on some x86 shadow stack code, it was a real pain to avoid causing recursive locking problems with mmap_lock. One way to avoid those was to avoid mmap_lock and use per-VMA locks instead. They are great, but they are not available in all configs which makes them unusable in generic code, or if you want to completely avoid mmap_lock.
Make per-VMA locks available in all configs. Right now, they are only available on select architectures when SMP and MMU are enabled. But all of the primitives that per-VMA locks are built on (RCU, maple trees, refcounts) work just fine without SMP or MMU.
The only real downside is that making VMAs a wee bit bigger on !MMU and !SMP builds.
The upside is much cleaner code, lower complexity and less #ifdeffery.
Clean up a binder VMA locking site now that it can rely on per-VMA locks.
Building on top of universally-available per-VMA locks, introduce a new helper. Since the new API does not require callers to have a fallback to mmap_lock, it's much easier to use. Callers can potentially replace this very common kernel idiom:
mmap_read_lock(mm); vma = vma_lookup() // fiddle with vma mmap_read_unlock(mm);
with:
vma = vma_start_read_unlocked(mm, address); // fiddle with vma vma_end_read(vma);
Which avoids mmap_lock entirely in the fast path.
Use that new API for another binder site and one in the TCP code.
Changes from v3 [2]:
Patch 1:
- Restored a comment in Kconfig, per Vlastimil Babka
- Removed extra braces in mm.rs, per Vlastimil Babka
- Removed obsolete comment in mm.rs, per Sashiko
- Updated patch description to explain considerations for !CONFIG_MMU
- Changed stack_map_lock_vma() to keep mmap_lock if !CONFIG_MMU
- Changed bpf_iter_task_vma_new() to bail out if !CONFIG_MMU
- Added !CONFIG_MMU versions of vma_mark_attached(), vma_mark_detached(), vma_start_write(), vma_start_write_killable(), vma_assert_attached() and vma_assert_write_locked()
Patch 2:
- Move binder_alloc_is_mapped() check to only protect zap_vma_range() and make error handling consistent, per Alice Ryhl and Lorenzo Stoakes
Patch 3:
- Added Suggested-by, per Lorenzo Stoakes
- Updated the comments for vma_start_read_unlocked(), per Lorenzo Stoakes and Vlastimil Babka
- Updated the patch description, per Vlastimil Babka and Lorenzo Stoakes Patch 4:
- Updated comments for vma_start_read_unlocked() Rust version to be consistent with C, per Lorenzo Stoakes
- Added Reviewed-by and Acked-by, per Alice Ryhl and Lorenzo Stoakes Patch 5:
- Added a note in the changelog why the mmap_lock fallback removal does not affect NOMMU case
Applies cleanly over mm-unstable
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
Dave Hansen (5):
mm: Make per-VMA locks available universally
binder: Make shrinker rely solely on per-VMA lock
mm: Add RCU-based VMA lookup helper that waits for writers
binder: Remove mmap_lock fallback
tcp: Remove mmap_lock fallback path
arch/arm/Kconfig | 1 - arch/arm64/Kconfig | 1 - arch/loongarch/Kconfig | 1 - arch/powerpc/platforms/powernv/Kconfig | 1 - arch/powerpc/platforms/pseries/Kconfig | 1 - arch/riscv/Kconfig | 1 - arch/s390/Kconfig | 1 - arch/x86/Kconfig | 2 - drivers/android/binder/page_range.rs | 19 +----- drivers/android/binder_alloc.c | 62 +++++++---------- fs/proc/internal.h | 2 - fs/proc/task_mmu.c | 93 -------------------------- include/linux/mm.h | 12 ---- include/linux/mm_types.h | 8 +-- include/linux/mmap_lock.h | 89 ++++++++++-------------- kernel/bpf/stackmap.c | 15 ++--- kernel/bpf/task_iter.c | 2 +- kernel/fork.c | 2 - mm/Kconfig | 12 ---- mm/Kconfig.debug | 1 - mm/debug.c | 4 -- mm/init-mm.c | 2 - mm/memory.c | 2 - mm/mmap_lock.c | 59 +++++++++------- mm/pagewalk.c | 2 - mm/rmap.c | 2 - mm/userfaultfd.c | 61 ++--------------- net/ipv4/tcp.c | 31 +++------ rust/kernel/mm.rs | 57 ++++++++++------ tools/testing/vma/include/dup.h | 5 +- tools/testing/vma/vma_internal.h | 1 - 31 files changed, 157 insertions(+), 395 deletions(-)
base-commit: bacc32cc7de65ffff70080a48eb294f89e434d5e
Signature · 1 line
2.55.0.654.g21b8a5bc05-goog
Suren Baghdasaryan
maintainerPATCH v4 1/5 mm: Make per-VMA locks available universally
From: Dave Hansen <[email protected]>
The per-VMA locks have been around for several years. They've had some bugs worked out of them and have seen quite wide use. However, they are still only available when architectures explicitly enable them. Remove the conditional compilation around the per-VMA locks, making them available on all architectures and configs.
The approach up to now seemed to be to add ARCH_SUPPORTS_PER_VMA_LOCK when the architecture started using per-VMA locks in the fault handler. But, contrary to the naming, the Kconfig option does not really indicate whether the architecture supports per-VMA locks or not. It is more of a marker for whether the architecture is likely to benefit from per-VMA locks.
To me, the most important thing side-effect of universal availability is letting per-VMA locks be used in SMP=n configs. This lets us use per-VMA locking in all x86 code without fallbacks.
Overall, this just generally makes the kernel simpler. Just look at the diffstat. It also opens the door to users that want to use the per-VMA locks in common code. Doing *that* brings additional simplifications.
The downside of this is adding some fields to vm_area_struct and mm_struct. There are likely ways to optimize this, especially for things like SMP=n configs. For now, do the simplest thing: use the same implementation everywhere.
== Considerations for NOMMU config ==
NOMMU systems do not write-lock VMAs, therefore read-locking a VMA would always succeed unless VMA is detached. Therefore for NOMMU config we make vma_mark_attached() a NOOP, which keeps VMAs always in detached state. This causes VMA read-locking to always fail and the caller falls back to locking mmap_lock.
The following functions will have a different implementation in NOMMU config:
- vma_mark_attached(), vma_mark_detached() are made NOOPs, keeping VMAs always in a detached state and preventing assertions and refcount underflows;
- vma_start_write(), vma_start_write_killable() are made NOOPs to avoid warnings in __vma_start_write() due to VMAs being detached. These functions are not used in NOMMU code but __vma_start_write() is an exported function, therefore might be used by drivers.
- vma_assert_attached() is made NOOP because it's reachable from NOMMU code via split_vma()->vma_iter_store_new()->vma_iter_store_overwrite();
- vma_assert_write_locked() is asserting vma->vm_mm is write-locked;
The following functions work for both MMU and NOMMU configs:
- vma_lock_init() performs the same initialization as for MMU config;
- mm_lock_seqcount_init(), mm_lock_seqcount_begin(), mm_lock_seqcount_end() are called from mmap_write_{lock|unlock} and update mm_lock_seq correctly.
- mmap_lock_speculate_try_begin(), mmap_lock_speculate_retry() work as is because mm_lock_seq is updated correctly;
- vma_start_read(), vma_start_read_locked() will always fail because VMAs are always detached;
- vma_end_read() will never be called because vma_start_read() never succeeds;
- vma_is_attached() always return false because VMAs are always detached;
- vma_assert_detached() will never trigger because VMAs are never attached;
Changes in the following files are not affecting NOMMU config:
task_mmu.c - not compiled when CONFIG_MMU=n;pagewalk.c - not compiled when CONFIG_MMU=n;userfaultfd.c - not compiled when CONFIG_MMU=n (CONFIG_USERFAULTFD depends on CONFIG_MMU);
The following changes are made to keep NOMMU config working like before:
stack_map_lock_vma() - keeps mmap_lock in NOMMU config; bpf_iter_task_vma_new() - bails out in NOMMU config;
--- arch/arm/Kconfig | 1 - arch/arm64/Kconfig | 1 - arch/loongarch/Kconfig | 1 - arch/powerpc/platforms/powernv/Kconfig | 1 - arch/powerpc/platforms/pseries/Kconfig | 1 - arch/riscv/Kconfig | 1 - arch/s390/Kconfig | 1 - arch/x86/Kconfig | 2 - fs/proc/internal.h | 2 - fs/proc/task_mmu.c | 93 -------------------------- include/linux/mm.h | 12 ---- include/linux/mm_types.h | 8 +-- include/linux/mmap_lock.h | 70 ++++++------------- kernel/bpf/stackmap.c | 15 ++--- kernel/bpf/task_iter.c | 2 +- kernel/fork.c | 2 - mm/Kconfig | 12 ---- mm/Kconfig.debug | 1 - mm/debug.c | 4 -- mm/init-mm.c | 2 - mm/memory.c | 2 - mm/mmap_lock.c | 24 ------- mm/pagewalk.c | 2 - mm/rmap.c | 2 - mm/userfaultfd.c | 55 --------------- rust/kernel/mm.rs | 32 +++------ tools/testing/vma/include/dup.h | 5 +- tools/testing/vma/vma_internal.h | 1 - 28 files changed, 39 insertions(+), 316 deletions(-)
arch/arm/Kconfig +0 -1
@@ -41,7 +41,6 @@ config ARM select ARCH_SUPPORTS_ATOMIC_RMW select ARCH_SUPPORTS_CFI select ARCH_SUPPORTS_HUGETLBFS if ARM_LPAE - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_RT select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_CMPXCHG_LOCKREF
arch/arm64/Kconfig +0 -1
@@ -81,7 +81,6 @@ config ARM64 select ARCH_HAS_PTE_PROTNONE select ARCH_SUPPORTS_NUMA_BALANCING select ARCH_SUPPORTS_PAGE_TABLE_CHECK - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_HUGE_PFNMAP if TRANSPARENT_HUGEPAGE select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SCHED_SMT
arch/loongarch/Kconfig +0 -1
@@ -69,7 +69,6 @@ config LOONGARCH select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS select ARCH_HAS_PTE_PROTNONE if 64BIT select ARCH_SUPPORTS_NUMA_BALANCING if NUMA - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SCHED_SMT if SMP select ARCH_SUPPORTS_SCHED_MC if SMP
arch/powerpc/platforms/powernv/Kconfig +0 -1
@@ -17,7 +17,6 @@ config PPC_POWERNV select PPC_DOORBELL select MMU_NOTIFIER select FORCE_SMP - select ARCH_SUPPORTS_PER_VMA_LOCK select PPC_RADIX_BROADCAST_TLBIE if PPC_RADIX_MMU default y
arch/powerpc/platforms/pseries/Kconfig +0 -1
@@ -23,7 +23,6 @@ config PPC_PSERIES select HOTPLUG_CPU select FORCE_SMP select SWIOTLB - select ARCH_SUPPORTS_PER_VMA_LOCK select PPC_RADIX_BROADCAST_TLBIE if PPC_RADIX_MMU default y
arch/riscv/Kconfig +0 -1
@@ -70,7 +70,6 @@ config RISCV select ARCH_SUPPORTS_LTO_CLANG_THIN select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS if 64BIT && MMU select ARCH_SUPPORTS_PAGE_TABLE_CHECK if MMU - select ARCH_SUPPORTS_PER_VMA_LOCK if MMU select ARCH_HAS_PTE_PROTNONE if MMU select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SHADOW_CALL_STACK if HAVE_SHADOW_CALL_STACK
arch/s390/Kconfig +0 -1
@@ -151,7 +151,6 @@ config S390 select ARCH_HAS_PTE_PROTNONE select ARCH_SUPPORTS_NUMA_BALANCING select ARCH_SUPPORTS_PAGE_TABLE_CHECK - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_CMPXCHG_LOCKREF select ARCH_USE_SYM_ANNOTATIONS
arch/x86/Kconfig +0 -2
@@ -27,7 +27,6 @@ config X86_64 select ARCH_HAS_GIGANTIC_PAGE select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS select ARCH_SUPPORTS_INT128 if CC_HAS_INT128 - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_HUGE_PFNMAP if TRANSPARENT_HUGEPAGE select HAVE_ARCH_SOFT_DIRTY select MODULES_USE_ELF_RELA
@@ -1846,7 +1845,6 @@ config X86_USER_SHADOW_STACK bool "X86 userspace shadow stack" depends on AS_WRUSS depends on X86_64 - depends on PER_VMA_LOCK select ARCH_USES_HIGH_VMA_FLAGS select ARCH_HAS_USER_SHADOW_STACK select X86_CET
fs/proc/internal.h +0 -2
@@ -385,10 +385,8 @@ struct mem_size_stats;struct proc_maps_locking_ctx {struct mm_struct *mm; -#ifdef CONFIG_PER_VMA_LOCK bool mmap_locked;struct vm_area_struct *locked_vma; -#endif };struct proc_maps_private {
fs/proc/task_mmu.c +0 -93
141 lines not on this page · raw message
include/linux/mm.h +0 -12
@@ -931,7 +931,6 @@ static inline void vma_numab_state_free(struct vm_area_struct *vma) {}* These must be here rather than mmap_lock.h as dependent on vm_fault type, * declared in this header. */ -#ifdef CONFIG_PER_VMA_LOCK static inline void release_fault_lock (struct vm_fault *vmf) {if (vmf->flags &FAULT_FLAG_VMA_LOCK )
@@ -947,17 +946,6 @@ static inline void assert_fault_locked(const struct vm_fault *vmf)else mmap_assert_locked (vmf->vma->vm_mm); } -#else -static inline void release_fault_lock (struct vm_fault *vmf) -{ -mmap_read_unlock (vmf->vma->vm_mm); -} - -static inline void assert_fault_locked (const struct vm_fault *vmf) -{ -mmap_assert_locked (vmf->vma->vm_mm); -} -#endif /* CONFIG_PER_VMA_LOCK */ static inline bool mm_flags_test (int flag,const struct mm_struct *mm) {
include/linux/mm_types.h +2 -6
@@ -950,7 +950,6 @@ struct vm_area_struct {vma_flags_t flags; }; -#ifdef CONFIG_PER_VMA_LOCK /* * Can only be written (using WRITE_ONCE()) while holding both: * - mmap_lock (in write mode)
@@ -966,7 +965,7 @@ struct vm_area_struct {* slowpath. */ unsigned int vm_lock_seq; -#endif +/* * Low 32-bits of virtual page offset. * See vma_start_virt_pgoff() comment for details.
@@ -1003,7 +1002,6 @@ struct vm_area_struct {#ifdef CONFIG_NUMA_BALANCING struct vma_numab_state *numab_state;/* NUMA Balancing state */ #endif -#ifdef CONFIG_PER_VMA_LOCK /* * Used to keep track of firstly, whether the VMA is attached, secondly, * if attached, how many read locks are taken, and thirdly, if the
@@ -1046,7 +1044,6 @@ struct vm_area_struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map vmlock_dep_map;#endif -#endif #ifdef CONFIG_64BIT /* * High 32-bits of virtual page offset.
@@ -1254,7 +1251,6 @@ struct mm_struct {* init_mm.mmlist, and are protected * by mmlist_lock */ -#ifdef CONFIG_PER_VMA_LOCK struct rcuwait vma_writer_wait;/* * This field has lock-like semantics, meaning it is sometimes
@@ -1274,7 +1270,7 @@ struct mm_struct {* mmap_lock. */ seqcount_t mm_lock_seq; -#endif +struct futex_mm_data futex;unsigned long hiwater_rss;/* High-watermark of RSS usage */
include/linux/mmap_lock.h +20 -50
118 lines not on this page · raw message
kernel/bpf/stackmap.c +4 -11
@@ -272,13 +272,8 @@ struct stack_map_vma_lock {/* * Acquire a stable read-side reference on the VMA covering @ip. * -* With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read -* lock held and mmap_lock dropped, so the caller may sleep. -* -* With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still -* held; the caller must snapshot any fields it needs and pin vm_file -* with get_file() before stack_map_unlock_vma() drops mmap_lock, as -* the VMA may be split, merged, or freed after that. +* This returns a VMA with its per-VMA read lock held and mmap_lock +* dropped, so the caller may sleep. * * Returns NULL on failure, in which case no lock is held. */
@@ -288,7 +283,6 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)struct mm_struct *mm = lock->mm;struct vm_area_struct *vma; -/* noop under !CONFIG_PER_VMA_LOCK */ vma =lock_vma_under_rcu (mm, ip);if (vma) { lock->vma = vma;
@@ -308,21 +302,20 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)return NULL ; } -#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU if (!vma_start_read_locked (vma)) {mmap_read_unlock (mm);return NULL ; }mmap_read_unlock (mm);#endif - lock->vma = vma;return vma; }static void stack_map_unlock_vma (struct stack_map_vma_lock *lock) { -#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU vma_end_read (lock->vma);#else mmap_read_unlock (lock->mm);
kernel/bpf/task_iter.c +1 -1
@@ -835,7 +835,7 @@ __bpf_kfunc int bpf_iter_task_vma_new(struct bpf_iter_task_vma *it,BUILD_BUG_ON (sizeof (struct bpf_iter_task_vma_kern ) !=sizeof (struct bpf_iter_task_vma ));BUILD_BUG_ON (__alignof__(struct bpf_iter_task_vma_kern ) != __alignof__(struct bpf_iter_task_vma )); -if (!IS_ENABLED (CONFIG_PER_VMA_LOCK )) { +if (!IS_ENABLED (CONFIG_MMU )) { kit->data =NULL ;return -EOPNOTSUPP ; }
kernel/fork.c +0 -2
@@ -1077,9 +1077,7 @@ static void mmap_init_lock(struct mm_struct *mm) {init_rwsem (&mm->mmap_lock);mm_lock_seqcount_init (mm); -#ifdef CONFIG_PER_VMA_LOCK rcuwait_init (&mm->vma_writer_wait); -#endif }static struct mm_struct *mm_init (struct mm_struct *mm,struct task_struct *p)
mm/Kconfig +0 -12
@@ -1429,18 +1429,6 @@ config LRU_GEN_WALKS_MMU depends on LRU_GEN && ARCH_HAS_HW_PTE_YOUNG # } -config ARCH_SUPPORTS_PER_VMA_LOCK - def_bool n - -config PER_VMA_LOCK - def_bool y - depends on ARCH_SUPPORTS_PER_VMA_LOCK && MMU && SMP - help - Allow per-vma locking during page fault handling. - - This feature allows locking each virtual memory area separately when - handling page faults instead of taking mmap_lock. - config LOCK_MM_AND_FIND_VMA bool depends on !STACK_GROWSUP
mm/Kconfig.debug +0 -1
@@ -310,7 +310,6 @@ config DEBUG_KMEMLEAK_VERBOSE config PER_VMA_LOCK_STATS bool "Statistics for per-vma locks" - depends on PER_VMA_LOCK help Say Y here to enable success, retry and failure counters of page faults handled under protection of per-vma locks. When enabled, the
mm/debug.c +0 -4
@@ -157,17 +157,13 @@ void dump_vma(const struct vm_area_struct *vma)pr_emerg ("vma %px start %px end %px mm %px\n" "prot %lx anon_vma %px vm_ops %px\n" "pgoff %lx file %px private_data %px\n" -#ifdef CONFIG_PER_VMA_LOCK"refcnt %x\n" -#endif"flags: %#lx(%pGv)\n" , vma, (void *)vma->vm_start, (void *)vma->vm_end, vma->vm_mm, (unsigned long )pgprot_val (vma->vm_page_prot), vma->anon_vma, vma->vm_ops,vma_start_pgoff (vma), vma->vm_file, vma->vm_private_data, -#ifdef CONFIG_PER_VMA_LOCKrefcount_read (&vma->vm_refcnt), -#endif vma->vm_flags, &vma->vm_flags); }EXPORT_SYMBOL (dump_vma);
mm/init-mm.c +0 -2
@@ -39,10 +39,8 @@ struct mm_struct init_mm = { .page_table_lock = __SPIN_LOCK_UNLOCKED(init_mm.page_table_lock), .arg_lock = __SPIN_LOCK_UNLOCKED(init_mm.arg_lock), .mmlist = LIST_HEAD_INIT(init_mm.mmlist), -#ifdef CONFIG_PER_VMA_LOCK .vma_writer_wait = __RCUWAIT_INITIALIZER(init_mm.vma_writer_wait), .mm_lock_seq = SEQCNT_ZERO(init_mm.mm_lock_seq), -#endif #ifdef CONFIG_SCHED_MM_CID .mm_cid.lock = __RAW_SPIN_LOCK_UNLOCKED(init_mm.mm_cid.lock),#endif
mm/memory.c +0 -2
@@ -6814,7 +6814,6 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, !is_cow_mapping(vma->vm_flags)))return VM_FAULT_SIGSEGV ; } -#ifdef CONFIG_PER_VMA_LOCK /* * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of * the assumption that lock is dropped on VM_FAULT_RETRY.
@@ -6823,7 +6822,6 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) == (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)))return VM_FAULT_SIGSEGV ; -#endif return 0 ; }
mm/mmap_lock.c +0 -24
@@ -43,9 +43,6 @@ void __mmap_lock_do_trace_released(struct mm_struct *mm, bool write)EXPORT_SYMBOL (__mmap_lock_do_trace_released);#endif /* CONFIG_TRACING */ -#ifdef CONFIG_MMU -#ifdef CONFIG_PER_VMA_LOCK -/* State shared across __vma_[start, end]_exclude_readers. */ struct vma_exclude_readers_state {/* Input parameters. */
@@ -431,7 +428,6 @@ struct vm_area_struct *lock_next_vma(struct mm_struct *mm,return vma; } -#endif /* CONFIG_PER_VMA_LOCK */ #ifdef CONFIG_LOCK_MM_AND_FIND_VMA #include <linux/extable.h>
@@ -548,23 +544,3 @@ struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm, return NULL; }#endif /* CONFIG_LOCK_MM_AND_FIND_VMA */ - -#else /* CONFIG_MMU */ - -/* -* At least xtensa ends up having protection faults even with no -* MMU.. No stack expansion, at least. -*/ -struct vm_area_struct *lock_mm_and_find_vma (struct mm_struct *mm, -unsigned long addr,struct pt_regs *regs) -{ -struct vm_area_struct *vma; - -mmap_read_lock (mm); - vma =vma_lookup (mm, addr); -if (!vma) -mmap_read_unlock (mm); -return vma; -} - -#endif /* CONFIG_MMU */
mm/pagewalk.c +0 -2
@@ -446,7 +446,6 @@ static inline void process_mm_walk_lock(struct mm_struct *mm,static inline void process_vma_walk_lock (struct vm_area_struct *vma,enum page_walk_lock walk_lock) { -#ifdef CONFIG_PER_VMA_LOCK switch (walk_lock) {case PGWALK_WRLOCK :vma_start_write (vma);
@@ -461,7 +460,6 @@ static inline void process_vma_walk_lock(struct vm_area_struct *vma,/* PGWALK_RDLOCK is handled by process_mm_walk_lock */ break ; } -#endif }/*
mm/rmap.c +0 -2
@@ -260,11 +260,9 @@ static void check_anon_vma_clone(struct vm_area_struct *dst,/* For the anon_vma to be compatible, it can only be singular. */ VM_WARN_ON_ONCE (operation ==VMA_OP_MERGE_UNFAULTED && !list_is_singular (&src->anon_vma_chain)); -#ifdef CONFIG_PER_VMA_LOCK /* Only merging an unfaulted VMA leaves the destination attached. */ VM_WARN_ON_ONCE (operation !=VMA_OP_MERGE_UNFAULTED &&vma_is_attached (dst)); -#endif } static void maybe_reuse_anon_vma(struct vm_area_struct *dst,
mm/userfaultfd.c +0 -55
79 lines not on this page · raw message
rust/kernel/mm.rs +11 -21
@@ -170,30 +170,20 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_struct) -> &'a MmWithUser {/// /// This is an optimistic trylock operation, so it may fail if there is contention. In that /// case, you should fall back to taking the mmap read lock. -/// -/// When per-vma locks are disabled, this always returns `None`. #[inline] pub fn lock_vma_under_rcu (&self, vma_addr:usize ) ->Option <VmaReadGuard <'_>> { -#[cfg( CONFIG_PER_VMA_LOCK )] - { -// SAFETY: Calling `bindings::lock_vma_under_rcu` is always okay given an mm where -// `mm_users` is non-zero. -let vma =unsafe { bindings::lock_vma_under_rcu (self.as_raw (), vma_addr) }; -if !vma.is_null () { -return Some (VmaReadGuard { -// SAFETY: If `lock_vma_under_rcu` returns a non-null ptr, then it points at a -// valid vma. The vma is stable for as long as the vma read lock is held. - vma:unsafe {VmaRef ::from_raw (vma) }, - _nts:NotThreadSafe , - }); - } +// SAFETY: Calling `bindings::lock_vma_under_rcu` is always okay given an mm where +// `mm_users` is non-zero. +let vma =unsafe { bindings::lock_vma_under_rcu (self.as_raw (), vma_addr) }; +if vma.is_null () { +return None ; } - -// Silence warnings about unused variables. -#[cfg(not( CONFIG_PER_VMA_LOCK ))] -let _ = vma_addr; - -None +Some (VmaReadGuard { +// SAFETY: If `lock_vma_under_rcu` returns a non-null ptr, then it points at a +// valid vma. The vma is stable for as long as the vma read lock is held. + vma:unsafe {VmaRef ::from_raw (vma) }, + _nts:NotThreadSafe , + }) }/// Lock the mmap read lock.
tools/testing/vma/include/dup.h +1 -4
@@ -582,7 +582,6 @@ struct vm_area_struct {vma_flags_t flags; }; -#ifdef CONFIG_PER_VMA_LOCK /* * Can only be written (using WRITE_ONCE()) while holding both: * - mmap_lock (in write mode)
@@ -598,7 +597,7 @@ struct vm_area_struct {* slowpath. */ unsigned int vm_lock_seq; -#endif +unsigned int __vm_virt_pgoff_lo;/*
@@ -632,10 +631,8 @@ struct vm_area_struct {#ifdef CONFIG_NUMA_BALANCING struct vma_numab_state *numab_state;/* NUMA Balancing state */ #endif -#ifdef CONFIG_PER_VMA_LOCK /* Unstable RCU readers are allowed to read this. */ refcount_t vm_refcnt; -#endif #ifdef CONFIG_64BIT unsigned int __vm_virt_pgoff_hi;#endif
tools/testing/vma/vma_internal.h +0 -1
@@ -15,7 +15,6 @@#include <stdlib.h> #define CONFIG_MMU 1 -#define CONFIG_PER_VMA_LOCK 1#ifdef __CONCAT#undef __CONCAT
Signature · 1 line
2.55.0.654.g21b8a5bc05-goog
Re: [PATCH v4 1/5] mm: Make per-VMA locks available universally
Quoted 96 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
The per-VMA locks have been around for several years. They've had some bugs worked out of them and have seen quite wide use. However, they are still only available when architectures explicitly enable them. Remove the conditional compilation around the per-VMA locks, making them available on all architectures and configs.
The approach up to now seemed to be to add
ARCH_SUPPORTS_PER_VMA_LOCKwhen the architecture started using per-VMA locks in the fault handler. But, contrary to the naming, theKconfigoption does not really indicate whether the architecture supports per-VMA locks or not. It is more of a marker for whether the architecture is likely to benefit from per-VMA locks.To me, the most important thing side-effect of universal availability is letting per-VMA locks be used in SMP=n configs. This lets us use per-VMA locking in all x86 code without fallbacks.
Overall, this just generally makes the kernel simpler. Just look at the diffstat. It also opens the door to users that want to use the per-VMA locks in common code. Doing *that* brings additional simplifications.
The downside of this is adding some fields to
vm_area_structandmm_struct. There are likely ways to optimize this, especially for things like SMP=n configs. For now, do the simplest thing: use the same implementation everywhere.== Considerations for NOMMU config ==
NOMMU systems do not write-lock VMAs, therefore read-locking a VMA would always succeed unless VMA is detached. Therefore for NOMMU config we make
vma_mark_attached()a NOOP, which keeps VMAs always in detached state. This causes VMA read-locking to always fail and the caller falls back to lockingmmap_lock.The following functions will have a different implementation in NOMMU config:
-
vma_mark_attached(),vma_mark_detached()are made NOOPs, keeping VMAs always in a detached state and preventing assertions and refcount underflows;-
vma_start_write(),vma_start_write_killable()are made NOOPs to avoid warnings in__vma_start_write()due to VMAs being detached. These functions are not used in NOMMU code but__vma_start_write()is an exported function, therefore might be used by drivers.-
vma_assert_attached()is made NOOP because it's reachable from NOMMU code via split_vma()->vma_iter_store_new()->vma_iter_store_overwrite();-
vma_assert_write_locked()is assertingvma->vm_mmis write-locked;The following functions work for both MMU and NOMMU configs:
-
vma_lock_init()performs the same initialization as for MMU config;-
mm_lock_seqcount_init(),mm_lock_seqcount_begin(),mm_lock_seqcount_end()are called from mmap_write_{lock|unlock} and updatemm_lock_seqcorrectly.-
mmap_lock_speculate_try_begin(),mmap_lock_speculate_retry()work as is becausemm_lock_seqis updated correctly;-
vma_start_read(),vma_start_read_locked()will always fail because VMAs are always detached;-
vma_end_read()will never be called becausevma_start_read()never succeeds;-
vma_is_attached()always return false because VMAs are always detached;-
vma_assert_detached()will never trigger because VMAs are never attached;Changes in the following files are not affecting NOMMU config:
task_mmu.c- not compiled whenCONFIG_MMU=n;pagewalk.c- not compiled whenCONFIG_MMU=n;userfaultfd.c- not compiled whenCONFIG_MMU=n(CONFIG_USERFAULTFDdepends onCONFIG_MMU);The following changes are made to keep NOMMU config working like before:
stack_map_lock_vma()- keepsmmap_lockin NOMMU config;bpf_iter_task_vma_new()- bails out in NOMMU config;Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Lorenzo Stoakes <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>
Quoted 8 lines
Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>
Re: [PATCH v4 1/5] mm: Make per-VMA locks available universally
In reply to Suren BaghdasaryanQuoted 4 lines · Suren Baghdasaryan
+++
b/kernel/bpf/stackmap.ckernel/bpf/stackmap.c +0
-0@@ -272,13 +272,8 @@ struct stack_map_vma_lock {/* * Acquire a stable read-side reference on the VMA covering @ip.
kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 276
Quoted 10 lines
kernel/bpf/stackmap.c +2
-7* -* With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read -* lock held and mmap_lock dropped, so the caller may sleep. -* -* With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still -* held; the caller must snapshot any fields it needs and pin vm_file -* with get_file() before stack_map_unlock_vma() drops mmap_lock, as -* the VMA may be split, merged, or freed after that. +* This returns a VMA with its per-VMA read lock held and mmap_lock +* dropped, so the caller may sleep.
I don't know if BPF is compatible with !MMU or not, but the comment is inconsistent with the code. How about:
* On NOMMU configurations, returns with the mmap_lock held. If the MMU
* is enabled, the per-VMA lock will be held instead. The lock
* should be released with stack_map_unlock_vma() which will release the
* appropriate lock. Once the lock is released, the VMA may be freed.
Quoted 26 lines
kernel/bpf/stackmap.c +1
-3* Returns NULL on failure, in which case no lock is held. */ @@ -288,7 +283,6 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)struct mm_struct *mm = lock->mm;struct vm_area_struct *vma; -/* noop under !CONFIG_PER_VMA_LOCK */ vma =lock_vma_under_rcu (mm, ip);if (vma) { lock->vma = vma;@@ -308,21 +302,20 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)return NULL ; } -#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU if (!vma_start_read_locked (vma)) {mmap_read_unlock (mm);return NULL ; }mmap_read_unlock (mm);#endif - lock->vma = vma;return vma; }
Suren Baghdasaryan
maintainerRe: [PATCH v4 1/5] mm: Make per-VMA locks available universally
Quoted 20 lines · Matthew Wilcox
Quoted 4 lines · Suren Baghdasaryan
+++
b/kernel/bpf/stackmap.ckernel/bpf/stackmap.c +0
-0@@ -272,13 +272,8 @@ struct stack_map_vma_lock {/* * Acquire a stable read-side reference on the VMA covering @ip. kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 276
Quoted 10 lines
kernel/bpf/stackmap.c +2
-7* -* With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read -* lock held and mmap_lock dropped, so the caller may sleep. -* -* With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still -* held; the caller must snapshot any fields it needs and pin vm_file -* with get_file() before stack_map_unlock_vma() drops mmap_lock, as -* the VMA may be split, merged, or freed after that. +* This returns a VMA with its per-VMA read lock held and mmap_lock +* dropped, so the caller may sleep. I don't know if BPF is compatible with !MMU or not, but the comment is inconsistent with the code. How about:
Quoted 4 lines
* On NOMMU configurations, returns with the
mmap_lockheld. If the MMU
* is enabled, the per-VMA lock will be held instead. The lock
* should be released withstack_map_unlock_vma()which will release the
* appropriate lock. Once the lock is released, the VMA may be freed.
Good point. I'll update the comment here. Thanks Matthew!
Quoted 27 lines
Quoted 27 lines
kernel/bpf/stackmap.c +1
-3* Returns NULL on failure, in which case no lock is held. */ @@ -288,7 +283,6 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)struct mm_struct *mm = lock->mm;struct vm_area_struct *vma; -/* noop under !CONFIG_PER_VMA_LOCK */ vma =lock_vma_under_rcu (mm, ip);if (vma) { lock->vma = vma;@@ -308,21 +302,20 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)return NULL ; } -#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU if (!vma_start_read_locked (vma)) {mmap_read_unlock (mm);return NULL ; }mmap_read_unlock (mm);#endif - lock->vma = vma;return vma; }
Lorenzo Stoakes (ARM)
maintainerRe: [PATCH v4 1/5] mm: Make per-VMA locks available universally
In reply to Matthew WilcoxQuoted 10 lines · Matthew Wilcox
Quoted 9 lines · Suren Baghdasaryan
+++
b/kernel/bpf/stackmap.ckernel/bpf/stackmap.c +0
-4@@ -272,13 +272,8 @@ struct stack_map_vma_lock {/* * Acquire a stable read-side reference on the VMA covering @ip. * -* With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read -* lock held and mmap_lock dropped, so the caller may sleep. -* -* With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still
Quoted 8 lines
kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 276
Quoted 5 lines
kernel/bpf/stackmap.c +2
-3-* held; the caller must snapshot any fields it needs and pin vm_file -* with get_file() before stack_map_unlock_vma() drops mmap_lock, as -* the VMA may be split, merged, or freed after that. +* This returns a VMA with its per-VMA read lock held and mmap_lock +* dropped, so the caller may sleep. I don't know if BPF is compatible with !MMU or not, but the comment is inconsistent with the code. How about:
<requisite nommu rant>
I do think there are components that simply don't think to depend on CONFIG_MMU even though they do.
In fact more than think - have run into exactly that before.
It's another thing that speaks to nommu being a legacy barnacle that bashes us on the head fairly regularly for little to no gain (and nobody is testing it for tip kernel AFAICT).
</requisite nommu rant>
Quoted 5 lines
* On NOMMU configurations, returns with the
mmap_lockheld. If the MMU
* is enabled, the per-VMA lock will be held instead. The lock
* should be released withstack_map_unlock_vma()which will release the
* appropriate lock. Once the lock is released, the VMA may be freed.
I mean I suppose it's accurate but I don't love the idea of essentially implying nommu+bpf is a thing and also treating it as so important that it must be called out here.
I'd rather it be inaccurate for nommu as are most comments in mm and mm-adjacent components, it's kinda implied in general. Those who care can look at the code.
Quoted 15 lines
Quoted 15 lines
kernel/bpf/stackmap.c +0
-1* Returns NULL on failure, in which case no lock is held. */ @@ -288,7 +283,6 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)struct mm_struct *mm = lock->mm;struct vm_area_struct *vma; -/* noop under !CONFIG_PER_VMA_LOCK */ vma =lock_vma_under_rcu (mm, ip);if (vma) { lock->vma = vma;@@ -308,21 +302,20 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)return NULL ; }
Quoted 12 lines
kernel/bpf/stackmap.c stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip) · line 314
Quoted 12 lines
kernel/bpf/stackmap.c +1
-2-#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU if (!vma_start_read_locked (vma)) {mmap_read_unlock (mm);return NULL ; }mmap_read_unlock (mm);#endif - lock->vma = vma;return vma; }
--
Cheers, Lorenzo
Lorenzo Stoakes (ARM)
maintainerRe: [PATCH v4 1/5] mm: Make per-VMA locks available universally
Quoted 39 lines · Lorenzo Stoakes (ARM)
Quoted 10 lines · Matthew Wilcox
Quoted 9 lines · Suren Baghdasaryan
+++
b/kernel/bpf/stackmap.ckernel/bpf/stackmap.c +0
-4@@ -272,13 +272,8 @@ struct stack_map_vma_lock {/* * Acquire a stable read-side reference on the VMA covering @ip. * -* With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read -* lock held and mmap_lock dropped, so the caller may sleep. -* -* With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still Quoted 8 lines
kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 276
Quoted 5 lines
kernel/bpf/stackmap.c +2
-3-* held; the caller must snapshot any fields it needs and pin vm_file -* with get_file() before stack_map_unlock_vma() drops mmap_lock, as -* the VMA may be split, merged, or freed after that. +* This returns a VMA with its per-VMA read lock held and mmap_lock +* dropped, so the caller may sleep. I don't know if BPF is compatible with !MMU or not, but the comment is inconsistent with the code. How about:
<requisite nommu rant>
I do think there are components that simply don't think to depend on
CONFIG_MMUeven though they do.In fact more than think - have run into exactly that before.
It's another thing that speaks to nommu being a legacy barnacle that bashes us on the head fairly regularly for little to no gain (and nobody is testing it for tip kernel AFAICT).
</requisite nommu rant>
Quoted 5 lines
* On NOMMU configurations, returns with the
mmap_lockheld. If the MMU
* is enabled, the per-VMA lock will be held instead. The lock
* should be released withstack_map_unlock_vma()which will release the
* appropriate lock. Once the lock is released, the VMA may be freed.
Quoted 6 lines
I mean I suppose it's accurate but I don't love the idea of essentially implying nommu+bpf is a thing and also treating it as so important that it must be called out here.
I'd rather it be inaccurate for nommu as are most comments in mm and mm-adjacent components, it's kinda implied in general. Those who care can look at the code.
Actually scratch that I'm wrong, firstly Suren's series explicitly does some nommu-specific logic in the bpf code and secondly BPF already has nommu-specific stuff in it.
It seems nommu bpf is (kinda) a supported path.
Quoted 4 lines
Quoted 4 lines
kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 279
Quoted 4 lines
kernel/bpf/stackmap.c +0
-0* Returns NULL on failure, in which case no lock is held. */
--
Cheers, Lorenzo
Suren Baghdasaryan
maintainerRe: [PATCH v4 1/5] mm: Make per-VMA locks available universally
Quoted 45 lines · Lorenzo Stoakes (ARM)
Quoted 43 lines · Lorenzo Stoakes (ARM)
Quoted 10 lines · Matthew Wilcox
Quoted 9 lines · Suren Baghdasaryan
+++
b/kernel/bpf/stackmap.ckernel/bpf/stackmap.c +0
-4@@ -272,13 +272,8 @@ struct stack_map_vma_lock {/* * Acquire a stable read-side reference on the VMA covering @ip. * -* With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read -* lock held and mmap_lock dropped, so the caller may sleep. -* -* With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still Quoted 8 lines
kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 276
Quoted 5 lines
kernel/bpf/stackmap.c +2
-3-* held; the caller must snapshot any fields it needs and pin vm_file -* with get_file() before stack_map_unlock_vma() drops mmap_lock, as -* the VMA may be split, merged, or freed after that. +* This returns a VMA with its per-VMA read lock held and mmap_lock +* dropped, so the caller may sleep. I don't know if BPF is compatible with !MMU or not, but the comment is inconsistent with the code. How about:
<requisite nommu rant>
I do think there are components that simply don't think to depend on
CONFIG_MMUeven though they do.In fact more than think - have run into exactly that before.
It's another thing that speaks to nommu being a legacy barnacle that bashes us on the head fairly regularly for little to no gain (and nobody is testing it for tip kernel AFAICT).
</requisite nommu rant>
Quoted 5 lines
* On NOMMU configurations, returns with the
mmap_lockheld. If the MMU
* is enabled, the per-VMA lock will be held instead. The lock
* should be released withstack_map_unlock_vma()which will release the
* appropriate lock. Once the lock is released, the VMA may be freed.I mean I suppose it's accurate but I don't love the idea of essentially implying nommu+bpf is a thing and also treating it as so important that it must be called out here.
Quoted 8 lines
Quoted 2 lines
I'd rather it be inaccurate for nommu as are most comments in mm and mm-adjacent components, it's kinda implied in general. Those who care can look at the code.
Actually scratch that I'm wrong, firstly Suren's series explicitly does some nommu-specific logic in the bpf code and secondly BPF already has nommu-specific stuff in it.
It seems nommu bpf is (kinda) a supported path.
Ok, I'll change it the way Matthew suggested then.
Quoted 8 lines
Quoted 5 lines
Quoted 5 lines
kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 279
Quoted 5 lines
kernel/bpf/stackmap.c +0
-0* Returns NULL on failure, in which case no lock is held. */ --
Cheers, Lorenzo
Lorenzo Stoakes (ARM)
maintainerRe: [PATCH v4 1/5] mm: Make per-VMA locks available universally
In reply to Suren BaghdasaryanQuoted 8 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
The per-VMA locks have been around for several years. They've had some bugs worked out of them and have seen quite wide use. However, they are still only available when architectures explicitly enable them. Remove the conditional compilation around the per-VMA locks, making them available on all architectures and configs.
Quoted 6 lines
The approach up to now seemed to be to add
ARCH_SUPPORTS_PER_VMA_LOCKwhen the architecture started using per-VMA locks in the fault handler. But, contrary to the naming, theKconfigoption does not really indicate whether the architecture supports per-VMA locks or not. It is more of a marker for whether the architecture is likely to benefit from per-VMA locks.
Thanks for clarifying this. I'm very glad we're getting rid of this :) it was a bit too conservative I think.
Quoted 9 lines
To me, the most important thing side-effect of universal availability is letting per-VMA locks be used in SMP=n configs. This lets us use per-VMA locking in all x86 code without fallbacks.
Overall, this just generally makes the kernel simpler. Just look at the diffstat. It also opens the door to users that want to use the per-VMA locks in common code. Doing *that* brings additional simplifications.
Yes!
Quoted 5 lines
The downside of this is adding some fields to
vm_area_structandmm_struct. There are likely ways to optimize this, especially for things like SMP=n configs. For now, do the simplest thing: use the same implementation everywhere.
I think for most cases SMP=n arches are not going to be scaling too crazily on threads/processes anyway.
If real world usecases exist that the struct bloat causes problems for then optimisations for those can be looked into.
But I wonder if cache line alignment would in any case alter the impact of this anyway?
Quoted 8 lines
== Considerations for NOMMU config ==
NOMMU systems do not write-lock VMAs, therefore read-locking a VMA would always succeed unless VMA is detached. Therefore for NOMMU config we make
vma_mark_attached()a NOOP, which keeps VMAs always in detached state. This causes VMA read-locking to always fail and the caller falls back to lockingmmap_lock.
Nice, I think this is the best way of handling nommu.
Quoted 4 lines
The following functions will have a different implementation in NOMMU config:
Quoted 8 lines
-
vma_mark_attached(),vma_mark_detached()are made NOOPs, keeping VMAs always in a detached state and preventing assertions and refcount underflows;-
vma_start_write(),vma_start_write_killable()are made NOOPs to avoid warnings in__vma_start_write()due to VMAs being detached. These functions are not used in NOMMU code but__vma_start_write()is an exported function, therefore might be used by drivers.
OK so being cautious. It sucks to do it but the IS_ENABLED(CONFIG_MMU) guard pattern makes it much less egregious.
Quoted 3 lines
-
vma_assert_attached()is made NOOP because it's reachable from NOMMU code via split_vma()->vma_iter_store_new()->vma_iter_store_overwrite();
Ugh yeah.
Quoted 2 lines
-
vma_assert_write_locked()is assertingvma->vm_mmis write-locked;
I'm confused by this one how is that reachable and how is that addressed? Seems like this sentence is missing something :)
Quoted 14 lines
The following functions work for both MMU and NOMMU configs:
-
vma_lock_init()performs the same initialization as for MMU config;-
mm_lock_seqcount_init(),mm_lock_seqcount_begin(),mm_lock_seqcount_end()are called from mmap_write_{lock|unlock} and updatemm_lock_seqcorrectly.-
mmap_lock_speculate_try_begin(),mmap_lock_speculate_retry()work as is becausemm_lock_seqis updated correctly;-
vma_start_read(),vma_start_read_locked()will always fail because VMAs are always detached;
Quoted 6 lines
-
vma_end_read()will never be called becausevma_start_read()never succeeds;-
vma_is_attached()always return false because VMAs are always detached;-
vma_assert_detached()will never trigger because VMAs are never attached;
Nice thanks for the write up!
Maybe worth looking ahead and pointing out that vma_start_read_unlocked() will also be safe (i.e. the attempted read lock will bail).
Though perhaps you'd want an IS_ENABLED(CONFIG_MMU) there to avoid wasted mmap lock toggling (will comment on that patch if you didn't already handle that there! :)
Quoted 8 lines
Changes in the following files are not affecting NOMMU config:
task_mmu.c- not compiled whenCONFIG_MMU=n;pagewalk.c- not compiled whenCONFIG_MMU=n;userfaultfd.c- not compiled whenCONFIG_MMU=n(CONFIG_USERFAULTFDdepends onCONFIG_MMU);
Quoted 4 lines
The following changes are made to keep NOMMU config working like before:
stack_map_lock_vma()- keepsmmap_lockin NOMMU config;bpf_iter_task_vma_new()- bails out in NOMMU config;
Worth saying both are in the BPF code.
Quoted 41 lines
Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Lorenzo Stoakes <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- arch/arm/Kconfig | 1 - arch/arm64/Kconfig | 1 - arch/loongarch/Kconfig | 1 - arch/powerpc/platforms/powernv/Kconfig | 1 - arch/powerpc/platforms/pseries/Kconfig | 1 - arch/riscv/Kconfig | 1 - arch/s390/Kconfig | 1 - arch/x86/Kconfig | 2 - fs/proc/internal.h | 2 - fs/proc/task_mmu.c | 93 -------------------------- include/linux/mm.h | 12 ---- include/linux/mm_types.h | 8 +-- include/linux/mmap_lock.h | 70 ++++++------------- kernel/bpf/stackmap.c | 15 ++--- kernel/bpf/task_iter.c | 2 +- kernel/fork.c | 2 - mm/Kconfig | 12 ---- mm/Kconfig.debug | 1 - mm/debug.c | 4 -- mm/init-mm.c | 2 - mm/memory.c | 2 -
Quoted 8 lines
mm/mmap_lock.c | 24 ------- mm/pagewalk.c | 2 - mm/rmap.c | 2 - mm/userfaultfd.c | 55 --------------- rust/kernel/mm.rs | 32 +++------ tools/testing/vma/include/dup.h | 5 +- tools/testing/vma/vma_internal.h | 1 - 28 files changed, 39 insertions(+), 316 deletions(-)
Still a lovely diffstat :) good.
Quoted 90 lines
arch/arm/Kconfig +0
-1@@ -41,7 +41,6 @@ config ARM select ARCH_SUPPORTS_ATOMIC_RMW select ARCH_SUPPORTS_CFI select ARCH_SUPPORTS_HUGETLBFS if ARM_LPAE - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_RT select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_CMPXCHG_LOCKREFarch/arm64/Kconfig +0
-1@@ -81,7 +81,6 @@ config ARM64 select ARCH_HAS_PTE_PROTNONE select ARCH_SUPPORTS_NUMA_BALANCING select ARCH_SUPPORTS_PAGE_TABLE_CHECK - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_HUGE_PFNMAP if TRANSPARENT_HUGEPAGE select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SCHED_SMTarch/loongarch/Kconfig +0
-1@@ -69,7 +69,6 @@ config LOONGARCH select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS select ARCH_HAS_PTE_PROTNONE if 64BIT select ARCH_SUPPORTS_NUMA_BALANCING if NUMA - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SCHED_SMT if SMP select ARCH_SUPPORTS_SCHED_MC if SMParch/powerpc/platforms/powernv/Kconfig +0
-1@@ -17,7 +17,6 @@ config PPC_POWERNV select PPC_DOORBELL select MMU_NOTIFIER select FORCE_SMP - select ARCH_SUPPORTS_PER_VMA_LOCK select PPC_RADIX_BROADCAST_TLBIE if PPC_RADIX_MMU default yarch/powerpc/platforms/pseries/Kconfig +0
-1@@ -23,7 +23,6 @@ config PPC_PSERIES select HOTPLUG_CPU select FORCE_SMP select SWIOTLB - select ARCH_SUPPORTS_PER_VMA_LOCK select PPC_RADIX_BROADCAST_TLBIE if PPC_RADIX_MMU default yarch/riscv/Kconfig +0
-1@@ -70,7 +70,6 @@ config RISCV select ARCH_SUPPORTS_LTO_CLANG_THIN select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS if 64BIT && MMU select ARCH_SUPPORTS_PAGE_TABLE_CHECK if MMU - select ARCH_SUPPORTS_PER_VMA_LOCK if MMU select ARCH_HAS_PTE_PROTNONE if MMU select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SHADOW_CALL_STACK if HAVE_SHADOW_CALL_STACKarch/s390/Kconfig +0
-1@@ -151,7 +151,6 @@ config S390 select ARCH_HAS_PTE_PROTNONE select ARCH_SUPPORTS_NUMA_BALANCING select ARCH_SUPPORTS_PAGE_TABLE_CHECK - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_CMPXCHG_LOCKREF select ARCH_USE_SYM_ANNOTATIONSarch/x86/Kconfig +0
-0
arch/x86/Kconfig config X86_64 · line 30
Quoted 4 lines
arch/x86/Kconfig +0
-1@@ -27,7 +27,6 @@ config X86_64 select ARCH_HAS_GIGANTIC_PAGE select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS select ARCH_SUPPORTS_INT128 if CC_HAS_INT128 - select ARCH_SUPPORTS_PER_VMA_LOCK
I'm glad we're getting rid of ARCH_SUPPORTS_PER_VMA_LOCK, it seemed to be an arbitrary 'these are arches that both _use_ it and _support_ it'.
And really every arch supports them.
We can't really have assumed anyway that an arch would definitely take a VMA read lock (alone) for page faulting as that was always a best-effort thing, so dropping this can't break anything.
In general I can't see any reason why actively using VMA locks the way we do in core mm would be detrimental to arches that don't currently have ARCH_SUPPORTS_PER_VMA_LOCK.
And on the same basis I think they should also do the same VMA lock faulting logic as everybody else. I can't see why they wouldn't just be faster on !ARCH_SUPPORTS_PER_VMA_LOCK arches.
But they will be at worse equivalently performing or perhaps _less_ adventageous than other arches.
And, in general, having consistent per-arch fault logic would be a good thing (TM) (and particularly - as Matthew intends to do - having shared code for this is a _really_ good idea, the duplication right now is horrible).
So perhaps Matthew could do this as part of his changes or you could follow up with changes to do that?
I think his work would be made easier by this being the same everywhere, however.
Quoted 73 lines
arch/x86/Kconfig +0
-1select ARCH_SUPPORTS_HUGE_PFNMAP if TRANSPARENT_HUGEPAGE select HAVE_ARCH_SOFT_DIRTY select MODULES_USE_ELF_RELA@@ -1846,7 +1845,6 @@ config X86_USER_SHADOW_STACK bool "X86 userspace shadow stack" depends on AS_WRUSS depends on X86_64 - depends on PER_VMA_LOCK select ARCH_USES_HIGH_VMA_FLAGS select ARCH_HAS_USER_SHADOW_STACK select X86_CETfs/proc/internal.h +0
-2@@ -385,10 +385,8 @@ struct mem_size_stats;struct proc_maps_locking_ctx {struct mm_struct *mm; -#ifdef CONFIG_PER_VMA_LOCK bool mmap_locked;struct vm_area_struct *locked_vma; -#endif };struct proc_maps_private {fs/proc/task_mmu.c +0
-32@@ -130,8 +130,6 @@ static void release_task_mempolicy(struct proc_maps_private *priv) }#endif -#ifdef CONFIG_PER_VMA_LOCK -static inline int lock_ctx_mm (struct proc_maps_locking_ctx *lock_ctx) {int ret =mmap_read_lock_killable (lock_ctx->mm);@@ -233,46 +231,6 @@ static inline void reacquire_rcu(struct proc_maps_private *priv)vma_iter_set (&priv->iter, priv->lock_ctx.locked_vma->vm_end); } -#else /* CONFIG_PER_VMA_LOCK */ - -static inline int lock_ctx_mm (struct proc_maps_locking_ctx *lock_ctx) -{ -return mmap_read_lock_killable (lock_ctx->mm); -} - -static inline void unlock_ctx_mm (struct proc_maps_locking_ctx *lock_ctx) -{ -mmap_read_unlock (lock_ctx->mm); -} - -static inline bool lock_vma_range (struct seq_file *m, -struct proc_maps_locking_ctx *lock_ctx) -{ -return lock_ctx_mm (lock_ctx) ==0 ; -} - -static inline void unlock_vma_range (struct proc_maps_locking_ctx *lock_ctx) -{ -unlock_ctx_mm (lock_ctx); -} - -static struct vm_area_struct *get_next_vma (struct proc_maps_private *priv, -loff_t last_pos) -{ -return vma_next (&priv->iter); -} - -static inline bool fallback_to_mmap_lock(struct proc_maps_private *priv,
fs/proc/task_mmu.c static inline void reacquire_rcu(struct proc_maps_private *priv) · line 275
Quoted 10 lines
fs/proc/task_mmu.c +0
-10- loff_t pos) -{ -return false; -} - -static inline void drop_rcu (struct proc_maps_private *priv) {} -static inline void reacquire_rcu (struct proc_maps_private *priv) {} - -#endif /* CONFIG_PER_VMA_LOCK */ -
Lovely :)
Quoted 139 lines
fs/proc/task_mmu.c +0
-51static struct vm_area_struct *proc_get_vma (struct seq_file *m,loff_t *ppos) {struct proc_maps_private *priv = m->private;@@ -560,8 +518,6 @@ static int pid_maps_open(struct inode *inode, struct file *file)PROCMAP_QUERY_VMA_FLAGS \ ) -#ifdef CONFIG_PER_VMA_LOCK - static int query_vma_setup(struct proc_maps_locking_ctx *lock_ctx) {reset_lock_ctx (lock_ctx);@@ -612,26 +568,6 @@ static struct vm_area_struct *query_vma_find_by_addr(struct proc_maps_locking_ctreturn vma; } -#else /* CONFIG_PER_VMA_LOCK */ - -static int query_vma_setup (struct proc_maps_locking_ctx *lock_ctx) -{ -return mmap_read_lock_killable (lock_ctx->mm); -} - -static void query_vma_teardown (struct proc_maps_locking_ctx *lock_ctx) -{ -mmap_read_unlock (lock_ctx->mm); -} - -static struct vm_area_struct *query_vma_find_by_addr (struct proc_maps_locking_ctx *lock_ctx, -unsigned long addr) -{ -return find_vma (lock_ctx->mm, addr); -} - -#endif /* CONFIG_PER_VMA_LOCK */ -static struct vm_area_struct *query_matching_vma (struct proc_maps_locking_ctx *lock_ctx,unsigned long addr,u32 flags) {@@ -1314,8 +1250,6 @@ static const struct mm_walk_ops smaps_shmem_walk_ops = { .walk_lock = PGWALK_RDLOCK, }; -#ifdef CONFIG_PER_VMA_LOCK -static const struct mm_walk_ops smaps_walk_vma_lock_ops = { .pmd_entry = smaps_pte_range, .hugetlb_entry = smaps_hugetlb_range,@@ -1345,22 +1279,6 @@ get_smaps_shmem_walk_ops(struct proc_maps_private *priv)return &smaps_shmem_walk_vma_lock_ops; } -#else /* CONFIG_PER_VMA_LOCK */ - -static inline const struct mm_walk_ops * -get_smaps_walk_ops (struct proc_maps_private *priv) -{ -return &smaps_walk_ops; -} - -static inline const struct mm_walk_ops * -get_smaps_shmem_walk_ops (struct proc_maps_private *priv) -{ -return &smaps_shmem_walk_ops; -} - -#endif /* CONFIG_PER_VMA_LOCK */ -/* * Gather mem stats from @vma with the indicated beginning * address @start, and keep them in @mss. @@ -3497,7 +3415,6 @@ static const struct mm_walk_ops show_numa_ops = { .walk_lock = PGWALK_RDLOCK, }; -#ifdef CONFIG_PER_VMA_LOCK static const struct mm_walk_ops show_numa_vma_lock_ops = { .hugetlb_entry = gather_hugetlb_stats, .pmd_entry = gather_pte_stats,@@ -3512,16 +3429,6 @@ get_show_numa_ops(struct proc_maps_private *priv)return &show_numa_vma_lock_ops; } -#else /* CONFIG_PER_VMA_LOCK */ - -static inline const struct mm_walk_ops * -get_show_numa_ops (struct proc_maps_private *priv) -{ -return &show_numa_ops; -} - -#endif /* CONFIG_PER_VMA_LOCK */ -/* * Display pages allocated per node and memory policy via /proc. */ include/linux/mm.h +0
-12@@ -931,7 +931,6 @@ static inline void vma_numab_state_free(struct vm_area_struct *vma) {}* These must be here rather than mmap_lock.h as dependent on vm_fault type, * declared in this header. */ -#ifdef CONFIG_PER_VMA_LOCK static inline void release_fault_lock (struct vm_fault *vmf) {if (vmf->flags &FAULT_FLAG_VMA_LOCK )@@ -947,17 +946,6 @@ static inline void assert_fault_locked(const struct vm_fault *vmf)else mmap_assert_locked (vmf->vma->vm_mm); } -#else -static inline void release_fault_lock (struct vm_fault *vmf) -{ -mmap_read_unlock (vmf->vma->vm_mm); -} - -static inline void assert_fault_locked (const struct vm_fault *vmf) -{ -mmap_assert_locked (vmf->vma->vm_mm); -} -#endif /* CONFIG_PER_VMA_LOCK */ static inline bool mm_flags_test (int flag,const struct mm_struct *mm) {include/linux/mm_types.h +0
-1@@ -950,7 +950,6 @@ struct vm_area_struct {vma_flags_t flags; }; -#ifdef CONFIG_PER_VMA_LOCK /* * Can only be written (using WRITE_ONCE()) while holding both: * - mmap_lock (in write mode)
include/linux/mm_types.h struct vm_area_struct { · line 971
Quoted 8 lines
include/linux/mm_types.h +1
-1@@ -966,7 +965,7 @@ struct vm_area_struct {* slowpath. */ unsigned int vm_lock_seq; -#endif +/* * Low 32-bits of virtual page offset. * See vma_start_virt_pgoff() comment for details.
<3 the consistent red in this diff :)
[Sorry to be awkward but this change must have been based on mm-new and an old revision of my series and needs a rebase :) all the *_virt_*() functions were renamed to *_anon_*().]
Quoted 47 lines
include/linux/mm_types.h +1
-4@@ -1003,7 +1002,6 @@ struct vm_area_struct {#ifdef CONFIG_NUMA_BALANCING struct vma_numab_state *numab_state;/* NUMA Balancing state */ #endif -#ifdef CONFIG_PER_VMA_LOCK /* * Used to keep track of firstly, whether the VMA is attached, secondly, * if attached, how many read locks are taken, and thirdly, if the @@ -1046,7 +1044,6 @@ struct vm_area_struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map vmlock_dep_map;#endif -#endif #ifdef CONFIG_64BIT /* * High 32-bits of virtual page offset. @@ -1254,7 +1251,6 @@ struct mm_struct {* init_mm.mmlist, and are protected * by mmlist_lock */ -#ifdef CONFIG_PER_VMA_LOCK struct rcuwait vma_writer_wait;/* * This field has lock-like semantics, meaning it is sometimes @@ -1274,7 +1270,7 @@ struct mm_struct {* mmap_lock. */ seqcount_t mm_lock_seq; -#endif +struct futex_mm_data futex;unsigned long hiwater_rss;/* High-watermark of RSS usage */ include/linux/mmap_lock.h +0
-2@@ -76,8 +76,6 @@ static inline void mmap_assert_write_locked(const struct mm_struct *mm)rwsem_assert_held_write (&mm->mmap_lock); } -#ifdef CONFIG_PER_VMA_LOCK -#ifdef CONFIG_LOCKDEP #define __vma_lockdep_map (vma) (&vma->vmlock_dep_map)#else
include/linux/mmap_lock.h int __vma_start_write(struct vm_area_struct *vma, int state); · line 300
Quoted 6 lines
include/linux/mmap_lock.h +3
-0@@ -297,6 +295,9 @@ int __vma_start_write(struct vm_area_struct *vma, int state);*/ static inline void vma_start_write (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return ; +
Nice and neat.
Quoted 14 lines
include/linux/mmap_lock.h +3
-0if (__is_vma_write_locked (vma))return ;@@ -319,6 +320,9 @@ static inline void vma_start_write(struct vm_area_struct *vma)static inline __must_check int vma_start_write_killable (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return 0 ; +if (__is_vma_write_locked (vma))return 0 ;
include/linux/mmap_lock.h int vma_start_write_killable(struct vm_area_struct *vma) · line 342
Quoted 8 lines
include/linux/mmap_lock.h +5
-0@@ -331,6 +335,11 @@ int vma_start_write_killable(struct vm_area_struct *vma)*/ static inline void vma_assert_write_locked (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) { +mmap_assert_write_locked (vma->vm_mm); +return ; + } +
Hmm don't love that this kinda reinstates the fallback, but I guess nommu may as well get the appropriate mmap equivalent check.
Quoted 24 lines
include/linux/mmap_lock.h +6
-0VM_WARN_ON_ONCE_VMA (!__is_vma_write_locked (vma), vma); }@@ -432,6 +441,9 @@ static inline bool vma_is_attached(struct vm_area_struct *vma)*/ static inline void vma_assert_attached (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return ; +WARN_ON_ONCE (!vma_is_attached (vma)); }@@ -442,6 +454,9 @@ static inline void vma_assert_detached(struct vm_area_struct *vma)static inline void vma_mark_attached (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return ; +vma_assert_write_locked (vma);vma_assert_detached (vma);refcount_set_release (&vma->vm_refcnt,1 );
include/linux/mmap_lock.h void __vma_exclude_readers_for_detach(struct vm_area_struct *vma); · line 471
Quoted 6 lines
include/linux/mmap_lock.h +3
-0@@ -451,6 +466,9 @@ void __vma_exclude_readers_for_detach(struct vm_area_struct *vma);static inline void vma_mark_detached (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return ; +
OK all the least-worse means of handling nommu like it :)
Quoted 65 lines
include/linux/mmap_lock.h +0
-48vma_assert_write_locked (vma);vma_assert_attached (vma);@@ -484,54 +502,6 @@ struct vm_area_struct *lock_next_vma(struct mm_struct *mm,struct vma_iterator *iter, unsigned long address); -#else /* CONFIG_PER_VMA_LOCK */ - -static inline void mm_lock_seqcount_init (struct mm_struct *mm) {} -static inline void mm_lock_seqcount_begin (struct mm_struct *mm) {} -static inline void mm_lock_seqcount_end (struct mm_struct *mm) {} - -static inline bool mmap_lock_speculate_try_begin (struct mm_struct *mm,unsigned int *seq) -{ -return false; -} - -static inline bool mmap_lock_speculate_retry (struct mm_struct *mm,unsigned int seq) -{ -return true; -} -static inline void vma_lock_init (struct vm_area_struct *vma,bool reset_refcnt) {} -static inline void vma_end_read (struct vm_area_struct *vma) {} -static inline void vma_start_write (struct vm_area_struct *vma) {} -static inline __must_check -int vma_start_write_killable (struct vm_area_struct *vma) {return 0 ; } -static inline void vma_assert_write_locked (struct vm_area_struct *vma) - {mmap_assert_write_locked (vma->vm_mm); } -static inline bool vma_is_attached (struct vm_area_struct *vma) - {return true; } -static inline void vma_assert_attached (struct vm_area_struct *vma) {} -static inline void vma_assert_detached (struct vm_area_struct *vma) {} -static inline void vma_mark_attached (struct vm_area_struct *vma) {} -static inline void vma_mark_detached (struct vm_area_struct *vma) {} - -static inline struct vm_area_struct *lock_vma_under_rcu (struct mm_struct *mm, -unsigned long address) -{ -return NULL ; -} - -static inline void vma_assert_locked (struct vm_area_struct *vma) -{ -mmap_assert_locked (vma->vm_mm); -} - -static inline void vma_assert_stabilised (struct vm_area_struct *vma) -{ -/* If no VMA locks, then either mmap lock suffices to stabilise. */ -mmap_assert_locked (vma->vm_mm); -} - -#endif /* CONFIG_PER_VMA_LOCK */ -static inline void vma_assert_can_modify (struct vm_area_struct *vma) {if (vma_is_attached (vma))kernel/bpf/stackmap.c +0
-0@@ -272,13 +272,8 @@ struct stack_map_vma_lock {/* * Acquire a stable read-side reference on the VMA covering @ip.
kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 276
Quoted 10 lines
kernel/bpf/stackmap.c +2
-7* -* With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read -* lock held and mmap_lock dropped, so the caller may sleep. -* -* With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still -* held; the caller must snapshot any fields it needs and pin vm_file -* with get_file() before stack_map_unlock_vma() drops mmap_lock, as -* the VMA may be split, merged, or freed after that. +* This returns a VMA with its per-VMA read lock held and mmap_lock +* dropped, so the caller may sleep.
As per sub-thread, this should be updated as per Matthew's suggestion.
But also - if !CONFIG_MMU it returns with the mmap lock held. Have you audited all callers to make sure they correctly handle this?
kernel/bpf/stackmap.c stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip) · line 286
Quoted 9 lines
kernel/bpf/stackmap.c +0
-1* * Returns NULL on failure, in which case no lock is held. */ @@ -288,7 +283,6 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)struct mm_struct *mm = lock->mm;struct vm_area_struct *vma; -/* noop under !CONFIG_PER_VMA_LOCK */ vma =lock_vma_under_rcu (mm, ip);
Hmm what does this do in nommu?
This is the only place I think that nommu would ever call this function, why not just avoid the possibility that this does something wrong (and confusion around that and instead do:
if (IS_ENABLED(CONFIG_MMU) && (vma = lock_vma_under_rcu(mm, ip))) {
lock->vma = vma;
return vma;
}Or if that's too cute then obviously:
if (IS_ENABLED(CONFIG_MMU)) {
vma = lock_vma_under_rcu(mm, ip);
if (vma) {
lock->vma = vma;
return vma;
}
}Or you could do a:
if (!IS_ENABLED(CONFIG_MMU)) return NULL;
At the start of lock_vma_under_rcu()?
Quoted 5 lines
kernel/bpf/stackmap.c +0
-0if (vma) { lock->vma = vma;@@ -308,21 +302,20 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)return NULL ; }
kernel/bpf/stackmap.c stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip) · line 318
Quoted 10 lines
kernel/bpf/stackmap.c +1
-2-#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU if (!vma_start_read_locked (vma)) {mmap_read_unlock (mm);return NULL ; }mmap_read_unlock (mm);#endif -
This all feels like vma_start_read_unlocked() in not so many words :)
It's a bit catch-22 so maybe worth still doing the code this way for now maybe with a comment saying it'll get get updated to use vma_start_read_unlocked() later and changing it in that patch?
It feels like it'd be a nice simplification!
Quoted 166 lines
kernel/bpf/stackmap.c +1
-1lock->vma = vma;return vma; }static void stack_map_unlock_vma (struct stack_map_vma_lock *lock) { -#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU vma_end_read (lock->vma);#else mmap_read_unlock (lock->mm);kernel/bpf/task_iter.c +1
-1@@ -835,7 +835,7 @@ __bpf_kfunc int bpf_iter_task_vma_new(struct bpf_iter_task_vma *it,BUILD_BUG_ON (sizeof (struct bpf_iter_task_vma_kern ) !=sizeof (struct bpf_iter_task_vma ));BUILD_BUG_ON (__alignof__(struct bpf_iter_task_vma_kern ) != __alignof__(struct bpf_iter_task_vma )); -if (!IS_ENABLED (CONFIG_PER_VMA_LOCK )) { +if (!IS_ENABLED (CONFIG_MMU )) { kit->data =NULL ;return -EOPNOTSUPP ; }kernel/fork.c +0
-2@@ -1077,9 +1077,7 @@ static void mmap_init_lock(struct mm_struct *mm) {init_rwsem (&mm->mmap_lock);mm_lock_seqcount_init (mm); -#ifdef CONFIG_PER_VMA_LOCK rcuwait_init (&mm->vma_writer_wait); -#endif }static struct mm_struct *mm_init (struct mm_struct *mm,struct task_struct *p)mm/Kconfig +0
-12@@ -1429,18 +1429,6 @@ config LRU_GEN_WALKS_MMU depends on LRU_GEN && ARCH_HAS_HW_PTE_YOUNG # } -config ARCH_SUPPORTS_PER_VMA_LOCK - def_bool n - -config PER_VMA_LOCK - def_bool y - depends on ARCH_SUPPORTS_PER_VMA_LOCK && MMU && SMP - help - Allow per-vma locking during page fault handling. - - This feature allows locking each virtual memory area separately when - handling page faults instead of taking mmap_lock. - config LOCK_MM_AND_FIND_VMA bool depends on !STACK_GROWSUPmm/Kconfig.debug +0
-1@@ -310,7 +310,6 @@ config DEBUG_KMEMLEAK_VERBOSE config PER_VMA_LOCK_STATS bool "Statistics for per-vma locks" - depends on PER_VMA_LOCK help Say Y here to enable success, retry and failure counters of page faults handled under protection of per-vma locks. When enabled, themm/debug.c +0
-4@@ -157,17 +157,13 @@ void dump_vma(const struct vm_area_struct *vma)pr_emerg ("vma %px start %px end %px mm %px\n" "prot %lx anon_vma %px vm_ops %px\n" "pgoff %lx file %px private_data %px\n" -#ifdef CONFIG_PER_VMA_LOCK"refcnt %x\n" -#endif"flags: %#lx(%pGv)\n" , vma, (void *)vma->vm_start, (void *)vma->vm_end, vma->vm_mm, (unsigned long )pgprot_val (vma->vm_page_prot), vma->anon_vma, vma->vm_ops,vma_start_pgoff (vma), vma->vm_file, vma->vm_private_data, -#ifdef CONFIG_PER_VMA_LOCKrefcount_read (&vma->vm_refcnt), -#endif vma->vm_flags, &vma->vm_flags); }EXPORT_SYMBOL (dump_vma);mm/init-mm.c +0
-2@@ -39,10 +39,8 @@ struct mm_struct init_mm = { .page_table_lock = __SPIN_LOCK_UNLOCKED(init_mm.page_table_lock), .arg_lock = __SPIN_LOCK_UNLOCKED(init_mm.arg_lock), .mmlist = LIST_HEAD_INIT(init_mm.mmlist), -#ifdef CONFIG_PER_VMA_LOCK .vma_writer_wait = __RCUWAIT_INITIALIZER(init_mm.vma_writer_wait), .mm_lock_seq = SEQCNT_ZERO(init_mm.mm_lock_seq), -#endif #ifdef CONFIG_SCHED_MM_CID .mm_cid.lock = __RAW_SPIN_LOCK_UNLOCKED(init_mm.mm_cid.lock),#endif mm/memory.c +0
-2@@ -6814,7 +6814,6 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, !is_cow_mapping(vma->vm_flags)))return VM_FAULT_SIGSEGV ; } -#ifdef CONFIG_PER_VMA_LOCK /* * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of * the assumption that lock is dropped on VM_FAULT_RETRY. @@ -6823,7 +6822,6 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) == (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)))return VM_FAULT_SIGSEGV ; -#endif return 0 ; }mm/mmap_lock.c +0
-14@@ -43,9 +43,6 @@ void __mmap_lock_do_trace_released(struct mm_struct *mm, bool write)EXPORT_SYMBOL (__mmap_lock_do_trace_released);#endif /* CONFIG_TRACING */ -#ifdef CONFIG_MMU -#ifdef CONFIG_PER_VMA_LOCK -/* State shared across __vma_[start, end]_exclude_readers. */ struct vma_exclude_readers_state {/* Input parameters. */ @@ -431,7 +428,6 @@ struct vm_area_struct *lock_next_vma(struct mm_struct *mm,return vma; } -#endif /* CONFIG_PER_VMA_LOCK */ #ifdef CONFIG_LOCK_MM_AND_FIND_VMA #include <linux/extable.h> @@ -548,23 +544,3 @@ struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm, return NULL; }#endif /* CONFIG_LOCK_MM_AND_FIND_VMA */ - -#else /* CONFIG_MMU */ - -/* -* At least xtensa ends up having protection faults even with no -* MMU.. No stack expansion, at least. -*/ -struct vm_area_struct *lock_mm_and_find_vma (struct mm_struct *mm, -unsigned long addr,struct pt_regs *regs) -{
mm/mmap_lock.c struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm, · line 570
Quoted 10 lines
mm/mmap_lock.c +0
-10-struct vm_area_struct *vma; - -mmap_read_lock (mm); - vma =vma_lookup (mm, addr); -if (!vma) -mmap_read_unlock (mm); - return vma; -} - -#endif /* CONFIG_MMU */
Oh lovely to get rid of this :)
Quoted 25 lines
mm/pagewalk.c +0
-2@@ -446,7 +446,6 @@ static inline void process_mm_walk_lock(struct mm_struct *mm,static inline void process_vma_walk_lock (struct vm_area_struct *vma,enum page_walk_lock walk_lock) { -#ifdef CONFIG_PER_VMA_LOCK switch (walk_lock) {case PGWALK_WRLOCK :vma_start_write (vma);@@ -461,7 +460,6 @@ static inline void process_vma_walk_lock(struct vm_area_struct *vma,/* PGWALK_RDLOCK is handled by process_mm_walk_lock */ break ; } -#endif }/* mm/rmap.c +0
-0
mm/rmap.c static void check_anon_vma_clone(struct vm_area_struct *dst, · line 265
Quoted 7 lines
mm/rmap.c +0
-1@@ -260,11 +260,9 @@ static void check_anon_vma_clone(struct vm_area_struct *dst,/* For the anon_vma to be compatible, it can only be singular. */ VM_WARN_ON_ONCE (operation ==VMA_OP_MERGE_UNFAULTED && !list_is_singular (&src->anon_vma_chain)); -#ifdef CONFIG_PER_VMA_LOCK /* Only merging an unfaulted VMA leaves the destination attached. */ VM_WARN_ON_ONCE (operation !=VMA_OP_MERGE_UNFAULTED &&vma_is_attached (dst));
Yeah this should be fine as VMAs are always !vma_is_attached() for nommu.
Quoted 150 lines
mm/rmap.c +0
-1-#endif } static void maybe_reuse_anon_vma(struct vm_area_struct *dst,mm/userfaultfd.c +0
-55@@ -122,7 +122,6 @@ struct vm_area_struct *find_vma_and_prepare_anon(struct mm_struct *mm,return vma; } -#ifdef CONFIG_PER_VMA_LOCK /* * uffd_lock_vma() - Lookup and lock vma corresponding to @address. * @mm: mm to search vma in. @@ -182,34 +181,6 @@ static void uffd_mfill_unlock(struct vm_area_struct *vma)vma_end_read (vma); } -#else - -static struct vm_area_struct *uffd_mfill_lock (struct mm_struct *dst_mm, -unsigned long dst_start, -unsigned long len) -{ -struct vm_area_struct *dst_vma; - -mmap_read_lock (dst_mm); - dst_vma =find_vma_and_prepare_anon (dst_mm, dst_start); -if (IS_ERR (dst_vma)) - goto out_unlock; - -if (validate_dst_vma (dst_vma, dst_start + len)) -return dst_vma; - - dst_vma =ERR_PTR (-ENOENT ); -out_unlock: -mmap_read_unlock (dst_mm); -return dst_vma; -} - -static void uffd_mfill_unlock (struct vm_area_struct *vma) -{ -mmap_read_unlock (vma->vm_mm); -} -#endif -static void mfill_put_vma (struct mfill_state *state) {if (!state->vma)@@ -1852,7 +1823,6 @@ int find_vmas_mm_locked(struct mm_struct *mm,return 0 ; } -#ifdef CONFIG_PER_VMA_LOCK static int uffd_move_lock(struct mm_struct *mm, unsigned long dst_start, unsigned long src_start,@@ -1927,31 +1897,6 @@ static void uffd_move_unlock(struct vm_area_struct *dst_vma,vma_end_read (dst_vma); } -#else - -static int uffd_move_lock (struct mm_struct *mm, -unsigned long dst_start, -unsigned long src_start, -struct vm_area_struct **dst_vmap, -struct vm_area_struct **src_vmap) -{ -int err; - -mmap_read_lock (mm); - err =find_vmas_mm_locked (mm, dst_start, src_start, dst_vmap, src_vmap); -if (err) -mmap_read_unlock (mm); -return err; -} - -static void uffd_move_unlock (struct vm_area_struct *dst_vma, -struct vm_area_struct *src_vma) -{ -mmap_assert_locked (src_vma->vm_mm); -mmap_read_unlock (dst_vma->vm_mm); -} -#endif -/** * move_pages - move arbitrary anonymous pages of an existing vma * @ctx: pointer to the userfaultfd context rust/kernel/mm.rs +11
-21@@ -170,30 +170,20 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_struct) -> &'a MmWithUser {/// /// This is an optimistic trylock operation, so it may fail if there is contention. In that /// case, you should fall back to taking the mmap read lock. -/// -/// When per-vma locks are disabled, this always returns `None`. #[inline] pub fn lock_vma_under_rcu (&self, vma_addr:usize ) ->Option <VmaReadGuard <'_>> { -#[cfg( CONFIG_PER_VMA_LOCK )] - { -// SAFETY: Calling `bindings::lock_vma_under_rcu` is always okay given an mm where -// `mm_users` is non-zero. -let vma =unsafe { bindings::lock_vma_under_rcu (self.as_raw (), vma_addr) }; -if !vma.is_null () { -return Some (VmaReadGuard { -// SAFETY: If `lock_vma_under_rcu` returns a non-null ptr, then it points at a -// valid vma. The vma is stable for as long as the vma read lock is held. - vma:unsafe {VmaRef ::from_raw (vma) }, - _nts:NotThreadSafe , - }); - } +// SAFETY: Calling `bindings::lock_vma_under_rcu` is always okay given an mm where +// `mm_users` is non-zero. +let vma =unsafe { bindings::lock_vma_under_rcu (self.as_raw (), vma_addr) }; +if vma.is_null () { +return None ; } - -// Silence warnings about unused variables. -#[cfg(not( CONFIG_PER_VMA_LOCK ))] -let _ = vma_addr; - -None +Some (VmaReadGuard { +// SAFETY: If `lock_vma_under_rcu` returns a non-null ptr, then it points at a +// valid vma. The vma is stable for as long as the vma read lock is held. + vma:unsafe {VmaRef ::from_raw (vma) }, + _nts:NotThreadSafe , + }) }/// Lock the mmap read lock. tools/testing/vma/include/dup.h +0
-1@@ -582,7 +582,6 @@ struct vm_area_struct {vma_flags_t flags; }; -#ifdef CONFIG_PER_VMA_LOCK /* * Can only be written (using WRITE_ONCE()) while holding both: * - mmap_lock (in write mode)
tools/testing/vma/include/dup.h struct vm_area_struct { · line 601
Quoted 6 lines
tools/testing/vma/include/dup.h +1
-1@@ -598,7 +597,7 @@ struct vm_area_struct {* slowpath. */ unsigned int vm_lock_seq; -#endif +unsigned int __vm_virt_pgoff_lo;
Similar rebase issue here :)
tools/testing/vma/include/dup.h struct vm_area_struct { · line 637
Quoted 12 lines
tools/testing/vma/include/dup.h +0
-2/* @@ -632,10 +631,8 @@ struct vm_area_struct {#ifdef CONFIG_NUMA_BALANCING struct vma_numab_state *numab_state;/* NUMA Balancing state */ #endif -#ifdef CONFIG_PER_VMA_LOCK /* Unstable RCU readers are allowed to read this. */ refcount_t vm_refcnt; -#endif #ifdef CONFIG_64BIT unsigned int __vm_virt_pgoff_hi;
And here.
Anyway, since this is for 7.4 I guess, you will need to be fairly rebase-happy anyway as things evolve! :)
Quoted 14 lines
tools/testing/vma/include/dup.h +0
-0#endif tools/testing/vma/vma_internal.h +0
-2@@ -15,7 +15,6 @@#include <stdlib.h> #define CONFIG_MMU 1 -#define CONFIG_PER_VMA_LOCK 1#ifdef __CONCAT#undef __CONCAT --
Quoted 2 lines
2.55.0.654.g21b8a5bc05-goog
--
Cheers, Lorenzo
Re: [PATCH v4 1/5] mm: Make per-VMA locks available universally
Quoted 1 line · Lorenzo Stoakes (ARM)
On Thu, Aug 06, 2026 at 01:05:44PM -0700, Suren Baghdasaryan wrote:
...
Quoted 10 lines
Quoted 4 lines
The downside of this is adding some fields to
vm_area_structandmm_struct. There are likely ways to optimize this, especially for things like SMP=n configs. For now, do the simplest thing: use the same implementation everywhere.I think for most cases SMP=n arches are not going to be scaling too crazily on threads/processes anyway.
If real world usecases exist that the struct bloat causes problems for then optimisations for those can be looked into.
Yup, totally agree. It's not worth adding complexity and bugs when the gains would be small.
Quoted 2 lines
But I wonder if cache line alignment would in any case alter the impact of this anyway?
Yes, the CONFIG_PER_VMA_LOCK structures are spread across a couple of spots in vm_area_struct. At least one of them is 4 bytes and another is ____cacheline_aligned_in_smp. I'd eat my hat if there aren't at least a couple of bytes that could be trimmed.
Re: [PATCH v4 1/5] mm: Make per-VMA locks available universally
In reply to Lorenzo Stoakes (ARM)Quoted 10 lines · Lorenzo Stoakes (ARM)
And, in general, having consistent per-arch fault logic would be a good thing (TM) (and particularly - as Matthew intends to do - having shared code for this is a _really_ good idea, the duplication right now is horrible).
So perhaps Matthew could do this as part of his changes or you could follow up with changes to do that?
I think his work would be made easier by this being the same everywhere, however.
Yes, having per-VMA locks everywhere is kind of essential, so I was planning on going second after this was merged. Hence the careful review ;-)
Suren Baghdasaryan
maintainerRe: [PATCH v4 1/5] mm: Make per-VMA locks available universally
In reply to Lorenzo Stoakes (ARM)Quoted 38 lines · Lorenzo Stoakes (ARM)
Quoted 8 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
The per-VMA locks have been around for several years. They've had some bugs worked out of them and have seen quite wide use. However, they are still only available when architectures explicitly enable them. Remove the conditional compilation around the per-VMA locks, making them available on all architectures and configs.
Quoted 6 lines
The approach up to now seemed to be to add
ARCH_SUPPORTS_PER_VMA_LOCKwhen the architecture started using per-VMA locks in the fault handler. But, contrary to the naming, theKconfigoption does not really indicate whether the architecture supports per-VMA locks or not. It is more of a marker for whether the architecture is likely to benefit from per-VMA locks.Thanks for clarifying this. I'm very glad we're getting rid of this :) it was a bit too conservative I think.
Quoted 9 lines
To me, the most important thing side-effect of universal availability is letting per-VMA locks be used in SMP=n configs. This lets us use per-VMA locking in all x86 code without fallbacks.
Overall, this just generally makes the kernel simpler. Just look at the diffstat. It also opens the door to users that want to use the per-VMA locks in common code. Doing *that* brings additional simplifications.
Yes!
Quoted 5 lines
The downside of this is adding some fields to
vm_area_structandmm_struct. There are likely ways to optimize this, especially for things like SMP=n configs. For now, do the simplest thing: use the same implementation everywhere.
Quoted 5 lines
I think for most cases SMP=n arches are not going to be scaling too crazily on threads/processes anyway.
If real world usecases exist that the struct bloat causes problems for then optimisations for those can be looked into.
Agree. If any regressions are reported we will address them.
Quoted 3 lines
But I wonder if cache line alignment would in any case alter the impact of this anyway?
I'll see what pahole tells me on SMP=n and maybe we can reason about the impact.
Quoted 11 lines
Quoted 9 lines
== Considerations for NOMMU config ==
NOMMU systems do not write-lock VMAs, therefore read-locking a VMA would always succeed unless VMA is detached. Therefore for NOMMU config we make
vma_mark_attached()a NOOP, which keeps VMAs always in detached state. This causes VMA read-locking to always fail and the caller falls back to lockingmmap_lock.Nice, I think this is the best way of handling nommu.
That's what you and Jann suggested :)
Quoted 21 lines
Quoted 5 lines
The following functions will have a different implementation in NOMMU config:
Quoted 8 lines
-
vma_mark_attached(),vma_mark_detached()are made NOOPs, keeping VMAs always in a detached state and preventing assertions and refcount underflows;-
vma_start_write(),vma_start_write_killable()are made NOOPs to avoid warnings in__vma_start_write()due to VMAs being detached. These functions are not used in NOMMU code but__vma_start_write()is an exported function, therefore might be used by drivers.OK so being cautious. It sucks to do it but the
IS_ENABLED(CONFIG_MMU)guard pattern makes it much less egregious.Quoted 3 lines
-
vma_assert_attached()is made NOOP because it's reachable from NOMMU code via split_vma()->vma_iter_store_new()->vma_iter_store_overwrite();
Quoted 7 lines
Ugh yeah.
Quoted 2 lines
-
vma_assert_write_locked()is assertingvma->vm_mmis write-locked;I'm confused by this one how is that reachable and how is that addressed? Seems like this sentence is missing something :)
Basically, I'm keeping this assert for NOMMU as it was before this change. If NOMMU code asserts this, we would expect it to hold mmap write lock, so I kept it that way. Does that make sense? Maybe I should amend the explanation as:
vma_assert_write_locked() is asserting vma->vm_mm is write-locked as before;
Quoted 18 lines
Quoted 18 lines
The following functions work for both MMU and NOMMU configs:
-
vma_lock_init()performs the same initialization as for MMU config;-
mm_lock_seqcount_init(),mm_lock_seqcount_begin(),mm_lock_seqcount_end()are called from mmap_write_{lock|unlock} and updatemm_lock_seqcorrectly.-
mmap_lock_speculate_try_begin(),mmap_lock_speculate_retry()work as is becausemm_lock_seqis updated correctly;-
vma_start_read(),vma_start_read_locked()will always fail because VMAs are always detached;-
vma_end_read()will never be called becausevma_start_read()never succeeds;
Quoted 8 lines
Quoted 3 lines
-
vma_is_attached()always return false because VMAs are always detached;-
vma_assert_detached()will never trigger because VMAs are never attached;Nice thanks for the write up!
Maybe worth looking ahead and pointing out that
vma_start_read_unlocked()will also be safe (i.e. the attempted read lock will bail).
Ack. Will add.
Quoted 4 lines
Though perhaps you'd want an
IS_ENABLED(CONFIG_MMU)there to avoid wasted mmap lock toggling (will comment on that patch if you didn't already handle that there! :)
I think adding IS_ENABLED(CONFIG_MMU) at the beginning of lock_vma_under_rcu(), as you suggest later, would be best. That way vma_start_read_unlocked() will use that too.
Quoted 9 lines
Quoted 9 lines
Changes in the following files are not affecting NOMMU config:
task_mmu.c- not compiled whenCONFIG_MMU=n;pagewalk.c- not compiled whenCONFIG_MMU=n;userfaultfd.c- not compiled whenCONFIG_MMU=n(CONFIG_USERFAULTFDdepends onCONFIG_MMU);
Quoted 6 lines
Quoted 4 lines
The following changes are made to keep NOMMU config working like before:
stack_map_lock_vma()- keepsmmap_lockin NOMMU config;bpf_iter_task_vma_new()- bails out in NOMMU config;Worth saying both are in the BPF code.
Ack.
Quoted 173 lines
Quoted 42 lines
Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Lorenzo Stoakes <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- arch/arm/Kconfig | 1 - arch/arm64/Kconfig | 1 - arch/loongarch/Kconfig | 1 - arch/powerpc/platforms/powernv/Kconfig | 1 - arch/powerpc/platforms/pseries/Kconfig | 1 - arch/riscv/Kconfig | 1 - arch/s390/Kconfig | 1 - arch/x86/Kconfig | 2 - fs/proc/internal.h | 2 - fs/proc/task_mmu.c | 93 -------------------------- include/linux/mm.h | 12 ---- include/linux/mm_types.h | 8 +-- include/linux/mmap_lock.h | 70 ++++++------------- kernel/bpf/stackmap.c | 15 ++--- kernel/bpf/task_iter.c | 2 +- kernel/fork.c | 2 - mm/Kconfig | 12 ---- mm/Kconfig.debug | 1 - mm/debug.c | 4 -- mm/init-mm.c | 2 - mm/memory.c | 2 -Quoted 8 lines
mm/mmap_lock.c | 24 ------- mm/pagewalk.c | 2 - mm/rmap.c | 2 - mm/userfaultfd.c | 55 --------------- rust/kernel/mm.rs | 32 +++------ tools/testing/vma/include/dup.h | 5 +- tools/testing/vma/vma_internal.h | 1 - 28 files changed, 39 insertions(+), 316 deletions(-)Still a lovely diffstat :) good.
Quoted 90 lines
arch/arm/Kconfig +0
-1@@ -41,7 +41,6 @@ config ARM select ARCH_SUPPORTS_ATOMIC_RMW select ARCH_SUPPORTS_CFI select ARCH_SUPPORTS_HUGETLBFS if ARM_LPAE - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_RT select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_CMPXCHG_LOCKREFarch/arm64/Kconfig +0
-1@@ -81,7 +81,6 @@ config ARM64 select ARCH_HAS_PTE_PROTNONE select ARCH_SUPPORTS_NUMA_BALANCING select ARCH_SUPPORTS_PAGE_TABLE_CHECK - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_HUGE_PFNMAP if TRANSPARENT_HUGEPAGE select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SCHED_SMTarch/loongarch/Kconfig +0
-1@@ -69,7 +69,6 @@ config LOONGARCH select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS select ARCH_HAS_PTE_PROTNONE if 64BIT select ARCH_SUPPORTS_NUMA_BALANCING if NUMA - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SCHED_SMT if SMP select ARCH_SUPPORTS_SCHED_MC if SMParch/powerpc/platforms/powernv/Kconfig +0
-1@@ -17,7 +17,6 @@ config PPC_POWERNV select PPC_DOORBELL select MMU_NOTIFIER select FORCE_SMP - select ARCH_SUPPORTS_PER_VMA_LOCK select PPC_RADIX_BROADCAST_TLBIE if PPC_RADIX_MMU default yarch/powerpc/platforms/pseries/Kconfig +0
-1@@ -23,7 +23,6 @@ config PPC_PSERIES select HOTPLUG_CPU select FORCE_SMP select SWIOTLB - select ARCH_SUPPORTS_PER_VMA_LOCK select PPC_RADIX_BROADCAST_TLBIE if PPC_RADIX_MMU default yarch/riscv/Kconfig +0
-1@@ -70,7 +70,6 @@ config RISCV select ARCH_SUPPORTS_LTO_CLANG_THIN select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS if 64BIT && MMU select ARCH_SUPPORTS_PAGE_TABLE_CHECK if MMU - select ARCH_SUPPORTS_PER_VMA_LOCK if MMU select ARCH_HAS_PTE_PROTNONE if MMU select ARCH_SUPPORTS_RT select ARCH_SUPPORTS_SHADOW_CALL_STACK if HAVE_SHADOW_CALL_STACKarch/s390/Kconfig +0
-1@@ -151,7 +151,6 @@ config S390 select ARCH_HAS_PTE_PROTNONE select ARCH_SUPPORTS_NUMA_BALANCING select ARCH_SUPPORTS_PAGE_TABLE_CHECK - select ARCH_SUPPORTS_PER_VMA_LOCK select ARCH_USE_BUILTIN_BSWAP select ARCH_USE_CMPXCHG_LOCKREF select ARCH_USE_SYM_ANNOTATIONSarch/x86/Kconfig +0
-0arch/x86/Kconfig config X86_64 · line 30
Quoted 4 lines
arch/x86/Kconfig +0
-1@@ -27,7 +27,6 @@ config X86_64 select ARCH_HAS_GIGANTIC_PAGE select ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS select ARCH_SUPPORTS_INT128 if CC_HAS_INT128 - select ARCH_SUPPORTS_PER_VMA_LOCKI'm glad we're getting rid of
ARCH_SUPPORTS_PER_VMA_LOCK, it seemed to be an arbitrary 'these are arches that both _use_ it and _support_ it'.And really every arch supports them.
We can't really have assumed anyway that an arch would definitely take a VMA read lock (alone) for page faulting as that was always a best-effort thing, so dropping this can't break anything.
In general I can't see any reason why actively using VMA locks the way we do in core mm would be detrimental to arches that don't currently have
ARCH_SUPPORTS_PER_VMA_LOCK.And on the same basis I think they should also do the same VMA lock faulting logic as everybody else. I can't see why they wouldn't just be faster on !ARCH_SUPPORTS_PER_VMA_LOCK arches.
But they will be at worse equivalently performing or perhaps _less_ adventageous than other arches.
And, in general, having consistent per-arch fault logic would be a good thing (TM) (and particularly - as Matthew intends to do - having shared code for this is a _really_ good idea, the duplication right now is horrible).
Quoted 5 lines
So perhaps Matthew could do this as part of his changes or you could follow up with changes to do that?
I think his work would be made easier by this being the same everywhere, however.
Sounds like he already plans for this :)
Quoted 237 lines
Quoted 74 lines
arch/x86/Kconfig +0
-1select ARCH_SUPPORTS_HUGE_PFNMAP if TRANSPARENT_HUGEPAGE select HAVE_ARCH_SOFT_DIRTY select MODULES_USE_ELF_RELA@@ -1846,7 +1845,6 @@ config X86_USER_SHADOW_STACK bool "X86 userspace shadow stack" depends on AS_WRUSS depends on X86_64 - depends on PER_VMA_LOCK select ARCH_USES_HIGH_VMA_FLAGS select ARCH_HAS_USER_SHADOW_STACK select X86_CETfs/proc/internal.h +0
-2@@ -385,10 +385,8 @@ struct mem_size_stats;struct proc_maps_locking_ctx {struct mm_struct *mm; -#ifdef CONFIG_PER_VMA_LOCK bool mmap_locked;struct vm_area_struct *locked_vma; -#endif };struct proc_maps_private {fs/proc/task_mmu.c +0
-32@@ -130,8 +130,6 @@ static void release_task_mempolicy(struct proc_maps_private *priv) }#endif -#ifdef CONFIG_PER_VMA_LOCK -static inline int lock_ctx_mm (struct proc_maps_locking_ctx *lock_ctx) {int ret =mmap_read_lock_killable (lock_ctx->mm);@@ -233,46 +231,6 @@ static inline void reacquire_rcu(struct proc_maps_private *priv)vma_iter_set (&priv->iter, priv->lock_ctx.locked_vma->vm_end); } -#else /* CONFIG_PER_VMA_LOCK */ - -static inline int lock_ctx_mm (struct proc_maps_locking_ctx *lock_ctx) -{ -return mmap_read_lock_killable (lock_ctx->mm); -} - -static inline void unlock_ctx_mm (struct proc_maps_locking_ctx *lock_ctx) -{ -mmap_read_unlock (lock_ctx->mm); -} - -static inline bool lock_vma_range (struct seq_file *m, -struct proc_maps_locking_ctx *lock_ctx) -{ -return lock_ctx_mm (lock_ctx) ==0 ; -} - -static inline void unlock_vma_range (struct proc_maps_locking_ctx *lock_ctx) -{ -unlock_ctx_mm (lock_ctx); -} - -static struct vm_area_struct *get_next_vma (struct proc_maps_private *priv, -loff_t last_pos) -{ -return vma_next (&priv->iter); -} - -static inline bool fallback_to_mmap_lock(struct proc_maps_private *priv,fs/proc/task_mmu.c static inline void reacquire_rcu(struct proc_maps_private *priv) · line 275
Quoted 10 lines
fs/proc/task_mmu.c +0
-10- loff_t pos) -{ -return false; -} - -static inline void drop_rcu (struct proc_maps_private *priv) {} -static inline void reacquire_rcu (struct proc_maps_private *priv) {} - -#endif /* CONFIG_PER_VMA_LOCK */ -Lovely :)
Quoted 139 lines
fs/proc/task_mmu.c +0
-51static struct vm_area_struct *proc_get_vma (struct seq_file *m,loff_t *ppos) {struct proc_maps_private *priv = m->private;@@ -560,8 +518,6 @@ static int pid_maps_open(struct inode *inode, struct file *file)PROCMAP_QUERY_VMA_FLAGS \ ) -#ifdef CONFIG_PER_VMA_LOCK - static int query_vma_setup(struct proc_maps_locking_ctx *lock_ctx) {reset_lock_ctx (lock_ctx);@@ -612,26 +568,6 @@ static struct vm_area_struct *query_vma_find_by_addr(struct proc_maps_locking_ctreturn vma; } -#else /* CONFIG_PER_VMA_LOCK */ - -static int query_vma_setup (struct proc_maps_locking_ctx *lock_ctx) -{ -return mmap_read_lock_killable (lock_ctx->mm); -} - -static void query_vma_teardown (struct proc_maps_locking_ctx *lock_ctx) -{ -mmap_read_unlock (lock_ctx->mm); -} - -static struct vm_area_struct *query_vma_find_by_addr (struct proc_maps_locking_ctx *lock_ctx, -unsigned long addr) -{ -return find_vma (lock_ctx->mm, addr); -} - -#endif /* CONFIG_PER_VMA_LOCK */ -static struct vm_area_struct *query_matching_vma (struct proc_maps_locking_ctx *lock_ctx,unsigned long addr,u32 flags) {@@ -1314,8 +1250,6 @@ static const struct mm_walk_ops smaps_shmem_walk_ops = { .walk_lock = PGWALK_RDLOCK, }; -#ifdef CONFIG_PER_VMA_LOCK -static const struct mm_walk_ops smaps_walk_vma_lock_ops = { .pmd_entry = smaps_pte_range, .hugetlb_entry = smaps_hugetlb_range,@@ -1345,22 +1279,6 @@ get_smaps_shmem_walk_ops(struct proc_maps_private *priv)return &smaps_shmem_walk_vma_lock_ops; } -#else /* CONFIG_PER_VMA_LOCK */ - -static inline const struct mm_walk_ops * -get_smaps_walk_ops (struct proc_maps_private *priv) -{ -return &smaps_walk_ops; -} - -static inline const struct mm_walk_ops * -get_smaps_shmem_walk_ops (struct proc_maps_private *priv) -{ -return &smaps_shmem_walk_ops; -} - -#endif /* CONFIG_PER_VMA_LOCK */ -/* * Gather mem stats from @vma with the indicated beginning * address @start, and keep them in @mss. @@ -3497,7 +3415,6 @@ static const struct mm_walk_ops show_numa_ops = { .walk_lock = PGWALK_RDLOCK, }; -#ifdef CONFIG_PER_VMA_LOCK static const struct mm_walk_ops show_numa_vma_lock_ops = { .hugetlb_entry = gather_hugetlb_stats, .pmd_entry = gather_pte_stats,@@ -3512,16 +3429,6 @@ get_show_numa_ops(struct proc_maps_private *priv)return &show_numa_vma_lock_ops; } -#else /* CONFIG_PER_VMA_LOCK */ - -static inline const struct mm_walk_ops * -get_show_numa_ops (struct proc_maps_private *priv) -{ -return &show_numa_ops; -} - -#endif /* CONFIG_PER_VMA_LOCK */ -/* * Display pages allocated per node and memory policy via /proc. */ include/linux/mm.h +0
-12@@ -931,7 +931,6 @@ static inline void vma_numab_state_free(struct vm_area_struct *vma) {}* These must be here rather than mmap_lock.h as dependent on vm_fault type, * declared in this header. */ -#ifdef CONFIG_PER_VMA_LOCK static inline void release_fault_lock (struct vm_fault *vmf) {if (vmf->flags &FAULT_FLAG_VMA_LOCK )@@ -947,17 +946,6 @@ static inline void assert_fault_locked(const struct vm_fault *vmf)else mmap_assert_locked (vmf->vma->vm_mm); } -#else -static inline void release_fault_lock (struct vm_fault *vmf) -{ -mmap_read_unlock (vmf->vma->vm_mm); -} - -static inline void assert_fault_locked (const struct vm_fault *vmf) -{ -mmap_assert_locked (vmf->vma->vm_mm); -} -#endif /* CONFIG_PER_VMA_LOCK */ static inline bool mm_flags_test (int flag,const struct mm_struct *mm) {include/linux/mm_types.h +0
-1@@ -950,7 +950,6 @@ struct vm_area_struct {vma_flags_t flags; }; -#ifdef CONFIG_PER_VMA_LOCK /* * Can only be written (using WRITE_ONCE()) while holding both: * - mmap_lock (in write mode) include/linux/mm_types.h struct vm_area_struct { · line 971
Quoted 8 lines
include/linux/mm_types.h +1
-1@@ -966,7 +965,7 @@ struct vm_area_struct {* slowpath. */ unsigned int vm_lock_seq; -#endif +/* * Low 32-bits of virtual page offset. * See vma_start_virt_pgoff() comment for details. <3 the consistent red in this diff :)
Quoted 3 lines
[Sorry to be awkward but this change must have been based on mm-new and an old revision of my series and needs a rebase :) all the *_virt_*() functions were renamed to *_anon_*().]
It was over mm-unstable but probably before your final changes went in. I'll rebase the nest version over mm-unstrable again.
Quoted 70 lines
Quoted 48 lines
include/linux/mm_types.h +1
-4@@ -1003,7 +1002,6 @@ struct vm_area_struct {#ifdef CONFIG_NUMA_BALANCING struct vma_numab_state *numab_state;/* NUMA Balancing state */ #endif -#ifdef CONFIG_PER_VMA_LOCK /* * Used to keep track of firstly, whether the VMA is attached, secondly, * if attached, how many read locks are taken, and thirdly, if the @@ -1046,7 +1044,6 @@ struct vm_area_struct {#ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map vmlock_dep_map;#endif -#endif #ifdef CONFIG_64BIT /* * High 32-bits of virtual page offset. @@ -1254,7 +1251,6 @@ struct mm_struct {* init_mm.mmlist, and are protected * by mmlist_lock */ -#ifdef CONFIG_PER_VMA_LOCK struct rcuwait vma_writer_wait;/* * This field has lock-like semantics, meaning it is sometimes @@ -1274,7 +1270,7 @@ struct mm_struct {* mmap_lock. */ seqcount_t mm_lock_seq; -#endif +struct futex_mm_data futex;unsigned long hiwater_rss;/* High-watermark of RSS usage */ include/linux/mmap_lock.h +0
-2@@ -76,8 +76,6 @@ static inline void mmap_assert_write_locked(const struct mm_struct *mm)rwsem_assert_held_write (&mm->mmap_lock); } -#ifdef CONFIG_PER_VMA_LOCK -#ifdef CONFIG_LOCKDEP #define __vma_lockdep_map (vma) (&vma->vmlock_dep_map)#else include/linux/mmap_lock.h int __vma_start_write(struct vm_area_struct *vma, int state); · line 300
Quoted 6 lines
include/linux/mmap_lock.h +3
-0@@ -297,6 +295,9 @@ int __vma_start_write(struct vm_area_struct *vma, int state);*/ static inline void vma_start_write (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return ; +Nice and neat.
Quoted 13 lines
include/linux/mmap_lock.h +3
-0if (__is_vma_write_locked (vma))return ;@@ -319,6 +320,9 @@ static inline void vma_start_write(struct vm_area_struct *vma)static inline __must_check int vma_start_write_killable (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return 0 ; +if (__is_vma_write_locked (vma))return 0 ;
Quoted 12 lines
include/linux/mmap_lock.h int vma_start_write_killable(struct vm_area_struct *vma) · line 342
Quoted 9 lines
include/linux/mmap_lock.h +5
-0@@ -331,6 +335,11 @@ int vma_start_write_killable(struct vm_area_struct *vma)*/ static inline void vma_assert_write_locked (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) { +mmap_assert_write_locked (vma->vm_mm); +return ; + } +Hmm don't love that this kinda reinstates the fallback, but I guess nommu may as well get the appropriate mmap equivalent check.
Yeah, I want this assertion to work correctly in NOMMU case instead of being just a NOOP.
Quoted 112 lines
Quoted 25 lines
include/linux/mmap_lock.h +6
-0VM_WARN_ON_ONCE_VMA (!__is_vma_write_locked (vma), vma); }@@ -432,6 +441,9 @@ static inline bool vma_is_attached(struct vm_area_struct *vma)*/ static inline void vma_assert_attached (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return ; +WARN_ON_ONCE (!vma_is_attached (vma)); }@@ -442,6 +454,9 @@ static inline void vma_assert_detached(struct vm_area_struct *vma)static inline void vma_mark_attached (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return ; +vma_assert_write_locked (vma);vma_assert_detached (vma);refcount_set_release (&vma->vm_refcnt,1 );include/linux/mmap_lock.h void __vma_exclude_readers_for_detach(struct vm_area_struct *vma); · line 471
Quoted 6 lines
include/linux/mmap_lock.h +3
-0@@ -451,6 +466,9 @@ void __vma_exclude_readers_for_detach(struct vm_area_struct *vma);static inline void vma_mark_detached (struct vm_area_struct *vma) { +if (!IS_ENABLED (CONFIG_MMU )) +return ; +OK all the least-worse means of handling nommu like it :)
Quoted 65 lines
include/linux/mmap_lock.h +0
-48vma_assert_write_locked (vma);vma_assert_attached (vma);@@ -484,54 +502,6 @@ struct vm_area_struct *lock_next_vma(struct mm_struct *mm,struct vma_iterator *iter, unsigned long address); -#else /* CONFIG_PER_VMA_LOCK */ - -static inline void mm_lock_seqcount_init (struct mm_struct *mm) {} -static inline void mm_lock_seqcount_begin (struct mm_struct *mm) {} -static inline void mm_lock_seqcount_end (struct mm_struct *mm) {} - -static inline bool mmap_lock_speculate_try_begin (struct mm_struct *mm,unsigned int *seq) -{ -return false; -} - -static inline bool mmap_lock_speculate_retry (struct mm_struct *mm,unsigned int seq) -{ -return true; -} -static inline void vma_lock_init (struct vm_area_struct *vma,bool reset_refcnt) {} -static inline void vma_end_read (struct vm_area_struct *vma) {} -static inline void vma_start_write (struct vm_area_struct *vma) {} -static inline __must_check -int vma_start_write_killable (struct vm_area_struct *vma) {return 0 ; } -static inline void vma_assert_write_locked (struct vm_area_struct *vma) - {mmap_assert_write_locked (vma->vm_mm); } -static inline bool vma_is_attached (struct vm_area_struct *vma) - {return true; } -static inline void vma_assert_attached (struct vm_area_struct *vma) {} -static inline void vma_assert_detached (struct vm_area_struct *vma) {} -static inline void vma_mark_attached (struct vm_area_struct *vma) {} -static inline void vma_mark_detached (struct vm_area_struct *vma) {} - -static inline struct vm_area_struct *lock_vma_under_rcu (struct mm_struct *mm, -unsigned long address) -{ -return NULL ; -} - -static inline void vma_assert_locked (struct vm_area_struct *vma) -{ -mmap_assert_locked (vma->vm_mm); -} - -static inline void vma_assert_stabilised (struct vm_area_struct *vma) -{ -/* If no VMA locks, then either mmap lock suffices to stabilise. */ -mmap_assert_locked (vma->vm_mm); -} - -#endif /* CONFIG_PER_VMA_LOCK */ -static inline void vma_assert_can_modify (struct vm_area_struct *vma) {if (vma_is_attached (vma))kernel/bpf/stackmap.c +0
-0@@ -272,13 +272,8 @@ struct stack_map_vma_lock {/* * Acquire a stable read-side reference on the VMA covering @ip. kernel/bpf/stackmap.c struct stack_map_vma_lock { · line 276
Quoted 10 lines
kernel/bpf/stackmap.c +2
-7* -* With CONFIG_PER_VMA_LOCK=y this returns a VMA with its per-VMA read -* lock held and mmap_lock dropped, so the caller may sleep. -* -* With CONFIG_PER_VMA_LOCK=n it returns a VMA with mmap_lock still -* held; the caller must snapshot any fields it needs and pin vm_file -* with get_file() before stack_map_unlock_vma() drops mmap_lock, as -* the VMA may be split, merged, or freed after that. +* This returns a VMA with its per-VMA read lock held and mmap_lock +* dropped, so the caller may sleep. As per sub-thread, this should be updated as per Matthew's suggestion.
Quoted 2 lines
But also - if !CONFIG_MMU it returns with the mmap lock held. Have you audited all callers to make sure they correctly handle this?
That's how it worked before this change, the only difference is that instread of using #ifdef CONFIG_PER_VMA_LOCK we use #ifdef CONFIG_MMU.
Quoted 8 lines
Quoted 8 lines
kernel/bpf/stackmap.c +0
-0* * Returns NULL on failure, in which case no lock is held. */ @@ -288,7 +283,6 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)struct mm_struct *mm = lock->mm;struct vm_area_struct *vma;
Quoted 4 lines
kernel/bpf/stackmap.c stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip) · line 286
Quoted 2 lines
kernel/bpf/stackmap.c +0
-1-/* noop under !CONFIG_PER_VMA_LOCK */ vma =lock_vma_under_rcu (mm, ip);Hmm what does this do in nommu?
It would return NULL because all VMAs are detached in NOMMU case. So, it's pretty much a NOOP.
Quoted 20 lines
This is the only place I think that nommu would ever call this function, why not just avoid the possibility that this does something wrong (and confusion around that and instead do:
if (IS_ENABLED(CONFIG_MMU) && (vma = lock_vma_under_rcu(mm, ip))) { lock->vma = vma; return vma; }Or if that's too cute then obviously:
if (IS_ENABLED(CONFIG_MMU)) { vma = lock_vma_under_rcu(mm, ip); if (vma) { lock->vma = vma; return vma; } }
Quoted 6 lines
Or you could do a:
if (!IS_ENABLED(CONFIG_MMU)) return NULL;At the start of
lock_vma_under_rcu()?
Yes!
Quoted 19 lines
Quoted 6 lines
kernel/bpf/stackmap.c +0
-0if (vma) { lock->vma = vma;@@ -308,21 +302,20 @@ stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip)return NULL ; }kernel/bpf/stackmap.c stack_map_lock_vma(struct stack_map_vma_lock *lock, unsigned long ip) · line 318
Quoted 10 lines
kernel/bpf/stackmap.c +1
-2-#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU if (!vma_start_read_locked (vma)) {mmap_read_unlock (mm);return NULL ; }mmap_read_unlock (mm);#endif -This all feels like
vma_start_read_unlocked()in not so many words :)
Quoted 5 lines
It's a bit catch-22 so maybe worth still doing the code this way for now maybe with a comment saying it'll get get updated to use
vma_start_read_unlocked()later and changing it in that patch?It feels like it'd be a nice simplification!
Yes, I think you are right. I'll try this simplification in the next version.
Quoted 389 lines
Quoted 167 lines
kernel/bpf/stackmap.c +1
-1lock->vma = vma;return vma; }static void stack_map_unlock_vma (struct stack_map_vma_lock *lock) { -#ifdef CONFIG_PER_VMA_LOCK +#ifdef CONFIG_MMU vma_end_read (lock->vma);#else mmap_read_unlock (lock->mm);kernel/bpf/task_iter.c +1
-1@@ -835,7 +835,7 @@ __bpf_kfunc int bpf_iter_task_vma_new(struct bpf_iter_task_vma *it,BUILD_BUG_ON (sizeof (struct bpf_iter_task_vma_kern ) !=sizeof (struct bpf_iter_task_vma ));BUILD_BUG_ON (__alignof__(struct bpf_iter_task_vma_kern ) != __alignof__(struct bpf_iter_task_vma )); -if (!IS_ENABLED (CONFIG_PER_VMA_LOCK )) { +if (!IS_ENABLED (CONFIG_MMU )) { kit->data =NULL ;return -EOPNOTSUPP ; }kernel/fork.c +0
-2@@ -1077,9 +1077,7 @@ static void mmap_init_lock(struct mm_struct *mm) {init_rwsem (&mm->mmap_lock);mm_lock_seqcount_init (mm); -#ifdef CONFIG_PER_VMA_LOCK rcuwait_init (&mm->vma_writer_wait); -#endif }static struct mm_struct *mm_init (struct mm_struct *mm,struct task_struct *p)mm/Kconfig +0
-12@@ -1429,18 +1429,6 @@ config LRU_GEN_WALKS_MMU depends on LRU_GEN && ARCH_HAS_HW_PTE_YOUNG # } -config ARCH_SUPPORTS_PER_VMA_LOCK - def_bool n - -config PER_VMA_LOCK - def_bool y - depends on ARCH_SUPPORTS_PER_VMA_LOCK && MMU && SMP - help - Allow per-vma locking during page fault handling. - - This feature allows locking each virtual memory area separately when - handling page faults instead of taking mmap_lock. - config LOCK_MM_AND_FIND_VMA bool depends on !STACK_GROWSUPmm/Kconfig.debug +0
-1@@ -310,7 +310,6 @@ config DEBUG_KMEMLEAK_VERBOSE config PER_VMA_LOCK_STATS bool "Statistics for per-vma locks" - depends on PER_VMA_LOCK help Say Y here to enable success, retry and failure counters of page faults handled under protection of per-vma locks. When enabled, themm/debug.c +0
-4@@ -157,17 +157,13 @@ void dump_vma(const struct vm_area_struct *vma)pr_emerg ("vma %px start %px end %px mm %px\n" "prot %lx anon_vma %px vm_ops %px\n" "pgoff %lx file %px private_data %px\n" -#ifdef CONFIG_PER_VMA_LOCK"refcnt %x\n" -#endif"flags: %#lx(%pGv)\n" , vma, (void *)vma->vm_start, (void *)vma->vm_end, vma->vm_mm, (unsigned long )pgprot_val (vma->vm_page_prot), vma->anon_vma, vma->vm_ops,vma_start_pgoff (vma), vma->vm_file, vma->vm_private_data, -#ifdef CONFIG_PER_VMA_LOCKrefcount_read (&vma->vm_refcnt), -#endif vma->vm_flags, &vma->vm_flags); }EXPORT_SYMBOL (dump_vma);mm/init-mm.c +0
-2@@ -39,10 +39,8 @@ struct mm_struct init_mm = { .page_table_lock = __SPIN_LOCK_UNLOCKED(init_mm.page_table_lock), .arg_lock = __SPIN_LOCK_UNLOCKED(init_mm.arg_lock), .mmlist = LIST_HEAD_INIT(init_mm.mmlist), -#ifdef CONFIG_PER_VMA_LOCK .vma_writer_wait = __RCUWAIT_INITIALIZER(init_mm.vma_writer_wait), .mm_lock_seq = SEQCNT_ZERO(init_mm.mm_lock_seq), -#endif #ifdef CONFIG_SCHED_MM_CID .mm_cid.lock = __RAW_SPIN_LOCK_UNLOCKED(init_mm.mm_cid.lock),#endif mm/memory.c +0
-2@@ -6814,7 +6814,6 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, !is_cow_mapping(vma->vm_flags)))return VM_FAULT_SIGSEGV ; } -#ifdef CONFIG_PER_VMA_LOCK /* * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of * the assumption that lock is dropped on VM_FAULT_RETRY. @@ -6823,7 +6822,6 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) == (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)))return VM_FAULT_SIGSEGV ; -#endif return 0 ; }mm/mmap_lock.c +0
-14@@ -43,9 +43,6 @@ void __mmap_lock_do_trace_released(struct mm_struct *mm, bool write)EXPORT_SYMBOL (__mmap_lock_do_trace_released);#endif /* CONFIG_TRACING */ -#ifdef CONFIG_MMU -#ifdef CONFIG_PER_VMA_LOCK -/* State shared across __vma_[start, end]_exclude_readers. */ struct vma_exclude_readers_state {/* Input parameters. */ @@ -431,7 +428,6 @@ struct vm_area_struct *lock_next_vma(struct mm_struct *mm,return vma; } -#endif /* CONFIG_PER_VMA_LOCK */ #ifdef CONFIG_LOCK_MM_AND_FIND_VMA #include <linux/extable.h> @@ -548,23 +544,3 @@ struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm, return NULL; }#endif /* CONFIG_LOCK_MM_AND_FIND_VMA */ - -#else /* CONFIG_MMU */ - -/* -* At least xtensa ends up having protection faults even with no -* MMU.. No stack expansion, at least. -*/ -struct vm_area_struct *lock_mm_and_find_vma (struct mm_struct *mm, -unsigned long addr,struct pt_regs *regs) -{mm/mmap_lock.c struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm, · line 570
Quoted 10 lines
mm/mmap_lock.c +0
-10-struct vm_area_struct *vma; - -mmap_read_lock (mm); - vma =vma_lookup (mm, addr); -if (!vma) -mmap_read_unlock (mm); - return vma; -} - -#endif /* CONFIG_MMU */ Oh lovely to get rid of this :)
Quoted 25 lines
mm/pagewalk.c +0
-2@@ -446,7 +446,6 @@ static inline void process_mm_walk_lock(struct mm_struct *mm,static inline void process_vma_walk_lock (struct vm_area_struct *vma,enum page_walk_lock walk_lock) { -#ifdef CONFIG_PER_VMA_LOCK switch (walk_lock) {case PGWALK_WRLOCK :vma_start_write (vma);@@ -461,7 +460,6 @@ static inline void process_vma_walk_lock(struct vm_area_struct *vma,/* PGWALK_RDLOCK is handled by process_mm_walk_lock */ break ; } -#endif }/* mm/rmap.c +0
-0mm/rmap.c static void check_anon_vma_clone(struct vm_area_struct *dst, · line 265
Quoted 7 lines
mm/rmap.c +0
-1@@ -260,11 +260,9 @@ static void check_anon_vma_clone(struct vm_area_struct *dst,/* For the anon_vma to be compatible, it can only be singular. */ VM_WARN_ON_ONCE (operation ==VMA_OP_MERGE_UNFAULTED && !list_is_singular (&src->anon_vma_chain)); -#ifdef CONFIG_PER_VMA_LOCK /* Only merging an unfaulted VMA leaves the destination attached. */ VM_WARN_ON_ONCE (operation !=VMA_OP_MERGE_UNFAULTED &&vma_is_attached (dst));Yeah this should be fine as VMAs are always !vma_is_attached() for nommu.
Quoted 150 lines
mm/rmap.c +0
-1-#endif } static void maybe_reuse_anon_vma(struct vm_area_struct *dst,mm/userfaultfd.c +0
-55@@ -122,7 +122,6 @@ struct vm_area_struct *find_vma_and_prepare_anon(struct mm_struct *mm,return vma; } -#ifdef CONFIG_PER_VMA_LOCK /* * uffd_lock_vma() - Lookup and lock vma corresponding to @address. * @mm: mm to search vma in. @@ -182,34 +181,6 @@ static void uffd_mfill_unlock(struct vm_area_struct *vma)vma_end_read (vma); } -#else - -static struct vm_area_struct *uffd_mfill_lock (struct mm_struct *dst_mm, -unsigned long dst_start, -unsigned long len) -{ -struct vm_area_struct *dst_vma; - -mmap_read_lock (dst_mm); - dst_vma =find_vma_and_prepare_anon (dst_mm, dst_start); -if (IS_ERR (dst_vma)) - goto out_unlock; - -if (validate_dst_vma (dst_vma, dst_start + len)) -return dst_vma; - - dst_vma =ERR_PTR (-ENOENT ); -out_unlock: -mmap_read_unlock (dst_mm); -return dst_vma; -} - -static void uffd_mfill_unlock (struct vm_area_struct *vma) -{ -mmap_read_unlock (vma->vm_mm); -} -#endif -static void mfill_put_vma (struct mfill_state *state) {if (!state->vma)@@ -1852,7 +1823,6 @@ int find_vmas_mm_locked(struct mm_struct *mm,return 0 ; } -#ifdef CONFIG_PER_VMA_LOCK static int uffd_move_lock(struct mm_struct *mm, unsigned long dst_start, unsigned long src_start,@@ -1927,31 +1897,6 @@ static void uffd_move_unlock(struct vm_area_struct *dst_vma,vma_end_read (dst_vma); } -#else - -static int uffd_move_lock (struct mm_struct *mm, -unsigned long dst_start, -unsigned long src_start, -struct vm_area_struct **dst_vmap, -struct vm_area_struct **src_vmap) -{ -int err; - -mmap_read_lock (mm); - err =find_vmas_mm_locked (mm, dst_start, src_start, dst_vmap, src_vmap); -if (err) -mmap_read_unlock (mm); -return err; -} - -static void uffd_move_unlock (struct vm_area_struct *dst_vma, -struct vm_area_struct *src_vma) -{ -mmap_assert_locked (src_vma->vm_mm); -mmap_read_unlock (dst_vma->vm_mm); -} -#endif -/** * move_pages - move arbitrary anonymous pages of an existing vma * @ctx: pointer to the userfaultfd context rust/kernel/mm.rs +11
-21@@ -170,30 +170,20 @@ pub unsafe fn from_raw<'a>(ptr: *const bindings::mm_struct) -> &'a MmWithUser {/// /// This is an optimistic trylock operation, so it may fail if there is contention. In that /// case, you should fall back to taking the mmap read lock. -/// -/// When per-vma locks are disabled, this always returns `None`. #[inline] pub fn lock_vma_under_rcu (&self, vma_addr:usize ) ->Option <VmaReadGuard <'_>> { -#[cfg( CONFIG_PER_VMA_LOCK )] - { -// SAFETY: Calling `bindings::lock_vma_under_rcu` is always okay given an mm where -// `mm_users` is non-zero. -let vma =unsafe { bindings::lock_vma_under_rcu (self.as_raw (), vma_addr) }; -if !vma.is_null () { -return Some (VmaReadGuard { -// SAFETY: If `lock_vma_under_rcu` returns a non-null ptr, then it points at a -// valid vma. The vma is stable for as long as the vma read lock is held. - vma:unsafe {VmaRef ::from_raw (vma) }, - _nts:NotThreadSafe , - }); - } +// SAFETY: Calling `bindings::lock_vma_under_rcu` is always okay given an mm where +// `mm_users` is non-zero. +let vma =unsafe { bindings::lock_vma_under_rcu (self.as_raw (), vma_addr) }; +if vma.is_null () { +return None ; } - -// Silence warnings about unused variables. -#[cfg(not( CONFIG_PER_VMA_LOCK ))] -let _ = vma_addr; - -None +Some (VmaReadGuard { +// SAFETY: If `lock_vma_under_rcu` returns a non-null ptr, then it points at a +// valid vma. The vma is stable for as long as the vma read lock is held. + vma:unsafe {VmaRef ::from_raw (vma) }, + _nts:NotThreadSafe , + }) }/// Lock the mmap read lock. tools/testing/vma/include/dup.h +0
-1@@ -582,7 +582,6 @@ struct vm_area_struct {vma_flags_t flags; }; -#ifdef CONFIG_PER_VMA_LOCK /* * Can only be written (using WRITE_ONCE()) while holding both: * - mmap_lock (in write mode) tools/testing/vma/include/dup.h struct vm_area_struct { · line 601
Quoted 6 lines
tools/testing/vma/include/dup.h +1
-1@@ -598,7 +597,7 @@ struct vm_area_struct {* slowpath. */ unsigned int vm_lock_seq; -#endif +unsigned int __vm_virt_pgoff_lo;Similar rebase issue here :)
tools/testing/vma/include/dup.h struct vm_area_struct { · line 637
Quoted 12 lines
tools/testing/vma/include/dup.h +0
-2/* @@ -632,10 +631,8 @@ struct vm_area_struct {#ifdef CONFIG_NUMA_BALANCING struct vma_numab_state *numab_state;/* NUMA Balancing state */ #endif -#ifdef CONFIG_PER_VMA_LOCK /* Unstable RCU readers are allowed to read this. */ refcount_t vm_refcnt; -#endif #ifdef CONFIG_64BIT unsigned int __vm_virt_pgoff_hi;And here.
Quoted 2 lines
Anyway, since this is for 7.4 I guess, you will need to be fairly rebase-happy anyway as things evolve! :)
Yes, will rebase over the latest mm-unstable.
Thanks for the review, Lorenzo!
Quoted 20 lines
Quoted 15 lines
tools/testing/vma/include/dup.h +0
-0#endif tools/testing/vma/vma_internal.h +0
-2@@ -15,7 +15,6 @@#include <stdlib.h> #define CONFIG_MMU 1 -#define CONFIG_PER_VMA_LOCK 1#ifdef __CONCAT#undef __CONCAT --Quoted 2 lines
2.55.0.654.g21b8a5bc05-goog
--
Cheers, Lorenzo
Suren Baghdasaryan
maintainerPATCH v4 2/5 binder: Make shrinker rely solely on per-VMA lock
In reply to Suren BaghdasaryanFrom: Dave Hansen <[email protected]>
tl;dr: lock_vma_under_rcu() is already a trylock. No need to do both it and mmap_read_trylock().
Long Version:
== Background ==
Historically, binder used an mmap_read_trylock() in its shrinker code. This ensures that reclaim is not blocked on an mmap_lock. Commit 95bc2d4a9020 ("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but left mmap_read_trylock() as a fallback.
This was presumably because the per-VMA locking can fail for several reasons and most (all?) lock_vma_under_rcu() callers have a fallback to mmap_read_trylock().
== Problem ==
The fallback is not worth the complexity here. lock_vma_under_rcu() is essentially already a non-blocking trylock. The main reason it fails is also the reason mmap_read_trylock() fails: something is holding mmap_write_lock().
The only remedy for a collision with mmap_write_lock() is to wait, which this code can not do. So the "fallback" after lock_vma_under_rcu() failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.
== Solution ==
Now that per-VMA locks are universally available, lock_vma_under_rcu() will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends on CONFIG_MMU.
Full disclosure: I originally tried to do this with lock_vma_under_rcu_wait(), but it did not fit well with the mmap_lock trylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.
--- drivers/android/binder_alloc.c | 45 ++++++++++++++++------------------ 1 file changed, 21 insertions(+), 24 deletions(-)
drivers/android/binder_alloc.c +21 -24
@@ -1142,7 +1142,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,struct vm_area_struct *vma;struct page *page_to_free;unsigned long page_addr; -int mm_locked =0 ;size_t index;if (!mmget_not_zero (mm))
@@ -1151,27 +1150,25 @@ enum lru_status binder_alloc_free_page(struct list_head *item, index = mdata->page_index; page_addr = alloc->vm_start + index *PAGE_SIZE ; -/* attempt per-vma lock first */ +/* +* Attempt per-vma lock. This is essentially a +* "trylock". It can fail even if the VMA exists +* for 'page_addr'. +*/ vma =lock_vma_under_rcu (mm, page_addr);if (!vma) { -/* fall back to mmap_lock */ -if (!mmap_read_trylock (mm)) - goto err_mmap_read_lock_failed; - mm_locked =1 ; - vma =vma_lookup (mm, page_addr); +/* +* If the vma exists, we can't continue because we cannot +* remove the page from the vma. However, if the vma was +* unmapped, it's okay to continue. +*/ +if (binder_alloc_is_mapped (alloc)) + goto err_vma_lock_failed; }if (!mutex_trylock (&alloc->mutex)) goto err_get_alloc_mutex_failed; -/* -* Since a binder_alloc can only be mapped once, we ensure -* the vma corresponds to this mapping by checking whether -* the binder_alloc is still mapped. -*/ -if (vma && !binder_alloc_is_mapped (alloc)) - goto err_invalid_vma; -trace_binder_unmap_kernel_start (alloc, index); page_to_free = alloc->pages[index];
@@ -1182,7 +1179,12 @@ enum lru_status binder_alloc_free_page(struct list_head *item,list_lru_isolate (lru, item);spin_unlock (&lru->lock); -if (vma) { +/* +* Since a binder_alloc can only be mapped once, we ensure +* the vma corresponds to this mapping by checking whether +* the binder_alloc is still mapped. +*/ +if (vma &&binder_alloc_is_mapped (alloc)) {trace_binder_unmap_user_start (alloc, index);zap_vma_range (vma, page_addr,PAGE_SIZE );
@@ -1191,23 +1193,18 @@ enum lru_status binder_alloc_free_page(struct list_head *item, }mutex_unlock (&alloc->mutex); -if (mm_locked) -mmap_read_unlock (mm); -else +if (vma)vma_end_read (vma);mmput_async (mm);binder_free_page (page_to_free);return LRU_REMOVED_RETRY ; -err_invalid_vma:mutex_unlock (&alloc->mutex); err_get_alloc_mutex_failed: -if (mm_locked) -mmap_read_unlock (mm); -else +if (vma)vma_end_read (vma); -err_mmap_read_lock_failed: +err_vma_lock_failed:mmput_async (mm); err_mmget:return LRU_SKIP ;
Signature · 1 line
2.55.0.654.g21b8a5bc05-goog
Re: [PATCH v4 2/5] binder: Make shrinker rely solely on per-VMA lock
Quoted 40 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
tl;dr:
lock_vma_under_rcu()is already a trylock. No need to do both it andmmap_read_trylock().Long Version:
== Background ==
Historically, binder used an
mmap_read_trylock()in its shrinker code. This ensures that reclaim is not blocked on anmmap_lock. Commit95bc2d4a9020("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but leftmmap_read_trylock()as a fallback.This was presumably because the per-VMA locking can fail for several reasons and most (all?)
lock_vma_under_rcu()callers have a fallback tommap_read_trylock().== Problem ==
The fallback is not worth the complexity here.
lock_vma_under_rcu()is essentially already a non-blocking trylock. The main reason it fails is also the reasonmmap_read_trylock()fails: something is holdingmmap_write_lock().The only remedy for a collision with
mmap_write_lock()is to wait, which this code can not do. So the "fallback" afterlock_vma_under_rcu()failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.== Solution ==
Now that per-VMA locks are universally available,
lock_vma_under_rcu()will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends onCONFIG_MMU.
Quoted 8 lines
Full disclosure: I originally tried to do this with
lock_vma_under_rcu_wait(), but it did not fit well with themmap_locktrylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>
Re: [PATCH v4 2/5] binder: Make shrinker rely solely on per-VMA lock
In reply to Suren BaghdasaryanQuoted 39 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
tl;dr:
lock_vma_under_rcu()is already a trylock. No need to do both it andmmap_read_trylock().Long Version:
== Background ==
Historically, binder used an
mmap_read_trylock()in its shrinker code. This ensures that reclaim is not blocked on anmmap_lock. Commit95bc2d4a9020("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but leftmmap_read_trylock()as a fallback.This was presumably because the per-VMA locking can fail for several reasons and most (all?)
lock_vma_under_rcu()callers have a fallback tommap_read_trylock().== Problem ==
The fallback is not worth the complexity here.
lock_vma_under_rcu()is essentially already a non-blocking trylock. The main reason it fails is also the reasonmmap_read_trylock()fails: something is holdingmmap_write_lock().The only remedy for a collision with
mmap_write_lock()is to wait, which this code can not do. So the "fallback" afterlock_vma_under_rcu()failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.== Solution ==
Now that per-VMA locks are universally available,
lock_vma_under_rcu()will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends onCONFIG_MMU.
Quoted 8 lines
Full disclosure: I originally tried to do this with
lock_vma_under_rcu_wait(), but it did not fit well with themmap_locktrylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>
Thanks, LGTM so:
Quoted 112 lines
Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- drivers/android/binder_alloc.c | 45 ++++++++++++++++------------------ 1 file changed, 21 insertions(+), 24 deletions(-)drivers/android/binder_alloc.c +21
-25@@ -1142,7 +1142,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,struct vm_area_struct *vma;struct page *page_to_free;unsigned long page_addr; -int mm_locked =0 ;size_t index;if (!mmget_not_zero (mm))@@ -1151,27 +1150,25 @@ enum lru_status binder_alloc_free_page(struct list_head *item, index = mdata->page_index; page_addr = alloc->vm_start + index *PAGE_SIZE ; -/* attempt per-vma lock first */ +/* +* Attempt per-vma lock. This is essentially a +* "trylock". It can fail even if the VMA exists +* for 'page_addr'. +*/ vma =lock_vma_under_rcu (mm, page_addr);if (!vma) { -/* fall back to mmap_lock */ -if (!mmap_read_trylock (mm)) - goto err_mmap_read_lock_failed; - mm_locked =1 ; - vma =vma_lookup (mm, page_addr); +/* +* If the vma exists, we can't continue because we cannot +* remove the page from the vma. However, if the vma was +* unmapped, it's okay to continue. +*/ +if (binder_alloc_is_mapped (alloc)) + goto err_vma_lock_failed; }if (!mutex_trylock (&alloc->mutex)) goto err_get_alloc_mutex_failed; -/* -* Since a binder_alloc can only be mapped once, we ensure -* the vma corresponds to this mapping by checking whether -* the binder_alloc is still mapped. -*/ -if (vma && !binder_alloc_is_mapped (alloc)) - goto err_invalid_vma; -trace_binder_unmap_kernel_start (alloc, index); page_to_free = alloc->pages[index];@@ -1182,7 +1179,12 @@ enum lru_status binder_alloc_free_page(struct list_head *item,list_lru_isolate (lru, item);spin_unlock (&lru->lock); -if (vma) { +/* +* Since a binder_alloc can only be mapped once, we ensure +* the vma corresponds to this mapping by checking whether +* the binder_alloc is still mapped. +*/ +if (vma &&binder_alloc_is_mapped (alloc)) {trace_binder_unmap_user_start (alloc, index);zap_vma_range (vma, page_addr,PAGE_SIZE );@@ -1191,23 +1193,18 @@ enum lru_status binder_alloc_free_page(struct list_head *item, }mutex_unlock (&alloc->mutex); -if (mm_locked) -mmap_read_unlock (mm); -else +if (vma)vma_end_read (vma);mmput_async (mm);binder_free_page (page_to_free);return LRU_REMOVED_RETRY ; -err_invalid_vma:mutex_unlock (&alloc->mutex); err_get_alloc_mutex_failed: -if (mm_locked) -mmap_read_unlock (mm); -else +if (vma)vma_end_read (vma); -err_mmap_read_lock_failed: +err_vma_lock_failed:mmput_async (mm); err_mmget:return LRU_SKIP ; --
Quoted 2 lines
2.55.0.654.g21b8a5bc05-goog
--
Cheers, Lorenzo
Carlos Llamas
maintainerRe: [PATCH v4 2/5] binder: Make shrinker rely solely on per-VMA lock
In reply to Suren BaghdasaryanQuoted 78 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
tl;dr:
lock_vma_under_rcu()is already a trylock. No need to do both it andmmap_read_trylock().Long Version:
== Background ==
Historically, binder used an
mmap_read_trylock()in its shrinker code. This ensures that reclaim is not blocked on anmmap_lock. Commit95bc2d4a9020("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but leftmmap_read_trylock()as a fallback.This was presumably because the per-VMA locking can fail for several reasons and most (all?)
lock_vma_under_rcu()callers have a fallback tommap_read_trylock().== Problem ==
The fallback is not worth the complexity here.
lock_vma_under_rcu()is essentially already a non-blocking trylock. The main reason it fails is also the reasonmmap_read_trylock()fails: something is holdingmmap_write_lock().The only remedy for a collision with
mmap_write_lock()is to wait, which this code can not do. So the "fallback" afterlock_vma_under_rcu()failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.== Solution ==
Now that per-VMA locks are universally available,
lock_vma_under_rcu()will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends onCONFIG_MMU.Full disclosure: I originally tried to do this with
lock_vma_under_rcu_wait(), but it did not fit well with themmap_locktrylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- drivers/android/binder_alloc.c | 45 ++++++++++++++++------------------ 1 file changed, 21 insertions(+), 24 deletions(-)drivers/android/binder_alloc.c +0
-1@@ -1142,7 +1142,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,struct vm_area_struct *vma;struct page *page_to_free;unsigned long page_addr; -int mm_locked =0 ;size_t index;if (!mmget_not_zero (mm))
drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1157
Quoted 9 lines
drivers/android/binder_alloc.c +5
-1@@ -1151,27 +1150,25 @@ enum lru_status binder_alloc_free_page(struct list_head *item, index = mdata->page_index; page_addr = alloc->vm_start + index *PAGE_SIZE ; -/* attempt per-vma lock first */ +/* +* Attempt per-vma lock. This is essentially a +* "trylock". It can fail even if the VMA exists +* for 'page_addr'. +*/
Do we need to explain how lock_vma_under_rcu() works here?
Quoted 4 lines
drivers/android/binder_alloc.c +0
-2vma =lock_vma_under_rcu (mm, page_addr);if (!vma) { -/* fall back to mmap_lock */ -if (!mmap_read_trylock (mm))
drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1166
Quoted 10 lines
drivers/android/binder_alloc.c +7
-3- goto err_mmap_read_lock_failed; - mm_locked =1 ; - vma =vma_lookup (mm, page_addr); +/* +* If the vma exists, we can't continue because we cannot +* remove the page from the vma. However, if the vma was +* unmapped, it's okay to continue. +*/ +if (binder_alloc_is_mapped (alloc)) + goto err_vma_lock_failed;
The comments seem redundant, the label is enough. This works:
vma = lock_vma_under_rcu(mm, page_addr); if (!vma && binder_alloc_is_mapped(alloc)) goto err_vma_lock_failed;
drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1174
Quoted 13 lines
drivers/android/binder_alloc.c +0
-8}if (!mutex_trylock (&alloc->mutex)) goto err_get_alloc_mutex_failed; -/* -* Since a binder_alloc can only be mapped once, we ensure -* the vma corresponds to this mapping by checking whether -* the binder_alloc is still mapped. -*/ -if (vma && !binder_alloc_is_mapped (alloc)) - goto err_invalid_vma; -
This introduces an "extra" change. We'll now release pages without a valid vma (e.g. after munmap()). Before, these pages were expected to be released via close() in binder_alloc_deferred_release() later.
I don't see anything wrong with it. However, it does seem out of the scope of this patch which just drops the mmap_read_lock() calls. Or at least I don't see how this part is necessary.
Quoted 23 lines
drivers/android/binder_alloc.c +6
-3trace_binder_unmap_kernel_start (alloc, index); page_to_free = alloc->pages[index];@@ -1182,7 +1179,12 @@ enum lru_status binder_alloc_free_page(struct list_head *item,list_lru_isolate (lru, item);spin_unlock (&lru->lock); -if (vma) { +/* +* Since a binder_alloc can only be mapped once, we ensure +* the vma corresponds to this mapping by checking whether +* the binder_alloc is still mapped. +*/ +if (vma &&binder_alloc_is_mapped (alloc)) {trace_binder_unmap_user_start (alloc, index);zap_vma_range (vma, page_addr,PAGE_SIZE );@@ -1191,23 +1193,18 @@ enum lru_status binder_alloc_free_page(struct list_head *item, }mutex_unlock (&alloc->mutex); -if (mm_locked) -mmap_read_unlock (mm);
drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1203
Quoted 10 lines
drivers/android/binder_alloc.c +1
-2-else +if (vma)vma_end_read (vma);mmput_async (mm);binder_free_page (page_to_free);return LRU_REMOVED_RETRY ; -err_invalid_vma:mutex_unlock (&alloc->mutex);
This mutex_unlock() is now dead-code.
Quoted 14 lines
drivers/android/binder_alloc.c +2
-4err_get_alloc_mutex_failed: -if (mm_locked) -mmap_read_unlock (mm); -else +if (vma)vma_end_read (vma); -err_mmap_read_lock_failed: +err_vma_lock_failed:mmput_async (mm); err_mmget:return LRU_SKIP ;Signature · 1 line
2.55.0.654.g21b8a5bc05-goog
Suren Baghdasaryan
maintainerRe: [PATCH v4 2/5] binder: Make shrinker rely solely on per-VMA lock
Quoted 107 lines · Carlos Llamas
Quoted 78 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
tl;dr:
lock_vma_under_rcu()is already a trylock. No need to do both it andmmap_read_trylock().Long Version:
== Background ==
Historically, binder used an
mmap_read_trylock()in its shrinker code. This ensures that reclaim is not blocked on anmmap_lock. Commit95bc2d4a9020("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but leftmmap_read_trylock()as a fallback.This was presumably because the per-VMA locking can fail for several reasons and most (all?)
lock_vma_under_rcu()callers have a fallback tommap_read_trylock().== Problem ==
The fallback is not worth the complexity here.
lock_vma_under_rcu()is essentially already a non-blocking trylock. The main reason it fails is also the reasonmmap_read_trylock()fails: something is holdingmmap_write_lock().The only remedy for a collision with
mmap_write_lock()is to wait, which this code can not do. So the "fallback" afterlock_vma_under_rcu()failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.== Solution ==
Now that per-VMA locks are universally available,
lock_vma_under_rcu()will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends onCONFIG_MMU.Full disclosure: I originally tried to do this with
lock_vma_under_rcu_wait(), but it did not fit well with themmap_locktrylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- drivers/android/binder_alloc.c | 45 ++++++++++++++++------------------ 1 file changed, 21 insertions(+), 24 deletions(-)drivers/android/binder_alloc.c +0
-1@@ -1142,7 +1142,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,struct vm_area_struct *vma;struct page *page_to_free;unsigned long page_addr; -int mm_locked =0 ;size_t index;if (!mmget_not_zero (mm))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1157
Quoted 9 lines
drivers/android/binder_alloc.c +5
-1@@ -1151,27 +1150,25 @@ enum lru_status binder_alloc_free_page(struct list_head *item, index = mdata->page_index; page_addr = alloc->vm_start + index *PAGE_SIZE ; -/* attempt per-vma lock first */ +/* +* Attempt per-vma lock. This is essentially a +* "trylock". It can fail even if the VMA exists +* for 'page_addr'. +*/ Do we need to explain how
lock_vma_under_rcu()works here?Quoted 4 lines
drivers/android/binder_alloc.c +0
-2vma =lock_vma_under_rcu (mm, page_addr);if (!vma) { -/* fall back to mmap_lock */ -if (!mmap_read_trylock (mm))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1166
Quoted 10 lines
drivers/android/binder_alloc.c +7
-3- goto err_mmap_read_lock_failed; - mm_locked =1 ; - vma =vma_lookup (mm, page_addr); +/* +* If the vma exists, we can't continue because we cannot +* remove the page from the vma. However, if the vma was +* unmapped, it's okay to continue. +*/ +if (binder_alloc_is_mapped (alloc)) + goto err_vma_lock_failed;
Quoted 5 lines
The comments seem redundant, the label is enough. This works:
vma = lock_vma_under_rcu(mm, page_addr); if (!vma && binder_alloc_is_mapped(alloc)) goto err_vma_lock_failed;
Yeah, for the binder maintainers what's happening here is probably obvious, but when Alice explained the logic to me, this comment really clarified what's going on, so I added it here. If you insist on removing it, I'll do that of course.
Quoted 16 lines
Quoted 5 lines
drivers/android/binder_alloc.c +0
-0}if (!mutex_trylock (&alloc->mutex))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1174
Quoted 10 lines
drivers/android/binder_alloc.c +0
-8goto err_get_alloc_mutex_failed; -/* -* Since a binder_alloc can only be mapped once, we ensure -* the vma corresponds to this mapping by checking whether -* the binder_alloc is still mapped. -*/ -if (vma && !binder_alloc_is_mapped (alloc)) - goto err_invalid_vma; -
Quoted 7 lines
This introduces an "extra" change. We'll now release pages without a valid vma (e.g. after
munmap()). Before, these pages were expected to be released viaclose()inbinder_alloc_deferred_release()later.I don't see anything wrong with it. However, it does seem out of the scope of this patch which just drops the
mmap_read_lock()calls. Or at least I don't see how this part is necessary.
This check came from this discussion:
https://lore.kernel.org/all/[email protected]/
It's added for consistency when handling cases where the original Binder VMA is gone.
Quoted 30 lines
Quoted 30 lines
drivers/android/binder_alloc.c +7
-4trace_binder_unmap_kernel_start (alloc, index); page_to_free = alloc->pages[index];@@ -1182,7 +1179,12 @@ enum lru_status binder_alloc_free_page(struct list_head *item,list_lru_isolate (lru, item);spin_unlock (&lru->lock); -if (vma) { +/* +* Since a binder_alloc can only be mapped once, we ensure +* the vma corresponds to this mapping by checking whether +* the binder_alloc is still mapped. +*/ +if (vma &&binder_alloc_is_mapped (alloc)) {trace_binder_unmap_user_start (alloc, index);zap_vma_range (vma, page_addr,PAGE_SIZE );@@ -1191,23 +1193,18 @@ enum lru_status binder_alloc_free_page(struct list_head *item, }mutex_unlock (&alloc->mutex); -if (mm_locked) -mmap_read_unlock (mm); -else +if (vma)vma_end_read (vma);mmput_async (mm);binder_free_page (page_to_free);
Quoted 6 lines
drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1203
Quoted 4 lines
drivers/android/binder_alloc.c +0
-1return LRU_REMOVED_RETRY ; -err_invalid_vma:mutex_unlock (&alloc->mutex);This
mutex_unlock()is now dead-code.
Ack. Will remove.
Quoted 15 lines
Quoted 15 lines
drivers/android/binder_alloc.c +2
-5err_get_alloc_mutex_failed: -if (mm_locked) -mmap_read_unlock (mm); -else +if (vma)vma_end_read (vma); -err_mmap_read_lock_failed: +err_vma_lock_failed:mmput_async (mm); err_mmget:return LRU_SKIP ; --2.55.0.654.g21b8a5bc05-goog
Carlos Llamas
maintainerRe: [PATCH v4 2/5] binder: Make shrinker rely solely on per-VMA lock
Quoted 139 lines · Suren Baghdasaryan
Quoted 107 lines · Carlos Llamas
Quoted 78 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
tl;dr:
lock_vma_under_rcu()is already a trylock. No need to do both it andmmap_read_trylock().Long Version:
== Background ==
Historically, binder used an
mmap_read_trylock()in its shrinker code. This ensures that reclaim is not blocked on anmmap_lock. Commit95bc2d4a9020("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but leftmmap_read_trylock()as a fallback.This was presumably because the per-VMA locking can fail for several reasons and most (all?)
lock_vma_under_rcu()callers have a fallback tommap_read_trylock().== Problem ==
The fallback is not worth the complexity here.
lock_vma_under_rcu()is essentially already a non-blocking trylock. The main reason it fails is also the reasonmmap_read_trylock()fails: something is holdingmmap_write_lock().The only remedy for a collision with
mmap_write_lock()is to wait, which this code can not do. So the "fallback" afterlock_vma_under_rcu()failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.== Solution ==
Now that per-VMA locks are universally available,
lock_vma_under_rcu()will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends onCONFIG_MMU.Full disclosure: I originally tried to do this with
lock_vma_under_rcu_wait(), but it did not fit well with themmap_locktrylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- drivers/android/binder_alloc.c | 45 ++++++++++++++++------------------ 1 file changed, 21 insertions(+), 24 deletions(-)drivers/android/binder_alloc.c +0
-1@@ -1142,7 +1142,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,struct vm_area_struct *vma;struct page *page_to_free;unsigned long page_addr; -int mm_locked =0 ;size_t index;if (!mmget_not_zero (mm))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1157
Quoted 9 lines
drivers/android/binder_alloc.c +5
-1@@ -1151,27 +1150,25 @@ enum lru_status binder_alloc_free_page(struct list_head *item, index = mdata->page_index; page_addr = alloc->vm_start + index *PAGE_SIZE ; -/* attempt per-vma lock first */ +/* +* Attempt per-vma lock. This is essentially a +* "trylock". It can fail even if the VMA exists +* for 'page_addr'. +*/ Do we need to explain how
lock_vma_under_rcu()works here?Quoted 4 lines
drivers/android/binder_alloc.c +0
-2vma =lock_vma_under_rcu (mm, page_addr);if (!vma) { -/* fall back to mmap_lock */ -if (!mmap_read_trylock (mm))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1166
Quoted 10 lines
drivers/android/binder_alloc.c +7
-3- goto err_mmap_read_lock_failed; - mm_locked =1 ; - vma =vma_lookup (mm, page_addr); +/* +* If the vma exists, we can't continue because we cannot +* remove the page from the vma. However, if the vma was +* unmapped, it's okay to continue. +*/ +if (binder_alloc_is_mapped (alloc)) + goto err_vma_lock_failed;Quoted 5 lines
The comments seem redundant, the label is enough. This works:
vma = lock_vma_under_rcu(mm, page_addr); if (!vma && binder_alloc_is_mapped(alloc)) goto err_vma_lock_failed;Yeah, for the binder maintainers what's happening here is probably obvious, but when Alice explained the logic to me, this comment really clarified what's going on, so I added it here. If you insist on removing it, I'll do that of course.
Quoted 20 lines
Quoted 5 lines
drivers/android/binder_alloc.c +0
-0}if (!mutex_trylock (&alloc->mutex))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1174
Quoted 10 lines
drivers/android/binder_alloc.c +0
-8goto err_get_alloc_mutex_failed; -/* -* Since a binder_alloc can only be mapped once, we ensure -* the vma corresponds to this mapping by checking whether -* the binder_alloc is still mapped. -*/ -if (vma && !binder_alloc_is_mapped (alloc)) - goto err_invalid_vma; -This introduces an "extra" change. We'll now release pages without a valid vma (e.g. after
munmap()). Before, these pages were expected to be released viaclose()inbinder_alloc_deferred_release()later.
Quoted 8 lines
Quoted 3 lines
I don't see anything wrong with it. However, it does seem out of the scope of this patch which just drops the
mmap_read_lock()calls. Or at least I don't see how this part is necessary.This check came from this discussion:
https://lore.kernel.org/all/[email protected]/
It's added for consistency when handling cases where the original Binder VMA is gone.
Oh sorry I missed that thread. Yes, I agree we can reclaim these pages earlier if really needed but my point is this is unrelated to the change done here IMO. I couldn't figure out why that was needed.
If you are keeping that in the same commit it's probably worth adding an explanation to the commit log?
--
Carlos Llamas
Suren Baghdasaryan
maintainerRe: [PATCH v4 2/5] binder: Make shrinker rely solely on per-VMA lock
Quoted 150 lines · Carlos Llamas
Quoted 139 lines · Suren Baghdasaryan
Quoted 107 lines · Carlos Llamas
Quoted 78 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
tl;dr:
lock_vma_under_rcu()is already a trylock. No need to do both it andmmap_read_trylock().Long Version:
== Background ==
Historically, binder used an
mmap_read_trylock()in its shrinker code. This ensures that reclaim is not blocked on anmmap_lock. Commit95bc2d4a9020("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but leftmmap_read_trylock()as a fallback.This was presumably because the per-VMA locking can fail for several reasons and most (all?)
lock_vma_under_rcu()callers have a fallback tommap_read_trylock().== Problem ==
The fallback is not worth the complexity here.
lock_vma_under_rcu()is essentially already a non-blocking trylock. The main reason it fails is also the reasonmmap_read_trylock()fails: something is holdingmmap_write_lock().The only remedy for a collision with
mmap_write_lock()is to wait, which this code can not do. So the "fallback" afterlock_vma_under_rcu()failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.== Solution ==
Now that per-VMA locks are universally available,
lock_vma_under_rcu()will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends onCONFIG_MMU.Full disclosure: I originally tried to do this with
lock_vma_under_rcu_wait(), but it did not fit well with themmap_locktrylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- drivers/android/binder_alloc.c | 45 ++++++++++++++++------------------ 1 file changed, 21 insertions(+), 24 deletions(-)drivers/android/binder_alloc.c +0
-1@@ -1142,7 +1142,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,struct vm_area_struct *vma;struct page *page_to_free;unsigned long page_addr; -int mm_locked =0 ;size_t index;if (!mmget_not_zero (mm))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1157
Quoted 9 lines
drivers/android/binder_alloc.c +5
-1@@ -1151,27 +1150,25 @@ enum lru_status binder_alloc_free_page(struct list_head *item, index = mdata->page_index; page_addr = alloc->vm_start + index *PAGE_SIZE ; -/* attempt per-vma lock first */ +/* +* Attempt per-vma lock. This is essentially a +* "trylock". It can fail even if the VMA exists +* for 'page_addr'. +*/ Do we need to explain how
lock_vma_under_rcu()works here?Quoted 4 lines
drivers/android/binder_alloc.c +0
-2vma =lock_vma_under_rcu (mm, page_addr);if (!vma) { -/* fall back to mmap_lock */ -if (!mmap_read_trylock (mm))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1166
Quoted 10 lines
drivers/android/binder_alloc.c +7
-3- goto err_mmap_read_lock_failed; - mm_locked =1 ; - vma =vma_lookup (mm, page_addr); +/* +* If the vma exists, we can't continue because we cannot +* remove the page from the vma. However, if the vma was +* unmapped, it's okay to continue. +*/ +if (binder_alloc_is_mapped (alloc)) + goto err_vma_lock_failed;Quoted 5 lines
The comments seem redundant, the label is enough. This works:
vma = lock_vma_under_rcu(mm, page_addr); if (!vma && binder_alloc_is_mapped(alloc)) goto err_vma_lock_failed;Yeah, for the binder maintainers what's happening here is probably obvious, but when Alice explained the logic to me, this comment really clarified what's going on, so I added it here. If you insist on removing it, I'll do that of course.
Quoted 20 lines
Quoted 5 lines
drivers/android/binder_alloc.c +0
-0}if (!mutex_trylock (&alloc->mutex))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1174
Quoted 10 lines
drivers/android/binder_alloc.c +0
-8goto err_get_alloc_mutex_failed; -/* -* Since a binder_alloc can only be mapped once, we ensure -* the vma corresponds to this mapping by checking whether -* the binder_alloc is still mapped. -*/ -if (vma && !binder_alloc_is_mapped (alloc)) - goto err_invalid_vma; -This introduces an "extra" change. We'll now release pages without a valid vma (e.g. after
munmap()). Before, these pages were expected to be released viaclose()inbinder_alloc_deferred_release()later.Quoted 8 lines
Quoted 3 lines
I don't see anything wrong with it. However, it does seem out of the scope of this patch which just drops the
mmap_read_lock()calls. Or at least I don't see how this part is necessary.This check came from this discussion:
https://lore.kernel.org/all/[email protected]/
It's added for consistency when handling cases where the original Binder VMA is gone.
Quoted 6 lines
Oh sorry I missed that thread. Yes, I agree we can reclaim these pages earlier if really needed but my point is this is unrelated to the change done here IMO. I couldn't figure out why that was needed.
If you are keeping that in the same commit it's probably worth adding an explanation to the commit log?
Ok, I'll amend the commit log with an explanation for this change. Are you ok with keeping the other comment, or do you want it removed?
Quoted 3 lines
--
Carlos Llamas
Carlos Llamas
maintainerRe: [PATCH v4 2/5] binder: Make shrinker rely solely on per-VMA lock
Quoted 155 lines · Suren Baghdasaryan
Quoted 154 lines · Carlos Llamas
Quoted 139 lines · Suren Baghdasaryan
Quoted 107 lines · Carlos Llamas
Quoted 78 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
tl;dr:
lock_vma_under_rcu()is already a trylock. No need to do both it andmmap_read_trylock().Long Version:
== Background ==
Historically, binder used an
mmap_read_trylock()in its shrinker code. This ensures that reclaim is not blocked on anmmap_lock. Commit95bc2d4a9020("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but leftmmap_read_trylock()as a fallback.This was presumably because the per-VMA locking can fail for several reasons and most (all?)
lock_vma_under_rcu()callers have a fallback tommap_read_trylock().== Problem ==
The fallback is not worth the complexity here.
lock_vma_under_rcu()is essentially already a non-blocking trylock. The main reason it fails is also the reasonmmap_read_trylock()fails: something is holdingmmap_write_lock().The only remedy for a collision with
mmap_write_lock()is to wait, which this code can not do. So the "fallback" afterlock_vma_under_rcu()failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.== Solution ==
Now that per-VMA locks are universally available,
lock_vma_under_rcu()will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends onCONFIG_MMU.Full disclosure: I originally tried to do this with
lock_vma_under_rcu_wait(), but it did not fit well with themmap_locktrylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- drivers/android/binder_alloc.c | 45 ++++++++++++++++------------------ 1 file changed, 21 insertions(+), 24 deletions(-)drivers/android/binder_alloc.c +0
-1@@ -1142,7 +1142,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,struct vm_area_struct *vma;struct page *page_to_free;unsigned long page_addr; -int mm_locked =0 ;size_t index;if (!mmget_not_zero (mm))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1157
Quoted 9 lines
drivers/android/binder_alloc.c +5
-1@@ -1151,27 +1150,25 @@ enum lru_status binder_alloc_free_page(struct list_head *item, index = mdata->page_index; page_addr = alloc->vm_start + index *PAGE_SIZE ; -/* attempt per-vma lock first */ +/* +* Attempt per-vma lock. This is essentially a +* "trylock". It can fail even if the VMA exists +* for 'page_addr'. +*/ Do we need to explain how
lock_vma_under_rcu()works here?Quoted 4 lines
drivers/android/binder_alloc.c +0
-2vma =lock_vma_under_rcu (mm, page_addr);if (!vma) { -/* fall back to mmap_lock */ -if (!mmap_read_trylock (mm))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1166
Quoted 10 lines
drivers/android/binder_alloc.c +7
-3- goto err_mmap_read_lock_failed; - mm_locked =1 ; - vma =vma_lookup (mm, page_addr); +/* +* If the vma exists, we can't continue because we cannot +* remove the page from the vma. However, if the vma was +* unmapped, it's okay to continue. +*/ +if (binder_alloc_is_mapped (alloc)) + goto err_vma_lock_failed;Quoted 5 lines
The comments seem redundant, the label is enough. This works:
vma = lock_vma_under_rcu(mm, page_addr); if (!vma && binder_alloc_is_mapped(alloc)) goto err_vma_lock_failed;Yeah, for the binder maintainers what's happening here is probably obvious, but when Alice explained the logic to me, this comment really clarified what's going on, so I added it here. If you insist on removing it, I'll do that of course.
Quoted 20 lines
Quoted 5 lines
drivers/android/binder_alloc.c +0
-0}if (!mutex_trylock (&alloc->mutex))drivers/android/binder_alloc.c enum lru_status binder_alloc_free_page(struct list_head *item, · line 1174
Quoted 10 lines
drivers/android/binder_alloc.c +0
-8goto err_get_alloc_mutex_failed; -/* -* Since a binder_alloc can only be mapped once, we ensure -* the vma corresponds to this mapping by checking whether -* the binder_alloc is still mapped. -*/ -if (vma && !binder_alloc_is_mapped (alloc)) - goto err_invalid_vma; -This introduces an "extra" change. We'll now release pages without a valid vma (e.g. after
munmap()). Before, these pages were expected to be released viaclose()inbinder_alloc_deferred_release()later.Quoted 8 lines
Quoted 3 lines
I don't see anything wrong with it. However, it does seem out of the scope of this patch which just drops the
mmap_read_lock()calls. Or at least I don't see how this part is necessary.This check came from this discussion:
https://lore.kernel.org/all/[email protected]/
It's added for consistency when handling cases where the original Binder VMA is gone.Oh sorry I missed that thread. Yes, I agree we can reclaim these pages earlier if really needed but my point is this is unrelated to the change done here IMO. I couldn't figure out why that was needed.
Quoted 5 lines
Quoted 2 lines
If you are keeping that in the same commit it's probably worth adding an explanation to the commit log?
Ok, I'll amend the commit log with an explanation for this change. Are you ok with keeping the other comment, or do you want it removed?
Ok, let's keep the comment. You are right that it is not obvious what the intend of the binder_alloc_is_mapped() check is.
Thanks,
Carlos Llamas
Carlos Llamas
maintainerRe: [PATCH v4 2/5] binder: Make shrinker rely solely on per-VMA lock
In reply to Carlos LlamasQuoted 55 lines · Carlos Llamas
Quoted 54 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
tl;dr:
lock_vma_under_rcu()is already a trylock. No need to do both it andmmap_read_trylock().Long Version:
== Background ==
Historically, binder used an
mmap_read_trylock()in its shrinker code. This ensures that reclaim is not blocked on anmmap_lock. Commit95bc2d4a9020("binder: use per-vma lock in page reclaiming") added support for the per-VMA lock, but leftmmap_read_trylock()as a fallback.This was presumably because the per-VMA locking can fail for several reasons and most (all?)
lock_vma_under_rcu()callers have a fallback tommap_read_trylock().== Problem ==
The fallback is not worth the complexity here.
lock_vma_under_rcu()is essentially already a non-blocking trylock. The main reason it fails is also the reasonmmap_read_trylock()fails: something is holdingmmap_write_lock().The only remedy for a collision with
mmap_write_lock()is to wait, which this code can not do. So the "fallback" afterlock_vma_under_rcu()failure is not really a fallback: it is really likely to just be retrying in vain. That retry in an of itself isn't horrible. But it adds complexity.== Solution ==
Now that per-VMA locks are universally available,
lock_vma_under_rcu()will not persistently fail. Rely on it alone and simplify the code. The removal of the fallback does not affect NOMMU case because binder driver depends onCONFIG_MMU.Full disclosure: I originally tried to do this with
lock_vma_under_rcu_wait(), but it did not fit well with themmap_locktrylock semantics. Claude caught this in a review and suggested the approach in this path. It seemed sane to me. So, Suggesed-by: Claude, I guess.Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>
Quoted 8 lines
Quoted 8 lines
Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>---
FWIW, I think we should just simply do the following:
---
drivers/android/binder_alloc.c +5 -17
@@ -1142,7 +1142,6 @@ enum lru_status binder_alloc_free_page(struct list_head *item,struct vm_area_struct *vma;struct page *page_to_free;unsigned long page_addr; -int mm_locked =0 ;size_t index;if (!mmget_not_zero (mm))
@@ -1153,13 +1152,8 @@ enum lru_status binder_alloc_free_page(struct list_head *item,/* attempt per-vma lock first */ vma =lock_vma_under_rcu (mm, page_addr); -if (!vma) { -/* fall back to mmap_lock */ -if (!mmap_read_trylock (mm)) - goto err_mmap_read_lock_failed; - mm_locked =1 ; - vma =vma_lookup (mm, page_addr); - } +if (!vma) + goto err_vma_lock_failed;if (!mutex_trylock (&alloc->mutex)) goto err_get_alloc_mutex_failed;
@@ -1191,10 +1185,7 @@ enum lru_status binder_alloc_free_page(struct list_head *item, }mutex_unlock (&alloc->mutex); -if (mm_locked) -mmap_read_unlock (mm); -else -vma_end_read (vma); +vma_end_read (vma);mmput_async (mm);binder_free_page (page_to_free);
@@ -1203,11 +1194,8 @@ enum lru_status binder_alloc_free_page(struct list_head *item, err_invalid_vma:mutex_unlock (&alloc->mutex); err_get_alloc_mutex_failed: -if (mm_locked) -mmap_read_unlock (mm); -else -vma_end_read (vma); -err_mmap_read_lock_failed: +vma_end_read (vma); +err_vma_lock_failed:mmput_async (mm); err_mmget:return LRU_SKIP ;
Suren Baghdasaryan
maintainerPATCH v4 3/5 mm: Add RCU-based VMA lookup helper that waits for writers
In reply to Suren BaghdasaryanFrom: Dave Hansen <[email protected]>
== Background ==
There are basically two parallel ways to look up a VMA: the traditional way, which is protected by mmap_read_lock, and the RCU-based per-VMA lock way which is based on RCU and refcounts.
== Problem ==
The mmap_lock one is more straightforward to use but it has a big disadvantage in that it can not be mixed with page faults since those can take mmap_lock for read, which can deadlock when mixed with nested page faults and parallel writers.
For example:
mmap_read_lock(mm); // Another thread does mmap_write_lock(). // New mmap_lock readers are blocked. vma = vma_lookup(mm, address); // This deadlocks on mmap_read_lock() if it faults: copy_from_user(address); mmap_read_unlock(mm);
The per-VMA lock can be mixed with faults, but they can fail and need to be able to fall back to the traditional way.
== Solution ==
Add vma_start_read_unlocked() - a variant of the RCU-based lookup that waits for writers. This is basically the same as the existing RCU-based lookup, but on a failure to lock it temporarily takes mmap_lock for read and waits for writers to finish before locking the VMA, dropping the mmap_lock and returning the locked VMA. This has some advantages:
1. Callers do not need to have a fallback path for when they collide with writers.
2. It can be used in contexts where page faults can happen because it can take the mmap_lock for read but never *holds* it.
3. Its fast path does not require taking mmap_lock for read.
Basically, when applied correctly, this approach results in faster *and* simpler code.
While at it, fix the comments for vma_start_read_locked(), vma_start_read_locked_nested(), and uffd_lock_vma().
--- include/linux/mmap_lock.h | 19 +++++++++++++++---- mm/mmap_lock.c | 35 +++++++++++++++++++++++++++++++++++ mm/userfaultfd.c | 6 ++++-- 3 files changed, 54 insertions(+), 6 deletions(-)
include/linux/mmap_lock.h +15 -4
@@ -228,10 +228,14 @@ static inline void vma_refcount_put(struct vm_area_struct *vma) }/* -* Use only while holding mmap read lock which guarantees that locking will not -* fail (nobody can concurrently write-lock the vma). vma_start_read() should +* Use only while holding mmap read lock which guarantees that vma lock is not +* contended (nobody can concurrently write-lock the vma). vma_start_read() should * not be used in such cases because it might fail due to mm_lock_seq overflow. * This functionality is used to obtain vma read lock and drop the mmap read lock. +* +* VMA can't be detached while we are holding mmap lock, therefore in practice this +* function can fail only when there are so many readers that vm_refcnt overflows. +* The failure case is very unlikely and is already annotated as such internally. */ static inline bool vma_start_read_locked_nested (struct vm_area_struct *vma,int subclass) {
@@ -247,16 +251,23 @@ static inline bool vma_start_read_locked_nested(struct vm_area_struct *vma, int }/* -* Use only while holding mmap read lock which guarantees that locking will not -* fail (nobody can concurrently write-lock the vma). vma_start_read() should +* Use only while holding mmap read lock which guarantees that vma lock is not +* contended (nobody can concurrently write-lock the vma). vma_start_read() should * not be used in such cases because it might fail due to mm_lock_seq overflow. * This functionality is used to obtain vma read lock and drop the mmap read lock. +* +* VMA can't be detached while we are holding mmap lock, therefore in practice this +* function can fail only when there are so many readers that vm_refcnt overflows. +* The failure case is very unlikely and is already annotated as such internally. */ static inline bool vma_start_read_locked (struct vm_area_struct *vma) {return vma_start_read_locked_nested (vma,0 ); } +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address); +static inline void vma_end_read (struct vm_area_struct *vma) {vma_refcount_put (vma);
mm/mmap_lock.c +35 -0
@@ -338,6 +338,41 @@ struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm,return NULL ; } +/** +* vma_start_read_unlocked() - Find the VMA covering 'address' and read-lock it. +* @mm: the mm_struct of the address space to search +* @address: address that the vma should contain +* +* The fast path does not take mmap_lock. Waits for writers to finish if the +* VMA is being modified by taking mmap_lock. +* Use when mmap_lock is not held, otherwise use vma_start_read_locked(). +* Nothing prevents VMAs being unmapped/mapped before or after the VMA is +* looked up, if a stronger guarantee is required, take an mmap_lock. +* +* Return: If a VMA exists which spans @address, return that VMA, read-locked. +* If no VMA is mapped there or, very unlikely, a reference count overflow +* occurred, return NULL. +*/ +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address) +{ +struct vm_area_struct *vma; + +/* Fast path: return stable VMA covering 'address': */ + vma =lock_vma_under_rcu (mm, address); +if (vma) +return vma; + +/* Slow path: preclude VMA writers by temporarily getting mmap read lock. */ +mmap_read_lock (mm); + vma =vma_lookup (mm, address); +if (vma && !vma_start_read_locked (vma)) + vma =NULL ; +mmap_read_unlock (mm); + +return vma; +} +static struct vm_area_struct *lock_next_vma_under_mmap_lock (struct mm_struct *mm,struct vma_iterator *vmi,unsigned long from_addr)
mm/userfaultfd.c +4 -2
@@ -129,8 +129,10 @@ struct vm_area_struct *find_vma_and_prepare_anon(struct mm_struct *mm,* * Should be called without holding mmap_lock. * -* Return: A locked vma containing @address, -ENOENT if no vma is found, or -* -ENOMEM if anon_vma couldn't be allocated. +* Return: A locked vma containing @address, -ENOENT if no vma is found, +* -ENOMEM if anon_vma couldn't be allocated, or -EAGAIN if vma refcount +* overflow happened due to high number of readers and the caller should +* retry later. */ static struct vm_area_struct *uffd_lock_vma (struct mm_struct *mm,unsigned long address)
Signature · 1 line
2.55.0.654.g21b8a5bc05-goog
Re: [PATCH v4 3/5] mm: Add RCU-based VMA lookup helper that waits for writers
Quoted 58 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
== Background ==
There are basically two parallel ways to look up a VMA: the traditional way, which is protected by
mmap_read_lock, and the RCU-based per-VMA lock way which is based on RCU and refcounts.== Problem ==
The
mmap_lockone is more straightforward to use but it has a big disadvantage in that it can not be mixed with page faults since those can takemmap_lockfor read, which can deadlock when mixed with nested page faults and parallel writers.
For example:mmap_read_lock(mm); // Another thread does mmap_write_lock(). // New mmap_lock readers are blocked. vma = vma_lookup(mm, address); // This deadlocks on mmap_read_lock() if it faults: copy_from_user(address); mmap_read_unlock(mm);The per-VMA lock can be mixed with faults, but they can fail and need to be able to fall back to the traditional way.
== Solution ==
Add
vma_start_read_unlocked()- a variant of the RCU-based lookup that waits for writers. This is basically the same as the existing RCU-based lookup, but on a failure to lock it temporarily takesmmap_lockfor read and waits for writers to finish before locking the VMA, dropping themmap_lockand returning the locked VMA. This has some advantages:1. Callers do not need to have a fallback path for when they collide with writers.
2. It can be used in contexts where page faults can happen because it can take themmap_lockfor read but never *holds* it.
3. Its fast path does not require takingmmap_lockfor read.Basically, when applied correctly, this approach results in faster *and* simpler code.
While at it, fix the comments for
vma_start_read_locked(),vma_start_read_locked_nested(), anduffd_lock_vma().Suggested-by Lorenzo Stoakes (ARM) <[email protected]>Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>Cc Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Lorenzo Stoakes <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>
Quoted 8 lines
Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>
Re: [PATCH v4 3/5] mm: Add RCU-based VMA lookup helper that waits for writers
In reply to Suren BaghdasaryanQuoted 35 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
== Background ==
There are basically two parallel ways to look up a VMA: the traditional way, which is protected by
mmap_read_lock, and the RCU-based per-VMA lock way which is based on RCU and refcounts.== Problem ==
The
mmap_lockone is more straightforward to use but it has a big disadvantage in that it can not be mixed with page faults since those can takemmap_lockfor read, which can deadlock when mixed with nested page faults and parallel writers.
For example:mmap_read_lock(mm); // Another thread does mmap_write_lock(). // New mmap_lock readers are blocked. vma = vma_lookup(mm, address); // This deadlocks on mmap_read_lock() if it faults: copy_from_user(address); mmap_read_unlock(mm);The per-VMA lock can be mixed with faults, but they can fail and need to be able to fall back to the traditional way.
== Solution ==
Add
vma_start_read_unlocked()- a variant of the RCU-based lookup that waits for writers. This is basically the same as the existing RCU-based lookup, but on a failure to lock it temporarily takesmmap_lockfor read and waits for writers to finish before locking the VMA, dropping themmap_lockand returning the locked VMA. This has some advantages:
Quoted 8 lines
1. Callers do not need to have a fallback path for when they collide with writers.
2. It can be used in contexts where page faults can happen because it can take themmap_lockfor read but never *holds* it.
3. Its fast path does not require takingmmap_lockfor read.Basically, when applied correctly, this approach results in faster *and* simpler code.
Maybe just write a new commit message, because while this is a useful primitive to have, (as evidenced by patch 5) it doesn't do what this commit message claims.
Re: [PATCH v4 3/5] mm: Add RCU-based VMA lookup helper that waits for writers
In reply to Suren BaghdasaryanQuoted 3 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
== Background ==
I think we can do without the headings?
Quoted 20 lines
There are basically two parallel ways to look up a VMA: the traditional way, which is protected by
mmap_read_lock, and the RCU-based per-VMA lock way which is based on RCU and refcounts.== Problem ==
The
mmap_lockone is more straightforward to use but it has a big disadvantage in that it can not be mixed with page faults since those can takemmap_lockfor read, which can deadlock when mixed with nested page faults and parallel writers.
For example:mmap_read_lock(mm); // Another thread does mmap_write_lock(). // New mmap_lock readers are blocked. vma = vma_lookup(mm, address); // This deadlocks on mmap_read_lock() if it faults: copy_from_user(address); mmap_read_unlock(mm);
Quoted 2 lines
The per-VMA lock can be mixed with faults, but they can fail and need to be able to fall back to the traditional way.
Umm. I don't see how this avoids deadlock. Assuming the next patch converts copy_from_user() to use the VMA lock, surely the following situation would obtain:
A takes mmap_read_lock
B tries to take mmap_write_lock, blocks
A calls copy_from_user()
A calls vma_start_read_unlocked() (because it doesn't know A actually holds the mmap_read_lock() already)
A does a lookup under RCU, but gets NULL back (maybe it's calling c_f_u() with an invalid address?)
A tries to take the mmap_read_lock again to make sure. Deadlock because B is waiting for A to release the mmap_read_lock.
Am I missing something?
Quoted 34 lines
mm/mmap_lock.c +34
-0+/** +* vma_start_read_unlocked() - Find the VMA covering 'address' and read-lock it. +* @mm: the mm_struct of the address space to search +* @address: address that the vma should contain +* +* The fast path does not take mmap_lock. Waits for writers to finish if the +* VMA is being modified by taking mmap_lock. +* Use when mmap_lock is not held, otherwise use vma_start_read_locked(). +* Nothing prevents VMAs being unmapped/mapped before or after the VMA is +* looked up, if a stronger guarantee is required, take an mmap_lock. +* +* Return: If a VMA exists which spans @address, return that VMA, read-locked. +* If no VMA is mapped there or, very unlikely, a reference count overflow +* occurred, return NULL. +*/ +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address) +{ +struct vm_area_struct *vma; + +/* Fast path: return stable VMA covering 'address': */ + vma =lock_vma_under_rcu (mm, address); +if (vma) +return vma; + +/* Slow path: preclude VMA writers by temporarily getting mmap read lock. */ +mmap_read_lock (mm); + vma =vma_lookup (mm, address); +if (vma && !vma_start_read_locked (vma)) + vma =NULL ; +mmap_read_unlock (mm); + +return vma; +}
Suren Baghdasaryan
maintainerRe: [PATCH v4 3/5] mm: Add RCU-based VMA lookup helper that waits for writers
Quoted 45 lines · Matthew Wilcox
Quoted 3 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
== Background ==
I think we can do without the headings?
Quoted 20 lines
There are basically two parallel ways to look up a VMA: the traditional way, which is protected by
mmap_read_lock, and the RCU-based per-VMA lock way which is based on RCU and refcounts.== Problem ==
The
mmap_lockone is more straightforward to use but it has a big disadvantage in that it can not be mixed with page faults since those can takemmap_lockfor read, which can deadlock when mixed with nested page faults and parallel writers.
For example:mmap_read_lock(mm); // Another thread does mmap_write_lock(). // New mmap_lock readers are blocked. vma = vma_lookup(mm, address); // This deadlocks on mmap_read_lock() if it faults: copy_from_user(address); mmap_read_unlock(mm);Quoted 2 lines
The per-VMA lock can be mixed with faults, but they can fail and need to be able to fall back to the traditional way.
Umm. I don't see how this avoids deadlock. Assuming the next patch converts
copy_from_user()to use the VMA lock, surely the following situation would obtain:A takes
mmap_read_lock
B tries to takemmap_write_lock, blocks
A callscopy_from_user()
A callsvma_start_read_unlocked()(because it doesn't know A actually holds themmap_read_lock()already)
A does a lookup under RCU, but gets NULL back (maybe it's callingc_f_u()with an invalid address?)
A tries to take themmap_read_lockagain to make sure. Deadlock because B is waiting for A to release themmap_read_lock.
Quoted 1 line
Am I missing something?
I think Dave's idea was that A would take a VMA lock (which might require taking mmap read lock temporarily) and then call copy_from_user() with VMA lock only, which allows copy_from_user() to take the mmap lock. This was used in the last patch [1] of the original RFC. That patch is dropped from the series because this approach has a conceptual lock ordering problem - it takes VMA lock and then mmap_lock (see explanation at [2]).
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/CAJuCfpHBzYUNEe_LBpeERf68_fso=Hy+UZWtqejTUkm1O4NLfA@mail.gmail.com/
So, yeah. I need to rewrite this commit message.
Quoted 35 lines
Quoted 35 lines
mm/mmap_lock.c +34
-0+/** +* vma_start_read_unlocked() - Find the VMA covering 'address' and read-lock it. +* @mm: the mm_struct of the address space to search +* @address: address that the vma should contain +* +* The fast path does not take mmap_lock. Waits for writers to finish if the +* VMA is being modified by taking mmap_lock. +* Use when mmap_lock is not held, otherwise use vma_start_read_locked(). +* Nothing prevents VMAs being unmapped/mapped before or after the VMA is +* looked up, if a stronger guarantee is required, take an mmap_lock. +* +* Return: If a VMA exists which spans @address, return that VMA, read-locked. +* If no VMA is mapped there or, very unlikely, a reference count overflow +* occurred, return NULL. +*/ +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address) +{ +struct vm_area_struct *vma; + +/* Fast path: return stable VMA covering 'address': */ + vma =lock_vma_under_rcu (mm, address); +if (vma) +return vma; + +/* Slow path: preclude VMA writers by temporarily getting mmap read lock. */ +mmap_read_lock (mm); + vma =vma_lookup (mm, address); +if (vma && !vma_start_read_locked (vma)) + vma =NULL ; +mmap_read_unlock (mm); + +return vma; +}
Lorenzo Stoakes (ARM)
maintainerRe: [PATCH v4 3/5] mm: Add RCU-based VMA lookup helper that waits for writers
Quoted 48 lines · Suren Baghdasaryan
Quoted 45 lines · Matthew Wilcox
Quoted 3 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
== Background ==
I think we can do without the headings?
Quoted 20 lines
There are basically two parallel ways to look up a VMA: the traditional way, which is protected by
mmap_read_lock, and the RCU-based per-VMA lock way which is based on RCU and refcounts.== Problem ==
The
mmap_lockone is more straightforward to use but it has a big disadvantage in that it can not be mixed with page faults since those can takemmap_lockfor read, which can deadlock when mixed with nested page faults and parallel writers.
For example:mmap_read_lock(mm); // Another thread does mmap_write_lock(). // New mmap_lock readers are blocked. vma = vma_lookup(mm, address); // This deadlocks on mmap_read_lock() if it faults: copy_from_user(address); mmap_read_unlock(mm);Quoted 2 lines
The per-VMA lock can be mixed with faults, but they can fail and need to be able to fall back to the traditional way.
Umm. I don't see how this avoids deadlock. Assuming the next patch converts
copy_from_user()to use the VMA lock, surely the following situation would obtain:A takes
mmap_read_lock
B tries to takemmap_write_lock, blocks
A callscopy_from_user()
A callsvma_start_read_unlocked()(because it doesn't know A actually holds themmap_read_lock()already)
A does a lookup under RCU, but gets NULL back (maybe it's callingc_f_u()with an invalid address?)
A tries to take themmap_read_lockagain to make sure. Deadlock because B is waiting for A to release themmap_read_lock.Quoted 1 line
Am I missing something?
Quoted 7 lines
I think Dave's idea was that A would take a VMA lock (which might require taking mmap read lock temporarily) and then call
copy_from_user()with VMA lock only, which allowscopy_from_user()to take the mmap lock. This was used in the last patch [1] of the original RFC. That patch is dropped from the series because this approach has a conceptual lock ordering problem - it takes VMA lock and thenmmap_lock(see explanation at [2]).
Yeah I wonder about the value of this. Dave can write all this up when he makes the change to use this in the relevant shadow stack (I think it was?) code.
Having it here when just adding the function is not really helpful I don't think.
Other use cases are stronger arguments for it anyway - we are essentially doing stuff like this in places and falling back to mmap when we don't need to - when we have the option to 'twiddle' the mmap lock and get a VMA lock.
Quoted 33 lines
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/CAJuCfpHBzYUNEe_LBpeERf68_fso=Hy+UZWtqejTUkm1O4NLfA@mail.gmail.com/So, yeah. I need to rewrite this commit message.
Quoted 27 lines
Quoted 27 lines
mm/mmap_lock.c +26
-0+/** +* vma_start_read_unlocked() - Find the VMA covering 'address' and read-lock it. +* @mm: the mm_struct of the address space to search +* @address: address that the vma should contain +* +* The fast path does not take mmap_lock. Waits for writers to finish if the +* VMA is being modified by taking mmap_lock. +* Use when mmap_lock is not held, otherwise use vma_start_read_locked(). +* Nothing prevents VMAs being unmapped/mapped before or after the VMA is +* looked up, if a stronger guarantee is required, take an mmap_lock. +* +* Return: If a VMA exists which spans @address, return that VMA, read-locked. +* If no VMA is mapped there or, very unlikely, a reference count overflow +* occurred, return NULL. +*/ +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address) +{ +struct vm_area_struct *vma; + +/* Fast path: return stable VMA covering 'address': */ + vma =lock_vma_under_rcu (mm, address); +if (vma) +return vma; + +/* Slow path: preclude VMA writers by temporarily getting mmap read lock. */
Quoted 8 lines
Quoted 8 lines
mm/mmap_lock.c struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm, · line 374
Quoted 8 lines
mm/mmap_lock.c +8
-0+mmap_read_lock (mm); + vma =vma_lookup (mm, address); +if (vma && !vma_start_read_locked (vma)) + vma =NULL ; +mmap_read_unlock (mm); + +return vma; +}
--
Cheers, Lorenzo
Re: [PATCH v4 3/5] mm: Add RCU-based VMA lookup helper that waits for writers
Quoted 4 lines · Lorenzo Stoakes (ARM)
Yeah I wonder about the value of this. Dave can write all this up when he makes the change to use this in the relevant shadow stack (I think it was?) code.
Having it here when just adding the function is not really helpful I don't think.
Yeah, all the analysis and chit chat needs to get moved to the place where it is used (if it's even possible), not here.
Re: [PATCH v4 3/5] mm: Add RCU-based VMA lookup helper that waits for writers
In reply to Suren BaghdasaryanQuoted 24 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
== Background ==
There are basically two parallel ways to look up a VMA: the traditional way, which is protected by
mmap_read_lock, and the RCU-based per-VMA lock way which is based on RCU and refcounts.== Problem ==
The
mmap_lockone is more straightforward to use but it has a big disadvantage in that it can not be mixed with page faults since those can takemmap_lockfor read, which can deadlock when mixed with nested page faults and parallel writers.
For example:mmap_read_lock(mm); // Another thread does mmap_write_lock(). // New mmap_lock readers are blocked. vma = vma_lookup(mm, address); // This deadlocks on mmap_read_lock() if it faults: copy_from_user(address); mmap_read_unlock(mm);
Quoted 2 lines
The per-VMA lock can be mixed with faults, but they can fail and need to be able to fall back to the traditional way.
As discussed in reply to Matthew, this isn't so useful to have here I don't think.
Quoted 8 lines
== Solution ==
Add
vma_start_read_unlocked()- a variant of the RCU-based lookup that waits for writers. This is basically the same as the existing RCU-based lookup, but on a failure to lock it temporarily takesmmap_lockfor read and waits for writers to finish before locking the VMA, dropping themmap_lockand returning the locked VMA. This has some advantages:
Nitty but maybe reads better as something like:
..., on failing to acquire the VMA lock it waits for writers to finish by temporarily acquiring the mmap read lock and taking the VMA lock with it held via vma_start_read_locked() before dropping it again.
Quoted 9 lines
1. Callers do not need to have a fallback path for when they collide with writers.
2. It can be used in contexts where page faults can happen because it can take themmap_lockfor read but never *holds* it.
3. Its fast path does not require takingmmap_lockfor read.Basically, when applied correctly, this approach results in faster *and* simpler code.
I think this suffices as justification for the function with the above deadlock scenario simply excised.
Quoted 5 lines
While at it, fix the comments for
vma_start_read_locked(),vma_start_read_locked_nested(), anduffd_lock_vma().Suggested-by Lorenzo Stoakes (ARM) <[email protected]>
Thanks :>)
Quoted 2 lines
Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>
LGTM, so with the changes to commit message applied feel free to add:
Quoted 77 lines
Cc Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Lorenzo Stoakes <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- include/linux/mmap_lock.h | 19 +++++++++++++++---- mm/mmap_lock.c | 35 +++++++++++++++++++++++++++++++++++ mm/userfaultfd.c | 6 ++++-- 3 files changed, 54 insertions(+), 6 deletions(-)include/linux/mmap_lock.h +15
-4@@ -228,10 +228,14 @@ static inline void vma_refcount_put(struct vm_area_struct *vma) }/* -* Use only while holding mmap read lock which guarantees that locking will not -* fail (nobody can concurrently write-lock the vma). vma_start_read() should +* Use only while holding mmap read lock which guarantees that vma lock is not +* contended (nobody can concurrently write-lock the vma). vma_start_read() should * not be used in such cases because it might fail due to mm_lock_seq overflow. * This functionality is used to obtain vma read lock and drop the mmap read lock. +* +* VMA can't be detached while we are holding mmap lock, therefore in practice this +* function can fail only when there are so many readers that vm_refcnt overflows. +* The failure case is very unlikely and is already annotated as such internally. */ static inline bool vma_start_read_locked_nested (struct vm_area_struct *vma,int subclass) {@@ -247,16 +251,23 @@ static inline bool vma_start_read_locked_nested(struct vm_area_struct *vma, int }/* -* Use only while holding mmap read lock which guarantees that locking will not -* fail (nobody can concurrently write-lock the vma). vma_start_read() should +* Use only while holding mmap read lock which guarantees that vma lock is not +* contended (nobody can concurrently write-lock the vma). vma_start_read() should * not be used in such cases because it might fail due to mm_lock_seq overflow. * This functionality is used to obtain vma read lock and drop the mmap read lock. +* +* VMA can't be detached while we are holding mmap lock, therefore in practice this +* function can fail only when there are so many readers that vm_refcnt overflows. +* The failure case is very unlikely and is already annotated as such internally. */ static inline bool vma_start_read_locked (struct vm_area_struct *vma) {return vma_start_read_locked_nested (vma,0 ); } +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address); +static inline void vma_end_read (struct vm_area_struct *vma) {vma_refcount_put (vma);mm/mmap_lock.c +0
-0@@ -338,6 +338,41 @@ struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm,return NULL ; }
mm/mmap_lock.c struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm, · line 350
Quoted 10 lines
mm/mmap_lock.c +10
-0+/** +* vma_start_read_unlocked() - Find the VMA covering 'address' and read-lock it. +* @mm: the mm_struct of the address space to search +* @address: address that the vma should contain +* +* The fast path does not take mmap_lock. Waits for writers to finish if the +* VMA is being modified by taking mmap_lock. +* Use when mmap_lock is not held, otherwise use vma_start_read_locked(). +* Nothing prevents VMAs being unmapped/mapped before or after the VMA is +* looked up, if a stronger guarantee is required, take an mmap_lock.
Great thanks!
Quoted 46 lines
mm/mmap_lock.c +25
-0+* +* Return: If a VMA exists which spans @address, return that VMA, read-locked. +* If no VMA is mapped there or, very unlikely, a reference count overflow +* occurred, return NULL. +*/ +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address) +{ +struct vm_area_struct *vma; + +/* Fast path: return stable VMA covering 'address': */ + vma =lock_vma_under_rcu (mm, address); +if (vma) +return vma; + +/* Slow path: preclude VMA writers by temporarily getting mmap read lock. */ +mmap_read_lock (mm); + vma =vma_lookup (mm, address); +if (vma && !vma_start_read_locked (vma)) + vma =NULL ; +mmap_read_unlock (mm); + +return vma; +} +static struct vm_area_struct *lock_next_vma_under_mmap_lock (struct mm_struct *mm,struct vma_iterator *vmi,unsigned long from_addr)mm/userfaultfd.c +4
-3@@ -129,8 +129,10 @@ struct vm_area_struct *find_vma_and_prepare_anon(struct mm_struct *mm,* * Should be called without holding mmap_lock. * -* Return: A locked vma containing @address, -ENOENT if no vma is found, or -* -ENOMEM if anon_vma couldn't be allocated. +* Return: A locked vma containing @address, -ENOENT if no vma is found, +* -ENOMEM if anon_vma couldn't be allocated, or -EAGAIN if vma refcount +* overflow happened due to high number of readers and the caller should +* retry later. */ static struct vm_area_struct *uffd_lock_vma (struct mm_struct *mm,unsigned long address) --
Quoted 2 lines
2.55.0.654.g21b8a5bc05-goog
--
Cheers, Lorenzo
Suren Baghdasaryan
maintainerRe: [PATCH v4 3/5] mm: Add RCU-based VMA lookup helper that waits for writers
Quoted 26 lines · Lorenzo Stoakes (ARM)
Quoted 24 lines · Suren Baghdasaryan
From: Dave Hansen <[email protected]>
== Background ==
There are basically two parallel ways to look up a VMA: the traditional way, which is protected by
mmap_read_lock, and the RCU-based per-VMA lock way which is based on RCU and refcounts.== Problem ==
The
mmap_lockone is more straightforward to use but it has a big disadvantage in that it can not be mixed with page faults since those can takemmap_lockfor read, which can deadlock when mixed with nested page faults and parallel writers.
For example:mmap_read_lock(mm); // Another thread does mmap_write_lock(). // New mmap_lock readers are blocked. vma = vma_lookup(mm, address); // This deadlocks on mmap_read_lock() if it faults: copy_from_user(address); mmap_read_unlock(mm);
Quoted 5 lines
Quoted 2 lines
The per-VMA lock can be mixed with faults, but they can fail and need to be able to fall back to the traditional way.
As discussed in reply to Matthew, this isn't so useful to have here I don't think.
Ack.
Quoted 10 lines
Quoted 9 lines
== Solution ==
Add
vma_start_read_unlocked()- a variant of the RCU-based lookup that waits for writers. This is basically the same as the existing RCU-based lookup, but on a failure to lock it temporarily takesmmap_lockfor read and waits for writers to finish before locking the VMA, dropping themmap_lockand returning the locked VMA. This has some advantages:
Quoted 6 lines
Nitty but maybe reads better as something like:
..., on failing to acquire the VMA lock it waits for writers to finish by temporarily acquiring the mmap read lock and taking the VMA lock with it held via
vma_start_read_locked()before dropping it again.
Sounds good. Will adopt your version/
Quoted 8 lines
Quoted 8 lines
1. Callers do not need to have a fallback path for when they collide with writers.
2. It can be used in contexts where page faults can happen because it can take themmap_lockfor read but never *holds* it.
3. Its fast path does not require takingmmap_lockfor read.
Quoted 5 lines
Quoted 2 lines
Basically, when applied correctly, this approach results in faster *and* simpler code.
I think this suffices as justification for the function with the above deadlock scenario simply excised.
Ack.
Quoted 7 lines
Quoted 6 lines
While at it, fix the comments for
vma_start_read_locked(),vma_start_read_locked_nested(), anduffd_lock_vma().Suggested-by Lorenzo Stoakes (ARM) <[email protected]>
Quoted 8 lines
Thanks :>)
Quoted 2 lines
Signed-off-by Dave Hansen <[email protected]>Signed-off-by Suren Baghdasaryan <[email protected]>LGTM, so with the changes to commit message applied feel free to add:
Reviewed-by Lorenzo Stoakes (ARM) <[email protected]>
Thanks!
Quoted 142 lines
Quoted 78 lines
Cc Suren Baghdasaryan <[email protected]>Cc Andrew Morton <[email protected]>Cc "Liam R. Howlett" <[email protected]>Cc Lorenzo Stoakes <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Shakeel Butt <[email protected]>Cc Greg Kroah-Hartman <[email protected]>Cc Arve Hjønnevåg <[email protected]>Cc Todd Kjos <[email protected]>Cc Christian Brauner <[email protected]>Cc Carlos Llamas <[email protected]>Cc Alice Ryhl <[email protected]>Cc "David S. Miller" <[email protected]>Cc David Ahern <[email protected]>--- include/linux/mmap_lock.h | 19 +++++++++++++++---- mm/mmap_lock.c | 35 +++++++++++++++++++++++++++++++++++ mm/userfaultfd.c | 6 ++++-- 3 files changed, 54 insertions(+), 6 deletions(-)include/linux/mmap_lock.h +15
-4@@ -228,10 +228,14 @@ static inline void vma_refcount_put(struct vm_area_struct *vma) }/* -* Use only while holding mmap read lock which guarantees that locking will not -* fail (nobody can concurrently write-lock the vma). vma_start_read() should +* Use only while holding mmap read lock which guarantees that vma lock is not +* contended (nobody can concurrently write-lock the vma). vma_start_read() should * not be used in such cases because it might fail due to mm_lock_seq overflow. * This functionality is used to obtain vma read lock and drop the mmap read lock. +* +* VMA can't be detached while we are holding mmap lock, therefore in practice this +* function can fail only when there are so many readers that vm_refcnt overflows. +* The failure case is very unlikely and is already annotated as such internally. */ static inline bool vma_start_read_locked_nested (struct vm_area_struct *vma,int subclass) {@@ -247,16 +251,23 @@ static inline bool vma_start_read_locked_nested(struct vm_area_struct *vma, int }/* -* Use only while holding mmap read lock which guarantees that locking will not -* fail (nobody can concurrently write-lock the vma). vma_start_read() should +* Use only while holding mmap read lock which guarantees that vma lock is not +* contended (nobody can concurrently write-lock the vma). vma_start_read() should * not be used in such cases because it might fail due to mm_lock_seq overflow. * This functionality is used to obtain vma read lock and drop the mmap read lock. +* +* VMA can't be detached while we are holding mmap lock, therefore in practice this +* function can fail only when there are so many readers that vm_refcnt overflows. +* The failure case is very unlikely and is already annotated as such internally. */ static inline bool vma_start_read_locked (struct vm_area_struct *vma) {return vma_start_read_locked_nested (vma,0 ); } +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address); +static inline void vma_end_read (struct vm_area_struct *vma) {vma_refcount_put (vma);mm/mmap_lock.c +0
-0@@ -338,6 +338,41 @@ struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm,return NULL ; }mm/mmap_lock.c struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm, · line 350
Quoted 10 lines
mm/mmap_lock.c +10
-0+/** +* vma_start_read_unlocked() - Find the VMA covering 'address' and read-lock it. +* @mm: the mm_struct of the address space to search +* @address: address that the vma should contain +* +* The fast path does not take mmap_lock. Waits for writers to finish if the +* VMA is being modified by taking mmap_lock. +* Use when mmap_lock is not held, otherwise use vma_start_read_locked(). +* Nothing prevents VMAs being unmapped/mapped before or after the VMA is +* looked up, if a stronger guarantee is required, take an mmap_lock. Great thanks!
Quoted 46 lines
mm/mmap_lock.c +25
-0+* +* Return: If a VMA exists which spans @address, return that VMA, read-locked. +* If no VMA is mapped there or, very unlikely, a reference count overflow +* occurred, return NULL. +*/ +struct vm_area_struct *vma_start_read_unlocked (struct mm_struct *mm, +unsigned long address) +{ +struct vm_area_struct *vma; + +/* Fast path: return stable VMA covering 'address': */ + vma =lock_vma_under_rcu (mm, address); +if (vma) +return vma; + +/* Slow path: preclude VMA writers by temporarily getting mmap read lock. */ +mmap_read_lock (mm); + vma =vma_lookup (mm, address); +if (vma && !vma_start_read_locked (vma)) + vma =NULL ; +mmap_read_unlock (mm); + +return vma; +} +static struct vm_area_struct *lock_next_vma_under_mmap_lock (struct mm_struct *mm,struct vma_iterator *vmi,unsigned long from_addr)mm/userfaultfd.c +4
-3@@ -129,8 +129,10 @@ struct vm_area_struct *find_vma_and_prepare_anon(struct mm_struct *mm,* * Should be called without holding mmap_lock. * -* Return: A locked vma containing @address, -ENOENT if no vma is found, or -* -ENOMEM if anon_vma couldn't be allocated. +* Return: A locked vma containing @address, -ENOENT if no vma is found, +* -ENOMEM if anon_vma couldn't be allocated, or -EAGAIN if vma refcount +* overflow happened due to high number of readers and the caller should +* retry later. */ static struct vm_area_struct *uffd_lock_vma (struct mm_struct *mm,unsigned long address) --Quoted 2 lines
2.55.0.654.g21b8a5bc05-goog
--
Cheers, Lorenzo
Suren Baghdasaryan
maintainerPATCH v4 4/5 binder: Remove mmap_lock fallback
In reply to Suren BaghdasaryanFrom: Dave Hansen <[email protected]>
Previously, the per-VMA locking could fail in the face of writers which necessitate a fallback to mmap_lock. The new vma_start_read_unlocked() will wait for writers instead of failing.
Use the new helper. Wait for writers. Remove the fallback to mmap_lock.
--- drivers/android/binder/page_range.rs | 19 +++---------------- drivers/android/binder_alloc.c | 17 +++++------------ rust/kernel/mm.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 28 deletions(-)
drivers/android/binder/page_range.rs +3 -16
@@ -439,22 +439,9 @@ unsafe fn use_page_slow(&self, i: usize) -> Result<()> {// workqueue. let mm =MmWithUser ::into_mmput_async (self.mm.mmget_not_zero ().ok_or (ESRCH )?); { -let vma_read; -let mmap_read; -let vma =if let Some (ret) = mm.lock_vma_under_rcu (vma_addr) { - vma_read = ret; -check_vma (&vma_read, self) - }else { - mmap_read = mm.mmap_read_lock (); - mmap_read - .vma_lookup (vma_addr) - .and_then (|vma|check_vma (vma, self)) - }; - -match vma { -Some (vma) => vma.vm_insert_page (user_page_addr, &new_page)?, -None =>return Err (ESRCH ), - } +let vma_read_guard = mm.vma_start_read_unlocked (vma_addr).ok_or (ESRCH )?; +let vma =check_vma (&vma_read_guard, self).ok_or (ESRCH )?; + vma.vm_insert_page (user_page_addr, &new_page)?; }let inner = self.lock.lock ();
drivers/android/binder_alloc.c +5 -12
@@ -259,21 +259,14 @@ static int binder_page_insert(struct binder_alloc *alloc,struct vm_area_struct *vma;int ret = -ESRCH ; -/* attempt per-vma lock first */ - vma =lock_vma_under_rcu (mm, addr); -if (vma) { -if (binder_alloc_is_mapped (alloc)) - ret =vm_insert_page (vma, addr, page); -vma_end_read (vma); + vma =vma_start_read_unlocked (mm, addr); +if (!vma)return ret; - } -/* fall back to mmap_lock */ -mmap_read_lock (mm); - vma =vma_lookup (mm, addr); -if (vma &&binder_alloc_is_mapped (alloc)) +if (binder_alloc_is_mapped (alloc)) ret =vm_insert_page (vma, addr, page); -mmap_read_unlock (mm); + +vma_end_read (vma);return ret; }
rust/kernel/mm.rs +27 -0
@@ -186,6 +186,33 @@ pub fn lock_vma_under_rcu(&self, vma_addr: usize) -> Option<VmaReadGuard<'_>> { }) } +/// Find the VMA covering 'address' and read-lock it. +/// +/// The fast path does not take mmap_lock. Waits for writers to finish if the +/// VMA is being modified by taking mmap_lock. +/// Use when mmap_lock is not held, otherwise use vma_start_read_locked(). +/// Nothing prevents VMAs being unmapped/mapped before or after the VMA is +/// looked up, if a stronger guarantee is required, take an mmap_lock. +/// +/// Return: If a VMA exists which spans @address, return that VMA, read-locked. +/// If no VMA is mapped there or, very unlikely, a reference count overflow +/// occurred, return NULL. +#[inline] +pub fn vma_start_read_unlocked (&self, vma_addr:usize ) ->Option <VmaReadGuard <'_>> { +// SAFETY: We may invoke `vma_start_read_unlocked` because we know this `mm` has non-zero +// `mm_users`. +let vma =unsafe { bindings::vma_start_read_unlocked (self.as_raw (), vma_addr) }; +if vma.is_null () { +return None ; + } +Some (VmaReadGuard { +// SAFETY: If `vma_start_read_unlocked` returns a non-null ptr, then it points at a +// valid vma. The vma is stable for as long as the vma read lock is held. + vma:unsafe {VmaRef ::from_raw (vma) }, + _nts:NotThreadSafe , + }) + } +/// Lock the mmap read lock. #[inline] pub fn mmap_read_lock (&self) ->MmapReadGuard <'_> {
Signature · 1 line
2.55.0.654.g21b8a5bc05-goog
Suren Baghdasaryan
maintainerPATCH v4 5/5 tcp: Remove mmap_lock fallback path
In reply to Suren BaghdasaryanFrom: Dave Hansen <[email protected]>
Previously, the per-VMA locking could fail in the face of writers which necessitates a fallback to mmap_lock. The new lock_vma_under_rcu_wait() will wait for writers instead of failing.
Use the new helper. Wait for writers. Remove the fallback to mmap_lock. The fallback removal does not affect NOMMU case because TCP_ZEROCOPY is gated on CONFIG_MMU.
This really is a nice cleanup. It removes the need to pass the lock state back and forth to find_tcp_vma().
--- net/ipv4/tcp.c | 31 +++++++++---------------------- 1 file changed, 9 insertions(+), 22 deletions(-)
net/ipv4/tcp.c +9 -22
@@ -2167,27 +2167,18 @@ static void tcp_zc_finalize_rx_tstamp(struct sock *sk, }static struct vm_area_struct *find_tcp_vma (struct mm_struct *mm, -unsigned long address, -bool *mmap_locked) +unsigned long address) { -struct vm_area_struct *vma =lock_vma_under_rcu (mm, address); +struct vm_area_struct *vma =vma_start_read_unlocked (mm, address); -if (vma) { -if (vma->vm_ops != &tcp_vm_ops) { -vma_end_read (vma); -return NULL ; - } - *mmap_locked = false; -return vma; - } +if (!vma) +return NULL ; -mmap_read_lock (mm); - vma =vma_lookup (mm, address); -if (!vma || vma->vm_ops != &tcp_vm_ops) { -mmap_read_unlock (mm); +if (vma->vm_ops != &tcp_vm_ops) { +vma_end_read (vma);return NULL ; } - *mmap_locked = true; +return vma; }
@@ -2208,7 +2199,6 @@ static int tcp_zerocopy_receive(struct sock *sk,u32 seq = tp->copied_seq;u32 total_bytes_to_map;int inq =tcp_inq (sk); -bool mmap_locked;int ret; zc->copybuf_len =0 ;
@@ -2233,7 +2223,7 @@ static int tcp_zerocopy_receive(struct sock *sk,return 0 ; } - vma =find_tcp_vma (current->mm, address, &mmap_locked); + vma =find_tcp_vma (current->mm, address);if (!vma)return -EINVAL ;
@@ -2315,10 +2305,7 @@ static int tcp_zerocopy_receive(struct sock *sk, zc, total_bytes_to_map); } out: -if (mmap_locked) -mmap_read_unlock (current->mm); -else -vma_end_read (vma); +vma_end_read (vma);/* Try to copy straggler data. */ if (!ret) copylen =tcp_zc_handle_leftover (zc, sk, skb, &seq, copybuf_len, tss);
Signature · 1 line
2.55.0.654.g21b8a5bc05-goog
Re: [PATCH v4 5/5] tcp: Remove mmap_lock fallback path
Quoted 3 lines · Suren Baghdasaryan
Previously, the per-VMA locking could fail in the face of writers which necessitates a fallback to
mmap_lock. The newlock_vma_under_rcu_wait()will wait for writers instead of failing.
It's not called that any more ...
Suren Baghdasaryan
maintainerRe: [PATCH v4 5/5] tcp: Remove mmap_lock fallback path
Quoted 7 lines · Matthew Wilcox
Quoted 3 lines · Suren Baghdasaryan
Previously, the per-VMA locking could fail in the face of writers which necessitates a fallback to
mmap_lock. The newlock_vma_under_rcu_wait()will wait for writers instead of failing.It's not called that any more ...
Ack. Will fix. It's obvious that I took over someone else's patch, isn't it? :)
Quoted 1 line
Re: [PATCH v4 5/5] tcp: Remove mmap_lock fallback path
Quoted 1 line · Suren Baghdasaryan
Ack. Will fix. It's obvious that I took over someone else's patch, isn't it? 🙂
BTW, Suren, thanks again for taking over the series!
Suren Baghdasaryan
maintainerRe: [PATCH v4 5/5] tcp: Remove mmap_lock fallback path
Quoted 5 lines · Dave Hansen
Quoted 1 line · Suren Baghdasaryan
Ack. Will fix. It's obvious that I took over someone else's patch, isn't it? 🙂
BTW, Suren, thanks again for taking over the series!
My pleasure! Thanks for starting this cleanup!