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