xref: /linux/mm/mmap.c (revision 1e76454f936178fd4e8052ddc92ce18c8937f043)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * mm/mmap.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  * Written by obz.
61da177e4SLinus Torvalds  *
7046c6884SAlan Cox  * Address space accounting code	<alan@lxorguk.ukuu.org.uk>
81da177e4SLinus Torvalds  */
91da177e4SLinus Torvalds 
10b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11b1de0d13SMitchel Humpherys 
12e8420a8eSCyril Hrubis #include <linux/kernel.h>
131da177e4SLinus Torvalds #include <linux/slab.h>
144af3c9ccSAlexey Dobriyan #include <linux/backing-dev.h>
151da177e4SLinus Torvalds #include <linux/mm.h>
1617fca131SArnd Bergmann #include <linux/mm_inline.h>
171da177e4SLinus Torvalds #include <linux/shm.h>
181da177e4SLinus Torvalds #include <linux/mman.h>
191da177e4SLinus Torvalds #include <linux/pagemap.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/syscalls.h>
22c59ede7bSRandy.Dunlap #include <linux/capability.h>
231da177e4SLinus Torvalds #include <linux/init.h>
241da177e4SLinus Torvalds #include <linux/file.h>
251da177e4SLinus Torvalds #include <linux/fs.h>
261da177e4SLinus Torvalds #include <linux/personality.h>
271da177e4SLinus Torvalds #include <linux/security.h>
281da177e4SLinus Torvalds #include <linux/hugetlb.h>
29c01d5b30SHugh Dickins #include <linux/shmem_fs.h>
301da177e4SLinus Torvalds #include <linux/profile.h>
31b95f1b31SPaul Gortmaker #include <linux/export.h>
321da177e4SLinus Torvalds #include <linux/mount.h>
331da177e4SLinus Torvalds #include <linux/mempolicy.h>
341da177e4SLinus Torvalds #include <linux/rmap.h>
35cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
3682f71ae4SKonstantin Khlebnikov #include <linux/mmdebug.h>
37cdd6c482SIngo Molnar #include <linux/perf_event.h>
38120a795dSAl Viro #include <linux/audit.h>
39b15d00b6SAndrea Arcangeli #include <linux/khugepaged.h>
402b144498SSrikar Dronamraju #include <linux/uprobes.h>
411640879aSAndrew Shewmaker #include <linux/notifier.h>
421640879aSAndrew Shewmaker #include <linux/memory.h>
43b1de0d13SMitchel Humpherys #include <linux/printk.h>
4419a809afSAndrea Arcangeli #include <linux/userfaultfd_k.h>
45d977d56cSKonstantin Khlebnikov #include <linux/moduleparam.h>
4662b5f7d0SDave Hansen #include <linux/pkeys.h>
4721292580SAndrea Arcangeli #include <linux/oom.h>
4804f5866eSAndrea Arcangeli #include <linux/sched/mm.h>
491da177e4SLinus Torvalds 
507c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
511da177e4SLinus Torvalds #include <asm/cacheflush.h>
521da177e4SLinus Torvalds #include <asm/tlb.h>
53d6dd61c8SJeremy Fitzhardinge #include <asm/mmu_context.h>
541da177e4SLinus Torvalds 
55df529cabSJaewon Kim #define CREATE_TRACE_POINTS
56df529cabSJaewon Kim #include <trace/events/mmap.h>
57df529cabSJaewon Kim 
5842b77728SJan Beulich #include "internal.h"
5942b77728SJan Beulich 
603a459756SKirill Korotaev #ifndef arch_mmap_check
613a459756SKirill Korotaev #define arch_mmap_check(addr, len, flags)	(0)
623a459756SKirill Korotaev #endif
633a459756SKirill Korotaev 
64d07e2259SDaniel Cashman #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
65d07e2259SDaniel Cashman const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
66d07e2259SDaniel Cashman const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
67d07e2259SDaniel Cashman int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
68d07e2259SDaniel Cashman #endif
69d07e2259SDaniel Cashman #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
70d07e2259SDaniel Cashman const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
71d07e2259SDaniel Cashman const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
72d07e2259SDaniel Cashman int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
73d07e2259SDaniel Cashman #endif
74d07e2259SDaniel Cashman 
75f4fcd558SKonstantin Khlebnikov static bool ignore_rlimit_data;
76d977d56cSKonstantin Khlebnikov core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
77d07e2259SDaniel Cashman 
78763ecb03SLiam R. Howlett static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
79e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
80763ecb03SLiam R. Howlett 		struct vm_area_struct *next, unsigned long start,
8168f48381SSuren Baghdasaryan 		unsigned long end, bool mm_wr_locked);
82e0da382cSHugh Dickins 
8364e45507SPeter Feiner static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
8464e45507SPeter Feiner {
8564e45507SPeter Feiner 	return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
8664e45507SPeter Feiner }
8764e45507SPeter Feiner 
8864e45507SPeter Feiner /* Update vma->vm_page_prot to reflect vma->vm_flags. */
8964e45507SPeter Feiner void vma_set_page_prot(struct vm_area_struct *vma)
9064e45507SPeter Feiner {
9164e45507SPeter Feiner 	unsigned long vm_flags = vma->vm_flags;
926d2329f8SAndrea Arcangeli 	pgprot_t vm_page_prot;
9364e45507SPeter Feiner 
946d2329f8SAndrea Arcangeli 	vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
956d2329f8SAndrea Arcangeli 	if (vma_wants_writenotify(vma, vm_page_prot)) {
9664e45507SPeter Feiner 		vm_flags &= ~VM_SHARED;
976d2329f8SAndrea Arcangeli 		vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
9864e45507SPeter Feiner 	}
99c1e8d7c6SMichel Lespinasse 	/* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
1006d2329f8SAndrea Arcangeli 	WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
10164e45507SPeter Feiner }
10264e45507SPeter Feiner 
1031da177e4SLinus Torvalds /*
104c8c06efaSDavidlohr Bueso  * Requires inode->i_mapping->i_mmap_rwsem
1051da177e4SLinus Torvalds  */
1061da177e4SLinus Torvalds static void __remove_shared_vm_struct(struct vm_area_struct *vma,
1071da177e4SLinus Torvalds 		struct file *file, struct address_space *mapping)
1081da177e4SLinus Torvalds {
1091da177e4SLinus Torvalds 	if (vma->vm_flags & VM_SHARED)
1104bb5f5d9SDavid Herrmann 		mapping_unmap_writable(mapping);
1111da177e4SLinus Torvalds 
1121da177e4SLinus Torvalds 	flush_dcache_mmap_lock(mapping);
1136b2dbba8SMichel Lespinasse 	vma_interval_tree_remove(vma, &mapping->i_mmap);
1141da177e4SLinus Torvalds 	flush_dcache_mmap_unlock(mapping);
1151da177e4SLinus Torvalds }
1161da177e4SLinus Torvalds 
1171da177e4SLinus Torvalds /*
1186b2dbba8SMichel Lespinasse  * Unlink a file-based vm structure from its interval tree, to hide
119a8fb5618SHugh Dickins  * vma from rmap and vmtruncate before freeing its page tables.
1201da177e4SLinus Torvalds  */
121a8fb5618SHugh Dickins void unlink_file_vma(struct vm_area_struct *vma)
1221da177e4SLinus Torvalds {
1231da177e4SLinus Torvalds 	struct file *file = vma->vm_file;
1241da177e4SLinus Torvalds 
1251da177e4SLinus Torvalds 	if (file) {
1261da177e4SLinus Torvalds 		struct address_space *mapping = file->f_mapping;
12783cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
1281da177e4SLinus Torvalds 		__remove_shared_vm_struct(vma, file, mapping);
12983cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
1301da177e4SLinus Torvalds 	}
131a8fb5618SHugh Dickins }
132a8fb5618SHugh Dickins 
133a8fb5618SHugh Dickins /*
134763ecb03SLiam R. Howlett  * Close a vm structure and free it.
135a8fb5618SHugh Dickins  */
136763ecb03SLiam R. Howlett static void remove_vma(struct vm_area_struct *vma)
137a8fb5618SHugh Dickins {
138a8fb5618SHugh Dickins 	might_sleep();
1391da177e4SLinus Torvalds 	if (vma->vm_ops && vma->vm_ops->close)
1401da177e4SLinus Torvalds 		vma->vm_ops->close(vma);
141e9714acfSKonstantin Khlebnikov 	if (vma->vm_file)
142a8fb5618SHugh Dickins 		fput(vma->vm_file);
143f0be3d32SLee Schermerhorn 	mpol_put(vma_policy(vma));
1443928d4f5SLinus Torvalds 	vm_area_free(vma);
1451da177e4SLinus Torvalds }
1461da177e4SLinus Torvalds 
147b62b633eSLiam R. Howlett static inline struct vm_area_struct *vma_prev_limit(struct vma_iterator *vmi,
148b62b633eSLiam R. Howlett 						    unsigned long min)
149b62b633eSLiam R. Howlett {
150b62b633eSLiam R. Howlett 	return mas_prev(&vmi->mas, min);
151b62b633eSLiam R. Howlett }
152b62b633eSLiam R. Howlett 
153b62b633eSLiam R. Howlett static inline int vma_iter_clear_gfp(struct vma_iterator *vmi,
154b62b633eSLiam R. Howlett 			unsigned long start, unsigned long end, gfp_t gfp)
155b62b633eSLiam R. Howlett {
156b62b633eSLiam R. Howlett 	vmi->mas.index = start;
157b62b633eSLiam R. Howlett 	vmi->mas.last = end - 1;
158b62b633eSLiam R. Howlett 	mas_store_gfp(&vmi->mas, NULL, gfp);
159b62b633eSLiam R. Howlett 	if (unlikely(mas_is_err(&vmi->mas)))
160b62b633eSLiam R. Howlett 		return -ENOMEM;
161b62b633eSLiam R. Howlett 
162b62b633eSLiam R. Howlett 	return 0;
163b62b633eSLiam R. Howlett }
164b62b633eSLiam R. Howlett 
1652e7ce7d3SLiam R. Howlett /*
1662e7ce7d3SLiam R. Howlett  * check_brk_limits() - Use platform specific check of range & verify mlock
1672e7ce7d3SLiam R. Howlett  * limits.
1682e7ce7d3SLiam R. Howlett  * @addr: The address to check
1692e7ce7d3SLiam R. Howlett  * @len: The size of increase.
1702e7ce7d3SLiam R. Howlett  *
1712e7ce7d3SLiam R. Howlett  * Return: 0 on success.
1722e7ce7d3SLiam R. Howlett  */
1732e7ce7d3SLiam R. Howlett static int check_brk_limits(unsigned long addr, unsigned long len)
1742e7ce7d3SLiam R. Howlett {
1752e7ce7d3SLiam R. Howlett 	unsigned long mapped_addr;
1762e7ce7d3SLiam R. Howlett 
1772e7ce7d3SLiam R. Howlett 	mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
1782e7ce7d3SLiam R. Howlett 	if (IS_ERR_VALUE(mapped_addr))
1792e7ce7d3SLiam R. Howlett 		return mapped_addr;
1802e7ce7d3SLiam R. Howlett 
1812e7ce7d3SLiam R. Howlett 	return mlock_future_check(current->mm, current->mm->def_flags, len);
1822e7ce7d3SLiam R. Howlett }
18392fed820SLiam R. Howlett static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma,
184763ecb03SLiam R. Howlett 		unsigned long addr, unsigned long request, unsigned long flags);
1856a6160a7SHeiko Carstens SYSCALL_DEFINE1(brk, unsigned long, brk)
1861da177e4SLinus Torvalds {
1879bc8039eSYang Shi 	unsigned long newbrk, oldbrk, origbrk;
1881da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1892e7ce7d3SLiam R. Howlett 	struct vm_area_struct *brkvma, *next = NULL;
190a5b4592cSJiri Kosina 	unsigned long min_brk;
191128557ffSMichel Lespinasse 	bool populate;
1929bc8039eSYang Shi 	bool downgraded = false;
193897ab3e0SMike Rapoport 	LIST_HEAD(uf);
19492fed820SLiam R. Howlett 	struct vma_iterator vmi;
1951da177e4SLinus Torvalds 
196d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
197dc0ef0dfSMichal Hocko 		return -EINTR;
1981da177e4SLinus Torvalds 
1999bc8039eSYang Shi 	origbrk = mm->brk;
2009bc8039eSYang Shi 
201a5b4592cSJiri Kosina #ifdef CONFIG_COMPAT_BRK
2025520e894SJiri Kosina 	/*
2035520e894SJiri Kosina 	 * CONFIG_COMPAT_BRK can still be overridden by setting
2045520e894SJiri Kosina 	 * randomize_va_space to 2, which will still cause mm->start_brk
2055520e894SJiri Kosina 	 * to be arbitrarily shifted
2065520e894SJiri Kosina 	 */
2074471a675SJiri Kosina 	if (current->brk_randomized)
2085520e894SJiri Kosina 		min_brk = mm->start_brk;
2095520e894SJiri Kosina 	else
2105520e894SJiri Kosina 		min_brk = mm->end_data;
211a5b4592cSJiri Kosina #else
212a5b4592cSJiri Kosina 	min_brk = mm->start_brk;
213a5b4592cSJiri Kosina #endif
214a5b4592cSJiri Kosina 	if (brk < min_brk)
2151da177e4SLinus Torvalds 		goto out;
2161e624196SRam Gupta 
2171e624196SRam Gupta 	/*
2181e624196SRam Gupta 	 * Check against rlimit here. If this check is done later after the test
2191e624196SRam Gupta 	 * of oldbrk with newbrk then it can escape the test and let the data
2201e624196SRam Gupta 	 * segment grow beyond its set limit the in case where the limit is
2211e624196SRam Gupta 	 * not page aligned -Ram Gupta
2221e624196SRam Gupta 	 */
2238764b338SCyrill Gorcunov 	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
2248764b338SCyrill Gorcunov 			      mm->end_data, mm->start_data))
2251e624196SRam Gupta 		goto out;
2261e624196SRam Gupta 
2271da177e4SLinus Torvalds 	newbrk = PAGE_ALIGN(brk);
2281da177e4SLinus Torvalds 	oldbrk = PAGE_ALIGN(mm->brk);
2299bc8039eSYang Shi 	if (oldbrk == newbrk) {
2309bc8039eSYang Shi 		mm->brk = brk;
2319bc8039eSYang Shi 		goto success;
2329bc8039eSYang Shi 	}
2331da177e4SLinus Torvalds 
2349bc8039eSYang Shi 	/*
2359bc8039eSYang Shi 	 * Always allow shrinking brk.
23627b26701SLiam R. Howlett 	 * do_vma_munmap() may downgrade mmap_lock to read.
2379bc8039eSYang Shi 	 */
2381da177e4SLinus Torvalds 	if (brk <= mm->brk) {
2399bc8039eSYang Shi 		int ret;
2409bc8039eSYang Shi 
2412e7ce7d3SLiam R. Howlett 		/* Search one past newbrk */
24292fed820SLiam R. Howlett 		vma_iter_init(&vmi, mm, newbrk);
24392fed820SLiam R. Howlett 		brkvma = vma_find(&vmi, oldbrk);
244f5ad5083SJason A. Donenfeld 		if (!brkvma || brkvma->vm_start >= oldbrk)
2452e7ce7d3SLiam R. Howlett 			goto out; /* mapping intersects with an existing non-brk vma. */
2469bc8039eSYang Shi 		/*
2472e7ce7d3SLiam R. Howlett 		 * mm->brk must be protected by write mmap_lock.
24827b26701SLiam R. Howlett 		 * do_vma_munmap() may downgrade the lock,  so update it
24927b26701SLiam R. Howlett 		 * before calling do_vma_munmap().
2509bc8039eSYang Shi 		 */
2519bc8039eSYang Shi 		mm->brk = brk;
25227b26701SLiam R. Howlett 		ret = do_vma_munmap(&vmi, brkvma, newbrk, oldbrk, &uf, true);
2532e7ce7d3SLiam R. Howlett 		if (ret == 1)  {
2542e7ce7d3SLiam R. Howlett 			downgraded = true;
2552e7ce7d3SLiam R. Howlett 			goto success;
2562e7ce7d3SLiam R. Howlett 		} else if (!ret)
2572e7ce7d3SLiam R. Howlett 			goto success;
2582e7ce7d3SLiam R. Howlett 
2599bc8039eSYang Shi 		mm->brk = origbrk;
2601da177e4SLinus Torvalds 		goto out;
2611da177e4SLinus Torvalds 	}
2621da177e4SLinus Torvalds 
2632e7ce7d3SLiam R. Howlett 	if (check_brk_limits(oldbrk, newbrk - oldbrk))
2642e7ce7d3SLiam R. Howlett 		goto out;
2652e7ce7d3SLiam R. Howlett 
2662e7ce7d3SLiam R. Howlett 	/*
2672e7ce7d3SLiam R. Howlett 	 * Only check if the next VMA is within the stack_guard_gap of the
2682e7ce7d3SLiam R. Howlett 	 * expansion area
2692e7ce7d3SLiam R. Howlett 	 */
27092fed820SLiam R. Howlett 	vma_iter_init(&vmi, mm, oldbrk);
27192fed820SLiam R. Howlett 	next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
2721be7107fSHugh Dickins 	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
2731da177e4SLinus Torvalds 		goto out;
2741da177e4SLinus Torvalds 
27592fed820SLiam R. Howlett 	brkvma = vma_prev_limit(&vmi, mm->start_brk);
2761da177e4SLinus Torvalds 	/* Ok, looks good - let it rip. */
27792fed820SLiam R. Howlett 	if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
2781da177e4SLinus Torvalds 		goto out;
2792e7ce7d3SLiam R. Howlett 
2801da177e4SLinus Torvalds 	mm->brk = brk;
2819bc8039eSYang Shi 
2829bc8039eSYang Shi success:
283128557ffSMichel Lespinasse 	populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
2849bc8039eSYang Shi 	if (downgraded)
285d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
2869bc8039eSYang Shi 	else
287d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
288897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
289128557ffSMichel Lespinasse 	if (populate)
290128557ffSMichel Lespinasse 		mm_populate(oldbrk, newbrk - oldbrk);
291128557ffSMichel Lespinasse 	return brk;
292128557ffSMichel Lespinasse 
2931da177e4SLinus Torvalds out:
294d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
295b7204006SAdrian Huang 	return origbrk;
2961da177e4SLinus Torvalds }
2971da177e4SLinus Torvalds 
298d4af56c5SLiam R. Howlett #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
299d4af56c5SLiam R. Howlett extern void mt_validate(struct maple_tree *mt);
300d4af56c5SLiam R. Howlett extern void mt_dump(const struct maple_tree *mt);
3011da177e4SLinus Torvalds 
302d4af56c5SLiam R. Howlett /* Validate the maple tree */
303d4af56c5SLiam R. Howlett static void validate_mm_mt(struct mm_struct *mm)
304d4af56c5SLiam R. Howlett {
305d4af56c5SLiam R. Howlett 	struct maple_tree *mt = &mm->mm_mt;
306763ecb03SLiam R. Howlett 	struct vm_area_struct *vma_mt;
307d4af56c5SLiam R. Howlett 
308d4af56c5SLiam R. Howlett 	MA_STATE(mas, mt, 0, 0);
309d4af56c5SLiam R. Howlett 
310d4af56c5SLiam R. Howlett 	mt_validate(&mm->mm_mt);
311d4af56c5SLiam R. Howlett 	mas_for_each(&mas, vma_mt, ULONG_MAX) {
312763ecb03SLiam R. Howlett 		if ((vma_mt->vm_start != mas.index) ||
313763ecb03SLiam R. Howlett 		    (vma_mt->vm_end - 1 != mas.last)) {
314d4af56c5SLiam R. Howlett 			pr_emerg("issue in %s\n", current->comm);
315d4af56c5SLiam R. Howlett 			dump_stack();
316d4af56c5SLiam R. Howlett 			dump_vma(vma_mt);
317d4af56c5SLiam R. Howlett 			pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
318d4af56c5SLiam R. Howlett 				 mas.index, mas.last);
319d4af56c5SLiam R. Howlett 			pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
320d4af56c5SLiam R. Howlett 				 vma_mt->vm_start, vma_mt->vm_end);
321d4af56c5SLiam R. Howlett 
322d4af56c5SLiam R. Howlett 			mt_dump(mas.tree);
323d4af56c5SLiam R. Howlett 			if (vma_mt->vm_end != mas.last + 1) {
324d4af56c5SLiam R. Howlett 				pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
325d4af56c5SLiam R. Howlett 						mm, vma_mt->vm_start, vma_mt->vm_end,
326d4af56c5SLiam R. Howlett 						mas.index, mas.last);
327d4af56c5SLiam R. Howlett 				mt_dump(mas.tree);
328d4af56c5SLiam R. Howlett 			}
329d4af56c5SLiam R. Howlett 			VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
330d4af56c5SLiam R. Howlett 			if (vma_mt->vm_start != mas.index) {
331d4af56c5SLiam R. Howlett 				pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
332d4af56c5SLiam R. Howlett 						mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
333d4af56c5SLiam R. Howlett 				mt_dump(mas.tree);
334d4af56c5SLiam R. Howlett 			}
335d4af56c5SLiam R. Howlett 			VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
336d4af56c5SLiam R. Howlett 		}
337d4af56c5SLiam R. Howlett 	}
338d4af56c5SLiam R. Howlett }
3391da177e4SLinus Torvalds 
340eafd4dc4SRashika Kheria static void validate_mm(struct mm_struct *mm)
3411da177e4SLinus Torvalds {
3421da177e4SLinus Torvalds 	int bug = 0;
3431da177e4SLinus Torvalds 	int i = 0;
344763ecb03SLiam R. Howlett 	struct vm_area_struct *vma;
345763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
346ff26f70fSAndrew Morton 
347524e00b3SLiam R. Howlett 	validate_mm_mt(mm);
348524e00b3SLiam R. Howlett 
349763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
350524e00b3SLiam R. Howlett #ifdef CONFIG_DEBUG_VM_RB
35112352d3cSKonstantin Khlebnikov 		struct anon_vma *anon_vma = vma->anon_vma;
352ed8ea815SMichel Lespinasse 		struct anon_vma_chain *avc;
353ff26f70fSAndrew Morton 
35412352d3cSKonstantin Khlebnikov 		if (anon_vma) {
35512352d3cSKonstantin Khlebnikov 			anon_vma_lock_read(anon_vma);
356ed8ea815SMichel Lespinasse 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
357ed8ea815SMichel Lespinasse 				anon_vma_interval_tree_verify(avc);
35812352d3cSKonstantin Khlebnikov 			anon_vma_unlock_read(anon_vma);
35912352d3cSKonstantin Khlebnikov 		}
360524e00b3SLiam R. Howlett #endif
3611da177e4SLinus Torvalds 		i++;
3621da177e4SLinus Torvalds 	}
3635a0768f6SMichel Lespinasse 	if (i != mm->map_count) {
364763ecb03SLiam R. Howlett 		pr_emerg("map_count %d mas_for_each %d\n", mm->map_count, i);
3655a0768f6SMichel Lespinasse 		bug = 1;
3665a0768f6SMichel Lespinasse 	}
36796dad67fSSasha Levin 	VM_BUG_ON_MM(bug, mm);
3681da177e4SLinus Torvalds }
369524e00b3SLiam R. Howlett 
370524e00b3SLiam R. Howlett #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
371d4af56c5SLiam R. Howlett #define validate_mm_mt(root) do { } while (0)
3721da177e4SLinus Torvalds #define validate_mm(mm) do { } while (0)
373524e00b3SLiam R. Howlett #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
374d3737187SMichel Lespinasse 
375bf181b9fSMichel Lespinasse /*
376bf181b9fSMichel Lespinasse  * vma has some anon_vma assigned, and is already inserted on that
377bf181b9fSMichel Lespinasse  * anon_vma's interval trees.
378bf181b9fSMichel Lespinasse  *
379bf181b9fSMichel Lespinasse  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
380bf181b9fSMichel Lespinasse  * vma must be removed from the anon_vma's interval trees using
381bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_pre_update_vma().
382bf181b9fSMichel Lespinasse  *
383bf181b9fSMichel Lespinasse  * After the update, the vma will be reinserted using
384bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_post_update_vma().
385bf181b9fSMichel Lespinasse  *
386c1e8d7c6SMichel Lespinasse  * The entire update must be protected by exclusive mmap_lock and by
387bf181b9fSMichel Lespinasse  * the root anon_vma's mutex.
388bf181b9fSMichel Lespinasse  */
389bf181b9fSMichel Lespinasse static inline void
390bf181b9fSMichel Lespinasse anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
391bf181b9fSMichel Lespinasse {
392bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
393bf181b9fSMichel Lespinasse 
394bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
395bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
396bf181b9fSMichel Lespinasse }
397bf181b9fSMichel Lespinasse 
398bf181b9fSMichel Lespinasse static inline void
399bf181b9fSMichel Lespinasse anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
400bf181b9fSMichel Lespinasse {
401bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
402bf181b9fSMichel Lespinasse 
403bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
404bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
405bf181b9fSMichel Lespinasse }
406bf181b9fSMichel Lespinasse 
407e8420a8eSCyril Hrubis static unsigned long count_vma_pages_range(struct mm_struct *mm,
408e8420a8eSCyril Hrubis 		unsigned long addr, unsigned long end)
409e8420a8eSCyril Hrubis {
4102e3af1dbSMatthew Wilcox (Oracle) 	VMA_ITERATOR(vmi, mm, addr);
411e8420a8eSCyril Hrubis 	struct vm_area_struct *vma;
4122e3af1dbSMatthew Wilcox (Oracle) 	unsigned long nr_pages = 0;
413e8420a8eSCyril Hrubis 
4142e3af1dbSMatthew Wilcox (Oracle) 	for_each_vma_range(vmi, vma, end) {
4152e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_start = max(addr, vma->vm_start);
4162e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_end = min(end, vma->vm_end);
417e8420a8eSCyril Hrubis 
4182e3af1dbSMatthew Wilcox (Oracle) 		nr_pages += PHYS_PFN(vm_end - vm_start);
419e8420a8eSCyril Hrubis 	}
420e8420a8eSCyril Hrubis 
421e8420a8eSCyril Hrubis 	return nr_pages;
422e8420a8eSCyril Hrubis }
423e8420a8eSCyril Hrubis 
424c154124fSLiam R. Howlett static void __vma_link_file(struct vm_area_struct *vma,
425c154124fSLiam R. Howlett 			    struct address_space *mapping)
4261da177e4SLinus Torvalds {
4271da177e4SLinus Torvalds 	if (vma->vm_flags & VM_SHARED)
428cf508b58SMiaohe Lin 		mapping_allow_writable(mapping);
4291da177e4SLinus Torvalds 
4301da177e4SLinus Torvalds 	flush_dcache_mmap_lock(mapping);
4316b2dbba8SMichel Lespinasse 	vma_interval_tree_insert(vma, &mapping->i_mmap);
4321da177e4SLinus Torvalds 	flush_dcache_mmap_unlock(mapping);
4331da177e4SLinus Torvalds }
4341da177e4SLinus Torvalds 
435763ecb03SLiam R. Howlett static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
4361da177e4SLinus Torvalds {
43779e4f2caSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, 0);
4381da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
4391da177e4SLinus Torvalds 
44079e4f2caSLiam R. Howlett 	if (vma_iter_prealloc(&vmi))
441d4af56c5SLiam R. Howlett 		return -ENOMEM;
442d4af56c5SLiam R. Howlett 
44364ac4940SHuang Shijie 	if (vma->vm_file) {
4441da177e4SLinus Torvalds 		mapping = vma->vm_file->f_mapping;
44583cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
44664ac4940SHuang Shijie 	}
4471da177e4SLinus Torvalds 
44879e4f2caSLiam R. Howlett 	vma_iter_store(&vmi, vma);
4491da177e4SLinus Torvalds 
450c154124fSLiam R. Howlett 	if (mapping) {
451c154124fSLiam R. Howlett 		__vma_link_file(vma, mapping);
45283cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
453c154124fSLiam R. Howlett 	}
4541da177e4SLinus Torvalds 
4551da177e4SLinus Torvalds 	mm->map_count++;
4561da177e4SLinus Torvalds 	validate_mm(mm);
457d4af56c5SLiam R. Howlett 	return 0;
4581da177e4SLinus Torvalds }
4591da177e4SLinus Torvalds 
4601da177e4SLinus Torvalds /*
46168cefec5SLiam R. Howlett  * init_multi_vma_prep() - Initializer for struct vma_prepare
46268cefec5SLiam R. Howlett  * @vp: The vma_prepare struct
46368cefec5SLiam R. Howlett  * @vma: The vma that will be altered once locked
46468cefec5SLiam R. Howlett  * @next: The next vma if it is to be adjusted
46568cefec5SLiam R. Howlett  * @remove: The first vma to be removed
46668cefec5SLiam R. Howlett  * @remove2: The second vma to be removed
46768cefec5SLiam R. Howlett  */
46868cefec5SLiam R. Howlett static inline void init_multi_vma_prep(struct vma_prepare *vp,
46968cefec5SLiam R. Howlett 		struct vm_area_struct *vma, struct vm_area_struct *next,
47068cefec5SLiam R. Howlett 		struct vm_area_struct *remove, struct vm_area_struct *remove2)
47168cefec5SLiam R. Howlett {
47268cefec5SLiam R. Howlett 	memset(vp, 0, sizeof(struct vma_prepare));
47368cefec5SLiam R. Howlett 	vp->vma = vma;
47468cefec5SLiam R. Howlett 	vp->anon_vma = vma->anon_vma;
47568cefec5SLiam R. Howlett 	vp->remove = remove;
47668cefec5SLiam R. Howlett 	vp->remove2 = remove2;
47768cefec5SLiam R. Howlett 	vp->adj_next = next;
47868cefec5SLiam R. Howlett 	if (!vp->anon_vma && next)
47968cefec5SLiam R. Howlett 		vp->anon_vma = next->anon_vma;
48068cefec5SLiam R. Howlett 
48168cefec5SLiam R. Howlett 	vp->file = vma->vm_file;
48268cefec5SLiam R. Howlett 	if (vp->file)
48368cefec5SLiam R. Howlett 		vp->mapping = vma->vm_file->f_mapping;
48468cefec5SLiam R. Howlett 
48568cefec5SLiam R. Howlett }
48668cefec5SLiam R. Howlett 
48768cefec5SLiam R. Howlett /*
48868cefec5SLiam R. Howlett  * init_vma_prep() - Initializer wrapper for vma_prepare struct
48968cefec5SLiam R. Howlett  * @vp: The vma_prepare struct
49068cefec5SLiam R. Howlett  * @vma: The vma that will be altered once locked
49168cefec5SLiam R. Howlett  */
49268cefec5SLiam R. Howlett static inline void init_vma_prep(struct vma_prepare *vp,
49368cefec5SLiam R. Howlett 				 struct vm_area_struct *vma)
49468cefec5SLiam R. Howlett {
49568cefec5SLiam R. Howlett 	init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
49668cefec5SLiam R. Howlett }
49768cefec5SLiam R. Howlett 
49868cefec5SLiam R. Howlett 
49968cefec5SLiam R. Howlett /*
500440703e0SLiam R. Howlett  * vma_prepare() - Helper function for handling locking VMAs prior to altering
501440703e0SLiam R. Howlett  * @vp: The initialized vma_prepare struct
502440703e0SLiam R. Howlett  */
503440703e0SLiam R. Howlett static inline void vma_prepare(struct vma_prepare *vp)
504440703e0SLiam R. Howlett {
505440703e0SLiam R. Howlett 	if (vp->file) {
506440703e0SLiam R. Howlett 		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
507440703e0SLiam R. Howlett 
508440703e0SLiam R. Howlett 		if (vp->adj_next)
509440703e0SLiam R. Howlett 			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
510440703e0SLiam R. Howlett 				      vp->adj_next->vm_end);
511440703e0SLiam R. Howlett 
512440703e0SLiam R. Howlett 		i_mmap_lock_write(vp->mapping);
513440703e0SLiam R. Howlett 		if (vp->insert && vp->insert->vm_file) {
514440703e0SLiam R. Howlett 			/*
515440703e0SLiam R. Howlett 			 * Put into interval tree now, so instantiated pages
516440703e0SLiam R. Howlett 			 * are visible to arm/parisc __flush_dcache_page
517440703e0SLiam R. Howlett 			 * throughout; but we cannot insert into address
518440703e0SLiam R. Howlett 			 * space until vma start or end is updated.
519440703e0SLiam R. Howlett 			 */
520440703e0SLiam R. Howlett 			__vma_link_file(vp->insert,
521440703e0SLiam R. Howlett 					vp->insert->vm_file->f_mapping);
522440703e0SLiam R. Howlett 		}
523440703e0SLiam R. Howlett 	}
524440703e0SLiam R. Howlett 
525440703e0SLiam R. Howlett 	if (vp->anon_vma) {
526440703e0SLiam R. Howlett 		anon_vma_lock_write(vp->anon_vma);
527440703e0SLiam R. Howlett 		anon_vma_interval_tree_pre_update_vma(vp->vma);
528440703e0SLiam R. Howlett 		if (vp->adj_next)
529440703e0SLiam R. Howlett 			anon_vma_interval_tree_pre_update_vma(vp->adj_next);
530440703e0SLiam R. Howlett 	}
531440703e0SLiam R. Howlett 
532440703e0SLiam R. Howlett 	if (vp->file) {
533440703e0SLiam R. Howlett 		flush_dcache_mmap_lock(vp->mapping);
534440703e0SLiam R. Howlett 		vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
535440703e0SLiam R. Howlett 		if (vp->adj_next)
536440703e0SLiam R. Howlett 			vma_interval_tree_remove(vp->adj_next,
537440703e0SLiam R. Howlett 						 &vp->mapping->i_mmap);
538440703e0SLiam R. Howlett 	}
539440703e0SLiam R. Howlett 
540440703e0SLiam R. Howlett }
541440703e0SLiam R. Howlett 
542440703e0SLiam R. Howlett /*
543440703e0SLiam R. Howlett  * vma_complete- Helper function for handling the unlocking after altering VMAs,
544440703e0SLiam R. Howlett  * or for inserting a VMA.
545440703e0SLiam R. Howlett  *
546440703e0SLiam R. Howlett  * @vp: The vma_prepare struct
547440703e0SLiam R. Howlett  * @vmi: The vma iterator
548440703e0SLiam R. Howlett  * @mm: The mm_struct
549440703e0SLiam R. Howlett  */
550440703e0SLiam R. Howlett static inline void vma_complete(struct vma_prepare *vp,
551440703e0SLiam R. Howlett 				struct vma_iterator *vmi, struct mm_struct *mm)
552440703e0SLiam R. Howlett {
553440703e0SLiam R. Howlett 	if (vp->file) {
554440703e0SLiam R. Howlett 		if (vp->adj_next)
555440703e0SLiam R. Howlett 			vma_interval_tree_insert(vp->adj_next,
556440703e0SLiam R. Howlett 						 &vp->mapping->i_mmap);
557440703e0SLiam R. Howlett 		vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
558440703e0SLiam R. Howlett 		flush_dcache_mmap_unlock(vp->mapping);
559440703e0SLiam R. Howlett 	}
560440703e0SLiam R. Howlett 
561440703e0SLiam R. Howlett 	if (vp->remove && vp->file) {
562440703e0SLiam R. Howlett 		__remove_shared_vm_struct(vp->remove, vp->file, vp->mapping);
563440703e0SLiam R. Howlett 		if (vp->remove2)
564440703e0SLiam R. Howlett 			__remove_shared_vm_struct(vp->remove2, vp->file,
565440703e0SLiam R. Howlett 						  vp->mapping);
566440703e0SLiam R. Howlett 	} else if (vp->insert) {
567440703e0SLiam R. Howlett 		/*
568440703e0SLiam R. Howlett 		 * split_vma has split insert from vma, and needs
569440703e0SLiam R. Howlett 		 * us to insert it before dropping the locks
570440703e0SLiam R. Howlett 		 * (it may either follow vma or precede it).
571440703e0SLiam R. Howlett 		 */
572440703e0SLiam R. Howlett 		vma_iter_store(vmi, vp->insert);
573440703e0SLiam R. Howlett 		mm->map_count++;
574440703e0SLiam R. Howlett 	}
575440703e0SLiam R. Howlett 
576440703e0SLiam R. Howlett 	if (vp->anon_vma) {
577440703e0SLiam R. Howlett 		anon_vma_interval_tree_post_update_vma(vp->vma);
578440703e0SLiam R. Howlett 		if (vp->adj_next)
579440703e0SLiam R. Howlett 			anon_vma_interval_tree_post_update_vma(vp->adj_next);
580440703e0SLiam R. Howlett 		anon_vma_unlock_write(vp->anon_vma);
581440703e0SLiam R. Howlett 	}
582440703e0SLiam R. Howlett 
583440703e0SLiam R. Howlett 	if (vp->file) {
584440703e0SLiam R. Howlett 		i_mmap_unlock_write(vp->mapping);
585440703e0SLiam R. Howlett 		uprobe_mmap(vp->vma);
586440703e0SLiam R. Howlett 
587440703e0SLiam R. Howlett 		if (vp->adj_next)
588440703e0SLiam R. Howlett 			uprobe_mmap(vp->adj_next);
589440703e0SLiam R. Howlett 	}
590440703e0SLiam R. Howlett 
591440703e0SLiam R. Howlett 	if (vp->remove) {
592440703e0SLiam R. Howlett again:
593440703e0SLiam R. Howlett 		if (vp->file) {
594440703e0SLiam R. Howlett 			uprobe_munmap(vp->remove, vp->remove->vm_start,
595440703e0SLiam R. Howlett 				      vp->remove->vm_end);
596440703e0SLiam R. Howlett 			fput(vp->file);
597440703e0SLiam R. Howlett 		}
598440703e0SLiam R. Howlett 		if (vp->remove->anon_vma)
599440703e0SLiam R. Howlett 			anon_vma_merge(vp->vma, vp->remove);
600440703e0SLiam R. Howlett 		mm->map_count--;
601440703e0SLiam R. Howlett 		mpol_put(vma_policy(vp->remove));
602440703e0SLiam R. Howlett 		if (!vp->remove2)
603440703e0SLiam R. Howlett 			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
604440703e0SLiam R. Howlett 		vm_area_free(vp->remove);
605440703e0SLiam R. Howlett 
606440703e0SLiam R. Howlett 		/*
607440703e0SLiam R. Howlett 		 * In mprotect's case 6 (see comments on vma_merge),
6085ff783f1SVlastimil Babka 		 * we are removing both mid and next vmas
609440703e0SLiam R. Howlett 		 */
610440703e0SLiam R. Howlett 		if (vp->remove2) {
611440703e0SLiam R. Howlett 			vp->remove = vp->remove2;
612440703e0SLiam R. Howlett 			vp->remove2 = NULL;
613440703e0SLiam R. Howlett 			goto again;
614440703e0SLiam R. Howlett 		}
615440703e0SLiam R. Howlett 	}
616440703e0SLiam R. Howlett 	if (vp->insert && vp->file)
617440703e0SLiam R. Howlett 		uprobe_mmap(vp->insert);
618440703e0SLiam R. Howlett }
619440703e0SLiam R. Howlett 
620440703e0SLiam R. Howlett /*
62104241ffeSLiam R. Howlett  * dup_anon_vma() - Helper function to duplicate anon_vma
62204241ffeSLiam R. Howlett  * @dst: The destination VMA
62304241ffeSLiam R. Howlett  * @src: The source VMA
62404241ffeSLiam R. Howlett  *
62504241ffeSLiam R. Howlett  * Returns: 0 on success.
62604241ffeSLiam R. Howlett  */
62704241ffeSLiam R. Howlett static inline int dup_anon_vma(struct vm_area_struct *dst,
62804241ffeSLiam R. Howlett 			       struct vm_area_struct *src)
62904241ffeSLiam R. Howlett {
63004241ffeSLiam R. Howlett 	/*
63104241ffeSLiam R. Howlett 	 * Easily overlooked: when mprotect shifts the boundary, make sure the
63204241ffeSLiam R. Howlett 	 * expanding vma has anon_vma set if the shrinking vma had, to cover any
63304241ffeSLiam R. Howlett 	 * anon pages imported.
63404241ffeSLiam R. Howlett 	 */
63504241ffeSLiam R. Howlett 	if (src->anon_vma && !dst->anon_vma) {
63604241ffeSLiam R. Howlett 		dst->anon_vma = src->anon_vma;
63704241ffeSLiam R. Howlett 		return anon_vma_clone(dst, src);
63804241ffeSLiam R. Howlett 	}
63904241ffeSLiam R. Howlett 
64004241ffeSLiam R. Howlett 	return 0;
64104241ffeSLiam R. Howlett }
64204241ffeSLiam R. Howlett 
64304241ffeSLiam R. Howlett /*
6449303d3e1SLiam R. Howlett  * vma_expand - Expand an existing VMA
6459303d3e1SLiam R. Howlett  *
6469303d3e1SLiam R. Howlett  * @vmi: The vma iterator
6479303d3e1SLiam R. Howlett  * @vma: The vma to expand
6489303d3e1SLiam R. Howlett  * @start: The start of the vma
6499303d3e1SLiam R. Howlett  * @end: The exclusive end of the vma
6509303d3e1SLiam R. Howlett  * @pgoff: The page offset of vma
6519303d3e1SLiam R. Howlett  * @next: The current of next vma.
6529303d3e1SLiam R. Howlett  *
6539303d3e1SLiam R. Howlett  * Expand @vma to @start and @end.  Can expand off the start and end.  Will
6549303d3e1SLiam R. Howlett  * expand over @next if it's different from @vma and @end == @next->vm_end.
6559303d3e1SLiam R. Howlett  * Checking if the @vma can expand and merge with @next needs to be handled by
6569303d3e1SLiam R. Howlett  * the caller.
6579303d3e1SLiam R. Howlett  *
6589303d3e1SLiam R. Howlett  * Returns: 0 on success
6599303d3e1SLiam R. Howlett  */
6607c9813e8SLiam R. Howlett int vma_expand(struct vma_iterator *vmi, struct vm_area_struct *vma,
6619303d3e1SLiam R. Howlett 	       unsigned long start, unsigned long end, pgoff_t pgoff,
6629303d3e1SLiam R. Howlett 	       struct vm_area_struct *next)
6639303d3e1SLiam R. Howlett {
66468cefec5SLiam R. Howlett 	bool remove_next = false;
6659303d3e1SLiam R. Howlett 	struct vma_prepare vp;
6669303d3e1SLiam R. Howlett 
6679303d3e1SLiam R. Howlett 	if (next && (vma != next) && (end == next->vm_end)) {
66804241ffeSLiam R. Howlett 		int ret;
6699303d3e1SLiam R. Howlett 
67004241ffeSLiam R. Howlett 		remove_next = true;
67104241ffeSLiam R. Howlett 		ret = dup_anon_vma(vma, next);
67204241ffeSLiam R. Howlett 		if (ret)
67304241ffeSLiam R. Howlett 			return ret;
6749303d3e1SLiam R. Howlett 	}
6759303d3e1SLiam R. Howlett 
67668cefec5SLiam R. Howlett 	init_multi_vma_prep(&vp, vma, NULL, remove_next ? next : NULL, NULL);
6779303d3e1SLiam R. Howlett 	/* Not merging but overwriting any part of next is not handled. */
6789303d3e1SLiam R. Howlett 	VM_WARN_ON(next && !vp.remove &&
6799303d3e1SLiam R. Howlett 		  next != vma && end > next->vm_start);
6809303d3e1SLiam R. Howlett 	/* Only handles expanding */
6819303d3e1SLiam R. Howlett 	VM_WARN_ON(vma->vm_start < start || vma->vm_end > end);
6829303d3e1SLiam R. Howlett 
6839303d3e1SLiam R. Howlett 	if (vma_iter_prealloc(vmi))
6849303d3e1SLiam R. Howlett 		goto nomem;
6859303d3e1SLiam R. Howlett 
6869303d3e1SLiam R. Howlett 	vma_adjust_trans_huge(vma, start, end, 0);
6879303d3e1SLiam R. Howlett 	/* VMA iterator points to previous, so set to start if necessary */
6889303d3e1SLiam R. Howlett 	if (vma_iter_addr(vmi) != start)
6899303d3e1SLiam R. Howlett 		vma_iter_set(vmi, start);
6909303d3e1SLiam R. Howlett 
6919303d3e1SLiam R. Howlett 	vma_prepare(&vp);
6929303d3e1SLiam R. Howlett 	vma->vm_start = start;
6939303d3e1SLiam R. Howlett 	vma->vm_end = end;
6949303d3e1SLiam R. Howlett 	vma->vm_pgoff = pgoff;
6959303d3e1SLiam R. Howlett 	/* Note: mas must be pointing to the expanding VMA */
6969303d3e1SLiam R. Howlett 	vma_iter_store(vmi, vma);
6979303d3e1SLiam R. Howlett 
6989303d3e1SLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
6999303d3e1SLiam R. Howlett 	validate_mm(vma->vm_mm);
7009303d3e1SLiam R. Howlett 	return 0;
7019303d3e1SLiam R. Howlett 
7029303d3e1SLiam R. Howlett nomem:
7039303d3e1SLiam R. Howlett 	return -ENOMEM;
7049303d3e1SLiam R. Howlett }
705cf51e86dSLiam R. Howlett 
706cf51e86dSLiam R. Howlett /*
707cf51e86dSLiam R. Howlett  * vma_shrink() - Reduce an existing VMAs memory area
708cf51e86dSLiam R. Howlett  * @vmi: The vma iterator
709cf51e86dSLiam R. Howlett  * @vma: The VMA to modify
710cf51e86dSLiam R. Howlett  * @start: The new start
711cf51e86dSLiam R. Howlett  * @end: The new end
712cf51e86dSLiam R. Howlett  *
713cf51e86dSLiam R. Howlett  * Returns: 0 on success, -ENOMEM otherwise
714cf51e86dSLiam R. Howlett  */
715cf51e86dSLiam R. Howlett int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
716cf51e86dSLiam R. Howlett 	       unsigned long start, unsigned long end, pgoff_t pgoff)
717cf51e86dSLiam R. Howlett {
718cf51e86dSLiam R. Howlett 	struct vma_prepare vp;
719cf51e86dSLiam R. Howlett 
720cf51e86dSLiam R. Howlett 	WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
721cf51e86dSLiam R. Howlett 
722cf51e86dSLiam R. Howlett 	if (vma_iter_prealloc(vmi))
723cf51e86dSLiam R. Howlett 		return -ENOMEM;
724cf51e86dSLiam R. Howlett 
725cf51e86dSLiam R. Howlett 	init_vma_prep(&vp, vma);
726cf51e86dSLiam R. Howlett 	vma_adjust_trans_huge(vma, start, end, 0);
727cf51e86dSLiam R. Howlett 	vma_prepare(&vp);
728cf51e86dSLiam R. Howlett 
729cf51e86dSLiam R. Howlett 	if (vma->vm_start < start)
730cf51e86dSLiam R. Howlett 		vma_iter_clear(vmi, vma->vm_start, start);
731cf51e86dSLiam R. Howlett 
732cf51e86dSLiam R. Howlett 	if (vma->vm_end > end)
733cf51e86dSLiam R. Howlett 		vma_iter_clear(vmi, end, vma->vm_end);
734cf51e86dSLiam R. Howlett 
735cf51e86dSLiam R. Howlett 	vma->vm_start = start;
736cf51e86dSLiam R. Howlett 	vma->vm_end = end;
737cf51e86dSLiam R. Howlett 	vma->vm_pgoff = pgoff;
738cf51e86dSLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
739cf51e86dSLiam R. Howlett 	validate_mm(vma->vm_mm);
740cf51e86dSLiam R. Howlett 	return 0;
741cf51e86dSLiam R. Howlett }
742cf51e86dSLiam R. Howlett 
7439303d3e1SLiam R. Howlett /*
7441da177e4SLinus Torvalds  * If the vma has a ->close operation then the driver probably needs to release
7451da177e4SLinus Torvalds  * per-vma resources, so we don't attempt to merge those.
7461da177e4SLinus Torvalds  */
7471da177e4SLinus Torvalds static inline int is_mergeable_vma(struct vm_area_struct *vma,
74819a809afSAndrea Arcangeli 				   struct file *file, unsigned long vm_flags,
7499a10064fSColin Cross 				   struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
7505c26f6acSSuren Baghdasaryan 				   struct anon_vma_name *anon_name)
7511da177e4SLinus Torvalds {
75234228d47SCyrill Gorcunov 	/*
75334228d47SCyrill Gorcunov 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
75434228d47SCyrill Gorcunov 	 * match the flags but dirty bit -- the caller should mark
75534228d47SCyrill Gorcunov 	 * merged VMA as dirty. If dirty bit won't be excluded from
7568bb4e7a2SWei Yang 	 * comparison, we increase pressure on the memory system forcing
75734228d47SCyrill Gorcunov 	 * the kernel to generate new VMAs when old one could be
75834228d47SCyrill Gorcunov 	 * extended instead.
75934228d47SCyrill Gorcunov 	 */
76034228d47SCyrill Gorcunov 	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
7611da177e4SLinus Torvalds 		return 0;
7621da177e4SLinus Torvalds 	if (vma->vm_file != file)
7631da177e4SLinus Torvalds 		return 0;
7641da177e4SLinus Torvalds 	if (vma->vm_ops && vma->vm_ops->close)
7651da177e4SLinus Torvalds 		return 0;
76619a809afSAndrea Arcangeli 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
76719a809afSAndrea Arcangeli 		return 0;
7685c26f6acSSuren Baghdasaryan 	if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
7699a10064fSColin Cross 		return 0;
7701da177e4SLinus Torvalds 	return 1;
7711da177e4SLinus Torvalds }
7721da177e4SLinus Torvalds 
7731da177e4SLinus Torvalds static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
774965f55deSShaohua Li 					struct anon_vma *anon_vma2,
775965f55deSShaohua Li 					struct vm_area_struct *vma)
7761da177e4SLinus Torvalds {
777965f55deSShaohua Li 	/*
778965f55deSShaohua Li 	 * The list_is_singular() test is to avoid merging VMA cloned from
779965f55deSShaohua Li 	 * parents. This can improve scalability caused by anon_vma lock.
780965f55deSShaohua Li 	 */
781965f55deSShaohua Li 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
782965f55deSShaohua Li 		list_is_singular(&vma->anon_vma_chain)))
783965f55deSShaohua Li 		return 1;
784965f55deSShaohua Li 	return anon_vma1 == anon_vma2;
7851da177e4SLinus Torvalds }
7861da177e4SLinus Torvalds 
7871da177e4SLinus Torvalds /*
7881da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
7891da177e4SLinus Torvalds  * in front of (at a lower virtual address and file offset than) the vma.
7901da177e4SLinus Torvalds  *
7911da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
7921da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
7931da177e4SLinus Torvalds  *
7941da177e4SLinus Torvalds  * We don't check here for the merged mmap wrapping around the end of pagecache
79545e55300SPeter Collingbourne  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
7961da177e4SLinus Torvalds  * wrap, nor mmaps which cover the final page at index -1UL.
7971da177e4SLinus Torvalds  */
7981da177e4SLinus Torvalds static int
7991da177e4SLinus Torvalds can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
80019a809afSAndrea Arcangeli 		     struct anon_vma *anon_vma, struct file *file,
80119a809afSAndrea Arcangeli 		     pgoff_t vm_pgoff,
8029a10064fSColin Cross 		     struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
8035c26f6acSSuren Baghdasaryan 		     struct anon_vma_name *anon_name)
8041da177e4SLinus Torvalds {
8059a10064fSColin Cross 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
806965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
8071da177e4SLinus Torvalds 		if (vma->vm_pgoff == vm_pgoff)
8081da177e4SLinus Torvalds 			return 1;
8091da177e4SLinus Torvalds 	}
8101da177e4SLinus Torvalds 	return 0;
8111da177e4SLinus Torvalds }
8121da177e4SLinus Torvalds 
8131da177e4SLinus Torvalds /*
8141da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
8151da177e4SLinus Torvalds  * beyond (at a higher virtual address and file offset than) the vma.
8161da177e4SLinus Torvalds  *
8171da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
8181da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
8191da177e4SLinus Torvalds  */
8201da177e4SLinus Torvalds static int
8211da177e4SLinus Torvalds can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
82219a809afSAndrea Arcangeli 		    struct anon_vma *anon_vma, struct file *file,
82319a809afSAndrea Arcangeli 		    pgoff_t vm_pgoff,
8249a10064fSColin Cross 		    struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
8255c26f6acSSuren Baghdasaryan 		    struct anon_vma_name *anon_name)
8261da177e4SLinus Torvalds {
8279a10064fSColin Cross 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
828965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
8291da177e4SLinus Torvalds 		pgoff_t vm_pglen;
830d6e93217SLibin 		vm_pglen = vma_pages(vma);
8311da177e4SLinus Torvalds 		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
8321da177e4SLinus Torvalds 			return 1;
8331da177e4SLinus Torvalds 	}
8341da177e4SLinus Torvalds 	return 0;
8351da177e4SLinus Torvalds }
8361da177e4SLinus Torvalds 
8371da177e4SLinus Torvalds /*
8389a10064fSColin Cross  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
8399a10064fSColin Cross  * figure out whether that can be merged with its predecessor or its
8409a10064fSColin Cross  * successor.  Or both (it neatly fills a hole).
8411da177e4SLinus Torvalds  *
8421da177e4SLinus Torvalds  * In most cases - when called for mmap, brk or mremap - [addr,end) is
8431da177e4SLinus Torvalds  * certain not to be mapped by the time vma_merge is called; but when
8441da177e4SLinus Torvalds  * called for mprotect, it is certain to be already mapped (either at
8451da177e4SLinus Torvalds  * an offset within prev, or at the start of next), and the flags of
8461da177e4SLinus Torvalds  * this area are about to be changed to vm_flags - and the no-change
8471da177e4SLinus Torvalds  * case has already been eliminated.
8481da177e4SLinus Torvalds  *
8491da177e4SLinus Torvalds  * The following mprotect cases have to be considered, where AAAA is
8501da177e4SLinus Torvalds  * the area passed down from mprotect_fixup, never extending beyond one
8519e8a39d2SVlastimil Babka  * vma, PPPP is the previous vma, NNNN is a vma that starts at the same
8529e8a39d2SVlastimil Babka  * address as AAAA and is of the same or larger span, and XXXX the next
8539e8a39d2SVlastimil Babka  * vma after AAAA:
8541da177e4SLinus Torvalds  *
8555d42ab29SWei Yang  *     AAAA             AAAA                   AAAA
8569e8a39d2SVlastimil Babka  *    PPPPPPXXXXXX    PPPPPPXXXXXX       PPPPPPNNNNNN
8575d42ab29SWei Yang  *    cannot merge    might become       might become
858183b7a60SVlastimil Babka  *                    PPXXXXXXXXXX       PPPPPPPPPPNN
8595d42ab29SWei Yang  *    mmap, brk or    case 4 below       case 5 below
8605d42ab29SWei Yang  *    mremap move:
8615d42ab29SWei Yang  *                        AAAA               AAAA
862097d70c6SVlastimil Babka  *                    PPPP    XXXX       PPPPNNNNXXXX
8635d42ab29SWei Yang  *                    might become       might become
8645d42ab29SWei Yang  *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
865097d70c6SVlastimil Babka  *                    PPPPPPPPXXXX 2 or  PPPPPPPPXXXX 7 or
866097d70c6SVlastimil Babka  *                    PPPPXXXXXXXX 3     PPPPXXXXXXXX 8
8671da177e4SLinus Torvalds  *
8688bb4e7a2SWei Yang  * It is important for case 8 that the vma NNNN overlapping the
869e86f15eeSAndrea Arcangeli  * region AAAA is never going to extended over XXXX. Instead XXXX must
870e86f15eeSAndrea Arcangeli  * be extended in region AAAA and NNNN must be removed. This way in
8710503ea8fSLiam R. Howlett  * all cases where vma_merge succeeds, the moment vma_merge drops the
872e86f15eeSAndrea Arcangeli  * rmap_locks, the properties of the merged vma will be already
873e86f15eeSAndrea Arcangeli  * correct for the whole merged range. Some of those properties like
874e86f15eeSAndrea Arcangeli  * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
875e86f15eeSAndrea Arcangeli  * be correct for the whole merged range immediately after the
876e86f15eeSAndrea Arcangeli  * rmap_locks are released. Otherwise if XXXX would be removed and
877e86f15eeSAndrea Arcangeli  * NNNN would be extended over the XXXX range, remove_migration_ptes
878e86f15eeSAndrea Arcangeli  * or other rmap walkers (if working on addresses beyond the "end"
879e86f15eeSAndrea Arcangeli  * parameter) may establish ptes with the wrong permissions of NNNN
880e86f15eeSAndrea Arcangeli  * instead of the right permissions of XXXX.
8810503ea8fSLiam R. Howlett  *
8820503ea8fSLiam R. Howlett  * In the code below:
8830503ea8fSLiam R. Howlett  * PPPP is represented by *prev
8849e8a39d2SVlastimil Babka  * NNNN is represented by *mid or not represented at all (NULL)
8859e8a39d2SVlastimil Babka  * XXXX is represented by *next or not represented at all (NULL)
8869e8a39d2SVlastimil Babka  * AAAA is not represented - it will be merged and the vma containing the
8879e8a39d2SVlastimil Babka  *      area is returned, or the function will return NULL
8881da177e4SLinus Torvalds  */
8899760ebffSLiam R. Howlett struct vm_area_struct *vma_merge(struct vma_iterator *vmi, struct mm_struct *mm,
8901da177e4SLinus Torvalds 			struct vm_area_struct *prev, unsigned long addr,
8911da177e4SLinus Torvalds 			unsigned long end, unsigned long vm_flags,
8921da177e4SLinus Torvalds 			struct anon_vma *anon_vma, struct file *file,
89319a809afSAndrea Arcangeli 			pgoff_t pgoff, struct mempolicy *policy,
8949a10064fSColin Cross 			struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
8955c26f6acSSuren Baghdasaryan 			struct anon_vma_name *anon_name)
8961da177e4SLinus Torvalds {
8971da177e4SLinus Torvalds 	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
8980503ea8fSLiam R. Howlett 	pgoff_t vma_pgoff;
8999760ebffSLiam R. Howlett 	struct vm_area_struct *mid, *next, *res = NULL;
9000503ea8fSLiam R. Howlett 	struct vm_area_struct *vma, *adjust, *remove, *remove2;
901eef19944SJakub Matěna 	int err = -1;
902eef19944SJakub Matěna 	bool merge_prev = false;
903eef19944SJakub Matěna 	bool merge_next = false;
9040503ea8fSLiam R. Howlett 	bool vma_expanded = false;
9050503ea8fSLiam R. Howlett 	struct vma_prepare vp;
9060503ea8fSLiam R. Howlett 	unsigned long vma_end = end;
907*1e76454fSVlastimil Babka 	long adj_start = 0;
9080503ea8fSLiam R. Howlett 	unsigned long vma_start = addr;
9091da177e4SLinus Torvalds 
9100503ea8fSLiam R. Howlett 	validate_mm(mm);
9111da177e4SLinus Torvalds 	/*
9121da177e4SLinus Torvalds 	 * We later require that vma->vm_flags == vm_flags,
9131da177e4SLinus Torvalds 	 * so this tests vma->vm_flags & VM_SPECIAL, too.
9141da177e4SLinus Torvalds 	 */
9151da177e4SLinus Torvalds 	if (vm_flags & VM_SPECIAL)
9161da177e4SLinus Torvalds 		return NULL;
9171da177e4SLinus Torvalds 
9185cd70b96SVlastimil Babka 	mid = find_vma(mm, prev ? prev->vm_end : 0);
9195cd70b96SVlastimil Babka 	if (mid && mid->vm_end == end)			/* cases 6, 7, 8 */
9205cd70b96SVlastimil Babka 		next = find_vma(mm, mid->vm_end);
9215cd70b96SVlastimil Babka 	else
9225cd70b96SVlastimil Babka 		next = mid;
9231da177e4SLinus Torvalds 
9249e8a39d2SVlastimil Babka 	/* In cases 1 - 4 there's no NNNN vma */
9259e8a39d2SVlastimil Babka 	if (mid && end <= mid->vm_start)
9269e8a39d2SVlastimil Babka 		mid = NULL;
9279e8a39d2SVlastimil Babka 
928e86f15eeSAndrea Arcangeli 	/* verify some invariant that must be enforced by the caller */
929e86f15eeSAndrea Arcangeli 	VM_WARN_ON(prev && addr <= prev->vm_start);
930eef19944SJakub Matěna 	VM_WARN_ON(mid && end > mid->vm_end);
931e86f15eeSAndrea Arcangeli 	VM_WARN_ON(addr >= end);
932e86f15eeSAndrea Arcangeli 
9330503ea8fSLiam R. Howlett 	if (prev) {
9340503ea8fSLiam R. Howlett 		res = prev;
9350503ea8fSLiam R. Howlett 		vma = prev;
9360503ea8fSLiam R. Howlett 		vma_start = prev->vm_start;
9370503ea8fSLiam R. Howlett 		vma_pgoff = prev->vm_pgoff;
938eef19944SJakub Matěna 		/* Can we merge the predecessor? */
9390503ea8fSLiam R. Howlett 		if (prev->vm_end == addr && mpol_equal(vma_policy(prev), policy)
9400503ea8fSLiam R. Howlett 		    && can_vma_merge_after(prev, vm_flags, anon_vma, file,
9410503ea8fSLiam R. Howlett 				   pgoff, vm_userfaultfd_ctx, anon_name)) {
942eef19944SJakub Matěna 			merge_prev = true;
94318b098afSLiam R. Howlett 			vma_prev(vmi);
9441da177e4SLinus Torvalds 		}
9450503ea8fSLiam R. Howlett 	}
946eef19944SJakub Matěna 	/* Can we merge the successor? */
9471da177e4SLinus Torvalds 	if (next && end == next->vm_start &&
9481da177e4SLinus Torvalds 			mpol_equal(policy, vma_policy(next)) &&
9491da177e4SLinus Torvalds 			can_vma_merge_before(next, vm_flags,
95019a809afSAndrea Arcangeli 					     anon_vma, file, pgoff+pglen,
9519a10064fSColin Cross 					     vm_userfaultfd_ctx, anon_name)) {
952eef19944SJakub Matěna 		merge_next = true;
953eef19944SJakub Matěna 	}
9540503ea8fSLiam R. Howlett 
9550503ea8fSLiam R. Howlett 	remove = remove2 = adjust = NULL;
956eef19944SJakub Matěna 	/* Can we merge both the predecessor and the successor? */
957eef19944SJakub Matěna 	if (merge_prev && merge_next &&
9580503ea8fSLiam R. Howlett 	    is_mergeable_anon_vma(prev->anon_vma, next->anon_vma, NULL)) {
9595ff783f1SVlastimil Babka 		remove = next;				/* case 1 */
9600503ea8fSLiam R. Howlett 		vma_end = next->vm_end;
96150dac011SVlastimil Babka 		err = dup_anon_vma(prev, next);
9629e8a39d2SVlastimil Babka 		if (mid) {				/* case 6 */
9635ff783f1SVlastimil Babka 			remove = mid;
9645ff783f1SVlastimil Babka 			remove2 = next;
9655ff783f1SVlastimil Babka 			if (!next->anon_vma)
9665ff783f1SVlastimil Babka 				err = dup_anon_vma(prev, mid);
9670503ea8fSLiam R. Howlett 		}
9680503ea8fSLiam R. Howlett 	} else if (merge_prev) {
9690503ea8fSLiam R. Howlett 		err = 0;				/* case 2 */
9709e8a39d2SVlastimil Babka 		if (mid) {
97150dac011SVlastimil Babka 			err = dup_anon_vma(prev, mid);
9720503ea8fSLiam R. Howlett 			if (end == mid->vm_end) {	/* case 7 */
9730503ea8fSLiam R. Howlett 				remove = mid;
9740503ea8fSLiam R. Howlett 			} else {			/* case 5 */
9750503ea8fSLiam R. Howlett 				adjust = mid;
976*1e76454fSVlastimil Babka 				adj_start = (end - mid->vm_start);
9770503ea8fSLiam R. Howlett 			}
9780503ea8fSLiam R. Howlett 		}
979eef19944SJakub Matěna 	} else if (merge_next) {
980eef19944SJakub Matěna 		res = next;
9810503ea8fSLiam R. Howlett 		if (prev && addr < prev->vm_end) {	/* case 4 */
9820503ea8fSLiam R. Howlett 			vma_end = addr;
983183b7a60SVlastimil Babka 			adjust = next;
984*1e76454fSVlastimil Babka 			adj_start = -(prev->vm_end - addr);
985183b7a60SVlastimil Babka 			err = dup_anon_vma(next, prev);
9860503ea8fSLiam R. Howlett 		} else {
9870503ea8fSLiam R. Howlett 			vma = next;			/* case 3 */
9880503ea8fSLiam R. Howlett 			vma_start = addr;
9890503ea8fSLiam R. Howlett 			vma_end = next->vm_end;
990097d70c6SVlastimil Babka 			vma_pgoff = next->vm_pgoff;
9910503ea8fSLiam R. Howlett 			err = 0;
9929e8a39d2SVlastimil Babka 			if (mid) {			/* case 8 */
993097d70c6SVlastimil Babka 				vma_pgoff = mid->vm_pgoff;
9940503ea8fSLiam R. Howlett 				remove = mid;
99550dac011SVlastimil Babka 				err = dup_anon_vma(next, mid);
9960503ea8fSLiam R. Howlett 			}
9970503ea8fSLiam R. Howlett 		}
9981da177e4SLinus Torvalds 	}
9991da177e4SLinus Torvalds 
10000503ea8fSLiam R. Howlett 	/* Cannot merge or error in anon_vma clone */
1001eef19944SJakub Matěna 	if (err)
10021da177e4SLinus Torvalds 		return NULL;
10030503ea8fSLiam R. Howlett 
10040503ea8fSLiam R. Howlett 	if (vma_iter_prealloc(vmi))
10050503ea8fSLiam R. Howlett 		return NULL;
10060503ea8fSLiam R. Howlett 
1007*1e76454fSVlastimil Babka 	vma_adjust_trans_huge(vma, vma_start, vma_end, adj_start);
10080503ea8fSLiam R. Howlett 	init_multi_vma_prep(&vp, vma, adjust, remove, remove2);
10090503ea8fSLiam R. Howlett 	VM_WARN_ON(vp.anon_vma && adjust && adjust->anon_vma &&
10100503ea8fSLiam R. Howlett 		   vp.anon_vma != adjust->anon_vma);
10110503ea8fSLiam R. Howlett 
10120503ea8fSLiam R. Howlett 	vma_prepare(&vp);
10130503ea8fSLiam R. Howlett 	if (vma_start < vma->vm_start || vma_end > vma->vm_end)
10140503ea8fSLiam R. Howlett 		vma_expanded = true;
10150503ea8fSLiam R. Howlett 
10160503ea8fSLiam R. Howlett 	vma->vm_start = vma_start;
10170503ea8fSLiam R. Howlett 	vma->vm_end = vma_end;
10180503ea8fSLiam R. Howlett 	vma->vm_pgoff = vma_pgoff;
10190503ea8fSLiam R. Howlett 
10200503ea8fSLiam R. Howlett 	if (vma_expanded)
10210503ea8fSLiam R. Howlett 		vma_iter_store(vmi, vma);
10220503ea8fSLiam R. Howlett 
1023*1e76454fSVlastimil Babka 	if (adj_start) {
1024*1e76454fSVlastimil Babka 		adjust->vm_start += adj_start;
1025*1e76454fSVlastimil Babka 		adjust->vm_pgoff += adj_start >> PAGE_SHIFT;
1026*1e76454fSVlastimil Babka 		if (adj_start < 0) {
10270503ea8fSLiam R. Howlett 			WARN_ON(vma_expanded);
10280503ea8fSLiam R. Howlett 			vma_iter_store(vmi, next);
10290503ea8fSLiam R. Howlett 		}
10300503ea8fSLiam R. Howlett 	}
10310503ea8fSLiam R. Howlett 
10320503ea8fSLiam R. Howlett 	vma_complete(&vp, vmi, mm);
10330503ea8fSLiam R. Howlett 	vma_iter_free(vmi);
10340503ea8fSLiam R. Howlett 	validate_mm(mm);
1035eef19944SJakub Matěna 	khugepaged_enter_vma(res, vm_flags);
10361da177e4SLinus Torvalds 
10379760ebffSLiam R. Howlett 	return res;
1038f2ebfe43SLiam R. Howlett }
1039f2ebfe43SLiam R. Howlett 
10401da177e4SLinus Torvalds /*
1041b4f315b4SEthon Paul  * Rough compatibility check to quickly see if it's even worth looking
1042d0e9fe17SLinus Torvalds  * at sharing an anon_vma.
1043d0e9fe17SLinus Torvalds  *
1044d0e9fe17SLinus Torvalds  * They need to have the same vm_file, and the flags can only differ
1045d0e9fe17SLinus Torvalds  * in things that mprotect may change.
1046d0e9fe17SLinus Torvalds  *
1047d0e9fe17SLinus Torvalds  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1048d0e9fe17SLinus Torvalds  * we can merge the two vma's. For example, we refuse to merge a vma if
1049d0e9fe17SLinus Torvalds  * there is a vm_ops->close() function, because that indicates that the
1050d0e9fe17SLinus Torvalds  * driver is doing some kind of reference counting. But that doesn't
1051d0e9fe17SLinus Torvalds  * really matter for the anon_vma sharing case.
1052d0e9fe17SLinus Torvalds  */
1053d0e9fe17SLinus Torvalds static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1054d0e9fe17SLinus Torvalds {
1055d0e9fe17SLinus Torvalds 	return a->vm_end == b->vm_start &&
1056d0e9fe17SLinus Torvalds 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1057d0e9fe17SLinus Torvalds 		a->vm_file == b->vm_file &&
10586cb4d9a2SAnshuman Khandual 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1059d0e9fe17SLinus Torvalds 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1060d0e9fe17SLinus Torvalds }
1061d0e9fe17SLinus Torvalds 
1062d0e9fe17SLinus Torvalds /*
1063d0e9fe17SLinus Torvalds  * Do some basic sanity checking to see if we can re-use the anon_vma
1064d0e9fe17SLinus Torvalds  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1065d0e9fe17SLinus Torvalds  * the same as 'old', the other will be the new one that is trying
1066d0e9fe17SLinus Torvalds  * to share the anon_vma.
1067d0e9fe17SLinus Torvalds  *
10685b449489SFlorian Rommel  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1069d0e9fe17SLinus Torvalds  * the anon_vma of 'old' is concurrently in the process of being set up
1070d0e9fe17SLinus Torvalds  * by another page fault trying to merge _that_. But that's ok: if it
1071d0e9fe17SLinus Torvalds  * is being set up, that automatically means that it will be a singleton
1072d0e9fe17SLinus Torvalds  * acceptable for merging, so we can do all of this optimistically. But
10734db0c3c2SJason Low  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1074d0e9fe17SLinus Torvalds  *
1075d0e9fe17SLinus Torvalds  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1076d0e9fe17SLinus Torvalds  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1077d0e9fe17SLinus Torvalds  * is to return an anon_vma that is "complex" due to having gone through
1078d0e9fe17SLinus Torvalds  * a fork).
1079d0e9fe17SLinus Torvalds  *
1080d0e9fe17SLinus Torvalds  * We also make sure that the two vma's are compatible (adjacent,
1081d0e9fe17SLinus Torvalds  * and with the same memory policies). That's all stable, even with just
10825b449489SFlorian Rommel  * a read lock on the mmap_lock.
1083d0e9fe17SLinus Torvalds  */
1084d0e9fe17SLinus Torvalds static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1085d0e9fe17SLinus Torvalds {
1086d0e9fe17SLinus Torvalds 	if (anon_vma_compatible(a, b)) {
10874db0c3c2SJason Low 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1088d0e9fe17SLinus Torvalds 
1089d0e9fe17SLinus Torvalds 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1090d0e9fe17SLinus Torvalds 			return anon_vma;
1091d0e9fe17SLinus Torvalds 	}
1092d0e9fe17SLinus Torvalds 	return NULL;
1093d0e9fe17SLinus Torvalds }
1094d0e9fe17SLinus Torvalds 
1095d0e9fe17SLinus Torvalds /*
10961da177e4SLinus Torvalds  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
10971da177e4SLinus Torvalds  * neighbouring vmas for a suitable anon_vma, before it goes off
10981da177e4SLinus Torvalds  * to allocate a new anon_vma.  It checks because a repetitive
10991da177e4SLinus Torvalds  * sequence of mprotects and faults may otherwise lead to distinct
11001da177e4SLinus Torvalds  * anon_vmas being allocated, preventing vma merge in subsequent
11011da177e4SLinus Torvalds  * mprotect.
11021da177e4SLinus Torvalds  */
11031da177e4SLinus Torvalds struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
11041da177e4SLinus Torvalds {
1105763ecb03SLiam R. Howlett 	MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
1106a67c8caaSMiaohe Lin 	struct anon_vma *anon_vma = NULL;
1107763ecb03SLiam R. Howlett 	struct vm_area_struct *prev, *next;
11081da177e4SLinus Torvalds 
1109a67c8caaSMiaohe Lin 	/* Try next first. */
1110763ecb03SLiam R. Howlett 	next = mas_walk(&mas);
1111763ecb03SLiam R. Howlett 	if (next) {
1112763ecb03SLiam R. Howlett 		anon_vma = reusable_anon_vma(next, vma, next);
1113d0e9fe17SLinus Torvalds 		if (anon_vma)
1114d0e9fe17SLinus Torvalds 			return anon_vma;
1115a67c8caaSMiaohe Lin 	}
11161da177e4SLinus Torvalds 
1117763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
1118763ecb03SLiam R. Howlett 	VM_BUG_ON_VMA(prev != vma, vma);
1119763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
1120a67c8caaSMiaohe Lin 	/* Try prev next. */
1121763ecb03SLiam R. Howlett 	if (prev)
1122763ecb03SLiam R. Howlett 		anon_vma = reusable_anon_vma(prev, prev, vma);
1123a67c8caaSMiaohe Lin 
11241da177e4SLinus Torvalds 	/*
1125a67c8caaSMiaohe Lin 	 * We might reach here with anon_vma == NULL if we can't find
1126a67c8caaSMiaohe Lin 	 * any reusable anon_vma.
11271da177e4SLinus Torvalds 	 * There's no absolute need to look only at touching neighbours:
11281da177e4SLinus Torvalds 	 * we could search further afield for "compatible" anon_vmas.
11291da177e4SLinus Torvalds 	 * But it would probably just be a waste of time searching,
11301da177e4SLinus Torvalds 	 * or lead to too many vmas hanging off the same anon_vma.
11311da177e4SLinus Torvalds 	 * We're trying to allow mprotect remerging later on,
11321da177e4SLinus Torvalds 	 * not trying to minimize memory used for anon_vmas.
11331da177e4SLinus Torvalds 	 */
1134a67c8caaSMiaohe Lin 	return anon_vma;
11351da177e4SLinus Torvalds }
11361da177e4SLinus Torvalds 
11371da177e4SLinus Torvalds /*
113840401530SAl Viro  * If a hint addr is less than mmap_min_addr change hint to be as
113940401530SAl Viro  * low as possible but still greater than mmap_min_addr
114040401530SAl Viro  */
114140401530SAl Viro static inline unsigned long round_hint_to_min(unsigned long hint)
114240401530SAl Viro {
114340401530SAl Viro 	hint &= PAGE_MASK;
114440401530SAl Viro 	if (((void *)hint != NULL) &&
114540401530SAl Viro 	    (hint < mmap_min_addr))
114640401530SAl Viro 		return PAGE_ALIGN(mmap_min_addr);
114740401530SAl Viro 	return hint;
114840401530SAl Viro }
114940401530SAl Viro 
11506aeb2542SMike Rapoport int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1151363ee17fSDavidlohr Bueso 		       unsigned long len)
1152363ee17fSDavidlohr Bueso {
1153363ee17fSDavidlohr Bueso 	unsigned long locked, lock_limit;
1154363ee17fSDavidlohr Bueso 
1155363ee17fSDavidlohr Bueso 	/*  mlock MCL_FUTURE? */
1156363ee17fSDavidlohr Bueso 	if (flags & VM_LOCKED) {
1157363ee17fSDavidlohr Bueso 		locked = len >> PAGE_SHIFT;
1158363ee17fSDavidlohr Bueso 		locked += mm->locked_vm;
1159363ee17fSDavidlohr Bueso 		lock_limit = rlimit(RLIMIT_MEMLOCK);
1160363ee17fSDavidlohr Bueso 		lock_limit >>= PAGE_SHIFT;
1161363ee17fSDavidlohr Bueso 		if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1162363ee17fSDavidlohr Bueso 			return -EAGAIN;
1163363ee17fSDavidlohr Bueso 	}
1164363ee17fSDavidlohr Bueso 	return 0;
1165363ee17fSDavidlohr Bueso }
1166363ee17fSDavidlohr Bueso 
1167be83bbf8SLinus Torvalds static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1168be83bbf8SLinus Torvalds {
1169be83bbf8SLinus Torvalds 	if (S_ISREG(inode->i_mode))
1170423913adSLinus Torvalds 		return MAX_LFS_FILESIZE;
1171be83bbf8SLinus Torvalds 
1172be83bbf8SLinus Torvalds 	if (S_ISBLK(inode->i_mode))
1173be83bbf8SLinus Torvalds 		return MAX_LFS_FILESIZE;
1174be83bbf8SLinus Torvalds 
117576f34950SIvan Khoronzhuk 	if (S_ISSOCK(inode->i_mode))
117676f34950SIvan Khoronzhuk 		return MAX_LFS_FILESIZE;
117776f34950SIvan Khoronzhuk 
1178be83bbf8SLinus Torvalds 	/* Special "we do even unsigned file positions" case */
1179be83bbf8SLinus Torvalds 	if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1180be83bbf8SLinus Torvalds 		return 0;
1181be83bbf8SLinus Torvalds 
1182be83bbf8SLinus Torvalds 	/* Yes, random drivers might want more. But I'm tired of buggy drivers */
1183be83bbf8SLinus Torvalds 	return ULONG_MAX;
1184be83bbf8SLinus Torvalds }
1185be83bbf8SLinus Torvalds 
1186be83bbf8SLinus Torvalds static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1187be83bbf8SLinus Torvalds 				unsigned long pgoff, unsigned long len)
1188be83bbf8SLinus Torvalds {
1189be83bbf8SLinus Torvalds 	u64 maxsize = file_mmap_size_max(file, inode);
1190be83bbf8SLinus Torvalds 
1191be83bbf8SLinus Torvalds 	if (maxsize && len > maxsize)
1192be83bbf8SLinus Torvalds 		return false;
1193be83bbf8SLinus Torvalds 	maxsize -= len;
1194be83bbf8SLinus Torvalds 	if (pgoff > maxsize >> PAGE_SHIFT)
1195be83bbf8SLinus Torvalds 		return false;
1196be83bbf8SLinus Torvalds 	return true;
1197be83bbf8SLinus Torvalds }
1198be83bbf8SLinus Torvalds 
119940401530SAl Viro /*
12003e4e28c5SMichel Lespinasse  * The caller must write-lock current->mm->mmap_lock.
12011da177e4SLinus Torvalds  */
12021fcfd8dbSOleg Nesterov unsigned long do_mmap(struct file *file, unsigned long addr,
12031da177e4SLinus Torvalds 			unsigned long len, unsigned long prot,
120445e55300SPeter Collingbourne 			unsigned long flags, unsigned long pgoff,
120545e55300SPeter Collingbourne 			unsigned long *populate, struct list_head *uf)
12061da177e4SLinus Torvalds {
12071da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
120845e55300SPeter Collingbourne 	vm_flags_t vm_flags;
120962b5f7d0SDave Hansen 	int pkey = 0;
12101da177e4SLinus Torvalds 
1211524e00b3SLiam R. Howlett 	validate_mm(mm);
121241badc15SMichel Lespinasse 	*populate = 0;
1213bebeb3d6SMichel Lespinasse 
1214e37609bbSPiotr Kwapulinski 	if (!len)
1215e37609bbSPiotr Kwapulinski 		return -EINVAL;
1216e37609bbSPiotr Kwapulinski 
12171da177e4SLinus Torvalds 	/*
12181da177e4SLinus Torvalds 	 * Does the application expect PROT_READ to imply PROT_EXEC?
12191da177e4SLinus Torvalds 	 *
12201da177e4SLinus Torvalds 	 * (the exception is when the underlying filesystem is noexec
12211da177e4SLinus Torvalds 	 *  mounted, in which case we dont add PROT_EXEC.)
12221da177e4SLinus Torvalds 	 */
12231da177e4SLinus Torvalds 	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
122490f8572bSEric W. Biederman 		if (!(file && path_noexec(&file->f_path)))
12251da177e4SLinus Torvalds 			prot |= PROT_EXEC;
12261da177e4SLinus Torvalds 
1227a4ff8e86SMichal Hocko 	/* force arch specific MAP_FIXED handling in get_unmapped_area */
1228a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE)
1229a4ff8e86SMichal Hocko 		flags |= MAP_FIXED;
1230a4ff8e86SMichal Hocko 
12317cd94146SEric Paris 	if (!(flags & MAP_FIXED))
12327cd94146SEric Paris 		addr = round_hint_to_min(addr);
12337cd94146SEric Paris 
12341da177e4SLinus Torvalds 	/* Careful about overflows.. */
12351da177e4SLinus Torvalds 	len = PAGE_ALIGN(len);
12369206de95SAl Viro 	if (!len)
12371da177e4SLinus Torvalds 		return -ENOMEM;
12381da177e4SLinus Torvalds 
12391da177e4SLinus Torvalds 	/* offset overflow? */
12401da177e4SLinus Torvalds 	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
12411da177e4SLinus Torvalds 		return -EOVERFLOW;
12421da177e4SLinus Torvalds 
12431da177e4SLinus Torvalds 	/* Too many mappings? */
12441da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
12451da177e4SLinus Torvalds 		return -ENOMEM;
12461da177e4SLinus Torvalds 
12471da177e4SLinus Torvalds 	/* Obtain the address to map to. we verify (or select) it and ensure
12481da177e4SLinus Torvalds 	 * that it represents a valid section of the address space.
12491da177e4SLinus Torvalds 	 */
12501da177e4SLinus Torvalds 	addr = get_unmapped_area(file, addr, len, pgoff, flags);
1251ff68dac6SGaowei Pu 	if (IS_ERR_VALUE(addr))
12521da177e4SLinus Torvalds 		return addr;
12531da177e4SLinus Torvalds 
1254a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE) {
125535e43c5fSLiam Howlett 		if (find_vma_intersection(mm, addr, addr + len))
1256a4ff8e86SMichal Hocko 			return -EEXIST;
1257a4ff8e86SMichal Hocko 	}
1258a4ff8e86SMichal Hocko 
125962b5f7d0SDave Hansen 	if (prot == PROT_EXEC) {
126062b5f7d0SDave Hansen 		pkey = execute_only_pkey(mm);
126162b5f7d0SDave Hansen 		if (pkey < 0)
126262b5f7d0SDave Hansen 			pkey = 0;
126362b5f7d0SDave Hansen 	}
126462b5f7d0SDave Hansen 
12651da177e4SLinus Torvalds 	/* Do simple checking here so the lower-level routines won't have
12661da177e4SLinus Torvalds 	 * to. we assume access permissions have been handled by the open
12671da177e4SLinus Torvalds 	 * of the memory object, so we don't do any here.
12681da177e4SLinus Torvalds 	 */
126945e55300SPeter Collingbourne 	vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
12701da177e4SLinus Torvalds 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
12711da177e4SLinus Torvalds 
1272cdf7b341SHuang Shijie 	if (flags & MAP_LOCKED)
12731da177e4SLinus Torvalds 		if (!can_do_mlock())
12741da177e4SLinus Torvalds 			return -EPERM;
1275ba470de4SRik van Riel 
1276363ee17fSDavidlohr Bueso 	if (mlock_future_check(mm, vm_flags, len))
12771da177e4SLinus Torvalds 		return -EAGAIN;
12781da177e4SLinus Torvalds 
12791da177e4SLinus Torvalds 	if (file) {
1280077bf22bSOleg Nesterov 		struct inode *inode = file_inode(file);
12811c972597SDan Williams 		unsigned long flags_mask;
12821c972597SDan Williams 
1283be83bbf8SLinus Torvalds 		if (!file_mmap_ok(file, inode, pgoff, len))
1284be83bbf8SLinus Torvalds 			return -EOVERFLOW;
1285be83bbf8SLinus Torvalds 
12861c972597SDan Williams 		flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1287077bf22bSOleg Nesterov 
12881da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
12891da177e4SLinus Torvalds 		case MAP_SHARED:
12901c972597SDan Williams 			/*
12911c972597SDan Williams 			 * Force use of MAP_SHARED_VALIDATE with non-legacy
12921c972597SDan Williams 			 * flags. E.g. MAP_SYNC is dangerous to use with
12931c972597SDan Williams 			 * MAP_SHARED as you don't know which consistency model
12941c972597SDan Williams 			 * you will get. We silently ignore unsupported flags
12951c972597SDan Williams 			 * with MAP_SHARED to preserve backward compatibility.
12961c972597SDan Williams 			 */
12971c972597SDan Williams 			flags &= LEGACY_MAP_MASK;
1298e4a9bc58SJoe Perches 			fallthrough;
12991c972597SDan Williams 		case MAP_SHARED_VALIDATE:
13001c972597SDan Williams 			if (flags & ~flags_mask)
13011c972597SDan Williams 				return -EOPNOTSUPP;
1302dc617f29SDarrick J. Wong 			if (prot & PROT_WRITE) {
1303dc617f29SDarrick J. Wong 				if (!(file->f_mode & FMODE_WRITE))
13041da177e4SLinus Torvalds 					return -EACCES;
1305dc617f29SDarrick J. Wong 				if (IS_SWAPFILE(file->f_mapping->host))
1306dc617f29SDarrick J. Wong 					return -ETXTBSY;
1307dc617f29SDarrick J. Wong 			}
13081da177e4SLinus Torvalds 
13091da177e4SLinus Torvalds 			/*
13101da177e4SLinus Torvalds 			 * Make sure we don't allow writing to an append-only
13111da177e4SLinus Torvalds 			 * file..
13121da177e4SLinus Torvalds 			 */
13131da177e4SLinus Torvalds 			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
13141da177e4SLinus Torvalds 				return -EACCES;
13151da177e4SLinus Torvalds 
13161da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
13171da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_WRITE))
13181da177e4SLinus Torvalds 				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1319e4a9bc58SJoe Perches 			fallthrough;
13201da177e4SLinus Torvalds 		case MAP_PRIVATE:
13211da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_READ))
13221da177e4SLinus Torvalds 				return -EACCES;
132390f8572bSEric W. Biederman 			if (path_noexec(&file->f_path)) {
132480c5606cSLinus Torvalds 				if (vm_flags & VM_EXEC)
132580c5606cSLinus Torvalds 					return -EPERM;
132680c5606cSLinus Torvalds 				vm_flags &= ~VM_MAYEXEC;
132780c5606cSLinus Torvalds 			}
132880c5606cSLinus Torvalds 
132972c2d531SAl Viro 			if (!file->f_op->mmap)
133080c5606cSLinus Torvalds 				return -ENODEV;
1331b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1332b2c56e4fSOleg Nesterov 				return -EINVAL;
13331da177e4SLinus Torvalds 			break;
13341da177e4SLinus Torvalds 
13351da177e4SLinus Torvalds 		default:
13361da177e4SLinus Torvalds 			return -EINVAL;
13371da177e4SLinus Torvalds 		}
13381da177e4SLinus Torvalds 	} else {
13391da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
13401da177e4SLinus Torvalds 		case MAP_SHARED:
1341b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1342b2c56e4fSOleg Nesterov 				return -EINVAL;
1343ce363942STejun Heo 			/*
1344ce363942STejun Heo 			 * Ignore pgoff.
1345ce363942STejun Heo 			 */
1346ce363942STejun Heo 			pgoff = 0;
13471da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
13481da177e4SLinus Torvalds 			break;
13491da177e4SLinus Torvalds 		case MAP_PRIVATE:
13501da177e4SLinus Torvalds 			/*
13511da177e4SLinus Torvalds 			 * Set pgoff according to addr for anon_vma.
13521da177e4SLinus Torvalds 			 */
13531da177e4SLinus Torvalds 			pgoff = addr >> PAGE_SHIFT;
13541da177e4SLinus Torvalds 			break;
13551da177e4SLinus Torvalds 		default:
13561da177e4SLinus Torvalds 			return -EINVAL;
13571da177e4SLinus Torvalds 		}
13581da177e4SLinus Torvalds 	}
13591da177e4SLinus Torvalds 
1360c22c0d63SMichel Lespinasse 	/*
1361c22c0d63SMichel Lespinasse 	 * Set 'VM_NORESERVE' if we should not account for the
1362c22c0d63SMichel Lespinasse 	 * memory use of this mapping.
1363c22c0d63SMichel Lespinasse 	 */
1364c22c0d63SMichel Lespinasse 	if (flags & MAP_NORESERVE) {
1365c22c0d63SMichel Lespinasse 		/* We honor MAP_NORESERVE if allowed to overcommit */
1366c22c0d63SMichel Lespinasse 		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1367c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1368c22c0d63SMichel Lespinasse 
1369c22c0d63SMichel Lespinasse 		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
1370c22c0d63SMichel Lespinasse 		if (file && is_file_hugepages(file))
1371c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1372c22c0d63SMichel Lespinasse 	}
1373c22c0d63SMichel Lespinasse 
1374897ab3e0SMike Rapoport 	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
137509a9f1d2SMichel Lespinasse 	if (!IS_ERR_VALUE(addr) &&
137609a9f1d2SMichel Lespinasse 	    ((vm_flags & VM_LOCKED) ||
137709a9f1d2SMichel Lespinasse 	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
137841badc15SMichel Lespinasse 		*populate = len;
1379bebeb3d6SMichel Lespinasse 	return addr;
13800165ab44SMiklos Szeredi }
13816be5ceb0SLinus Torvalds 
1382a90f590aSDominik Brodowski unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1383a90f590aSDominik Brodowski 			      unsigned long prot, unsigned long flags,
1384a90f590aSDominik Brodowski 			      unsigned long fd, unsigned long pgoff)
138566f0dc48SHugh Dickins {
138666f0dc48SHugh Dickins 	struct file *file = NULL;
13871e3ee14bSChen Gang 	unsigned long retval;
138866f0dc48SHugh Dickins 
138966f0dc48SHugh Dickins 	if (!(flags & MAP_ANONYMOUS)) {
1390120a795dSAl Viro 		audit_mmap_fd(fd, flags);
139166f0dc48SHugh Dickins 		file = fget(fd);
139266f0dc48SHugh Dickins 		if (!file)
13931e3ee14bSChen Gang 			return -EBADF;
13947bba8f0eSZhen Lei 		if (is_file_hugepages(file)) {
1395af73e4d9SNaoya Horiguchi 			len = ALIGN(len, huge_page_size(hstate_file(file)));
13967bba8f0eSZhen Lei 		} else if (unlikely(flags & MAP_HUGETLB)) {
1397493af578SJörn Engel 			retval = -EINVAL;
1398493af578SJörn Engel 			goto out_fput;
13997bba8f0eSZhen Lei 		}
140066f0dc48SHugh Dickins 	} else if (flags & MAP_HUGETLB) {
1401c103a4dcSAndrew Morton 		struct hstate *hs;
1402af73e4d9SNaoya Horiguchi 
140320ac2893SAnshuman Khandual 		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1404091d0d55SLi Zefan 		if (!hs)
1405091d0d55SLi Zefan 			return -EINVAL;
1406091d0d55SLi Zefan 
1407091d0d55SLi Zefan 		len = ALIGN(len, huge_page_size(hs));
140866f0dc48SHugh Dickins 		/*
140966f0dc48SHugh Dickins 		 * VM_NORESERVE is used because the reservations will be
141066f0dc48SHugh Dickins 		 * taken when vm_ops->mmap() is called
141166f0dc48SHugh Dickins 		 */
1412af73e4d9SNaoya Horiguchi 		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
141342d7395fSAndi Kleen 				VM_NORESERVE,
141483c1fd76Szhangyiru 				HUGETLB_ANONHUGE_INODE,
141542d7395fSAndi Kleen 				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
141666f0dc48SHugh Dickins 		if (IS_ERR(file))
141766f0dc48SHugh Dickins 			return PTR_ERR(file);
141866f0dc48SHugh Dickins 	}
141966f0dc48SHugh Dickins 
14209fbeb5abSMichal Hocko 	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1421493af578SJörn Engel out_fput:
142266f0dc48SHugh Dickins 	if (file)
142366f0dc48SHugh Dickins 		fput(file);
142466f0dc48SHugh Dickins 	return retval;
142566f0dc48SHugh Dickins }
142666f0dc48SHugh Dickins 
1427a90f590aSDominik Brodowski SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1428a90f590aSDominik Brodowski 		unsigned long, prot, unsigned long, flags,
1429a90f590aSDominik Brodowski 		unsigned long, fd, unsigned long, pgoff)
1430a90f590aSDominik Brodowski {
1431a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1432a90f590aSDominik Brodowski }
1433a90f590aSDominik Brodowski 
1434a4679373SChristoph Hellwig #ifdef __ARCH_WANT_SYS_OLD_MMAP
1435a4679373SChristoph Hellwig struct mmap_arg_struct {
1436a4679373SChristoph Hellwig 	unsigned long addr;
1437a4679373SChristoph Hellwig 	unsigned long len;
1438a4679373SChristoph Hellwig 	unsigned long prot;
1439a4679373SChristoph Hellwig 	unsigned long flags;
1440a4679373SChristoph Hellwig 	unsigned long fd;
1441a4679373SChristoph Hellwig 	unsigned long offset;
1442a4679373SChristoph Hellwig };
1443a4679373SChristoph Hellwig 
1444a4679373SChristoph Hellwig SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1445a4679373SChristoph Hellwig {
1446a4679373SChristoph Hellwig 	struct mmap_arg_struct a;
1447a4679373SChristoph Hellwig 
1448a4679373SChristoph Hellwig 	if (copy_from_user(&a, arg, sizeof(a)))
1449a4679373SChristoph Hellwig 		return -EFAULT;
1450de1741a1SAlexander Kuleshov 	if (offset_in_page(a.offset))
1451a4679373SChristoph Hellwig 		return -EINVAL;
1452a4679373SChristoph Hellwig 
1453a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1454a4679373SChristoph Hellwig 			       a.offset >> PAGE_SHIFT);
1455a4679373SChristoph Hellwig }
1456a4679373SChristoph Hellwig #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1457a4679373SChristoph Hellwig 
14584e950f6fSAlexey Dobriyan /*
14598bb4e7a2SWei Yang  * Some shared mappings will want the pages marked read-only
14604e950f6fSAlexey Dobriyan  * to track write events. If so, we'll downgrade vm_page_prot
14614e950f6fSAlexey Dobriyan  * to the private version (using protection_map[] without the
14624e950f6fSAlexey Dobriyan  * VM_SHARED bit).
14634e950f6fSAlexey Dobriyan  */
14646d2329f8SAndrea Arcangeli int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
14654e950f6fSAlexey Dobriyan {
1466ca16d140SKOSAKI Motohiro 	vm_flags_t vm_flags = vma->vm_flags;
14678a04446aSKirill A. Shutemov 	const struct vm_operations_struct *vm_ops = vma->vm_ops;
14684e950f6fSAlexey Dobriyan 
14694e950f6fSAlexey Dobriyan 	/* If it was private or non-writable, the write bit is already clear */
14704e950f6fSAlexey Dobriyan 	if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
14714e950f6fSAlexey Dobriyan 		return 0;
14724e950f6fSAlexey Dobriyan 
14734e950f6fSAlexey Dobriyan 	/* The backer wishes to know when pages are first written to? */
14748a04446aSKirill A. Shutemov 	if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
14754e950f6fSAlexey Dobriyan 		return 1;
14764e950f6fSAlexey Dobriyan 
147764e45507SPeter Feiner 	/* The open routine did something to the protections that pgprot_modify
147864e45507SPeter Feiner 	 * won't preserve? */
14796d2329f8SAndrea Arcangeli 	if (pgprot_val(vm_page_prot) !=
14806d2329f8SAndrea Arcangeli 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
14814e950f6fSAlexey Dobriyan 		return 0;
14824e950f6fSAlexey Dobriyan 
1483f96f7a40SDavid Hildenbrand 	/*
1484f96f7a40SDavid Hildenbrand 	 * Do we need to track softdirty? hugetlb does not support softdirty
1485f96f7a40SDavid Hildenbrand 	 * tracking yet.
1486f96f7a40SDavid Hildenbrand 	 */
1487f96f7a40SDavid Hildenbrand 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
148864e45507SPeter Feiner 		return 1;
148964e45507SPeter Feiner 
149051d3d5ebSDavid Hildenbrand 	/* Do we need write faults for uffd-wp tracking? */
149151d3d5ebSDavid Hildenbrand 	if (userfaultfd_wp(vma))
149251d3d5ebSDavid Hildenbrand 		return 1;
149351d3d5ebSDavid Hildenbrand 
14944e950f6fSAlexey Dobriyan 	/* Specialty mapping? */
14954b6e1e37SKonstantin Khlebnikov 	if (vm_flags & VM_PFNMAP)
14964e950f6fSAlexey Dobriyan 		return 0;
14974e950f6fSAlexey Dobriyan 
14984e950f6fSAlexey Dobriyan 	/* Can the mapping track the dirty pages? */
14994e950f6fSAlexey Dobriyan 	return vma->vm_file && vma->vm_file->f_mapping &&
1500f56753acSChristoph Hellwig 		mapping_can_writeback(vma->vm_file->f_mapping);
15014e950f6fSAlexey Dobriyan }
15024e950f6fSAlexey Dobriyan 
1503fc8744adSLinus Torvalds /*
1504fc8744adSLinus Torvalds  * We account for memory if it's a private writeable mapping,
15055a6fe125SMel Gorman  * not hugepages and VM_NORESERVE wasn't set.
1506fc8744adSLinus Torvalds  */
1507ca16d140SKOSAKI Motohiro static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1508fc8744adSLinus Torvalds {
15095a6fe125SMel Gorman 	/*
15105a6fe125SMel Gorman 	 * hugetlb has its own accounting separate from the core VM
15115a6fe125SMel Gorman 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
15125a6fe125SMel Gorman 	 */
15135a6fe125SMel Gorman 	if (file && is_file_hugepages(file))
15145a6fe125SMel Gorman 		return 0;
15155a6fe125SMel Gorman 
1516fc8744adSLinus Torvalds 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1517fc8744adSLinus Torvalds }
1518fc8744adSLinus Torvalds 
15193499a131SLiam R. Howlett /**
15203499a131SLiam R. Howlett  * unmapped_area() - Find an area between the low_limit and the high_limit with
15213499a131SLiam R. Howlett  * the correct alignment and offset, all from @info. Note: current->mm is used
15223499a131SLiam R. Howlett  * for the search.
15233499a131SLiam R. Howlett  *
152482b24936SVernon Yang  * @info: The unmapped area information including the range [low_limit -
152582b24936SVernon Yang  * high_limit), the alignment offset and mask.
15263499a131SLiam R. Howlett  *
15273499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
15283499a131SLiam R. Howlett  */
1529baceaf1cSJaewon Kim static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1530db4fbfb9SMichel Lespinasse {
15313499a131SLiam R. Howlett 	unsigned long length, gap;
1532db4fbfb9SMichel Lespinasse 
15333499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1534db4fbfb9SMichel Lespinasse 
1535db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1536db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1537db4fbfb9SMichel Lespinasse 	if (length < info->length)
1538db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1539db4fbfb9SMichel Lespinasse 
15403499a131SLiam R. Howlett 	if (mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
15413499a131SLiam R. Howlett 				  length))
15423499a131SLiam R. Howlett 		return -ENOMEM;
15433499a131SLiam R. Howlett 
1544d4af56c5SLiam R. Howlett 	gap = mas.index;
1545d4af56c5SLiam R. Howlett 	gap += (info->align_offset - gap) & info->align_mask;
15463499a131SLiam R. Howlett 	return gap;
1547db4fbfb9SMichel Lespinasse }
1548db4fbfb9SMichel Lespinasse 
15493499a131SLiam R. Howlett /**
15503499a131SLiam R. Howlett  * unmapped_area_topdown() - Find an area between the low_limit and the
155182b24936SVernon Yang  * high_limit with the correct alignment and offset at the highest available
15523499a131SLiam R. Howlett  * address, all from @info. Note: current->mm is used for the search.
15533499a131SLiam R. Howlett  *
155482b24936SVernon Yang  * @info: The unmapped area information including the range [low_limit -
155582b24936SVernon Yang  * high_limit), the alignment offset and mask.
15563499a131SLiam R. Howlett  *
15573499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
15583499a131SLiam R. Howlett  */
1559baceaf1cSJaewon Kim static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1560db4fbfb9SMichel Lespinasse {
15613499a131SLiam R. Howlett 	unsigned long length, gap;
1562d4af56c5SLiam R. Howlett 
15633499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1564db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1565db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1566db4fbfb9SMichel Lespinasse 	if (length < info->length)
1567db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1568db4fbfb9SMichel Lespinasse 
15693499a131SLiam R. Howlett 	if (mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
15703499a131SLiam R. Howlett 				length))
15713499a131SLiam R. Howlett 		return -ENOMEM;
15723499a131SLiam R. Howlett 
1573d4af56c5SLiam R. Howlett 	gap = mas.last + 1 - info->length;
1574d4af56c5SLiam R. Howlett 	gap -= (gap - info->align_offset) & info->align_mask;
15753499a131SLiam R. Howlett 	return gap;
1576db4fbfb9SMichel Lespinasse }
1577db4fbfb9SMichel Lespinasse 
1578baceaf1cSJaewon Kim /*
1579baceaf1cSJaewon Kim  * Search for an unmapped address range.
1580baceaf1cSJaewon Kim  *
1581baceaf1cSJaewon Kim  * We are looking for a range that:
1582baceaf1cSJaewon Kim  * - does not intersect with any VMA;
1583baceaf1cSJaewon Kim  * - is contained within the [low_limit, high_limit) interval;
1584baceaf1cSJaewon Kim  * - is at least the desired size.
1585baceaf1cSJaewon Kim  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
1586baceaf1cSJaewon Kim  */
1587baceaf1cSJaewon Kim unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
1588baceaf1cSJaewon Kim {
1589df529cabSJaewon Kim 	unsigned long addr;
1590df529cabSJaewon Kim 
1591baceaf1cSJaewon Kim 	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1592df529cabSJaewon Kim 		addr = unmapped_area_topdown(info);
1593baceaf1cSJaewon Kim 	else
1594df529cabSJaewon Kim 		addr = unmapped_area(info);
1595df529cabSJaewon Kim 
1596df529cabSJaewon Kim 	trace_vm_unmapped_area(addr, info);
1597df529cabSJaewon Kim 	return addr;
1598baceaf1cSJaewon Kim }
1599f6795053SSteve Capper 
16001da177e4SLinus Torvalds /* Get an address range which is currently unmapped.
16011da177e4SLinus Torvalds  * For shmat() with addr=0.
16021da177e4SLinus Torvalds  *
16031da177e4SLinus Torvalds  * Ugly calling convention alert:
16041da177e4SLinus Torvalds  * Return value with the low bits set means error value,
16051da177e4SLinus Torvalds  * ie
16061da177e4SLinus Torvalds  *	if (ret & ~PAGE_MASK)
16071da177e4SLinus Torvalds  *		error = ret;
16081da177e4SLinus Torvalds  *
16091da177e4SLinus Torvalds  * This function "knows" that -ENOMEM has the bits set.
16101da177e4SLinus Torvalds  */
16111da177e4SLinus Torvalds unsigned long
16124b439e25SChristophe Leroy generic_get_unmapped_area(struct file *filp, unsigned long addr,
16134b439e25SChristophe Leroy 			  unsigned long len, unsigned long pgoff,
16144b439e25SChristophe Leroy 			  unsigned long flags)
16151da177e4SLinus Torvalds {
16161da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
16171be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
1618db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
16192cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
16201da177e4SLinus Torvalds 
1621f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
16221da177e4SLinus Torvalds 		return -ENOMEM;
16231da177e4SLinus Torvalds 
162406abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
162506abdfb4SBenjamin Herrenschmidt 		return addr;
162606abdfb4SBenjamin Herrenschmidt 
16271da177e4SLinus Torvalds 	if (addr) {
16281da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
16291be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1630f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
16311be7107fSHugh Dickins 		    (!vma || addr + len <= vm_start_gap(vma)) &&
16321be7107fSHugh Dickins 		    (!prev || addr >= vm_end_gap(prev)))
16331da177e4SLinus Torvalds 			return addr;
16341da177e4SLinus Torvalds 	}
16351da177e4SLinus Torvalds 
1636db4fbfb9SMichel Lespinasse 	info.flags = 0;
1637db4fbfb9SMichel Lespinasse 	info.length = len;
16384e99b021SHeiko Carstens 	info.low_limit = mm->mmap_base;
1639f6795053SSteve Capper 	info.high_limit = mmap_end;
1640db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
164109ef5283SJaewon Kim 	info.align_offset = 0;
1642db4fbfb9SMichel Lespinasse 	return vm_unmapped_area(&info);
16431da177e4SLinus Torvalds }
16444b439e25SChristophe Leroy 
16454b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA
16464b439e25SChristophe Leroy unsigned long
16474b439e25SChristophe Leroy arch_get_unmapped_area(struct file *filp, unsigned long addr,
16484b439e25SChristophe Leroy 		       unsigned long len, unsigned long pgoff,
16494b439e25SChristophe Leroy 		       unsigned long flags)
16504b439e25SChristophe Leroy {
16514b439e25SChristophe Leroy 	return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
16524b439e25SChristophe Leroy }
16531da177e4SLinus Torvalds #endif
16541da177e4SLinus Torvalds 
16551da177e4SLinus Torvalds /*
16561da177e4SLinus Torvalds  * This mmap-allocator allocates new areas top-down from below the
16571da177e4SLinus Torvalds  * stack's low limit (the base):
16581da177e4SLinus Torvalds  */
16591da177e4SLinus Torvalds unsigned long
16604b439e25SChristophe Leroy generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
166143cca0b1SYang Fan 				  unsigned long len, unsigned long pgoff,
166243cca0b1SYang Fan 				  unsigned long flags)
16631da177e4SLinus Torvalds {
16641be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
16651da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1666db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
16672cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
16681da177e4SLinus Torvalds 
16691da177e4SLinus Torvalds 	/* requested length too big for entire address space */
1670f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
16711da177e4SLinus Torvalds 		return -ENOMEM;
16721da177e4SLinus Torvalds 
167306abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
167406abdfb4SBenjamin Herrenschmidt 		return addr;
167506abdfb4SBenjamin Herrenschmidt 
16761da177e4SLinus Torvalds 	/* requesting a specific address */
16771da177e4SLinus Torvalds 	if (addr) {
16781da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
16791be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1680f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
16811be7107fSHugh Dickins 				(!vma || addr + len <= vm_start_gap(vma)) &&
16821be7107fSHugh Dickins 				(!prev || addr >= vm_end_gap(prev)))
16831da177e4SLinus Torvalds 			return addr;
16841da177e4SLinus Torvalds 	}
16851da177e4SLinus Torvalds 
1686db4fbfb9SMichel Lespinasse 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1687db4fbfb9SMichel Lespinasse 	info.length = len;
16882afc745fSAkira Takeuchi 	info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1689f6795053SSteve Capper 	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1690db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
169109ef5283SJaewon Kim 	info.align_offset = 0;
1692db4fbfb9SMichel Lespinasse 	addr = vm_unmapped_area(&info);
1693b716ad95SXiao Guangrong 
16941da177e4SLinus Torvalds 	/*
16951da177e4SLinus Torvalds 	 * A failed mmap() very likely causes application failure,
16961da177e4SLinus Torvalds 	 * so fall back to the bottom-up function here. This scenario
16971da177e4SLinus Torvalds 	 * can happen with large stack limits and large mmap()
16981da177e4SLinus Torvalds 	 * allocations.
16991da177e4SLinus Torvalds 	 */
1700de1741a1SAlexander Kuleshov 	if (offset_in_page(addr)) {
1701db4fbfb9SMichel Lespinasse 		VM_BUG_ON(addr != -ENOMEM);
1702db4fbfb9SMichel Lespinasse 		info.flags = 0;
1703db4fbfb9SMichel Lespinasse 		info.low_limit = TASK_UNMAPPED_BASE;
1704f6795053SSteve Capper 		info.high_limit = mmap_end;
1705db4fbfb9SMichel Lespinasse 		addr = vm_unmapped_area(&info);
1706db4fbfb9SMichel Lespinasse 	}
17071da177e4SLinus Torvalds 
17081da177e4SLinus Torvalds 	return addr;
17091da177e4SLinus Torvalds }
17104b439e25SChristophe Leroy 
17114b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
17124b439e25SChristophe Leroy unsigned long
17134b439e25SChristophe Leroy arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
17144b439e25SChristophe Leroy 			       unsigned long len, unsigned long pgoff,
17154b439e25SChristophe Leroy 			       unsigned long flags)
17164b439e25SChristophe Leroy {
17174b439e25SChristophe Leroy 	return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
17184b439e25SChristophe Leroy }
17191da177e4SLinus Torvalds #endif
17201da177e4SLinus Torvalds 
17211da177e4SLinus Torvalds unsigned long
17221da177e4SLinus Torvalds get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
17231da177e4SLinus Torvalds 		unsigned long pgoff, unsigned long flags)
17241da177e4SLinus Torvalds {
172506abdfb4SBenjamin Herrenschmidt 	unsigned long (*get_area)(struct file *, unsigned long,
172606abdfb4SBenjamin Herrenschmidt 				  unsigned long, unsigned long, unsigned long);
172707ab67c8SLinus Torvalds 
17289206de95SAl Viro 	unsigned long error = arch_mmap_check(addr, len, flags);
17299206de95SAl Viro 	if (error)
17309206de95SAl Viro 		return error;
17319206de95SAl Viro 
17329206de95SAl Viro 	/* Careful about overflows.. */
17339206de95SAl Viro 	if (len > TASK_SIZE)
17349206de95SAl Viro 		return -ENOMEM;
17359206de95SAl Viro 
173607ab67c8SLinus Torvalds 	get_area = current->mm->get_unmapped_area;
1737c01d5b30SHugh Dickins 	if (file) {
1738c01d5b30SHugh Dickins 		if (file->f_op->get_unmapped_area)
173907ab67c8SLinus Torvalds 			get_area = file->f_op->get_unmapped_area;
1740c01d5b30SHugh Dickins 	} else if (flags & MAP_SHARED) {
1741c01d5b30SHugh Dickins 		/*
1742c01d5b30SHugh Dickins 		 * mmap_region() will call shmem_zero_setup() to create a file,
1743c01d5b30SHugh Dickins 		 * so use shmem's get_unmapped_area in case it can be huge.
174445e55300SPeter Collingbourne 		 * do_mmap() will clear pgoff, so match alignment.
1745c01d5b30SHugh Dickins 		 */
1746c01d5b30SHugh Dickins 		pgoff = 0;
1747c01d5b30SHugh Dickins 		get_area = shmem_get_unmapped_area;
1748c01d5b30SHugh Dickins 	}
1749c01d5b30SHugh Dickins 
175007ab67c8SLinus Torvalds 	addr = get_area(file, addr, len, pgoff, flags);
175107ab67c8SLinus Torvalds 	if (IS_ERR_VALUE(addr))
175207ab67c8SLinus Torvalds 		return addr;
175307ab67c8SLinus Torvalds 
17541da177e4SLinus Torvalds 	if (addr > TASK_SIZE - len)
17551da177e4SLinus Torvalds 		return -ENOMEM;
1756de1741a1SAlexander Kuleshov 	if (offset_in_page(addr))
17571da177e4SLinus Torvalds 		return -EINVAL;
175806abdfb4SBenjamin Herrenschmidt 
17599ac4ed4bSAl Viro 	error = security_mmap_addr(addr);
17609ac4ed4bSAl Viro 	return error ? error : addr;
17611da177e4SLinus Torvalds }
17621da177e4SLinus Torvalds 
17631da177e4SLinus Torvalds EXPORT_SYMBOL(get_unmapped_area);
17641da177e4SLinus Torvalds 
1765be8432e7SLiam R. Howlett /**
1766abdba2ddSLiam R. Howlett  * find_vma_intersection() - Look up the first VMA which intersects the interval
1767abdba2ddSLiam R. Howlett  * @mm: The process address space.
1768abdba2ddSLiam R. Howlett  * @start_addr: The inclusive start user address.
1769abdba2ddSLiam R. Howlett  * @end_addr: The exclusive end user address.
1770abdba2ddSLiam R. Howlett  *
1771abdba2ddSLiam R. Howlett  * Returns: The first VMA within the provided range, %NULL otherwise.  Assumes
1772abdba2ddSLiam R. Howlett  * start_addr < end_addr.
1773abdba2ddSLiam R. Howlett  */
1774abdba2ddSLiam R. Howlett struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
1775abdba2ddSLiam R. Howlett 					     unsigned long start_addr,
1776abdba2ddSLiam R. Howlett 					     unsigned long end_addr)
1777abdba2ddSLiam R. Howlett {
1778abdba2ddSLiam R. Howlett 	unsigned long index = start_addr;
1779abdba2ddSLiam R. Howlett 
1780abdba2ddSLiam R. Howlett 	mmap_assert_locked(mm);
17817964cf8cSLiam R. Howlett 	return mt_find(&mm->mm_mt, &index, end_addr - 1);
1782abdba2ddSLiam R. Howlett }
1783abdba2ddSLiam R. Howlett EXPORT_SYMBOL(find_vma_intersection);
1784abdba2ddSLiam R. Howlett 
1785abdba2ddSLiam R. Howlett /**
1786be8432e7SLiam R. Howlett  * find_vma() - Find the VMA for a given address, or the next VMA.
1787be8432e7SLiam R. Howlett  * @mm: The mm_struct to check
1788be8432e7SLiam R. Howlett  * @addr: The address
1789be8432e7SLiam R. Howlett  *
1790be8432e7SLiam R. Howlett  * Returns: The VMA associated with addr, or the next VMA.
1791be8432e7SLiam R. Howlett  * May return %NULL in the case of no VMA at addr or above.
1792be8432e7SLiam R. Howlett  */
17931da177e4SLinus Torvalds struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
17941da177e4SLinus Torvalds {
1795be8432e7SLiam R. Howlett 	unsigned long index = addr;
17961da177e4SLinus Torvalds 
17975b78ed24SLuigi Rizzo 	mmap_assert_locked(mm);
17987964cf8cSLiam R. Howlett 	return mt_find(&mm->mm_mt, &index, ULONG_MAX);
17991da177e4SLinus Torvalds }
18001da177e4SLinus Torvalds EXPORT_SYMBOL(find_vma);
18011da177e4SLinus Torvalds 
18027fdbd37dSLiam R. Howlett /**
18037fdbd37dSLiam R. Howlett  * find_vma_prev() - Find the VMA for a given address, or the next vma and
18047fdbd37dSLiam R. Howlett  * set %pprev to the previous VMA, if any.
18057fdbd37dSLiam R. Howlett  * @mm: The mm_struct to check
18067fdbd37dSLiam R. Howlett  * @addr: The address
18077fdbd37dSLiam R. Howlett  * @pprev: The pointer to set to the previous VMA
18087fdbd37dSLiam R. Howlett  *
18097fdbd37dSLiam R. Howlett  * Note that RCU lock is missing here since the external mmap_lock() is used
18107fdbd37dSLiam R. Howlett  * instead.
18117fdbd37dSLiam R. Howlett  *
18127fdbd37dSLiam R. Howlett  * Returns: The VMA associated with @addr, or the next vma.
18137fdbd37dSLiam R. Howlett  * May return %NULL in the case of no vma at addr or above.
18146bd4837dSKOSAKI Motohiro  */
18151da177e4SLinus Torvalds struct vm_area_struct *
18161da177e4SLinus Torvalds find_vma_prev(struct mm_struct *mm, unsigned long addr,
18171da177e4SLinus Torvalds 			struct vm_area_struct **pprev)
18181da177e4SLinus Torvalds {
18196bd4837dSKOSAKI Motohiro 	struct vm_area_struct *vma;
18207fdbd37dSLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, addr, addr);
18211da177e4SLinus Torvalds 
18227fdbd37dSLiam R. Howlett 	vma = mas_walk(&mas);
18237fdbd37dSLiam R. Howlett 	*pprev = mas_prev(&mas, 0);
18247fdbd37dSLiam R. Howlett 	if (!vma)
18257fdbd37dSLiam R. Howlett 		vma = mas_next(&mas, ULONG_MAX);
18266bd4837dSKOSAKI Motohiro 	return vma;
18271da177e4SLinus Torvalds }
18281da177e4SLinus Torvalds 
18291da177e4SLinus Torvalds /*
18301da177e4SLinus Torvalds  * Verify that the stack growth is acceptable and
18311da177e4SLinus Torvalds  * update accounting. This is shared with both the
18321da177e4SLinus Torvalds  * grow-up and grow-down cases.
18331da177e4SLinus Torvalds  */
18341be7107fSHugh Dickins static int acct_stack_growth(struct vm_area_struct *vma,
18351be7107fSHugh Dickins 			     unsigned long size, unsigned long grow)
18361da177e4SLinus Torvalds {
18371da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
18381be7107fSHugh Dickins 	unsigned long new_start;
18391da177e4SLinus Torvalds 
18401da177e4SLinus Torvalds 	/* address space limit tests */
184184638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vma->vm_flags, grow))
18421da177e4SLinus Torvalds 		return -ENOMEM;
18431da177e4SLinus Torvalds 
18441da177e4SLinus Torvalds 	/* Stack limit test */
184524c79d8eSKrzysztof Opasiak 	if (size > rlimit(RLIMIT_STACK))
18461da177e4SLinus Torvalds 		return -ENOMEM;
18471da177e4SLinus Torvalds 
18481da177e4SLinus Torvalds 	/* mlock limit tests */
1849c5d8a364SMiaohe Lin 	if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
18501da177e4SLinus Torvalds 		return -ENOMEM;
18511da177e4SLinus Torvalds 
18520d59a01bSAdam Litke 	/* Check to ensure the stack will not grow into a hugetlb-only region */
18530d59a01bSAdam Litke 	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
18540d59a01bSAdam Litke 			vma->vm_end - size;
18550d59a01bSAdam Litke 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
18560d59a01bSAdam Litke 		return -EFAULT;
18570d59a01bSAdam Litke 
18581da177e4SLinus Torvalds 	/*
18591da177e4SLinus Torvalds 	 * Overcommit..  This must be the final test, as it will
18601da177e4SLinus Torvalds 	 * update security statistics.
18611da177e4SLinus Torvalds 	 */
186205fa199dSHugh Dickins 	if (security_vm_enough_memory_mm(mm, grow))
18631da177e4SLinus Torvalds 		return -ENOMEM;
18641da177e4SLinus Torvalds 
18651da177e4SLinus Torvalds 	return 0;
18661da177e4SLinus Torvalds }
18671da177e4SLinus Torvalds 
186846dea3d0SHugh Dickins #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
18691da177e4SLinus Torvalds /*
187046dea3d0SHugh Dickins  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
187146dea3d0SHugh Dickins  * vma is the last one with address > vma->vm_end.  Have to extend vma.
18721da177e4SLinus Torvalds  */
187346dea3d0SHugh Dickins int expand_upwards(struct vm_area_struct *vma, unsigned long address)
18741da177e4SLinus Torvalds {
187509357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
18761be7107fSHugh Dickins 	struct vm_area_struct *next;
18771be7107fSHugh Dickins 	unsigned long gap_addr;
187812352d3cSKonstantin Khlebnikov 	int error = 0;
1879d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
18801da177e4SLinus Torvalds 
18811da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSUP))
18821da177e4SLinus Torvalds 		return -EFAULT;
18831da177e4SLinus Torvalds 
1884bd726c90SHelge Deller 	/* Guard against exceeding limits of the address space. */
18851be7107fSHugh Dickins 	address &= PAGE_MASK;
188637511fb5SHelge Deller 	if (address >= (TASK_SIZE & PAGE_MASK))
188712352d3cSKonstantin Khlebnikov 		return -ENOMEM;
1888bd726c90SHelge Deller 	address += PAGE_SIZE;
188912352d3cSKonstantin Khlebnikov 
18901be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
18911be7107fSHugh Dickins 	gap_addr = address + stack_guard_gap;
1892bd726c90SHelge Deller 
1893bd726c90SHelge Deller 	/* Guard against overflow */
1894bd726c90SHelge Deller 	if (gap_addr < address || gap_addr > TASK_SIZE)
1895bd726c90SHelge Deller 		gap_addr = TASK_SIZE;
1896bd726c90SHelge Deller 
1897763ecb03SLiam R. Howlett 	next = find_vma_intersection(mm, vma->vm_end, gap_addr);
1898763ecb03SLiam R. Howlett 	if (next && vma_is_accessible(next)) {
18991be7107fSHugh Dickins 		if (!(next->vm_flags & VM_GROWSUP))
19001be7107fSHugh Dickins 			return -ENOMEM;
19011be7107fSHugh Dickins 		/* Check that both stack segments have the same anon_vma? */
19021be7107fSHugh Dickins 	}
19031be7107fSHugh Dickins 
1904c5d5546eSVernon Yang 	if (mas_preallocate(&mas, GFP_KERNEL))
19051da177e4SLinus Torvalds 		return -ENOMEM;
19061da177e4SLinus Torvalds 
1907d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
1908d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
1909d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
1910d4af56c5SLiam R. Howlett 		return -ENOMEM;
1911d4af56c5SLiam R. Howlett 	}
1912d4af56c5SLiam R. Howlett 
19131da177e4SLinus Torvalds 	/*
19141da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
1915c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
19161da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
19171da177e4SLinus Torvalds 	 */
191812352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
19191da177e4SLinus Torvalds 
19201da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
19211da177e4SLinus Torvalds 	if (address > vma->vm_end) {
19221da177e4SLinus Torvalds 		unsigned long size, grow;
19231da177e4SLinus Torvalds 
19241da177e4SLinus Torvalds 		size = address - vma->vm_start;
19251da177e4SLinus Torvalds 		grow = (address - vma->vm_end) >> PAGE_SHIFT;
19261da177e4SLinus Torvalds 
192742c36f63SHugh Dickins 		error = -ENOMEM;
192842c36f63SHugh Dickins 		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
19291da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
19303af9e859SEric B Munson 			if (!error) {
19314128997bSMichel Lespinasse 				/*
1932524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
1933524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
1934524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
1935524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
1936524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
1937524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
1938524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
19394128997bSMichel Lespinasse 				 */
194009357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
194187e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
194209357814SOleg Nesterov 					mm->locked_vm += grow;
194384638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
1944bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
19451da177e4SLinus Torvalds 				vma->vm_end = address;
1946d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
1947fbcc3104SLiam R. Howlett 				mas_set_range(&mas, vma->vm_start, address - 1);
1948fbcc3104SLiam R. Howlett 				mas_store_prealloc(&mas, vma);
1949bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
195009357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
19514128997bSMichel Lespinasse 
19523af9e859SEric B Munson 				perf_event_mmap(vma);
19533af9e859SEric B Munson 			}
19541da177e4SLinus Torvalds 		}
195542c36f63SHugh Dickins 	}
195612352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
1957c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
1958d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
19591da177e4SLinus Torvalds 	return error;
19601da177e4SLinus Torvalds }
196146dea3d0SHugh Dickins #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
196246dea3d0SHugh Dickins 
19631da177e4SLinus Torvalds /*
19641da177e4SLinus Torvalds  * vma is the first one with address < vma->vm_start.  Have to extend vma.
19651da177e4SLinus Torvalds  */
1966524e00b3SLiam R. Howlett int expand_downwards(struct vm_area_struct *vma, unsigned long address)
19671da177e4SLinus Torvalds {
196809357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
1969763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
19701be7107fSHugh Dickins 	struct vm_area_struct *prev;
19710a1d5299SJann Horn 	int error = 0;
19721da177e4SLinus Torvalds 
19738869477aSEric Paris 	address &= PAGE_MASK;
19740a1d5299SJann Horn 	if (address < mmap_min_addr)
19750a1d5299SJann Horn 		return -EPERM;
19768869477aSEric Paris 
19771be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
1978763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
19791be7107fSHugh Dickins 	/* Check that both stack segments have the same anon_vma? */
198032e4e6d5SOleg Nesterov 	if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
19813122e80eSAnshuman Khandual 			vma_is_accessible(prev)) {
198232e4e6d5SOleg Nesterov 		if (address - prev->vm_end < stack_guard_gap)
198332e4e6d5SOleg Nesterov 			return -ENOMEM;
19841be7107fSHugh Dickins 	}
19851be7107fSHugh Dickins 
1986c5d5546eSVernon Yang 	if (mas_preallocate(&mas, GFP_KERNEL))
198712352d3cSKonstantin Khlebnikov 		return -ENOMEM;
19881da177e4SLinus Torvalds 
1989d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
1990d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
1991d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
1992d4af56c5SLiam R. Howlett 		return -ENOMEM;
1993d4af56c5SLiam R. Howlett 	}
1994d4af56c5SLiam R. Howlett 
19951da177e4SLinus Torvalds 	/*
19961da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
1997c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
19981da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
19991da177e4SLinus Torvalds 	 */
200012352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
20011da177e4SLinus Torvalds 
20021da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
20031da177e4SLinus Torvalds 	if (address < vma->vm_start) {
20041da177e4SLinus Torvalds 		unsigned long size, grow;
20051da177e4SLinus Torvalds 
20061da177e4SLinus Torvalds 		size = vma->vm_end - address;
20071da177e4SLinus Torvalds 		grow = (vma->vm_start - address) >> PAGE_SHIFT;
20081da177e4SLinus Torvalds 
2009a626ca6aSLinus Torvalds 		error = -ENOMEM;
2010a626ca6aSLinus Torvalds 		if (grow <= vma->vm_pgoff) {
20111da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
20121da177e4SLinus Torvalds 			if (!error) {
20134128997bSMichel Lespinasse 				/*
2014524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
2015524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
2016524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
2017524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
2018524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
2019524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
2020524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
20214128997bSMichel Lespinasse 				 */
202209357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
202387e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
202409357814SOleg Nesterov 					mm->locked_vm += grow;
202584638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2026bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
20271da177e4SLinus Torvalds 				vma->vm_start = address;
20281da177e4SLinus Torvalds 				vma->vm_pgoff -= grow;
2029d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2030fbcc3104SLiam R. Howlett 				mas_set_range(&mas, address, vma->vm_end - 1);
2031fbcc3104SLiam R. Howlett 				mas_store_prealloc(&mas, vma);
2032bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
203309357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
20344128997bSMichel Lespinasse 
20353af9e859SEric B Munson 				perf_event_mmap(vma);
20361da177e4SLinus Torvalds 			}
20371da177e4SLinus Torvalds 		}
2038a626ca6aSLinus Torvalds 	}
203912352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2040c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2041d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
20421da177e4SLinus Torvalds 	return error;
20431da177e4SLinus Torvalds }
20441da177e4SLinus Torvalds 
20451be7107fSHugh Dickins /* enforced gap between the expanding stack and other mappings. */
20461be7107fSHugh Dickins unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
20471be7107fSHugh Dickins 
20481be7107fSHugh Dickins static int __init cmdline_parse_stack_guard_gap(char *p)
20491be7107fSHugh Dickins {
20501be7107fSHugh Dickins 	unsigned long val;
20511be7107fSHugh Dickins 	char *endptr;
20521be7107fSHugh Dickins 
20531be7107fSHugh Dickins 	val = simple_strtoul(p, &endptr, 10);
20541be7107fSHugh Dickins 	if (!*endptr)
20551be7107fSHugh Dickins 		stack_guard_gap = val << PAGE_SHIFT;
20561be7107fSHugh Dickins 
2057e6d09493SRandy Dunlap 	return 1;
20581be7107fSHugh Dickins }
20591be7107fSHugh Dickins __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
20601be7107fSHugh Dickins 
2061b6a2fea3SOllie Wild #ifdef CONFIG_STACK_GROWSUP
2062b6a2fea3SOllie Wild int expand_stack(struct vm_area_struct *vma, unsigned long address)
2063b6a2fea3SOllie Wild {
2064b6a2fea3SOllie Wild 	return expand_upwards(vma, address);
2065b6a2fea3SOllie Wild }
2066b6a2fea3SOllie Wild 
2067b6a2fea3SOllie Wild struct vm_area_struct *
2068b6a2fea3SOllie Wild find_extend_vma(struct mm_struct *mm, unsigned long addr)
2069b6a2fea3SOllie Wild {
2070b6a2fea3SOllie Wild 	struct vm_area_struct *vma, *prev;
2071b6a2fea3SOllie Wild 
2072b6a2fea3SOllie Wild 	addr &= PAGE_MASK;
2073b6a2fea3SOllie Wild 	vma = find_vma_prev(mm, addr, &prev);
2074b6a2fea3SOllie Wild 	if (vma && (vma->vm_start <= addr))
2075b6a2fea3SOllie Wild 		return vma;
20764d45e75aSJann Horn 	if (!prev || expand_stack(prev, addr))
2077b6a2fea3SOllie Wild 		return NULL;
2078cea10a19SMichel Lespinasse 	if (prev->vm_flags & VM_LOCKED)
2079fc05f566SKirill A. Shutemov 		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2080b6a2fea3SOllie Wild 	return prev;
2081b6a2fea3SOllie Wild }
2082b6a2fea3SOllie Wild #else
2083b6a2fea3SOllie Wild int expand_stack(struct vm_area_struct *vma, unsigned long address)
2084b6a2fea3SOllie Wild {
2085b6a2fea3SOllie Wild 	return expand_downwards(vma, address);
2086b6a2fea3SOllie Wild }
2087b6a2fea3SOllie Wild 
20881da177e4SLinus Torvalds struct vm_area_struct *
20891da177e4SLinus Torvalds find_extend_vma(struct mm_struct *mm, unsigned long addr)
20901da177e4SLinus Torvalds {
20911da177e4SLinus Torvalds 	struct vm_area_struct *vma;
20921da177e4SLinus Torvalds 	unsigned long start;
20931da177e4SLinus Torvalds 
20941da177e4SLinus Torvalds 	addr &= PAGE_MASK;
20951da177e4SLinus Torvalds 	vma = find_vma(mm, addr);
20961da177e4SLinus Torvalds 	if (!vma)
20971da177e4SLinus Torvalds 		return NULL;
20981da177e4SLinus Torvalds 	if (vma->vm_start <= addr)
20991da177e4SLinus Torvalds 		return vma;
21001da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSDOWN))
21011da177e4SLinus Torvalds 		return NULL;
21021da177e4SLinus Torvalds 	start = vma->vm_start;
21031da177e4SLinus Torvalds 	if (expand_stack(vma, addr))
21041da177e4SLinus Torvalds 		return NULL;
2105cea10a19SMichel Lespinasse 	if (vma->vm_flags & VM_LOCKED)
2106fc05f566SKirill A. Shutemov 		populate_vma_page_range(vma, addr, start, NULL);
21071da177e4SLinus Torvalds 	return vma;
21081da177e4SLinus Torvalds }
21091da177e4SLinus Torvalds #endif
21101da177e4SLinus Torvalds 
2111e1d6d01aSJesse Barnes EXPORT_SYMBOL_GPL(find_extend_vma);
2112e1d6d01aSJesse Barnes 
21132c0b3814SHugh Dickins /*
2114763ecb03SLiam R. Howlett  * Ok - we have the memory areas we should free on a maple tree so release them,
2115763ecb03SLiam R. Howlett  * and do the vma updates.
21161da177e4SLinus Torvalds  *
21172c0b3814SHugh Dickins  * Called with the mm semaphore held.
21181da177e4SLinus Torvalds  */
2119763ecb03SLiam R. Howlett static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
21201da177e4SLinus Torvalds {
21214f74d2c8SLinus Torvalds 	unsigned long nr_accounted = 0;
2122763ecb03SLiam R. Howlett 	struct vm_area_struct *vma;
21234f74d2c8SLinus Torvalds 
2124365e9c87SHugh Dickins 	/* Update high watermark before we lower total_vm */
2125365e9c87SHugh Dickins 	update_hiwater_vm(mm);
2126763ecb03SLiam R. Howlett 	mas_for_each(mas, vma, ULONG_MAX) {
2127ab50b8edSHugh Dickins 		long nrpages = vma_pages(vma);
21281da177e4SLinus Torvalds 
21294f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
21304f74d2c8SLinus Torvalds 			nr_accounted += nrpages;
213184638335SKonstantin Khlebnikov 		vm_stat_account(mm, vma->vm_flags, -nrpages);
2132763ecb03SLiam R. Howlett 		remove_vma(vma);
2133763ecb03SLiam R. Howlett 	}
21344f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
21351da177e4SLinus Torvalds 	validate_mm(mm);
21361da177e4SLinus Torvalds }
21371da177e4SLinus Torvalds 
21381da177e4SLinus Torvalds /*
21391da177e4SLinus Torvalds  * Get rid of page table information in the indicated region.
21401da177e4SLinus Torvalds  *
2141f10df686SPaolo 'Blaisorblade' Giarrusso  * Called with the mm semaphore held.
21421da177e4SLinus Torvalds  */
2143763ecb03SLiam R. Howlett static void unmap_region(struct mm_struct *mm, struct maple_tree *mt,
2144e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
2145763ecb03SLiam R. Howlett 		struct vm_area_struct *next,
214668f48381SSuren Baghdasaryan 		unsigned long start, unsigned long end, bool mm_wr_locked)
21471da177e4SLinus Torvalds {
2148d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
21491da177e4SLinus Torvalds 
21501da177e4SLinus Torvalds 	lru_add_drain();
2151a72afd87SWill Deacon 	tlb_gather_mmu(&tlb, mm);
2152365e9c87SHugh Dickins 	update_hiwater_rss(mm);
215368f48381SSuren Baghdasaryan 	unmap_vmas(&tlb, mt, vma, start, end, mm_wr_locked);
2154763ecb03SLiam R. Howlett 	free_pgtables(&tlb, mt, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
21556ee8630eSHugh Dickins 				 next ? next->vm_start : USER_PGTABLES_CEILING);
2156ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
21571da177e4SLinus Torvalds }
21581da177e4SLinus Torvalds 
21591da177e4SLinus Torvalds /*
2160def5efe0SDavid Rientjes  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2161def5efe0SDavid Rientjes  * has already been checked or doesn't make sense to fail.
21620fd5a9e2SLiam R. Howlett  * VMA Iterator will point to the end VMA.
21631da177e4SLinus Torvalds  */
21649760ebffSLiam R. Howlett int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
21651da177e4SLinus Torvalds 		unsigned long addr, int new_below)
21661da177e4SLinus Torvalds {
2167b2b3b886SLiam R. Howlett 	struct vma_prepare vp;
21681da177e4SLinus Torvalds 	struct vm_area_struct *new;
2169e3975891SChen Gang 	int err;
21709760ebffSLiam R. Howlett 
21719760ebffSLiam R. Howlett 	validate_mm_mt(vma->vm_mm);
21721da177e4SLinus Torvalds 
2173b2b3b886SLiam R. Howlett 	WARN_ON(vma->vm_start >= addr);
2174b2b3b886SLiam R. Howlett 	WARN_ON(vma->vm_end <= addr);
2175b2b3b886SLiam R. Howlett 
2176dd3b614fSDmitry Safonov 	if (vma->vm_ops && vma->vm_ops->may_split) {
2177dd3b614fSDmitry Safonov 		err = vma->vm_ops->may_split(vma, addr);
217831383c68SDan Williams 		if (err)
217931383c68SDan Williams 			return err;
218031383c68SDan Williams 	}
21811da177e4SLinus Torvalds 
21823928d4f5SLinus Torvalds 	new = vm_area_dup(vma);
21831da177e4SLinus Torvalds 	if (!new)
2184e3975891SChen Gang 		return -ENOMEM;
21851da177e4SLinus Torvalds 
2186b2b3b886SLiam R. Howlett 	err = -ENOMEM;
2187b2b3b886SLiam R. Howlett 	if (vma_iter_prealloc(vmi))
2188b2b3b886SLiam R. Howlett 		goto out_free_vma;
2189b2b3b886SLiam R. Howlett 
2190b2b3b886SLiam R. Howlett 	if (new_below) {
21911da177e4SLinus Torvalds 		new->vm_end = addr;
2192b2b3b886SLiam R. Howlett 	} else {
21931da177e4SLinus Torvalds 		new->vm_start = addr;
21941da177e4SLinus Torvalds 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
21951da177e4SLinus Torvalds 	}
21961da177e4SLinus Torvalds 
2197ef0855d3SOleg Nesterov 	err = vma_dup_policy(vma, new);
2198ef0855d3SOleg Nesterov 	if (err)
2199b2b3b886SLiam R. Howlett 		goto out_free_vmi;
22001da177e4SLinus Torvalds 
2201c4ea95d7SDaniel Forrest 	err = anon_vma_clone(new, vma);
2202c4ea95d7SDaniel Forrest 	if (err)
22035beb4930SRik van Riel 		goto out_free_mpol;
22045beb4930SRik van Riel 
2205e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
22061da177e4SLinus Torvalds 		get_file(new->vm_file);
22071da177e4SLinus Torvalds 
22081da177e4SLinus Torvalds 	if (new->vm_ops && new->vm_ops->open)
22091da177e4SLinus Torvalds 		new->vm_ops->open(new);
22101da177e4SLinus Torvalds 
2211b2b3b886SLiam R. Howlett 	vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
2212b2b3b886SLiam R. Howlett 	init_vma_prep(&vp, vma);
2213b2b3b886SLiam R. Howlett 	vp.insert = new;
2214b2b3b886SLiam R. Howlett 	vma_prepare(&vp);
22151da177e4SLinus Torvalds 
2216b2b3b886SLiam R. Howlett 	if (new_below) {
2217b2b3b886SLiam R. Howlett 		vma->vm_start = addr;
2218b2b3b886SLiam R. Howlett 		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
2219b2b3b886SLiam R. Howlett 	} else {
2220b2b3b886SLiam R. Howlett 		vma->vm_end = addr;
22219760ebffSLiam R. Howlett 	}
22225beb4930SRik van Riel 
2223b2b3b886SLiam R. Howlett 	/* vma_complete stores the new vma */
2224b2b3b886SLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
2225b2b3b886SLiam R. Howlett 
2226b2b3b886SLiam R. Howlett 	/* Success. */
2227b2b3b886SLiam R. Howlett 	if (new_below)
2228b2b3b886SLiam R. Howlett 		vma_next(vmi);
2229b2b3b886SLiam R. Howlett 	validate_mm_mt(vma->vm_mm);
2230b2b3b886SLiam R. Howlett 	return 0;
2231b2b3b886SLiam R. Howlett 
22325beb4930SRik van Riel out_free_mpol:
2233ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new));
2234b2b3b886SLiam R. Howlett out_free_vmi:
2235b2b3b886SLiam R. Howlett 	vma_iter_free(vmi);
22365beb4930SRik van Riel out_free_vma:
22373928d4f5SLinus Torvalds 	vm_area_free(new);
22389760ebffSLiam R. Howlett 	validate_mm_mt(vma->vm_mm);
22395beb4930SRik van Riel 	return err;
22401da177e4SLinus Torvalds }
22411da177e4SLinus Torvalds 
2242659ace58SKOSAKI Motohiro /*
2243659ace58SKOSAKI Motohiro  * Split a vma into two pieces at address 'addr', a new vma is allocated
2244659ace58SKOSAKI Motohiro  * either for the first part or the tail.
2245659ace58SKOSAKI Motohiro  */
22469760ebffSLiam R. Howlett int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2247659ace58SKOSAKI Motohiro 	      unsigned long addr, int new_below)
2248659ace58SKOSAKI Motohiro {
22499760ebffSLiam R. Howlett 	if (vma->vm_mm->map_count >= sysctl_max_map_count)
2250659ace58SKOSAKI Motohiro 		return -ENOMEM;
2251659ace58SKOSAKI Motohiro 
22529760ebffSLiam R. Howlett 	return __split_vma(vmi, vma, addr, new_below);
2253f2ebfe43SLiam R. Howlett }
2254f2ebfe43SLiam R. Howlett 
2255763ecb03SLiam R. Howlett static inline int munmap_sidetree(struct vm_area_struct *vma,
2256763ecb03SLiam R. Howlett 				   struct ma_state *mas_detach)
22571da177e4SLinus Torvalds {
2258763ecb03SLiam R. Howlett 	mas_set_range(mas_detach, vma->vm_start, vma->vm_end - 1);
2259763ecb03SLiam R. Howlett 	if (mas_store_gfp(mas_detach, vma, GFP_KERNEL))
2260763ecb03SLiam R. Howlett 		return -ENOMEM;
226111f9a21aSLiam R. Howlett 
2262763ecb03SLiam R. Howlett 	if (vma->vm_flags & VM_LOCKED)
2263763ecb03SLiam R. Howlett 		vma->vm_mm->locked_vm -= vma_pages(vma);
226411f9a21aSLiam R. Howlett 
2265763ecb03SLiam R. Howlett 	return 0;
226611f9a21aSLiam R. Howlett }
226711f9a21aSLiam R. Howlett 
226811f9a21aSLiam R. Howlett /*
2269183654ceSLiam R. Howlett  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
2270183654ceSLiam R. Howlett  * @vmi: The vma iterator
227111f9a21aSLiam R. Howlett  * @vma: The starting vm_area_struct
227211f9a21aSLiam R. Howlett  * @mm: The mm_struct
227311f9a21aSLiam R. Howlett  * @start: The aligned start address to munmap.
227411f9a21aSLiam R. Howlett  * @end: The aligned end address to munmap.
227511f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
22768651a137SLorenzo Stoakes  * @downgrade: Set to true to attempt a write downgrade of the mmap_lock
227711f9a21aSLiam R. Howlett  *
227811f9a21aSLiam R. Howlett  * If @downgrade is true, check return code for potential release of the lock.
227911f9a21aSLiam R. Howlett  */
228011f9a21aSLiam R. Howlett static int
2281183654ceSLiam R. Howlett do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
228211f9a21aSLiam R. Howlett 		    struct mm_struct *mm, unsigned long start,
228311f9a21aSLiam R. Howlett 		    unsigned long end, struct list_head *uf, bool downgrade)
228411f9a21aSLiam R. Howlett {
2285763ecb03SLiam R. Howlett 	struct vm_area_struct *prev, *next = NULL;
2286763ecb03SLiam R. Howlett 	struct maple_tree mt_detach;
2287763ecb03SLiam R. Howlett 	int count = 0;
2288d4af56c5SLiam R. Howlett 	int error = -ENOMEM;
2289763ecb03SLiam R. Howlett 	MA_STATE(mas_detach, &mt_detach, 0, 0);
2290763ecb03SLiam R. Howlett 	mt_init_flags(&mt_detach, MT_FLAGS_LOCK_EXTERN);
2291763ecb03SLiam R. Howlett 	mt_set_external_lock(&mt_detach, &mm->mmap_lock);
2292524e00b3SLiam R. Howlett 
22931da177e4SLinus Torvalds 	/*
22941da177e4SLinus Torvalds 	 * If we need to split any vma, do it now to save pain later.
22951da177e4SLinus Torvalds 	 *
22961da177e4SLinus Torvalds 	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
22971da177e4SLinus Torvalds 	 * unmapped vm_area_struct will remain in use: so lower split_vma
22981da177e4SLinus Torvalds 	 * places tmp vma above, and higher split_vma places tmp vma below.
22991da177e4SLinus Torvalds 	 */
2300763ecb03SLiam R. Howlett 
2301763ecb03SLiam R. Howlett 	/* Does it split the first one? */
2302146425a3SHugh Dickins 	if (start > vma->vm_start) {
2303659ace58SKOSAKI Motohiro 
2304659ace58SKOSAKI Motohiro 		/*
2305659ace58SKOSAKI Motohiro 		 * Make sure that map_count on return from munmap() will
2306659ace58SKOSAKI Motohiro 		 * not exceed its limit; but let map_count go just above
2307659ace58SKOSAKI Motohiro 		 * its limit temporarily, to help free resources as expected.
2308659ace58SKOSAKI Motohiro 		 */
2309659ace58SKOSAKI Motohiro 		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2310d4af56c5SLiam R. Howlett 			goto map_count_exceeded;
2311659ace58SKOSAKI Motohiro 
23129760ebffSLiam R. Howlett 		error = __split_vma(vmi, vma, start, 0);
23131da177e4SLinus Torvalds 		if (error)
2314763ecb03SLiam R. Howlett 			goto start_split_failed;
231511f9a21aSLiam R. Howlett 
23160fd5a9e2SLiam R. Howlett 		vma = vma_iter_load(vmi);
23171da177e4SLinus Torvalds 	}
23181da177e4SLinus Torvalds 
2319183654ceSLiam R. Howlett 	prev = vma_prev(vmi);
2320763ecb03SLiam R. Howlett 	if (unlikely((!prev)))
2321183654ceSLiam R. Howlett 		vma_iter_set(vmi, start);
232211f9a21aSLiam R. Howlett 
2323763ecb03SLiam R. Howlett 	/*
2324763ecb03SLiam R. Howlett 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
2325763ecb03SLiam R. Howlett 	 * it is always overwritten.
2326763ecb03SLiam R. Howlett 	 */
2327183654ceSLiam R. Howlett 	for_each_vma_range(*vmi, next, end) {
2328763ecb03SLiam R. Howlett 		/* Does it split the end? */
2329763ecb03SLiam R. Howlett 		if (next->vm_end > end) {
23306b73cff2SLiam R. Howlett 			error = __split_vma(vmi, next, end, 0);
23311da177e4SLinus Torvalds 			if (error)
2332763ecb03SLiam R. Howlett 				goto end_split_failed;
233311f9a21aSLiam R. Howlett 		}
2334763ecb03SLiam R. Howlett 		error = munmap_sidetree(next, &mas_detach);
2335763ecb03SLiam R. Howlett 		if (error)
2336763ecb03SLiam R. Howlett 			goto munmap_sidetree_failed;
2337763ecb03SLiam R. Howlett 
2338763ecb03SLiam R. Howlett 		count++;
2339763ecb03SLiam R. Howlett #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
2340763ecb03SLiam R. Howlett 		BUG_ON(next->vm_start < start);
2341763ecb03SLiam R. Howlett 		BUG_ON(next->vm_start > end);
2342763ecb03SLiam R. Howlett #endif
2343763ecb03SLiam R. Howlett 	}
2344763ecb03SLiam R. Howlett 
2345183654ceSLiam R. Howlett 	next = vma_next(vmi);
23462376dd7cSAndrea Arcangeli 	if (unlikely(uf)) {
23472376dd7cSAndrea Arcangeli 		/*
23482376dd7cSAndrea Arcangeli 		 * If userfaultfd_unmap_prep returns an error the vmas
2349f0953a1bSIngo Molnar 		 * will remain split, but userland will get a
23502376dd7cSAndrea Arcangeli 		 * highly unexpected error anyway. This is no
23512376dd7cSAndrea Arcangeli 		 * different than the case where the first of the two
23522376dd7cSAndrea Arcangeli 		 * __split_vma fails, but we don't undo the first
23532376dd7cSAndrea Arcangeli 		 * split, despite we could. This is unlikely enough
23542376dd7cSAndrea Arcangeli 		 * failure that it's not worth optimizing it for.
23552376dd7cSAndrea Arcangeli 		 */
235669dbe6daSLiam R. Howlett 		error = userfaultfd_unmap_prep(mm, start, end, uf);
235711f9a21aSLiam R. Howlett 
23582376dd7cSAndrea Arcangeli 		if (error)
2359d4af56c5SLiam R. Howlett 			goto userfaultfd_error;
23602376dd7cSAndrea Arcangeli 	}
23612376dd7cSAndrea Arcangeli 
2362763ecb03SLiam R. Howlett #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2363763ecb03SLiam R. Howlett 	/* Make sure no VMAs are about to be lost. */
2364763ecb03SLiam R. Howlett 	{
2365763ecb03SLiam R. Howlett 		MA_STATE(test, &mt_detach, start, end - 1);
2366763ecb03SLiam R. Howlett 		struct vm_area_struct *vma_mas, *vma_test;
2367763ecb03SLiam R. Howlett 		int test_count = 0;
2368763ecb03SLiam R. Howlett 
2369183654ceSLiam R. Howlett 		vma_iter_set(vmi, start);
2370763ecb03SLiam R. Howlett 		rcu_read_lock();
2371763ecb03SLiam R. Howlett 		vma_test = mas_find(&test, end - 1);
2372183654ceSLiam R. Howlett 		for_each_vma_range(*vmi, vma_mas, end) {
2373763ecb03SLiam R. Howlett 			BUG_ON(vma_mas != vma_test);
2374763ecb03SLiam R. Howlett 			test_count++;
2375763ecb03SLiam R. Howlett 			vma_test = mas_next(&test, end - 1);
2376763ecb03SLiam R. Howlett 		}
2377763ecb03SLiam R. Howlett 		rcu_read_unlock();
2378763ecb03SLiam R. Howlett 		BUG_ON(count != test_count);
2379763ecb03SLiam R. Howlett 	}
2380763ecb03SLiam R. Howlett #endif
23810378c0a0SLiam R. Howlett 	/* Point of no return */
2382183654ceSLiam R. Howlett 	vma_iter_set(vmi, start);
2383183654ceSLiam R. Howlett 	if (vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL))
23840378c0a0SLiam R. Howlett 		return -ENOMEM;
23850378c0a0SLiam R. Howlett 
2386763ecb03SLiam R. Howlett 	mm->map_count -= count;
238711f9a21aSLiam R. Howlett 	/*
238811f9a21aSLiam R. Howlett 	 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
238911f9a21aSLiam R. Howlett 	 * VM_GROWSUP VMA. Such VMAs can change their size under
239011f9a21aSLiam R. Howlett 	 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
239111f9a21aSLiam R. Howlett 	 */
239211f9a21aSLiam R. Howlett 	if (downgrade) {
2393763ecb03SLiam R. Howlett 		if (next && (next->vm_flags & VM_GROWSDOWN))
239411f9a21aSLiam R. Howlett 			downgrade = false;
239511f9a21aSLiam R. Howlett 		else if (prev && (prev->vm_flags & VM_GROWSUP))
239611f9a21aSLiam R. Howlett 			downgrade = false;
239711f9a21aSLiam R. Howlett 		else
2398d8ed45c5SMichel Lespinasse 			mmap_write_downgrade(mm);
239911f9a21aSLiam R. Howlett 	}
2400dd2283f2SYang Shi 
240168f48381SSuren Baghdasaryan 	/*
240268f48381SSuren Baghdasaryan 	 * We can free page tables without write-locking mmap_lock because VMAs
240368f48381SSuren Baghdasaryan 	 * were isolated before we downgraded mmap_lock.
240468f48381SSuren Baghdasaryan 	 */
240568f48381SSuren Baghdasaryan 	unmap_region(mm, &mt_detach, vma, prev, next, start, end, !downgrade);
2406763ecb03SLiam R. Howlett 	/* Statistics and freeing VMAs */
2407763ecb03SLiam R. Howlett 	mas_set(&mas_detach, start);
2408763ecb03SLiam R. Howlett 	remove_mt(mm, &mas_detach);
2409763ecb03SLiam R. Howlett 	__mt_destroy(&mt_detach);
24101da177e4SLinus Torvalds 
2411524e00b3SLiam R. Howlett 
2412524e00b3SLiam R. Howlett 	validate_mm(mm);
2413dd2283f2SYang Shi 	return downgrade ? 1 : 0;
2414d4af56c5SLiam R. Howlett 
2415d4af56c5SLiam R. Howlett userfaultfd_error:
2416763ecb03SLiam R. Howlett munmap_sidetree_failed:
2417763ecb03SLiam R. Howlett end_split_failed:
2418763ecb03SLiam R. Howlett 	__mt_destroy(&mt_detach);
2419763ecb03SLiam R. Howlett start_split_failed:
2420763ecb03SLiam R. Howlett map_count_exceeded:
2421d4af56c5SLiam R. Howlett 	return error;
24221da177e4SLinus Torvalds }
24231da177e4SLinus Torvalds 
242411f9a21aSLiam R. Howlett /*
2425183654ceSLiam R. Howlett  * do_vmi_munmap() - munmap a given range.
2426183654ceSLiam R. Howlett  * @vmi: The vma iterator
242711f9a21aSLiam R. Howlett  * @mm: The mm_struct
242811f9a21aSLiam R. Howlett  * @start: The start address to munmap
242911f9a21aSLiam R. Howlett  * @len: The length of the range to munmap
243011f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
243111f9a21aSLiam R. Howlett  * @downgrade: set to true if the user wants to attempt to write_downgrade the
24328651a137SLorenzo Stoakes  * mmap_lock
243311f9a21aSLiam R. Howlett  *
243411f9a21aSLiam R. Howlett  * This function takes a @mas that is either pointing to the previous VMA or set
243511f9a21aSLiam R. Howlett  * to MA_START and sets it up to remove the mapping(s).  The @len will be
243611f9a21aSLiam R. Howlett  * aligned and any arch_unmap work will be preformed.
243711f9a21aSLiam R. Howlett  *
243811f9a21aSLiam R. Howlett  * Returns: -EINVAL on failure, 1 on success and unlock, 0 otherwise.
243911f9a21aSLiam R. Howlett  */
2440183654ceSLiam R. Howlett int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
244111f9a21aSLiam R. Howlett 		  unsigned long start, size_t len, struct list_head *uf,
244211f9a21aSLiam R. Howlett 		  bool downgrade)
244311f9a21aSLiam R. Howlett {
244411f9a21aSLiam R. Howlett 	unsigned long end;
244511f9a21aSLiam R. Howlett 	struct vm_area_struct *vma;
244611f9a21aSLiam R. Howlett 
244711f9a21aSLiam R. Howlett 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
244811f9a21aSLiam R. Howlett 		return -EINVAL;
244911f9a21aSLiam R. Howlett 
245011f9a21aSLiam R. Howlett 	end = start + PAGE_ALIGN(len);
245111f9a21aSLiam R. Howlett 	if (end == start)
245211f9a21aSLiam R. Howlett 		return -EINVAL;
245311f9a21aSLiam R. Howlett 
245411f9a21aSLiam R. Howlett 	 /* arch_unmap() might do unmaps itself.  */
245511f9a21aSLiam R. Howlett 	arch_unmap(mm, start, end);
245611f9a21aSLiam R. Howlett 
245711f9a21aSLiam R. Howlett 	/* Find the first overlapping VMA */
2458183654ceSLiam R. Howlett 	vma = vma_find(vmi, end);
245911f9a21aSLiam R. Howlett 	if (!vma)
246011f9a21aSLiam R. Howlett 		return 0;
246111f9a21aSLiam R. Howlett 
2462183654ceSLiam R. Howlett 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
246311f9a21aSLiam R. Howlett }
246411f9a21aSLiam R. Howlett 
246511f9a21aSLiam R. Howlett /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
246611f9a21aSLiam R. Howlett  * @mm: The mm_struct
246711f9a21aSLiam R. Howlett  * @start: The start address to munmap
246811f9a21aSLiam R. Howlett  * @len: The length to be munmapped.
246911f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
247011f9a21aSLiam R. Howlett  */
2471dd2283f2SYang Shi int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2472dd2283f2SYang Shi 	      struct list_head *uf)
2473dd2283f2SYang Shi {
2474183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, start);
247511f9a21aSLiam R. Howlett 
2476183654ceSLiam R. Howlett 	return do_vmi_munmap(&vmi, mm, start, len, uf, false);
2477dd2283f2SYang Shi }
2478dd2283f2SYang Shi 
2479e99668a5SLiam R. Howlett unsigned long mmap_region(struct file *file, unsigned long addr,
2480e99668a5SLiam R. Howlett 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2481e99668a5SLiam R. Howlett 		struct list_head *uf)
2482e99668a5SLiam R. Howlett {
2483e99668a5SLiam R. Howlett 	struct mm_struct *mm = current->mm;
2484e99668a5SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
2485e99668a5SLiam R. Howlett 	struct vm_area_struct *next, *prev, *merge;
2486e99668a5SLiam R. Howlett 	pgoff_t pglen = len >> PAGE_SHIFT;
2487e99668a5SLiam R. Howlett 	unsigned long charged = 0;
2488e99668a5SLiam R. Howlett 	unsigned long end = addr + len;
2489e99668a5SLiam R. Howlett 	unsigned long merge_start = addr, merge_end = end;
2490e99668a5SLiam R. Howlett 	pgoff_t vm_pgoff;
2491e99668a5SLiam R. Howlett 	int error;
2492183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
2493e99668a5SLiam R. Howlett 
2494e99668a5SLiam R. Howlett 	/* Check against address space limit. */
2495e99668a5SLiam R. Howlett 	if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2496e99668a5SLiam R. Howlett 		unsigned long nr_pages;
2497e99668a5SLiam R. Howlett 
2498e99668a5SLiam R. Howlett 		/*
2499e99668a5SLiam R. Howlett 		 * MAP_FIXED may remove pages of mappings that intersects with
2500e99668a5SLiam R. Howlett 		 * requested mapping. Account for the pages it would unmap.
2501e99668a5SLiam R. Howlett 		 */
2502e99668a5SLiam R. Howlett 		nr_pages = count_vma_pages_range(mm, addr, end);
2503e99668a5SLiam R. Howlett 
2504e99668a5SLiam R. Howlett 		if (!may_expand_vm(mm, vm_flags,
2505e99668a5SLiam R. Howlett 					(len >> PAGE_SHIFT) - nr_pages))
2506e99668a5SLiam R. Howlett 			return -ENOMEM;
2507e99668a5SLiam R. Howlett 	}
2508e99668a5SLiam R. Howlett 
2509e99668a5SLiam R. Howlett 	/* Unmap any existing mapping in the area */
2510183654ceSLiam R. Howlett 	if (do_vmi_munmap(&vmi, mm, addr, len, uf, false))
2511e99668a5SLiam R. Howlett 		return -ENOMEM;
2512e99668a5SLiam R. Howlett 
2513e99668a5SLiam R. Howlett 	/*
2514e99668a5SLiam R. Howlett 	 * Private writable mapping: check memory availability
2515e99668a5SLiam R. Howlett 	 */
2516e99668a5SLiam R. Howlett 	if (accountable_mapping(file, vm_flags)) {
2517e99668a5SLiam R. Howlett 		charged = len >> PAGE_SHIFT;
2518e99668a5SLiam R. Howlett 		if (security_vm_enough_memory_mm(mm, charged))
2519e99668a5SLiam R. Howlett 			return -ENOMEM;
2520e99668a5SLiam R. Howlett 		vm_flags |= VM_ACCOUNT;
2521e99668a5SLiam R. Howlett 	}
2522e99668a5SLiam R. Howlett 
2523183654ceSLiam R. Howlett 	next = vma_next(&vmi);
2524183654ceSLiam R. Howlett 	prev = vma_prev(&vmi);
2525e99668a5SLiam R. Howlett 	if (vm_flags & VM_SPECIAL)
2526e99668a5SLiam R. Howlett 		goto cannot_expand;
2527e99668a5SLiam R. Howlett 
2528e99668a5SLiam R. Howlett 	/* Attempt to expand an old mapping */
2529e99668a5SLiam R. Howlett 	/* Check next */
2530e99668a5SLiam R. Howlett 	if (next && next->vm_start == end && !vma_policy(next) &&
2531e99668a5SLiam R. Howlett 	    can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2532e99668a5SLiam R. Howlett 				 NULL_VM_UFFD_CTX, NULL)) {
2533e99668a5SLiam R. Howlett 		merge_end = next->vm_end;
2534e99668a5SLiam R. Howlett 		vma = next;
2535e99668a5SLiam R. Howlett 		vm_pgoff = next->vm_pgoff - pglen;
2536e99668a5SLiam R. Howlett 	}
2537e99668a5SLiam R. Howlett 
2538e99668a5SLiam R. Howlett 	/* Check prev */
2539e99668a5SLiam R. Howlett 	if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2540e99668a5SLiam R. Howlett 	    (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2541e99668a5SLiam R. Howlett 				       pgoff, vma->vm_userfaultfd_ctx, NULL) :
2542e99668a5SLiam R. Howlett 		   can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2543e99668a5SLiam R. Howlett 				       NULL_VM_UFFD_CTX, NULL))) {
2544e99668a5SLiam R. Howlett 		merge_start = prev->vm_start;
2545e99668a5SLiam R. Howlett 		vma = prev;
2546e99668a5SLiam R. Howlett 		vm_pgoff = prev->vm_pgoff;
2547e99668a5SLiam R. Howlett 	}
2548e99668a5SLiam R. Howlett 
2549e99668a5SLiam R. Howlett 
2550e99668a5SLiam R. Howlett 	/* Actually expand, if possible */
2551e99668a5SLiam R. Howlett 	if (vma &&
25523c441ab7SLiam R. Howlett 	    !vma_expand(&vmi, vma, merge_start, merge_end, vm_pgoff, next)) {
2553e99668a5SLiam R. Howlett 		khugepaged_enter_vma(vma, vm_flags);
2554e99668a5SLiam R. Howlett 		goto expanded;
2555e99668a5SLiam R. Howlett 	}
2556e99668a5SLiam R. Howlett 
2557e99668a5SLiam R. Howlett cannot_expand:
2558e99668a5SLiam R. Howlett 	/*
2559e99668a5SLiam R. Howlett 	 * Determine the object being mapped and call the appropriate
2560e99668a5SLiam R. Howlett 	 * specific mapper. the address has already been validated, but
2561e99668a5SLiam R. Howlett 	 * not unmapped, but the maps are removed from the list.
2562e99668a5SLiam R. Howlett 	 */
2563e99668a5SLiam R. Howlett 	vma = vm_area_alloc(mm);
2564e99668a5SLiam R. Howlett 	if (!vma) {
2565e99668a5SLiam R. Howlett 		error = -ENOMEM;
2566e99668a5SLiam R. Howlett 		goto unacct_error;
2567e99668a5SLiam R. Howlett 	}
2568e99668a5SLiam R. Howlett 
25690fd5a9e2SLiam R. Howlett 	vma_iter_set(&vmi, addr);
2570e99668a5SLiam R. Howlett 	vma->vm_start = addr;
2571e99668a5SLiam R. Howlett 	vma->vm_end = end;
25721c71222eSSuren Baghdasaryan 	vm_flags_init(vma, vm_flags);
2573e99668a5SLiam R. Howlett 	vma->vm_page_prot = vm_get_page_prot(vm_flags);
2574e99668a5SLiam R. Howlett 	vma->vm_pgoff = pgoff;
2575e99668a5SLiam R. Howlett 
2576e99668a5SLiam R. Howlett 	if (file) {
2577e99668a5SLiam R. Howlett 		if (vm_flags & VM_SHARED) {
2578e99668a5SLiam R. Howlett 			error = mapping_map_writable(file->f_mapping);
2579e99668a5SLiam R. Howlett 			if (error)
2580e99668a5SLiam R. Howlett 				goto free_vma;
2581e99668a5SLiam R. Howlett 		}
2582e99668a5SLiam R. Howlett 
2583e99668a5SLiam R. Howlett 		vma->vm_file = get_file(file);
2584e99668a5SLiam R. Howlett 		error = call_mmap(file, vma);
2585e99668a5SLiam R. Howlett 		if (error)
2586e99668a5SLiam R. Howlett 			goto unmap_and_free_vma;
2587e99668a5SLiam R. Howlett 
2588a57b7051SLiam Howlett 		/*
2589a57b7051SLiam Howlett 		 * Expansion is handled above, merging is handled below.
2590a57b7051SLiam Howlett 		 * Drivers should not alter the address of the VMA.
2591e99668a5SLiam R. Howlett 		 */
2592a57b7051SLiam Howlett 		error = -EINVAL;
2593cc8d1b09SLiam R. Howlett 		if (WARN_ON((addr != vma->vm_start)))
2594a57b7051SLiam Howlett 			goto close_and_free_vma;
2595e99668a5SLiam R. Howlett 
2596cc8d1b09SLiam R. Howlett 		vma_iter_set(&vmi, addr);
2597e99668a5SLiam R. Howlett 		/*
2598e99668a5SLiam R. Howlett 		 * If vm_flags changed after call_mmap(), we should try merge
2599e99668a5SLiam R. Howlett 		 * vma again as we may succeed this time.
2600e99668a5SLiam R. Howlett 		 */
2601e99668a5SLiam R. Howlett 		if (unlikely(vm_flags != vma->vm_flags && prev)) {
26029760ebffSLiam R. Howlett 			merge = vma_merge(&vmi, mm, prev, vma->vm_start,
26039760ebffSLiam R. Howlett 				    vma->vm_end, vma->vm_flags, NULL,
26049760ebffSLiam R. Howlett 				    vma->vm_file, vma->vm_pgoff, NULL,
26059760ebffSLiam R. Howlett 				    NULL_VM_UFFD_CTX, NULL);
2606e99668a5SLiam R. Howlett 			if (merge) {
2607e99668a5SLiam R. Howlett 				/*
2608e99668a5SLiam R. Howlett 				 * ->mmap() can change vma->vm_file and fput
2609e99668a5SLiam R. Howlett 				 * the original file. So fput the vma->vm_file
2610e99668a5SLiam R. Howlett 				 * here or we would add an extra fput for file
2611e99668a5SLiam R. Howlett 				 * and cause general protection fault
2612e99668a5SLiam R. Howlett 				 * ultimately.
2613e99668a5SLiam R. Howlett 				 */
2614e99668a5SLiam R. Howlett 				fput(vma->vm_file);
2615e99668a5SLiam R. Howlett 				vm_area_free(vma);
2616e99668a5SLiam R. Howlett 				vma = merge;
2617e99668a5SLiam R. Howlett 				/* Update vm_flags to pick up the change. */
2618e99668a5SLiam R. Howlett 				vm_flags = vma->vm_flags;
2619e99668a5SLiam R. Howlett 				goto unmap_writable;
2620e99668a5SLiam R. Howlett 			}
2621e99668a5SLiam R. Howlett 		}
2622e99668a5SLiam R. Howlett 
2623e99668a5SLiam R. Howlett 		vm_flags = vma->vm_flags;
2624e99668a5SLiam R. Howlett 	} else if (vm_flags & VM_SHARED) {
2625e99668a5SLiam R. Howlett 		error = shmem_zero_setup(vma);
2626e99668a5SLiam R. Howlett 		if (error)
2627e99668a5SLiam R. Howlett 			goto free_vma;
2628e99668a5SLiam R. Howlett 	} else {
2629e99668a5SLiam R. Howlett 		vma_set_anonymous(vma);
2630e99668a5SLiam R. Howlett 	}
2631e99668a5SLiam R. Howlett 
2632b507808eSJoey Gouly 	if (map_deny_write_exec(vma, vma->vm_flags)) {
2633b507808eSJoey Gouly 		error = -EACCES;
2634b507808eSJoey Gouly 		goto close_and_free_vma;
2635b507808eSJoey Gouly 	}
2636b507808eSJoey Gouly 
2637e99668a5SLiam R. Howlett 	/* Allow architectures to sanity-check the vm_flags */
2638e99668a5SLiam R. Howlett 	error = -EINVAL;
2639cc8d1b09SLiam R. Howlett 	if (!arch_validate_flags(vma->vm_flags))
2640deb0f656SCarlos Llamas 		goto close_and_free_vma;
2641e99668a5SLiam R. Howlett 
2642e99668a5SLiam R. Howlett 	error = -ENOMEM;
2643cc8d1b09SLiam R. Howlett 	if (vma_iter_prealloc(&vmi))
26445789151eSMike Kravetz 		goto close_and_free_vma;
2645e99668a5SLiam R. Howlett 
2646e99668a5SLiam R. Howlett 	if (vma->vm_file)
2647e99668a5SLiam R. Howlett 		i_mmap_lock_write(vma->vm_file->f_mapping);
2648e99668a5SLiam R. Howlett 
2649183654ceSLiam R. Howlett 	vma_iter_store(&vmi, vma);
2650e99668a5SLiam R. Howlett 	mm->map_count++;
2651e99668a5SLiam R. Howlett 	if (vma->vm_file) {
2652e99668a5SLiam R. Howlett 		if (vma->vm_flags & VM_SHARED)
2653e99668a5SLiam R. Howlett 			mapping_allow_writable(vma->vm_file->f_mapping);
2654e99668a5SLiam R. Howlett 
2655e99668a5SLiam R. Howlett 		flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2656e99668a5SLiam R. Howlett 		vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2657e99668a5SLiam R. Howlett 		flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2658e99668a5SLiam R. Howlett 		i_mmap_unlock_write(vma->vm_file->f_mapping);
2659e99668a5SLiam R. Howlett 	}
2660e99668a5SLiam R. Howlett 
2661e99668a5SLiam R. Howlett 	/*
2662e99668a5SLiam R. Howlett 	 * vma_merge() calls khugepaged_enter_vma() either, the below
2663e99668a5SLiam R. Howlett 	 * call covers the non-merge case.
2664e99668a5SLiam R. Howlett 	 */
2665e99668a5SLiam R. Howlett 	khugepaged_enter_vma(vma, vma->vm_flags);
2666e99668a5SLiam R. Howlett 
2667e99668a5SLiam R. Howlett 	/* Once vma denies write, undo our temporary denial count */
2668e99668a5SLiam R. Howlett unmap_writable:
2669e99668a5SLiam R. Howlett 	if (file && vm_flags & VM_SHARED)
2670e99668a5SLiam R. Howlett 		mapping_unmap_writable(file->f_mapping);
2671e99668a5SLiam R. Howlett 	file = vma->vm_file;
2672e99668a5SLiam R. Howlett expanded:
2673e99668a5SLiam R. Howlett 	perf_event_mmap(vma);
2674e99668a5SLiam R. Howlett 
2675e99668a5SLiam R. Howlett 	vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2676e99668a5SLiam R. Howlett 	if (vm_flags & VM_LOCKED) {
2677e99668a5SLiam R. Howlett 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2678e99668a5SLiam R. Howlett 					is_vm_hugetlb_page(vma) ||
2679e99668a5SLiam R. Howlett 					vma == get_gate_vma(current->mm))
2680e430a95aSSuren Baghdasaryan 			vm_flags_clear(vma, VM_LOCKED_MASK);
2681e99668a5SLiam R. Howlett 		else
2682e99668a5SLiam R. Howlett 			mm->locked_vm += (len >> PAGE_SHIFT);
2683e99668a5SLiam R. Howlett 	}
2684e99668a5SLiam R. Howlett 
2685e99668a5SLiam R. Howlett 	if (file)
2686e99668a5SLiam R. Howlett 		uprobe_mmap(vma);
2687e99668a5SLiam R. Howlett 
2688e99668a5SLiam R. Howlett 	/*
2689e99668a5SLiam R. Howlett 	 * New (or expanded) vma always get soft dirty status.
2690e99668a5SLiam R. Howlett 	 * Otherwise user-space soft-dirty page tracker won't
2691e99668a5SLiam R. Howlett 	 * be able to distinguish situation when vma area unmapped,
2692e99668a5SLiam R. Howlett 	 * then new mapped in-place (which must be aimed as
2693e99668a5SLiam R. Howlett 	 * a completely new data area).
2694e99668a5SLiam R. Howlett 	 */
26951c71222eSSuren Baghdasaryan 	vm_flags_set(vma, VM_SOFTDIRTY);
2696e99668a5SLiam R. Howlett 
2697e99668a5SLiam R. Howlett 	vma_set_page_prot(vma);
2698e99668a5SLiam R. Howlett 
2699e99668a5SLiam R. Howlett 	validate_mm(mm);
2700e99668a5SLiam R. Howlett 	return addr;
2701e99668a5SLiam R. Howlett 
2702deb0f656SCarlos Llamas close_and_free_vma:
2703cc8d1b09SLiam R. Howlett 	if (file && vma->vm_ops && vma->vm_ops->close)
2704deb0f656SCarlos Llamas 		vma->vm_ops->close(vma);
2705cc8d1b09SLiam R. Howlett 
2706cc8d1b09SLiam R. Howlett 	if (file || vma->vm_file) {
2707e99668a5SLiam R. Howlett unmap_and_free_vma:
2708e99668a5SLiam R. Howlett 		fput(vma->vm_file);
2709e99668a5SLiam R. Howlett 		vma->vm_file = NULL;
2710e99668a5SLiam R. Howlett 
2711e99668a5SLiam R. Howlett 		/* Undo any partial mapping done by a device driver. */
2712cc8d1b09SLiam R. Howlett 		unmap_region(mm, &mm->mm_mt, vma, prev, next, vma->vm_start,
271368f48381SSuren Baghdasaryan 			     vma->vm_end, true);
2714cc8d1b09SLiam R. Howlett 	}
2715cc674ab3SLi Zetao 	if (file && (vm_flags & VM_SHARED))
2716e99668a5SLiam R. Howlett 		mapping_unmap_writable(file->f_mapping);
2717e99668a5SLiam R. Howlett free_vma:
2718e99668a5SLiam R. Howlett 	vm_area_free(vma);
2719e99668a5SLiam R. Howlett unacct_error:
2720e99668a5SLiam R. Howlett 	if (charged)
2721e99668a5SLiam R. Howlett 		vm_unacct_memory(charged);
2722e99668a5SLiam R. Howlett 	validate_mm(mm);
2723e99668a5SLiam R. Howlett 	return error;
2724e99668a5SLiam R. Howlett }
2725e99668a5SLiam R. Howlett 
2726dd2283f2SYang Shi static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2727a46ef99dSLinus Torvalds {
2728a46ef99dSLinus Torvalds 	int ret;
2729bfce281cSAl Viro 	struct mm_struct *mm = current->mm;
2730897ab3e0SMike Rapoport 	LIST_HEAD(uf);
2731183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, start);
2732a46ef99dSLinus Torvalds 
2733d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2734ae798783SMichal Hocko 		return -EINTR;
2735ae798783SMichal Hocko 
2736183654ceSLiam R. Howlett 	ret = do_vmi_munmap(&vmi, mm, start, len, &uf, downgrade);
2737dd2283f2SYang Shi 	/*
2738c1e8d7c6SMichel Lespinasse 	 * Returning 1 indicates mmap_lock is downgraded.
2739dd2283f2SYang Shi 	 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2740dd2283f2SYang Shi 	 * it to 0 before return.
2741dd2283f2SYang Shi 	 */
2742dd2283f2SYang Shi 	if (ret == 1) {
2743d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
2744dd2283f2SYang Shi 		ret = 0;
2745dd2283f2SYang Shi 	} else
2746d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
2747dd2283f2SYang Shi 
2748897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
2749a46ef99dSLinus Torvalds 	return ret;
2750a46ef99dSLinus Torvalds }
2751dd2283f2SYang Shi 
2752dd2283f2SYang Shi int vm_munmap(unsigned long start, size_t len)
2753dd2283f2SYang Shi {
2754dd2283f2SYang Shi 	return __vm_munmap(start, len, false);
2755dd2283f2SYang Shi }
2756a46ef99dSLinus Torvalds EXPORT_SYMBOL(vm_munmap);
2757a46ef99dSLinus Torvalds 
27586a6160a7SHeiko Carstens SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
27591da177e4SLinus Torvalds {
2760ce18d171SCatalin Marinas 	addr = untagged_addr(addr);
2761dd2283f2SYang Shi 	return __vm_munmap(addr, len, true);
27621da177e4SLinus Torvalds }
27631da177e4SLinus Torvalds 
2764c8d78c18SKirill A. Shutemov 
2765c8d78c18SKirill A. Shutemov /*
2766c8d78c18SKirill A. Shutemov  * Emulation of deprecated remap_file_pages() syscall.
2767c8d78c18SKirill A. Shutemov  */
2768c8d78c18SKirill A. Shutemov SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2769c8d78c18SKirill A. Shutemov 		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2770c8d78c18SKirill A. Shutemov {
2771c8d78c18SKirill A. Shutemov 
2772c8d78c18SKirill A. Shutemov 	struct mm_struct *mm = current->mm;
2773c8d78c18SKirill A. Shutemov 	struct vm_area_struct *vma;
2774c8d78c18SKirill A. Shutemov 	unsigned long populate = 0;
2775c8d78c18SKirill A. Shutemov 	unsigned long ret = -EINVAL;
2776c8d78c18SKirill A. Shutemov 	struct file *file;
2777c8d78c18SKirill A. Shutemov 
2778ee65728eSMike Rapoport 	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2779c8d78c18SKirill A. Shutemov 		     current->comm, current->pid);
2780c8d78c18SKirill A. Shutemov 
2781c8d78c18SKirill A. Shutemov 	if (prot)
2782c8d78c18SKirill A. Shutemov 		return ret;
2783c8d78c18SKirill A. Shutemov 	start = start & PAGE_MASK;
2784c8d78c18SKirill A. Shutemov 	size = size & PAGE_MASK;
2785c8d78c18SKirill A. Shutemov 
2786c8d78c18SKirill A. Shutemov 	if (start + size <= start)
2787c8d78c18SKirill A. Shutemov 		return ret;
2788c8d78c18SKirill A. Shutemov 
2789c8d78c18SKirill A. Shutemov 	/* Does pgoff wrap? */
2790c8d78c18SKirill A. Shutemov 	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2791c8d78c18SKirill A. Shutemov 		return ret;
2792c8d78c18SKirill A. Shutemov 
2793d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2794dc0ef0dfSMichal Hocko 		return -EINTR;
2795dc0ef0dfSMichal Hocko 
27969b593cb2SLiam R. Howlett 	vma = vma_lookup(mm, start);
2797c8d78c18SKirill A. Shutemov 
2798c8d78c18SKirill A. Shutemov 	if (!vma || !(vma->vm_flags & VM_SHARED))
2799c8d78c18SKirill A. Shutemov 		goto out;
2800c8d78c18SKirill A. Shutemov 
280148f7df32SKirill A. Shutemov 	if (start + size > vma->vm_end) {
2802763ecb03SLiam R. Howlett 		VMA_ITERATOR(vmi, mm, vma->vm_end);
2803763ecb03SLiam R. Howlett 		struct vm_area_struct *next, *prev = vma;
280448f7df32SKirill A. Shutemov 
2805763ecb03SLiam R. Howlett 		for_each_vma_range(vmi, next, start + size) {
280648f7df32SKirill A. Shutemov 			/* hole between vmas ? */
2807763ecb03SLiam R. Howlett 			if (next->vm_start != prev->vm_end)
280848f7df32SKirill A. Shutemov 				goto out;
280948f7df32SKirill A. Shutemov 
281048f7df32SKirill A. Shutemov 			if (next->vm_file != vma->vm_file)
281148f7df32SKirill A. Shutemov 				goto out;
281248f7df32SKirill A. Shutemov 
281348f7df32SKirill A. Shutemov 			if (next->vm_flags != vma->vm_flags)
281448f7df32SKirill A. Shutemov 				goto out;
281548f7df32SKirill A. Shutemov 
28161db43d3fSLiam Howlett 			if (start + size <= next->vm_end)
28171db43d3fSLiam Howlett 				break;
28181db43d3fSLiam Howlett 
2819763ecb03SLiam R. Howlett 			prev = next;
282048f7df32SKirill A. Shutemov 		}
282148f7df32SKirill A. Shutemov 
282248f7df32SKirill A. Shutemov 		if (!next)
2823c8d78c18SKirill A. Shutemov 			goto out;
2824c8d78c18SKirill A. Shutemov 	}
2825c8d78c18SKirill A. Shutemov 
2826c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2827c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2828c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2829c8d78c18SKirill A. Shutemov 
2830c8d78c18SKirill A. Shutemov 	flags &= MAP_NONBLOCK;
2831c8d78c18SKirill A. Shutemov 	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2832fce000b1SLiam Howlett 	if (vma->vm_flags & VM_LOCKED)
2833c8d78c18SKirill A. Shutemov 		flags |= MAP_LOCKED;
283448f7df32SKirill A. Shutemov 
2835c8d78c18SKirill A. Shutemov 	file = get_file(vma->vm_file);
283645e55300SPeter Collingbourne 	ret = do_mmap(vma->vm_file, start, size,
2837897ab3e0SMike Rapoport 			prot, flags, pgoff, &populate, NULL);
2838c8d78c18SKirill A. Shutemov 	fput(file);
2839c8d78c18SKirill A. Shutemov out:
2840d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
2841c8d78c18SKirill A. Shutemov 	if (populate)
2842c8d78c18SKirill A. Shutemov 		mm_populate(ret, populate);
2843c8d78c18SKirill A. Shutemov 	if (!IS_ERR_VALUE(ret))
2844c8d78c18SKirill A. Shutemov 		ret = 0;
2845c8d78c18SKirill A. Shutemov 	return ret;
2846c8d78c18SKirill A. Shutemov }
2847c8d78c18SKirill A. Shutemov 
28481da177e4SLinus Torvalds /*
284927b26701SLiam R. Howlett  * do_vma_munmap() - Unmap a full or partial vma.
285027b26701SLiam R. Howlett  * @vmi: The vma iterator pointing at the vma
285127b26701SLiam R. Howlett  * @vma: The first vma to be munmapped
285227b26701SLiam R. Howlett  * @start: the start of the address to unmap
285327b26701SLiam R. Howlett  * @end: The end of the address to unmap
28542e7ce7d3SLiam R. Howlett  * @uf: The userfaultfd list_head
285527b26701SLiam R. Howlett  * @downgrade: Attempt to downgrade or not
28562e7ce7d3SLiam R. Howlett  *
285727b26701SLiam R. Howlett  * Returns: 0 on success and not downgraded, 1 on success and downgraded.
285827b26701SLiam R. Howlett  * unmaps a VMA mapping when the vma iterator is already in position.
285927b26701SLiam R. Howlett  * Does not handle alignment.
28601da177e4SLinus Torvalds  */
286127b26701SLiam R. Howlett int do_vma_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
286227b26701SLiam R. Howlett 		  unsigned long start, unsigned long end,
286327b26701SLiam R. Howlett 		  struct list_head *uf, bool downgrade)
28642e7ce7d3SLiam R. Howlett {
28652e7ce7d3SLiam R. Howlett 	struct mm_struct *mm = vma->vm_mm;
28662e7ce7d3SLiam R. Howlett 	int ret;
28672e7ce7d3SLiam R. Howlett 
286827b26701SLiam R. Howlett 	arch_unmap(mm, start, end);
286927b26701SLiam R. Howlett 	ret = do_vmi_align_munmap(vmi, vma, mm, start, end, uf, downgrade);
28702e7ce7d3SLiam R. Howlett 	validate_mm_mt(mm);
28712e7ce7d3SLiam R. Howlett 	return ret;
28722e7ce7d3SLiam R. Howlett }
28732e7ce7d3SLiam R. Howlett 
28742e7ce7d3SLiam R. Howlett /*
28752e7ce7d3SLiam R. Howlett  * do_brk_flags() - Increase the brk vma if the flags match.
287692fed820SLiam R. Howlett  * @vmi: The vma iterator
28772e7ce7d3SLiam R. Howlett  * @addr: The start address
28782e7ce7d3SLiam R. Howlett  * @len: The length of the increase
28792e7ce7d3SLiam R. Howlett  * @vma: The vma,
28802e7ce7d3SLiam R. Howlett  * @flags: The VMA Flags
28812e7ce7d3SLiam R. Howlett  *
28822e7ce7d3SLiam R. Howlett  * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
28832e7ce7d3SLiam R. Howlett  * do not match then create a new anonymous VMA.  Eventually we may be able to
28842e7ce7d3SLiam R. Howlett  * do some brk-specific accounting here.
28852e7ce7d3SLiam R. Howlett  */
288692fed820SLiam R. Howlett static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
2887763ecb03SLiam R. Howlett 		unsigned long addr, unsigned long len, unsigned long flags)
28881da177e4SLinus Torvalds {
28891da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
2890287051b1SLiam R. Howlett 	struct vma_prepare vp;
28912e7ce7d3SLiam R. Howlett 
2892d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
28932e7ce7d3SLiam R. Howlett 	/*
28942e7ce7d3SLiam R. Howlett 	 * Check against address space limits by the changed size
28952e7ce7d3SLiam R. Howlett 	 * Note: This happens *after* clearing old mappings in some code paths.
28962e7ce7d3SLiam R. Howlett 	 */
289716e72e9bSDenys Vlasenko 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
289884638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
28991da177e4SLinus Torvalds 		return -ENOMEM;
29001da177e4SLinus Torvalds 
29011da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
29021da177e4SLinus Torvalds 		return -ENOMEM;
29031da177e4SLinus Torvalds 
2904191c5424SAl Viro 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
29051da177e4SLinus Torvalds 		return -ENOMEM;
29061da177e4SLinus Torvalds 
29071da177e4SLinus Torvalds 	/*
29082e7ce7d3SLiam R. Howlett 	 * Expand the existing vma if possible; Note that singular lists do not
29092e7ce7d3SLiam R. Howlett 	 * occur after forking, so the expand will only happen on new VMAs.
29101da177e4SLinus Torvalds 	 */
29116c28ca64SLiam Howlett 	if (vma && vma->vm_end == addr && !vma_policy(vma) &&
29126c28ca64SLiam Howlett 	    can_vma_merge_after(vma, flags, NULL, NULL,
29136c28ca64SLiam Howlett 				addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
291492fed820SLiam R. Howlett 		if (vma_iter_prealloc(vmi))
2915675eaca1SAlistair Popple 			goto unacct_fail;
291628c5609fSLiam Howlett 
291728c5609fSLiam Howlett 		vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
2918287051b1SLiam R. Howlett 		init_vma_prep(&vp, vma);
2919287051b1SLiam R. Howlett 		vma_prepare(&vp);
29202e7ce7d3SLiam R. Howlett 		vma->vm_end = addr + len;
29211c71222eSSuren Baghdasaryan 		vm_flags_set(vma, VM_SOFTDIRTY);
292292fed820SLiam R. Howlett 		vma_iter_store(vmi, vma);
29232e7ce7d3SLiam R. Howlett 
2924287051b1SLiam R. Howlett 		vma_complete(&vp, vmi, mm);
29252e7ce7d3SLiam R. Howlett 		khugepaged_enter_vma(vma, flags);
29262e7ce7d3SLiam R. Howlett 		goto out;
29272e7ce7d3SLiam R. Howlett 	}
29282e7ce7d3SLiam R. Howlett 
29292e7ce7d3SLiam R. Howlett 	/* create a vma struct for an anonymous mapping */
29302e7ce7d3SLiam R. Howlett 	vma = vm_area_alloc(mm);
29312e7ce7d3SLiam R. Howlett 	if (!vma)
2932675eaca1SAlistair Popple 		goto unacct_fail;
29331da177e4SLinus Torvalds 
2934bfd40eafSKirill A. Shutemov 	vma_set_anonymous(vma);
29351da177e4SLinus Torvalds 	vma->vm_start = addr;
29361da177e4SLinus Torvalds 	vma->vm_end = addr + len;
29372e7ce7d3SLiam R. Howlett 	vma->vm_pgoff = addr >> PAGE_SHIFT;
29381c71222eSSuren Baghdasaryan 	vm_flags_init(vma, flags);
29393ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(flags);
294092fed820SLiam R. Howlett 	if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
29412e7ce7d3SLiam R. Howlett 		goto mas_store_fail;
2942d4af56c5SLiam R. Howlett 
29432e7ce7d3SLiam R. Howlett 	mm->map_count++;
29441da177e4SLinus Torvalds out:
29453af9e859SEric B Munson 	perf_event_mmap(vma);
29461da177e4SLinus Torvalds 	mm->total_vm += len >> PAGE_SHIFT;
294784638335SKonstantin Khlebnikov 	mm->data_vm += len >> PAGE_SHIFT;
2948128557ffSMichel Lespinasse 	if (flags & VM_LOCKED)
2949ba470de4SRik van Riel 		mm->locked_vm += (len >> PAGE_SHIFT);
29501c71222eSSuren Baghdasaryan 	vm_flags_set(vma, VM_SOFTDIRTY);
2951763ecb03SLiam R. Howlett 	validate_mm(mm);
29525d22fc25SLinus Torvalds 	return 0;
2953d4af56c5SLiam R. Howlett 
29542e7ce7d3SLiam R. Howlett mas_store_fail:
2955d4af56c5SLiam R. Howlett 	vm_area_free(vma);
2956675eaca1SAlistair Popple unacct_fail:
29572e7ce7d3SLiam R. Howlett 	vm_unacct_memory(len >> PAGE_SHIFT);
29582e7ce7d3SLiam R. Howlett 	return -ENOMEM;
29591da177e4SLinus Torvalds }
29601da177e4SLinus Torvalds 
2961bb177a73SMichal Hocko int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
2962e4eb1ff6SLinus Torvalds {
2963e4eb1ff6SLinus Torvalds 	struct mm_struct *mm = current->mm;
29642e7ce7d3SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
2965bb177a73SMichal Hocko 	unsigned long len;
29665d22fc25SLinus Torvalds 	int ret;
2967128557ffSMichel Lespinasse 	bool populate;
2968897ab3e0SMike Rapoport 	LIST_HEAD(uf);
296992fed820SLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
2970e4eb1ff6SLinus Torvalds 
2971bb177a73SMichal Hocko 	len = PAGE_ALIGN(request);
2972bb177a73SMichal Hocko 	if (len < request)
2973bb177a73SMichal Hocko 		return -ENOMEM;
2974bb177a73SMichal Hocko 	if (!len)
2975bb177a73SMichal Hocko 		return 0;
2976bb177a73SMichal Hocko 
2977d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
29782d6c9282SMichal Hocko 		return -EINTR;
29792d6c9282SMichal Hocko 
29802e7ce7d3SLiam R. Howlett 	/* Until we need other flags, refuse anything except VM_EXEC. */
29812e7ce7d3SLiam R. Howlett 	if ((flags & (~VM_EXEC)) != 0)
29822e7ce7d3SLiam R. Howlett 		return -EINVAL;
29832e7ce7d3SLiam R. Howlett 
29842e7ce7d3SLiam R. Howlett 	ret = check_brk_limits(addr, len);
29852e7ce7d3SLiam R. Howlett 	if (ret)
29862e7ce7d3SLiam R. Howlett 		goto limits_failed;
29872e7ce7d3SLiam R. Howlett 
2988183654ceSLiam R. Howlett 	ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
29892e7ce7d3SLiam R. Howlett 	if (ret)
29902e7ce7d3SLiam R. Howlett 		goto munmap_failed;
29912e7ce7d3SLiam R. Howlett 
299292fed820SLiam R. Howlett 	vma = vma_prev(&vmi);
299392fed820SLiam R. Howlett 	ret = do_brk_flags(&vmi, vma, addr, len, flags);
2994128557ffSMichel Lespinasse 	populate = ((mm->def_flags & VM_LOCKED) != 0);
2995d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
2996897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
29975d22fc25SLinus Torvalds 	if (populate && !ret)
2998128557ffSMichel Lespinasse 		mm_populate(addr, len);
2999e4eb1ff6SLinus Torvalds 	return ret;
30002e7ce7d3SLiam R. Howlett 
30012e7ce7d3SLiam R. Howlett munmap_failed:
30022e7ce7d3SLiam R. Howlett limits_failed:
30032e7ce7d3SLiam R. Howlett 	mmap_write_unlock(mm);
30042e7ce7d3SLiam R. Howlett 	return ret;
3005e4eb1ff6SLinus Torvalds }
300616e72e9bSDenys Vlasenko EXPORT_SYMBOL(vm_brk_flags);
300716e72e9bSDenys Vlasenko 
300816e72e9bSDenys Vlasenko int vm_brk(unsigned long addr, unsigned long len)
300916e72e9bSDenys Vlasenko {
301016e72e9bSDenys Vlasenko 	return vm_brk_flags(addr, len, 0);
301116e72e9bSDenys Vlasenko }
3012e4eb1ff6SLinus Torvalds EXPORT_SYMBOL(vm_brk);
30131da177e4SLinus Torvalds 
30141da177e4SLinus Torvalds /* Release all mmaps. */
30151da177e4SLinus Torvalds void exit_mmap(struct mm_struct *mm)
30161da177e4SLinus Torvalds {
3017d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
3018ba470de4SRik van Riel 	struct vm_area_struct *vma;
30191da177e4SLinus Torvalds 	unsigned long nr_accounted = 0;
3020763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
3021763ecb03SLiam R. Howlett 	int count = 0;
30221da177e4SLinus Torvalds 
3023d6dd61c8SJeremy Fitzhardinge 	/* mm's last user has gone, and its about to be pulled down */
3024cddb8a5cSAndrea Arcangeli 	mmu_notifier_release(mm);
3025d6dd61c8SJeremy Fitzhardinge 
3026bf3980c8SSuren Baghdasaryan 	mmap_read_lock(mm);
30279480c53eSJeremy Fitzhardinge 	arch_exit_mmap(mm);
30289480c53eSJeremy Fitzhardinge 
3029763ecb03SLiam R. Howlett 	vma = mas_find(&mas, ULONG_MAX);
303064591e86SSuren Baghdasaryan 	if (!vma) {
303164591e86SSuren Baghdasaryan 		/* Can happen if dup_mmap() received an OOM */
3032bf3980c8SSuren Baghdasaryan 		mmap_read_unlock(mm);
30339480c53eSJeremy Fitzhardinge 		return;
303464591e86SSuren Baghdasaryan 	}
30359480c53eSJeremy Fitzhardinge 
30361da177e4SLinus Torvalds 	lru_add_drain();
30371da177e4SLinus Torvalds 	flush_cache_mm(mm);
3038d8b45053SWill Deacon 	tlb_gather_mmu_fullmm(&tlb, mm);
3039901608d9SOleg Nesterov 	/* update_hiwater_rss(mm) here? but nobody should be looking */
3040763ecb03SLiam R. Howlett 	/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
304168f48381SSuren Baghdasaryan 	unmap_vmas(&tlb, &mm->mm_mt, vma, 0, ULONG_MAX, false);
3042bf3980c8SSuren Baghdasaryan 	mmap_read_unlock(mm);
3043bf3980c8SSuren Baghdasaryan 
3044bf3980c8SSuren Baghdasaryan 	/*
3045bf3980c8SSuren Baghdasaryan 	 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
3046b3541d91SSuren Baghdasaryan 	 * because the memory has been already freed.
3047bf3980c8SSuren Baghdasaryan 	 */
3048bf3980c8SSuren Baghdasaryan 	set_bit(MMF_OOM_SKIP, &mm->flags);
3049bf3980c8SSuren Baghdasaryan 	mmap_write_lock(mm);
3050763ecb03SLiam R. Howlett 	free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS,
3051763ecb03SLiam R. Howlett 		      USER_PGTABLES_CEILING);
3052ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
30531da177e4SLinus Torvalds 
3054763ecb03SLiam R. Howlett 	/*
3055763ecb03SLiam R. Howlett 	 * Walk the list again, actually closing and freeing it, with preemption
3056763ecb03SLiam R. Howlett 	 * enabled, without holding any MM locks besides the unreachable
3057763ecb03SLiam R. Howlett 	 * mmap_write_lock.
3058763ecb03SLiam R. Howlett 	 */
3059763ecb03SLiam R. Howlett 	do {
30604f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
30614f74d2c8SLinus Torvalds 			nr_accounted += vma_pages(vma);
3062763ecb03SLiam R. Howlett 		remove_vma(vma);
3063763ecb03SLiam R. Howlett 		count++;
30640a3b3c25SPaul E. McKenney 		cond_resched();
3065763ecb03SLiam R. Howlett 	} while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);
3066763ecb03SLiam R. Howlett 
3067763ecb03SLiam R. Howlett 	BUG_ON(count != mm->map_count);
3068d4af56c5SLiam R. Howlett 
3069d4af56c5SLiam R. Howlett 	trace_exit_mmap(mm);
3070d4af56c5SLiam R. Howlett 	__mt_destroy(&mm->mm_mt);
307164591e86SSuren Baghdasaryan 	mmap_write_unlock(mm);
30724f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
30731da177e4SLinus Torvalds }
30741da177e4SLinus Torvalds 
30751da177e4SLinus Torvalds /* Insert vm structure into process list sorted by address
30761da177e4SLinus Torvalds  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3077c8c06efaSDavidlohr Bueso  * then i_mmap_rwsem is taken here.
30781da177e4SLinus Torvalds  */
30791da177e4SLinus Torvalds int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
30801da177e4SLinus Torvalds {
3081d4af56c5SLiam R. Howlett 	unsigned long charged = vma_pages(vma);
30821da177e4SLinus Torvalds 
3083d4af56c5SLiam R. Howlett 
3084d0601a50SLiam R. Howlett 	if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3085c9d13f5fSChen Gang 		return -ENOMEM;
3086d4af56c5SLiam R. Howlett 
3087c9d13f5fSChen Gang 	if ((vma->vm_flags & VM_ACCOUNT) &&
3088d4af56c5SLiam R. Howlett 	     security_vm_enough_memory_mm(mm, charged))
3089c9d13f5fSChen Gang 		return -ENOMEM;
3090c9d13f5fSChen Gang 
30911da177e4SLinus Torvalds 	/*
30921da177e4SLinus Torvalds 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
30931da177e4SLinus Torvalds 	 * until its first write fault, when page's anon_vma and index
30941da177e4SLinus Torvalds 	 * are set.  But now set the vm_pgoff it will almost certainly
30951da177e4SLinus Torvalds 	 * end up with (unless mremap moves it elsewhere before that
30961da177e4SLinus Torvalds 	 * first wfault), so /proc/pid/maps tells a consistent story.
30971da177e4SLinus Torvalds 	 *
30981da177e4SLinus Torvalds 	 * By setting it to reflect the virtual start address of the
30991da177e4SLinus Torvalds 	 * vma, merges and splits can happen in a seamless way, just
31001da177e4SLinus Torvalds 	 * using the existing file pgoff checks and manipulations.
31018332326eSLiao Pingfang 	 * Similarly in do_mmap and in do_brk_flags.
31021da177e4SLinus Torvalds 	 */
31038a9cc3b5SOleg Nesterov 	if (vma_is_anonymous(vma)) {
31041da177e4SLinus Torvalds 		BUG_ON(vma->anon_vma);
31051da177e4SLinus Torvalds 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
31061da177e4SLinus Torvalds 	}
31072b144498SSrikar Dronamraju 
3108763ecb03SLiam R. Howlett 	if (vma_link(mm, vma)) {
3109d4af56c5SLiam R. Howlett 		vm_unacct_memory(charged);
3110d4af56c5SLiam R. Howlett 		return -ENOMEM;
3111d4af56c5SLiam R. Howlett 	}
3112d4af56c5SLiam R. Howlett 
31131da177e4SLinus Torvalds 	return 0;
31141da177e4SLinus Torvalds }
31151da177e4SLinus Torvalds 
31161da177e4SLinus Torvalds /*
31171da177e4SLinus Torvalds  * Copy the vma structure to a new location in the same mm,
31181da177e4SLinus Torvalds  * prior to moving page table entries, to effect an mremap move.
31191da177e4SLinus Torvalds  */
31201da177e4SLinus Torvalds struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
312138a76013SMichel Lespinasse 	unsigned long addr, unsigned long len, pgoff_t pgoff,
312238a76013SMichel Lespinasse 	bool *need_rmap_locks)
31231da177e4SLinus Torvalds {
31241da177e4SLinus Torvalds 	struct vm_area_struct *vma = *vmap;
31251da177e4SLinus Torvalds 	unsigned long vma_start = vma->vm_start;
31261da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
31271da177e4SLinus Torvalds 	struct vm_area_struct *new_vma, *prev;
3128948f017bSAndrea Arcangeli 	bool faulted_in_anon_vma = true;
3129076f16bfSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
31301da177e4SLinus Torvalds 
3131d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
31321da177e4SLinus Torvalds 	/*
31331da177e4SLinus Torvalds 	 * If anonymous vma has not yet been faulted, update new pgoff
31341da177e4SLinus Torvalds 	 * to match new location, to increase its chance of merging.
31351da177e4SLinus Torvalds 	 */
3136ce75799bSOleg Nesterov 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
31371da177e4SLinus Torvalds 		pgoff = addr >> PAGE_SHIFT;
3138948f017bSAndrea Arcangeli 		faulted_in_anon_vma = false;
3139948f017bSAndrea Arcangeli 	}
31401da177e4SLinus Torvalds 
3141763ecb03SLiam R. Howlett 	new_vma = find_vma_prev(mm, addr, &prev);
3142763ecb03SLiam R. Howlett 	if (new_vma && new_vma->vm_start < addr + len)
31436597d783SHugh Dickins 		return NULL;	/* should never get here */
3144524e00b3SLiam R. Howlett 
31459760ebffSLiam R. Howlett 	new_vma = vma_merge(&vmi, mm, prev, addr, addr + len, vma->vm_flags,
314619a809afSAndrea Arcangeli 			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
31475c26f6acSSuren Baghdasaryan 			    vma->vm_userfaultfd_ctx, anon_vma_name(vma));
31481da177e4SLinus Torvalds 	if (new_vma) {
31491da177e4SLinus Torvalds 		/*
31501da177e4SLinus Torvalds 		 * Source vma may have been merged into new_vma
31511da177e4SLinus Torvalds 		 */
3152948f017bSAndrea Arcangeli 		if (unlikely(vma_start >= new_vma->vm_start &&
3153948f017bSAndrea Arcangeli 			     vma_start < new_vma->vm_end)) {
3154948f017bSAndrea Arcangeli 			/*
3155948f017bSAndrea Arcangeli 			 * The only way we can get a vma_merge with
3156948f017bSAndrea Arcangeli 			 * self during an mremap is if the vma hasn't
3157948f017bSAndrea Arcangeli 			 * been faulted in yet and we were allowed to
3158948f017bSAndrea Arcangeli 			 * reset the dst vma->vm_pgoff to the
3159948f017bSAndrea Arcangeli 			 * destination address of the mremap to allow
3160948f017bSAndrea Arcangeli 			 * the merge to happen. mremap must change the
3161948f017bSAndrea Arcangeli 			 * vm_pgoff linearity between src and dst vmas
3162948f017bSAndrea Arcangeli 			 * (in turn preventing a vma_merge) to be
3163948f017bSAndrea Arcangeli 			 * safe. It is only safe to keep the vm_pgoff
3164948f017bSAndrea Arcangeli 			 * linear if there are no pages mapped yet.
3165948f017bSAndrea Arcangeli 			 */
316681d1b09cSSasha Levin 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
316738a76013SMichel Lespinasse 			*vmap = vma = new_vma;
3168108d6642SMichel Lespinasse 		}
316938a76013SMichel Lespinasse 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
31701da177e4SLinus Torvalds 	} else {
31713928d4f5SLinus Torvalds 		new_vma = vm_area_dup(vma);
3172e3975891SChen Gang 		if (!new_vma)
3173e3975891SChen Gang 			goto out;
31741da177e4SLinus Torvalds 		new_vma->vm_start = addr;
31751da177e4SLinus Torvalds 		new_vma->vm_end = addr + len;
31761da177e4SLinus Torvalds 		new_vma->vm_pgoff = pgoff;
3177ef0855d3SOleg Nesterov 		if (vma_dup_policy(vma, new_vma))
3178523d4e20SMichel Lespinasse 			goto out_free_vma;
3179523d4e20SMichel Lespinasse 		if (anon_vma_clone(new_vma, vma))
3180523d4e20SMichel Lespinasse 			goto out_free_mempol;
3181e9714acfSKonstantin Khlebnikov 		if (new_vma->vm_file)
31821da177e4SLinus Torvalds 			get_file(new_vma->vm_file);
31831da177e4SLinus Torvalds 		if (new_vma->vm_ops && new_vma->vm_ops->open)
31841da177e4SLinus Torvalds 			new_vma->vm_ops->open(new_vma);
3185763ecb03SLiam R. Howlett 		if (vma_link(mm, new_vma))
3186524e00b3SLiam R. Howlett 			goto out_vma_link;
318738a76013SMichel Lespinasse 		*need_rmap_locks = false;
31881da177e4SLinus Torvalds 	}
3189d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
31901da177e4SLinus Torvalds 	return new_vma;
31915beb4930SRik van Riel 
3192524e00b3SLiam R. Howlett out_vma_link:
3193524e00b3SLiam R. Howlett 	if (new_vma->vm_ops && new_vma->vm_ops->close)
3194524e00b3SLiam R. Howlett 		new_vma->vm_ops->close(new_vma);
319592b73996SLiam Howlett 
319692b73996SLiam Howlett 	if (new_vma->vm_file)
319792b73996SLiam Howlett 		fput(new_vma->vm_file);
319892b73996SLiam Howlett 
319992b73996SLiam Howlett 	unlink_anon_vmas(new_vma);
32005beb4930SRik van Riel out_free_mempol:
3201ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new_vma));
32025beb4930SRik van Riel out_free_vma:
32033928d4f5SLinus Torvalds 	vm_area_free(new_vma);
3204e3975891SChen Gang out:
3205d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
32065beb4930SRik van Riel 	return NULL;
32071da177e4SLinus Torvalds }
3208119f657cSakpm@osdl.org 
3209119f657cSakpm@osdl.org /*
3210119f657cSakpm@osdl.org  * Return true if the calling process may expand its vm space by the passed
3211119f657cSakpm@osdl.org  * number of pages
3212119f657cSakpm@osdl.org  */
321384638335SKonstantin Khlebnikov bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3214119f657cSakpm@osdl.org {
321584638335SKonstantin Khlebnikov 	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
321684638335SKonstantin Khlebnikov 		return false;
3217119f657cSakpm@osdl.org 
3218d977d56cSKonstantin Khlebnikov 	if (is_data_mapping(flags) &&
3219d977d56cSKonstantin Khlebnikov 	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3220f4fcd558SKonstantin Khlebnikov 		/* Workaround for Valgrind */
3221f4fcd558SKonstantin Khlebnikov 		if (rlimit(RLIMIT_DATA) == 0 &&
3222f4fcd558SKonstantin Khlebnikov 		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3223f4fcd558SKonstantin Khlebnikov 			return true;
322457a7702bSDavid Woodhouse 
322557a7702bSDavid Woodhouse 		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3226d977d56cSKonstantin Khlebnikov 			     current->comm, current->pid,
3227d977d56cSKonstantin Khlebnikov 			     (mm->data_vm + npages) << PAGE_SHIFT,
322857a7702bSDavid Woodhouse 			     rlimit(RLIMIT_DATA),
322957a7702bSDavid Woodhouse 			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
323057a7702bSDavid Woodhouse 
323157a7702bSDavid Woodhouse 		if (!ignore_rlimit_data)
3232d977d56cSKonstantin Khlebnikov 			return false;
3233d977d56cSKonstantin Khlebnikov 	}
3234119f657cSakpm@osdl.org 
323584638335SKonstantin Khlebnikov 	return true;
323684638335SKonstantin Khlebnikov }
323784638335SKonstantin Khlebnikov 
323884638335SKonstantin Khlebnikov void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
323984638335SKonstantin Khlebnikov {
32407866076bSPeng Liu 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
324184638335SKonstantin Khlebnikov 
3242d977d56cSKonstantin Khlebnikov 	if (is_exec_mapping(flags))
324384638335SKonstantin Khlebnikov 		mm->exec_vm += npages;
3244d977d56cSKonstantin Khlebnikov 	else if (is_stack_mapping(flags))
324584638335SKonstantin Khlebnikov 		mm->stack_vm += npages;
3246d977d56cSKonstantin Khlebnikov 	else if (is_data_mapping(flags))
324784638335SKonstantin Khlebnikov 		mm->data_vm += npages;
3248119f657cSakpm@osdl.org }
3249fa5dc22fSRoland McGrath 
3250b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3251a62c34bdSAndy Lutomirski 
3252a62c34bdSAndy Lutomirski /*
3253a62c34bdSAndy Lutomirski  * Having a close hook prevents vma merging regardless of flags.
3254a62c34bdSAndy Lutomirski  */
3255a62c34bdSAndy Lutomirski static void special_mapping_close(struct vm_area_struct *vma)
3256a62c34bdSAndy Lutomirski {
3257a62c34bdSAndy Lutomirski }
3258a62c34bdSAndy Lutomirski 
3259a62c34bdSAndy Lutomirski static const char *special_mapping_name(struct vm_area_struct *vma)
3260a62c34bdSAndy Lutomirski {
3261a62c34bdSAndy Lutomirski 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3262a62c34bdSAndy Lutomirski }
3263a62c34bdSAndy Lutomirski 
326414d07113SBrian Geffon static int special_mapping_mremap(struct vm_area_struct *new_vma)
3265b059a453SDmitry Safonov {
3266b059a453SDmitry Safonov 	struct vm_special_mapping *sm = new_vma->vm_private_data;
3267b059a453SDmitry Safonov 
3268280e87e9SDmitry Safonov 	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3269280e87e9SDmitry Safonov 		return -EFAULT;
3270280e87e9SDmitry Safonov 
3271b059a453SDmitry Safonov 	if (sm->mremap)
3272b059a453SDmitry Safonov 		return sm->mremap(sm, new_vma);
3273280e87e9SDmitry Safonov 
3274b059a453SDmitry Safonov 	return 0;
3275b059a453SDmitry Safonov }
3276b059a453SDmitry Safonov 
3277871402e0SDmitry Safonov static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3278871402e0SDmitry Safonov {
3279871402e0SDmitry Safonov 	/*
3280871402e0SDmitry Safonov 	 * Forbid splitting special mappings - kernel has expectations over
3281871402e0SDmitry Safonov 	 * the number of pages in mapping. Together with VM_DONTEXPAND
3282871402e0SDmitry Safonov 	 * the size of vma should stay the same over the special mapping's
3283871402e0SDmitry Safonov 	 * lifetime.
3284871402e0SDmitry Safonov 	 */
3285871402e0SDmitry Safonov 	return -EINVAL;
3286871402e0SDmitry Safonov }
3287871402e0SDmitry Safonov 
3288a62c34bdSAndy Lutomirski static const struct vm_operations_struct special_mapping_vmops = {
3289a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3290a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3291b059a453SDmitry Safonov 	.mremap = special_mapping_mremap,
3292a62c34bdSAndy Lutomirski 	.name = special_mapping_name,
3293af34ebebSDmitry Safonov 	/* vDSO code relies that VVAR can't be accessed remotely */
3294af34ebebSDmitry Safonov 	.access = NULL,
3295871402e0SDmitry Safonov 	.may_split = special_mapping_split,
3296a62c34bdSAndy Lutomirski };
3297a62c34bdSAndy Lutomirski 
3298a62c34bdSAndy Lutomirski static const struct vm_operations_struct legacy_special_mapping_vmops = {
3299a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3300a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3301a62c34bdSAndy Lutomirski };
3302fa5dc22fSRoland McGrath 
3303b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3304fa5dc22fSRoland McGrath {
330511bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
3306b1d0e4f5SNick Piggin 	pgoff_t pgoff;
3307fa5dc22fSRoland McGrath 	struct page **pages;
3308fa5dc22fSRoland McGrath 
3309f872f540SAndy Lutomirski 	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3310a62c34bdSAndy Lutomirski 		pages = vma->vm_private_data;
3311f872f540SAndy Lutomirski 	} else {
3312f872f540SAndy Lutomirski 		struct vm_special_mapping *sm = vma->vm_private_data;
3313f872f540SAndy Lutomirski 
3314f872f540SAndy Lutomirski 		if (sm->fault)
331511bac800SDave Jiang 			return sm->fault(sm, vmf->vma, vmf);
3316f872f540SAndy Lutomirski 
3317f872f540SAndy Lutomirski 		pages = sm->pages;
3318f872f540SAndy Lutomirski 	}
3319a62c34bdSAndy Lutomirski 
33208a9cc3b5SOleg Nesterov 	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3321b1d0e4f5SNick Piggin 		pgoff--;
3322fa5dc22fSRoland McGrath 
3323fa5dc22fSRoland McGrath 	if (*pages) {
3324fa5dc22fSRoland McGrath 		struct page *page = *pages;
3325fa5dc22fSRoland McGrath 		get_page(page);
3326b1d0e4f5SNick Piggin 		vmf->page = page;
3327b1d0e4f5SNick Piggin 		return 0;
3328fa5dc22fSRoland McGrath 	}
3329fa5dc22fSRoland McGrath 
3330b1d0e4f5SNick Piggin 	return VM_FAULT_SIGBUS;
3331fa5dc22fSRoland McGrath }
3332fa5dc22fSRoland McGrath 
3333a62c34bdSAndy Lutomirski static struct vm_area_struct *__install_special_mapping(
3334a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3335fa5dc22fSRoland McGrath 	unsigned long addr, unsigned long len,
333627f28b97SChen Gang 	unsigned long vm_flags, void *priv,
333727f28b97SChen Gang 	const struct vm_operations_struct *ops)
3338fa5dc22fSRoland McGrath {
3339462e635eSTavis Ormandy 	int ret;
3340fa5dc22fSRoland McGrath 	struct vm_area_struct *vma;
3341fa5dc22fSRoland McGrath 
3342d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
3343490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
3344fa5dc22fSRoland McGrath 	if (unlikely(vma == NULL))
33453935ed6aSStefani Seibold 		return ERR_PTR(-ENOMEM);
3346fa5dc22fSRoland McGrath 
3347fa5dc22fSRoland McGrath 	vma->vm_start = addr;
3348fa5dc22fSRoland McGrath 	vma->vm_end = addr + len;
3349fa5dc22fSRoland McGrath 
3350e430a95aSSuren Baghdasaryan 	vm_flags_init(vma, (vm_flags | mm->def_flags |
3351e430a95aSSuren Baghdasaryan 		      VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
33523ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3353fa5dc22fSRoland McGrath 
3354a62c34bdSAndy Lutomirski 	vma->vm_ops = ops;
3355a62c34bdSAndy Lutomirski 	vma->vm_private_data = priv;
3356fa5dc22fSRoland McGrath 
3357462e635eSTavis Ormandy 	ret = insert_vm_struct(mm, vma);
3358462e635eSTavis Ormandy 	if (ret)
3359462e635eSTavis Ormandy 		goto out;
3360fa5dc22fSRoland McGrath 
336184638335SKonstantin Khlebnikov 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3362fa5dc22fSRoland McGrath 
3363cdd6c482SIngo Molnar 	perf_event_mmap(vma);
3364089dd79dSPeter Zijlstra 
3365d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
33663935ed6aSStefani Seibold 	return vma;
3367462e635eSTavis Ormandy 
3368462e635eSTavis Ormandy out:
33693928d4f5SLinus Torvalds 	vm_area_free(vma);
3370d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
33713935ed6aSStefani Seibold 	return ERR_PTR(ret);
33723935ed6aSStefani Seibold }
33733935ed6aSStefani Seibold 
33742eefd878SDmitry Safonov bool vma_is_special_mapping(const struct vm_area_struct *vma,
33752eefd878SDmitry Safonov 	const struct vm_special_mapping *sm)
33762eefd878SDmitry Safonov {
33772eefd878SDmitry Safonov 	return vma->vm_private_data == sm &&
33782eefd878SDmitry Safonov 		(vma->vm_ops == &special_mapping_vmops ||
33792eefd878SDmitry Safonov 		 vma->vm_ops == &legacy_special_mapping_vmops);
33802eefd878SDmitry Safonov }
33812eefd878SDmitry Safonov 
3382a62c34bdSAndy Lutomirski /*
3383c1e8d7c6SMichel Lespinasse  * Called with mm->mmap_lock held for writing.
3384a62c34bdSAndy Lutomirski  * Insert a new vma covering the given region, with the given flags.
3385a62c34bdSAndy Lutomirski  * Its pages are supplied by the given array of struct page *.
3386a62c34bdSAndy Lutomirski  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3387a62c34bdSAndy Lutomirski  * The region past the last page supplied will always produce SIGBUS.
3388a62c34bdSAndy Lutomirski  * The array pointer and the pages it points to are assumed to stay alive
3389a62c34bdSAndy Lutomirski  * for as long as this mapping might exist.
3390a62c34bdSAndy Lutomirski  */
3391a62c34bdSAndy Lutomirski struct vm_area_struct *_install_special_mapping(
3392a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3393a62c34bdSAndy Lutomirski 	unsigned long addr, unsigned long len,
3394a62c34bdSAndy Lutomirski 	unsigned long vm_flags, const struct vm_special_mapping *spec)
3395a62c34bdSAndy Lutomirski {
339627f28b97SChen Gang 	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
339727f28b97SChen Gang 					&special_mapping_vmops);
3398a62c34bdSAndy Lutomirski }
3399a62c34bdSAndy Lutomirski 
34003935ed6aSStefani Seibold int install_special_mapping(struct mm_struct *mm,
34013935ed6aSStefani Seibold 			    unsigned long addr, unsigned long len,
34023935ed6aSStefani Seibold 			    unsigned long vm_flags, struct page **pages)
34033935ed6aSStefani Seibold {
3404a62c34bdSAndy Lutomirski 	struct vm_area_struct *vma = __install_special_mapping(
340527f28b97SChen Gang 		mm, addr, len, vm_flags, (void *)pages,
340627f28b97SChen Gang 		&legacy_special_mapping_vmops);
34073935ed6aSStefani Seibold 
340814bd5b45SDuan Jiong 	return PTR_ERR_OR_ZERO(vma);
3409fa5dc22fSRoland McGrath }
34107906d00cSAndrea Arcangeli 
34117906d00cSAndrea Arcangeli static DEFINE_MUTEX(mm_all_locks_mutex);
34127906d00cSAndrea Arcangeli 
3413454ed842SPeter Zijlstra static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
34147906d00cSAndrea Arcangeli {
3415f808c13fSDavidlohr Bueso 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
34167906d00cSAndrea Arcangeli 		/*
34177906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change from under us
34187906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
34197906d00cSAndrea Arcangeli 		 */
3420da1c55f1SMichel Lespinasse 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
34217906d00cSAndrea Arcangeli 		/*
34227906d00cSAndrea Arcangeli 		 * We can safely modify head.next after taking the
34235a505085SIngo Molnar 		 * anon_vma->root->rwsem. If some other vma in this mm shares
34247906d00cSAndrea Arcangeli 		 * the same anon_vma we won't take it again.
34257906d00cSAndrea Arcangeli 		 *
34267906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
34277906d00cSAndrea Arcangeli 		 * can't change from under us thanks to the
34285a505085SIngo Molnar 		 * anon_vma->root->rwsem.
34297906d00cSAndrea Arcangeli 		 */
34307906d00cSAndrea Arcangeli 		if (__test_and_set_bit(0, (unsigned long *)
3431f808c13fSDavidlohr Bueso 				       &anon_vma->root->rb_root.rb_root.rb_node))
34327906d00cSAndrea Arcangeli 			BUG();
34337906d00cSAndrea Arcangeli 	}
34347906d00cSAndrea Arcangeli }
34357906d00cSAndrea Arcangeli 
3436454ed842SPeter Zijlstra static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
34377906d00cSAndrea Arcangeli {
34387906d00cSAndrea Arcangeli 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
34397906d00cSAndrea Arcangeli 		/*
34407906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change from under us because
34417906d00cSAndrea Arcangeli 		 * we hold the mm_all_locks_mutex.
34427906d00cSAndrea Arcangeli 		 *
34437906d00cSAndrea Arcangeli 		 * Operations on ->flags have to be atomic because
34447906d00cSAndrea Arcangeli 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
34457906d00cSAndrea Arcangeli 		 * mm_all_locks_mutex, there may be other cpus
34467906d00cSAndrea Arcangeli 		 * changing other bitflags in parallel to us.
34477906d00cSAndrea Arcangeli 		 */
34487906d00cSAndrea Arcangeli 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
34497906d00cSAndrea Arcangeli 			BUG();
3450da1c55f1SMichel Lespinasse 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
34517906d00cSAndrea Arcangeli 	}
34527906d00cSAndrea Arcangeli }
34537906d00cSAndrea Arcangeli 
34547906d00cSAndrea Arcangeli /*
34557906d00cSAndrea Arcangeli  * This operation locks against the VM for all pte/vma/mm related
34567906d00cSAndrea Arcangeli  * operations that could ever happen on a certain mm. This includes
34577906d00cSAndrea Arcangeli  * vmtruncate, try_to_unmap, and all page faults.
34587906d00cSAndrea Arcangeli  *
3459c1e8d7c6SMichel Lespinasse  * The caller must take the mmap_lock in write mode before calling
34607906d00cSAndrea Arcangeli  * mm_take_all_locks(). The caller isn't allowed to release the
3461c1e8d7c6SMichel Lespinasse  * mmap_lock until mm_drop_all_locks() returns.
34627906d00cSAndrea Arcangeli  *
3463c1e8d7c6SMichel Lespinasse  * mmap_lock in write mode is required in order to block all operations
34647906d00cSAndrea Arcangeli  * that could modify pagetables and free pages without need of
346527ba0644SKirill A. Shutemov  * altering the vma layout. It's also needed in write mode to avoid new
34667906d00cSAndrea Arcangeli  * anon_vmas to be associated with existing vmas.
34677906d00cSAndrea Arcangeli  *
34687906d00cSAndrea Arcangeli  * A single task can't take more than one mm_take_all_locks() in a row
34697906d00cSAndrea Arcangeli  * or it would deadlock.
34707906d00cSAndrea Arcangeli  *
3471bf181b9fSMichel Lespinasse  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
34727906d00cSAndrea Arcangeli  * mapping->flags avoid to take the same lock twice, if more than one
34737906d00cSAndrea Arcangeli  * vma in this mm is backed by the same anon_vma or address_space.
34747906d00cSAndrea Arcangeli  *
347588f306b6SKirill A. Shutemov  * We take locks in following order, accordingly to comment at beginning
347688f306b6SKirill A. Shutemov  * of mm/rmap.c:
347788f306b6SKirill A. Shutemov  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
347888f306b6SKirill A. Shutemov  *     hugetlb mapping);
347988f306b6SKirill A. Shutemov  *   - all i_mmap_rwsem locks;
348088f306b6SKirill A. Shutemov  *   - all anon_vma->rwseml
348188f306b6SKirill A. Shutemov  *
348288f306b6SKirill A. Shutemov  * We can take all locks within these types randomly because the VM code
348388f306b6SKirill A. Shutemov  * doesn't nest them and we protected from parallel mm_take_all_locks() by
348488f306b6SKirill A. Shutemov  * mm_all_locks_mutex.
34857906d00cSAndrea Arcangeli  *
34867906d00cSAndrea Arcangeli  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
34877906d00cSAndrea Arcangeli  * that may have to take thousand of locks.
34887906d00cSAndrea Arcangeli  *
34897906d00cSAndrea Arcangeli  * mm_take_all_locks() can fail if it's interrupted by signals.
34907906d00cSAndrea Arcangeli  */
34917906d00cSAndrea Arcangeli int mm_take_all_locks(struct mm_struct *mm)
34927906d00cSAndrea Arcangeli {
34937906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
34945beb4930SRik van Riel 	struct anon_vma_chain *avc;
3495763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
34967906d00cSAndrea Arcangeli 
3497325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
34987906d00cSAndrea Arcangeli 
34997906d00cSAndrea Arcangeli 	mutex_lock(&mm_all_locks_mutex);
35007906d00cSAndrea Arcangeli 
3501763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
35027906d00cSAndrea Arcangeli 		if (signal_pending(current))
35037906d00cSAndrea Arcangeli 			goto out_unlock;
350488f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
350588f306b6SKirill A. Shutemov 				is_vm_hugetlb_page(vma))
350688f306b6SKirill A. Shutemov 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
350788f306b6SKirill A. Shutemov 	}
350888f306b6SKirill A. Shutemov 
3509763ecb03SLiam R. Howlett 	mas_set(&mas, 0);
3510763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
351188f306b6SKirill A. Shutemov 		if (signal_pending(current))
351288f306b6SKirill A. Shutemov 			goto out_unlock;
351388f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
351488f306b6SKirill A. Shutemov 				!is_vm_hugetlb_page(vma))
3515454ed842SPeter Zijlstra 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
35167906d00cSAndrea Arcangeli 	}
35177cd5a02fSPeter Zijlstra 
3518763ecb03SLiam R. Howlett 	mas_set(&mas, 0);
3519763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
35207cd5a02fSPeter Zijlstra 		if (signal_pending(current))
35217cd5a02fSPeter Zijlstra 			goto out_unlock;
35227cd5a02fSPeter Zijlstra 		if (vma->anon_vma)
35235beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
35245beb4930SRik van Riel 				vm_lock_anon_vma(mm, avc->anon_vma);
35257cd5a02fSPeter Zijlstra 	}
35267cd5a02fSPeter Zijlstra 
3527584cff54SKautuk Consul 	return 0;
35287906d00cSAndrea Arcangeli 
35297906d00cSAndrea Arcangeli out_unlock:
35307906d00cSAndrea Arcangeli 	mm_drop_all_locks(mm);
3531584cff54SKautuk Consul 	return -EINTR;
35327906d00cSAndrea Arcangeli }
35337906d00cSAndrea Arcangeli 
35347906d00cSAndrea Arcangeli static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
35357906d00cSAndrea Arcangeli {
3536f808c13fSDavidlohr Bueso 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
35377906d00cSAndrea Arcangeli 		/*
35387906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change to 0 from under
35397906d00cSAndrea Arcangeli 		 * us because we hold the mm_all_locks_mutex.
35407906d00cSAndrea Arcangeli 		 *
35417906d00cSAndrea Arcangeli 		 * We must however clear the bitflag before unlocking
3542bf181b9fSMichel Lespinasse 		 * the vma so the users using the anon_vma->rb_root will
35437906d00cSAndrea Arcangeli 		 * never see our bitflag.
35447906d00cSAndrea Arcangeli 		 *
35457906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
35467906d00cSAndrea Arcangeli 		 * can't change from under us until we release the
35475a505085SIngo Molnar 		 * anon_vma->root->rwsem.
35487906d00cSAndrea Arcangeli 		 */
35497906d00cSAndrea Arcangeli 		if (!__test_and_clear_bit(0, (unsigned long *)
3550f808c13fSDavidlohr Bueso 					  &anon_vma->root->rb_root.rb_root.rb_node))
35517906d00cSAndrea Arcangeli 			BUG();
355208b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
35537906d00cSAndrea Arcangeli 	}
35547906d00cSAndrea Arcangeli }
35557906d00cSAndrea Arcangeli 
35567906d00cSAndrea Arcangeli static void vm_unlock_mapping(struct address_space *mapping)
35577906d00cSAndrea Arcangeli {
35587906d00cSAndrea Arcangeli 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
35597906d00cSAndrea Arcangeli 		/*
35607906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
35617906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
35627906d00cSAndrea Arcangeli 		 */
356383cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
35647906d00cSAndrea Arcangeli 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
35657906d00cSAndrea Arcangeli 					&mapping->flags))
35667906d00cSAndrea Arcangeli 			BUG();
35677906d00cSAndrea Arcangeli 	}
35687906d00cSAndrea Arcangeli }
35697906d00cSAndrea Arcangeli 
35707906d00cSAndrea Arcangeli /*
3571c1e8d7c6SMichel Lespinasse  * The mmap_lock cannot be released by the caller until
35727906d00cSAndrea Arcangeli  * mm_drop_all_locks() returns.
35737906d00cSAndrea Arcangeli  */
35747906d00cSAndrea Arcangeli void mm_drop_all_locks(struct mm_struct *mm)
35757906d00cSAndrea Arcangeli {
35767906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
35775beb4930SRik van Riel 	struct anon_vma_chain *avc;
3578763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
35797906d00cSAndrea Arcangeli 
3580325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
35817906d00cSAndrea Arcangeli 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
35827906d00cSAndrea Arcangeli 
3583763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
35847906d00cSAndrea Arcangeli 		if (vma->anon_vma)
35855beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
35865beb4930SRik van Riel 				vm_unlock_anon_vma(avc->anon_vma);
35877906d00cSAndrea Arcangeli 		if (vma->vm_file && vma->vm_file->f_mapping)
35887906d00cSAndrea Arcangeli 			vm_unlock_mapping(vma->vm_file->f_mapping);
35897906d00cSAndrea Arcangeli 	}
35907906d00cSAndrea Arcangeli 
35917906d00cSAndrea Arcangeli 	mutex_unlock(&mm_all_locks_mutex);
35927906d00cSAndrea Arcangeli }
35938feae131SDavid Howells 
35948feae131SDavid Howells /*
35953edf41d8Sseokhoon.yoon  * initialise the percpu counter for VM
35968feae131SDavid Howells  */
35978feae131SDavid Howells void __init mmap_init(void)
35988feae131SDavid Howells {
359900a62ce9SKOSAKI Motohiro 	int ret;
360000a62ce9SKOSAKI Motohiro 
3601908c7f19STejun Heo 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
360200a62ce9SKOSAKI Motohiro 	VM_BUG_ON(ret);
36038feae131SDavid Howells }
3604c9b1d098SAndrew Shewmaker 
3605c9b1d098SAndrew Shewmaker /*
3606c9b1d098SAndrew Shewmaker  * Initialise sysctl_user_reserve_kbytes.
3607c9b1d098SAndrew Shewmaker  *
3608c9b1d098SAndrew Shewmaker  * This is intended to prevent a user from starting a single memory hogging
3609c9b1d098SAndrew Shewmaker  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3610c9b1d098SAndrew Shewmaker  * mode.
3611c9b1d098SAndrew Shewmaker  *
3612c9b1d098SAndrew Shewmaker  * The default value is min(3% of free memory, 128MB)
3613c9b1d098SAndrew Shewmaker  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3614c9b1d098SAndrew Shewmaker  */
36151640879aSAndrew Shewmaker static int init_user_reserve(void)
3616c9b1d098SAndrew Shewmaker {
3617c9b1d098SAndrew Shewmaker 	unsigned long free_kbytes;
3618c9b1d098SAndrew Shewmaker 
3619c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3620c9b1d098SAndrew Shewmaker 
3621c9b1d098SAndrew Shewmaker 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3622c9b1d098SAndrew Shewmaker 	return 0;
3623c9b1d098SAndrew Shewmaker }
3624a64fb3cdSPaul Gortmaker subsys_initcall(init_user_reserve);
36254eeab4f5SAndrew Shewmaker 
36264eeab4f5SAndrew Shewmaker /*
36274eeab4f5SAndrew Shewmaker  * Initialise sysctl_admin_reserve_kbytes.
36284eeab4f5SAndrew Shewmaker  *
36294eeab4f5SAndrew Shewmaker  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
36304eeab4f5SAndrew Shewmaker  * to log in and kill a memory hogging process.
36314eeab4f5SAndrew Shewmaker  *
36324eeab4f5SAndrew Shewmaker  * Systems with more than 256MB will reserve 8MB, enough to recover
36334eeab4f5SAndrew Shewmaker  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
36344eeab4f5SAndrew Shewmaker  * only reserve 3% of free pages by default.
36354eeab4f5SAndrew Shewmaker  */
36361640879aSAndrew Shewmaker static int init_admin_reserve(void)
36374eeab4f5SAndrew Shewmaker {
36384eeab4f5SAndrew Shewmaker 	unsigned long free_kbytes;
36394eeab4f5SAndrew Shewmaker 
3640c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
36414eeab4f5SAndrew Shewmaker 
36424eeab4f5SAndrew Shewmaker 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
36434eeab4f5SAndrew Shewmaker 	return 0;
36444eeab4f5SAndrew Shewmaker }
3645a64fb3cdSPaul Gortmaker subsys_initcall(init_admin_reserve);
36461640879aSAndrew Shewmaker 
36471640879aSAndrew Shewmaker /*
36481640879aSAndrew Shewmaker  * Reinititalise user and admin reserves if memory is added or removed.
36491640879aSAndrew Shewmaker  *
36501640879aSAndrew Shewmaker  * The default user reserve max is 128MB, and the default max for the
36511640879aSAndrew Shewmaker  * admin reserve is 8MB. These are usually, but not always, enough to
36521640879aSAndrew Shewmaker  * enable recovery from a memory hogging process using login/sshd, a shell,
36531640879aSAndrew Shewmaker  * and tools like top. It may make sense to increase or even disable the
36541640879aSAndrew Shewmaker  * reserve depending on the existence of swap or variations in the recovery
36551640879aSAndrew Shewmaker  * tools. So, the admin may have changed them.
36561640879aSAndrew Shewmaker  *
36571640879aSAndrew Shewmaker  * If memory is added and the reserves have been eliminated or increased above
36581640879aSAndrew Shewmaker  * the default max, then we'll trust the admin.
36591640879aSAndrew Shewmaker  *
36601640879aSAndrew Shewmaker  * If memory is removed and there isn't enough free memory, then we
36611640879aSAndrew Shewmaker  * need to reset the reserves.
36621640879aSAndrew Shewmaker  *
36631640879aSAndrew Shewmaker  * Otherwise keep the reserve set by the admin.
36641640879aSAndrew Shewmaker  */
36651640879aSAndrew Shewmaker static int reserve_mem_notifier(struct notifier_block *nb,
36661640879aSAndrew Shewmaker 			     unsigned long action, void *data)
36671640879aSAndrew Shewmaker {
36681640879aSAndrew Shewmaker 	unsigned long tmp, free_kbytes;
36691640879aSAndrew Shewmaker 
36701640879aSAndrew Shewmaker 	switch (action) {
36711640879aSAndrew Shewmaker 	case MEM_ONLINE:
36721640879aSAndrew Shewmaker 		/* Default max is 128MB. Leave alone if modified by operator. */
36731640879aSAndrew Shewmaker 		tmp = sysctl_user_reserve_kbytes;
36741640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 17))
36751640879aSAndrew Shewmaker 			init_user_reserve();
36761640879aSAndrew Shewmaker 
36771640879aSAndrew Shewmaker 		/* Default max is 8MB.  Leave alone if modified by operator. */
36781640879aSAndrew Shewmaker 		tmp = sysctl_admin_reserve_kbytes;
36791640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 13))
36801640879aSAndrew Shewmaker 			init_admin_reserve();
36811640879aSAndrew Shewmaker 
36821640879aSAndrew Shewmaker 		break;
36831640879aSAndrew Shewmaker 	case MEM_OFFLINE:
3684c41f012aSMichal Hocko 		free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
36851640879aSAndrew Shewmaker 
36861640879aSAndrew Shewmaker 		if (sysctl_user_reserve_kbytes > free_kbytes) {
36871640879aSAndrew Shewmaker 			init_user_reserve();
36881640879aSAndrew Shewmaker 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
36891640879aSAndrew Shewmaker 				sysctl_user_reserve_kbytes);
36901640879aSAndrew Shewmaker 		}
36911640879aSAndrew Shewmaker 
36921640879aSAndrew Shewmaker 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
36931640879aSAndrew Shewmaker 			init_admin_reserve();
36941640879aSAndrew Shewmaker 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
36951640879aSAndrew Shewmaker 				sysctl_admin_reserve_kbytes);
36961640879aSAndrew Shewmaker 		}
36971640879aSAndrew Shewmaker 		break;
36981640879aSAndrew Shewmaker 	default:
36991640879aSAndrew Shewmaker 		break;
37001640879aSAndrew Shewmaker 	}
37011640879aSAndrew Shewmaker 	return NOTIFY_OK;
37021640879aSAndrew Shewmaker }
37031640879aSAndrew Shewmaker 
37041640879aSAndrew Shewmaker static int __meminit init_reserve_notifier(void)
37051640879aSAndrew Shewmaker {
37061eeaa4fdSLiu Shixin 	if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
3707b1de0d13SMitchel Humpherys 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
37081640879aSAndrew Shewmaker 
37091640879aSAndrew Shewmaker 	return 0;
37101640879aSAndrew Shewmaker }
3711a64fb3cdSPaul Gortmaker subsys_initcall(init_reserve_notifier);
3712