FROMGIT: BACKPORT: mm: avoid rewalk in mmap_region

If the iterator has moved to the previous entry, then step forward one
range, back to the gap.

Link: https://lkml.kernel.org/r/20230518145544.1722059-36-Liam.Howlett@oracle.com
Signed-off-by: Liam R. Howlett <Liam.Howlett@oracle.com>
Cc: David Binderman <dcb314@hotmail.com>
Cc: Peng Zhang <zhangpeng.00@bytedance.com>
Cc: Sergey Senozhatsky <senozhatsky@chromium.org>
Cc: Vernon Yang <vernon2gm@gmail.com>
Cc: Wei Yang <richard.weiyang@gmail.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>

(cherry picked from commit d3f028c7599ea2297dd630e1a6acaf4915c769d3
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm mm-unstable)

Bug: 274059236
Change-Id: Ic45e095c728095d41647a704a287596d03489cdf
Signed-off-by: Suren Baghdasaryan <surenb@google.com>
diff --git a/mm/mmap.c b/mm/mmap.c
index 91e5f2aa..b08f1082 100644
--- a/mm/mmap.c
+++ b/mm/mmap.c
@@ -2611,9 +2611,13 @@ unsigned long mmap_region(struct file *file, unsigned long addr,
 		goto expanded;
 	}
 
+cannot_expand:
+	if (prev)
+		mas_next_range(&mas, ULONG_MAX);
+	BUG_ON(mas.last < addr);
+	BUG_ON(mas.index > end - 1);
 	mas.index = addr;
 	mas.last = end - 1;
-cannot_expand:
 	/*
 	 * Determine the object being mapped and call the appropriate
 	 * specific mapper. the address has already been validated, but
@@ -2710,7 +2714,7 @@ unsigned long mmap_region(struct file *file, unsigned long addr,
 	if (vma->vm_file)
 		i_mmap_lock_write(vma->vm_file->f_mapping);
 
-	vma_mas_store(vma, &mas);
+	mas_store_prealloc(&mas, vma);
 	mm->map_count++;
 	if (vma->vm_file) {
 		if (vma->vm_flags & VM_SHARED)