Re: [PATCH 1/1] mm/madvise: initialize prev pointer in madvise_walk_vmas

From: Lorenzo Stoakes
Date: Tue Jun 17 2025 - 04:52:33 EST


Lace - To simplify and not get bogged down in sub-threads am replying at the top
level.

TL;DR this fix is incorrect, but the issue is correct :)

So the patch at [0] introduced by Barry changed things in a way that _appears_
broken but in fact aren't, however we should do something about this, obviously.

That patch added:

if (madv_behavior && madv_behavior->lock_mode == MADVISE_VMA_READ_LOCK) {
vma = try_vma_read_lock(mm, madv_behavior, start, end);
if (vma) {
error = visit(vma, &prev, start, end, arg);
vma_end_read(vma);
return error;
}
}

And the problem is, in this case, we don't initialise prev.

In all other cases, we do (under mmap lock):

vma = find_vma_prev(mm, start, &prev);
if (vma && start > vma->vm_start)
prev = vma;

The reason this isn't a problem is that the only madvise operation that
currently supports this, madvise_dontneed_free() will initialise *prev = vma.

BUT we really shouldn't be relying on this, so I attach a fixpatch.

Given Barry's patch isn't mainline yet, I think this should just be squashed
into that as a fix?

It kind of sucks to do this, but it resolves any potential bug.

I think a follow up is needed, as there's an implicit assumption it seems that
prev is updated immediately for most callers, but of course anon_vma_name is a
special snowflake.

todos++;

Lance - I suggest you reply to Barry's series with the below fix, or I can if
you prefer?

[0]: https://lore.kernel.org/linux-mm/20250607220150.2980-1-21cnbao@xxxxxxxxx/

Thanks!

On Tue, Jun 17, 2025 at 10:05:43AM +0800, Lance Yang wrote:
> From: Lance Yang <lance.yang@xxxxxxxxx>
>
> The prev pointer was uninitialized, which could lead to undefined behavior
> where its address is taken and passed to the visit() callback without being
> assigned a value.
>
> Initializing it to NULL makes the code safer and prevents potential bugs
> if a future callback function attempts to read from it.
>
> Signed-off-by: Lance Yang <lance.yang@xxxxxxxxx>
> ---
> mm/madvise.c | 4 ++--
> 1 file changed, 2 insertions(+), 2 deletions(-)
>
> diff --git a/mm/madvise.c b/mm/madvise.c
> index 267d8e4adf31..c87325000303 100644
> --- a/mm/madvise.c
> +++ b/mm/madvise.c
> @@ -1536,10 +1536,10 @@ int madvise_walk_vmas(struct mm_struct *mm, unsigned long start,
> struct vm_area_struct **prev, unsigned long start,
> unsigned long end, void *arg))
> {
> + struct vm_area_struct *prev = NULL;
> struct vm_area_struct *vma;
> - struct vm_area_struct *prev;
> - unsigned long tmp;
> int unmapped_error = 0;
> + unsigned long tmp;
> int error;
>
> /*
> --
> 2.49.0
>

----8<----