xref: /linux/mm/mremap.c (revision d03df42ddae196f20e9cfb775704e60269eb6b44)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *	mm/mremap.c
4  *
5  *	(C) Copyright 1996 Linus Torvalds
6  *
7  *	Address space accounting code	<alan@lxorguk.ukuu.org.uk>
8  *	(C) Copyright 2002 Red Hat Inc, All Rights Reserved
9  */
10 
11 #include <linux/mm.h>
12 #include <linux/mm_inline.h>
13 #include <linux/hugetlb.h>
14 #include <linux/shm.h>
15 #include <linux/ksm.h>
16 #include <linux/mman.h>
17 #include <linux/swap.h>
18 #include <linux/capability.h>
19 #include <linux/fs.h>
20 #include <linux/leafops.h>
21 #include <linux/highmem.h>
22 #include <linux/security.h>
23 #include <linux/syscalls.h>
24 #include <linux/mmu_notifier.h>
25 #include <linux/uaccess.h>
26 #include <linux/userfaultfd_k.h>
27 #include <linux/mempolicy.h>
28 #include <linux/pgalloc.h>
29 
30 #include <asm/cacheflush.h>
31 #include <asm/tlb.h>
32 
33 #include "internal.h"
34 
35 /* Classify the kind of remap operation being performed. */
36 enum mremap_type {
37 	MREMAP_INVALID,		/* Initial state. */
38 	MREMAP_NO_RESIZE,	/* old_len == new_len, if not moved, do nothing. */
39 	MREMAP_SHRINK,		/* old_len > new_len. */
40 	MREMAP_EXPAND,		/* old_len < new_len. */
41 };
42 
43 /*
44  * Describes a VMA mremap() operation and is threaded throughout it.
45  *
46  * Any of the fields may be mutated by the operation, however these values will
47  * always accurately reflect the remap (for instance, we may adjust lengths and
48  * delta to account for hugetlb alignment).
49  */
50 struct vma_remap_struct {
51 	/* User-provided state. */
52 	unsigned long addr;	/* User-specified address from which we remap. */
53 	unsigned long old_len;	/* Length of range being remapped. */
54 	unsigned long new_len;	/* Desired new length of mapping. */
55 	const unsigned long flags; /* user-specified MREMAP_* flags. */
56 	unsigned long new_addr;	/* Optionally, desired new address. */
57 
58 	/* uffd state. */
59 	struct vm_userfaultfd_ctx *uf;
60 	struct list_head *uf_unmap_early;
61 	struct list_head *uf_unmap;
62 
63 	/* VMA state, determined in do_mremap(). */
64 	struct vm_area_struct *vma;
65 
66 	/* Internal state, determined in do_mremap(). */
67 	unsigned long delta;		/* Absolute delta of old_len,new_len. */
68 	bool populate_expand;		/* mlock()'d expanded, must populate. */
69 	enum mremap_type remap_type;	/* expand, shrink, etc. */
70 	bool mmap_locked;		/* Is mm currently write-locked? */
71 	unsigned long charged;		/* If VMA_ACCOUNT_BIT, # pgs to account */
72 	bool vmi_needs_invalidate;	/* Is the VMA iterator invalidated? */
73 };
74 
75 static pud_t *get_old_pud(struct mm_struct *mm, unsigned long addr)
76 {
77 	pgd_t *pgd;
78 	p4d_t *p4d;
79 	pud_t *pud;
80 
81 	pgd = pgd_offset(mm, addr);
82 	if (pgd_none_or_clear_bad(pgd))
83 		return NULL;
84 
85 	p4d = p4d_offset(pgd, addr);
86 	if (p4d_none_or_clear_bad(p4d))
87 		return NULL;
88 
89 	pud = pud_offset(p4d, addr);
90 	if (!pud_trans_huge(*pud) && pud_none_or_clear_bad(pud))
91 		return NULL;
92 
93 	return pud;
94 }
95 
96 static pmd_t *get_old_pmd(struct mm_struct *mm, unsigned long addr)
97 {
98 	pud_t *pud;
99 	pmd_t *pmd;
100 
101 	pud = get_old_pud(mm, addr);
102 	if (!pud)
103 		return NULL;
104 
105 	pmd = pmd_offset(pud, addr);
106 	if (pmd_none(*pmd))
107 		return NULL;
108 
109 	return pmd;
110 }
111 
112 static pud_t *alloc_new_pud(struct mm_struct *mm, unsigned long addr)
113 {
114 	pgd_t *pgd;
115 	p4d_t *p4d;
116 
117 	pgd = pgd_offset(mm, addr);
118 	p4d = p4d_alloc(mm, pgd, addr);
119 	if (!p4d)
120 		return NULL;
121 
122 	return pud_alloc(mm, p4d, addr);
123 }
124 
125 static pmd_t *alloc_new_pmd(struct mm_struct *mm, unsigned long addr)
126 {
127 	pud_t *pud;
128 	pmd_t *pmd;
129 
130 	pud = alloc_new_pud(mm, addr);
131 	if (!pud)
132 		return NULL;
133 
134 	pmd = pmd_alloc(mm, pud, addr);
135 	if (!pmd)
136 		return NULL;
137 
138 	VM_BUG_ON(pmd_trans_huge(*pmd));
139 
140 	return pmd;
141 }
142 
143 static void take_rmap_locks(struct vm_area_struct *vma)
144 {
145 	if (vma->vm_file)
146 		i_mmap_lock_write(vma->vm_file->f_mapping);
147 	if (vma_has_anon_rmap(vma))
148 		anon_vma_lock_write(vma->anon_vma);
149 }
150 
151 static void drop_rmap_locks(struct vm_area_struct *vma)
152 {
153 	if (vma_has_anon_rmap(vma))
154 		anon_vma_unlock_write(vma->anon_vma);
155 	if (vma->vm_file)
156 		i_mmap_unlock_write(vma->vm_file->f_mapping);
157 }
158 
159 static pte_t move_soft_dirty_pte(pte_t pte)
160 {
161 	if (pte_none(pte))
162 		return pte;
163 
164 	/*
165 	 * Set soft dirty bit so we can notice
166 	 * in userspace the ptes were moved.
167 	 */
168 	if (pgtable_supports_soft_dirty()) {
169 		if (pte_present(pte))
170 			pte = pte_mksoft_dirty(pte);
171 		else
172 			pte = pte_swp_mksoft_dirty(pte);
173 	}
174 
175 	return pte;
176 }
177 
178 static int mremap_folio_pte_batch(struct vm_area_struct *vma, unsigned long addr,
179 		pte_t *ptep, pte_t pte, int max_nr)
180 {
181 	struct folio *folio;
182 
183 	if (max_nr == 1)
184 		return 1;
185 
186 	/* Avoid expensive folio lookup if we stand no chance of benefit. */
187 	if (pte_batch_hint(ptep, pte) == 1)
188 		return 1;
189 
190 	folio = vm_normal_folio(vma, addr, pte);
191 	if (!folio || !folio_test_large(folio))
192 		return 1;
193 
194 	return folio_pte_batch_flags(folio, NULL, ptep, &pte, max_nr, FPB_RESPECT_WRITE);
195 }
196 
197 static int move_ptes(struct pagetable_move_control *pmc,
198 		unsigned long extent, pmd_t *old_pmd, pmd_t *new_pmd)
199 {
200 	struct vm_area_struct *vma = pmc->old;
201 	bool need_clear_uffd_wp = vma_has_uffd_without_event_remap(vma);
202 	struct mm_struct *mm = vma->vm_mm;
203 	pte_t *old_ptep, *new_ptep;
204 	pte_t old_pte, pte;
205 	pmd_t old_pmdval, new_pmdval;
206 	spinlock_t *old_ptl, *new_ptl;
207 	bool force_flush = false;
208 	unsigned long old_addr = pmc->old_addr;
209 	unsigned long new_addr = pmc->new_addr;
210 	unsigned long old_end = old_addr + extent;
211 	unsigned long len = old_end - old_addr;
212 	int max_nr_ptes;
213 	int nr_ptes;
214 	int err = 0;
215 
216 	/*
217 	 * When need_rmap_locks is true, we take the i_mmap_rwsem and anon rmap
218 	 * locks to ensure that rmap will always observe either the old or the
219 	 * new ptes. This is the easiest way to avoid races with
220 	 * truncate_pagecache(), page migration, etc...
221 	 *
222 	 * When need_rmap_locks is false, we use other ways to avoid
223 	 * such races:
224 	 *
225 	 * - During exec() shift_arg_pages(), we use a specially tagged vma
226 	 *   which rmap call sites look for using vma_is_temporary_stack().
227 	 *
228 	 * - During mremap(), new_vma is often known to be placed after vma
229 	 *   in rmap traversal order. This ensures rmap will always observe
230 	 *   either the old pte, or the new pte, or both (the page table locks
231 	 *   serialize access to individual ptes, but only rmap traversal
232 	 *   order guarantees that we won't miss both the old and new ptes).
233 	 */
234 	if (pmc->need_rmap_locks)
235 		take_rmap_locks(vma);
236 
237 	old_ptep = pte_offset_map_rw_nolock(mm, old_pmd, old_addr, &old_pmdval,
238 					    &old_ptl);
239 	if (!old_ptep) {
240 		err = -EAGAIN;
241 		goto out;
242 	}
243 	new_ptep = pte_offset_map_rw_nolock(mm, new_pmd, new_addr, &new_pmdval,
244 					    &new_ptl);
245 	if (!new_ptep) {
246 		pte_unmap(old_ptep);
247 		err = -EAGAIN;
248 		goto out;
249 	}
250 
251 	double_pt_lock(old_ptl, new_ptl);
252 	if (unlikely(!pmd_same(old_pmdval, pmdp_get_lockless(old_pmd)) ||
253 		     !pmd_same(new_pmdval, pmdp_get_lockless(new_pmd)))) {
254 		double_pt_unlock(old_ptl, new_ptl);
255 		pte_unmap(new_ptep);
256 		pte_unmap(old_ptep);
257 		err = -EAGAIN;
258 		goto out;
259 	}
260 
261 	flush_tlb_batched_pending(vma->vm_mm);
262 	lazy_mmu_mode_enable();
263 
264 	for (; old_addr < old_end; old_ptep += nr_ptes, old_addr += nr_ptes * PAGE_SIZE,
265 		new_ptep += nr_ptes, new_addr += nr_ptes * PAGE_SIZE) {
266 		VM_WARN_ON_ONCE(!pte_none(ptep_get(new_ptep)));
267 
268 		nr_ptes = 1;
269 		max_nr_ptes = (old_end - old_addr) >> PAGE_SHIFT;
270 		old_pte = ptep_get(old_ptep);
271 		if (pte_none(old_pte))
272 			continue;
273 
274 		/*
275 		 * If we are remapping a valid PTE, make sure
276 		 * to flush TLB before we drop the PTL for the
277 		 * PTE.
278 		 *
279 		 * NOTE! Both old and new PTL matter: the old one
280 		 * for racing with folio_mkclean(), the new one to
281 		 * make sure the physical page stays valid until
282 		 * the TLB entry for the old mapping has been
283 		 * flushed.
284 		 */
285 		if (pte_present(old_pte)) {
286 			nr_ptes = mremap_folio_pte_batch(vma, old_addr, old_ptep,
287 							 old_pte, max_nr_ptes);
288 			force_flush = true;
289 		}
290 		pte = get_and_clear_ptes(mm, old_addr, old_ptep, nr_ptes);
291 		pte = move_pte(pte, old_addr, new_addr);
292 		pte = move_soft_dirty_pte(pte);
293 
294 		if (need_clear_uffd_wp && pte_is_uffd_wp_marker(pte))
295 			pte_clear(mm, new_addr, new_ptep);
296 		else {
297 			if (need_clear_uffd_wp) {
298 				if (pte_present(pte)) {
299 					/*
300 					 * See __copy_present_ptes(): normalise
301 					 * RWP PTEs so the destination starts
302 					 * accessible instead of taking a
303 					 * numa-hinting fault on first access.
304 					 */
305 					if (userfaultfd_rwp(vma) && pte_uffd(pte))
306 						pte = pte_modify(pte, vma->vm_page_prot);
307 					pte = pte_clear_uffd(pte);
308 				} else {
309 					pte = pte_swp_clear_uffd(pte);
310 				}
311 			}
312 			set_ptes(mm, new_addr, new_ptep, pte, nr_ptes);
313 		}
314 	}
315 
316 	lazy_mmu_mode_disable();
317 	if (force_flush)
318 		flush_tlb_range(vma, old_end - len, old_end);
319 	double_pt_unlock(old_ptl, new_ptl);
320 	pte_unmap(new_ptep - 1);
321 	pte_unmap(old_ptep - 1);
322 out:
323 	if (pmc->need_rmap_locks)
324 		drop_rmap_locks(vma);
325 	return err;
326 }
327 
328 #ifndef arch_supports_page_table_move
329 #define arch_supports_page_table_move arch_supports_page_table_move
330 static inline bool arch_supports_page_table_move(void)
331 {
332 	return IS_ENABLED(CONFIG_HAVE_MOVE_PMD) ||
333 		IS_ENABLED(CONFIG_HAVE_MOVE_PUD);
334 }
335 #endif
336 
337 static inline bool uffd_supports_page_table_move(struct pagetable_move_control *pmc)
338 {
339 	/*
340 	 * If we are moving a VMA that has uffd-wp registered but with
341 	 * remap events disabled (new VMA will not be registered with uffd), we
342 	 * need to ensure that the uffd-wp state is cleared from all pgtables.
343 	 * This means recursing into lower page tables in move_page_tables().
344 	 *
345 	 * We might get called with VMAs reversed when recovering from a
346 	 * failed page table move. In that case, the
347 	 * "old"-but-actually-"originally new" VMA during recovery will not have
348 	 * a uffd context. Recursing into lower page tables during the original
349 	 * move but not during the recovery move will cause trouble, because we
350 	 * run into already-existing page tables. So check both VMAs.
351 	 */
352 	return !vma_has_uffd_without_event_remap(pmc->old) &&
353 	       !vma_has_uffd_without_event_remap(pmc->new);
354 }
355 
356 #ifdef CONFIG_HAVE_MOVE_PMD
357 static bool move_normal_pmd(struct pagetable_move_control *pmc,
358 			pmd_t *old_pmd, pmd_t *new_pmd)
359 {
360 	spinlock_t *old_ptl, *new_ptl;
361 	struct vm_area_struct *vma = pmc->old;
362 	struct mm_struct *mm = vma->vm_mm;
363 	bool res = false;
364 	pmd_t pmd;
365 
366 	if (!arch_supports_page_table_move())
367 		return false;
368 	if (!uffd_supports_page_table_move(pmc))
369 		return false;
370 	/*
371 	 * The destination pmd shouldn't be established, free_pgtables()
372 	 * should have released it.
373 	 *
374 	 * However, there's a case during execve() where we use mremap
375 	 * to move the initial stack, and in that case the target area
376 	 * may overlap the source area (always moving down).
377 	 *
378 	 * If everything is PMD-aligned, that works fine, as moving
379 	 * each pmd down will clear the source pmd. But if we first
380 	 * have a few 4kB-only pages that get moved down, and then
381 	 * hit the "now the rest is PMD-aligned, let's do everything
382 	 * one pmd at a time", we will still have the old (now empty
383 	 * of any 4kB pages, but still there) PMD in the page table
384 	 * tree.
385 	 *
386 	 * Warn on it once - because we really should try to figure
387 	 * out how to do this better - but then say "I won't move
388 	 * this pmd".
389 	 *
390 	 * One alternative might be to just unmap the target pmd at
391 	 * this point, and verify that it really is empty. We'll see.
392 	 */
393 	if (WARN_ON_ONCE(!pmd_none(*new_pmd)))
394 		return false;
395 
396 	old_ptl = pmd_lockptr(mm, old_pmd);
397 	new_ptl = pmd_lockptr(mm, new_pmd);
398 	double_pt_lock(old_ptl, new_ptl);
399 
400 	pmd = *old_pmd;
401 
402 	/* Racing with collapse? */
403 	if (unlikely(!pmd_present(pmd) || pmd_leaf(pmd)))
404 		goto out_unlock;
405 	/* Clear the pmd */
406 	pmd_clear(old_pmd);
407 	res = true;
408 
409 	VM_BUG_ON(!pmd_none(*new_pmd));
410 
411 	pmd_populate(mm, new_pmd, pmd_pgtable(pmd));
412 	flush_tlb_range(vma, pmc->old_addr, pmc->old_addr + PMD_SIZE);
413 out_unlock:
414 	double_pt_unlock(old_ptl, new_ptl);
415 
416 	return res;
417 }
418 #else
419 static inline bool move_normal_pmd(struct pagetable_move_control *pmc,
420 		pmd_t *old_pmd, pmd_t *new_pmd)
421 {
422 	return false;
423 }
424 #endif
425 
426 #if CONFIG_PGTABLE_LEVELS > 2 && defined(CONFIG_HAVE_MOVE_PUD)
427 static bool move_normal_pud(struct pagetable_move_control *pmc,
428 		pud_t *old_pud, pud_t *new_pud)
429 {
430 	spinlock_t *old_ptl, *new_ptl;
431 	struct vm_area_struct *vma = pmc->old;
432 	struct mm_struct *mm = vma->vm_mm;
433 	pud_t pud;
434 
435 	if (!arch_supports_page_table_move())
436 		return false;
437 	if (!uffd_supports_page_table_move(pmc))
438 		return false;
439 	/*
440 	 * The destination pud shouldn't be established, free_pgtables()
441 	 * should have released it.
442 	 */
443 	if (WARN_ON_ONCE(!pud_none(*new_pud)))
444 		return false;
445 
446 	old_ptl = pud_lockptr(mm, old_pud);
447 	new_ptl = pud_lockptr(mm, new_pud);
448 
449 	double_pt_lock(old_ptl, new_ptl);
450 
451 	pud = *old_pud;
452 	if (unlikely(pud_none(pud)))
453 		goto out_unlock;
454 
455 	/* Clear the pud */
456 	pud_clear(old_pud);
457 
458 	VM_BUG_ON(!pud_none(*new_pud));
459 
460 	pud_populate(mm, new_pud, pud_pgtable(pud));
461 	flush_tlb_range(vma, pmc->old_addr, pmc->old_addr + PUD_SIZE);
462 out_unlock:
463 	double_pt_unlock(old_ptl, new_ptl);
464 
465 	return true;
466 }
467 #else
468 static inline bool move_normal_pud(struct pagetable_move_control *pmc,
469 		pud_t *old_pud, pud_t *new_pud)
470 {
471 	return false;
472 }
473 #endif
474 
475 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
476 static bool move_huge_pud(struct pagetable_move_control *pmc,
477 		pud_t *old_pud, pud_t *new_pud)
478 {
479 	spinlock_t *old_ptl, *new_ptl;
480 	struct vm_area_struct *vma = pmc->old;
481 	struct mm_struct *mm = vma->vm_mm;
482 	pud_t pud;
483 
484 	/*
485 	 * The destination pud shouldn't be established, free_pgtables()
486 	 * should have released it.
487 	 */
488 	if (WARN_ON_ONCE(!pud_none(*new_pud)))
489 		return false;
490 
491 	old_ptl = pud_lockptr(mm, old_pud);
492 	new_ptl = pud_lockptr(mm, new_pud);
493 
494 	double_pt_lock(old_ptl, new_ptl);
495 	if (unlikely(!pud_trans_huge(*old_pud))) {
496 		double_pt_unlock(old_ptl, new_ptl);
497 		return false;
498 	}
499 
500 	/* Clear the pud */
501 	pud = pudp_huge_get_and_clear(mm, pmc->old_addr, old_pud);
502 
503 	VM_BUG_ON(!pud_none(*new_pud));
504 
505 	/* Set the new pud */
506 	/* mark soft_ditry when we add pud level soft dirty support */
507 	set_pud_at(mm, pmc->new_addr, new_pud, pud);
508 	flush_pud_tlb_range(vma, pmc->old_addr, pmc->old_addr + HPAGE_PUD_SIZE);
509 	double_pt_unlock(old_ptl, new_ptl);
510 
511 	return true;
512 }
513 #else
514 static bool move_huge_pud(struct pagetable_move_control *pmc,
515 		pud_t *old_pud, pud_t *new_pud)
516 
517 {
518 	WARN_ON_ONCE(1);
519 	return false;
520 
521 }
522 #endif
523 
524 enum pgt_entry {
525 	NORMAL_PMD,
526 	HPAGE_PMD,
527 	NORMAL_PUD,
528 	HPAGE_PUD,
529 };
530 
531 /*
532  * Returns an extent of the corresponding size for the pgt_entry specified if
533  * valid. Else returns a smaller extent bounded by the end of the source and
534  * destination pgt_entry.
535  */
536 static __always_inline unsigned long get_extent(enum pgt_entry entry,
537 						struct pagetable_move_control *pmc)
538 {
539 	unsigned long next, extent, mask, size;
540 	unsigned long old_addr = pmc->old_addr;
541 	unsigned long old_end = pmc->old_end;
542 	unsigned long new_addr = pmc->new_addr;
543 
544 	switch (entry) {
545 	case HPAGE_PMD:
546 	case NORMAL_PMD:
547 		mask = PMD_MASK;
548 		size = PMD_SIZE;
549 		break;
550 	case HPAGE_PUD:
551 	case NORMAL_PUD:
552 		mask = PUD_MASK;
553 		size = PUD_SIZE;
554 		break;
555 	default:
556 		BUILD_BUG();
557 		break;
558 	}
559 
560 	next = (old_addr + size) & mask;
561 	/* even if next overflowed, extent below will be ok */
562 	extent = next - old_addr;
563 	if (extent > old_end - old_addr)
564 		extent = old_end - old_addr;
565 	next = (new_addr + size) & mask;
566 	if (extent > next - new_addr)
567 		extent = next - new_addr;
568 	return extent;
569 }
570 
571 /*
572  * Should move_pgt_entry() acquire the rmap locks? This is either expressed in
573  * the PMC, or overridden in the case of normal, larger page tables.
574  */
575 static bool should_take_rmap_locks(struct pagetable_move_control *pmc,
576 				   enum pgt_entry entry)
577 {
578 	switch (entry) {
579 	case NORMAL_PMD:
580 	case NORMAL_PUD:
581 		return true;
582 	default:
583 		return pmc->need_rmap_locks;
584 	}
585 }
586 
587 /*
588  * Attempts to speedup the move by moving entry at the level corresponding to
589  * pgt_entry. Returns true if the move was successful, else false.
590  */
591 static bool move_pgt_entry(struct pagetable_move_control *pmc,
592 			   enum pgt_entry entry, void *old_entry, void *new_entry)
593 {
594 	bool moved = false;
595 	bool need_rmap_locks = should_take_rmap_locks(pmc, entry);
596 
597 	/* See comment in move_ptes() */
598 	if (need_rmap_locks)
599 		take_rmap_locks(pmc->old);
600 
601 	switch (entry) {
602 	case NORMAL_PMD:
603 		moved = move_normal_pmd(pmc, old_entry, new_entry);
604 		break;
605 	case NORMAL_PUD:
606 		moved = move_normal_pud(pmc, old_entry, new_entry);
607 		break;
608 	case HPAGE_PMD:
609 		moved = IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
610 			move_huge_pmd(pmc->old, pmc->old_addr, pmc->new_addr, old_entry,
611 				      new_entry);
612 		break;
613 	case HPAGE_PUD:
614 		moved = IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
615 			move_huge_pud(pmc, old_entry, new_entry);
616 		break;
617 
618 	default:
619 		WARN_ON_ONCE(1);
620 		break;
621 	}
622 
623 	if (need_rmap_locks)
624 		drop_rmap_locks(pmc->old);
625 
626 	return moved;
627 }
628 
629 /*
630  * A helper to check if aligning down is OK. The aligned address should fall
631  * on *no mapping*. For the stack moving down, that's a special move within
632  * the VMA that is created to span the source and destination of the move,
633  * so we make an exception for it.
634  */
635 static bool can_align_down(struct pagetable_move_control *pmc,
636 			   struct vm_area_struct *vma, unsigned long addr_to_align,
637 			   unsigned long mask)
638 {
639 	unsigned long addr_masked = addr_to_align & mask;
640 
641 	/*
642 	 * If @addr_to_align of either source or destination is not the beginning
643 	 * of the corresponding VMA, we can't align down or we will destroy part
644 	 * of the current mapping.
645 	 */
646 	if (!pmc->for_stack && vma->vm_start != addr_to_align)
647 		return false;
648 
649 	/* In the stack case we explicitly permit in-VMA alignment. */
650 	if (pmc->for_stack && addr_masked >= vma->vm_start)
651 		return true;
652 
653 	/*
654 	 * Make sure the realignment doesn't cause the address to fall on an
655 	 * existing mapping.
656 	 */
657 	return find_vma_intersection(vma->vm_mm, addr_masked, vma->vm_start) == NULL;
658 }
659 
660 /*
661  * Determine if are in fact able to realign for efficiency to a higher page
662  * table boundary.
663  */
664 static bool can_realign_addr(struct pagetable_move_control *pmc,
665 			     unsigned long pagetable_mask)
666 {
667 	unsigned long align_mask = ~pagetable_mask;
668 	unsigned long old_align = pmc->old_addr & align_mask;
669 	unsigned long new_align = pmc->new_addr & align_mask;
670 	unsigned long pagetable_size = align_mask + 1;
671 	unsigned long old_align_next = pagetable_size - old_align;
672 
673 	/*
674 	 * We don't want to have to go hunting for VMAs from the end of the old
675 	 * VMA to the next page table boundary, also we want to make sure the
676 	 * operation is worthwhile.
677 	 *
678 	 * So ensure that we only perform this realignment if the end of the
679 	 * range being copied reaches or crosses the page table boundary.
680 	 *
681 	 * boundary                        boundary
682 	 *    .<- old_align ->                .
683 	 *    .              |----------------.-----------|
684 	 *    .              |          vma   .           |
685 	 *    .              |----------------.-----------|
686 	 *    .              <----------------.----------->
687 	 *    .                          len_in
688 	 *    <------------------------------->
689 	 *    .         pagetable_size        .
690 	 *    .              <---------------->
691 	 *    .                old_align_next .
692 	 */
693 	if (pmc->len_in < old_align_next)
694 		return false;
695 
696 	/* Skip if the addresses are already aligned. */
697 	if (old_align == 0)
698 		return false;
699 
700 	/* Only realign if the new and old addresses are mutually aligned. */
701 	if (old_align != new_align)
702 		return false;
703 
704 	/* Ensure realignment doesn't cause overlap with existing mappings. */
705 	if (!can_align_down(pmc, pmc->old, pmc->old_addr, pagetable_mask) ||
706 	    !can_align_down(pmc, pmc->new, pmc->new_addr, pagetable_mask))
707 		return false;
708 
709 	return true;
710 }
711 
712 /*
713  * Opportunistically realign to specified boundary for faster copy.
714  *
715  * Consider an mremap() of a VMA with page table boundaries as below, and no
716  * preceding VMAs from the lower page table boundary to the start of the VMA,
717  * with the end of the range reaching or crossing the page table boundary.
718  *
719  *   boundary                        boundary
720  *      .              |----------------.-----------|
721  *      .              |          vma   .           |
722  *      .              |----------------.-----------|
723  *      .         pmc->old_addr         .      pmc->old_end
724  *      .              <---------------------------->
725  *      .                  move these page tables
726  *
727  * If we proceed with moving page tables in this scenario, we will have a lot of
728  * work to do traversing old page tables and establishing new ones in the
729  * destination across multiple lower level page tables.
730  *
731  * The idea here is simply to align pmc->old_addr, pmc->new_addr down to the
732  * page table boundary, so we can simply copy a single page table entry for the
733  * aligned portion of the VMA instead:
734  *
735  *   boundary                        boundary
736  *      .              |----------------.-----------|
737  *      .              |          vma   .           |
738  *      .              |----------------.-----------|
739  * pmc->old_addr                        .      pmc->old_end
740  *      <------------------------------------------->
741  *      .           move these page tables
742  */
743 static void try_realign_addr(struct pagetable_move_control *pmc,
744 			     unsigned long pagetable_mask)
745 {
746 
747 	if (!can_realign_addr(pmc, pagetable_mask))
748 		return;
749 
750 	/*
751 	 * Simply align to page table boundaries. Note that we do NOT update the
752 	 * pmc->old_end value, and since the move_page_tables() operation spans
753 	 * from [old_addr, old_end) (offsetting new_addr as it is performed),
754 	 * this simply changes the start of the copy, not the end.
755 	 */
756 	pmc->old_addr &= pagetable_mask;
757 	pmc->new_addr &= pagetable_mask;
758 }
759 
760 /* Is the page table move operation done? */
761 static bool pmc_done(struct pagetable_move_control *pmc)
762 {
763 	return pmc->old_addr >= pmc->old_end;
764 }
765 
766 /* Advance to the next page table, offset by extent bytes. */
767 static void pmc_next(struct pagetable_move_control *pmc, unsigned long extent)
768 {
769 	pmc->old_addr += extent;
770 	pmc->new_addr += extent;
771 }
772 
773 /*
774  * Determine how many bytes in the specified input range have had their page
775  * tables moved so far.
776  */
777 static unsigned long pmc_progress(struct pagetable_move_control *pmc)
778 {
779 	unsigned long orig_old_addr = pmc->old_end - pmc->len_in;
780 	unsigned long old_addr = pmc->old_addr;
781 
782 	/*
783 	 * Prevent negative return values when {old,new}_addr was realigned but
784 	 * we broke out of the loop in move_page_tables() for the first PMD
785 	 * itself.
786 	 */
787 	return old_addr < orig_old_addr ? 0 : old_addr - orig_old_addr;
788 }
789 
790 unsigned long move_page_tables(struct pagetable_move_control *pmc)
791 {
792 	unsigned long extent;
793 	struct mmu_notifier_range range;
794 	pmd_t *old_pmd, *new_pmd;
795 	pud_t *old_pud, *new_pud;
796 	struct mm_struct *mm = pmc->old->vm_mm;
797 
798 	if (!pmc->len_in)
799 		return 0;
800 
801 	if (vma_is_hugetlb(pmc->old))
802 		return move_hugetlb_page_tables(pmc->old, pmc->new, pmc->old_addr,
803 						pmc->new_addr, pmc->len_in);
804 
805 	/*
806 	 * If possible, realign addresses to PMD boundary for faster copy.
807 	 * Only realign if the mremap copying hits a PMD boundary.
808 	 */
809 	try_realign_addr(pmc, PMD_MASK);
810 
811 	flush_cache_range(pmc->old, pmc->old_addr, pmc->old_end);
812 	mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, mm,
813 				pmc->old_addr, pmc->old_end);
814 	mmu_notifier_invalidate_range_start(&range);
815 
816 	for (; !pmc_done(pmc); pmc_next(pmc, extent)) {
817 		cond_resched();
818 		/*
819 		 * If extent is PUD-sized try to speed up the move by moving at the
820 		 * PUD level if possible.
821 		 */
822 		extent = get_extent(NORMAL_PUD, pmc);
823 
824 		old_pud = get_old_pud(mm, pmc->old_addr);
825 		if (!old_pud)
826 			continue;
827 		new_pud = alloc_new_pud(mm, pmc->new_addr);
828 		if (!new_pud)
829 			break;
830 		if (pud_trans_huge(*old_pud)) {
831 			if (extent == HPAGE_PUD_SIZE &&
832 			    move_pgt_entry(pmc, HPAGE_PUD, old_pud, new_pud))
833 				continue;
834 			split_huge_pud(pmc->old, old_pud, pmc->old_addr);
835 		} else if (IS_ENABLED(CONFIG_HAVE_MOVE_PUD) && extent == PUD_SIZE) {
836 			if (move_pgt_entry(pmc, NORMAL_PUD, old_pud, new_pud))
837 				continue;
838 		}
839 
840 		extent = get_extent(NORMAL_PMD, pmc);
841 		old_pmd = get_old_pmd(mm, pmc->old_addr);
842 		if (!old_pmd)
843 			continue;
844 		new_pmd = alloc_new_pmd(mm, pmc->new_addr);
845 		if (!new_pmd)
846 			break;
847 again:
848 		if (pmd_is_huge(*old_pmd)) {
849 			if (extent == HPAGE_PMD_SIZE &&
850 			    move_pgt_entry(pmc, HPAGE_PMD, old_pmd, new_pmd))
851 				continue;
852 			split_huge_pmd(pmc->old, old_pmd, pmc->old_addr);
853 		} else if (IS_ENABLED(CONFIG_HAVE_MOVE_PMD) &&
854 			   extent == PMD_SIZE) {
855 			/*
856 			 * If the extent is PMD-sized, try to speed the move by
857 			 * moving at the PMD level if possible.
858 			 */
859 			if (move_pgt_entry(pmc, NORMAL_PMD, old_pmd, new_pmd))
860 				continue;
861 		}
862 		if (pmd_none(*old_pmd))
863 			continue;
864 		if (pte_alloc(pmc->new->vm_mm, new_pmd))
865 			break;
866 		if (move_ptes(pmc, extent, old_pmd, new_pmd) < 0)
867 			goto again;
868 	}
869 
870 	mmu_notifier_invalidate_range_end(&range);
871 
872 	return pmc_progress(pmc);
873 }
874 
875 /* Determine what kind of remap this is - shrink, expand or no resize at all. */
876 static enum mremap_type vrm_remap_type(struct vma_remap_struct *vrm)
877 {
878 	if (vrm->delta == 0)
879 		return MREMAP_NO_RESIZE;
880 
881 	if (vrm->old_len > vrm->new_len)
882 		return MREMAP_SHRINK;
883 
884 	return MREMAP_EXPAND;
885 }
886 
887 /* Populate calculated fields. */
888 static void vrm_populate_calculated(struct vma_remap_struct *vrm)
889 {
890 	vrm->delta = abs_diff(vrm->old_len, vrm->new_len);
891 	vrm->remap_type = vrm_remap_type(vrm);
892 }
893 
894 /*
895  * When moving a VMA to vrm->new_adr, does this result in the new and old VMAs
896  * overlapping?
897  */
898 static bool vrm_overlaps(struct vma_remap_struct *vrm)
899 {
900 	unsigned long start_old = vrm->addr;
901 	unsigned long start_new = vrm->new_addr;
902 	unsigned long end_old = vrm->addr + vrm->old_len;
903 	unsigned long end_new = vrm->new_addr + vrm->new_len;
904 
905 	/*
906 	 * start_old    end_old
907 	 *     |-----------|
908 	 *     |           |
909 	 *     |-----------|
910 	 *             |-------------|
911 	 *             |             |
912 	 *             |-------------|
913 	 *         start_new      end_new
914 	 */
915 	if (end_old > start_new && end_new > start_old)
916 		return true;
917 
918 	return false;
919 }
920 
921 /*
922  * Will a new address definitely be assigned? This either if the user specifies
923  * it via MREMAP_FIXED, or if MREMAP_DONTUNMAP is used, indicating we will
924  * always determine a target address.
925  */
926 static bool vrm_implies_new_addr(struct vma_remap_struct *vrm)
927 {
928 	return vrm->flags & (MREMAP_FIXED | MREMAP_DONTUNMAP);
929 }
930 
931 /*
932  * Find an unmapped area for the requested vrm->new_addr.
933  *
934  * If MREMAP_FIXED then this is equivalent to a MAP_FIXED mmap() call. If only
935  * MREMAP_DONTUNMAP is set, then this is equivalent to providing a hint to
936  * mmap(), otherwise this is equivalent to mmap() specifying a NULL address.
937  *
938  * Returns 0 on success (with vrm->new_addr updated), or an error code upon
939  * failure.
940  */
941 static unsigned long vrm_set_new_addr(struct vma_remap_struct *vrm)
942 {
943 	struct vm_area_struct *vma = vrm->vma;
944 	unsigned long map_flags = 0;
945 	/* Page Offset _into_ the VMA. */
946 	const pgoff_t pgoff = linear_page_index(vma, vrm->addr);
947 	unsigned long new_addr = vrm_implies_new_addr(vrm) ? vrm->new_addr : 0;
948 	unsigned long res;
949 
950 	if (vrm->flags & MREMAP_FIXED)
951 		map_flags |= MAP_FIXED;
952 	if (vma_test(vma, VMA_MAYSHARE_BIT))
953 		map_flags |= MAP_SHARED;
954 
955 	res = get_unmapped_area(vma->vm_file, new_addr, vrm->new_len, pgoff,
956 				map_flags);
957 	if (IS_ERR_VALUE(res))
958 		return res;
959 
960 	vrm->new_addr = res;
961 	return 0;
962 }
963 
964 /*
965  * Keep track of pages which have been added to the memory mapping. If the VMA
966  * is accounted, also check to see if there is sufficient memory.
967  *
968  * Returns true on success, false if insufficient memory to charge.
969  */
970 static bool vrm_calc_charge(struct vma_remap_struct *vrm)
971 {
972 	unsigned long charged;
973 
974 	if (!vma_test(vrm->vma, VMA_ACCOUNT_BIT))
975 		return true;
976 
977 	/*
978 	 * If we don't unmap the old mapping, then we account the entirety of
979 	 * the length of the new one. Otherwise it's just the delta in size.
980 	 */
981 	if (vrm->flags & MREMAP_DONTUNMAP)
982 		charged = vrm->new_len >> PAGE_SHIFT;
983 	else
984 		charged = vrm->delta >> PAGE_SHIFT;
985 
986 
987 	/* This accounts 'charged' pages of memory. */
988 	if (security_vm_enough_memory_mm(current->mm, charged))
989 		return false;
990 
991 	vrm->charged = charged;
992 	return true;
993 }
994 
995 /*
996  * an error has occurred so we will not be using vrm->charged memory. Unaccount
997  * this memory if the VMA is accounted.
998  */
999 static void vrm_uncharge(struct vma_remap_struct *vrm)
1000 {
1001 	if (!vma_test(vrm->vma, VMA_ACCOUNT_BIT))
1002 		return;
1003 
1004 	vm_unacct_memory(vrm->charged);
1005 	vrm->charged = 0;
1006 }
1007 
1008 /*
1009  * Update mm exec_vm, stack_vm, data_vm, and locked_vm fields as needed to
1010  * account for 'bytes' memory used, and if locked, indicate this in the VRM so
1011  * we can handle this correctly later.
1012  */
1013 static void vrm_stat_account(struct vma_remap_struct *vrm,
1014 			     unsigned long bytes)
1015 {
1016 	unsigned long pages = bytes >> PAGE_SHIFT;
1017 	struct mm_struct *mm = current->mm;
1018 	struct vm_area_struct *vma = vrm->vma;
1019 
1020 	vm_stat_account(mm, vma->vm_flags, pages);
1021 	if (vma_test(vma, VMA_LOCKED_BIT))
1022 		mm->locked_vm += pages;
1023 }
1024 
1025 static bool __check_map_count_against_split(struct mm_struct *mm,
1026 					    bool pre_split,
1027 					    bool before_unmaps)
1028 {
1029 	const int sys_map_count = get_sysctl_max_map_count();
1030 	int map_count = mm->map_count;
1031 
1032 	mmap_assert_write_locked(mm);
1033 
1034 	/*
1035 	 * At the point of shrinking the VMA, if new_len < old_len, we unmap
1036 	 * thusly in the worst case:
1037 	 *
1038 	 *              old_addr+old_len                    old_addr+old_len
1039 	 * |---------------.----.---------|    |---------------|    |---------|
1040 	 * |               .    .         | -> |      +1       | -1 |   +1    |
1041 	 * |---------------.----.---------|    |---------------|    |---------|
1042 	 *        old_addr+new_len                     old_addr+new_len
1043 	 *
1044 	 * At the point of removing the portion of an existing VMA to make space
1045 	 * for the moved VMA if MREMAP_FIXED, we unmap thusly in the worst case:
1046 	 *
1047 	 *   new_addr   new_addr+new_len         new_addr   new_addr+new_len
1048 	 * |----.---------------.---------|    |----|               |---------|
1049 	 * |    .               .         | -> | +1 |      -1       |   +1    |
1050 	 * |----.---------------.---------|    |----|               |---------|
1051 	 *
1052 	 * Therefore, before we consider the move anything, we have to account
1053 	 * for 2 additional VMAs possibly being created upon these unmappings.
1054 	 */
1055 	if (before_unmaps)
1056 		map_count += 2;
1057 
1058 	/*
1059 	 * At the point of MOVING the VMA:
1060 	 *
1061 	 * We start by copying a VMA, which creates an additional VMA if no
1062 	 * merge occurs, then if not MREMAP_DONTUNMAP, we unmap the source VMA.
1063 	 * In the worst case we might then observe:
1064 	 *
1065 	 *   new_addr   new_addr+new_len         new_addr   new_addr+new_len
1066 	 * |----|               |---------|    |----|---------------|---------|
1067 	 * |    |               |         | -> |    |      +1       |         |
1068 	 * |----|               |---------|    |----|---------------|---------|
1069 	 *
1070 	 *   old_addr   old_addr+old_len         old_addr   old_addr+old_len
1071 	 * |----.---------------.---------|    |----|               |---------|
1072 	 * |    .               .         | -> | +1 |      -1       |   +1    |
1073 	 * |----.---------------.---------|    |----|               |---------|
1074 	 *
1075 	 * Therefore we must check to ensure we have headroom of 2 additional
1076 	 * VMAs.
1077 	 */
1078 	map_count += 2;
1079 
1080 	/* If pre-split, the -1 observed above doesn't apply. */
1081 	if (pre_split)
1082 		map_count++;
1083 
1084 	return map_count <= sys_map_count;
1085 }
1086 
1087 static bool needs_pre_split(struct vma_remap_struct *vrm)
1088 {
1089 	/*
1090 	 * An MREMAP_DONTUNMAP of a mlock()'d VMA needs to unlock the
1091 	 * source VMA, so split in this case.
1092 	 */
1093 	return (vrm->flags & MREMAP_DONTUNMAP) &&
1094 		vma_test(vrm->vma, VMA_LOCKED_BIT);
1095 }
1096 
1097 /* Do we violate the map count limit if we split VMAs when moving the VMA? */
1098 static bool check_map_count_against_split(struct vma_remap_struct *vrm)
1099 {
1100 	return __check_map_count_against_split(current->mm,
1101 		needs_pre_split(vrm), /*before_unmaps=*/false);
1102 }
1103 
1104 /* Do we violate the map count limit if we split VMAs prior to early unmaps? */
1105 static bool check_map_count_against_split_early(struct vma_remap_struct *vrm)
1106 {
1107 	return __check_map_count_against_split(current->mm,
1108 		vrm->flags & MREMAP_DONTUNMAP, /*before_unmaps=*/true);
1109 }
1110 
1111 /*
1112  * Perform checks and preparation before attempting to write a VMA prior to it
1113  * being moved.
1114  */
1115 static unsigned long prep_move_vma(struct vma_remap_struct *vrm)
1116 {
1117 	unsigned long err = 0;
1118 	struct vm_area_struct *vma = vrm->vma;
1119 	unsigned long old_addr = vrm->addr;
1120 	unsigned long old_len = vrm->old_len;
1121 	vm_flags_t dummy = vma->vm_flags;
1122 	const bool split_before = vma->vm_start != old_addr;
1123 	const bool split_after = vma->vm_end != old_addr + old_len;
1124 
1125 	/* Avoid failure later on. */
1126 	if (!check_map_count_against_split(vrm))
1127 		return -ENOMEM;
1128 
1129 	if (vma->vm_ops && vma->vm_ops->may_split) {
1130 		if (split_before)
1131 			err = vma->vm_ops->may_split(vma, old_addr);
1132 		if (!err && split_after)
1133 			err = vma->vm_ops->may_split(vma, old_addr + old_len);
1134 		if (err)
1135 			return err;
1136 	}
1137 
1138 	/*
1139 	 * Advise KSM to break any KSM pages in the area to be moved:
1140 	 * it would be confusing if they were to turn up at the new
1141 	 * location, where they happen to coincide with different KSM
1142 	 * pages recently unmapped.  But leave vma->vm_flags as it was,
1143 	 * so KSM can come around to merge on vma and new_vma afterwards.
1144 	 */
1145 	err = ksm_madvise(vma, old_addr, old_addr + old_len,
1146 			  MADV_UNMERGEABLE, &dummy);
1147 	if (err)
1148 		return err;
1149 
1150 	/*
1151 	 * To account mlock()'d pages correctly in the MREMAP_DONTUNMAP
1152 	 * case perform any split ahead of time for an mlock()'d VMA.
1153 	 */
1154 	if (needs_pre_split(vrm)) {
1155 		VMA_ITERATOR(vmi, vma->vm_mm, old_addr);
1156 
1157 		if (split_before)
1158 			err = split_vma(&vmi, vma, old_addr, 1);
1159 		if (!err && split_after)
1160 			err = split_vma(&vmi, vma, old_addr + old_len, 0);
1161 		vrm->vmi_needs_invalidate = true;
1162 		return err;
1163 	}
1164 
1165 	return 0;
1166 }
1167 
1168 /*
1169  * Unmap source VMA for VMA move, turning it from a copy to a move, being
1170  * careful to ensure we do not underflow memory account while doing so if an
1171  * accountable move.
1172  *
1173  * This is best effort, if we fail to unmap then we simply try to correct
1174  * accounting and exit.
1175  */
1176 static void unmap_source_vma(struct vma_remap_struct *vrm)
1177 {
1178 	struct mm_struct *mm = current->mm;
1179 	unsigned long addr = vrm->addr;
1180 	unsigned long len = vrm->old_len;
1181 	struct vm_area_struct *vma = vrm->vma;
1182 	VMA_ITERATOR(vmi, mm, addr);
1183 	int err;
1184 	unsigned long vm_start;
1185 	unsigned long vm_end;
1186 	/*
1187 	 * It might seem odd that we check for MREMAP_DONTUNMAP here, given this
1188 	 * function implies that we unmap the original VMA, which seems
1189 	 * contradictory.
1190 	 *
1191 	 * However, this occurs when this operation was attempted and an error
1192 	 * arose, in which case we _do_ wish to unmap the _new_ VMA, which means
1193 	 * we actually _do_ want it be unaccounted.
1194 	 */
1195 	bool accountable_move = vma_test(vma, VMA_ACCOUNT_BIT) &&
1196 		!(vrm->flags & MREMAP_DONTUNMAP);
1197 
1198 	/*
1199 	 * So we perform a trick here to prevent incorrect accounting. Any merge
1200 	 * or new VMA allocation performed in copy_vma() does not adjust
1201 	 * accounting, it is expected that callers handle this.
1202 	 *
1203 	 * And indeed we already have, accounting appropriately in the case of
1204 	 * both in vrm_charge().
1205 	 *
1206 	 * However, when we unmap the existing VMA (to effect the move), this
1207 	 * code will, if the VMA has VM_ACCOUNT set, attempt to unaccount
1208 	 * removed pages.
1209 	 *
1210 	 * To avoid this we temporarily clear this flag, reinstating on any
1211 	 * portions of the original VMA that remain.
1212 	 */
1213 	if (accountable_move) {
1214 		vma_clear_flags(vma, VMA_ACCOUNT_BIT);
1215 		/* We are about to split vma, so store the start/end. */
1216 		vm_start = vma->vm_start;
1217 		vm_end = vma->vm_end;
1218 	}
1219 
1220 	err = do_vmi_munmap(&vmi, mm, addr, len, vrm->uf_unmap, /* unlock= */false);
1221 	vrm->vma = NULL; /* Invalidated. */
1222 	vrm->vmi_needs_invalidate = true;
1223 	if (err) {
1224 		/* OOM: unable to split vma, just get accounts right */
1225 		vm_acct_memory(len >> PAGE_SHIFT);
1226 		return;
1227 	}
1228 
1229 	/*
1230 	 * If we mremap() from a VMA like this:
1231 	 *
1232 	 *    addr  end
1233 	 *     |     |
1234 	 *     v     v
1235 	 * |-------------|
1236 	 * |             |
1237 	 * |-------------|
1238 	 *
1239 	 * Having cleared VMA_ACCOUNT_BIT from the whole VMA, after we unmap
1240 	 * above we'll end up with:
1241 	 *
1242 	 *    addr  end
1243 	 *     |     |
1244 	 *     v     v
1245 	 * |---|     |---|
1246 	 * | A |     | B |
1247 	 * |---|     |---|
1248 	 *
1249 	 * The VMI is still pointing at addr, so vma_prev() will give us A, and
1250 	 * a subsequent or lone vma_next() will give as B.
1251 	 *
1252 	 * do_vmi_munmap() will have restored the VMI back to addr.
1253 	 */
1254 	if (accountable_move) {
1255 		unsigned long end = addr + len;
1256 
1257 		if (vm_start < addr) {
1258 			struct vm_area_struct *prev = vma_prev(&vmi);
1259 
1260 			vma_start_write(prev);
1261 			vma_set_flags(prev, VMA_ACCOUNT_BIT);
1262 		}
1263 
1264 		if (vm_end > end) {
1265 			struct vm_area_struct *next = vma_next(&vmi);
1266 
1267 			vma_start_write(next);
1268 			vma_set_flags(next, VMA_ACCOUNT_BIT);
1269 		}
1270 	}
1271 }
1272 
1273 /*
1274  * Copy vrm->vma over to vrm->new_addr possibly adjusting size as part of the
1275  * process. Additionally handle an error occurring on moving of page tables,
1276  * where we reset vrm state to cause unmapping of the new VMA.
1277  *
1278  * Outputs the newly installed VMA to new_vma_ptr. Returns 0 on success or an
1279  * error code.
1280  */
1281 static int copy_vma_and_data(struct vma_remap_struct *vrm,
1282 			     struct vm_area_struct **new_vma_ptr)
1283 {
1284 	const pgoff_t new_pgoff = linear_page_index(vrm->vma, vrm->addr);
1285 	const pgoff_t new_anon_pgoff =
1286 		__linear_anon_page_index(vrm->vma, vrm->addr);
1287 	struct vm_area_struct *vma = vrm->vma;
1288 	struct vm_area_struct *new_vma;
1289 	unsigned long moved_len;
1290 	int err = 0;
1291 	PAGETABLE_MOVE(pmc, NULL, NULL, vrm->addr, vrm->new_addr, vrm->old_len);
1292 
1293 	new_vma = copy_vma(&vma, vrm->new_addr, vrm->new_len, new_pgoff,
1294 			   new_anon_pgoff, &pmc.need_rmap_locks,
1295 			   vrm->flags & MREMAP_DONTUNMAP);
1296 	if (!new_vma) {
1297 		vrm_uncharge(vrm);
1298 		*new_vma_ptr = NULL;
1299 		return -ENOMEM;
1300 	}
1301 	/* By merging, we may have invalidated any iterator in use. */
1302 	if (vma != vrm->vma)
1303 		vrm->vmi_needs_invalidate = true;
1304 
1305 	vrm->vma = vma;
1306 	pmc.old = vma;
1307 	pmc.new = new_vma;
1308 
1309 	moved_len = move_page_tables(&pmc);
1310 	if (moved_len < vrm->old_len)
1311 		err = -ENOMEM;
1312 	else if (vma->vm_ops && vma->vm_ops->mremap)
1313 		err = vma->vm_ops->mremap(new_vma);
1314 
1315 	if (unlikely(err)) {
1316 		PAGETABLE_MOVE(pmc_revert, new_vma, vma, vrm->new_addr,
1317 			       vrm->addr, moved_len);
1318 
1319 		/*
1320 		 * On error, move entries back from new area to old,
1321 		 * which will succeed since page tables still there,
1322 		 * and then proceed to unmap new area instead of old.
1323 		 */
1324 		pmc_revert.need_rmap_locks = true;
1325 		move_page_tables(&pmc_revert);
1326 
1327 		/*
1328 		 * When copy_vma_and_data() returns, the new VMA will be
1329 		 * unmapped rather than the old one.
1330 		 *
1331 		 * When an accountable move is being performed, this unmapping
1332 		 * will not uncharge any expansion, so do that now.
1333 		 *
1334 		 * A move is accountable if the VMA is accountable and
1335 		 * MREMAP_DONTUNMAP is not specified, so only do so if the
1336 		 * latter is true.
1337 		 */
1338 		if (!(vrm->flags & MREMAP_DONTUNMAP))
1339 			vrm_uncharge(vrm);
1340 
1341 		vrm->vma = new_vma;
1342 		vrm->old_len = vrm->new_len;
1343 		vrm->addr = vrm->new_addr;
1344 	} else {
1345 		mremap_userfaultfd_prep(new_vma, vrm->uf);
1346 	}
1347 
1348 	fixup_hugetlb_reservations(vrm->vma);
1349 
1350 	*new_vma_ptr = new_vma;
1351 	return err;
1352 }
1353 
1354 /*
1355  * Perform final tasks for MADV_DONTUNMAP operation, clearing mlock() flag on
1356  * remaining VMA by convention (it cannot be mlock()'d any longer, as pages in
1357  * range are no longer mapped), and removing anon_vma_chain links from it if the
1358  * entire VMA was copied over.
1359  */
1360 static void dontunmap_complete(struct vma_remap_struct *vrm,
1361 			       struct vm_area_struct *new_vma)
1362 {
1363 	unsigned long start = vrm->addr;
1364 	unsigned long end = vrm->addr + vrm->old_len;
1365 	struct vm_area_struct *vma = vrm->vma;
1366 	unsigned long old_start = vma->vm_start;
1367 	unsigned long old_end = vma->vm_end;
1368 
1369 	/* Self-merge is disallowed. */
1370 	VM_WARN_ON_ONCE(new_vma == vma);
1371 
1372 	/* We always clear VMA_LOCKED[ONFAULT]_BIT on the old VMA. */
1373 	vma_clear_flags_mask(vma, VMA_LOCKED_MASK);
1374 
1375 	/*
1376 	 * The anon rmap links of the old vma are no longer needed after its
1377 	 * page table has been moved.
1378 	 */
1379 	if (start == old_start && end == old_end) {
1380 		const pgoff_t pgoff_unfaulted = vma->vm_start >> PAGE_SHIFT;
1381 
1382 		unlink_anon_vmas(vma);
1383 		/*
1384 		 * The VMA is now unfaulted and it is an invariant that
1385 		 * unfaulted anonymous VMAs have page offset equal to
1386 		 * vma->vm_start >> PAGE_SHIFT.
1387 		 */
1388 		vma_set_anon_pgoff(vma, pgoff_unfaulted);
1389 		if (vma_is_anonymous(vma) && !vma->vm_file)
1390 			vma_set_pgoff(vma, pgoff_unfaulted);
1391 	}
1392 }
1393 
1394 static unsigned long move_vma(struct vma_remap_struct *vrm)
1395 {
1396 	const bool is_dontunmap = vrm->flags & MREMAP_DONTUNMAP;
1397 	struct mm_struct *mm = current->mm;
1398 	struct vm_area_struct *new_vma;
1399 	unsigned long hiwater_vm;
1400 	int err;
1401 
1402 	err = prep_move_vma(vrm);
1403 	if (err)
1404 		return err;
1405 
1406 	/*
1407 	 * If accounted, determine the number of bytes the operation will
1408 	 * charge.
1409 	 */
1410 	if (!vrm_calc_charge(vrm))
1411 		return -ENOMEM;
1412 
1413 	/* We don't want racing faults. */
1414 	vma_start_write(vrm->vma);
1415 
1416 	/* Perform copy step. */
1417 	err = copy_vma_and_data(vrm, &new_vma);
1418 	/*
1419 	 * If we established the copied-to VMA, we attempt to recover from the
1420 	 * error by setting the destination VMA to the source VMA and unmapping
1421 	 * it below.
1422 	 */
1423 	if (err && !new_vma)
1424 		return err;
1425 
1426 	/*
1427 	 * If we failed to move page tables we still do total_vm increment
1428 	 * since do_munmap() will decrement it by old_len == new_len.
1429 	 *
1430 	 * Since total_vm is about to be raised artificially high for a
1431 	 * moment, we need to restore high watermark afterwards: if stats
1432 	 * are taken meanwhile, total_vm and hiwater_vm appear too high.
1433 	 * If this were a serious issue, we'd add a flag to do_munmap().
1434 	 */
1435 	hiwater_vm = mm->hiwater_vm;
1436 
1437 	if (unlikely(is_dontunmap && !err))
1438 		dontunmap_complete(vrm, new_vma);
1439 	vrm_stat_account(vrm, vrm->new_len);
1440 	if (!is_dontunmap || err)
1441 		unmap_source_vma(vrm);
1442 
1443 	mm->hiwater_vm = hiwater_vm;
1444 
1445 	return err ? (unsigned long)err : vrm->new_addr;
1446 }
1447 
1448 /*
1449  * The user has requested that the VMA be shrunk (i.e., old_len > new_len), so
1450  * execute this, optionally dropping the mmap lock when we do so.
1451  *
1452  * In both cases this invalidates the VMA, however if we don't drop the lock,
1453  * then load the correct VMA into vrm->vma afterwards.
1454  */
1455 static unsigned long shrink_vma(struct vma_remap_struct *vrm,
1456 				bool drop_lock)
1457 {
1458 	struct mm_struct *mm = current->mm;
1459 	unsigned long unmap_start = vrm->addr + vrm->new_len;
1460 	unsigned long unmap_bytes = vrm->delta;
1461 	unsigned long res;
1462 	VMA_ITERATOR(vmi, mm, unmap_start);
1463 
1464 	VM_BUG_ON(vrm->remap_type != MREMAP_SHRINK);
1465 
1466 	res = do_vmi_munmap(&vmi, mm, unmap_start, unmap_bytes,
1467 			    vrm->uf_unmap, drop_lock);
1468 	vrm->vma = NULL; /* Invalidated. */
1469 	if (res)
1470 		return res;
1471 
1472 	/*
1473 	 * If we've not dropped the lock, then we should reload the VMA to
1474 	 * replace the invalidated VMA with the one that may have now been
1475 	 * split.
1476 	 */
1477 	if (drop_lock) {
1478 		vrm->mmap_locked = false;
1479 	} else {
1480 		vrm->vma = vma_lookup(mm, vrm->addr);
1481 		if (!vrm->vma)
1482 			return -EFAULT;
1483 	}
1484 
1485 	return 0;
1486 }
1487 
1488 /*
1489  * mremap_to() - remap a vma to a new location.
1490  * Returns: The new address of the vma or an error.
1491  */
1492 static unsigned long mremap_to(struct vma_remap_struct *vrm)
1493 {
1494 	struct mm_struct *mm = current->mm;
1495 	unsigned long err;
1496 
1497 	if (vrm->flags & MREMAP_FIXED) {
1498 		/*
1499 		 * In mremap_to().
1500 		 * VMA is moved to dst address, and munmap dst first.
1501 		 * do_munmap will check if dst is sealed.
1502 		 */
1503 		err = do_munmap(mm, vrm->new_addr, vrm->new_len,
1504 				vrm->uf_unmap_early);
1505 		vrm->vma = NULL; /* Invalidated. */
1506 		vrm->vmi_needs_invalidate = true;
1507 		if (err)
1508 			return err;
1509 
1510 		/*
1511 		 * If we remap a portion of a VMA elsewhere in the same VMA,
1512 		 * this can invalidate the old VMA. Reset.
1513 		 */
1514 		vrm->vma = vma_lookup(mm, vrm->addr);
1515 		if (!vrm->vma)
1516 			return -EFAULT;
1517 	}
1518 
1519 	if (vrm->remap_type == MREMAP_SHRINK) {
1520 		err = shrink_vma(vrm, /* drop_lock= */false);
1521 		if (err)
1522 			return err;
1523 
1524 		/* Set up for the move now shrink has been executed. */
1525 		vrm->old_len = vrm->new_len;
1526 		vrm_populate_calculated(vrm);
1527 	}
1528 
1529 	/* MREMAP_DONTUNMAP expands by old_len since old_len == new_len */
1530 	if (vrm->flags & MREMAP_DONTUNMAP) {
1531 		vma_flags_t vma_flags = vrm->vma->flags;
1532 		unsigned long pages = vrm->old_len >> PAGE_SHIFT;
1533 
1534 		if (!may_expand_vm(mm, &vma_flags, pages))
1535 			return -ENOMEM;
1536 	}
1537 
1538 	err = vrm_set_new_addr(vrm);
1539 	if (err)
1540 		return err;
1541 
1542 	return move_vma(vrm);
1543 }
1544 
1545 static int vma_expandable(struct vm_area_struct *vma, unsigned long delta)
1546 {
1547 	unsigned long end = vma->vm_end + delta;
1548 
1549 	if (end < vma->vm_end) /* overflow */
1550 		return 0;
1551 	if (find_vma_intersection(vma->vm_mm, vma->vm_end, end))
1552 		return 0;
1553 	if (get_unmapped_area(NULL, vma->vm_start, end - vma->vm_start,
1554 			      0, MAP_FIXED) & ~PAGE_MASK)
1555 		return 0;
1556 	return 1;
1557 }
1558 
1559 /* Determine whether we are actually able to execute an in-place expansion. */
1560 static bool vrm_can_expand_in_place(struct vma_remap_struct *vrm)
1561 {
1562 	/* Number of bytes from vrm->addr to end of VMA. */
1563 	unsigned long suffix_bytes = vrm->vma->vm_end - vrm->addr;
1564 
1565 	/* If end of range aligns to end of VMA, we can just expand in-place. */
1566 	if (suffix_bytes != vrm->old_len)
1567 		return false;
1568 
1569 	/* Check whether this is feasible. */
1570 	if (!vma_expandable(vrm->vma, vrm->delta))
1571 		return false;
1572 
1573 	return true;
1574 }
1575 
1576 /*
1577  * We know we can expand the VMA in-place by delta pages, so do so.
1578  *
1579  * If we discover the VMA is locked, update mm_struct statistics accordingly and
1580  * indicate so to the caller.
1581  */
1582 static unsigned long expand_vma_in_place(struct vma_remap_struct *vrm)
1583 {
1584 	struct mm_struct *mm = current->mm;
1585 	struct vm_area_struct *vma = vrm->vma;
1586 	VMA_ITERATOR(vmi, mm, vma->vm_end);
1587 
1588 	if (!vrm_calc_charge(vrm))
1589 		return -ENOMEM;
1590 
1591 	/*
1592 	 * Function vma_merge_extend() is called on the
1593 	 * extension we are adding to the already existing vma,
1594 	 * vma_merge_extend() will merge this extension with the
1595 	 * already existing vma (expand operation itself) and
1596 	 * possibly also with the next vma if it becomes
1597 	 * adjacent to the expanded vma and otherwise
1598 	 * compatible.
1599 	 */
1600 	vma = vma_merge_extend(&vmi, vma, vrm->delta);
1601 	if (!vma) {
1602 		vrm_uncharge(vrm);
1603 		return -ENOMEM;
1604 	}
1605 	vrm->vma = vma;
1606 
1607 	vrm_stat_account(vrm, vrm->delta);
1608 
1609 	return 0;
1610 }
1611 
1612 static bool align_hugetlb(struct vma_remap_struct *vrm)
1613 {
1614 	struct hstate *h __maybe_unused = hstate_vma(vrm->vma);
1615 
1616 	vrm->old_len = ALIGN(vrm->old_len, huge_page_size(h));
1617 	vrm->new_len = ALIGN(vrm->new_len, huge_page_size(h));
1618 
1619 	/* addrs must be huge page aligned */
1620 	if (vrm->addr & ~huge_page_mask(h))
1621 		return false;
1622 	if (vrm->new_addr & ~huge_page_mask(h))
1623 		return false;
1624 
1625 	/*
1626 	 * Don't allow remap expansion, because the underlying hugetlb
1627 	 * reservation is not yet capable to handle split reservation.
1628 	 */
1629 	if (vrm->new_len > vrm->old_len)
1630 		return false;
1631 
1632 	return true;
1633 }
1634 
1635 /*
1636  * We are mremap()'ing without specifying a fixed address to move to, but are
1637  * requesting that the VMA's size be increased.
1638  *
1639  * Try to do so in-place, if this fails, then move the VMA to a new location to
1640  * action the change.
1641  */
1642 static unsigned long expand_vma(struct vma_remap_struct *vrm)
1643 {
1644 	unsigned long err;
1645 
1646 	/*
1647 	 * [addr, old_len) spans precisely to the end of the VMA, so try to
1648 	 * expand it in-place.
1649 	 */
1650 	if (vrm_can_expand_in_place(vrm)) {
1651 		err = expand_vma_in_place(vrm);
1652 		if (err)
1653 			return err;
1654 
1655 		/* OK we're done! */
1656 		return vrm->addr;
1657 	}
1658 
1659 	/*
1660 	 * We weren't able to just expand or shrink the area,
1661 	 * we need to create a new one and move it.
1662 	 */
1663 
1664 	/* We're not allowed to move the VMA, so error out. */
1665 	if (!(vrm->flags & MREMAP_MAYMOVE))
1666 		return -ENOMEM;
1667 
1668 	/* Find a new location to move the VMA to. */
1669 	err = vrm_set_new_addr(vrm);
1670 	if (err)
1671 		return err;
1672 
1673 	return move_vma(vrm);
1674 }
1675 
1676 /*
1677  * Attempt to resize the VMA in-place, if we cannot, then move the VMA to the
1678  * first available address to perform the operation.
1679  */
1680 static unsigned long mremap_at(struct vma_remap_struct *vrm)
1681 {
1682 	unsigned long res;
1683 
1684 	switch (vrm->remap_type) {
1685 	case MREMAP_INVALID:
1686 		break;
1687 	case MREMAP_NO_RESIZE:
1688 		/* NO-OP CASE - resizing to the same size. */
1689 		return vrm->addr;
1690 	case MREMAP_SHRINK:
1691 		/*
1692 		 * SHRINK CASE. Can always be done in-place.
1693 		 *
1694 		 * Simply unmap the shrunken portion of the VMA. This does all
1695 		 * the needed commit accounting, and we indicate that the mmap
1696 		 * lock should be dropped.
1697 		 */
1698 		res = shrink_vma(vrm, /* drop_lock= */true);
1699 		if (res)
1700 			return res;
1701 
1702 		return vrm->addr;
1703 	case MREMAP_EXPAND:
1704 		return expand_vma(vrm);
1705 	}
1706 
1707 	/* Should not be possible. */
1708 	WARN_ON_ONCE(1);
1709 	return -EINVAL;
1710 }
1711 
1712 /*
1713  * Will this operation result in the VMA being expanded or moved and thus need
1714  * to map a new portion of virtual address space?
1715  */
1716 static bool vrm_will_map_new(struct vma_remap_struct *vrm)
1717 {
1718 	if (vrm->remap_type == MREMAP_EXPAND)
1719 		return true;
1720 
1721 	if (vrm_implies_new_addr(vrm))
1722 		return true;
1723 
1724 	return false;
1725 }
1726 
1727 /* Does this remap ONLY move mappings? */
1728 static bool vrm_move_only(struct vma_remap_struct *vrm)
1729 {
1730 	if (!(vrm->flags & MREMAP_FIXED))
1731 		return false;
1732 
1733 	if (vrm->old_len != vrm->new_len)
1734 		return false;
1735 
1736 	return true;
1737 }
1738 
1739 static void notify_uffd(struct vma_remap_struct *vrm, bool failed)
1740 {
1741 	struct mm_struct *mm = current->mm;
1742 
1743 	/* Regardless of success/failure, we always notify of any unmaps. */
1744 	userfaultfd_unmap_complete(mm, vrm->uf_unmap_early);
1745 	if (failed)
1746 		mremap_userfaultfd_fail(vrm->uf);
1747 	else
1748 		mremap_userfaultfd_complete(vrm->uf, vrm->addr,
1749 			vrm->new_addr, vrm->old_len);
1750 	userfaultfd_unmap_complete(mm, vrm->uf_unmap);
1751 }
1752 
1753 static bool vma_multi_allowed(struct vm_area_struct *vma)
1754 {
1755 	struct file *file = vma->vm_file;
1756 
1757 	/*
1758 	 * We can't support moving multiple uffd VMAs as notify requires
1759 	 * mmap lock to be dropped.
1760 	 */
1761 	if (userfaultfd_armed(vma))
1762 		return false;
1763 
1764 	/*
1765 	 * Custom get unmapped area might result in MREMAP_FIXED not
1766 	 * being obeyed.
1767 	 */
1768 	if (!file || !file->f_op->get_unmapped_area)
1769 		return true;
1770 	/* Known good. */
1771 	if (vma_is_shmem(vma))
1772 		return true;
1773 	if (vma_is_hugetlb(vma))
1774 		return true;
1775 	if (file->f_op->get_unmapped_area == thp_get_unmapped_area)
1776 		return true;
1777 
1778 	return false;
1779 }
1780 
1781 static int check_prep_vma(struct vma_remap_struct *vrm)
1782 {
1783 	struct vm_area_struct *vma = vrm->vma;
1784 	struct mm_struct *mm = current->mm;
1785 	unsigned long addr = vrm->addr;
1786 	unsigned long old_len, new_len, pgoff;
1787 
1788 	if (!vma)
1789 		return -EFAULT;
1790 
1791 	/* If mseal()'d, mremap() is prohibited. */
1792 	if (vma_is_sealed(vma))
1793 		return -EPERM;
1794 
1795 	/* Align to hugetlb page size, if required. */
1796 	if (vma_is_hugetlb(vma) && !align_hugetlb(vrm))
1797 		return -EINVAL;
1798 
1799 	vrm_populate_calculated(vrm);
1800 	/* For convenience, we set new_addr even if VMA won't move. */
1801 	if (!vrm_implies_new_addr(vrm))
1802 		vrm->new_addr = addr;
1803 
1804 	/* Below only meaningful if we expand or move a VMA. */
1805 	if (!vrm_will_map_new(vrm))
1806 		return 0;
1807 
1808 	old_len = vrm->old_len;
1809 	new_len = vrm->new_len;
1810 
1811 	/*
1812 	 * !old_len is a special case where an attempt is made to 'duplicate'
1813 	 * a mapping.  This makes no sense for private mappings as it will
1814 	 * instead create a fresh/new mapping unrelated to the original.  This
1815 	 * is contrary to the basic idea of mremap which creates new mappings
1816 	 * based on the original.  There are no known use cases for this
1817 	 * behavior.  As a result, fail such attempts.
1818 	 */
1819 	if (!old_len && !vma_test_any(vma, VMA_SHARED_BIT, VMA_MAYSHARE_BIT)) {
1820 		pr_warn_once("%s (%d): attempted to duplicate a private mapping with mremap.  This is not supported.\n",
1821 			     current->comm, current->pid);
1822 		return -EINVAL;
1823 	}
1824 
1825 	if ((vrm->flags & MREMAP_DONTUNMAP) && vma_is_fixed_mapping(vma))
1826 		return -EINVAL;
1827 
1828 	/*
1829 	 * We permit crossing of boundaries for the range being unmapped due to
1830 	 * a shrink.
1831 	 */
1832 	if (vrm->remap_type == MREMAP_SHRINK)
1833 		old_len = new_len;
1834 
1835 	/*
1836 	 * We can't remap across the end of VMAs, as another VMA may be
1837 	 * adjacent:
1838 	 *
1839 	 *       addr   vma->vm_end
1840 	 *  |-----.----------|
1841 	 *  |     .          |
1842 	 *  |-----.----------|
1843 	 *        .<--------->xxx>
1844 	 *            old_len
1845 	 *
1846 	 * We also require that vma->vm_start <= addr < vma->vm_end.
1847 	 */
1848 	if (old_len > vma->vm_end - addr)
1849 		return -EFAULT;
1850 
1851 	if (new_len == old_len)
1852 		return 0;
1853 
1854 	/* We are expanding and the VMA is mlock()'d so we need to populate. */
1855 	if (vma_test(vma, VMA_LOCKED_BIT))
1856 		vrm->populate_expand = true;
1857 
1858 	/* Need to be careful about a growing mapping */
1859 	pgoff = linear_page_index(vma, addr);
1860 	if (pgoff + (new_len >> PAGE_SHIFT) < pgoff)
1861 		return -EINVAL;
1862 
1863 	if (vma_is_fixed_mapping(vma))
1864 		return -EFAULT;
1865 
1866 	if (!mlock_future_ok(mm, vma_test(vma, VMA_LOCKED_BIT), vrm->delta))
1867 		return -EAGAIN;
1868 
1869 	if (!may_expand_vm(mm, &vma->flags, vrm->delta >> PAGE_SHIFT))
1870 		return -ENOMEM;
1871 
1872 	return 0;
1873 }
1874 
1875 /*
1876  * Are the parameters passed to mremap() valid? If so return 0, otherwise return
1877  * error.
1878  */
1879 static unsigned long check_mremap_params(struct vma_remap_struct *vrm)
1880 
1881 {
1882 	unsigned long addr = vrm->addr;
1883 	unsigned long flags = vrm->flags;
1884 
1885 	/* Ensure no unexpected flag values. */
1886 	if (flags & ~(MREMAP_FIXED | MREMAP_MAYMOVE | MREMAP_DONTUNMAP))
1887 		return -EINVAL;
1888 
1889 	/* Start address must be page-aligned. */
1890 	if (offset_in_page(addr))
1891 		return -EINVAL;
1892 
1893 	/*
1894 	 * We allow a zero old-len as a special case
1895 	 * for DOS-emu "duplicate shm area" thing. But
1896 	 * a zero new-len is nonsensical.
1897 	 */
1898 	if (!vrm->new_len)
1899 		return -EINVAL;
1900 
1901 	/* Is the new length silly? */
1902 	if (vrm->new_len > TASK_SIZE)
1903 		return -EINVAL;
1904 
1905 	/* Remainder of checks are for cases with specific new_addr. */
1906 	if (!vrm_implies_new_addr(vrm))
1907 		return 0;
1908 
1909 	/* Is the new address silly? */
1910 	if (vrm->new_addr > TASK_SIZE - vrm->new_len)
1911 		return -EINVAL;
1912 
1913 	/* The new address must be page-aligned. */
1914 	if (offset_in_page(vrm->new_addr))
1915 		return -EINVAL;
1916 
1917 	/* A fixed address implies a move. */
1918 	if (!(flags & MREMAP_MAYMOVE))
1919 		return -EINVAL;
1920 
1921 	/* MREMAP_DONTUNMAP does not allow resizing in the process. */
1922 	if (flags & MREMAP_DONTUNMAP && vrm->old_len != vrm->new_len)
1923 		return -EINVAL;
1924 
1925 	/* Target VMA must not overlap source VMA. */
1926 	if (vrm_overlaps(vrm))
1927 		return -EINVAL;
1928 
1929 	return 0;
1930 }
1931 
1932 static unsigned long remap_move(struct vma_remap_struct *vrm)
1933 {
1934 	struct vm_area_struct *vma;
1935 	unsigned long start = vrm->addr;
1936 	unsigned long end = vrm->addr + vrm->old_len;
1937 	unsigned long new_addr = vrm->new_addr;
1938 	unsigned long target_addr = new_addr;
1939 	unsigned long res = -EFAULT;
1940 	unsigned long last_end;
1941 	bool seen_vma = false;
1942 
1943 	VMA_ITERATOR(vmi, current->mm, start);
1944 
1945 	/*
1946 	 * When moving VMAs we allow for batched moves across multiple VMAs,
1947 	 * with all VMAs in the input range [addr, addr + old_len) being moved
1948 	 * (and split as necessary).
1949 	 */
1950 	for_each_vma_range(vmi, vma, end) {
1951 		/* Account for start, end not aligned with VMA start, end. */
1952 		unsigned long addr = max(vma->vm_start, start);
1953 		unsigned long len = min(end, vma->vm_end) - addr;
1954 		unsigned long offset, res_vma;
1955 		bool multi_allowed;
1956 
1957 		/* No gap permitted at the start of the range. */
1958 		if (!seen_vma && start < vma->vm_start)
1959 			return -EFAULT;
1960 
1961 		/*
1962 		 * To sensibly move multiple VMAs, accounting for the fact that
1963 		 * get_unmapped_area() may align even MAP_FIXED moves, we simply
1964 		 * attempt to move such that the gaps between source VMAs remain
1965 		 * consistent in destination VMAs, e.g.:
1966 		 *
1967 		 *           X        Y                       X        Y
1968 		 *         <--->     <->                    <--->     <->
1969 		 * |-------|   |-----| |-----|      |-------|   |-----| |-----|
1970 		 * |   A   |   |  B  | |  C  | ---> |   A'  |   |  B' | |  C' |
1971 		 * |-------|   |-----| |-----|      |-------|   |-----| |-----|
1972 		 *                               new_addr
1973 		 *
1974 		 * So we map B' at A'->vm_end + X, and C' at B'->vm_end + Y.
1975 		 */
1976 		offset = seen_vma ? vma->vm_start - last_end : 0;
1977 		last_end = vma->vm_end;
1978 
1979 		vrm->vma = vma;
1980 		vrm->addr = addr;
1981 		vrm->new_addr = target_addr + offset;
1982 		vrm->old_len = vrm->new_len = len;
1983 
1984 		multi_allowed = vma_multi_allowed(vma);
1985 		if (!multi_allowed) {
1986 			/* This is not the first VMA, abort immediately. */
1987 			if (seen_vma)
1988 				return -EFAULT;
1989 			/* This is the first, but there are more, abort. */
1990 			if (vma->vm_end < end)
1991 				return -EFAULT;
1992 		}
1993 
1994 		res_vma = check_prep_vma(vrm);
1995 		if (!res_vma)
1996 			res_vma = mremap_to(vrm);
1997 		if (IS_ERR_VALUE(res_vma))
1998 			return res_vma;
1999 
2000 		if (!seen_vma) {
2001 			VM_WARN_ON_ONCE(multi_allowed && res_vma != new_addr);
2002 			res = res_vma;
2003 		}
2004 
2005 		/* mmap lock is only dropped on shrink. */
2006 		VM_WARN_ON_ONCE(!vrm->mmap_locked);
2007 		/* This is a move, no expand should occur. */
2008 		VM_WARN_ON_ONCE(vrm->populate_expand);
2009 
2010 		if (vrm->vmi_needs_invalidate) {
2011 			vma_iter_invalidate(&vmi);
2012 			vrm->vmi_needs_invalidate = false;
2013 		}
2014 		seen_vma = true;
2015 		target_addr = res_vma + vrm->new_len;
2016 	}
2017 
2018 	return res;
2019 }
2020 
2021 static unsigned long do_mremap(struct vma_remap_struct *vrm)
2022 {
2023 	struct mm_struct *mm = current->mm;
2024 	unsigned long res;
2025 	bool failed;
2026 
2027 	vrm->old_len = PAGE_ALIGN(vrm->old_len);
2028 	vrm->new_len = PAGE_ALIGN(vrm->new_len);
2029 
2030 	res = check_mremap_params(vrm);
2031 	if (res)
2032 		return res;
2033 
2034 	if (mmap_write_lock_killable(mm))
2035 		return -EINTR;
2036 	vrm->mmap_locked = true;
2037 
2038 	if (!check_map_count_against_split_early(vrm)) {
2039 		mmap_write_unlock(mm);
2040 		return -ENOMEM;
2041 	}
2042 
2043 	if (vrm_move_only(vrm)) {
2044 		res = remap_move(vrm);
2045 	} else {
2046 		vrm->vma = vma_lookup(current->mm, vrm->addr);
2047 		res = check_prep_vma(vrm);
2048 		if (res)
2049 			goto out;
2050 
2051 		/* Actually execute mremap. */
2052 		res = vrm_implies_new_addr(vrm) ? mremap_to(vrm) : mremap_at(vrm);
2053 	}
2054 
2055 out:
2056 	failed = IS_ERR_VALUE(res);
2057 
2058 	if (vrm->mmap_locked)
2059 		mmap_write_unlock(mm);
2060 
2061 	/* VMA mlock'd + was expanded, so populated expanded region. */
2062 	if (!failed && vrm->populate_expand)
2063 		mm_populate(vrm->new_addr + vrm->old_len, vrm->delta);
2064 
2065 	notify_uffd(vrm, failed);
2066 	return res;
2067 }
2068 
2069 /*
2070  * Expand (or shrink) an existing mapping, potentially moving it at the
2071  * same time (controlled by the MREMAP_MAYMOVE flag and available VM space)
2072  *
2073  * MREMAP_FIXED option added 5-Dec-1999 by Benjamin LaHaise
2074  * This option implies MREMAP_MAYMOVE.
2075  */
2076 SYSCALL_DEFINE5(mremap, unsigned long, addr, unsigned long, old_len,
2077 		unsigned long, new_len, unsigned long, flags,
2078 		unsigned long, new_addr)
2079 {
2080 	struct vm_userfaultfd_ctx uf = NULL_VM_UFFD_CTX;
2081 	LIST_HEAD(uf_unmap_early);
2082 	LIST_HEAD(uf_unmap);
2083 	/*
2084 	 * There is a deliberate asymmetry here: we strip the pointer tag
2085 	 * from the old address but leave the new address alone. This is
2086 	 * for consistency with mmap(), where we prevent the creation of
2087 	 * aliasing mappings in userspace by leaving the tag bits of the
2088 	 * mapping address intact. A non-zero tag will cause the subsequent
2089 	 * range checks to reject the address as invalid.
2090 	 *
2091 	 * See Documentation/arch/arm64/tagged-address-abi.rst for more
2092 	 * information.
2093 	 */
2094 	struct vma_remap_struct vrm = {
2095 		.addr = untagged_addr(addr),
2096 		.old_len = old_len,
2097 		.new_len = new_len,
2098 		.flags = flags,
2099 		.new_addr = new_addr,
2100 
2101 		.uf = &uf,
2102 		.uf_unmap_early = &uf_unmap_early,
2103 		.uf_unmap = &uf_unmap,
2104 
2105 		.remap_type = MREMAP_INVALID, /* We set later. */
2106 	};
2107 
2108 	return do_mremap(&vrm);
2109 }
2110