Skip to contentSkip to conversation

mm: continue using per-VMA lock when retrying page faults after I/O

RFC PATCH In review Barry Song 7 participants 17 messages Nov 27, 2025 – Apr 4

Subsystems (13)
lore
Share & tools
lore

Barry Song

author
#0 lore raw

cover mm: continue using per-VMA lock when retrying page faults after I/O

From: Barry Song <[email protected]>

Oven observed most mmap_lock contention and priority inversion come from page fault retries after waiting for I/O completion. Oven subsequently raised the following idea:

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

In this case, the retry path can continue using the per-VMA lock. This is a big win: it greatly reduces mmap_lock acquisitions.

Oven Liyang (1):
mm/filemap: Retry fault by VMA lock if the lock was released for I/O

Barry Song (1):
mm/swapin: Retry swapin by VMA lock if the lock was released for I/O

 arch/arm/mm/fault.c       |  5 +++++
 arch/arm64/mm/fault.c     |  5 +++++
 arch/loongarch/mm/fault.c |  4 ++++
 arch/powerpc/mm/fault.c   |  5 ++++-
 arch/riscv/mm/fault.c     |  4 ++++
 arch/s390/mm/fault.c      |  4 ++++
 arch/x86/mm/fault.c       |  4 ++++
 include/linux/mm_types.h  |  9 +++++----
 mm/filemap.c              |  5 ++++-
 mm/memory.c               | 10 ++++++++--
 10 files changed, 47 insertions(+), 8 deletions(-)
Cc Russell King <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Will Deacon <[email protected]>
Cc Huacai Chen <[email protected]>
Cc WANG Xuerui <[email protected]>
Cc Madhavan Srinivasan <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc Christophe Leroy <[email protected]>
Cc Paul Walmsley <[email protected]>
Cc Palmer Dabbelt <[email protected]>
Cc Albert Ou <[email protected]>
Cc Alexandre Ghiti <[email protected]>
Cc Alexander Gordeev <[email protected]>
Cc Gerald Schaefer <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Vasily Gorbik <[email protected]>
Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Borislav Petkov <[email protected]>
Cc H. Peter Anvin <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Kuninori Morimoto <[email protected]>
Cc Oven Liyang <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Ada Couprie Diaz <[email protected]>
Cc Robin Murphy <[email protected]>
Cc Kristina Martšenko <[email protected]>
Cc Kevin Brodsky <[email protected]>
Cc Yeoreum Yun <[email protected]>
Cc Wentao Guan <[email protected]>
Cc Thorsten Blum <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Yunhui Cui <[email protected]>
Cc Nam Cao <[email protected]>
Cc Chris Li <[email protected]>
Cc Kairui Song <[email protected]>
Cc Kemeng Shi <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Baoquan He <[email protected]>
Signature · 1 line
2.39.3 (Apple Git-146)
author
#1 lore raw

RFC PATCH 1/2 mm/filemap: Retry fault by VMA lock if the lock was released for I/O

From: Oven Liyang <[email protected]>

If the current page fault is using the per-VMA lock, and we only released the lock to wait for I/O completion (e.g., using folio_lock()), then when the fault is retried after the I/O completes, it should still qualify for the per-VMA-lock path.

Cc Russell King <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Will Deacon <[email protected]>
Cc Huacai Chen <[email protected]>
Cc WANG Xuerui <[email protected]>
Cc Madhavan Srinivasan <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc Christophe Leroy <[email protected]>
Cc Paul Walmsley <[email protected]>
Cc Palmer Dabbelt <[email protected]>
Cc Albert Ou <[email protected]>
Cc Alexandre Ghiti <[email protected]>
Cc Alexander Gordeev <[email protected]>
Cc Gerald Schaefer <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Vasily Gorbik <[email protected]>
Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Borislav Petkov <[email protected]>
Cc H. Peter Anvin <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Kuninori Morimoto <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Ada Couprie Diaz <[email protected]>
Cc Robin Murphy <[email protected]>
Cc Kristina Martšenko <[email protected]>
Cc Kevin Brodsky <[email protected]>
Cc Yeoreum Yun <[email protected]>
Cc Wentao Guan <[email protected]>
Cc Thorsten Blum <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Yunhui Cui <[email protected]>
Cc Nam Cao <[email protected]>
Cc Chris Li <[email protected]>
Cc Kairui Song <[email protected]>
Cc Kemeng Shi <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Baoquan He <[email protected]>
---
 arch/arm/mm/fault.c       | 5 +++++
 arch/arm64/mm/fault.c     | 5 +++++
 arch/loongarch/mm/fault.c | 4 ++++
 arch/powerpc/mm/fault.c   | 5 ++++-
 arch/riscv/mm/fault.c     | 4 ++++
 arch/s390/mm/fault.c      | 4 ++++
 arch/x86/mm/fault.c       | 4 ++++
 include/linux/mm_types.h  | 9 +++++----
 mm/filemap.c              | 5 ++++-
 9 files changed, 39 insertions(+), 6 deletions(-)
arch/arm/mm/fault.c +5 -0
index 2bc828a1940c..49fc0340821c 100644
@@ -313,6 +313,7 @@ do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
 	if (!(flags & FAULT_FLAG_USER))
 		goto lock_mmap;
 
+retry_vma:
 	vma = lock_vma_under_rcu(mm, addr);
 	if (!vma)
 		goto lock_mmap;
@@ -342,6 +343,10 @@ do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs)
 			goto no_context;
 		return 0;
 	}
+
+	/* If the first try is only about waiting for the I/O to complete */
+	if (fault & VM_FAULT_RETRY_VMA)
+		goto retry_vma;
 lock_mmap:
 
 retry:
arch/arm64/mm/fault.c +5 -0
index 125dfa6c613b..842f50b99d3e 100644
@@ -622,6 +622,7 @@ static int __kprobes do_page_fault(unsigned long far, unsigned long esr,
 	if (!(mm_flags & FAULT_FLAG_USER))
 		goto lock_mmap;
 
+retry_vma:
 	vma = lock_vma_under_rcu(mm, addr);
 	if (!vma)
 		goto lock_mmap;
@@ -668,6 +669,10 @@ static int __kprobes do_page_fault(unsigned long far, unsigned long esr,
 			goto no_context;
 		return 0;
 	}
+
+	/* If the first try is only about waiting for the I/O to complete */
+	if (fault & VM_FAULT_RETRY_VMA)
+		goto retry_vma;
 lock_mmap:
 
 retry:
arch/loongarch/mm/fault.c +4 -0
index 2c93d33356e5..738f495560c0 100644
@@ -219,6 +219,7 @@ static void __kprobes __do_page_fault(struct pt_regs *regs,
 	if (!(flags & FAULT_FLAG_USER))
 		goto lock_mmap;
 
+retry_vma:
 	vma = lock_vma_under_rcu(mm, address);
 	if (!vma)
 		goto lock_mmap;
@@ -265,6 +266,9 @@ static void __kprobes __do_page_fault(struct pt_regs *regs,
 			no_context(regs, write, address);
 		return;
 	}
+	/* If the first try is only about waiting for the I/O to complete */
+	if (fault & VM_FAULT_RETRY_VMA)
+		goto retry_vma;
 lock_mmap:
 
 retry:
arch/powerpc/mm/fault.c +4 -1
index 806c74e0d5ab..cb7ffc20c760 100644
@@ -487,6 +487,7 @@ static int ___do_page_fault(struct pt_regs *regs, unsigned long address,
 	if (!(flags & FAULT_FLAG_USER))
 		goto lock_mmap;
 
+retry_vma:
 	vma = lock_vma_under_rcu(mm, address);
 	if (!vma)
 		goto lock_mmap;
@@ -516,7 +517,9 @@ static int ___do_page_fault(struct pt_regs *regs, unsigned long address,
 
 	if (fault_signal_pending(fault, regs))
 		return user_mode(regs) ? 0 : SIGBUS;
-
+	/* If the first try is only about waiting for the I/O to complete */
+	if (fault & VM_FAULT_RETRY_VMA)
+		goto retry_vma;
 lock_mmap:
 
 	/* When running in the kernel we expect faults to occur only to
arch/riscv/mm/fault.c +4 -0
index 04ed6f8acae4..b94cf57c2b9a 100644
@@ -347,6 +347,7 @@ void handle_page_fault(struct pt_regs *regs)
 	if (!(flags & FAULT_FLAG_USER))
 		goto lock_mmap;
 
+retry_vma:
 	vma = lock_vma_under_rcu(mm, addr);
 	if (!vma)
 		goto lock_mmap;
@@ -376,6 +377,9 @@ void handle_page_fault(struct pt_regs *regs)
 			no_context(regs, addr);
 		return;
 	}
+	/* If the first try is only about waiting for the I/O to complete */
+	if (fault & VM_FAULT_RETRY_VMA)
+		goto retry_vma;
 lock_mmap:
 
 retry:
arch/s390/mm/fault.c +4 -0
index e1ad05bfd28a..8d91c6495e13 100644
@@ -286,6 +286,7 @@ static void do_exception(struct pt_regs *regs, int access)
 		flags |= FAULT_FLAG_WRITE;
 	if (!(flags & FAULT_FLAG_USER))
 		goto lock_mmap;
+retry_vma:
 	vma = lock_vma_under_rcu(mm, address);
 	if (!vma)
 		goto lock_mmap;
@@ -310,6 +311,9 @@ static void do_exception(struct pt_regs *regs, int access)
 			handle_fault_error_nolock(regs, 0);
 		return;
 	}
+	/* If the first try is only about waiting for the I/O to complete */
+	if (fault & VM_FAULT_RETRY_VMA)
+		goto retry_vma;
 lock_mmap:
 retry:
 	vma = lock_mm_and_find_vma(mm, address, regs);
arch/x86/mm/fault.c +4 -0
index 998bd807fc7b..6023d0083903 100644
@@ -1324,6 +1324,7 @@ void do_user_addr_fault(struct pt_regs *regs,
 	if (!(flags & FAULT_FLAG_USER))
 		goto lock_mmap;
 
+retry_vma:
 	vma = lock_vma_under_rcu(mm, address);
 	if (!vma)
 		goto lock_mmap;
@@ -1353,6 +1354,9 @@ void do_user_addr_fault(struct pt_regs *regs,
 						 ARCH_DEFAULT_PKEY);
 		return;
 	}
+	/* If the first try is only about waiting for the I/O to complete */
+	if (fault & VM_FAULT_RETRY_VMA)
+		goto retry_vma;
 lock_mmap:
 
 retry:
include/linux/mm_types.h +5 -4
index b71625378ce3..12b2d65ef1b9 100644
@@ -1670,10 +1670,11 @@ enum vm_fault_reason {
 	VM_FAULT_NOPAGE         = (__force vm_fault_t)0x000100,
 	VM_FAULT_LOCKED         = (__force vm_fault_t)0x000200,
 	VM_FAULT_RETRY          = (__force vm_fault_t)0x000400,
-	VM_FAULT_FALLBACK       = (__force vm_fault_t)0x000800,
-	VM_FAULT_DONE_COW       = (__force vm_fault_t)0x001000,
-	VM_FAULT_NEEDDSYNC      = (__force vm_fault_t)0x002000,
-	VM_FAULT_COMPLETED      = (__force vm_fault_t)0x004000,
+	VM_FAULT_RETRY_VMA      = (__force vm_fault_t)0x000800,
+	VM_FAULT_FALLBACK       = (__force vm_fault_t)0x001000,
+	VM_FAULT_DONE_COW       = (__force vm_fault_t)0x002000,
+	VM_FAULT_NEEDDSYNC      = (__force vm_fault_t)0x004000,
+	VM_FAULT_COMPLETED      = (__force vm_fault_t)0x008000,
 	VM_FAULT_HINDEX_MASK    = (__force vm_fault_t)0x0f0000,
 };
 
mm/filemap.c +4 -1
index 7d15a9c216ef..57dfd2211109 100644
@@ -3464,6 +3464,7 @@ vm_fault_t filemap_fault(struct vm_fault *vmf)
 	struct folio *folio;
 	vm_fault_t ret = 0;
 	bool mapping_locked = false;
+	bool retry_by_vma_lock = false;
 
 	max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
 	if (unlikely(index >= max_idx))
@@ -3560,6 +3561,8 @@ vm_fault_t filemap_fault(struct vm_fault *vmf)
 	 */
 	if (fpin) {
 		folio_unlock(folio);
+		if (vmf->flags & FAULT_FLAG_VMA_LOCK)
+			retry_by_vma_lock = true;
 		goto out_retry;
 	}
 	if (mapping_locked)
@@ -3610,7 +3613,7 @@ vm_fault_t filemap_fault(struct vm_fault *vmf)
 		filemap_invalidate_unlock_shared(mapping);
 	if (fpin)
 		fput(fpin);
-	return ret | VM_FAULT_RETRY;
+	return ret | VM_FAULT_RETRY | (retry_by_vma_lock ? VM_FAULT_RETRY_VMA : 0);
 }
 EXPORT_SYMBOL(filemap_fault);
 
Signature · 1 line
2.39.3 (Apple Git-146)
#2 lore raw

Re: [RFC PATCH 1/2] mm/filemap: Retry fault by VMA lock if the lock was released for I/O

Quoted 7 lines · Barry Song

From: Oven Liyang <[email protected]>

If the current page fault is using the per-VMA lock, and we only released the lock to wait for I/O completion (e.g., using folio_lock()), then when the fault is retried after the I/O completes, it should still qualify for the per-VMA-lock path.

<snip>

Quoted 10 lines
---
 arch/arm/mm/fault.c       | 5 +++++
 arch/arm64/mm/fault.c     | 5 +++++
 arch/loongarch/mm/fault.c | 4 ++++
 arch/powerpc/mm/fault.c   | 5 ++++-
 arch/riscv/mm/fault.c     | 4 ++++
 arch/s390/mm/fault.c      | 4 ++++
 arch/x86/mm/fault.c       | 4 ++++

If only we could unify all these paths :(

Quoted 9 lines
 include/linux/mm_types.h  | 9 +++++----
 mm/filemap.c              | 5 ++++-
 9 files changed, 39 insertions(+), 6 deletions(-)
include/linux/mm_types.h +0 -0
index b71625378ce3..12b2d65ef1b9 100644

include/linux/mm_types.h enum vm_fault_reason { · line 1673

Quoted 8 lines
include/linux/mm_types.h +1 -4
@@ -1670,10 +1670,11 @@ enum vm_fault_reason {
 	VM_FAULT_NOPAGE         = (__force vm_fault_t)0x000100,
 	VM_FAULT_LOCKED         = (__force vm_fault_t)0x000200,
 	VM_FAULT_RETRY          = (__force vm_fault_t)0x000400,
-	VM_FAULT_FALLBACK       = (__force vm_fault_t)0x000800,
-	VM_FAULT_DONE_COW       = (__force vm_fault_t)0x001000,
-	VM_FAULT_NEEDDSYNC      = (__force vm_fault_t)0x002000,
-	VM_FAULT_COMPLETED      = (__force vm_fault_t)0x004000,
+	VM_FAULT_RETRY_VMA      = (__force vm_fault_t)0x000800,

So, what I am wondering here is why we need one more fault flag versus just blindly doing this on a plain-old RETRY. Is there any particular reason why? I can't think of one.

I would also like to see performance numbers.

The rest of the patch looks OK to me.

Signature · 1 line
Pedro
author
#3 lore raw

Re: [RFC PATCH 1/2] mm/filemap: Retry fault by VMA lock if the lock was released for I/O

Quoted 21 lines · Pedro Falcato
Quoted 7 lines · Barry Song

From: Oven Liyang <[email protected]>

If the current page fault is using the per-VMA lock, and we only released the lock to wait for I/O completion (e.g., using folio_lock()), then when the fault is retried after the I/O completes, it should still qualify for the per-VMA-lock path.

<snip>

Quoted 10 lines
---
 arch/arm/mm/fault.c       | 5 +++++
 arch/arm64/mm/fault.c     | 5 +++++
 arch/loongarch/mm/fault.c | 4 ++++
 arch/powerpc/mm/fault.c   | 5 ++++-
 arch/riscv/mm/fault.c     | 4 ++++
 arch/s390/mm/fault.c      | 4 ++++
 arch/x86/mm/fault.c       | 4 ++++
Quoted 1 line

If only we could unify all these paths :(

Right, it’s a pain, but we do have bots for that?
And it’s basically just copy-and-paste across different architectures.

Quoted 14 lines
Quoted 14 lines
 include/linux/mm_types.h  | 9 +++++----
 mm/filemap.c              | 5 ++++-
 9 files changed, 39 insertions(+), 6 deletions(-)
include/linux/mm_types.h +0 -1
index b71625378ce3..12b2d65ef1b9 100644
@@ -1670,10 +1670,11 @@ enum vm_fault_reason {
      VM_FAULT_NOPAGE         = (__force vm_fault_t)0x000100,
      VM_FAULT_LOCKED         = (__force vm_fault_t)0x000200,
      VM_FAULT_RETRY          = (__force vm_fault_t)0x000400,
-     VM_FAULT_FALLBACK       = (__force vm_fault_t)0x000800,
Quoted 8 lines

include/linux/mm_types.h enum vm_fault_reason { · line 1673

Quoted 4 lines
include/linux/mm_types.h +1 -3
-     VM_FAULT_DONE_COW       = (__force vm_fault_t)0x001000,
-     VM_FAULT_NEEDDSYNC      = (__force vm_fault_t)0x002000,
-     VM_FAULT_COMPLETED      = (__force vm_fault_t)0x004000,
+     VM_FAULT_RETRY_VMA      = (__force vm_fault_t)0x000800,

So, what I am wondering here is why we need one more fault flag versus just blindly doing this on a plain-old RETRY. Is there any particular reason why? I can't think of one.

Because in some cases we retry simply due to needing to take mmap_lock. For example:

/**
* __vmf_anon_prepare - Prepare to handle an anonymous fault.
* @vmf: The vm_fault descriptor passed from the fault handler. *
* When preparing to insert an anonymous page into a VMA from a
* fault handler, call this function rather than anon_vma_prepare().
* If this vma does not already have an associated anon_vma and we are
* only protected by the per-VMA lock, the caller must retry with the
* mmap_lock held. __anon_vma_prepare() will look at adjacent VMAs to
* determine if this VMA can share its anon_vma, and that's not safe to
* do with only the per-VMA lock held for this VMA.
*
* Return: 0 if fault handling can proceed. Any other value should be
* returned to the caller.
*/
vm_fault_t __vmf_anon_prepare(struct vm_fault *vmf)
{
...
}

Thus, we have to check each branch one by one, but I/O wait is the most frequent path, so we handle it first.

Quoted 2 lines

I would also like to see performance numbers.

Yes. From what I understand, this patchset should improve performance in a fairly straightforward way.
But yes, I can certainly include some data in v2.

Quoted 2 lines

The rest of the patch looks OK to me.

Thanks
Barry

Acked-by
#4 lore raw

Re: [RFC PATCH 1/2] mm/filemap: Retry fault by VMA lock if the lock was released for I/O

Quoted 73 lines · Barry Song
Quoted 21 lines · Pedro Falcato
Quoted 7 lines · Barry Song

From: Oven Liyang <[email protected]>

If the current page fault is using the per-VMA lock, and we only released the lock to wait for I/O completion (e.g., using folio_lock()), then when the fault is retried after the I/O completes, it should still qualify for the per-VMA-lock path.

<snip>

Quoted 10 lines
---
 arch/arm/mm/fault.c       | 5 +++++
 arch/arm64/mm/fault.c     | 5 +++++
 arch/loongarch/mm/fault.c | 4 ++++
 arch/powerpc/mm/fault.c   | 5 ++++-
 arch/riscv/mm/fault.c     | 4 ++++
 arch/s390/mm/fault.c      | 4 ++++
 arch/x86/mm/fault.c       | 4 ++++
Quoted 1 line

If only we could unify all these paths :(

Right, it’s a pain, but we do have bots for that?
And it’s basically just copy-and-paste across different architectures.

Quoted 14 lines
Quoted 14 lines
 include/linux/mm_types.h  | 9 +++++----
 mm/filemap.c              | 5 ++++-
 9 files changed, 39 insertions(+), 6 deletions(-)
include/linux/mm_types.h +0 -1
index b71625378ce3..12b2d65ef1b9 100644
@@ -1670,10 +1670,11 @@ enum vm_fault_reason {
      VM_FAULT_NOPAGE         = (__force vm_fault_t)0x000100,
      VM_FAULT_LOCKED         = (__force vm_fault_t)0x000200,
      VM_FAULT_RETRY          = (__force vm_fault_t)0x000400,
-     VM_FAULT_FALLBACK       = (__force vm_fault_t)0x000800,
Quoted 8 lines

include/linux/mm_types.h enum vm_fault_reason { · line 1673

Quoted 4 lines
include/linux/mm_types.h +1 -3
-     VM_FAULT_DONE_COW       = (__force vm_fault_t)0x001000,
-     VM_FAULT_NEEDDSYNC      = (__force vm_fault_t)0x002000,
-     VM_FAULT_COMPLETED      = (__force vm_fault_t)0x004000,
+     VM_FAULT_RETRY_VMA      = (__force vm_fault_t)0x000800,

So, what I am wondering here is why we need one more fault flag versus just blindly doing this on a plain-old RETRY. Is there any particular reason why? I can't think of one.

Because in some cases we retry simply due to needing to take mmap_lock. For example:

/**
* __vmf_anon_prepare - Prepare to handle an anonymous fault.
* @vmf: The vm_fault descriptor passed from the fault handler. *
* When preparing to insert an anonymous page into a VMA from a
* fault handler, call this function rather than anon_vma_prepare().
* If this vma does not already have an associated anon_vma and we are
* only protected by the per-VMA lock, the caller must retry with the
* mmap_lock held. __anon_vma_prepare() will look at adjacent VMAs to
* determine if this VMA can share its anon_vma, and that's not safe to
* do with only the per-VMA lock held for this VMA.
*
* Return: 0 if fault handling can proceed. Any other value should be
* returned to the caller.
*/
vm_fault_t __vmf_anon_prepare(struct vm_fault *vmf)
{
...
}

Quoted 3 lines

Thus, we have to check each branch one by one, but I/O wait is the most frequent path, so we handle it first.

Hmm, right, good point. I think this is the safest option then.

FWIW:

Signature · 1 line
Pedro
author
#5 lore raw

RFC PATCH 2/2 mm/swapin: Retry swapin by VMA lock if the lock was released for I/O

In reply to Barry Song

From: Barry Song <[email protected]>

If the current do_swap_page() took the per-VMA lock and we dropped it only to wait for I/O completion (e.g., use folio_wait_locked()), then when do_swap_page() is retried after the I/O completes, it should still qualify for the per-VMA-lock path.

Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Paul Walmsley <[email protected]>
Cc Palmer Dabbelt <[email protected]>
Cc Albert Ou <[email protected]>
Cc Alexandre Ghiti <[email protected]>
Cc Russell King <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Will Deacon <[email protected]>
Cc Huacai Chen <[email protected]>
Cc WANG Xuerui <[email protected]>
Cc Madhavan Srinivasan <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc Christophe Leroy <[email protected]>
Cc Alexander Gordeev <[email protected]>
Cc Gerald Schaefer <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Vasily Gorbik <[email protected]>
Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Borislav Petkov <[email protected]>
Cc H. Peter Anvin <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Kuninori Morimoto <[email protected]>
Cc Oven Liyang <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Ada Couprie Diaz <[email protected]>
Cc Robin Murphy <[email protected]>
Cc Kristina Martšenko <[email protected]>
Cc Kevin Brodsky <[email protected]>
Cc Yeoreum Yun <[email protected]>
Cc Wentao Guan <[email protected]>
Cc Thorsten Blum <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Yunhui Cui <[email protected]>
Cc Nam Cao <[email protected]>
Cc Chris Li <[email protected]>
Cc Kairui Song <[email protected]>
Cc Kemeng Shi <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Baoquan He <[email protected]>
---
 mm/memory.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
mm/memory.c +8 -2
index 4f933fedd33e..7f70f0324dcf 100644
@@ -4654,6 +4654,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 	unsigned long page_idx;
 	unsigned long address;
 	pte_t *ptep;
+	bool retry_by_vma_lock = false;
 
 	if (!pte_unmap_same(vmf))
 		goto out;
@@ -4758,8 +4759,13 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 
 	swapcache = folio;
 	ret |= folio_lock_or_retry(folio, vmf);
-	if (ret & VM_FAULT_RETRY)
+	if (ret & VM_FAULT_RETRY) {
+		if (fault_flag_allow_retry_first(vmf->flags) &&
+		    !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT) &&
+		    (vmf->flags & FAULT_FLAG_VMA_LOCK))
+			retry_by_vma_lock = true;
 		goto out_release;
+	}
 
 	page = folio_file_page(folio, swp_offset(entry));
 	/*
@@ -5044,7 +5050,7 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
 	}
 	if (si)
 		put_swap_device(si);
-	return ret;
+	return ret | (retry_by_vma_lock ? VM_FAULT_RETRY_VMA : 0);
 }
 
 static bool pte_range_none(pte_t *pte, int nr_pages)
Signature · 1 line
2.39.3 (Apple Git-146)
maintainer
#6 lore raw
In reply to Barry Song
Quoted 3 lines · Barry Song

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

Something I've been wondering about is removing all the "drop the MM locks while we wait for I/O" gunk. It's a nice amount of code removed:

 include/linux/pagemap.h |  8 +---
 mm/filemap.c            | 98 ++++++++++++-------------------------------------
 mm/internal.h           | 21 -----------
 mm/memory.c             | 13 +------
 mm/shmem.c              |  6 ---
 5 files changed, 27 insertions(+), 119 deletions(-)

and I'm not sure we still need to do it with per-VMA locks. What I have here doesn't boot and I ran out of time to debug it.

author
#7 lore raw
Quoted 8 lines · Matthew Wilcox
Quoted 3 lines · Barry Song

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

Something I've been wondering about is removing all the "drop the MM locks while we wait for I/O" gunk. It's a nice amount of code removed:

I think the point is that page fault handlers should avoid holding the VMA lock or mmap_lock for too long while waiting for I/O. Otherwise, those writers and readers will be stuck for a while.

Quoted 10 lines
 include/linux/pagemap.h |  8 +---
 mm/filemap.c            | 98 ++++++++++++-------------------------------------
 mm/internal.h           | 21 -----------
 mm/memory.c             | 13 +------
 mm/shmem.c              |  6 ---
 5 files changed, 27 insertions(+), 119 deletions(-)

and I'm not sure we still need to do it with per-VMA locks. What I have here doesn't boot and I ran out of time to debug it.

I agree there’s room for improvement, but merely removing the "drop the MM locks while waiting for I/O" code is unlikely to improve performance.

For example, we could change the flow to:
1. Release the VMA lock or mmap_lock
2. Lock the folio
3. Re-acquire the VMA lock or mmap_lock
4. Re-check whether we can still map the PTE
5. Map the PTE

Currently, the flow is always:

1. Release the VMA lock or mmap_lock
2. Lock the folio
3. Unlock the folio
4. Re-enter the page fault handling from the beginning

The change would be much more complex, so I’d prefer to land the current patchset first. At least this way, we avoid falling back to mmap_lock and causing contention or priority inversion, with minimal changes.

Thanks
Barry

author
#8 lore raw
Quoted 23 lines · Barry Song
Quoted 8 lines · Matthew Wilcox
Quoted 3 lines · Barry Song

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

Something I've been wondering about is removing all the "drop the MM locks while we wait for I/O" gunk. It's a nice amount of code removed:

I think the point is that page fault handlers should avoid holding the VMA lock or mmap_lock for too long while waiting for I/O. Otherwise, those writers and readers will be stuck for a while.

Quoted 8 lines
 include/linux/pagemap.h |  8 +---
 mm/filemap.c            | 98 ++++++++++++-------------------------------------
 mm/internal.h           | 21 -----------
 mm/memory.c             | 13 +------
 mm/shmem.c              |  6 ---
 5 files changed, 27 insertions(+), 119 deletions(-)
Quoted 6 lines
Quoted 2 lines

and I'm not sure we still need to do it with per-VMA locks. What I have here doesn't boot and I ran out of time to debug it.

I agree there’s room for improvement, but merely removing the "drop the MM locks while waiting for I/O" code is unlikely to improve performance.

One idea I have is that we could conditionally remove the "drop lock and retry page fault" step if we are reasonably sure the I/O has already completed:

mm/filemap.c +3 -1
index 57dfd2211109..151f6d38c284 100644
@@ -3517,7 +3517,9 @@ vm_fault_t filemap_fault(struct vm_fault *vmf)
                }
        }
 
-       if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
+       if (folio_test_uptodate(folio))
+               folio_lock(folio);
+       else if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
                goto out_retry;
 
        /* Did it get truncated? */
mm/memory.c +4 -1
index 7f70f0324dcf..355ed02560fd 100644
@@ -4758,7 +4758,10 @@ vm_fault_t do_swap_page(struct vm_fault *vmf)
        }
 
        swapcache = folio;
-       ret |= folio_lock_or_retry(folio, vmf);
+       if (folio_test_uptodate(folio))
+               folio_lock(folio);
+       else
+               ret |= folio_lock_or_retry(folio, vmf);
        if (ret & VM_FAULT_RETRY) {
                if (fault_flag_allow_retry_first(vmf->flags) &&
                    !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT) &&

In that case, we are likely just waiting for the mapping to be completed by another process. I may develop the above idea as an incremental patch after this patchset.

Thanks
Barry

maintainer
#9 lore raw
In reply to Barry Song

[dropping individuals, leaving only mailing lists. please don't send this kind of thing to so many people in future]

Quoted 7 lines · Barry Song
Quoted 6 lines · Matthew Wilcox
Quoted 3 lines · Barry Song

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

Quoted 6 lines
Quoted 2 lines

Something I've been wondering about is removing all the "drop the MM locks while we wait for I/O" gunk. It's a nice amount of code removed:

I think the point is that page fault handlers should avoid holding the VMA lock or mmap_lock for too long while waiting for I/O. Otherwise, those writers and readers will be stuck for a while.

There's a usecase some of us have been discussing off-list for a few weeks that our current strategy pessimises. It's a process with thousands (maybe tens of thousands) of threads. It has much more mapped files than it has memory that cgroups will allow it to use. So on a page fault, we drop the vma lock, allocate a page of ram, kick off the read, sleep waiting for the folio to come uptodate, once it is return, expecting the page to still be there when we reenter filemap_fault. But it's under so much memory pressure that it's already been reclaimed by the time we get back to it. So all the threads just batter the storage re-reading data.

If we don't drop the vma lock, we can insert the pages in the page table and return, maybe getting some work done before this thread is descheduled.

This use case also manages to get utterly hung-up trying to do reclaim today with the mmap_lock held. SO it manifests somewhat similarly to your problem (everybody ends up blocked on mmap_lock) but it has a rather different root cause.

Quoted 2 lines

I agree there’s room for improvement, but merely removing the "drop the MM locks while waiting for I/O" code is unlikely to improve performance.

I'm not sure it'd hurt performance. The "drop mmap locks for I/O" code was written before the VMA locking code was written. I don't know that it's actually helping these days.

Quoted 3 lines

The change would be much more complex, so I’d prefer to land the current patchset first. At least this way, we avoid falling back to mmap_lock and causing contention or priority inversion, with minimal changes.

Uh, this is an RFC patchset. I'm giving you my comment, which is that I don't think this is the right direction to go in. Any talk of "landing" these patches is extremely premature.

author
#10 lore raw
Quoted 19 lines · Matthew Wilcox

[dropping individuals, leaving only mailing lists. please don't send this kind of thing to so many people in future]

Quoted 7 lines · Barry Song
Quoted 6 lines · Matthew Wilcox
Quoted 3 lines · Barry Song

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

Quoted 6 lines
Quoted 2 lines

Something I've been wondering about is removing all the "drop the MM locks while we wait for I/O" gunk. It's a nice amount of code removed:

I think the point is that page fault handlers should avoid holding the VMA lock or mmap_lock for too long while waiting for I/O. Otherwise, those writers and readers will be stuck for a while.

Quoted 10 lines

There's a usecase some of us have been discussing off-list for a few weeks that our current strategy pessimises. It's a process with thousands (maybe tens of thousands) of threads. It has much more mapped files than it has memory that cgroups will allow it to use. So on a page fault, we drop the vma lock, allocate a page of ram, kick off the read, sleep waiting for the folio to come uptodate, once it is return, expecting the page to still be there when we reenter filemap_fault. But it's under so much memory pressure that it's already been reclaimed by the time we get back to it. So all the threads just batter the storage re-reading data.

Is this entirely the fault of re-entering the page fault? Under extreme memory pressure, even if we map the pages, they can still be reclaimed quickly?

Quoted 4 lines

If we don't drop the vma lock, we can insert the pages in the page table and return, maybe getting some work done before this thread is descheduled.

If we need to protect the page from being reclaimed too early, the fix should reside within LRU management, not in page fault handling.

Also, I gave an example where we may not drop the VMA lock if the folio is already up to date. That likely corresponds to waiting for the PTE mapping to complete.

Quoted 6 lines

This use case also manages to get utterly hung-up trying to do reclaim today with the mmap_lock held. SO it manifests somewhat similarly to your problem (everybody ends up blocked on mmap_lock) but it has a rather different root cause.

Quoted 6 lines
Quoted 2 lines

I agree there’s room for improvement, but merely removing the "drop the MM locks while waiting for I/O" code is unlikely to improve performance.

I'm not sure it'd hurt performance. The "drop mmap locks for I/O" code was written before the VMA locking code was written. I don't know that it's actually helping these days.

I am concerned that other write paths may still need to modify the VMA, for example during splitting. Tail latency has long been a significant issue for Android users, and we have observed it even with folio_lock, which has much finer granularity than the VMA lock.

Quoted 8 lines
Quoted 4 lines

The change would be much more complex, so I’d prefer to land the current patchset first. At least this way, we avoid falling back to mmap_lock and causing contention or priority inversion, with minimal changes.

Uh, this is an RFC patchset. I'm giving you my comment, which is that I don't think this is the right direction to go in. Any talk of "landing" these patches is extremely premature.

While I agree that there are other approaches worth exploring, I remain entirely unconvinced that this patchset is the wrong direction. With the current retry logic, it substantially reduces mmap_lock acquisitions and represents a clear low-hanging fruit.

Also, I am not referring to landing the RFC itself, but to a subsequent formal patchset that retries using the per-VMA lock.

Thanks
Barry

author
#11 lore raw
Quoted 5 lines · Barry Song
Quoted 3 lines · Matthew Wilcox

[dropping individuals, leaving only mailing lists. please don't send this kind of thing to so many people in future]

Apologies, I missed this one.

The output comes from ./scripts/get_maintainer.pl. If you think the group is too large, I guess we should at least include Suren, Lorenzo, David, and a few others in the discussion?

[...]

Quoted 6 lines
Quoted 6 lines

This use case also manages to get utterly hung-up trying to do reclaim today with the mmap_lock held. SO it manifests somewhat similarly to your problem (everybody ends up blocked on mmap_lock) but it has a rather different root cause.

If I understand the use case correctly, I believe retrying with the per-VMA lock would also be very helpful. Previously, we always retried using mmap_lock, which can be difficult to acquire under heavy contention, leading to long latency while the pages might be reclaimed. With the per-VMA lock, it is much easier to hold and proceed with the work.

Thanks
Barry

#12 lore raw
In reply to Barry Song
Quoted 57 lines · Barry Song
Quoted 19 lines · Matthew Wilcox

[dropping individuals, leaving only mailing lists. please don't send this kind of thing to so many people in future]

Quoted 7 lines · Barry Song
Quoted 6 lines · Matthew Wilcox
Quoted 3 lines · Barry Song

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

Quoted 6 lines
Quoted 2 lines

Something I've been wondering about is removing all the "drop the MM locks while we wait for I/O" gunk. It's a nice amount of code removed:

I think the point is that page fault handlers should avoid holding the VMA lock or mmap_lock for too long while waiting for I/O. Otherwise, those writers and readers will be stuck for a while.

Quoted 10 lines

There's a usecase some of us have been discussing off-list for a few weeks that our current strategy pessimises. It's a process with thousands (maybe tens of thousands) of threads. It has much more mapped files than it has memory that cgroups will allow it to use. So on a page fault, we drop the vma lock, allocate a page of ram, kick off the read, sleep waiting for the folio to come uptodate, once it is return, expecting the page to still be there when we reenter filemap_fault. But it's under so much memory pressure that it's already been reclaimed by the time we get back to it. So all the threads just batter the storage re-reading data.

Is this entirely the fault of re-entering the page fault? Under extreme memory pressure, even if we map the pages, they can still be reclaimed quickly?

Quoted 4 lines

If we don't drop the vma lock, we can insert the pages in the page table and return, maybe getting some work done before this thread is descheduled.

If we need to protect the page from being reclaimed too early, the fix should reside within LRU management, not in page fault handling.

Also, I gave an example where we may not drop the VMA lock if the folio is already up to date. That likely corresponds to waiting for the PTE mapping to complete.

Quoted 9 lines

This use case also manages to get utterly hung-up trying to do reclaim today with the mmap_lock held. SO it manifests somewhat similarly to your problem (everybody ends up blocked on mmap_lock) but it has a rather different root cause.

Quoted 2 lines

I agree there’s room for improvement, but merely removing the "drop the MM locks while waiting for I/O" code is unlikely to improve performance.

Quoted 8 lines
Quoted 3 lines

I'm not sure it'd hurt performance. The "drop mmap locks for I/O" code was written before the VMA locking code was written. I don't know that it's actually helping these days.

I am concerned that other write paths may still need to modify the VMA, for example during splitting. Tail latency has long been a significant issue for Android users, and we have observed it even with folio_lock, which has much finer granularity than the VMA lock.

Another corner case we need to consider is when there is a large VMA covering most of the address space, so holding a VMA lock during IO would resemble holding an mmap_lock, leading to the same issue that we faced before "drop mmap locks for I/O". We discussed this with Matthew in the context of the problem he mentioned (the page is reclaimed before page fault retry happens) with no conclusion yet.

Quoted 10 lines
Quoted 9 lines
Quoted 5 lines

The change would be much more complex, so I’d prefer to land the current patchset first. At least this way, we avoid falling back to mmap_lock and causing contention or priority inversion, with minimal changes.

Uh, this is an RFC patchset. I'm giving you my comment, which is that I don't think this is the right direction to go in. Any talk of "landing" these patches is extremely premature.

Quoted 7 lines

While I agree that there are other approaches worth exploring, I remain entirely unconvinced that this patchset is the wrong direction. With the current retry logic, it substantially reduces mmap_lock acquisitions and represents a clear low-hanging fruit.

Also, I am not referring to landing the RFC itself, but to a subsequent formal patchset that retries using the per-VMA lock.

I don't know if this direction is the right one but I agree with Matthew that we should consider alternatives before adopting a new direction. Hopefully we can find one fix for both problems rather than fixing each one in isolation.

Quoted 4 lines

Thanks
Barry

author
#13 lore raw
Quoted 68 lines · Suren Baghdasaryan
Quoted 57 lines · Barry Song
Quoted 19 lines · Matthew Wilcox

[dropping individuals, leaving only mailing lists. please don't send this kind of thing to so many people in future]

Quoted 7 lines · Barry Song
Quoted 6 lines · Matthew Wilcox
Quoted 3 lines · Barry Song

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

Quoted 6 lines
Quoted 2 lines

Something I've been wondering about is removing all the "drop the MM locks while we wait for I/O" gunk. It's a nice amount of code removed:

I think the point is that page fault handlers should avoid holding the VMA lock or mmap_lock for too long while waiting for I/O. Otherwise, those writers and readers will be stuck for a while.

Quoted 10 lines

There's a usecase some of us have been discussing off-list for a few weeks that our current strategy pessimises. It's a process with thousands (maybe tens of thousands) of threads. It has much more mapped files than it has memory that cgroups will allow it to use. So on a page fault, we drop the vma lock, allocate a page of ram, kick off the read, sleep waiting for the folio to come uptodate, once it is return, expecting the page to still be there when we reenter filemap_fault. But it's under so much memory pressure that it's already been reclaimed by the time we get back to it. So all the threads just batter the storage re-reading data.

Is this entirely the fault of re-entering the page fault? Under extreme memory pressure, even if we map the pages, they can still be reclaimed quickly?

Quoted 4 lines

If we don't drop the vma lock, we can insert the pages in the page table and return, maybe getting some work done before this thread is descheduled.

If we need to protect the page from being reclaimed too early, the fix should reside within LRU management, not in page fault handling.

Also, I gave an example where we may not drop the VMA lock if the folio is already up to date. That likely corresponds to waiting for the PTE mapping to complete.

Quoted 9 lines

This use case also manages to get utterly hung-up trying to do reclaim today with the mmap_lock held. SO it manifests somewhat similarly to your problem (everybody ends up blocked on mmap_lock) but it has a rather different root cause.

Quoted 2 lines

I agree there’s room for improvement, but merely removing the "drop the MM locks while waiting for I/O" code is unlikely to improve performance.

Quoted 8 lines
Quoted 3 lines

I'm not sure it'd hurt performance. The "drop mmap locks for I/O" code was written before the VMA locking code was written. I don't know that it's actually helping these days.

I am concerned that other write paths may still need to modify the VMA, for example during splitting. Tail latency has long been a significant issue for Android users, and we have observed it even with folio_lock, which has much finer granularity than the VMA lock.

Quoted 6 lines

Another corner case we need to consider is when there is a large VMA covering most of the address space, so holding a VMA lock during IO would resemble holding an mmap_lock, leading to the same issue that we faced before "drop mmap locks for I/O". We discussed this with Matthew in the context of the problem he mentioned (the page is reclaimed before page fault retry happens) with no conclusion yet.

Suren, thank you very much for your input.

Right. I think we may discover more corner cases on Android in places where we previously saw VMA merging, such as between two native heap mmap areas. This can happen fairly often, and we don’t want long BIO queues to block those writers.

Quoted 16 lines
Quoted 16 lines
Quoted 10 lines
Quoted 6 lines

The change would be much more complex, so I’d prefer to land the current patchset first. At least this way, we avoid falling back to mmap_lock and causing contention or priority inversion, with minimal changes.

Uh, this is an RFC patchset. I'm giving you my comment, which is that I don't think this is the right direction to go in. Any talk of "landing" these patches is extremely premature.

While I agree that there are other approaches worth exploring, I remain entirely unconvinced that this patchset is the wrong direction. With the current retry logic, it substantially reduces mmap_lock acquisitions and represents a clear low-hanging fruit.

Quoted 7 lines
Quoted 2 lines

Also, I am not referring to landing the RFC itself, but to a subsequent formal patchset that retries using the per-VMA lock.

I don't know if this direction is the right one but I agree with Matthew that we should consider alternatives before adopting a new direction. Hopefully we can find one fix for both problems rather than fixing each one in isolation.

As I mentioned in a follow-up reply to Matthew[1], I think the current approach also helps in cases where pages are reclaimed during retries. Previously, we required mmap_lock to retry, so any contention made it hard to acquire and introduced high latency. During that time, pages could be reclaimed before mmap_lock was obtained. Now that we only require the per-VMA lock, retries can proceed much more easily than before.
As long as we replace a big lock with a smaller one, there is less chance of getting stuck in D state.

If either you or Matthew have a reproducer for this issue, I’d be happy to try it out.

BTW, we also observed mmap_lock contention during MGLRU aging. TBH, the non-RMAP clearing of the PTE young bit does not seem helpful on arm64, which does not support non-leaf young bits at all. After disabling the feature below, we found that reclamation used less CPU and ran better.

echo 1 >/sys/kernel/mm/lru_gen/enabled

0x0002 Clearing the accessed bit in leaf page table entries in large
batches, when MMU sets it (e.g., on x86). This behavior can theoretically worsen lock contention (mmap_lock). If it is disabled, the multi-gen LRU will suffer a minor performance degradation for workloads that contiguously map hot pages, whose accessed bits can be otherwise cleared by fewer larger batches.

[1] https://lore.kernel.org/linux-mm/CAGsJ_4wvaieWtTrK+koM3SFu9rDExkVHX5eUwYiEotVqP-ndEQ@mail.gmail.com/

Thanks
Barry

Tested-by Tested-by Kunwu Chan Reviewed-by Reviewed-by Kunwu Chan
#14 lore raw

Hi Barry,

Quoted 2 lines

If either you or Matthew have a reproducer for this issue, I’d be happy to try it out.

Kunwu and I evaluated this series ("mm: continue using per-VMA lock when retrying page faults after I/O") under a stress scenario specifically designed to expose the retry behavior in filemap_fault(). This models the exact situation described by Matthew Wilcox [1], where retries after I/O fail to make forward progress under memory pressure.

The scenario targets the critical window between I/O completion and mmap_lock reacquisition. This workload deliberately includes frequent mmap/munmap operations to simulate a highly contended mmap_lock environment alongside severe memory pressure (1GB memcg limit). Under this pressure, folios instantiated by the I/O can be aggressively reclaimed before the delayed task can re-acquire the lock and install the PTE, forcing retries to repeat the entire work.

To make this behavior reproducible, we constructed a stress setup that intentionally extends this interval:
* 256-core x86 system
* 1GB memory cgroup
* 500 threads continuously faulting on a 16MB file

The core reproducer and the execution command are provided below:

#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <time.h>

#define THREADS 500
#define FILE_SIZE (16 * 1024 * 1024) /* 16MB */

static _Atomic int g_stop = 0;
#define RUN_SECONDS 600

struct worker_arg { 
        long id; 
        uint64_t *counts; 
}; 

void *worker(void *arg)

{ 
        struct worker_arg *wa = (struct worker_arg *)arg; 
        long id = wa->id; 
        char path[64]; 
        uint64_t local_rounds = 0; 

        snprintf(path, sizeof(path), "./test_file_%d_%ld.dat", 
                 getpid(), id); 
        int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666); 
        if (fd < 0) return NULL; 
        if (ftruncate(fd, FILE_SIZE) < 0) { 
                close(fd); return NULL; 
        } 

        while (!atomic_load_explicit(&g_stop, memory_order_relaxed)) { 
                char *f_map = mmap(NULL, FILE_SIZE, PROT_READ, 
                                   MAP_SHARED, fd, 0); 
                if (f_map != MAP_FAILED) { 
                        /* Pure page cache thrashing */ 
                        for (int i = 0; i < FILE_SIZE; i += 4096) { 
                                volatile unsigned char c = 
                                        (unsigned char)f_map[i]; 
                                (void)c; 
                        } 
                        munmap(f_map, FILE_SIZE); 
                        local_rounds++; 
                } 
        } 
        wa->counts[id] = local_rounds; 
        close(fd); 
        unlink(path); 
        return NULL; 
} 

int main(void)

{ 
        printf("Pure File Thrashing Started. PID: %d\n", getpid()); 
        pthread_t t[THREADS]; 
        uint64_t local_counts[THREADS]; 
        memset(local_counts, 0, sizeof(local_counts)); 
        struct worker_arg args[THREADS]; 

        for (long i = 0; i < THREADS; i++) { 
                args[i].id = i; 
                args[i].counts = local_counts; 
                pthread_create(&t[i], NULL, worker, &args[i]); 
        } 

        sleep(RUN_SECONDS); 
        atomic_store_explicit(&g_stop, 1, memory_order_relaxed); 

        for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL); 

        uint64_t total = 0; 
        for (int i = 0; i < THREADS; i++) total += local_counts[i]; 

        printf("Total rounds     : %llu\n", (unsigned long long)total); 
        printf("Throughput       : %.2f rounds/sec\n", 
               (double)total / RUN_SECONDS); 
        return 0; 
}

Command line used for the test:
systemd-run --scope -p MemoryHigh=1G -p MemoryMax=1.2G -p MemorySwapMax=0 \
--unit=mmap-thrash-$$ ./mmap_lock & \
TEST_PID=$!

We also added temporary counters in page fault retries [2]:
- RETRY_IO_MISS : folio not present after I/O completion
- RETRY_MMAP_DROP : retry fallback due to waiting for I/O

We report representative runs from our 600-second test iterations (kernel v7.0-rc3):

| Case                | Total Rounds | Throughput | Miss/Drop(%) | RETRY_MMAP_DROP | RETRY_IO_MISS |
| ------------------- | ------------ | ---------- | ------------ | --------------- | ------------- |
| Baseline (Run 1)    | 22,711       | 37.85 /s   | 45.04        | 970,078         | 436,956       |
| Baseline (Run 2)    | 23,530       | 39.22 /s   | 44.96        | 972,043         | 437,077       |
| With Series (Run A) | 54,428       | 90.71 /s   | 1.69         | 1,204,124       | 20,398        |
| With Series (Run B) | 35,949       | 59.91 /s   | 0.03         | 327,023         | 99            |

Notes:
1. Throughput Improvement: During the 600-second testing window, overall workload throughput can more than double (e.g., Run A jumped from ~38 to 90.71 rounds/sec).
2. Elimination of Race Condition: Without the patch, ~45% of retries were invalid because newly fetched folios were evicted during the mmap_lock reacquisition delay. With the per-VMA retry path, the invalidation ratio plummeted to near zero (0.03% - 1.69%).
3. Counter Scaling and Variance: In Run A, because the I/O wait bottleneck is eliminated, the threads advance much faster. Thus, the absolute number of mmap_lock drops naturally scales up with the increased throughput. In Run B, the primary bottleneck shifts to the mmap write-lock contention (lock convoying), causing throughput and total drops to fluctuate. Crucially, the Miss/Drop ratio remains near zero regardless of this variance.

Without this series, almost half of the retries fail to observe completed I/O results, causing severe CPU and I/O waste. With the finer-grained VMA lock, the faulting threads bypass the heavily contended mmap_lock entirely during retries, completing the fault almost instantly.

This scenario perfectly aligns with the exact concern raised, and these results show that the patch not only successfully eliminates the retry inefficiency but also tangibly boosts macro-level system throughput.

[1] https://lore.kernel.org/linux-mm/[email protected]/
[2] https://github.com/lianux-mm/ioretry_test/

--
Best Regards,
wang lian

#15 lore raw
In reply to Matthew Wilcox
Quoted 18 lines · Matthew Wilcox

[dropping individuals, leaving only mailing lists. please don't send this kind of thing to so many people in future]

Quoted 7 lines · Barry Song
Quoted 6 lines · Matthew Wilcox
Quoted 3 lines · Barry Song

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

Quoted 6 lines
Quoted 2 lines

Something I've been wondering about is removing all the "drop the MM locks while we wait for I/O" gunk. It's a nice amount of code removed:

I think the point is that page fault handlers should avoid holding the VMA lock or mmap_lock for too long while waiting for I/O. Otherwise, those writers and readers will be stuck for a while.

Quoted 10 lines

There's a usecase some of us have been discussing off-list for a few weeks that our current strategy pessimises. It's a process with thousands (maybe tens of thousands) of threads. It has much more mapped files than it has memory that cgroups will allow it to use. So on a page fault, we drop the vma lock, allocate a page of ram, kick off the read, sleep waiting for the folio to come uptodate, once it is return, expecting the page to still be there when we reenter filemap_fault. But it's under so much memory pressure that it's already been reclaimed by the time we get back to it. So all the threads just batter the storage re-reading data.

I would caution against changing kernel for such usecase. Actually I would call it a misconfigured system instead of a usecase. If a workload is under that much memory pressure that its refaulted pages are getting reclaimed then it means its workingset is larger than the available memory and is thrashing. The only option here is to either increase the memory limits or kill the workload and reschedule on the system with enough memory available.

#16 lore raw
In reply to Barry Song
Quoted 7 lines · Barry Song

From: Barry Song <[email protected]>

Oven observed most mmap_lock contention and priority inversion come from page fault retries after waiting for I/O completion. Oven subsequently raised the following idea:

Quoted 6 lines

There is no need to always fall back to mmap_lock if the per-VMA lock was released only to wait for pagecache or swapcache to become ready.

In this case, the retry path can continue using the per-VMA lock. This is a big win: it greatly reduces mmap_lock acquisitions.

Here are some test data for the patches:

== Test Case ==

Douyin (Chinese version of TikTok) warm start on smart phone with 8GB RAM

== mmap_lock Acquisitions And Wait Time ==

Metric Before (Avg) After (Avg) Change
------------------------------------------------------------------------

Read Lock Count           20,010          5,719          -71.42%
Read Total Wait (us)      10,695,877     408,436        -96.18%
Read Avg Wait (us)        534.00         71.00           -86.70%
Write Lock Count          838             909            +8.47%
Write Total Wait (us)     501,293        97,633          -80.52%
Write Avg Wait (us)       598.00         107.00          -82.11%

== Read Lock Waiting Time Distribution of mmap_lock ==

Range (us) Before (Avg) After (Avg) Change
------------------------------------------------------------------------

[0, 1)                     9,927           4,286          -56.82%
[1, 10)                    9,179           1,327          -85.54%
[10, 100)                  191             88             -53.93%
[100, 1000)                57              6              -89.47%
[1000, 10000)              328             9              -97.26%
[10000, 100000)            328             6              -98.17%
[100000, 1000000)          0               0              N/A
[1000000, +)               0               0              N/A

== Write Lock Waiting Time Distribution of mmap_lock ==

Range (us) Before (Avg) After (Avg) Change
------------------------------------------------------------------------

[0, 1)                     250             300            +20.00%
[1, 10)                    483             556            +15.11%
[10, 100)                  52              41             -21.15%
[100, 1000)                12              5              -58.33%
[1000, 10000)              22              4              -81.82%
[10000, 100000)            16              1              -93.75%
[100000, 1000000)          0               0              N/A
[1000000, +)               0               0              N/A

After the optimization, the number of read lock acquisitions is significantly reduced, and both lock waiting time and tail latency are dramatically improved.

Thanks,
Oven

Quoted 87 lines

Oven Liyang (1):
mm/filemap: Retry fault by VMA lock if the lock was released for I/O

Barry Song (1):
mm/swapin: Retry swapin by VMA lock if the lock was released for I/O

  arch/arm/mm/fault.c       |  5 +++++
  arch/arm64/mm/fault.c     |  5 +++++
  arch/loongarch/mm/fault.c |  4 ++++
  arch/powerpc/mm/fault.c   |  5 ++++-
  arch/riscv/mm/fault.c     |  4 ++++
  arch/s390/mm/fault.c      |  4 ++++
  arch/x86/mm/fault.c       |  4 ++++
  include/linux/mm_types.h  |  9 +++++----
  mm/filemap.c              |  5 ++++-
  mm/memory.c               | 10 ++++++++--
  10 files changed, 47 insertions(+), 8 deletions(-)
Cc Russell King <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Will Deacon <[email protected]>
Cc Huacai Chen <[email protected]>
Cc WANG Xuerui <[email protected]>
Cc Madhavan Srinivasan <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc Christophe Leroy <[email protected]>
Cc Paul Walmsley <[email protected]>
Cc Palmer Dabbelt <[email protected]>
Cc Albert Ou <[email protected]>
Cc Alexandre Ghiti <[email protected]>
Cc Alexander Gordeev <[email protected]>
Cc Gerald Schaefer <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Vasily Gorbik <[email protected]>
Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Andy Lutomirski <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Borislav Petkov <[email protected]>
Cc H. Peter Anvin <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Jarkko Sakkinen <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Kuninori Morimoto <[email protected]>
Cc Oven Liyang <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Ada Couprie Diaz <[email protected]>
Cc Robin Murphy <[email protected]>
Cc Kristina Martšenko <[email protected]>
Cc Kevin Brodsky <[email protected]>
Cc Yeoreum Yun <[email protected]>
Cc Wentao Guan <[email protected]>
Cc Thorsten Blum <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Yunhui Cui <[email protected]>
Cc Nam Cao <[email protected]>
Cc Chris Li <[email protected]>
Cc Kairui Song <[email protected]>
Cc Kemeng Shi <[email protected]>
Cc Nhat Pham <[email protected]>
Cc Baoquan He <[email protected]>

--
2.39.3 (Apple Git-146)