xref: /linux/mm/mremap.c (revision f0953a1bbaca71e1ebbcb9864eb1b273156157ed)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *	mm/mremap.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  *	(C) Copyright 1996 Linus Torvalds
61da177e4SLinus Torvalds  *
7046c6884SAlan Cox  *	Address space accounting code	<alan@lxorguk.ukuu.org.uk>
81da177e4SLinus Torvalds  *	(C) Copyright 2002 Red Hat Inc, All Rights Reserved
91da177e4SLinus Torvalds  */
101da177e4SLinus Torvalds 
111da177e4SLinus Torvalds #include <linux/mm.h>
121da177e4SLinus Torvalds #include <linux/hugetlb.h>
131da177e4SLinus Torvalds #include <linux/shm.h>
141ff82995SHugh Dickins #include <linux/ksm.h>
151da177e4SLinus Torvalds #include <linux/mman.h>
161da177e4SLinus Torvalds #include <linux/swap.h>
17c59ede7bSRandy.Dunlap #include <linux/capability.h>
181da177e4SLinus Torvalds #include <linux/fs.h>
196dec97dcSCyrill Gorcunov #include <linux/swapops.h>
201da177e4SLinus Torvalds #include <linux/highmem.h>
211da177e4SLinus Torvalds #include <linux/security.h>
221da177e4SLinus Torvalds #include <linux/syscalls.h>
23cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
242581d202SPaul McQuade #include <linux/uaccess.h>
2572f87654SPavel Emelyanov #include <linux/userfaultfd_k.h>
261da177e4SLinus Torvalds 
271da177e4SLinus Torvalds #include <asm/cacheflush.h>
281da177e4SLinus Torvalds #include <asm/tlbflush.h>
291da177e4SLinus Torvalds 
30ba470de4SRik van Riel #include "internal.h"
31ba470de4SRik van Riel 
32c49dd340SKalesh Singh static pud_t *get_old_pud(struct mm_struct *mm, unsigned long addr)
331da177e4SLinus Torvalds {
341da177e4SLinus Torvalds 	pgd_t *pgd;
35c2febafcSKirill A. Shutemov 	p4d_t *p4d;
361da177e4SLinus Torvalds 	pud_t *pud;
371da177e4SLinus Torvalds 
381da177e4SLinus Torvalds 	pgd = pgd_offset(mm, addr);
391da177e4SLinus Torvalds 	if (pgd_none_or_clear_bad(pgd))
401da177e4SLinus Torvalds 		return NULL;
411da177e4SLinus Torvalds 
42c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
43c2febafcSKirill A. Shutemov 	if (p4d_none_or_clear_bad(p4d))
44c2febafcSKirill A. Shutemov 		return NULL;
45c2febafcSKirill A. Shutemov 
46c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
471da177e4SLinus Torvalds 	if (pud_none_or_clear_bad(pud))
481da177e4SLinus Torvalds 		return NULL;
491da177e4SLinus Torvalds 
50c49dd340SKalesh Singh 	return pud;
51c49dd340SKalesh Singh }
52c49dd340SKalesh Singh 
53c49dd340SKalesh Singh static pmd_t *get_old_pmd(struct mm_struct *mm, unsigned long addr)
54c49dd340SKalesh Singh {
55c49dd340SKalesh Singh 	pud_t *pud;
56c49dd340SKalesh Singh 	pmd_t *pmd;
57c49dd340SKalesh Singh 
58c49dd340SKalesh Singh 	pud = get_old_pud(mm, addr);
59c49dd340SKalesh Singh 	if (!pud)
60c49dd340SKalesh Singh 		return NULL;
61c49dd340SKalesh Singh 
621da177e4SLinus Torvalds 	pmd = pmd_offset(pud, addr);
6337a1c49aSAndrea Arcangeli 	if (pmd_none(*pmd))
641da177e4SLinus Torvalds 		return NULL;
651da177e4SLinus Torvalds 
667be7a546SHugh Dickins 	return pmd;
671da177e4SLinus Torvalds }
681da177e4SLinus Torvalds 
69c49dd340SKalesh Singh static pud_t *alloc_new_pud(struct mm_struct *mm, struct vm_area_struct *vma,
708ac1f832SAndrea Arcangeli 			    unsigned long addr)
711da177e4SLinus Torvalds {
721da177e4SLinus Torvalds 	pgd_t *pgd;
73c2febafcSKirill A. Shutemov 	p4d_t *p4d;
741da177e4SLinus Torvalds 
751da177e4SLinus Torvalds 	pgd = pgd_offset(mm, addr);
76c2febafcSKirill A. Shutemov 	p4d = p4d_alloc(mm, pgd, addr);
77c2febafcSKirill A. Shutemov 	if (!p4d)
78c2febafcSKirill A. Shutemov 		return NULL;
79c49dd340SKalesh Singh 
80c49dd340SKalesh Singh 	return pud_alloc(mm, p4d, addr);
81c49dd340SKalesh Singh }
82c49dd340SKalesh Singh 
83c49dd340SKalesh Singh static pmd_t *alloc_new_pmd(struct mm_struct *mm, struct vm_area_struct *vma,
84c49dd340SKalesh Singh 			    unsigned long addr)
85c49dd340SKalesh Singh {
86c49dd340SKalesh Singh 	pud_t *pud;
87c49dd340SKalesh Singh 	pmd_t *pmd;
88c49dd340SKalesh Singh 
89c49dd340SKalesh Singh 	pud = alloc_new_pud(mm, vma, addr);
901da177e4SLinus Torvalds 	if (!pud)
91c74df32cSHugh Dickins 		return NULL;
927be7a546SHugh Dickins 
931da177e4SLinus Torvalds 	pmd = pmd_alloc(mm, pud, addr);
9457a8f0cdSHugh Dickins 	if (!pmd)
95c74df32cSHugh Dickins 		return NULL;
967be7a546SHugh Dickins 
978ac1f832SAndrea Arcangeli 	VM_BUG_ON(pmd_trans_huge(*pmd));
98c74df32cSHugh Dickins 
997be7a546SHugh Dickins 	return pmd;
1001da177e4SLinus Torvalds }
1011da177e4SLinus Torvalds 
1021d069b7dSHugh Dickins static void take_rmap_locks(struct vm_area_struct *vma)
1031d069b7dSHugh Dickins {
1041d069b7dSHugh Dickins 	if (vma->vm_file)
1051d069b7dSHugh Dickins 		i_mmap_lock_write(vma->vm_file->f_mapping);
1061d069b7dSHugh Dickins 	if (vma->anon_vma)
1071d069b7dSHugh Dickins 		anon_vma_lock_write(vma->anon_vma);
1081d069b7dSHugh Dickins }
1091d069b7dSHugh Dickins 
1101d069b7dSHugh Dickins static void drop_rmap_locks(struct vm_area_struct *vma)
1111d069b7dSHugh Dickins {
1121d069b7dSHugh Dickins 	if (vma->anon_vma)
1131d069b7dSHugh Dickins 		anon_vma_unlock_write(vma->anon_vma);
1141d069b7dSHugh Dickins 	if (vma->vm_file)
1151d069b7dSHugh Dickins 		i_mmap_unlock_write(vma->vm_file->f_mapping);
1161d069b7dSHugh Dickins }
1171d069b7dSHugh Dickins 
1186dec97dcSCyrill Gorcunov static pte_t move_soft_dirty_pte(pte_t pte)
1196dec97dcSCyrill Gorcunov {
1206dec97dcSCyrill Gorcunov 	/*
1216dec97dcSCyrill Gorcunov 	 * Set soft dirty bit so we can notice
1226dec97dcSCyrill Gorcunov 	 * in userspace the ptes were moved.
1236dec97dcSCyrill Gorcunov 	 */
1246dec97dcSCyrill Gorcunov #ifdef CONFIG_MEM_SOFT_DIRTY
1256dec97dcSCyrill Gorcunov 	if (pte_present(pte))
1266dec97dcSCyrill Gorcunov 		pte = pte_mksoft_dirty(pte);
1276dec97dcSCyrill Gorcunov 	else if (is_swap_pte(pte))
1286dec97dcSCyrill Gorcunov 		pte = pte_swp_mksoft_dirty(pte);
1296dec97dcSCyrill Gorcunov #endif
1306dec97dcSCyrill Gorcunov 	return pte;
1316dec97dcSCyrill Gorcunov }
1326dec97dcSCyrill Gorcunov 
1337be7a546SHugh Dickins static void move_ptes(struct vm_area_struct *vma, pmd_t *old_pmd,
1347be7a546SHugh Dickins 		unsigned long old_addr, unsigned long old_end,
1357be7a546SHugh Dickins 		struct vm_area_struct *new_vma, pmd_t *new_pmd,
136eb66ae03SLinus Torvalds 		unsigned long new_addr, bool need_rmap_locks)
1371da177e4SLinus Torvalds {
1381da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
1397be7a546SHugh Dickins 	pte_t *old_pte, *new_pte, pte;
1404c21e2f2SHugh Dickins 	spinlock_t *old_ptl, *new_ptl;
1415d190420SAaron Lu 	bool force_flush = false;
1425d190420SAaron Lu 	unsigned long len = old_end - old_addr;
1431da177e4SLinus Torvalds 
1441da177e4SLinus Torvalds 	/*
145c8c06efaSDavidlohr Bueso 	 * When need_rmap_locks is true, we take the i_mmap_rwsem and anon_vma
14638a76013SMichel Lespinasse 	 * locks to ensure that rmap will always observe either the old or the
14738a76013SMichel Lespinasse 	 * new ptes. This is the easiest way to avoid races with
14838a76013SMichel Lespinasse 	 * truncate_pagecache(), page migration, etc...
14938a76013SMichel Lespinasse 	 *
15038a76013SMichel Lespinasse 	 * When need_rmap_locks is false, we use other ways to avoid
15138a76013SMichel Lespinasse 	 * such races:
15238a76013SMichel Lespinasse 	 *
15338a76013SMichel Lespinasse 	 * - During exec() shift_arg_pages(), we use a specially tagged vma
154222100eeSAnshuman Khandual 	 *   which rmap call sites look for using vma_is_temporary_stack().
15538a76013SMichel Lespinasse 	 *
15638a76013SMichel Lespinasse 	 * - During mremap(), new_vma is often known to be placed after vma
15738a76013SMichel Lespinasse 	 *   in rmap traversal order. This ensures rmap will always observe
15838a76013SMichel Lespinasse 	 *   either the old pte, or the new pte, or both (the page table locks
15938a76013SMichel Lespinasse 	 *   serialize access to individual ptes, but only rmap traversal
16038a76013SMichel Lespinasse 	 *   order guarantees that we won't miss both the old and new ptes).
1611da177e4SLinus Torvalds 	 */
1621d069b7dSHugh Dickins 	if (need_rmap_locks)
1631d069b7dSHugh Dickins 		take_rmap_locks(vma);
1641da177e4SLinus Torvalds 
1654c21e2f2SHugh Dickins 	/*
1664c21e2f2SHugh Dickins 	 * We don't have to worry about the ordering of src and dst
167c1e8d7c6SMichel Lespinasse 	 * pte locks because exclusive mmap_lock prevents deadlock.
1684c21e2f2SHugh Dickins 	 */
169c74df32cSHugh Dickins 	old_pte = pte_offset_map_lock(mm, old_pmd, old_addr, &old_ptl);
170ece0e2b6SPeter Zijlstra 	new_pte = pte_offset_map(new_pmd, new_addr);
1714c21e2f2SHugh Dickins 	new_ptl = pte_lockptr(mm, new_pmd);
1724c21e2f2SHugh Dickins 	if (new_ptl != old_ptl)
173f20dc5f7SIngo Molnar 		spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
1743ea27719SMel Gorman 	flush_tlb_batched_pending(vma->vm_mm);
1756606c3e0SZachary Amsden 	arch_enter_lazy_mmu_mode();
1768b1f3124SNick Piggin 
1777be7a546SHugh Dickins 	for (; old_addr < old_end; old_pte++, old_addr += PAGE_SIZE,
1787be7a546SHugh Dickins 				   new_pte++, new_addr += PAGE_SIZE) {
1797be7a546SHugh Dickins 		if (pte_none(*old_pte))
1807be7a546SHugh Dickins 			continue;
1815d190420SAaron Lu 
1827b6efc2bSAndrea Arcangeli 		pte = ptep_get_and_clear(mm, old_addr, old_pte);
183a2ce2666SAaron Lu 		/*
184eb66ae03SLinus Torvalds 		 * If we are remapping a valid PTE, make sure
185a2ce2666SAaron Lu 		 * to flush TLB before we drop the PTL for the
186eb66ae03SLinus Torvalds 		 * PTE.
187a2ce2666SAaron Lu 		 *
188eb66ae03SLinus Torvalds 		 * NOTE! Both old and new PTL matter: the old one
189eb66ae03SLinus Torvalds 		 * for racing with page_mkclean(), the new one to
190eb66ae03SLinus Torvalds 		 * make sure the physical page stays valid until
191eb66ae03SLinus Torvalds 		 * the TLB entry for the old mapping has been
192eb66ae03SLinus Torvalds 		 * flushed.
193a2ce2666SAaron Lu 		 */
194eb66ae03SLinus Torvalds 		if (pte_present(pte))
195a2ce2666SAaron Lu 			force_flush = true;
1967be7a546SHugh Dickins 		pte = move_pte(pte, new_vma->vm_page_prot, old_addr, new_addr);
1976dec97dcSCyrill Gorcunov 		pte = move_soft_dirty_pte(pte);
1986dec97dcSCyrill Gorcunov 		set_pte_at(mm, new_addr, new_pte, pte);
1991da177e4SLinus Torvalds 	}
2007be7a546SHugh Dickins 
2016606c3e0SZachary Amsden 	arch_leave_lazy_mmu_mode();
202eb66ae03SLinus Torvalds 	if (force_flush)
203eb66ae03SLinus Torvalds 		flush_tlb_range(vma, old_end - len, old_end);
2044c21e2f2SHugh Dickins 	if (new_ptl != old_ptl)
2054c21e2f2SHugh Dickins 		spin_unlock(new_ptl);
206ece0e2b6SPeter Zijlstra 	pte_unmap(new_pte - 1);
207c74df32cSHugh Dickins 	pte_unmap_unlock(old_pte - 1, old_ptl);
2081d069b7dSHugh Dickins 	if (need_rmap_locks)
2091d069b7dSHugh Dickins 		drop_rmap_locks(vma);
2101da177e4SLinus Torvalds }
2111da177e4SLinus Torvalds 
2122c91bd4aSJoel Fernandes (Google) #ifdef CONFIG_HAVE_MOVE_PMD
2132c91bd4aSJoel Fernandes (Google) static bool move_normal_pmd(struct vm_area_struct *vma, unsigned long old_addr,
214b8aa9d9dSWei Yang 		  unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd)
2152c91bd4aSJoel Fernandes (Google) {
2162c91bd4aSJoel Fernandes (Google) 	spinlock_t *old_ptl, *new_ptl;
2172c91bd4aSJoel Fernandes (Google) 	struct mm_struct *mm = vma->vm_mm;
2182c91bd4aSJoel Fernandes (Google) 	pmd_t pmd;
2192c91bd4aSJoel Fernandes (Google) 
2202c91bd4aSJoel Fernandes (Google) 	/*
2212c91bd4aSJoel Fernandes (Google) 	 * The destination pmd shouldn't be established, free_pgtables()
222f81fdd0cSLinus Torvalds 	 * should have released it.
223f81fdd0cSLinus Torvalds 	 *
224f81fdd0cSLinus Torvalds 	 * However, there's a case during execve() where we use mremap
225f81fdd0cSLinus Torvalds 	 * to move the initial stack, and in that case the target area
226f81fdd0cSLinus Torvalds 	 * may overlap the source area (always moving down).
227f81fdd0cSLinus Torvalds 	 *
228f81fdd0cSLinus Torvalds 	 * If everything is PMD-aligned, that works fine, as moving
229f81fdd0cSLinus Torvalds 	 * each pmd down will clear the source pmd. But if we first
230f81fdd0cSLinus Torvalds 	 * have a few 4kB-only pages that get moved down, and then
231f81fdd0cSLinus Torvalds 	 * hit the "now the rest is PMD-aligned, let's do everything
232f81fdd0cSLinus Torvalds 	 * one pmd at a time", we will still have the old (now empty
233f81fdd0cSLinus Torvalds 	 * of any 4kB pages, but still there) PMD in the page table
234f81fdd0cSLinus Torvalds 	 * tree.
235f81fdd0cSLinus Torvalds 	 *
236f81fdd0cSLinus Torvalds 	 * Warn on it once - because we really should try to figure
237f81fdd0cSLinus Torvalds 	 * out how to do this better - but then say "I won't move
238f81fdd0cSLinus Torvalds 	 * this pmd".
239f81fdd0cSLinus Torvalds 	 *
240f81fdd0cSLinus Torvalds 	 * One alternative might be to just unmap the target pmd at
241f81fdd0cSLinus Torvalds 	 * this point, and verify that it really is empty. We'll see.
2422c91bd4aSJoel Fernandes (Google) 	 */
243f81fdd0cSLinus Torvalds 	if (WARN_ON_ONCE(!pmd_none(*new_pmd)))
2442c91bd4aSJoel Fernandes (Google) 		return false;
2452c91bd4aSJoel Fernandes (Google) 
2462c91bd4aSJoel Fernandes (Google) 	/*
2472c91bd4aSJoel Fernandes (Google) 	 * We don't have to worry about the ordering of src and dst
248c1e8d7c6SMichel Lespinasse 	 * ptlocks because exclusive mmap_lock prevents deadlock.
2492c91bd4aSJoel Fernandes (Google) 	 */
2502c91bd4aSJoel Fernandes (Google) 	old_ptl = pmd_lock(vma->vm_mm, old_pmd);
2512c91bd4aSJoel Fernandes (Google) 	new_ptl = pmd_lockptr(mm, new_pmd);
2522c91bd4aSJoel Fernandes (Google) 	if (new_ptl != old_ptl)
2532c91bd4aSJoel Fernandes (Google) 		spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
2542c91bd4aSJoel Fernandes (Google) 
2552c91bd4aSJoel Fernandes (Google) 	/* Clear the pmd */
2562c91bd4aSJoel Fernandes (Google) 	pmd = *old_pmd;
2572c91bd4aSJoel Fernandes (Google) 	pmd_clear(old_pmd);
2582c91bd4aSJoel Fernandes (Google) 
2592c91bd4aSJoel Fernandes (Google) 	VM_BUG_ON(!pmd_none(*new_pmd));
2602c91bd4aSJoel Fernandes (Google) 
2612c91bd4aSJoel Fernandes (Google) 	/* Set the new pmd */
2622c91bd4aSJoel Fernandes (Google) 	set_pmd_at(mm, new_addr, new_pmd, pmd);
2632c91bd4aSJoel Fernandes (Google) 	flush_tlb_range(vma, old_addr, old_addr + PMD_SIZE);
2642c91bd4aSJoel Fernandes (Google) 	if (new_ptl != old_ptl)
2652c91bd4aSJoel Fernandes (Google) 		spin_unlock(new_ptl);
2662c91bd4aSJoel Fernandes (Google) 	spin_unlock(old_ptl);
2672c91bd4aSJoel Fernandes (Google) 
2682c91bd4aSJoel Fernandes (Google) 	return true;
2692c91bd4aSJoel Fernandes (Google) }
270c49dd340SKalesh Singh #else
271c49dd340SKalesh Singh static inline bool move_normal_pmd(struct vm_area_struct *vma,
272c49dd340SKalesh Singh 		unsigned long old_addr, unsigned long new_addr, pmd_t *old_pmd,
273c49dd340SKalesh Singh 		pmd_t *new_pmd)
274c49dd340SKalesh Singh {
275c49dd340SKalesh Singh 	return false;
276c49dd340SKalesh Singh }
2772c91bd4aSJoel Fernandes (Google) #endif
2782c91bd4aSJoel Fernandes (Google) 
279c49dd340SKalesh Singh #ifdef CONFIG_HAVE_MOVE_PUD
280c49dd340SKalesh Singh static bool move_normal_pud(struct vm_area_struct *vma, unsigned long old_addr,
281c49dd340SKalesh Singh 		  unsigned long new_addr, pud_t *old_pud, pud_t *new_pud)
282c49dd340SKalesh Singh {
283c49dd340SKalesh Singh 	spinlock_t *old_ptl, *new_ptl;
284c49dd340SKalesh Singh 	struct mm_struct *mm = vma->vm_mm;
285c49dd340SKalesh Singh 	pud_t pud;
286c49dd340SKalesh Singh 
287c49dd340SKalesh Singh 	/*
288c49dd340SKalesh Singh 	 * The destination pud shouldn't be established, free_pgtables()
289c49dd340SKalesh Singh 	 * should have released it.
290c49dd340SKalesh Singh 	 */
291c49dd340SKalesh Singh 	if (WARN_ON_ONCE(!pud_none(*new_pud)))
292c49dd340SKalesh Singh 		return false;
293c49dd340SKalesh Singh 
294c49dd340SKalesh Singh 	/*
295c49dd340SKalesh Singh 	 * We don't have to worry about the ordering of src and dst
296c49dd340SKalesh Singh 	 * ptlocks because exclusive mmap_lock prevents deadlock.
297c49dd340SKalesh Singh 	 */
298c49dd340SKalesh Singh 	old_ptl = pud_lock(vma->vm_mm, old_pud);
299c49dd340SKalesh Singh 	new_ptl = pud_lockptr(mm, new_pud);
300c49dd340SKalesh Singh 	if (new_ptl != old_ptl)
301c49dd340SKalesh Singh 		spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING);
302c49dd340SKalesh Singh 
303c49dd340SKalesh Singh 	/* Clear the pud */
304c49dd340SKalesh Singh 	pud = *old_pud;
305c49dd340SKalesh Singh 	pud_clear(old_pud);
306c49dd340SKalesh Singh 
307c49dd340SKalesh Singh 	VM_BUG_ON(!pud_none(*new_pud));
308c49dd340SKalesh Singh 
309c49dd340SKalesh Singh 	/* Set the new pud */
310c49dd340SKalesh Singh 	set_pud_at(mm, new_addr, new_pud, pud);
311c49dd340SKalesh Singh 	flush_tlb_range(vma, old_addr, old_addr + PUD_SIZE);
312c49dd340SKalesh Singh 	if (new_ptl != old_ptl)
313c49dd340SKalesh Singh 		spin_unlock(new_ptl);
314c49dd340SKalesh Singh 	spin_unlock(old_ptl);
315c49dd340SKalesh Singh 
316c49dd340SKalesh Singh 	return true;
317c49dd340SKalesh Singh }
318c49dd340SKalesh Singh #else
319c49dd340SKalesh Singh static inline bool move_normal_pud(struct vm_area_struct *vma,
320c49dd340SKalesh Singh 		unsigned long old_addr, unsigned long new_addr, pud_t *old_pud,
321c49dd340SKalesh Singh 		pud_t *new_pud)
322c49dd340SKalesh Singh {
323c49dd340SKalesh Singh 	return false;
324c49dd340SKalesh Singh }
325c49dd340SKalesh Singh #endif
326c49dd340SKalesh Singh 
327c49dd340SKalesh Singh enum pgt_entry {
328c49dd340SKalesh Singh 	NORMAL_PMD,
329c49dd340SKalesh Singh 	HPAGE_PMD,
330c49dd340SKalesh Singh 	NORMAL_PUD,
331c49dd340SKalesh Singh };
332c49dd340SKalesh Singh 
333c49dd340SKalesh Singh /*
334c49dd340SKalesh Singh  * Returns an extent of the corresponding size for the pgt_entry specified if
335c49dd340SKalesh Singh  * valid. Else returns a smaller extent bounded by the end of the source and
336c49dd340SKalesh Singh  * destination pgt_entry.
337c49dd340SKalesh Singh  */
338a30a2909SArnd Bergmann static __always_inline unsigned long get_extent(enum pgt_entry entry,
339a30a2909SArnd Bergmann 			unsigned long old_addr, unsigned long old_end,
340a30a2909SArnd Bergmann 			unsigned long new_addr)
341c49dd340SKalesh Singh {
342c49dd340SKalesh Singh 	unsigned long next, extent, mask, size;
343c49dd340SKalesh Singh 
344c49dd340SKalesh Singh 	switch (entry) {
345c49dd340SKalesh Singh 	case HPAGE_PMD:
346c49dd340SKalesh Singh 	case NORMAL_PMD:
347c49dd340SKalesh Singh 		mask = PMD_MASK;
348c49dd340SKalesh Singh 		size = PMD_SIZE;
349c49dd340SKalesh Singh 		break;
350c49dd340SKalesh Singh 	case NORMAL_PUD:
351c49dd340SKalesh Singh 		mask = PUD_MASK;
352c49dd340SKalesh Singh 		size = PUD_SIZE;
353c49dd340SKalesh Singh 		break;
354c49dd340SKalesh Singh 	default:
355c49dd340SKalesh Singh 		BUILD_BUG();
356c49dd340SKalesh Singh 		break;
357c49dd340SKalesh Singh 	}
358c49dd340SKalesh Singh 
359c49dd340SKalesh Singh 	next = (old_addr + size) & mask;
360c49dd340SKalesh Singh 	/* even if next overflowed, extent below will be ok */
361e05986eeSKalesh Singh 	extent = next - old_addr;
362e05986eeSKalesh Singh 	if (extent > old_end - old_addr)
363e05986eeSKalesh Singh 		extent = old_end - old_addr;
364c49dd340SKalesh Singh 	next = (new_addr + size) & mask;
365c49dd340SKalesh Singh 	if (extent > next - new_addr)
366c49dd340SKalesh Singh 		extent = next - new_addr;
367c49dd340SKalesh Singh 	return extent;
368c49dd340SKalesh Singh }
369c49dd340SKalesh Singh 
370c49dd340SKalesh Singh /*
371c49dd340SKalesh Singh  * Attempts to speedup the move by moving entry at the level corresponding to
372c49dd340SKalesh Singh  * pgt_entry. Returns true if the move was successful, else false.
373c49dd340SKalesh Singh  */
374c49dd340SKalesh Singh static bool move_pgt_entry(enum pgt_entry entry, struct vm_area_struct *vma,
375c49dd340SKalesh Singh 			unsigned long old_addr, unsigned long new_addr,
376c49dd340SKalesh Singh 			void *old_entry, void *new_entry, bool need_rmap_locks)
377c49dd340SKalesh Singh {
378c49dd340SKalesh Singh 	bool moved = false;
379c49dd340SKalesh Singh 
380c49dd340SKalesh Singh 	/* See comment in move_ptes() */
381c49dd340SKalesh Singh 	if (need_rmap_locks)
382c49dd340SKalesh Singh 		take_rmap_locks(vma);
383c49dd340SKalesh Singh 
384c49dd340SKalesh Singh 	switch (entry) {
385c49dd340SKalesh Singh 	case NORMAL_PMD:
386c49dd340SKalesh Singh 		moved = move_normal_pmd(vma, old_addr, new_addr, old_entry,
387c49dd340SKalesh Singh 					new_entry);
388c49dd340SKalesh Singh 		break;
389c49dd340SKalesh Singh 	case NORMAL_PUD:
390c49dd340SKalesh Singh 		moved = move_normal_pud(vma, old_addr, new_addr, old_entry,
391c49dd340SKalesh Singh 					new_entry);
392c49dd340SKalesh Singh 		break;
393c49dd340SKalesh Singh 	case HPAGE_PMD:
394c49dd340SKalesh Singh 		moved = IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
395c49dd340SKalesh Singh 			move_huge_pmd(vma, old_addr, new_addr, old_entry,
396c49dd340SKalesh Singh 				      new_entry);
397c49dd340SKalesh Singh 		break;
398c49dd340SKalesh Singh 	default:
399c49dd340SKalesh Singh 		WARN_ON_ONCE(1);
400c49dd340SKalesh Singh 		break;
401c49dd340SKalesh Singh 	}
402c49dd340SKalesh Singh 
403c49dd340SKalesh Singh 	if (need_rmap_locks)
404c49dd340SKalesh Singh 		drop_rmap_locks(vma);
405c49dd340SKalesh Singh 
406c49dd340SKalesh Singh 	return moved;
407c49dd340SKalesh Singh }
408c49dd340SKalesh Singh 
409b6a2fea3SOllie Wild unsigned long move_page_tables(struct vm_area_struct *vma,
4101da177e4SLinus Torvalds 		unsigned long old_addr, struct vm_area_struct *new_vma,
41138a76013SMichel Lespinasse 		unsigned long new_addr, unsigned long len,
41238a76013SMichel Lespinasse 		bool need_rmap_locks)
4131da177e4SLinus Torvalds {
414c49dd340SKalesh Singh 	unsigned long extent, old_end;
415ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
4167be7a546SHugh Dickins 	pmd_t *old_pmd, *new_pmd;
4171da177e4SLinus Torvalds 
4187be7a546SHugh Dickins 	old_end = old_addr + len;
4197be7a546SHugh Dickins 	flush_cache_range(vma, old_addr, old_end);
4201da177e4SLinus Torvalds 
4216f4f13e8SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
4226f4f13e8SJérôme Glisse 				old_addr, old_end);
423ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
4247b6efc2bSAndrea Arcangeli 
4257be7a546SHugh Dickins 	for (; old_addr < old_end; old_addr += extent, new_addr += extent) {
4261da177e4SLinus Torvalds 		cond_resched();
427c49dd340SKalesh Singh 		/*
428c49dd340SKalesh Singh 		 * If extent is PUD-sized try to speed up the move by moving at the
429c49dd340SKalesh Singh 		 * PUD level if possible.
430c49dd340SKalesh Singh 		 */
431c49dd340SKalesh Singh 		extent = get_extent(NORMAL_PUD, old_addr, old_end, new_addr);
432c49dd340SKalesh Singh 		if (IS_ENABLED(CONFIG_HAVE_MOVE_PUD) && extent == PUD_SIZE) {
433c49dd340SKalesh Singh 			pud_t *old_pud, *new_pud;
434c49dd340SKalesh Singh 
435c49dd340SKalesh Singh 			old_pud = get_old_pud(vma->vm_mm, old_addr);
436c49dd340SKalesh Singh 			if (!old_pud)
437c49dd340SKalesh Singh 				continue;
438c49dd340SKalesh Singh 			new_pud = alloc_new_pud(vma->vm_mm, vma, new_addr);
439c49dd340SKalesh Singh 			if (!new_pud)
440c49dd340SKalesh Singh 				break;
441c49dd340SKalesh Singh 			if (move_pgt_entry(NORMAL_PUD, vma, old_addr, new_addr,
442c49dd340SKalesh Singh 					   old_pud, new_pud, need_rmap_locks))
443c49dd340SKalesh Singh 				continue;
444c49dd340SKalesh Singh 		}
445c49dd340SKalesh Singh 
446c49dd340SKalesh Singh 		extent = get_extent(NORMAL_PMD, old_addr, old_end, new_addr);
4477be7a546SHugh Dickins 		old_pmd = get_old_pmd(vma->vm_mm, old_addr);
4487be7a546SHugh Dickins 		if (!old_pmd)
4497be7a546SHugh Dickins 			continue;
4508ac1f832SAndrea Arcangeli 		new_pmd = alloc_new_pmd(vma->vm_mm, vma, new_addr);
4517be7a546SHugh Dickins 		if (!new_pmd)
4527be7a546SHugh Dickins 			break;
453c49dd340SKalesh Singh 		if (is_swap_pmd(*old_pmd) || pmd_trans_huge(*old_pmd) ||
454c49dd340SKalesh Singh 		    pmd_devmap(*old_pmd)) {
455c49dd340SKalesh Singh 			if (extent == HPAGE_PMD_SIZE &&
456c49dd340SKalesh Singh 			    move_pgt_entry(HPAGE_PMD, vma, old_addr, new_addr,
457c49dd340SKalesh Singh 					   old_pmd, new_pmd, need_rmap_locks))
45837a1c49aSAndrea Arcangeli 				continue;
4594b471e88SKirill A. Shutemov 			split_huge_pmd(vma, old_pmd, old_addr);
460337d9abfSNaoya Horiguchi 			if (pmd_trans_unstable(old_pmd))
4616b9116a6SKirill A. Shutemov 				continue;
462c49dd340SKalesh Singh 		} else if (IS_ENABLED(CONFIG_HAVE_MOVE_PMD) &&
463c49dd340SKalesh Singh 			   extent == PMD_SIZE) {
4642c91bd4aSJoel Fernandes (Google) 			/*
4652c91bd4aSJoel Fernandes (Google) 			 * If the extent is PMD-sized, try to speed the move by
4662c91bd4aSJoel Fernandes (Google) 			 * moving at the PMD level if possible.
4672c91bd4aSJoel Fernandes (Google) 			 */
468c49dd340SKalesh Singh 			if (move_pgt_entry(NORMAL_PMD, vma, old_addr, new_addr,
469c49dd340SKalesh Singh 					   old_pmd, new_pmd, need_rmap_locks))
4702c91bd4aSJoel Fernandes (Google) 				continue;
47137a1c49aSAndrea Arcangeli 		}
4722c91bd4aSJoel Fernandes (Google) 
4734cf58924SJoel Fernandes (Google) 		if (pte_alloc(new_vma->vm_mm, new_pmd))
47437a1c49aSAndrea Arcangeli 			break;
4755d190420SAaron Lu 		move_ptes(vma, old_pmd, old_addr, old_addr + extent, new_vma,
476eb66ae03SLinus Torvalds 			  new_pmd, new_addr, need_rmap_locks);
4771da177e4SLinus Torvalds 	}
4787b6efc2bSAndrea Arcangeli 
479ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
4807be7a546SHugh Dickins 
4817be7a546SHugh Dickins 	return len + old_addr - old_end;	/* how much done */
4821da177e4SLinus Torvalds }
4831da177e4SLinus Torvalds 
4841da177e4SLinus Torvalds static unsigned long move_vma(struct vm_area_struct *vma,
4851da177e4SLinus Torvalds 		unsigned long old_addr, unsigned long old_len,
48672f87654SPavel Emelyanov 		unsigned long new_len, unsigned long new_addr,
487e346b381SBrian Geffon 		bool *locked, unsigned long flags,
488e346b381SBrian Geffon 		struct vm_userfaultfd_ctx *uf, struct list_head *uf_unmap)
4891da177e4SLinus Torvalds {
4901da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
4911da177e4SLinus Torvalds 	struct vm_area_struct *new_vma;
4921da177e4SLinus Torvalds 	unsigned long vm_flags = vma->vm_flags;
4931da177e4SLinus Torvalds 	unsigned long new_pgoff;
4941da177e4SLinus Torvalds 	unsigned long moved_len;
4951da177e4SLinus Torvalds 	unsigned long excess = 0;
496365e9c87SHugh Dickins 	unsigned long hiwater_vm;
4971da177e4SLinus Torvalds 	int split = 0;
49873d5e062SDmitry Safonov 	int err = 0;
49938a76013SMichel Lespinasse 	bool need_rmap_locks;
5001da177e4SLinus Torvalds 
5011da177e4SLinus Torvalds 	/*
5021da177e4SLinus Torvalds 	 * We'd prefer to avoid failure later on in do_munmap:
5031da177e4SLinus Torvalds 	 * which may split one vma into three before unmapping.
5041da177e4SLinus Torvalds 	 */
5051da177e4SLinus Torvalds 	if (mm->map_count >= sysctl_max_map_count - 3)
5061da177e4SLinus Torvalds 		return -ENOMEM;
5071da177e4SLinus Torvalds 
50873d5e062SDmitry Safonov 	if (vma->vm_ops && vma->vm_ops->may_split) {
50973d5e062SDmitry Safonov 		if (vma->vm_start != old_addr)
51073d5e062SDmitry Safonov 			err = vma->vm_ops->may_split(vma, old_addr);
51173d5e062SDmitry Safonov 		if (!err && vma->vm_end != old_addr + old_len)
51273d5e062SDmitry Safonov 			err = vma->vm_ops->may_split(vma, old_addr + old_len);
51373d5e062SDmitry Safonov 		if (err)
51473d5e062SDmitry Safonov 			return err;
51573d5e062SDmitry Safonov 	}
51673d5e062SDmitry Safonov 
5171ff82995SHugh Dickins 	/*
5181ff82995SHugh Dickins 	 * Advise KSM to break any KSM pages in the area to be moved:
5191ff82995SHugh Dickins 	 * it would be confusing if they were to turn up at the new
5201ff82995SHugh Dickins 	 * location, where they happen to coincide with different KSM
5211ff82995SHugh Dickins 	 * pages recently unmapped.  But leave vma->vm_flags as it was,
5221ff82995SHugh Dickins 	 * so KSM can come around to merge on vma and new_vma afterwards.
5231ff82995SHugh Dickins 	 */
5247103ad32SHugh Dickins 	err = ksm_madvise(vma, old_addr, old_addr + old_len,
5257103ad32SHugh Dickins 						MADV_UNMERGEABLE, &vm_flags);
5267103ad32SHugh Dickins 	if (err)
5277103ad32SHugh Dickins 		return err;
5281ff82995SHugh Dickins 
529ad8ee77eSDmitry Safonov 	if (unlikely(flags & MREMAP_DONTUNMAP && vm_flags & VM_ACCOUNT)) {
530ad8ee77eSDmitry Safonov 		if (security_vm_enough_memory_mm(mm, new_len >> PAGE_SHIFT))
531ad8ee77eSDmitry Safonov 			return -ENOMEM;
532ad8ee77eSDmitry Safonov 	}
533ad8ee77eSDmitry Safonov 
5341da177e4SLinus Torvalds 	new_pgoff = vma->vm_pgoff + ((old_addr - vma->vm_start) >> PAGE_SHIFT);
53538a76013SMichel Lespinasse 	new_vma = copy_vma(&vma, new_addr, new_len, new_pgoff,
53638a76013SMichel Lespinasse 			   &need_rmap_locks);
537ad8ee77eSDmitry Safonov 	if (!new_vma) {
538ad8ee77eSDmitry Safonov 		if (unlikely(flags & MREMAP_DONTUNMAP && vm_flags & VM_ACCOUNT))
539ad8ee77eSDmitry Safonov 			vm_unacct_memory(new_len >> PAGE_SHIFT);
5401da177e4SLinus Torvalds 		return -ENOMEM;
541ad8ee77eSDmitry Safonov 	}
5421da177e4SLinus Torvalds 
54338a76013SMichel Lespinasse 	moved_len = move_page_tables(vma, old_addr, new_vma, new_addr, old_len,
54438a76013SMichel Lespinasse 				     need_rmap_locks);
5451da177e4SLinus Torvalds 	if (moved_len < old_len) {
546df1eab30SOleg Nesterov 		err = -ENOMEM;
5475477e70aSOleg Nesterov 	} else if (vma->vm_ops && vma->vm_ops->mremap) {
54814d07113SBrian Geffon 		err = vma->vm_ops->mremap(new_vma);
549df1eab30SOleg Nesterov 	}
550df1eab30SOleg Nesterov 
551df1eab30SOleg Nesterov 	if (unlikely(err)) {
5521da177e4SLinus Torvalds 		/*
5531da177e4SLinus Torvalds 		 * On error, move entries back from new area to old,
5541da177e4SLinus Torvalds 		 * which will succeed since page tables still there,
5551da177e4SLinus Torvalds 		 * and then proceed to unmap new area instead of old.
5561da177e4SLinus Torvalds 		 */
55738a76013SMichel Lespinasse 		move_page_tables(new_vma, new_addr, vma, old_addr, moved_len,
55838a76013SMichel Lespinasse 				 true);
5591da177e4SLinus Torvalds 		vma = new_vma;
5601da177e4SLinus Torvalds 		old_len = new_len;
5611da177e4SLinus Torvalds 		old_addr = new_addr;
562df1eab30SOleg Nesterov 		new_addr = err;
5634abad2caSLaurent Dufour 	} else {
56472f87654SPavel Emelyanov 		mremap_userfaultfd_prep(new_vma, uf);
5654abad2caSLaurent Dufour 	}
5661da177e4SLinus Torvalds 
5671da177e4SLinus Torvalds 	/* Conceal VM_ACCOUNT so old reservation is not undone */
568ad8ee77eSDmitry Safonov 	if (vm_flags & VM_ACCOUNT && !(flags & MREMAP_DONTUNMAP)) {
5691da177e4SLinus Torvalds 		vma->vm_flags &= ~VM_ACCOUNT;
5701da177e4SLinus Torvalds 		excess = vma->vm_end - vma->vm_start - old_len;
5711da177e4SLinus Torvalds 		if (old_addr > vma->vm_start &&
5721da177e4SLinus Torvalds 		    old_addr + old_len < vma->vm_end)
5731da177e4SLinus Torvalds 			split = 1;
5741da177e4SLinus Torvalds 	}
5751da177e4SLinus Torvalds 
57671799062SKirill Korotaev 	/*
577365e9c87SHugh Dickins 	 * If we failed to move page tables we still do total_vm increment
578365e9c87SHugh Dickins 	 * since do_munmap() will decrement it by old_len == new_len.
579365e9c87SHugh Dickins 	 *
580365e9c87SHugh Dickins 	 * Since total_vm is about to be raised artificially high for a
581365e9c87SHugh Dickins 	 * moment, we need to restore high watermark afterwards: if stats
582365e9c87SHugh Dickins 	 * are taken meanwhile, total_vm and hiwater_vm appear too high.
583365e9c87SHugh Dickins 	 * If this were a serious issue, we'd add a flag to do_munmap().
58471799062SKirill Korotaev 	 */
585365e9c87SHugh Dickins 	hiwater_vm = mm->hiwater_vm;
58684638335SKonstantin Khlebnikov 	vm_stat_account(mm, vma->vm_flags, new_len >> PAGE_SHIFT);
58771799062SKirill Korotaev 
588d9fe4fabSToshi Kani 	/* Tell pfnmap has moved from this vma */
589d9fe4fabSToshi Kani 	if (unlikely(vma->vm_flags & VM_PFNMAP))
590d9fe4fabSToshi Kani 		untrack_pfn_moved(vma);
591d9fe4fabSToshi Kani 
592e346b381SBrian Geffon 	if (unlikely(!err && (flags & MREMAP_DONTUNMAP))) {
593e346b381SBrian Geffon 		/* We always clear VM_LOCKED[ONFAULT] on the old vma */
594e346b381SBrian Geffon 		vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
595e346b381SBrian Geffon 
5961583aa27SLi Xinhai 		/*
5971583aa27SLi Xinhai 		 * anon_vma links of the old vma is no longer needed after its page
5981583aa27SLi Xinhai 		 * table has been moved.
5991583aa27SLi Xinhai 		 */
6001583aa27SLi Xinhai 		if (new_vma != vma && vma->vm_start == old_addr &&
6011583aa27SLi Xinhai 			vma->vm_end == (old_addr + old_len))
6021583aa27SLi Xinhai 			unlink_anon_vmas(vma);
6031583aa27SLi Xinhai 
604e346b381SBrian Geffon 		/* Because we won't unmap we don't need to touch locked_vm */
605ad8ee77eSDmitry Safonov 		return new_addr;
606e346b381SBrian Geffon 	}
607e346b381SBrian Geffon 
608897ab3e0SMike Rapoport 	if (do_munmap(mm, old_addr, old_len, uf_unmap) < 0) {
6091da177e4SLinus Torvalds 		/* OOM: unable to split vma, just get accounts right */
610ad8ee77eSDmitry Safonov 		if (vm_flags & VM_ACCOUNT && !(flags & MREMAP_DONTUNMAP))
61151df7bcbSDmitry Safonov 			vm_acct_memory(new_len >> PAGE_SHIFT);
6121da177e4SLinus Torvalds 		excess = 0;
6131da177e4SLinus Torvalds 	}
614e346b381SBrian Geffon 
615e346b381SBrian Geffon 	if (vm_flags & VM_LOCKED) {
616e346b381SBrian Geffon 		mm->locked_vm += new_len >> PAGE_SHIFT;
617e346b381SBrian Geffon 		*locked = true;
618e346b381SBrian Geffon 	}
619ad8ee77eSDmitry Safonov 
620365e9c87SHugh Dickins 	mm->hiwater_vm = hiwater_vm;
6211da177e4SLinus Torvalds 
6221da177e4SLinus Torvalds 	/* Restore VM_ACCOUNT if one or two pieces of vma left */
6231da177e4SLinus Torvalds 	if (excess) {
6241da177e4SLinus Torvalds 		vma->vm_flags |= VM_ACCOUNT;
6251da177e4SLinus Torvalds 		if (split)
6261da177e4SLinus Torvalds 			vma->vm_next->vm_flags |= VM_ACCOUNT;
6271da177e4SLinus Torvalds 	}
6281da177e4SLinus Torvalds 
6291da177e4SLinus Torvalds 	return new_addr;
6301da177e4SLinus Torvalds }
6311da177e4SLinus Torvalds 
63254f5de70SAl Viro static struct vm_area_struct *vma_to_resize(unsigned long addr,
633e346b381SBrian Geffon 	unsigned long old_len, unsigned long new_len, unsigned long flags,
634e346b381SBrian Geffon 	unsigned long *p)
63554f5de70SAl Viro {
63654f5de70SAl Viro 	struct mm_struct *mm = current->mm;
63754f5de70SAl Viro 	struct vm_area_struct *vma = find_vma(mm, addr);
6381d391686SOleg Nesterov 	unsigned long pgoff;
63954f5de70SAl Viro 
64054f5de70SAl Viro 	if (!vma || vma->vm_start > addr)
6416cd57613SDerek 		return ERR_PTR(-EFAULT);
64254f5de70SAl Viro 
643dba58d3bSMike Kravetz 	/*
644dba58d3bSMike Kravetz 	 * !old_len is a special case where an attempt is made to 'duplicate'
645dba58d3bSMike Kravetz 	 * a mapping.  This makes no sense for private mappings as it will
646dba58d3bSMike Kravetz 	 * instead create a fresh/new mapping unrelated to the original.  This
647dba58d3bSMike Kravetz 	 * is contrary to the basic idea of mremap which creates new mappings
648dba58d3bSMike Kravetz 	 * based on the original.  There are no known use cases for this
649dba58d3bSMike Kravetz 	 * behavior.  As a result, fail such attempts.
650dba58d3bSMike Kravetz 	 */
651dba58d3bSMike Kravetz 	if (!old_len && !(vma->vm_flags & (VM_SHARED | VM_MAYSHARE))) {
652dba58d3bSMike Kravetz 		pr_warn_once("%s (%d): attempted to duplicate a private mapping with mremap.  This is not supported.\n", current->comm, current->pid);
653dba58d3bSMike Kravetz 		return ERR_PTR(-EINVAL);
654dba58d3bSMike Kravetz 	}
655dba58d3bSMike Kravetz 
656a4609387SBrian Geffon 	if ((flags & MREMAP_DONTUNMAP) &&
657a4609387SBrian Geffon 			(vma->vm_flags & (VM_DONTEXPAND | VM_PFNMAP)))
658e346b381SBrian Geffon 		return ERR_PTR(-EINVAL);
659e346b381SBrian Geffon 
66054f5de70SAl Viro 	if (is_vm_hugetlb_page(vma))
6616cd57613SDerek 		return ERR_PTR(-EINVAL);
66254f5de70SAl Viro 
66354f5de70SAl Viro 	/* We can't remap across vm area boundaries */
66454f5de70SAl Viro 	if (old_len > vma->vm_end - addr)
6656cd57613SDerek 		return ERR_PTR(-EFAULT);
66654f5de70SAl Viro 
6671d391686SOleg Nesterov 	if (new_len == old_len)
6681d391686SOleg Nesterov 		return vma;
669982134baSLinus Torvalds 
6701d391686SOleg Nesterov 	/* Need to be careful about a growing mapping */
671982134baSLinus Torvalds 	pgoff = (addr - vma->vm_start) >> PAGE_SHIFT;
672982134baSLinus Torvalds 	pgoff += vma->vm_pgoff;
673982134baSLinus Torvalds 	if (pgoff + (new_len >> PAGE_SHIFT) < pgoff)
6746cd57613SDerek 		return ERR_PTR(-EINVAL);
6751d391686SOleg Nesterov 
6761d391686SOleg Nesterov 	if (vma->vm_flags & (VM_DONTEXPAND | VM_PFNMAP))
6771d391686SOleg Nesterov 		return ERR_PTR(-EFAULT);
67854f5de70SAl Viro 
67954f5de70SAl Viro 	if (vma->vm_flags & VM_LOCKED) {
68054f5de70SAl Viro 		unsigned long locked, lock_limit;
68154f5de70SAl Viro 		locked = mm->locked_vm << PAGE_SHIFT;
68259e99e5bSJiri Slaby 		lock_limit = rlimit(RLIMIT_MEMLOCK);
68354f5de70SAl Viro 		locked += new_len - old_len;
68454f5de70SAl Viro 		if (locked > lock_limit && !capable(CAP_IPC_LOCK))
6856cd57613SDerek 			return ERR_PTR(-EAGAIN);
68654f5de70SAl Viro 	}
68754f5de70SAl Viro 
68884638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vma->vm_flags,
68984638335SKonstantin Khlebnikov 				(new_len - old_len) >> PAGE_SHIFT))
6906cd57613SDerek 		return ERR_PTR(-ENOMEM);
69154f5de70SAl Viro 
69254f5de70SAl Viro 	if (vma->vm_flags & VM_ACCOUNT) {
69354f5de70SAl Viro 		unsigned long charged = (new_len - old_len) >> PAGE_SHIFT;
694191c5424SAl Viro 		if (security_vm_enough_memory_mm(mm, charged))
6956cd57613SDerek 			return ERR_PTR(-ENOMEM);
69654f5de70SAl Viro 		*p = charged;
69754f5de70SAl Viro 	}
69854f5de70SAl Viro 
69954f5de70SAl Viro 	return vma;
70054f5de70SAl Viro }
70154f5de70SAl Viro 
70281909b84SMichel Lespinasse static unsigned long mremap_to(unsigned long addr, unsigned long old_len,
70372f87654SPavel Emelyanov 		unsigned long new_addr, unsigned long new_len, bool *locked,
704e346b381SBrian Geffon 		unsigned long flags, struct vm_userfaultfd_ctx *uf,
705b2282371SMike Rapoport 		struct list_head *uf_unmap_early,
706897ab3e0SMike Rapoport 		struct list_head *uf_unmap)
707ecc1a899SAl Viro {
708ecc1a899SAl Viro 	struct mm_struct *mm = current->mm;
709ecc1a899SAl Viro 	struct vm_area_struct *vma;
710ecc1a899SAl Viro 	unsigned long ret = -EINVAL;
711ecc1a899SAl Viro 	unsigned long charged = 0;
712e346b381SBrian Geffon 	unsigned long map_flags = 0;
713ecc1a899SAl Viro 
714f19cb115SAlexander Kuleshov 	if (offset_in_page(new_addr))
715ecc1a899SAl Viro 		goto out;
716ecc1a899SAl Viro 
717ecc1a899SAl Viro 	if (new_len > TASK_SIZE || new_addr > TASK_SIZE - new_len)
718ecc1a899SAl Viro 		goto out;
719ecc1a899SAl Viro 
7209943242cSOleg Nesterov 	/* Ensure the old/new locations do not overlap */
7219943242cSOleg Nesterov 	if (addr + old_len > new_addr && new_addr + new_len > addr)
722ecc1a899SAl Viro 		goto out;
723ecc1a899SAl Viro 
724ea2c3f6fSOscar Salvador 	/*
725ea2c3f6fSOscar Salvador 	 * move_vma() need us to stay 4 maps below the threshold, otherwise
726ea2c3f6fSOscar Salvador 	 * it will bail out at the very beginning.
727ea2c3f6fSOscar Salvador 	 * That is a problem if we have already unmaped the regions here
728ea2c3f6fSOscar Salvador 	 * (new_addr, and old_addr), because userspace will not know the
729ea2c3f6fSOscar Salvador 	 * state of the vma's after it gets -ENOMEM.
730ea2c3f6fSOscar Salvador 	 * So, to avoid such scenario we can pre-compute if the whole
731ea2c3f6fSOscar Salvador 	 * operation has high chances to success map-wise.
732ea2c3f6fSOscar Salvador 	 * Worst-scenario case is when both vma's (new_addr and old_addr) get
733*f0953a1bSIngo Molnar 	 * split in 3 before unmapping it.
734ea2c3f6fSOscar Salvador 	 * That means 2 more maps (1 for each) to the ones we already hold.
735ea2c3f6fSOscar Salvador 	 * Check whether current map count plus 2 still leads us to 4 maps below
736ea2c3f6fSOscar Salvador 	 * the threshold, otherwise return -ENOMEM here to be more safe.
737ea2c3f6fSOscar Salvador 	 */
738ea2c3f6fSOscar Salvador 	if ((mm->map_count + 2) >= sysctl_max_map_count - 3)
739ea2c3f6fSOscar Salvador 		return -ENOMEM;
740ea2c3f6fSOscar Salvador 
741e346b381SBrian Geffon 	if (flags & MREMAP_FIXED) {
742b2282371SMike Rapoport 		ret = do_munmap(mm, new_addr, new_len, uf_unmap_early);
743ecc1a899SAl Viro 		if (ret)
744ecc1a899SAl Viro 			goto out;
745e346b381SBrian Geffon 	}
746ecc1a899SAl Viro 
747ecc1a899SAl Viro 	if (old_len >= new_len) {
748897ab3e0SMike Rapoport 		ret = do_munmap(mm, addr+new_len, old_len - new_len, uf_unmap);
749ecc1a899SAl Viro 		if (ret && old_len != new_len)
750ecc1a899SAl Viro 			goto out;
751ecc1a899SAl Viro 		old_len = new_len;
752ecc1a899SAl Viro 	}
753ecc1a899SAl Viro 
754e346b381SBrian Geffon 	vma = vma_to_resize(addr, old_len, new_len, flags, &charged);
755ecc1a899SAl Viro 	if (IS_ERR(vma)) {
756ecc1a899SAl Viro 		ret = PTR_ERR(vma);
757ecc1a899SAl Viro 		goto out;
758ecc1a899SAl Viro 	}
759ecc1a899SAl Viro 
760e346b381SBrian Geffon 	/* MREMAP_DONTUNMAP expands by old_len since old_len == new_len */
761e346b381SBrian Geffon 	if (flags & MREMAP_DONTUNMAP &&
762e346b381SBrian Geffon 		!may_expand_vm(mm, vma->vm_flags, old_len >> PAGE_SHIFT)) {
763e346b381SBrian Geffon 		ret = -ENOMEM;
764e346b381SBrian Geffon 		goto out;
765e346b381SBrian Geffon 	}
766e346b381SBrian Geffon 
767e346b381SBrian Geffon 	if (flags & MREMAP_FIXED)
768e346b381SBrian Geffon 		map_flags |= MAP_FIXED;
769e346b381SBrian Geffon 
770097eed10SAl Viro 	if (vma->vm_flags & VM_MAYSHARE)
771097eed10SAl Viro 		map_flags |= MAP_SHARED;
7729206de95SAl Viro 
773097eed10SAl Viro 	ret = get_unmapped_area(vma->vm_file, new_addr, new_len, vma->vm_pgoff +
774097eed10SAl Viro 				((addr - vma->vm_start) >> PAGE_SHIFT),
775097eed10SAl Viro 				map_flags);
776ff68dac6SGaowei Pu 	if (IS_ERR_VALUE(ret))
777097eed10SAl Viro 		goto out1;
778097eed10SAl Viro 
779e346b381SBrian Geffon 	/* We got a new mapping */
780e346b381SBrian Geffon 	if (!(flags & MREMAP_FIXED))
781e346b381SBrian Geffon 		new_addr = ret;
782e346b381SBrian Geffon 
783e346b381SBrian Geffon 	ret = move_vma(vma, addr, old_len, new_len, new_addr, locked, flags, uf,
784897ab3e0SMike Rapoport 		       uf_unmap);
785e346b381SBrian Geffon 
786f19cb115SAlexander Kuleshov 	if (!(offset_in_page(ret)))
787097eed10SAl Viro 		goto out;
788e346b381SBrian Geffon 
789097eed10SAl Viro out1:
790ecc1a899SAl Viro 	vm_unacct_memory(charged);
791ecc1a899SAl Viro 
792ecc1a899SAl Viro out:
793ecc1a899SAl Viro 	return ret;
794ecc1a899SAl Viro }
795ecc1a899SAl Viro 
7961a0ef85fSAl Viro static int vma_expandable(struct vm_area_struct *vma, unsigned long delta)
7971a0ef85fSAl Viro {
798f106af4eSAl Viro 	unsigned long end = vma->vm_end + delta;
7999206de95SAl Viro 	if (end < vma->vm_end) /* overflow */
8001a0ef85fSAl Viro 		return 0;
8019206de95SAl Viro 	if (vma->vm_next && vma->vm_next->vm_start < end) /* intersection */
802f106af4eSAl Viro 		return 0;
803f106af4eSAl Viro 	if (get_unmapped_area(NULL, vma->vm_start, end - vma->vm_start,
804f106af4eSAl Viro 			      0, MAP_FIXED) & ~PAGE_MASK)
805f106af4eSAl Viro 		return 0;
8061a0ef85fSAl Viro 	return 1;
8071a0ef85fSAl Viro }
8081a0ef85fSAl Viro 
8091da177e4SLinus Torvalds /*
8101da177e4SLinus Torvalds  * Expand (or shrink) an existing mapping, potentially moving it at the
8111da177e4SLinus Torvalds  * same time (controlled by the MREMAP_MAYMOVE flag and available VM space)
8121da177e4SLinus Torvalds  *
8131da177e4SLinus Torvalds  * MREMAP_FIXED option added 5-Dec-1999 by Benjamin LaHaise
8141da177e4SLinus Torvalds  * This option implies MREMAP_MAYMOVE.
8151da177e4SLinus Torvalds  */
81663a81db1SAl Viro SYSCALL_DEFINE5(mremap, unsigned long, addr, unsigned long, old_len,
81763a81db1SAl Viro 		unsigned long, new_len, unsigned long, flags,
81863a81db1SAl Viro 		unsigned long, new_addr)
8191da177e4SLinus Torvalds {
820d0de32d9SHugh Dickins 	struct mm_struct *mm = current->mm;
8211da177e4SLinus Torvalds 	struct vm_area_struct *vma;
8221da177e4SLinus Torvalds 	unsigned long ret = -EINVAL;
8231da177e4SLinus Torvalds 	unsigned long charged = 0;
82481909b84SMichel Lespinasse 	bool locked = false;
82585a06835SYang Shi 	bool downgraded = false;
82672f87654SPavel Emelyanov 	struct vm_userfaultfd_ctx uf = NULL_VM_UFFD_CTX;
827b2282371SMike Rapoport 	LIST_HEAD(uf_unmap_early);
828897ab3e0SMike Rapoport 	LIST_HEAD(uf_unmap);
8291da177e4SLinus Torvalds 
830b2a84de2SWill Deacon 	/*
831b2a84de2SWill Deacon 	 * There is a deliberate asymmetry here: we strip the pointer tag
832b2a84de2SWill Deacon 	 * from the old address but leave the new address alone. This is
833b2a84de2SWill Deacon 	 * for consistency with mmap(), where we prevent the creation of
834b2a84de2SWill Deacon 	 * aliasing mappings in userspace by leaving the tag bits of the
835b2a84de2SWill Deacon 	 * mapping address intact. A non-zero tag will cause the subsequent
836b2a84de2SWill Deacon 	 * range checks to reject the address as invalid.
837b2a84de2SWill Deacon 	 *
838b2a84de2SWill Deacon 	 * See Documentation/arm64/tagged-address-abi.rst for more information.
839b2a84de2SWill Deacon 	 */
840057d3389SAndrey Konovalov 	addr = untagged_addr(addr);
841057d3389SAndrey Konovalov 
842e346b381SBrian Geffon 	if (flags & ~(MREMAP_FIXED | MREMAP_MAYMOVE | MREMAP_DONTUNMAP))
8439a2458a6SRasmus Villemoes 		return ret;
8449a2458a6SRasmus Villemoes 
8459a2458a6SRasmus Villemoes 	if (flags & MREMAP_FIXED && !(flags & MREMAP_MAYMOVE))
8469a2458a6SRasmus Villemoes 		return ret;
8471da177e4SLinus Torvalds 
848e346b381SBrian Geffon 	/*
849e346b381SBrian Geffon 	 * MREMAP_DONTUNMAP is always a move and it does not allow resizing
850e346b381SBrian Geffon 	 * in the process.
851e346b381SBrian Geffon 	 */
852e346b381SBrian Geffon 	if (flags & MREMAP_DONTUNMAP &&
853e346b381SBrian Geffon 			(!(flags & MREMAP_MAYMOVE) || old_len != new_len))
854e346b381SBrian Geffon 		return ret;
855e346b381SBrian Geffon 
856e346b381SBrian Geffon 
857f19cb115SAlexander Kuleshov 	if (offset_in_page(addr))
8589a2458a6SRasmus Villemoes 		return ret;
8591da177e4SLinus Torvalds 
8601da177e4SLinus Torvalds 	old_len = PAGE_ALIGN(old_len);
8611da177e4SLinus Torvalds 	new_len = PAGE_ALIGN(new_len);
8621da177e4SLinus Torvalds 
8631da177e4SLinus Torvalds 	/*
8641da177e4SLinus Torvalds 	 * We allow a zero old-len as a special case
8651da177e4SLinus Torvalds 	 * for DOS-emu "duplicate shm area" thing. But
8661da177e4SLinus Torvalds 	 * a zero new-len is nonsensical.
8671da177e4SLinus Torvalds 	 */
8681da177e4SLinus Torvalds 	if (!new_len)
8699a2458a6SRasmus Villemoes 		return ret;
8709a2458a6SRasmus Villemoes 
871d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(current->mm))
872dc0ef0dfSMichal Hocko 		return -EINTR;
8731da177e4SLinus Torvalds 
874e346b381SBrian Geffon 	if (flags & (MREMAP_FIXED | MREMAP_DONTUNMAP)) {
87581909b84SMichel Lespinasse 		ret = mremap_to(addr, old_len, new_addr, new_len,
876e346b381SBrian Geffon 				&locked, flags, &uf, &uf_unmap_early,
877e346b381SBrian Geffon 				&uf_unmap);
8781da177e4SLinus Torvalds 		goto out;
8791da177e4SLinus Torvalds 	}
8801da177e4SLinus Torvalds 
8811da177e4SLinus Torvalds 	/*
8821da177e4SLinus Torvalds 	 * Always allow a shrinking remap: that just unmaps
8831da177e4SLinus Torvalds 	 * the unnecessary pages..
88485a06835SYang Shi 	 * __do_munmap does all the needed commit accounting, and
885c1e8d7c6SMichel Lespinasse 	 * downgrades mmap_lock to read if so directed.
8861da177e4SLinus Torvalds 	 */
8871da177e4SLinus Torvalds 	if (old_len >= new_len) {
88885a06835SYang Shi 		int retval;
88985a06835SYang Shi 
89085a06835SYang Shi 		retval = __do_munmap(mm, addr+new_len, old_len - new_len,
89185a06835SYang Shi 				  &uf_unmap, true);
89285a06835SYang Shi 		if (retval < 0 && old_len != new_len) {
89385a06835SYang Shi 			ret = retval;
8941da177e4SLinus Torvalds 			goto out;
895c1e8d7c6SMichel Lespinasse 		/* Returning 1 indicates mmap_lock is downgraded to read. */
89685a06835SYang Shi 		} else if (retval == 1)
89785a06835SYang Shi 			downgraded = true;
8981da177e4SLinus Torvalds 		ret = addr;
8991da177e4SLinus Torvalds 		goto out;
9001da177e4SLinus Torvalds 	}
9011da177e4SLinus Torvalds 
9021da177e4SLinus Torvalds 	/*
903ecc1a899SAl Viro 	 * Ok, we need to grow..
9041da177e4SLinus Torvalds 	 */
905e346b381SBrian Geffon 	vma = vma_to_resize(addr, old_len, new_len, flags, &charged);
90654f5de70SAl Viro 	if (IS_ERR(vma)) {
90754f5de70SAl Viro 		ret = PTR_ERR(vma);
9081da177e4SLinus Torvalds 		goto out;
9091da177e4SLinus Torvalds 	}
9101da177e4SLinus Torvalds 
9111da177e4SLinus Torvalds 	/* old_len exactly to the end of the area..
9121da177e4SLinus Torvalds 	 */
913ecc1a899SAl Viro 	if (old_len == vma->vm_end - addr) {
9141da177e4SLinus Torvalds 		/* can we just expand the current mapping? */
9151a0ef85fSAl Viro 		if (vma_expandable(vma, new_len - old_len)) {
9161da177e4SLinus Torvalds 			int pages = (new_len - old_len) >> PAGE_SHIFT;
9171da177e4SLinus Torvalds 
9185beb4930SRik van Riel 			if (vma_adjust(vma, vma->vm_start, addr + new_len,
9195beb4930SRik van Riel 				       vma->vm_pgoff, NULL)) {
9205beb4930SRik van Riel 				ret = -ENOMEM;
9215beb4930SRik van Riel 				goto out;
9225beb4930SRik van Riel 			}
9231da177e4SLinus Torvalds 
92484638335SKonstantin Khlebnikov 			vm_stat_account(mm, vma->vm_flags, pages);
9251da177e4SLinus Torvalds 			if (vma->vm_flags & VM_LOCKED) {
926d0de32d9SHugh Dickins 				mm->locked_vm += pages;
92781909b84SMichel Lespinasse 				locked = true;
92881909b84SMichel Lespinasse 				new_addr = addr;
9291da177e4SLinus Torvalds 			}
9301da177e4SLinus Torvalds 			ret = addr;
9311da177e4SLinus Torvalds 			goto out;
9321da177e4SLinus Torvalds 		}
9331da177e4SLinus Torvalds 	}
9341da177e4SLinus Torvalds 
9351da177e4SLinus Torvalds 	/*
9361da177e4SLinus Torvalds 	 * We weren't able to just expand or shrink the area,
9371da177e4SLinus Torvalds 	 * we need to create a new one and move it..
9381da177e4SLinus Torvalds 	 */
9391da177e4SLinus Torvalds 	ret = -ENOMEM;
9401da177e4SLinus Torvalds 	if (flags & MREMAP_MAYMOVE) {
9411da177e4SLinus Torvalds 		unsigned long map_flags = 0;
9421da177e4SLinus Torvalds 		if (vma->vm_flags & VM_MAYSHARE)
9431da177e4SLinus Torvalds 			map_flags |= MAP_SHARED;
9441da177e4SLinus Torvalds 
9451da177e4SLinus Torvalds 		new_addr = get_unmapped_area(vma->vm_file, 0, new_len,
94693587414SAl Viro 					vma->vm_pgoff +
94793587414SAl Viro 					((addr - vma->vm_start) >> PAGE_SHIFT),
94893587414SAl Viro 					map_flags);
949ff68dac6SGaowei Pu 		if (IS_ERR_VALUE(new_addr)) {
9501da177e4SLinus Torvalds 			ret = new_addr;
951ed032189SEric Paris 			goto out;
952ed032189SEric Paris 		}
953ed032189SEric Paris 
95472f87654SPavel Emelyanov 		ret = move_vma(vma, addr, old_len, new_len, new_addr,
955e346b381SBrian Geffon 			       &locked, flags, &uf, &uf_unmap);
9561da177e4SLinus Torvalds 	}
9571da177e4SLinus Torvalds out:
958f19cb115SAlexander Kuleshov 	if (offset_in_page(ret)) {
9591da177e4SLinus Torvalds 		vm_unacct_memory(charged);
960fa1f68ccSZou Wei 		locked = false;
961d456fb9eSOleg Nesterov 	}
96285a06835SYang Shi 	if (downgraded)
963d8ed45c5SMichel Lespinasse 		mmap_read_unlock(current->mm);
96485a06835SYang Shi 	else
965d8ed45c5SMichel Lespinasse 		mmap_write_unlock(current->mm);
96681909b84SMichel Lespinasse 	if (locked && new_len > old_len)
96781909b84SMichel Lespinasse 		mm_populate(new_addr + old_len, new_len - old_len);
968b2282371SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf_unmap_early);
969d1564926SBrian Geffon 	mremap_userfaultfd_complete(&uf, addr, ret, old_len);
970897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf_unmap);
9711da177e4SLinus Torvalds 	return ret;
9721da177e4SLinus Torvalds }
973