Skip to contentSkip to conversation

mm: reworked AI-generated VMA and mremap fixes

PATCH Applied Lorenzo Stoakes (ARM) 7 participants 37 messages Nov 21 – Nov 24

Subsystems (6)
lore
Share & tools
lore

Lorenzo Stoakes (ARM)

author maintainer
#0 lore raw

cover mm: reworked AI-generated VMA and mremap fixes

I have reordered the patches here by priority, David - the first 2 should be prioritised as hotfixes, the rest can go in 7.5:

== Critical ==

1. unmapped_area_topdown() invalid bounds - possible memory corruption, triggerable by any local user.
2. Lock VMAs before mm_all_locks_mutex - system-wide unkillable hang, triggerable by a local user with FUSE.

== Need fixing ==

3. KSM unmerge only interrupted by fatal signal - silent data loss on mremap() of KSM memory.
4. Uncharge after failed stack relocation - strict overcommit limit defeated system-wide.
5. mmap() offset limits on mremap() expansion - invalid file offset reaches the DAX fault handler.

== Hardening (no need for Cc: stable) ==

6. Guard gaps on in-place mremap() expansion.
7. Non-executable brk mappings under MDWE.

As usual, please go through and check these carefully for correctness, sanity.

Note that one of the original patches was punted over to the BPF guys ([0]), as it doesn't feel that it'd make sense to change core mm to address it.

[0]:https://lore.kernel.org/all/awGZWsCp6v63H_py@gremlin/

---
Chris Mason (4):
mm/vma: fix uncharge after failed stack relocation mm/mremap: apply the mmap() offset limits on expansion mm/mremap: respect guard gaps on in-place expansion mm/vma: make brk mappings non-executable under MDWE

Lorenzo Stoakes (ARM) (3):
mm/vma: error out on invalid bounds in unmapped_area_topdown() mm/vma: lock VMAs before taking mm_all_locks_mutex mm/ksm: only interrupt unmerging on a fatal signal

 mm/internal.h |  2 ++
 mm/ksm.c      |  4 ++--
 mm/mmap.c     |  4 ++--
 mm/mremap.c   | 10 +++++++-
 mm/vma.c      | 75 ++++++++++++++++++++++++++++++-----------------------------
 mm/vma_exec.c | 22 +++++++++++++++---
 6 files changed, 72 insertions(+), 45 deletions(-)

---
base-commit: d12eccbcb79a4fa35c3aa588eb79056af62eb859
change-id: 20261120-some-more-ai-fixes-aed3c4b5ef5c

Cheers,

Signature · 1 line
Lorenzo Stoakes (ARM) <[email protected]>
author maintainer
#1 lore raw

PATCH 1/7 mm/vma: error out on invalid bounds in unmapped_area_topdown()

unmapped_area_topdown() suffers from a class of bug arising from a mismatch between how maple tree functions and VMA iterator functions express ranges
- the former inclusively, the latter exclusively.

This is problematic with an exclusive upper bound of 0, as it translates to an inclusive upper bound of ULONG_MAX, that is a range which extends to the end of the address space, and start < end or equivalent comparisons evaluate false in a situation where in fact the expression should evaluate true.

unmapped_area_topdown() calls vma_iter_area_highest() to position the VMA iterator into the next highest empty range spanning [low_limit, high_limit), iteratively reducing high_limit without checking whether it has reached 0.

This can result in a [low_limit, 0) pair being passed to vma_iter_area_highest() and thus unexpected underflow. Consider:

    vm_start        = 0x30000
    stack_guard_gap = 0x100000
    info->length    = 0x1000
    high_limit      = vm_start_gap() = 0
    high_limit - 1  = ULONG_MAX
    window          = [low_limit, ULONG_MAX]
    vma_iter_end()  = ULONG_MAX + 1 = 0
    gap             = 0 - info->length = 0xfffffffffffff000

The result is page aligned and below the IS_ERR_VALUE() range, so it does not look like an error. What follows depends on the caller:

- mmap() with no hint can fail with -ENOMEM while space is free. The bottom-up fallback is skipped, and __get_unmapped_area() refuses the address as above TASK_SIZE.
- On x86-64, find_nearest_trampoline() can pick the address for the uprobe trampoline. _install_special_mapping() then inserts a VMA whose vm_end is 0, and exit_mmap() frees kernel page tables that every mm shares.
- On powerpc64 with the hash MMU, slice_get_unmapped_area() can pass the address to alloc_extended_context(), which then writes out of bounds of mm->context.extended_id[].

mmap() can succeed with an address from the wrapped window where the range above TASK_SIZE is too short for the request and its alignment padding. On s390 that range is one page, so this takes no more than the default stack_guard_gap.

Fix the issue by converting the loop into one that explicitly tests low_limit < high_limit.

Additionally, simplify the logic by declaring the VMA iterator in the loop (it is reset on each iteration anyway) and exiting with the correct output value on success rather than performing a goto when an iteration is required.

Fixes 58c5d0d6d522 ("mm/mmap: regression fix for unmapped_area{_topdown}")
---
 mm/vma.c | 42 ++++++++++++++++++++----------------------
 1 file changed, 20 insertions(+), 22 deletions(-)
mm/vma.c +20 -22
index c82e9306b11a..09bbcdb4971b 100644
@@ -3369,8 +3369,6 @@ unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
 {
 	unsigned long length, gap, gap_end;
 	unsigned long low_limit, high_limit;
-	struct vm_area_struct *tmp;
-	VMA_ITERATOR(vmi, current->mm, 0);
 
 	/* Adjust search length to account for worst case alignment overhead */
 	length = info->length + info->align_mask + info->start_gap;
@@ -3381,31 +3379,31 @@ unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
 	if (low_limit < mmap_min_addr)
 		low_limit = mmap_min_addr;
 	high_limit = info->high_limit;
-retry:
-	if (vma_iter_area_highest(&vmi, low_limit, high_limit, length))
-		return -ENOMEM;
 
-	gap = vma_iter_end(&vmi) - info->length;
-	gap -= (gap - info->align_offset) & info->align_mask;
-	gap_end = vma_iter_end(&vmi);
-	tmp = vma_next(&vmi);
-	 /* Avoid prev check if possible */
-	if (tmp && vma_test_any_mask(tmp, VMA_STARTGAP_FLAGS)) {
-		if (vm_start_gap(tmp) < gap_end) {
+	while (low_limit < high_limit) {
+		VMA_ITERATOR(vmi, current->mm, 0);
+		struct vm_area_struct *tmp;
+
+		if (vma_iter_area_highest(&vmi, low_limit, high_limit, length))
+			break;
+
+		gap = vma_iter_end(&vmi) - info->length;
+		gap -= (gap - info->align_offset) & info->align_mask;
+		gap_end = vma_iter_end(&vmi);
+		tmp = vma_next(&vmi);
+		/* Avoid prev check if possible */
+		if (tmp && vma_test_any_mask(tmp, VMA_STARTGAP_FLAGS)) {
+			if (vm_start_gap(tmp) >= gap_end)
+				return gap;
 			high_limit = vm_start_gap(tmp);
-			vma_iter_reset(&vmi);
-			goto retry;
-		}
-	} else {
-		tmp = vma_prev(&vmi);
-		if (tmp && vm_end_gap(tmp) > gap) {
+		} else {
+			tmp = vma_prev(&vmi);
+			if (!tmp || vm_end_gap(tmp) <= gap)
+				return gap;
 			high_limit = tmp->vm_start;
-			vma_iter_reset(&vmi);
-			goto retry;
 		}
 	}
-
-	return gap;
+	return -ENOMEM;
 }
 
 /*
Signature · 1 line
2.56.0
reviewer Reviewed-by on v1 1/7
#2 lore raw

Re: [PATCH 1/7] mm/vma: error out on invalid bounds in unmapped_area_topdown()

Quoted 55 lines · Lorenzo Stoakes (ARM)

unmapped_area_topdown() suffers from a class of bug arising from a mismatch between how maple tree functions and VMA iterator functions express ranges
- the former inclusively, the latter exclusively.

This is problematic with an exclusive upper bound of 0, as it translates to an inclusive upper bound of ULONG_MAX, that is a range which extends to the end of the address space, and start < end or equivalent comparisons evaluate false in a situation where in fact the expression should evaluate true.

unmapped_area_topdown() calls vma_iter_area_highest() to position the VMA iterator into the next highest empty range spanning [low_limit, high_limit), iteratively reducing high_limit without checking whether it has reached 0.

This can result in a [low_limit, 0) pair being passed to vma_iter_area_highest() and thus unexpected underflow. Consider:

    vm_start        = 0x30000
    stack_guard_gap = 0x100000
    info->length    = 0x1000
    high_limit      = vm_start_gap() = 0
    high_limit - 1  = ULONG_MAX
    window          = [low_limit, ULONG_MAX]
    vma_iter_end()  = ULONG_MAX + 1 = 0
    gap             = 0 - info->length = 0xfffffffffffff000

The result is page aligned and below the IS_ERR_VALUE() range, so it does not look like an error. What follows depends on the caller:

- mmap() with no hint can fail with -ENOMEM while space is free. The bottom-up fallback is skipped, and __get_unmapped_area() refuses the address as above TASK_SIZE.
- On x86-64, find_nearest_trampoline() can pick the address for the uprobe trampoline. _install_special_mapping() then inserts a VMA whose vm_end is 0, and exit_mmap() frees kernel page tables that every mm shares.
- On powerpc64 with the hash MMU, slice_get_unmapped_area() can pass the address to alloc_extended_context(), which then writes out of bounds of mm->context.extended_id[].

mmap() can succeed with an address from the wrapped window where the range above TASK_SIZE is too short for the request and its alignment padding. On s390 that range is one page, so this takes no more than the default stack_guard_gap.

Fix the issue by converting the loop into one that explicitly tests low_limit < high_limit.

Additionally, simplify the logic by declaring the VMA iterator in the loop (it is reset on each iteration anyway) and exiting with the correct output value on success rather than performing a goto when an iteration is required.

Quoted 4 lines
Fixes 58c5d0d6d522 ("mm/mmap: regression fix for unmapped_area{_topdown}")
Quoted 73 lines
---
 mm/vma.c | 42 ++++++++++++++++++++----------------------
 1 file changed, 20 insertions(+), 22 deletions(-)
mm/vma.c +20 -23
index c82e9306b11a..09bbcdb4971b 100644
@@ -3369,8 +3369,6 @@ unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
 {
        unsigned long length, gap, gap_end;
        unsigned long low_limit, high_limit;
-       struct vm_area_struct *tmp;
-       VMA_ITERATOR(vmi, current->mm, 0);
 
        /* Adjust search length to account for worst case alignment overhead */
        length = info->length + info->align_mask + info->start_gap;
@@ -3381,31 +3379,31 @@ unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
        if (low_limit < mmap_min_addr)
                low_limit = mmap_min_addr;
        high_limit = info->high_limit;
-retry:
-       if (vma_iter_area_highest(&vmi, low_limit, high_limit, length))
-               return -ENOMEM;
 
-       gap = vma_iter_end(&vmi) - info->length;
-       gap -= (gap - info->align_offset) & info->align_mask;
-       gap_end = vma_iter_end(&vmi);
-       tmp = vma_next(&vmi);
-        /* Avoid prev check if possible */
-       if (tmp && vma_test_any_mask(tmp, VMA_STARTGAP_FLAGS)) {
-               if (vm_start_gap(tmp) < gap_end) {
+       while (low_limit < high_limit) {
+               VMA_ITERATOR(vmi, current->mm, 0);
+               struct vm_area_struct *tmp;
+
+               if (vma_iter_area_highest(&vmi, low_limit, high_limit, length))
+                       break;
+
+               gap = vma_iter_end(&vmi) - info->length;
+               gap -= (gap - info->align_offset) & info->align_mask;
+               gap_end = vma_iter_end(&vmi);
+               tmp = vma_next(&vmi);
+               /* Avoid prev check if possible */
+               if (tmp && vma_test_any_mask(tmp, VMA_STARTGAP_FLAGS)) {
+                       if (vm_start_gap(tmp) >= gap_end)
+                               return gap;
                        high_limit = vm_start_gap(tmp);
-                       vma_iter_reset(&vmi);
-                       goto retry;
-               }
-       } else {
-               tmp = vma_prev(&vmi);
-               if (tmp && vm_end_gap(tmp) > gap) {
+               } else {
+                       tmp = vma_prev(&vmi);
+                       if (!tmp || vm_end_gap(tmp) <= gap)
+                               return gap;
                        high_limit = tmp->vm_start;
-                       vma_iter_reset(&vmi);
-                       goto retry;
                }
        }
-
-       return gap;
+       return -ENOMEM;
 }
 
 /*
 
--

2.56.0

Tested-by Reviewed-by on v1 1/7
#3 lore raw

Re: [PATCH 1/7] mm/vma: error out on invalid bounds in unmapped_area_topdown()

In reply to Lorenzo Stoakes (ARM)
Quoted 54 lines · Lorenzo Stoakes (ARM)

unmapped_area_topdown() suffers from a class of bug arising from a mismatch between how maple tree functions and VMA iterator functions express ranges
- the former inclusively, the latter exclusively.

This is problematic with an exclusive upper bound of 0, as it translates to an inclusive upper bound of ULONG_MAX, that is a range which extends to the end of the address space, and start < end or equivalent comparisons evaluate false in a situation where in fact the expression should evaluate true.

unmapped_area_topdown() calls vma_iter_area_highest() to position the VMA iterator into the next highest empty range spanning [low_limit, high_limit), iteratively reducing high_limit without checking whether it has reached 0.

This can result in a [low_limit, 0) pair being passed to vma_iter_area_highest() and thus unexpected underflow. Consider:

    vm_start        = 0x30000
    stack_guard_gap = 0x100000
    info->length    = 0x1000
    high_limit      = vm_start_gap() = 0
    high_limit - 1  = ULONG_MAX
    window          = [low_limit, ULONG_MAX]
    vma_iter_end()  = ULONG_MAX + 1 = 0
    gap             = 0 - info->length = 0xfffffffffffff000

The result is page aligned and below the IS_ERR_VALUE() range, so it does not look like an error. What follows depends on the caller:

- mmap() with no hint can fail with -ENOMEM while space is free. The bottom-up fallback is skipped, and __get_unmapped_area() refuses the address as above TASK_SIZE.
- On x86-64, find_nearest_trampoline() can pick the address for the uprobe trampoline. _install_special_mapping() then inserts a VMA whose vm_end is 0, and exit_mmap() frees kernel page tables that every mm shares.
- On powerpc64 with the hash MMU, slice_get_unmapped_area() can pass the address to alloc_extended_context(), which then writes out of bounds of mm->context.extended_id[].

mmap() can succeed with an address from the wrapped window where the range above TASK_SIZE is too short for the request and its alignment padding. On s390 that range is one page, so this takes no more than the default stack_guard_gap.

Fix the issue by converting the loop into one that explicitly tests low_limit < high_limit.

Additionally, simplify the logic by declaring the VMA iterator in the loop (it is reset on each iteration anyway) and exiting with the correct output value on success rather than performing a goto when an iteration is required.

Quoted 4 lines
Fixes 58c5d0d6d522 ("mm/mmap: regression fix for unmapped_area{_topdown}")
Signature · 1 line
~Gregory
Reviewed-by on v1 1/7
#4 lore raw

Re: [PATCH 1/7] mm/vma: error out on invalid bounds in unmapped_area_topdown()

In reply to Lorenzo Stoakes (ARM)
Quoted 54 lines · Lorenzo Stoakes (ARM)

unmapped_area_topdown() suffers from a class of bug arising from a mismatch between how maple tree functions and VMA iterator functions express ranges
- the former inclusively, the latter exclusively.

This is problematic with an exclusive upper bound of 0, as it translates to an inclusive upper bound of ULONG_MAX, that is a range which extends to the end of the address space, and start < end or equivalent comparisons evaluate false in a situation where in fact the expression should evaluate true.

unmapped_area_topdown() calls vma_iter_area_highest() to position the VMA iterator into the next highest empty range spanning [low_limit, high_limit), iteratively reducing high_limit without checking whether it has reached 0.

This can result in a [low_limit, 0) pair being passed to vma_iter_area_highest() and thus unexpected underflow. Consider:

    vm_start        = 0x30000
    stack_guard_gap = 0x100000
    info->length    = 0x1000
    high_limit      = vm_start_gap() = 0
    high_limit - 1  = ULONG_MAX
    window          = [low_limit, ULONG_MAX]
    vma_iter_end()  = ULONG_MAX + 1 = 0
    gap             = 0 - info->length = 0xfffffffffffff000

The result is page aligned and below the IS_ERR_VALUE() range, so it does not look like an error. What follows depends on the caller:

- mmap() with no hint can fail with -ENOMEM while space is free. The bottom-up fallback is skipped, and __get_unmapped_area() refuses the address as above TASK_SIZE.
- On x86-64, find_nearest_trampoline() can pick the address for the uprobe trampoline. _install_special_mapping() then inserts a VMA whose vm_end is 0, and exit_mmap() frees kernel page tables that every mm shares.
- On powerpc64 with the hash MMU, slice_get_unmapped_area() can pass the address to alloc_extended_context(), which then writes out of bounds of mm->context.extended_id[].

mmap() can succeed with an address from the wrapped window where the range above TASK_SIZE is too short for the request and its alignment padding. On s390 that range is one page, so this takes no more than the default stack_guard_gap.

Fix the issue by converting the loop into one that explicitly tests low_limit < high_limit.

Additionally, simplify the logic by declaring the VMA iterator in the loop (it is reset on each iteration anyway) and exiting with the correct output value on success rather than performing a goto when an iteration is required.

Quoted 4 lines
Fixes 58c5d0d6d522 ("mm/mmap: regression fix for unmapped_area{_topdown}")

LGTM:

Signature · 2 lines
cheers,
jose a. p-a
maintainer tree notice
#5 lore raw

+ mm-vma-error-out-on-invalid-bounds-in-unmapped_area_topdown.patch added to mm-new branch

In reply to Lorenzo Stoakes (ARM)
The patch titled Subject: mm/vma: error out on invalid bounds in unmapped_area_topdown() has been added to the -mm mm-new branch. Its filename is…

The patch titled
Subject: mm/vma: error out on invalid bounds in unmapped_area_topdown()
has been added to the -mm mm-new branch. Its filename is
mm-vma-error-out-on-invalid-bounds-in-unmapped_area_topdown.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-vma-error-out-on-invalid-bounds-in-unmapped_area_topdown.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: "Lorenzo Stoakes (ARM)" <[email protected]>
Subject: mm/vma: error out on invalid bounds in unmapped_area_topdown()
Date: Sat, 21 Nov 2026 16:02:27 +0000

Patch series "mm: reworked AI-generated VMA and mremap fixes".

I have reordered the patches here by priority, David - the first 2 should be prioritised as hotfixes, the rest can go in 7.5:

== Critical ==

1. unmapped_area_topdown() invalid bounds - possible memory corruption, triggerable by any local user.
2. Lock VMAs before mm_all_locks_mutex - system-wide unkillable hang, triggerable by a local user with FUSE.

== Need fixing ==

3. Uncharge after failed stack relocation - strict overcommit limit defeated system-wide.
4. mmap() offset limits on mremap() expansion - invalid file offset reaches the DAX fault handler.

== Hardening (no need for Cc: stable) ==

5. Guard gaps on in-place mremap() expansion.
6. Non-executable brk mappings under MDWE.

As usual, please go through and check these carefully for correctness,

This patch (of 6):

unmapped_area_topdown() suffers from a class of bug arising from a mismatch between how maple tree functions and VMA iterator functions express ranges
- the former inclusively, the latter exclusively.

This is problematic with an exclusive upper bound of 0, as it translates to an inclusive upper bound of ULONG_MAX, that is a range which extends to the end of the address space, and start < end or equivalent comparisons evaluate false in a situation where in fact the expression should evaluate true.

unmapped_area_topdown() calls vma_iter_area_highest() to position the VMA iterator into the next highest empty range spanning [low_limit, high_limit), iteratively reducing high_limit without checking whether it has reached 0.

This can result in a [low_limit, 0) pair being passed to vma_iter_area_highest() and thus unexpected underflow. Consider:

    vm_start        = 0x30000
    stack_guard_gap = 0x100000
    info->length    = 0x1000
    high_limit      = vm_start_gap() = 0
    high_limit - 1  = ULONG_MAX
    window          = [low_limit, ULONG_MAX]
    vma_iter_end()  = ULONG_MAX + 1 = 0
    gap             = 0 - info->length = 0xfffffffffffff000

The result is page aligned and below the IS_ERR_VALUE() range, so it does not look like an error. What follows depends on the caller:

- mmap() with no hint can fail with -ENOMEM while space is free. The bottom-up fallback is skipped, and __get_unmapped_area() refuses the address as above TASK_SIZE.
- On x86-64, find_nearest_trampoline() can pick the address for the uprobe trampoline. _install_special_mapping() then inserts a VMA whose vm_end is 0, and exit_mmap() frees kernel page tables that every mm shares.
- On powerpc64 with the hash MMU, slice_get_unmapped_area() can pass the address to alloc_extended_context(), which then writes out of bounds of mm->context.extended_id[].

mmap() can succeed with an address from the wrapped window where the range above TASK_SIZE is too short for the request and its alignment padding. On s390 that range is one page, so this takes no more than the default stack_guard_gap.

Fix the issue by converting the loop into one that explicitly tests low_limit < high_limit.

Additionally, simplify the logic by declaring the VMA iterator in the loop (it is reset on each iteration anyway) and exiting with the correct output value on success rather than performing a goto when an iteration is required.

 mm/vma.c |   42 ++++++++++++++++++++----------------------
 1 file changed, 20 insertions(+), 22 deletions(-)
mm/vma.c renamed from mm/vma.c~mm-vma-error-out-on-invalid-bounds-in-unmapped_area_topdown +20 -22
@@ -3369,8 +3369,6 @@ unsigned long unmapped_area_topdown(stru
 {
 	unsigned long length, gap, gap_end;
 	unsigned long low_limit, high_limit;
-	struct vm_area_struct *tmp;
-	VMA_ITERATOR(vmi, current->mm, 0);
 
 	/* Adjust search length to account for worst case alignment overhead */
 	length = info->length + info->align_mask + info->start_gap;
@@ -3381,31 +3379,31 @@ unsigned long unmapped_area_topdown(stru
 	if (low_limit < mmap_min_addr)
 		low_limit = mmap_min_addr;
 	high_limit = info->high_limit;
-retry:
-	if (vma_iter_area_highest(&vmi, low_limit, high_limit, length))
-		return -ENOMEM;
 
-	gap = vma_iter_end(&vmi) - info->length;
-	gap -= (gap - info->align_offset) & info->align_mask;
-	gap_end = vma_iter_end(&vmi);
-	tmp = vma_next(&vmi);
-	 /* Avoid prev check if possible */
-	if (tmp && vma_test_any_mask(tmp, VMA_STARTGAP_FLAGS)) {
-		if (vm_start_gap(tmp) < gap_end) {
+	while (low_limit < high_limit) {
+		VMA_ITERATOR(vmi, current->mm, 0);
+		struct vm_area_struct *tmp;
+
+		if (vma_iter_area_highest(&vmi, low_limit, high_limit, length))
+			break;
+
+		gap = vma_iter_end(&vmi) - info->length;
+		gap -= (gap - info->align_offset) & info->align_mask;
+		gap_end = vma_iter_end(&vmi);
+		tmp = vma_next(&vmi);
+		/* Avoid prev check if possible */
+		if (tmp && vma_test_any_mask(tmp, VMA_STARTGAP_FLAGS)) {
+			if (vm_start_gap(tmp) >= gap_end)
+				return gap;
 			high_limit = vm_start_gap(tmp);
-			vma_iter_reset(&vmi);
-			goto retry;
-		}
-	} else {
-		tmp = vma_prev(&vmi);
-		if (tmp && vm_end_gap(tmp) > gap) {
+		} else {
+			tmp = vma_prev(&vmi);
+			if (!tmp || vm_end_gap(tmp) <= gap)
+				return gap;
 			high_limit = tmp->vm_start;
-			vma_iter_reset(&vmi);
-			goto retry;
 		}
 	}
-
-	return gap;
+	return -ENOMEM;
 }
 
 /*

_

Patches currently in -mm which might be from [email protected] are

mm-msync-return-enomem-if-page-aligned-length-overflows.patch mm-vma-drop-mm-asynchronously-in-vma_start_read.patch mm-vma-predicate-vma_assert_stabilised-on-config_debug_vm.patch mm-only-assert-mmap-locks-if-config_debug_vm-or-lockdep-is-set.patch mm-only-assert-vma-locks-if-config_debug_vm-is-set.patch mm-convert-warn_on_onces-to-vm_warn_on_once-in-vma-lock-code.patch mm-madvise-zap-markers-from-guard-regions.patch mm-mmap-free-gathered-pages-before-mmf_oom_skip.patch percpu-fix-contig-hints-that-are-too-low.patch percpu-search-the-whole-reserved-chunk.patch mm-filemap-convert-fault-and-readahead-logic-to-use-vma_flags_t.patch mm-madvise-convert-madvise_vma_behavior-to-use-vma_flags_t.patch mm-convert-miscellaneous-vma-flag-tests-to-use-vma_flags_t.patch fs-proc-task_mmu-convert-vma-flag-tests-to-use-vma_flags_t.patch fs-coredump-convert-vma_dump_size-to-use-vma_flags_t.patch uprobes-convert-vma-flag-tests-to-use-vma_flags_t.patch perf-convert-vma-flag-tests-to-use-vma_flags_t.patch selinux-convert-vma-flag-tests-to-use-vma_flags_t.patch apparmor-convert-vma-flag-tests-to-use-vma_flags_t.patch ima-convert-vma-flag-tests-to-use-vma_flags_t.patch ipe-convert-vma-flag-tests-to-use-vma_flags_t.patch xen-privcmd-convert-mmap-hook-to-mmap_prepare.patch kvm-ppc-book3s-convert-spapr-tce-mmap-hook-to-mmap_prepare.patch mshv_vtl-convert-mmap-hooks-to-mmap_prepare.patch x86-sgx-convert-vepc-mmap-hook-to-mmap_prepare.patch udf-convert-mmap-hook-to-mmap_prepare.patch selinuxfs-convert-mmap-hooks-to-mmap_prepare.patch xen-convert-xenstore-interface-mmap-hooks-to-mmap_prepare.patch soc-aspeed-convert-lpc-and-p2a-control-mmap-hooks-to-mmap_prepare.patch soc-qcom-rmtfs_mem-convert-mmap-hook-to-mmap_prepare.patch tee-convert-shm-mmap-hook-to-mmap_prepare.patch misc-bcm-vk-convert-mmap-hook-to-mmap_prepare.patch ptp-vmclock-convert-mmap-hook-to-mmap_prepare.patch vhost-vdpa-convert-mmap-hook-to-mmap_prepare.patch mm-vma-error-out-on-invalid-bounds-in-unmapped_area_topdown.patch mm-vma-lock-vmas-before-taking-mm_all_locks_mutex.patch

author maintainer
#6 lore raw

PATCH 2/7 mm/vma: lock VMAs before taking mm_all_locks_mutex

In reply to Lorenzo Stoakes (ARM)

If an mmu notifier is registered for an mm while one of its page faults sleeps indefinitely under the VMA lock, the registration of mmu notifiers for every other mm can hang un-killably.

mm_all_locks_mutex is shared by all mms, so its holder must not wait for something that has no bound.

However, mm_take_all_locks() calls vma_start_write() on each VMA with the mutex held, and thus waits for the readers of the VMA.

Since commit 4ed4379881aa ("mm: handle shared faults under the VMA lock"), such a reader can sleep in ->page_mkwrite().

Consider fuse_page_mkwrite(), which sleeps until the FUSE server replies to a write request:

    mm A, thread 1          mm A, thread 2         mm B
    ==============          ==============         ====
    lock_vma_under_rcu()
    fuse_page_mkwrite()
      folio_wait_writeback()
                            mm_take_all_locks()
                              mutex_lock()
                              vma_start_write()
                                                   mm_take_all_locks()
                                                     mutex_lock()

Fix the issue by locking the VMAs before the mutex is taken.

Additionally, make the VMA write lock killable so a fatal signal returns as quickly as possible.

Finally, update the comments to reflect the change, dropping the lock ordering list which begs for bitrot.

Note that the lock order at the top of mm/rmap.c doesn't appear to be right
- the hugetlb locks are taken after the VMA write locks. However, this was already the case, and can be addressed in a follow-up in any case.

Target commit 4ed4379881aa ("mm: handle shared faults under the VMA lock") as this is where it became possible for VMA lock readers to sleep in ->page_mkwrite().

Fixes 4ed4379881aa ("mm: handle shared faults under the VMA lock")
---
 mm/vma.c | 29 ++++++++++++++---------------
 1 file changed, 14 insertions(+), 15 deletions(-)
mm/vma.c +14 -15
index 09bbcdb4971b..f8cf319ff9cf 100644
@@ -2375,15 +2375,10 @@ static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
  * mapping->flags avoid to take the same lock twice, if more than one
  * vma in this mm is backed by the same anon rmap or address_space.
  *
- * We take locks in following order, accordingly to comment at beginning
- * of mm/rmap.c:
- *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
- *     hugetlb mapping);
- *   - all vmas marked locked
- *   - all i_mmap_rwsem locks;
- *   - all anon_vma->rwseml
- *
- * We can take all locks within these types randomly because the VM code
+ * Mark all vmas locked, before taking mm_all_locks_mutex. Then take remaining
+ * locks in the order mandated by the comment at the top of mm/rmap.c.
+ *
+ * We can take locks of the same type in arbitrary order because the VM code
  * doesn't nest them and we protected from parallel mm_take_all_locks() by
  * mm_all_locks_mutex.
  *
@@ -2400,20 +2395,24 @@ int mm_take_all_locks(struct mm_struct *mm)
 
 	mmap_assert_write_locked(mm);
 
-	mutex_lock(&mm_all_locks_mutex);
-
 	/*
-	 * vma_start_write() does not have a complement in mm_drop_all_locks()
-	 * because vma_start_write() is always asymmetrical; it marks a VMA as
+	 * VMA write locks do not have a complement in mm_drop_all_locks(),
+	 * because VMA write locking is always asymmetrical; it marks a VMA as
 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
 	 * is reached.
 	 */
 	for_each_vma(vmi, vma) {
+		int err;
+
 		if (signal_pending(current))
-			goto out_unlock;
-		vma_start_write(vma);
+			return -EINTR;
+		err = vma_start_write_killable(vma);
+		if (err)
+			return err;
 	}
 
+	mutex_lock(&mm_all_locks_mutex);
+
 	vma_iter_init(&vmi, mm, 0);
 	for_each_vma(vmi, vma) {
 		if (signal_pending(current))
Signature · 1 line
2.56.0
reviewer Reviewed-by on v1 2/7
#7 lore raw

Re: [PATCH 2/7] mm/vma: lock VMAs before taking mm_all_locks_mutex

Quoted 40 lines · Lorenzo Stoakes (ARM)

If an mmu notifier is registered for an mm while one of its page faults sleeps indefinitely under the VMA lock, the registration of mmu notifiers for every other mm can hang un-killably.

mm_all_locks_mutex is shared by all mms, so its holder must not wait for something that has no bound.

However, mm_take_all_locks() calls vma_start_write() on each VMA with the mutex held, and thus waits for the readers of the VMA.

Since commit 4ed4379881aa ("mm: handle shared faults under the VMA lock"), such a reader can sleep in ->page_mkwrite().

Consider fuse_page_mkwrite(), which sleeps until the FUSE server replies to a write request:

    mm A, thread 1          mm A, thread 2         mm B
    ==============          ==============         ====
    lock_vma_under_rcu()
    fuse_page_mkwrite()
      folio_wait_writeback()
                            mm_take_all_locks()
                              mutex_lock()
                              vma_start_write()
                                                   mm_take_all_locks()
                                                     mutex_lock()

Fix the issue by locking the VMAs before the mutex is taken.

Additionally, make the VMA write lock killable so a fatal signal returns as quickly as possible.

Finally, update the comments to reflect the change, dropping the lock ordering list which begs for bitrot.

Note that the lock order at the top of mm/rmap.c doesn't appear to be right
- the hugetlb locks are taken after the VMA write locks. However, this was already the case, and can be addressed in a follow-up in any case.

Quoted 8 lines

Target commit 4ed4379881aa ("mm: handle shared faults under the VMA lock") as this is where it became possible for VMA lock readers to sleep in ->page_mkwrite().

Fixes 4ed4379881aa ("mm: handle shared faults under the VMA lock")
Quoted 63 lines
---
 mm/vma.c | 29 ++++++++++++++---------------
 1 file changed, 14 insertions(+), 15 deletions(-)
mm/vma.c +14 -16
index 09bbcdb4971b..f8cf319ff9cf 100644
@@ -2375,15 +2375,10 @@ static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
  * mapping->flags avoid to take the same lock twice, if more than one
  * vma in this mm is backed by the same anon rmap or address_space.
  *
- * We take locks in following order, accordingly to comment at beginning
- * of mm/rmap.c:
- *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
- *     hugetlb mapping);
- *   - all vmas marked locked
- *   - all i_mmap_rwsem locks;
- *   - all anon_vma->rwseml
- *
- * We can take all locks within these types randomly because the VM code
+ * Mark all vmas locked, before taking mm_all_locks_mutex. Then take remaining
+ * locks in the order mandated by the comment at the top of mm/rmap.c.
+ *
+ * We can take locks of the same type in arbitrary order because the VM code
  * doesn't nest them and we protected from parallel mm_take_all_locks() by
  * mm_all_locks_mutex.
  *
@@ -2400,20 +2395,24 @@ int mm_take_all_locks(struct mm_struct *mm)
 
        mmap_assert_write_locked(mm);
 
-       mutex_lock(&mm_all_locks_mutex);
-
        /*
-        * vma_start_write() does not have a complement in mm_drop_all_locks()
-        * because vma_start_write() is always asymmetrical; it marks a VMA as
+        * VMA write locks do not have a complement in mm_drop_all_locks(),
+        * because VMA write locking is always asymmetrical; it marks a VMA as
         * being written to until mmap_write_unlock() or mmap_write_downgrade()
         * is reached.
         */
        for_each_vma(vmi, vma) {
+               int err;
+
                if (signal_pending(current))
-                       goto out_unlock;
-               vma_start_write(vma);
+                       return -EINTR;
+               err = vma_start_write_killable(vma);
+               if (err)
+                       return err;
        }
 
+       mutex_lock(&mm_all_locks_mutex);
+
        vma_iter_init(&vmi, mm, 0);
        for_each_vma(vmi, vma) {
                if (signal_pending(current))
 
--

2.56.0

Tested-by Reviewed-by on v1 2/7
#8 lore raw

Re: [PATCH 2/7] mm/vma: lock VMAs before taking mm_all_locks_mutex

In reply to Lorenzo Stoakes (ARM)
Quoted 39 lines · Lorenzo Stoakes (ARM)

If an mmu notifier is registered for an mm while one of its page faults sleeps indefinitely under the VMA lock, the registration of mmu notifiers for every other mm can hang un-killably.

mm_all_locks_mutex is shared by all mms, so its holder must not wait for something that has no bound.

However, mm_take_all_locks() calls vma_start_write() on each VMA with the mutex held, and thus waits for the readers of the VMA.

Since commit 4ed4379881aa ("mm: handle shared faults under the VMA lock"), such a reader can sleep in ->page_mkwrite().

Consider fuse_page_mkwrite(), which sleeps until the FUSE server replies to a write request:

    mm A, thread 1          mm A, thread 2         mm B
    ==============          ==============         ====
    lock_vma_under_rcu()
    fuse_page_mkwrite()
      folio_wait_writeback()
                            mm_take_all_locks()
                              mutex_lock()
                              vma_start_write()
                                                   mm_take_all_locks()
                                                     mutex_lock()

Fix the issue by locking the VMAs before the mutex is taken.

Additionally, make the VMA write lock killable so a fatal signal returns as quickly as possible.

Finally, update the comments to reflect the change, dropping the lock ordering list which begs for bitrot.

Note that the lock order at the top of mm/rmap.c doesn't appear to be right
- the hugetlb locks are taken after the VMA write locks. However, this was already the case, and can be addressed in a follow-up in any case.

Quoted 8 lines

Target commit 4ed4379881aa ("mm: handle shared faults under the VMA lock") as this is where it became possible for VMA lock readers to sleep in ->page_mkwrite().

Fixes 4ed4379881aa ("mm: handle shared faults under the VMA lock")
Signature · 1 line
~Gregory
Reviewed-by on v1 2/7
#9 lore raw

Re: [PATCH 2/7] mm/vma: lock VMAs before taking mm_all_locks_mutex

In reply to Lorenzo Stoakes (ARM)
Quoted 39 lines · Lorenzo Stoakes (ARM)

If an mmu notifier is registered for an mm while one of its page faults sleeps indefinitely under the VMA lock, the registration of mmu notifiers for every other mm can hang un-killably.

mm_all_locks_mutex is shared by all mms, so its holder must not wait for something that has no bound.

However, mm_take_all_locks() calls vma_start_write() on each VMA with the mutex held, and thus waits for the readers of the VMA.

Since commit 4ed4379881aa ("mm: handle shared faults under the VMA lock"), such a reader can sleep in ->page_mkwrite().

Consider fuse_page_mkwrite(), which sleeps until the FUSE server replies to a write request:

    mm A, thread 1          mm A, thread 2         mm B
    ==============          ==============         ====
    lock_vma_under_rcu()
    fuse_page_mkwrite()
      folio_wait_writeback()
                            mm_take_all_locks()
                              mutex_lock()
                              vma_start_write()
                                                   mm_take_all_locks()
                                                     mutex_lock()

Fix the issue by locking the VMAs before the mutex is taken.

Additionally, make the VMA write lock killable so a fatal signal returns as quickly as possible.

Finally, update the comments to reflect the change, dropping the lock ordering list which begs for bitrot.

Note that the lock order at the top of mm/rmap.c doesn't appear to be right
- the hugetlb locks are taken after the VMA write locks. However, this was already the case, and can be addressed in a follow-up in any case.

Quoted 8 lines

Target commit 4ed4379881aa ("mm: handle shared faults under the VMA lock") as this is where it became possible for VMA lock readers to sleep in ->page_mkwrite().

Fixes 4ed4379881aa ("mm: handle shared faults under the VMA lock")

LGTM:

Signature · 2 lines
cheers,
jose a. p-a
maintainer tree notice
#10 lore raw

+ mm-vma-lock-vmas-before-taking-mm_all_locks_mutex.patch added to mm-new branch

In reply to Lorenzo Stoakes (ARM)
The patch titled Subject: mm/vma: lock VMAs before taking mm_all_locks_mutex has been added to the -mm mm-new branch. Its filename is mm-vma-lock-vmas-before-taking-mm_all_locks_mutex.patch

The patch titled
Subject: mm/vma: lock VMAs before taking mm_all_locks_mutex
has been added to the -mm mm-new branch. Its filename is
mm-vma-lock-vmas-before-taking-mm_all_locks_mutex.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-vma-lock-vmas-before-taking-mm_all_locks_mutex.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: "Lorenzo Stoakes (ARM)" <[email protected]>
Subject: mm/vma: lock VMAs before taking mm_all_locks_mutex
Date: Sat, 21 Nov 2026 16:02:28 +0000

If an mmu notifier is registered for an mm while one of its page faults sleeps indefinitely under the VMA lock, the registration of mmu notifiers for every other mm can hang un-killably.

mm_all_locks_mutex is shared by all mms, so its holder must not wait for something that has no bound.

However, mm_take_all_locks() calls vma_start_write() on each VMA with the mutex held, and thus waits for the readers of the VMA.

Since commit 4ed4379881aa ("mm: handle shared faults under the VMA lock"), such a reader can sleep in ->page_mkwrite().

Consider fuse_page_mkwrite(), which sleeps until the FUSE server replies to a write request:

    mm A, thread 1          mm A, thread 2         mm B
    ==============          ==============         ====
    lock_vma_under_rcu()
    fuse_page_mkwrite()
      folio_wait_writeback()
                            mm_take_all_locks()
                              mutex_lock()
                              vma_start_write()
                                                   mm_take_all_locks()
                                                     mutex_lock()

Fix the issue by locking the VMAs before the mutex is taken.

Additionally, make the VMA write lock killable so a fatal signal returns as quickly as possible.

Finally, update the comments to reflect the change, dropping the lock ordering list which begs for bitrot.

Note that the lock order at the top of mm/rmap.c doesn't appear to be right
- the hugetlb locks are taken after the VMA write locks. However, this was already the case, and can be addressed in a follow-up in any case.

Target commit 4ed4379881aa ("mm: handle shared faults under the VMA lock") as this is where it became possible for VMA lock readers to sleep in ->page_mkwrite().

Fixes 4ed4379881aa ("mm: handle shared faults under the VMA lock")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Jann Horn <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Kees Cook <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Ollie Wild <[email protected]>
Cc Adrian Bunk <[email protected]>
Cc Xu Xin <[email protected]>
Cc Chengming Zhou <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Joey Gouly <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Josef Bacik <[email protected]>
 mm/vma.c |   27 +++++++++++++--------------
 1 file changed, 13 insertions(+), 14 deletions(-)
mm/vma.c renamed from mm/vma.c~mm-vma-lock-vmas-before-taking-mm_all_locks_mutex +13 -14
@@ -2375,15 +2375,10 @@ static void vm_lock_mapping(struct mm_st
  * mapping->flags avoid to take the same lock twice, if more than one
  * vma in this mm is backed by the same anon rmap or address_space.
  *
- * We take locks in following order, accordingly to comment at beginning
- * of mm/rmap.c:
- *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
- *     hugetlb mapping);
- *   - all vmas marked locked
- *   - all i_mmap_rwsem locks;
- *   - all anon_vma->rwseml
+ * Mark all vmas locked, before taking mm_all_locks_mutex. Then take remaining
+ * locks in the order mandated by the comment at the top of mm/rmap.c.
  *
- * We can take all locks within these types randomly because the VM code
+ * We can take locks of the same type in arbitrary order because the VM code
  * doesn't nest them and we protected from parallel mm_take_all_locks() by
  * mm_all_locks_mutex.
  *
@@ -2400,20 +2395,24 @@ int mm_take_all_locks(struct mm_struct *
 
 	mmap_assert_write_locked(mm);
 
-	mutex_lock(&mm_all_locks_mutex);
-
 	/*
-	 * vma_start_write() does not have a complement in mm_drop_all_locks()
-	 * because vma_start_write() is always asymmetrical; it marks a VMA as
+	 * VMA write locks do not have a complement in mm_drop_all_locks(),
+	 * because VMA write locking is always asymmetrical; it marks a VMA as
 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
 	 * is reached.
 	 */
 	for_each_vma(vmi, vma) {
+		int err;
+
 		if (signal_pending(current))
-			goto out_unlock;
-		vma_start_write(vma);
+			return -EINTR;
+		err = vma_start_write_killable(vma);
+		if (err)
+			return err;
 	}
 
+	mutex_lock(&mm_all_locks_mutex);
+
 	vma_iter_init(&vmi, mm, 0);
 	for_each_vma(vmi, vma) {
 		if (signal_pending(current))

_

Patches currently in -mm which might be from [email protected] are

mm-msync-return-enomem-if-page-aligned-length-overflows.patch mm-vma-drop-mm-asynchronously-in-vma_start_read.patch mm-vma-predicate-vma_assert_stabilised-on-config_debug_vm.patch mm-only-assert-mmap-locks-if-config_debug_vm-or-lockdep-is-set.patch mm-only-assert-vma-locks-if-config_debug_vm-is-set.patch mm-convert-warn_on_onces-to-vm_warn_on_once-in-vma-lock-code.patch mm-madvise-zap-markers-from-guard-regions.patch mm-mmap-free-gathered-pages-before-mmf_oom_skip.patch percpu-fix-contig-hints-that-are-too-low.patch percpu-search-the-whole-reserved-chunk.patch mm-filemap-convert-fault-and-readahead-logic-to-use-vma_flags_t.patch mm-madvise-convert-madvise_vma_behavior-to-use-vma_flags_t.patch mm-convert-miscellaneous-vma-flag-tests-to-use-vma_flags_t.patch fs-proc-task_mmu-convert-vma-flag-tests-to-use-vma_flags_t.patch fs-coredump-convert-vma_dump_size-to-use-vma_flags_t.patch uprobes-convert-vma-flag-tests-to-use-vma_flags_t.patch perf-convert-vma-flag-tests-to-use-vma_flags_t.patch selinux-convert-vma-flag-tests-to-use-vma_flags_t.patch apparmor-convert-vma-flag-tests-to-use-vma_flags_t.patch ima-convert-vma-flag-tests-to-use-vma_flags_t.patch ipe-convert-vma-flag-tests-to-use-vma_flags_t.patch xen-privcmd-convert-mmap-hook-to-mmap_prepare.patch kvm-ppc-book3s-convert-spapr-tce-mmap-hook-to-mmap_prepare.patch mshv_vtl-convert-mmap-hooks-to-mmap_prepare.patch x86-sgx-convert-vepc-mmap-hook-to-mmap_prepare.patch udf-convert-mmap-hook-to-mmap_prepare.patch selinuxfs-convert-mmap-hooks-to-mmap_prepare.patch xen-convert-xenstore-interface-mmap-hooks-to-mmap_prepare.patch soc-aspeed-convert-lpc-and-p2a-control-mmap-hooks-to-mmap_prepare.patch soc-qcom-rmtfs_mem-convert-mmap-hook-to-mmap_prepare.patch tee-convert-shm-mmap-hook-to-mmap_prepare.patch misc-bcm-vk-convert-mmap-hook-to-mmap_prepare.patch ptp-vmclock-convert-mmap-hook-to-mmap_prepare.patch vhost-vdpa-convert-mmap-hook-to-mmap_prepare.patch mm-vma-error-out-on-invalid-bounds-in-unmapped_area_topdown.patch mm-vma-lock-vmas-before-taking-mm_all_locks_mutex.patch

author maintainer
#11 lore raw

PATCH 3/7 mm/ksm: only interrupt unmerging on a fatal signal

In reply to Lorenzo Stoakes (ARM)

Commit d952b79136a6 ("ksm: fix endless loop on oom") added a check for pending signals on KSM break, so that a lengthy unmerge could be interrupted, with the system call then restarted via -ERESTARTSYS.

However, it assumes that the callers can always restart whatever system call started it in the first place (the commit message questions whether this was wise).

Well, it turns out that it was not wise, as this baked in an implicit assumption about system call restartability, and it was and is not safe for mremap().

mremap() holds an mmap write lock over the operation, which an -ERESTARTSYS drops, meaning that the restart is not in a consistent state.

This was made considerably worse with commit d23cb648e365 ("mm/mremap:
permit mremap() move of multiple VMAs"), which can result in data loss if you encounter this issue.

Consider an mremap() specifying MREMAP_FIXED | MREMAP_DONTUNMAP of two KSM-mergeable VMAs, where a signal becomes pending part way through:

first pass restart
========== =======
unmap tgt1 range
copy src1 to tgt1, move page tables
unmap tgt2 range
break_ksm(src2) = -ERESTARTSYS
unmap tgt1 range, which now
holds the data from src1
copy the now-empty src1 to tgt1

This results in the user observing a successful mremap() but with src1's data missing.

Without MREMAP_DONTUNMAP, remap_move() would find a gap at the start of the range on restart and fail with -EFAULT there instead.

Fix the issue by only breaking out of an unmerge if a fatal signal is pending, returning -EINTR when we do. This makes KSM unmerging consistent with many other signal checks in mm.

Target commit d23cb648e365 ("mm/mremap: permit mremap() move of multiple VMAs") for the fix as this made the issue significantly more impactful.

Fixes d23cb648e365 ("mm/mremap: permit mremap() move of multiple VMAs")
---
 mm/ksm.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/ksm.c +2 -2
index 623a2cdb3924..5d320a200951 100644
@@ -627,8 +627,8 @@ static int break_ksm_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long en
 
 	if (ksm_test_exit(walk->mm))
 		return 0;
-	if (signal_pending(current))
-		return -ERESTARTSYS;
+	if (fatal_signal_pending(current))
+		return -EINTR;
 
 	start_ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
 	if (!start_ptep)
Signature · 1 line
2.56.0
reviewer Reviewed-by on v1 3/7
#12 lore raw

Re: [PATCH 3/7] mm/ksm: only interrupt unmerging on a fatal signal

Quoted 43 lines · Lorenzo Stoakes (ARM)

Commit d952b79136a6 ("ksm: fix endless loop on oom") added a check for pending signals on KSM break, so that a lengthy unmerge could be interrupted, with the system call then restarted via -ERESTARTSYS.

However, it assumes that the callers can always restart whatever system call started it in the first place (the commit message questions whether this was wise).

Well, it turns out that it was not wise, as this baked in an implicit assumption about system call restartability, and it was and is not safe for mremap().

mremap() holds an mmap write lock over the operation, which an -ERESTARTSYS drops, meaning that the restart is not in a consistent state.

This was made considerably worse with commit d23cb648e365 ("mm/mremap:
permit mremap() move of multiple VMAs"), which can result in data loss if you encounter this issue.

Consider an mremap() specifying MREMAP_FIXED | MREMAP_DONTUNMAP of two KSM-mergeable VMAs, where a signal becomes pending part way through:

first pass restart
========== =======
unmap tgt1 range
copy src1 to tgt1, move page tables
unmap tgt2 range
break_ksm(src2) = -ERESTARTSYS
unmap tgt1 range, which now
holds the data from src1
copy the now-empty src1 to tgt1

This results in the user observing a successful mremap() but with src1's data missing.

Without MREMAP_DONTUNMAP, remap_move() would find a gap at the start of the range on restart and fail with -EFAULT there instead.

Fix the issue by only breaking out of an unmerge if a fatal signal is pending, returning -EINTR when we do. This makes KSM unmerging consistent with many other signal checks in mm.

Quoted 7 lines

Target commit d23cb648e365 ("mm/mremap: permit mremap() move of multiple VMAs") for the fix as this made the issue significantly more impactful.

Fixes d23cb648e365 ("mm/mremap: permit mremap() move of multiple VMAs")
Quoted 23 lines
---
 mm/ksm.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/ksm.c +2 -3
index 623a2cdb3924..5d320a200951 100644
@@ -627,8 +627,8 @@ static int break_ksm_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long en
 
        if (ksm_test_exit(walk->mm))
                return 0;
-       if (signal_pending(current))
-               return -ERESTARTSYS;
+       if (fatal_signal_pending(current))
+               return -EINTR;
 
        start_ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
        if (!start_ptep)
 
--

2.56.0

maintainer Reviewed-by on v1 3/7
#13 lore raw

Re: [PATCH 3/7] mm/ksm: only interrupt unmerging on a fatal signal

In reply to Lorenzo Stoakes (ARM)
Quoted 59 lines · Lorenzo Stoakes (ARM)

Commit d952b79136a6 ("ksm: fix endless loop on oom") added a check for pending signals on KSM break, so that a lengthy unmerge could be interrupted, with the system call then restarted via -ERESTARTSYS.

However, it assumes that the callers can always restart whatever system call started it in the first place (the commit message questions whether this was wise).

Well, it turns out that it was not wise, as this baked in an implicit assumption about system call restartability, and it was and is not safe for mremap().

mremap() holds an mmap write lock over the operation, which an -ERESTARTSYS drops, meaning that the restart is not in a consistent state.

This was made considerably worse with commit d23cb648e365 ("mm/mremap:
permit mremap() move of multiple VMAs"), which can result in data loss if you encounter this issue.

Consider an mremap() specifying MREMAP_FIXED | MREMAP_DONTUNMAP of two KSM-mergeable VMAs, where a signal becomes pending part way through:

first pass restart
========== =======
unmap tgt1 range
copy src1 to tgt1, move page tables
unmap tgt2 range
break_ksm(src2) = -ERESTARTSYS
unmap tgt1 range, which now
holds the data from src1
copy the now-empty src1 to tgt1

This results in the user observing a successful mremap() but with src1's data missing.

Without MREMAP_DONTUNMAP, remap_move() would find a gap at the start of the range on restart and fail with -EFAULT there instead.

Fix the issue by only breaking out of an unmerge if a fatal signal is pending, returning -EINTR when we do. This makes KSM unmerging consistent with many other signal checks in mm.

Target commit d23cb648e365 ("mm/mremap: permit mremap() move of multiple VMAs") for the fix as this made the issue significantly more impactful.

Fixes d23cb648e365 ("mm/mremap: permit mremap() move of multiple VMAs")
---
 mm/ksm.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/ksm.c +0 -0
index 623a2cdb3924..5d320a200951 100644

mm/ksm.c static int break_ksm_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long en · line 634

Quoted 10 lines
mm/ksm.c +2 -2
@@ -627,8 +627,8 @@ static int break_ksm_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long en
 
 	if (ksm_test_exit(walk->mm))
 		return 0;
-	if (signal_pending(current))
-		return -ERESTARTSYS;
+	if (fatal_signal_pending(current))
+		return -EINTR;
 
 	start_ptep = pte_offset_map_lock(mm, pmdp, addr, &ptl);
 	if (!start_ptep)

Thanks, I'll queue this in mm-core for the next merge window.

Everything else can be merged by Andrew.

Signature · 3 lines
Cheers,

David
Tested-by Reviewed-by on v1 3/7
#14 lore raw

Re: [PATCH 3/7] mm/ksm: only interrupt unmerging on a fatal signal

In reply to Lorenzo Stoakes (ARM)
Quoted 42 lines · Lorenzo Stoakes (ARM)

Commit d952b79136a6 ("ksm: fix endless loop on oom") added a check for pending signals on KSM break, so that a lengthy unmerge could be interrupted, with the system call then restarted via -ERESTARTSYS.

However, it assumes that the callers can always restart whatever system call started it in the first place (the commit message questions whether this was wise).

Well, it turns out that it was not wise, as this baked in an implicit assumption about system call restartability, and it was and is not safe for mremap().

mremap() holds an mmap write lock over the operation, which an -ERESTARTSYS drops, meaning that the restart is not in a consistent state.

This was made considerably worse with commit d23cb648e365 ("mm/mremap:
permit mremap() move of multiple VMAs"), which can result in data loss if you encounter this issue.

Consider an mremap() specifying MREMAP_FIXED | MREMAP_DONTUNMAP of two KSM-mergeable VMAs, where a signal becomes pending part way through:

first pass restart
========== =======
unmap tgt1 range
copy src1 to tgt1, move page tables
unmap tgt2 range
break_ksm(src2) = -ERESTARTSYS
unmap tgt1 range, which now
holds the data from src1
copy the now-empty src1 to tgt1

This results in the user observing a successful mremap() but with src1's data missing.

Without MREMAP_DONTUNMAP, remap_move() would find a gap at the start of the range on restart and fail with -EFAULT there instead.

Fix the issue by only breaking out of an unmerge if a fatal signal is pending, returning -EINTR when we do. This makes KSM unmerging consistent with many other signal checks in mm.

Quoted 7 lines

Target commit d23cb648e365 ("mm/mremap: permit mremap() move of multiple VMAs") for the fix as this made the issue significantly more impactful.

Fixes d23cb648e365 ("mm/mremap: permit mremap() move of multiple VMAs")
Signature · 1 line
~Gregory
author maintainer
#15 lore raw

PATCH 4/7 mm/vma: fix uncharge after failed stack relocation

In reply to Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

An execve() that fails to relocate its stack can underflow vm_committed_as, and the commit limit of vm.overcommit_memory=2 then no longer holds.

exit_mmap() uncharges vma_pages() of each VMA with VMA_ACCOUNT_BIT, so the charge has to match the size of the VMA. relocate_vma_down() expands the stack VMA by the relocation distance without a charge, and relies on its vma_shrink() to make the two match again. But it returns with the VMA still expanded if move_page_tables() can't allocate a page table, for example at the memory cgroup limit, or if vma_shrink() fails:

    relocate_vma_down()             charged    vma_pages()
    ===================             =======    ===========
                                    L          L
    vma_expand()                    L          L + shift

move_page_tables() fails
return -ENOMEM

exit_mmap()
tear_down_vmas()
vm_unacct_memory(L + shift) -shift

On x86-64 with 4-level page tables, the distance is up to 16 GiB for a 64-bit program, and about 128 TiB for a 32-bit one.

Fix the issue by giving back the charge of the stack VMA where its relocation fails, and excluding the VMA from what exit_mmap() uncharges. The argument pages of the dying task are then outside the commit charge until exit_mmap() frees them.

Fixes b6a2fea39318 ("mm: variable length argument support")
---
 mm/vma_exec.c | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
mm/vma_exec.c +19 -3
index 586c52155942..84b98f1a201d 100644
@@ -45,6 +45,7 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
 	struct vm_area_struct *next;
 	struct mmu_gather tlb;
 	PAGETABLE_MOVE(pmc, vma, vma, old_start, new_start, length);
+	int err;
 
 	BUG_ON(new_start > new_end);
 
@@ -68,8 +69,10 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
 	 * process cleanup to remove whatever mess we made.
 	 */
 	pmc.for_stack = true;
-	if (length != move_page_tables(&pmc))
-		return -ENOMEM;
+	if (length != move_page_tables(&pmc)) {
+		err = -ENOMEM;
+		goto err_unacct;
+	}
 
 	tlb_gather_mmu(&tlb, mm);
 	next = vma_next(&vmi);
@@ -93,7 +96,20 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
 
 	vma_prev(&vmi);
 	/* Shrink the vma to just the new range */
-	return vma_shrink(&vmi, vma, new_end);
+	err = vma_shrink(&vmi, vma, new_end);
+	if (err)
+		goto err_unacct;
+
+	return 0;
+
+err_unacct:
+	/*
+	 * The vma now spans more than was charged, so exit_mmap() must not
+	 * derive the uncharge from its size.
+	 */
+	vm_unacct_memory(length >> PAGE_SHIFT);
+	vma_clear_flags(vma, VMA_ACCOUNT_BIT);
+	return err;
 }
 
 /*
Signature · 1 line
2.56.0
reviewer Reviewed-by on v1 4/7
#16 lore raw

Re: [PATCH 4/7] mm/vma: fix uncharge after failed stack relocation

Quoted 33 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

An execve() that fails to relocate its stack can underflow vm_committed_as, and the commit limit of vm.overcommit_memory=2 then no longer holds.

exit_mmap() uncharges vma_pages() of each VMA with VMA_ACCOUNT_BIT, so the charge has to match the size of the VMA. relocate_vma_down() expands the stack VMA by the relocation distance without a charge, and relies on its vma_shrink() to make the two match again. But it returns with the VMA still expanded if move_page_tables() can't allocate a page table, for example at the memory cgroup limit, or if vma_shrink() fails:

    relocate_vma_down()             charged    vma_pages()
    ===================             =======    ===========
                                    L          L
    vma_expand()                    L          L + shift

move_page_tables() fails
return -ENOMEM

exit_mmap()
tear_down_vmas()
vm_unacct_memory(L + shift) -shift

On x86-64 with 4-level page tables, the distance is up to 16 GiB for a 64-bit program, and about 128 TiB for a 32-bit one.

Fix the issue by giving back the charge of the stack VMA where its relocation fails, and excluding the VMA from what exit_mmap() uncharges. The argument pages of the dying task are then outside the commit charge until exit_mmap() frees them.

Quoted 4 lines
Fixes b6a2fea39318 ("mm: variable length argument support")
Quoted 55 lines
---
 mm/vma_exec.c | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
mm/vma_exec.c +19 -4
index 586c52155942..84b98f1a201d 100644
@@ -45,6 +45,7 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
        struct vm_area_struct *next;
        struct mmu_gather tlb;
        PAGETABLE_MOVE(pmc, vma, vma, old_start, new_start, length);
+       int err;
 
        BUG_ON(new_start > new_end);
 
@@ -68,8 +69,10 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
         * process cleanup to remove whatever mess we made.
         */
        pmc.for_stack = true;
-       if (length != move_page_tables(&pmc))
-               return -ENOMEM;
+       if (length != move_page_tables(&pmc)) {
+               err = -ENOMEM;
+               goto err_unacct;
+       }
 
        tlb_gather_mmu(&tlb, mm);
        next = vma_next(&vmi);
@@ -93,7 +96,20 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
 
        vma_prev(&vmi);
        /* Shrink the vma to just the new range */
-       return vma_shrink(&vmi, vma, new_end);
+       err = vma_shrink(&vmi, vma, new_end);
+       if (err)
+               goto err_unacct;
+
+       return 0;
+
+err_unacct:
+       /*
+        * The vma now spans more than was charged, so exit_mmap() must not
+        * derive the uncharge from its size.
+        */
+       vm_unacct_memory(length >> PAGE_SHIFT);
+       vma_clear_flags(vma, VMA_ACCOUNT_BIT);
+       return err;
 }
 
 /*
 
--

2.56.0

Tested-by Reviewed-by on v1 4/7
#17 lore raw

Re: [PATCH 4/7] mm/vma: fix uncharge after failed stack relocation

In reply to Lorenzo Stoakes (ARM)
Quoted 32 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

An execve() that fails to relocate its stack can underflow vm_committed_as, and the commit limit of vm.overcommit_memory=2 then no longer holds.

exit_mmap() uncharges vma_pages() of each VMA with VMA_ACCOUNT_BIT, so the charge has to match the size of the VMA. relocate_vma_down() expands the stack VMA by the relocation distance without a charge, and relies on its vma_shrink() to make the two match again. But it returns with the VMA still expanded if move_page_tables() can't allocate a page table, for example at the memory cgroup limit, or if vma_shrink() fails:

    relocate_vma_down()             charged    vma_pages()
    ===================             =======    ===========
                                    L          L
    vma_expand()                    L          L + shift

move_page_tables() fails
return -ENOMEM

exit_mmap()
tear_down_vmas()
vm_unacct_memory(L + shift) -shift

On x86-64 with 4-level page tables, the distance is up to 16 GiB for a 64-bit program, and about 128 TiB for a 32-bit one.

Fix the issue by giving back the charge of the stack VMA where its relocation fails, and excluding the VMA from what exit_mmap() uncharges. The argument pages of the dying task are then outside the commit charge until exit_mmap() frees them.

Quoted 4 lines
Fixes b6a2fea39318 ("mm: variable length argument support")
Signature · 1 line
~Gregory
#18 lore raw

Re: [PATCH 4/7] mm/vma: fix uncharge after failed stack relocation

In reply to Lorenzo Stoakes (ARM)
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] mm/vma: unaccounted writable VMA left mapped after relocate_vma_down() fails --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] mm/vma: unaccounted writable VMA left mapped after relocate_vma_down() fails
--

commit 9c6f7e9f77d24dc1b72d41f3c440f1ede99ab822
Author: Chris Mason <[email protected]>

mm/vma: fix uncharge after failed stack relocation

This commit uncharges the initial stack length and clears VMA_ACCOUNT_BIT when relocate_vma_down() fails after expanding the stack VMA, avoiding a vm_committed_as underflow in exit_mmap().

Quoted 35 lines
mm/vma_exec.c +10 -3
index 586c521559424..84b98f1a201d7 100644
@@ -45,6 +45,7 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
 	struct vm_area_struct *next;
 	struct mmu_gather tlb;
 	PAGETABLE_MOVE(pmc, vma, vma, old_start, new_start, length);
+	int err;
 
 	BUG_ON(new_start > new_end);
 
@@ -68,8 +69,10 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
 	 * process cleanup to remove whatever mess we made.
 	 */
 	pmc.for_stack = true;
-	if (length != move_page_tables(&pmc))
-		return -ENOMEM;
+	if (length != move_page_tables(&pmc)) {
+		err = -ENOMEM;
+		goto err_unacct;
+	}
 
 	tlb_gather_mmu(&tlb, mm);
 	next = vma_next(&vmi);
@@ -93,7 +96,20 @@ int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift)
 
 	vma_prev(&vmi);
 	/* Shrink the vma to just the new range */
-	return vma_shrink(&vmi, vma, new_end);
+	err = vma_shrink(&vmi, vma, new_end);
+	if (err)
+		goto err_unacct;
+
+	return 0;

mm/vma_exec.c int relocate_vma_down(struct vm_area_struct *vma, unsigned long shift) · line 113

Quoted 10 lines
mm/vma_exec.c +9 -0
+
+err_unacct:
+	/*
+	 * The vma now spans more than was charged, so exit_mmap() must not
+	 * derive the uncharge from its size.
+	 */
+	vm_unacct_memory(length >> PAGE_SHIFT);
+	vma_clear_flags(vma, VMA_ACCOUNT_BIT);
+	return err;
 }

[Severity: High]
Does clearing VMA_ACCOUNT_BIT here leave the expanded [new_start, old_end) stack VMA writable and unaccounted if the task does not immediately exit?

When execve() fails after bprm->point_of_no_return, bprm_execve() sends SIGSEGV via force_fatal_sig(SIGSEGV) rather than force_exit_sig(SIGSEGV), so SA_IMMUTABLE is not set. If the task is ptraced (for example via PTRACE_TRACEME) when a memory cgroup limit causes move_page_tables() or vma_shrink() to fail with -ENOMEM, get_signal() intercepts the SIGSEGV in ptrace_signal() and the tracer can suppress it by resuming with signal 0.

The task then survives in userspace with an unaccounted writable VMA of size length + shift (up to 16 GiB for 64-bit tasks or 128 TiB for 32-bit tasks on x86-64), allowing anonymous pages to be faulted in without charging vm_committed_as (bypassing vm.overcommit_memory=2) and underflowing mm->total_vm and mm->stack_vm (which remain at length >> PAGE_SHIFT) if the VMA is later unmapped.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
maintainer tree notice
#19 lore raw

+ mm-vma-fix-uncharge-after-failed-stack-relocation.patch added to mm-new branch

In reply to Lorenzo Stoakes (ARM)
The patch titled Subject: mm/vma: fix uncharge after failed stack relocation has been added to the -mm mm-new branch. Its filename is mm-vma-fix-uncharge-after-failed-stack-relocation.patch

The patch titled
Subject: mm/vma: fix uncharge after failed stack relocation
has been added to the -mm mm-new branch. Its filename is
mm-vma-fix-uncharge-after-failed-stack-relocation.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-vma-fix-uncharge-after-failed-stack-relocation.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Chris Mason <[email protected]>
Subject: mm/vma: fix uncharge after failed stack relocation
Date: Sat, 21 Nov 2026 16:02:30 +0000

An execve() that fails to relocate its stack can underflow vm_committed_as, and the commit limit of vm.overcommit_memory=2 then no longer holds.

exit_mmap() uncharges vma_pages() of each VMA with VMA_ACCOUNT_BIT, so the charge has to match the size of the VMA. relocate_vma_down() expands the stack VMA by the relocation distance without a charge, and relies on its vma_shrink() to make the two match again. But it returns with the VMA still expanded if move_page_tables() can't allocate a page table, for example at the memory cgroup limit, or if vma_shrink() fails:

    relocate_vma_down()             charged    vma_pages()
    ===================             =======    ===========
                                    L          L
    vma_expand()                    L          L + shift

move_page_tables() fails
return -ENOMEM

exit_mmap()
tear_down_vmas()
vm_unacct_memory(L + shift) -shift

On x86-64 with 4-level page tables, the distance is up to 16 GiB for a 64-bit program, and about 128 TiB for a 32-bit one.

Fix the issue by giving back the charge of the stack VMA where its relocation fails, and excluding the VMA from what exit_mmap() uncharges. The argument pages of the dying task are then outside the commit charge until exit_mmap() frees them.

Fixes b6a2fea39318 ("mm: variable length argument support")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Jann Horn <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Kees Cook <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Ollie Wild <[email protected]>
Cc Adrian Bunk <[email protected]>
Cc Xu Xin <[email protected]>
Cc Chengming Zhou <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Joey Gouly <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Josef Bacik <[email protected]>
Cc "Jose A. Perez de Azpillaga" <[email protected]>
 mm/vma_exec.c |   22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
mm/vma_exec.c renamed from mm/vma_exec.c~mm-vma-fix-uncharge-after-failed-stack-relocation +19 -3
@@ -45,6 +45,7 @@ int relocate_vma_down(struct vm_area_str
 	struct vm_area_struct *next;
 	struct mmu_gather tlb;
 	PAGETABLE_MOVE(pmc, vma, vma, old_start, new_start, length);
+	int err;
 
 	BUG_ON(new_start > new_end);
 
@@ -68,8 +69,10 @@ int relocate_vma_down(struct vm_area_str
 	 * process cleanup to remove whatever mess we made.
 	 */
 	pmc.for_stack = true;
-	if (length != move_page_tables(&pmc))
-		return -ENOMEM;
+	if (length != move_page_tables(&pmc)) {
+		err = -ENOMEM;
+		goto err_unacct;
+	}
 
 	tlb_gather_mmu(&tlb, mm);
 	next = vma_next(&vmi);
@@ -93,7 +96,20 @@ int relocate_vma_down(struct vm_area_str
 
 	vma_prev(&vmi);
 	/* Shrink the vma to just the new range */
-	return vma_shrink(&vmi, vma, new_end);
+	err = vma_shrink(&vmi, vma, new_end);
+	if (err)
+		goto err_unacct;
+
+	return 0;
+
+err_unacct:
+	/*
+	 * The vma now spans more than was charged, so exit_mmap() must not
+	 * derive the uncharge from its size.
+	 */
+	vm_unacct_memory(length >> PAGE_SHIFT);
+	vma_clear_flags(vma, VMA_ACCOUNT_BIT);
+	return err;
 }
 
 /*

_

Patches currently in -mm which might be from [email protected] are

mm-swap-fix-large-swap-in-across-swap-file-extents.patch hugetlbfs-do-not-grow-a-sealed-file-in-mmap.patch mm-hugetlb-keep-surplus-folios-that-are-reserved.patch mm-hugetlb-fix-reservation-leak-on-min_size=-mounts.patch mm-cachestat-count-each-page-only-once.patch mm-cachestat-restart-the-walk-after-each-entry.patch percpu-queue-the-balance-work-on-an-unbound-workqueue.patch mm-vma-fix-uncharge-after-failed-stack-relocation.patch mm-mremap-apply-the-mmap-offset-limits-on-expansion.patch mm-mremap-respect-guard-gaps-on-in-place-expansion.patch mm-vma-make-brk-mappings-non-executable-under-mdwe.patch

author maintainer
#20 lore raw

PATCH 5/7 mm/mremap: apply the mmap() offset limits on expansion

In reply to Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

Commit be83bbf80682 ("mmap: introduce sane default mmap limits") made do_mmap() reject file mappings which extend beyond the maximum offset the file can support, via file_mmap_ok().

However mremap() can expand a file mapping and only checks that the page offset does not wrap, so a mapping can be grown past the limit that mmap() would have enforced.

Fault handlers rely on that limit. For instance dax_iomap_pte_fault() converts vmf->pgoff into a loff_t, which overflows for such an offset and defeats its i_size check.

Fix the issue by applying file_mmap_ok() to the expanded range in check_prep_vma(), failing the mremap() with -EINVAL if it exceeds the limit.

This means that mremap() now refuses expansions it previously permitted, however no file can have data at these offsets, and mmap() already refuses the equivalent mapping.

Fixes be83bbf80682 ("mmap: introduce sane default mmap limits")
[ ljs: fixed up commit msg ]
---
 mm/internal.h | 2 ++
 mm/mmap.c     | 4 ++--
 mm/mremap.c   | 6 ++++++
 3 files changed, 10 insertions(+), 2 deletions(-)
mm/internal.h +2 -0
index a09dbdfd615d..aa7fba0a1c41 100644
@@ -941,6 +941,8 @@ extern long faultin_page_range(struct mm_struct *mm, unsigned long start,
 		unsigned long end, bool write, int *locked);
 bool mlock_future_ok(const struct mm_struct *mm, bool is_vma_locked,
 		unsigned long bytes);
+bool file_mmap_ok(struct file *file, struct inode *inode, unsigned long pgoff,
+		  unsigned long len);
 
 /*
  * NOTE: This function can't tell whether the folio is "fully mapped" in the
mm/mmap.c +2 -2
index 7618e72766a5..79702841c06c 100644
@@ -264,8 +264,8 @@ static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
 	return ULONG_MAX;
 }
 
-static inline bool file_mmap_ok(struct file *file, struct inode *inode,
-				unsigned long pgoff, unsigned long len)
+bool file_mmap_ok(struct file *file, struct inode *inode, unsigned long pgoff,
+		  unsigned long len)
 {
 	u64 maxsize = file_mmap_size_max(file, inode);
 
mm/mremap.c +6 -0
index fff0465f5e06..8043c425b5df 100644
@@ -1791,6 +1791,7 @@ static int check_prep_vma(struct vma_remap_struct *vrm)
 	struct mm_struct *mm = current->mm;
 	unsigned long addr = vrm->addr;
 	unsigned long old_len, new_len, pgoff;
+	struct file *file;
 
 	if (!vma)
 		return -EFAULT;
@@ -1870,6 +1871,11 @@ static int check_prep_vma(struct vma_remap_struct *vrm)
 	if (vma_is_fixed_mapping(vma))
 		return -EFAULT;
 
+	/* The expanded range must obey the same offset limits as mmap(). */
+	file = vma->vm_file;
+	if (file && !file_mmap_ok(file, file_inode(file), pgoff, new_len))
+		return -EINVAL;
+
 	if (!mlock_future_ok(mm, vma_test(vma, VMA_LOCKED_BIT), vrm->delta))
 		return -EAGAIN;
 
Signature · 1 line
2.56.0
reviewer Reviewed-by on v1 5/7
#21 lore raw

Re: [PATCH 5/7] mm/mremap: apply the mmap() offset limits on expansion

Quoted 23 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

Commit be83bbf80682 ("mmap: introduce sane default mmap limits") made do_mmap() reject file mappings which extend beyond the maximum offset the file can support, via file_mmap_ok().

However mremap() can expand a file mapping and only checks that the page offset does not wrap, so a mapping can be grown past the limit that mmap() would have enforced.

Fault handlers rely on that limit. For instance dax_iomap_pte_fault() converts vmf->pgoff into a loff_t, which overflows for such an offset and defeats its i_size check.

Fix the issue by applying file_mmap_ok() to the expanded range in check_prep_vma(), failing the mremap() with -EINVAL if it exceeds the limit.

This means that mremap() now refuses expansions it previously permitted, however no file can have data at these offsets, and mmap() already refuses the equivalent mapping.

Quoted 5 lines
Fixes be83bbf80682 ("mmap: introduce sane default mmap limits")
[ ljs: fixed up commit msg ]
Quoted 62 lines
---
 mm/internal.h | 2 ++
 mm/mmap.c     | 4 ++--
 mm/mremap.c   | 6 ++++++
 3 files changed, 10 insertions(+), 2 deletions(-)
mm/internal.h +2 -0
index a09dbdfd615d..aa7fba0a1c41 100644
@@ -941,6 +941,8 @@ extern long faultin_page_range(struct mm_struct *mm, unsigned long start,
                unsigned long end, bool write, int *locked);
 bool mlock_future_ok(const struct mm_struct *mm, bool is_vma_locked,
                unsigned long bytes);
+bool file_mmap_ok(struct file *file, struct inode *inode, unsigned long pgoff,
+                 unsigned long len);
 
 /*
  * NOTE: This function can't tell whether the folio is "fully mapped" in the
mm/mmap.c +2 -2
index 7618e72766a5..79702841c06c 100644
@@ -264,8 +264,8 @@ static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
        return ULONG_MAX;
 }
 
-static inline bool file_mmap_ok(struct file *file, struct inode *inode,
-                               unsigned long pgoff, unsigned long len)
+bool file_mmap_ok(struct file *file, struct inode *inode, unsigned long pgoff,
+                 unsigned long len)
 {
        u64 maxsize = file_mmap_size_max(file, inode);
 
mm/mremap.c +6 -1
index fff0465f5e06..8043c425b5df 100644
@@ -1791,6 +1791,7 @@ static int check_prep_vma(struct vma_remap_struct *vrm)
        struct mm_struct *mm = current->mm;
        unsigned long addr = vrm->addr;
        unsigned long old_len, new_len, pgoff;
+       struct file *file;
 
        if (!vma)
                return -EFAULT;
@@ -1870,6 +1871,11 @@ static int check_prep_vma(struct vma_remap_struct *vrm)
        if (vma_is_fixed_mapping(vma))
                return -EFAULT;
 
+       /* The expanded range must obey the same offset limits as mmap(). */
+       file = vma->vm_file;
+       if (file && !file_mmap_ok(file, file_inode(file), pgoff, new_len))
+               return -EINVAL;
+
        if (!mlock_future_ok(mm, vma_test(vma, VMA_LOCKED_BIT), vrm->delta))
                return -EAGAIN;
 
 
--

2.56.0

Tested-by Reviewed-by on v1 5/7
#22 lore raw

Re: [PATCH 5/7] mm/mremap: apply the mmap() offset limits on expansion

In reply to Lorenzo Stoakes (ARM)
Quoted 22 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

Commit be83bbf80682 ("mmap: introduce sane default mmap limits") made do_mmap() reject file mappings which extend beyond the maximum offset the file can support, via file_mmap_ok().

However mremap() can expand a file mapping and only checks that the page offset does not wrap, so a mapping can be grown past the limit that mmap() would have enforced.

Fault handlers rely on that limit. For instance dax_iomap_pte_fault() converts vmf->pgoff into a loff_t, which overflows for such an offset and defeats its i_size check.

Fix the issue by applying file_mmap_ok() to the expanded range in check_prep_vma(), failing the mremap() with -EINVAL if it exceeds the limit.

This means that mremap() now refuses expansions it previously permitted, however no file can have data at these offsets, and mmap() already refuses the equivalent mapping.

Quoted 5 lines
Fixes be83bbf80682 ("mmap: introduce sane default mmap limits")
[ ljs: fixed up commit msg ]
Signature · 1 line
~Gregory
Reviewed-by on v1 5/7
#23 lore raw

Re: [PATCH 5/7] mm/mremap: apply the mmap() offset limits on expansion

In reply to Lorenzo Stoakes (ARM)
Quoted 22 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

Commit be83bbf80682 ("mmap: introduce sane default mmap limits") made do_mmap() reject file mappings which extend beyond the maximum offset the file can support, via file_mmap_ok().

However mremap() can expand a file mapping and only checks that the page offset does not wrap, so a mapping can be grown past the limit that mmap() would have enforced.

Fault handlers rely on that limit. For instance dax_iomap_pte_fault() converts vmf->pgoff into a loff_t, which overflows for such an offset and defeats its i_size check.

Fix the issue by applying file_mmap_ok() to the expanded range in check_prep_vma(), failing the mremap() with -EINVAL if it exceeds the limit.

This means that mremap() now refuses expansions it previously permitted, however no file can have data at these offsets, and mmap() already refuses the equivalent mapping.

Quoted 5 lines
Fixes be83bbf80682 ("mmap: introduce sane default mmap limits")
[ ljs: fixed up commit msg ]

LGTM:

Signature · 2 lines
cheers,
jose a. p-a
maintainer tree notice
#24 lore raw

+ mm-mremap-apply-the-mmap-offset-limits-on-expansion.patch added to mm-new branch

In reply to Lorenzo Stoakes (ARM)
The patch titled Subject: mm/mremap: apply the mmap() offset limits on expansion has been added to the -mm mm-new branch. Its filename is mm-mremap-apply-the-mmap-offset-limits-on-expansion.patch

The patch titled
Subject: mm/mremap: apply the mmap() offset limits on expansion
has been added to the -mm mm-new branch. Its filename is
mm-mremap-apply-the-mmap-offset-limits-on-expansion.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mremap-apply-the-mmap-offset-limits-on-expansion.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Chris Mason <[email protected]>
Subject: mm/mremap: apply the mmap() offset limits on expansion
Date: Sat, 21 Nov 2026 16:02:31 +0000

Commit be83bbf80682 ("mmap: introduce sane default mmap limits") made do_mmap() reject file mappings which extend beyond the maximum offset the file can support, via file_mmap_ok().

However mremap() can expand a file mapping and only checks that the page offset does not wrap, so a mapping can be grown past the limit that mmap() would have enforced.

Fault handlers rely on that limit. For instance dax_iomap_pte_fault() converts vmf->pgoff into a loff_t, which overflows for such an offset and defeats its i_size check.

Fix the issue by applying file_mmap_ok() to the expanded range in check_prep_vma(), failing the mremap() with -EINVAL if it exceeds the limit.

This means that mremap() now refuses expansions it previously permitted, however no file can have data at these offsets, and mmap() already refuses the equivalent mapping.

[[email protected]: fixed up commit msg]
Fixes be83bbf80682 ("mmap: introduce sane default mmap limits")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Jann Horn <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Kees Cook <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Ollie Wild <[email protected]>
Cc Adrian Bunk <[email protected]>
Cc Xu Xin <[email protected]>
Cc Chengming Zhou <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Joey Gouly <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Josef Bacik <[email protected]>
 mm/internal.h |    2 ++
 mm/mmap.c     |    4 ++--
 mm/mremap.c   |    6 ++++++
 3 files changed, 10 insertions(+), 2 deletions(-)
mm/internal.h renamed from mm/internal.h~mm-mremap-apply-the-mmap-offset-limits-on-expansion +2 -0
@@ -950,6 +950,8 @@ extern long faultin_page_range(struct mm
 		unsigned long end, bool write, int *locked);
 bool mlock_future_ok(const struct mm_struct *mm, bool is_vma_locked,
 		unsigned long bytes);
+bool file_mmap_ok(struct file *file, struct inode *inode, unsigned long pgoff,
+		  unsigned long len);
 
 /*
  * NOTE: This function can't tell whether the folio is "fully mapped" in the
mm/mmap.c renamed from mm/mmap.c~mm-mremap-apply-the-mmap-offset-limits-on-expansion +2 -2
@@ -265,8 +265,8 @@ static inline u64 file_mmap_size_max(str
 	return ULONG_MAX;
 }
 
-static inline bool file_mmap_ok(struct file *file, struct inode *inode,
-				unsigned long pgoff, unsigned long len)
+bool file_mmap_ok(struct file *file, struct inode *inode, unsigned long pgoff,
+		  unsigned long len)
 {
 	u64 maxsize = file_mmap_size_max(file, inode);
 
mm/mremap.c renamed from mm/mremap.c~mm-mremap-apply-the-mmap-offset-limits-on-expansion +6 -0
@@ -1748,6 +1748,7 @@ static int check_prep_vma(struct vma_rem
 	struct mm_struct *mm = current->mm;
 	unsigned long addr = vrm->addr;
 	unsigned long old_len, new_len, pgoff;
+	struct file *file;
 
 	if (!vma)
 		return -EFAULT;
@@ -1827,6 +1828,11 @@ static int check_prep_vma(struct vma_rem
 	if (vma_is_fixed_mapping(vma))
 		return -EFAULT;
 
+	/* The expanded range must obey the same offset limits as mmap(). */
+	file = vma->vm_file;
+	if (file && !file_mmap_ok(file, file_inode(file), pgoff, new_len))
+		return -EINVAL;
+
 	if (!mlock_future_ok(mm, vma_test(vma, VMA_LOCKED_BIT), vrm->delta))
 		return -EAGAIN;
 

_

Patches currently in -mm which might be from [email protected] are

mm-swap-fix-large-swap-in-across-swap-file-extents.patch hugetlbfs-do-not-grow-a-sealed-file-in-mmap.patch mm-hugetlb-keep-surplus-folios-that-are-reserved.patch mm-hugetlb-fix-reservation-leak-on-min_size=-mounts.patch mm-cachestat-count-each-page-only-once.patch mm-cachestat-restart-the-walk-after-each-entry.patch percpu-queue-the-balance-work-on-an-unbound-workqueue.patch mm-vma-fix-uncharge-after-failed-stack-relocation.patch mm-mremap-apply-the-mmap-offset-limits-on-expansion.patch mm-mremap-respect-guard-gaps-on-in-place-expansion.patch mm-vma-make-brk-mappings-non-executable-under-mdwe.patch

author maintainer
#25 lore raw

PATCH 6/7 mm/mremap: respect guard gaps on in-place expansion

In reply to Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

Growing a mapping in place can let it use up the guard gap below a stack, so that the stack can't grow any further, or overflows into the mapping instead of faulting.

A mapping has to stay out of the gap of the next VMA unless the caller fixed its address. But vma_expandable() only checks that the new range doesn't intersect the next VMA, and it passes MAP_FIXED to get_unmapped_area(), which skips the gap check there.

Fix the issue by stopping in-place growth at the start of the gap.

Growing a mapping into or within the gap of a stack or shadow stack now fails with ENOMEM without MREMAP_MAYMOVE, or if the mapping can't be moved.

Fixes 1be7107fbe18 ("mm: larger stack guard gap, between vmas")
---
 mm/mremap.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/mremap.c +3 -1
index 8043c425b5df..2460f9421a13 100644
@@ -1552,10 +1552,12 @@ static unsigned long mremap_to(struct vma_remap_struct *vrm)
 static int vma_expandable(struct vm_area_struct *vma, unsigned long delta)
 {
 	unsigned long end = vma->vm_end + delta;
+	struct vm_area_struct *next;
 
 	if (end < vma->vm_end) /* overflow */
 		return 0;
-	if (find_vma_intersection(vma->vm_mm, vma->vm_end, end))
+	next = find_vma(vma->vm_mm, vma->vm_end);
+	if (next && end > vm_start_gap(next)) /* intersection, or in its gap */
 		return 0;
 	if (get_unmapped_area(NULL, vma->vm_start, end - vma->vm_start,
 			      0, MAP_FIXED) & ~PAGE_MASK)
Signature · 1 line
2.56.0
reviewer Reviewed-by on v1 6/7
#26 lore raw

Re: [PATCH 6/7] mm/mremap: respect guard gaps on in-place expansion

Quoted 14 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

Growing a mapping in place can let it use up the guard gap below a stack, so that the stack can't grow any further, or overflows into the mapping instead of faulting.

A mapping has to stay out of the gap of the next VMA unless the caller fixed its address. But vma_expandable() only checks that the new range doesn't intersect the next VMA, and it passes MAP_FIXED to get_unmapped_area(), which skips the gap check there.

Fix the issue by stopping in-place growth at the start of the gap.

Quoted 7 lines

Growing a mapping into or within the gap of a stack or shadow stack now fails with ENOMEM without MREMAP_MAYMOVE, or if the mapping can't be moved.

Fixes 1be7107fbe18 ("mm: larger stack guard gap, between vmas")
Quoted 26 lines
---
 mm/mremap.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/mremap.c +3 -2
index 8043c425b5df..2460f9421a13 100644
@@ -1552,10 +1552,12 @@ static unsigned long mremap_to(struct vma_remap_struct *vrm)
 static int vma_expandable(struct vm_area_struct *vma, unsigned long delta)
 {
        unsigned long end = vma->vm_end + delta;
+       struct vm_area_struct *next;
 
        if (end < vma->vm_end) /* overflow */
                return 0;
-       if (find_vma_intersection(vma->vm_mm, vma->vm_end, end))
+       next = find_vma(vma->vm_mm, vma->vm_end);
+       if (next && end > vm_start_gap(next)) /* intersection, or in its gap */
                return 0;
        if (get_unmapped_area(NULL, vma->vm_start, end - vma->vm_start,
                              0, MAP_FIXED) & ~PAGE_MASK)
 
--

2.56.0

Tested-by Reviewed-by on v1 6/7
#27 lore raw

Re: [PATCH 6/7] mm/mremap: respect guard gaps on in-place expansion

In reply to Lorenzo Stoakes (ARM)
Quoted 13 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

Growing a mapping in place can let it use up the guard gap below a stack, so that the stack can't grow any further, or overflows into the mapping instead of faulting.

A mapping has to stay out of the gap of the next VMA unless the caller fixed its address. But vma_expandable() only checks that the new range doesn't intersect the next VMA, and it passes MAP_FIXED to get_unmapped_area(), which skips the gap check there.

Fix the issue by stopping in-place growth at the start of the gap.

Quoted 7 lines

Growing a mapping into or within the gap of a stack or shadow stack now fails with ENOMEM without MREMAP_MAYMOVE, or if the mapping can't be moved.

Fixes 1be7107fbe18 ("mm: larger stack guard gap, between vmas")
Signature · 1 line
~Gregory
Reviewed-by on v1 6/7
#28 lore raw

Re: [PATCH 6/7] mm/mremap: respect guard gaps on in-place expansion

In reply to Lorenzo Stoakes (ARM)
Quoted 13 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

Growing a mapping in place can let it use up the guard gap below a stack, so that the stack can't grow any further, or overflows into the mapping instead of faulting.

A mapping has to stay out of the gap of the next VMA unless the caller fixed its address. But vma_expandable() only checks that the new range doesn't intersect the next VMA, and it passes MAP_FIXED to get_unmapped_area(), which skips the gap check there.

Fix the issue by stopping in-place growth at the start of the gap.

Quoted 7 lines

Growing a mapping into or within the gap of a stack or shadow stack now fails with ENOMEM without MREMAP_MAYMOVE, or if the mapping can't be moved.

Fixes 1be7107fbe18 ("mm: larger stack guard gap, between vmas")

LGTM:

Signature · 2 lines
cheers,
jose a. p-a
maintainer tree notice
#29 lore raw

+ mm-mremap-respect-guard-gaps-on-in-place-expansion.patch added to mm-new branch

In reply to Lorenzo Stoakes (ARM)
The patch titled Subject: mm/mremap: respect guard gaps on in-place expansion has been added to the -mm mm-new branch. Its filename is mm-mremap-respect-guard-gaps-on-in-place-expansion.patch

The patch titled
Subject: mm/mremap: respect guard gaps on in-place expansion
has been added to the -mm mm-new branch. Its filename is
mm-mremap-respect-guard-gaps-on-in-place-expansion.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-mremap-respect-guard-gaps-on-in-place-expansion.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Chris Mason <[email protected]>
Subject: mm/mremap: respect guard gaps on in-place expansion
Date: Sat, 21 Nov 2026 16:02:32 +0000

Growing a mapping in place can let it use up the guard gap below a stack, so that the stack can't grow any further, or overflows into the mapping instead of faulting.

A mapping has to stay out of the gap of the next VMA unless the caller fixed its address. But vma_expandable() only checks that the new range doesn't intersect the next VMA, and it passes MAP_FIXED to get_unmapped_area(), which skips the gap check there.

Fix the issue by stopping in-place growth at the start of the gap.

Growing a mapping into or within the gap of a stack or shadow stack now fails with ENOMEM without MREMAP_MAYMOVE, or if the mapping can't be moved.

Fixes 1be7107fbe18 ("mm: larger stack guard gap, between vmas")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Jann Horn <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Kees Cook <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Ollie Wild <[email protected]>
Cc Adrian Bunk <[email protected]>
Cc Xu Xin <[email protected]>
Cc Chengming Zhou <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Joey Gouly <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Josef Bacik <[email protected]>
 mm/mremap.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/mremap.c renamed from mm/mremap.c~mm-mremap-respect-guard-gaps-on-in-place-expansion +3 -1
@@ -1509,10 +1509,12 @@ static unsigned long mremap_to(struct vm
 static int vma_expandable(struct vm_area_struct *vma, unsigned long delta)
 {
 	unsigned long end = vma->vm_end + delta;
+	struct vm_area_struct *next;
 
 	if (end < vma->vm_end) /* overflow */
 		return 0;
-	if (find_vma_intersection(vma->vm_mm, vma->vm_end, end))
+	next = find_vma(vma->vm_mm, vma->vm_end);
+	if (next && end > vm_start_gap(next)) /* intersection, or in its gap */
 		return 0;
 	if (get_unmapped_area(NULL, vma->vm_start, end - vma->vm_start,
 			      0, MAP_FIXED) & ~PAGE_MASK)

_

Patches currently in -mm which might be from [email protected] are

mm-swap-fix-large-swap-in-across-swap-file-extents.patch hugetlbfs-do-not-grow-a-sealed-file-in-mmap.patch mm-hugetlb-keep-surplus-folios-that-are-reserved.patch mm-hugetlb-fix-reservation-leak-on-min_size=-mounts.patch mm-cachestat-count-each-page-only-once.patch mm-cachestat-restart-the-walk-after-each-entry.patch percpu-queue-the-balance-work-on-an-unbound-workqueue.patch mm-vma-fix-uncharge-after-failed-stack-relocation.patch mm-mremap-apply-the-mmap-offset-limits-on-expansion.patch mm-mremap-respect-guard-gaps-on-in-place-expansion.patch mm-vma-make-brk-mappings-non-executable-under-mdwe.patch

author maintainer
#30 lore raw

PATCH 7/7 mm/vma: make brk mappings non-executable under MDWE

In reply to Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

With PR_SET_MDWE in effect, brk() and the ELF loader can still create anonymous mappings that are both writable and executable.

MDWE only holds if every path that decides the flags of a VMA asks map_deny_write_exec(). mmap_region() and do_mprotect_pkey() do, but do_brk_flags() does not. It always sets VMA_WRITE_BIT, and it gets VMA_EXEC_BIT in any of these cases:

VMA_DATA_DEFAULT_FLAGS is
VMA_DATA_FLAGS_TSK_EXEC the personality has READ_IMPLIES_EXEC
(e.g. x86, arm, arm64, mips)
VMA_DATA_FLAGS_EXEC always
(the default, e.g. m68k, sh, sparc)
vm_brk_flags(is_exec) elf_load() of a PT_LOAD with PF_X and
p_memsz > p_filesz

Fix the issue by dropping VMA_EXEC_BIT if MDWE is in effect, so that brk() and execve() keep working where the bit is only a default.

Under MDWE, a task that runs code from its heap, or from the part of an executable PT_LOAD beyond p_filesz, now gets SIGSEGV in the cases above.

mprotect(PROT_READ | PROT_EXEC) on these mappings now fails with -EACCES. While the personality has READ_IMPLIES_EXEC, so does mprotect(PROT_READ), as on any other anonymous mapping that is not executable.

Fixes b507808ebce2 ("mm: implement memory-deny-write-execute as a prctl")
[ ljs: switched to MMF_HAS_MDWE test, tweaked commit msg ]
---
 mm/vma.c | 4 ++++
 1 file changed, 4 insertions(+)
mm/vma.c +4 -0
index f8cf319ff9cf..a8b8101ff781 100644
@@ -3235,6 +3235,10 @@ int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
 	vma_flags_set(&vma_flags, VMA_ACCOUNT_BIT);
 	vma_flags_set_mask(&vma_flags, mm->def_vma_flags);
 
+	/* The flags are implied, so under MDWE drop exec rather than fail. */
+	if (mm_flags_test(MMF_HAS_MDWE, mm))
+		vma_flags_clear(&vma_flags, VMA_EXEC_BIT);
+
 	vma_flags = ksm_vma_flags(mm, NULL, vma_flags);
 	if (!may_expand_vm(mm, &vma_flags, len >> PAGE_SHIFT))
 		return -ENOMEM;
Signature · 1 line
2.56.0
reviewer Reviewed-by on v1 7/7
#31 lore raw

Re: [PATCH 7/7] mm/vma: make brk mappings non-executable under MDWE

Quoted 30 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

With PR_SET_MDWE in effect, brk() and the ELF loader can still create anonymous mappings that are both writable and executable.

MDWE only holds if every path that decides the flags of a VMA asks map_deny_write_exec(). mmap_region() and do_mprotect_pkey() do, but do_brk_flags() does not. It always sets VMA_WRITE_BIT, and it gets VMA_EXEC_BIT in any of these cases:

VMA_DATA_DEFAULT_FLAGS is
VMA_DATA_FLAGS_TSK_EXEC the personality has READ_IMPLIES_EXEC
(e.g. x86, arm, arm64, mips)
VMA_DATA_FLAGS_EXEC always
(the default, e.g. m68k, sh, sparc)
vm_brk_flags(is_exec) elf_load() of a PT_LOAD with PF_X and
p_memsz > p_filesz

Fix the issue by dropping VMA_EXEC_BIT if MDWE is in effect, so that brk() and execve() keep working where the bit is only a default.

Under MDWE, a task that runs code from its heap, or from the part of an executable PT_LOAD beyond p_filesz, now gets SIGSEGV in the cases above.

mprotect(PROT_READ | PROT_EXEC) on these mappings now fails with -EACCES. While the personality has READ_IMPLIES_EXEC, so does mprotect(PROT_READ), as on any other anonymous mapping that is not executable.

Quoted 4 lines
Fixes b507808ebce2 ("mm: implement memory-deny-write-execute as a prctl")
[ ljs: switched to MMF_HAS_MDWE test, tweaked commit msg ]
Quoted 23 lines
---
 mm/vma.c | 4 ++++
 1 file changed, 4 insertions(+)
mm/vma.c +4 -1
index f8cf319ff9cf..a8b8101ff781 100644
@@ -3235,6 +3235,10 @@ int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
        vma_flags_set(&vma_flags, VMA_ACCOUNT_BIT);
        vma_flags_set_mask(&vma_flags, mm->def_vma_flags);
 
+       /* The flags are implied, so under MDWE drop exec rather than fail. */
+       if (mm_flags_test(MMF_HAS_MDWE, mm))
+               vma_flags_clear(&vma_flags, VMA_EXEC_BIT);
+
        vma_flags = ksm_vma_flags(mm, NULL, vma_flags);
        if (!may_expand_vm(mm, &vma_flags, len >> PAGE_SHIFT))
                return -ENOMEM;
 
--

2.56.0

Tested-by Reviewed-by on v1 7/7
#32 lore raw

Re: [PATCH 7/7] mm/vma: make brk mappings non-executable under MDWE

In reply to Lorenzo Stoakes (ARM)
Quoted 29 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

With PR_SET_MDWE in effect, brk() and the ELF loader can still create anonymous mappings that are both writable and executable.

MDWE only holds if every path that decides the flags of a VMA asks map_deny_write_exec(). mmap_region() and do_mprotect_pkey() do, but do_brk_flags() does not. It always sets VMA_WRITE_BIT, and it gets VMA_EXEC_BIT in any of these cases:

VMA_DATA_DEFAULT_FLAGS is
VMA_DATA_FLAGS_TSK_EXEC the personality has READ_IMPLIES_EXEC
(e.g. x86, arm, arm64, mips)
VMA_DATA_FLAGS_EXEC always
(the default, e.g. m68k, sh, sparc)
vm_brk_flags(is_exec) elf_load() of a PT_LOAD with PF_X and
p_memsz > p_filesz

Fix the issue by dropping VMA_EXEC_BIT if MDWE is in effect, so that brk() and execve() keep working where the bit is only a default.

Under MDWE, a task that runs code from its heap, or from the part of an executable PT_LOAD beyond p_filesz, now gets SIGSEGV in the cases above.

mprotect(PROT_READ | PROT_EXEC) on these mappings now fails with -EACCES. While the personality has READ_IMPLIES_EXEC, so does mprotect(PROT_READ), as on any other anonymous mapping that is not executable.

Quoted 4 lines
Fixes b507808ebce2 ("mm: implement memory-deny-write-execute as a prctl")
[ ljs: switched to MMF_HAS_MDWE test, tweaked commit msg ]

this is a pretty bad bug, should probably consider stable. I would hope no one is actually dependent on this behavior.

Signature · 1 line
~Gregory
Reviewed-by on v1 7/7
#33 lore raw

Re: [PATCH 7/7] mm/vma: make brk mappings non-executable under MDWE

In reply to Lorenzo Stoakes (ARM)
Quoted 29 lines · Lorenzo Stoakes (ARM)

From: Chris Mason <[email protected]>

With PR_SET_MDWE in effect, brk() and the ELF loader can still create anonymous mappings that are both writable and executable.

MDWE only holds if every path that decides the flags of a VMA asks map_deny_write_exec(). mmap_region() and do_mprotect_pkey() do, but do_brk_flags() does not. It always sets VMA_WRITE_BIT, and it gets VMA_EXEC_BIT in any of these cases:

VMA_DATA_DEFAULT_FLAGS is
VMA_DATA_FLAGS_TSK_EXEC the personality has READ_IMPLIES_EXEC
(e.g. x86, arm, arm64, mips)
VMA_DATA_FLAGS_EXEC always
(the default, e.g. m68k, sh, sparc)
vm_brk_flags(is_exec) elf_load() of a PT_LOAD with PF_X and
p_memsz > p_filesz

Fix the issue by dropping VMA_EXEC_BIT if MDWE is in effect, so that brk() and execve() keep working where the bit is only a default.

Under MDWE, a task that runs code from its heap, or from the part of an executable PT_LOAD beyond p_filesz, now gets SIGSEGV in the cases above.

mprotect(PROT_READ | PROT_EXEC) on these mappings now fails with -EACCES. While the personality has READ_IMPLIES_EXEC, so does mprotect(PROT_READ), as on any other anonymous mapping that is not executable.

Quoted 4 lines
Fixes b507808ebce2 ("mm: implement memory-deny-write-execute as a prctl")
[ ljs: switched to MMF_HAS_MDWE test, tweaked commit msg ]

LGTM:

Signature · 2 lines
cheers,
jose a. p-a
maintainer tree notice
#34 lore raw

+ mm-vma-make-brk-mappings-non-executable-under-mdwe.patch added to mm-new branch

In reply to Lorenzo Stoakes (ARM)
The patch titled Subject: mm/vma: make brk mappings non-executable under MDWE has been added to the -mm mm-new branch. Its filename is mm-vma-make-brk-mappings-non-executable-under-mdwe.patch

The patch titled
Subject: mm/vma: make brk mappings non-executable under MDWE
has been added to the -mm mm-new branch. Its filename is
mm-vma-make-brk-mappings-non-executable-under-mdwe.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-vma-make-brk-mappings-non-executable-under-mdwe.patch

This patch will later appear in the mm-new branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Note, mm-new is a provisional staging ground for work-in-progress patches, and acceptance into mm-new is a notification for others take notice and to finish up reviews. Please do not hesitate to respond to review feedback and post updated versions to replace or incrementally fixup patches in mm-new.

The mm-new branch of mm.git is not included in linux-next

If a few days of testing in mm-new is successful, the patch will me moved into mm.git's mm-unstable branch, which is included in linux-next

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: Chris Mason <[email protected]>
Subject: mm/vma: make brk mappings non-executable under MDWE
Date: Sat, 21 Nov 2026 16:02:33 +0000

With PR_SET_MDWE in effect, brk() and the ELF loader can still create anonymous mappings that are both writable and executable.

MDWE only holds if every path that decides the flags of a VMA asks map_deny_write_exec(). mmap_region() and do_mprotect_pkey() do, but do_brk_flags() does not. It always sets VMA_WRITE_BIT, and it gets VMA_EXEC_BIT in any of these cases:

VMA_DATA_DEFAULT_FLAGS is
VMA_DATA_FLAGS_TSK_EXEC the personality has READ_IMPLIES_EXEC
(e.g. x86, arm, arm64, mips)
VMA_DATA_FLAGS_EXEC always
(the default, e.g. m68k, sh, sparc)
vm_brk_flags(is_exec) elf_load() of a PT_LOAD with PF_X and
p_memsz > p_filesz

Fix the issue by dropping VMA_EXEC_BIT if MDWE is in effect, so that brk() and execve() keep working where the bit is only a default.

Under MDWE, a task that runs code from its heap, or from the part of an executable PT_LOAD beyond p_filesz, now gets SIGSEGV in the cases above.

mprotect(PROT_READ | PROT_EXEC) on these mappings now fails with -EACCES. While the personality has READ_IMPLIES_EXEC, so does mprotect(PROT_READ), as on any other anonymous mapping that is not executable.

[[email protected]: switched to MMF_HAS_MDWE test, tweaked commit msg]
Fixes b507808ebce2 ("mm: implement memory-deny-write-execute as a prctl")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Jann Horn <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Kees Cook <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Ollie Wild <[email protected]>
Cc Adrian Bunk <[email protected]>
Cc Xu Xin <[email protected]>
Cc Chengming Zhou <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Joey Gouly <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Josef Bacik <[email protected]>
 mm/vma.c |    4 ++++
 1 file changed, 4 insertions(+)
mm/vma.c renamed from mm/vma.c~mm-vma-make-brk-mappings-non-executable-under-mdwe +4 -0
@@ -3235,6 +3235,10 @@ int do_brk_flags(struct vma_iterator *vm
 	vma_flags_set(&vma_flags, VMA_ACCOUNT_BIT);
 	vma_flags_set_mask(&vma_flags, mm->def_vma_flags);
 
+	/* The flags are implied, so under MDWE drop exec rather than fail. */
+	if (mm_flags_test(MMF_HAS_MDWE, mm))
+		vma_flags_clear(&vma_flags, VMA_EXEC_BIT);
+
 	vma_flags = ksm_vma_flags(mm, NULL, vma_flags);
 	if (!may_expand_vm(mm, &vma_flags, len >> PAGE_SHIFT))
 		return -ENOMEM;

_

Patches currently in -mm which might be from [email protected] are

mm-swap-fix-large-swap-in-across-swap-file-extents.patch hugetlbfs-do-not-grow-a-sealed-file-in-mmap.patch mm-hugetlb-keep-surplus-folios-that-are-reserved.patch mm-hugetlb-fix-reservation-leak-on-min_size=-mounts.patch mm-cachestat-count-each-page-only-once.patch mm-cachestat-restart-the-walk-after-each-entry.patch percpu-queue-the-balance-work-on-an-unbound-workqueue.patch mm-vma-fix-uncharge-after-failed-stack-relocation.patch mm-mremap-apply-the-mmap-offset-limits-on-expansion.patch mm-mremap-respect-guard-gaps-on-in-place-expansion.patch mm-vma-make-brk-mappings-non-executable-under-mdwe.patch

maintainer Applied
#35 lore raw

Re: (subset) [PATCH 0/7] mm: reworked AI-generated VMA and mremap fixes

In reply to Lorenzo Stoakes (ARM)
Quoted 11 lines · Lorenzo Stoakes (ARM)

I have reordered the patches here by priority, David - the first 2 should be prioritised as hotfixes, the rest can go in 7.5:

== Critical ==

1. unmapped_area_topdown() invalid bounds - possible memory corruption, triggerable by any local user.
2. Lock VMAs before mm_all_locks_mutex - system-wide unkillable hang, triggerable by a local user with FUSE.

[...]

Applied, thanks!

tree: mm/core.git
branch: ksm-7.5.misc

Applied patches will appear soon in mm-next, followed by linux-next.

Please report any outstanding bugs that were missed during review, so we can either drop the patch series or decide how to fix it up.

It is encouraged to provide Acked-bys, Reviewed-bys, and Tested-bys even though the patches have already been applied. If possible, patch trailers will be updated.

Note that commit hashes shown below are subject to change due to rebase, trailer updates or similar. Further, this is not a guarantee that the patches will go upstream. If in doubt, please check the listed branch.

[3/7] mm/ksm: only interrupt unmerging on a fatal signal

      https://git.kernel.org/mm/core/c/d90efc5d
Signature · 3 lines
Cheers,

David
#36 lore raw
In reply to Lorenzo Stoakes (ARM)
Quoted 27 lines · Lorenzo Stoakes (ARM)

I have reordered the patches here by priority, David - the first 2 should be prioritised as hotfixes, the rest can go in 7.5:

== Critical ==

1. unmapped_area_topdown() invalid bounds - possible memory corruption, triggerable by any local user.
2. Lock VMAs before mm_all_locks_mutex - system-wide unkillable hang, triggerable by a local user with FUSE.

== Need fixing ==

3. KSM unmerge only interrupted by fatal signal - silent data loss on mremap() of KSM memory.
4. Uncharge after failed stack relocation - strict overcommit limit defeated system-wide.
5. mmap() offset limits on mremap() expansion - invalid file offset reaches the DAX fault handler.

== Hardening (no need for Cc: stable) ==

6. Guard gaps on in-place mremap() expansion.
7. Non-executable brk mappings under MDWE.

As usual, please go through and check these carefully for correctness, sanity.

Quoted 7 lines

Note that one of the original patches was punted over to the BPF guys ([0]), as it doesn't feel that it'd make sense to change core mm to address it.

[0]:https://lore.kernel.org/all/awGZWsCp6v63H_py@gremlin/

Was able to reproduce every issue and validate the fix.

Not sure I agree with your assessment of NX brk mappings not needing stable, that's a pretty bad bug in my opinion.

Signature · 1 line
~Gregory