xref: /linux/mm/mmap.c (revision da0892547b101df6e13255b378380d077975368d)
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>
49d7597f59SStefan Roesch #include <linux/ksm.h>
501da177e4SLinus Torvalds 
517c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
521da177e4SLinus Torvalds #include <asm/cacheflush.h>
531da177e4SLinus Torvalds #include <asm/tlb.h>
54d6dd61c8SJeremy Fitzhardinge #include <asm/mmu_context.h>
551da177e4SLinus Torvalds 
56df529cabSJaewon Kim #define CREATE_TRACE_POINTS
57df529cabSJaewon Kim #include <trace/events/mmap.h>
58df529cabSJaewon Kim 
5942b77728SJan Beulich #include "internal.h"
6042b77728SJan Beulich 
613a459756SKirill Korotaev #ifndef arch_mmap_check
623a459756SKirill Korotaev #define arch_mmap_check(addr, len, flags)	(0)
633a459756SKirill Korotaev #endif
643a459756SKirill Korotaev 
65d07e2259SDaniel Cashman #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
66d07e2259SDaniel Cashman const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
67d07e2259SDaniel Cashman const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
68d07e2259SDaniel Cashman int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
69d07e2259SDaniel Cashman #endif
70d07e2259SDaniel Cashman #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
71d07e2259SDaniel Cashman const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
72d07e2259SDaniel Cashman const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
73d07e2259SDaniel Cashman int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
74d07e2259SDaniel Cashman #endif
75d07e2259SDaniel Cashman 
76f4fcd558SKonstantin Khlebnikov static bool ignore_rlimit_data;
77d977d56cSKonstantin Khlebnikov core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
78d07e2259SDaniel Cashman 
79fd892593SLiam R. Howlett static void unmap_region(struct mm_struct *mm, struct ma_state *mas,
80e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
81763ecb03SLiam R. Howlett 		struct vm_area_struct *next, unsigned long start,
82fd892593SLiam R. Howlett 		unsigned long end, unsigned long tree_end, bool mm_wr_locked);
83e0da382cSHugh Dickins 
8464e45507SPeter Feiner static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
8564e45507SPeter Feiner {
8664e45507SPeter Feiner 	return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
8764e45507SPeter Feiner }
8864e45507SPeter Feiner 
8964e45507SPeter Feiner /* Update vma->vm_page_prot to reflect vma->vm_flags. */
9064e45507SPeter Feiner void vma_set_page_prot(struct vm_area_struct *vma)
9164e45507SPeter Feiner {
9264e45507SPeter Feiner 	unsigned long vm_flags = vma->vm_flags;
936d2329f8SAndrea Arcangeli 	pgprot_t vm_page_prot;
9464e45507SPeter Feiner 
956d2329f8SAndrea Arcangeli 	vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
966d2329f8SAndrea Arcangeli 	if (vma_wants_writenotify(vma, vm_page_prot)) {
9764e45507SPeter Feiner 		vm_flags &= ~VM_SHARED;
986d2329f8SAndrea Arcangeli 		vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
9964e45507SPeter Feiner 	}
100c1e8d7c6SMichel Lespinasse 	/* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
1016d2329f8SAndrea Arcangeli 	WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
10264e45507SPeter Feiner }
10364e45507SPeter Feiner 
1041da177e4SLinus Torvalds /*
105c8c06efaSDavidlohr Bueso  * Requires inode->i_mapping->i_mmap_rwsem
1061da177e4SLinus Torvalds  */
1071da177e4SLinus Torvalds static void __remove_shared_vm_struct(struct vm_area_struct *vma,
1081da177e4SLinus Torvalds 		struct file *file, struct address_space *mapping)
1091da177e4SLinus Torvalds {
1101da177e4SLinus Torvalds 	if (vma->vm_flags & VM_SHARED)
1114bb5f5d9SDavid Herrmann 		mapping_unmap_writable(mapping);
1121da177e4SLinus Torvalds 
1131da177e4SLinus Torvalds 	flush_dcache_mmap_lock(mapping);
1146b2dbba8SMichel Lespinasse 	vma_interval_tree_remove(vma, &mapping->i_mmap);
1151da177e4SLinus Torvalds 	flush_dcache_mmap_unlock(mapping);
1161da177e4SLinus Torvalds }
1171da177e4SLinus Torvalds 
1181da177e4SLinus Torvalds /*
1196b2dbba8SMichel Lespinasse  * Unlink a file-based vm structure from its interval tree, to hide
120a8fb5618SHugh Dickins  * vma from rmap and vmtruncate before freeing its page tables.
1211da177e4SLinus Torvalds  */
122a8fb5618SHugh Dickins void unlink_file_vma(struct vm_area_struct *vma)
1231da177e4SLinus Torvalds {
1241da177e4SLinus Torvalds 	struct file *file = vma->vm_file;
1251da177e4SLinus Torvalds 
1261da177e4SLinus Torvalds 	if (file) {
1271da177e4SLinus Torvalds 		struct address_space *mapping = file->f_mapping;
12883cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
1291da177e4SLinus Torvalds 		__remove_shared_vm_struct(vma, file, mapping);
13083cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
1311da177e4SLinus Torvalds 	}
132a8fb5618SHugh Dickins }
133a8fb5618SHugh Dickins 
134a8fb5618SHugh Dickins /*
135763ecb03SLiam R. Howlett  * Close a vm structure and free it.
136a8fb5618SHugh Dickins  */
1370d2ebf9cSSuren Baghdasaryan static void remove_vma(struct vm_area_struct *vma, bool unreachable)
138a8fb5618SHugh Dickins {
139a8fb5618SHugh Dickins 	might_sleep();
1401da177e4SLinus Torvalds 	if (vma->vm_ops && vma->vm_ops->close)
1411da177e4SLinus Torvalds 		vma->vm_ops->close(vma);
142e9714acfSKonstantin Khlebnikov 	if (vma->vm_file)
143a8fb5618SHugh Dickins 		fput(vma->vm_file);
144f0be3d32SLee Schermerhorn 	mpol_put(vma_policy(vma));
1450d2ebf9cSSuren Baghdasaryan 	if (unreachable)
1460d2ebf9cSSuren Baghdasaryan 		__vm_area_free(vma);
1470d2ebf9cSSuren Baghdasaryan 	else
1483928d4f5SLinus Torvalds 		vm_area_free(vma);
1491da177e4SLinus Torvalds }
1501da177e4SLinus Torvalds 
151b62b633eSLiam R. Howlett static inline struct vm_area_struct *vma_prev_limit(struct vma_iterator *vmi,
152b62b633eSLiam R. Howlett 						    unsigned long min)
153b62b633eSLiam R. Howlett {
154b62b633eSLiam R. Howlett 	return mas_prev(&vmi->mas, min);
155b62b633eSLiam R. Howlett }
156b62b633eSLiam R. Howlett 
157b62b633eSLiam R. Howlett static inline int vma_iter_clear_gfp(struct vma_iterator *vmi,
158b62b633eSLiam R. Howlett 			unsigned long start, unsigned long end, gfp_t gfp)
159b62b633eSLiam R. Howlett {
160b62b633eSLiam R. Howlett 	vmi->mas.index = start;
161b62b633eSLiam R. Howlett 	vmi->mas.last = end - 1;
162b62b633eSLiam R. Howlett 	mas_store_gfp(&vmi->mas, NULL, gfp);
163b62b633eSLiam R. Howlett 	if (unlikely(mas_is_err(&vmi->mas)))
164b62b633eSLiam R. Howlett 		return -ENOMEM;
165b62b633eSLiam R. Howlett 
166b62b633eSLiam R. Howlett 	return 0;
167b62b633eSLiam R. Howlett }
168b62b633eSLiam R. Howlett 
1692e7ce7d3SLiam R. Howlett /*
1702e7ce7d3SLiam R. Howlett  * check_brk_limits() - Use platform specific check of range & verify mlock
1712e7ce7d3SLiam R. Howlett  * limits.
1722e7ce7d3SLiam R. Howlett  * @addr: The address to check
1732e7ce7d3SLiam R. Howlett  * @len: The size of increase.
1742e7ce7d3SLiam R. Howlett  *
1752e7ce7d3SLiam R. Howlett  * Return: 0 on success.
1762e7ce7d3SLiam R. Howlett  */
1772e7ce7d3SLiam R. Howlett static int check_brk_limits(unsigned long addr, unsigned long len)
1782e7ce7d3SLiam R. Howlett {
1792e7ce7d3SLiam R. Howlett 	unsigned long mapped_addr;
1802e7ce7d3SLiam R. Howlett 
1812e7ce7d3SLiam R. Howlett 	mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
1822e7ce7d3SLiam R. Howlett 	if (IS_ERR_VALUE(mapped_addr))
1832e7ce7d3SLiam R. Howlett 		return mapped_addr;
1842e7ce7d3SLiam R. Howlett 
185b0cc5e89SAndrew Morton 	return mlock_future_ok(current->mm, current->mm->def_flags, len)
1863c54a298SLorenzo Stoakes 		? 0 : -EAGAIN;
1872e7ce7d3SLiam R. Howlett }
18892fed820SLiam R. Howlett static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma,
189763ecb03SLiam R. Howlett 		unsigned long addr, unsigned long request, unsigned long flags);
1906a6160a7SHeiko Carstens SYSCALL_DEFINE1(brk, unsigned long, brk)
1911da177e4SLinus Torvalds {
1929bc8039eSYang Shi 	unsigned long newbrk, oldbrk, origbrk;
1931da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1942e7ce7d3SLiam R. Howlett 	struct vm_area_struct *brkvma, *next = NULL;
195a5b4592cSJiri Kosina 	unsigned long min_brk;
196408579cdSLiam R. Howlett 	bool populate = false;
197897ab3e0SMike Rapoport 	LIST_HEAD(uf);
19892fed820SLiam R. Howlett 	struct vma_iterator vmi;
1991da177e4SLinus Torvalds 
200d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
201dc0ef0dfSMichal Hocko 		return -EINTR;
2021da177e4SLinus Torvalds 
2039bc8039eSYang Shi 	origbrk = mm->brk;
2049bc8039eSYang Shi 
205a5b4592cSJiri Kosina #ifdef CONFIG_COMPAT_BRK
2065520e894SJiri Kosina 	/*
2075520e894SJiri Kosina 	 * CONFIG_COMPAT_BRK can still be overridden by setting
2085520e894SJiri Kosina 	 * randomize_va_space to 2, which will still cause mm->start_brk
2095520e894SJiri Kosina 	 * to be arbitrarily shifted
2105520e894SJiri Kosina 	 */
2114471a675SJiri Kosina 	if (current->brk_randomized)
2125520e894SJiri Kosina 		min_brk = mm->start_brk;
2135520e894SJiri Kosina 	else
2145520e894SJiri Kosina 		min_brk = mm->end_data;
215a5b4592cSJiri Kosina #else
216a5b4592cSJiri Kosina 	min_brk = mm->start_brk;
217a5b4592cSJiri Kosina #endif
218a5b4592cSJiri Kosina 	if (brk < min_brk)
2191da177e4SLinus Torvalds 		goto out;
2201e624196SRam Gupta 
2211e624196SRam Gupta 	/*
2221e624196SRam Gupta 	 * Check against rlimit here. If this check is done later after the test
2231e624196SRam Gupta 	 * of oldbrk with newbrk then it can escape the test and let the data
2241e624196SRam Gupta 	 * segment grow beyond its set limit the in case where the limit is
2251e624196SRam Gupta 	 * not page aligned -Ram Gupta
2261e624196SRam Gupta 	 */
2278764b338SCyrill Gorcunov 	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
2288764b338SCyrill Gorcunov 			      mm->end_data, mm->start_data))
2291e624196SRam Gupta 		goto out;
2301e624196SRam Gupta 
2311da177e4SLinus Torvalds 	newbrk = PAGE_ALIGN(brk);
2321da177e4SLinus Torvalds 	oldbrk = PAGE_ALIGN(mm->brk);
2339bc8039eSYang Shi 	if (oldbrk == newbrk) {
2349bc8039eSYang Shi 		mm->brk = brk;
2359bc8039eSYang Shi 		goto success;
2369bc8039eSYang Shi 	}
2371da177e4SLinus Torvalds 
238408579cdSLiam R. Howlett 	/* Always allow shrinking brk. */
2391da177e4SLinus Torvalds 	if (brk <= mm->brk) {
2402e7ce7d3SLiam R. Howlett 		/* Search one past newbrk */
24192fed820SLiam R. Howlett 		vma_iter_init(&vmi, mm, newbrk);
24292fed820SLiam R. Howlett 		brkvma = vma_find(&vmi, oldbrk);
243f5ad5083SJason A. Donenfeld 		if (!brkvma || brkvma->vm_start >= oldbrk)
2442e7ce7d3SLiam R. Howlett 			goto out; /* mapping intersects with an existing non-brk vma. */
2459bc8039eSYang Shi 		/*
2462e7ce7d3SLiam R. Howlett 		 * mm->brk must be protected by write mmap_lock.
247408579cdSLiam R. Howlett 		 * do_vma_munmap() will drop the lock on success,  so update it
24827b26701SLiam R. Howlett 		 * before calling do_vma_munmap().
2499bc8039eSYang Shi 		 */
2509bc8039eSYang Shi 		mm->brk = brk;
251408579cdSLiam R. Howlett 		if (do_vma_munmap(&vmi, brkvma, newbrk, oldbrk, &uf, true))
2521da177e4SLinus Torvalds 			goto out;
253408579cdSLiam R. Howlett 
254408579cdSLiam R. Howlett 		goto success_unlocked;
2551da177e4SLinus Torvalds 	}
2561da177e4SLinus Torvalds 
2572e7ce7d3SLiam R. Howlett 	if (check_brk_limits(oldbrk, newbrk - oldbrk))
2582e7ce7d3SLiam R. Howlett 		goto out;
2592e7ce7d3SLiam R. Howlett 
2602e7ce7d3SLiam R. Howlett 	/*
2612e7ce7d3SLiam R. Howlett 	 * Only check if the next VMA is within the stack_guard_gap of the
2622e7ce7d3SLiam R. Howlett 	 * expansion area
2632e7ce7d3SLiam R. Howlett 	 */
26492fed820SLiam R. Howlett 	vma_iter_init(&vmi, mm, oldbrk);
26592fed820SLiam R. Howlett 	next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
2661be7107fSHugh Dickins 	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
2671da177e4SLinus Torvalds 		goto out;
2681da177e4SLinus Torvalds 
26992fed820SLiam R. Howlett 	brkvma = vma_prev_limit(&vmi, mm->start_brk);
2701da177e4SLinus Torvalds 	/* Ok, looks good - let it rip. */
27192fed820SLiam R. Howlett 	if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
2721da177e4SLinus Torvalds 		goto out;
2732e7ce7d3SLiam R. Howlett 
2741da177e4SLinus Torvalds 	mm->brk = brk;
275408579cdSLiam R. Howlett 	if (mm->def_flags & VM_LOCKED)
276408579cdSLiam R. Howlett 		populate = true;
2779bc8039eSYang Shi 
2789bc8039eSYang Shi success:
279d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
280408579cdSLiam R. Howlett success_unlocked:
281897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
282128557ffSMichel Lespinasse 	if (populate)
283128557ffSMichel Lespinasse 		mm_populate(oldbrk, newbrk - oldbrk);
284128557ffSMichel Lespinasse 	return brk;
285128557ffSMichel Lespinasse 
2861da177e4SLinus Torvalds out:
287408579cdSLiam R. Howlett 	mm->brk = origbrk;
288d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
289b7204006SAdrian Huang 	return origbrk;
2901da177e4SLinus Torvalds }
2911da177e4SLinus Torvalds 
292d4af56c5SLiam R. Howlett #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
293eafd4dc4SRashika Kheria static void validate_mm(struct mm_struct *mm)
2941da177e4SLinus Torvalds {
2951da177e4SLinus Torvalds 	int bug = 0;
2961da177e4SLinus Torvalds 	int i = 0;
297763ecb03SLiam R. Howlett 	struct vm_area_struct *vma;
298b50e195fSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, 0);
299ff26f70fSAndrew Morton 
300b50e195fSLiam R. Howlett 	mt_validate(&mm->mm_mt);
301b50e195fSLiam R. Howlett 	for_each_vma(vmi, vma) {
302524e00b3SLiam R. Howlett #ifdef CONFIG_DEBUG_VM_RB
30312352d3cSKonstantin Khlebnikov 		struct anon_vma *anon_vma = vma->anon_vma;
304ed8ea815SMichel Lespinasse 		struct anon_vma_chain *avc;
305b50e195fSLiam R. Howlett #endif
306b50e195fSLiam R. Howlett 		unsigned long vmi_start, vmi_end;
307b50e195fSLiam R. Howlett 		bool warn = 0;
308ff26f70fSAndrew Morton 
309b50e195fSLiam R. Howlett 		vmi_start = vma_iter_addr(&vmi);
310b50e195fSLiam R. Howlett 		vmi_end = vma_iter_end(&vmi);
311b50e195fSLiam R. Howlett 		if (VM_WARN_ON_ONCE_MM(vma->vm_end != vmi_end, mm))
312b50e195fSLiam R. Howlett 			warn = 1;
313b50e195fSLiam R. Howlett 
314b50e195fSLiam R. Howlett 		if (VM_WARN_ON_ONCE_MM(vma->vm_start != vmi_start, mm))
315b50e195fSLiam R. Howlett 			warn = 1;
316b50e195fSLiam R. Howlett 
317b50e195fSLiam R. Howlett 		if (warn) {
318b50e195fSLiam R. Howlett 			pr_emerg("issue in %s\n", current->comm);
319b50e195fSLiam R. Howlett 			dump_stack();
320b50e195fSLiam R. Howlett 			dump_vma(vma);
321b50e195fSLiam R. Howlett 			pr_emerg("tree range: %px start %lx end %lx\n", vma,
322b50e195fSLiam R. Howlett 				 vmi_start, vmi_end - 1);
323b50e195fSLiam R. Howlett 			vma_iter_dump_tree(&vmi);
324b50e195fSLiam R. Howlett 		}
325b50e195fSLiam R. Howlett 
326b50e195fSLiam R. Howlett #ifdef CONFIG_DEBUG_VM_RB
32712352d3cSKonstantin Khlebnikov 		if (anon_vma) {
32812352d3cSKonstantin Khlebnikov 			anon_vma_lock_read(anon_vma);
329ed8ea815SMichel Lespinasse 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
330ed8ea815SMichel Lespinasse 				anon_vma_interval_tree_verify(avc);
33112352d3cSKonstantin Khlebnikov 			anon_vma_unlock_read(anon_vma);
33212352d3cSKonstantin Khlebnikov 		}
333524e00b3SLiam R. Howlett #endif
3341da177e4SLinus Torvalds 		i++;
3351da177e4SLinus Torvalds 	}
3365a0768f6SMichel Lespinasse 	if (i != mm->map_count) {
337b50e195fSLiam R. Howlett 		pr_emerg("map_count %d vma iterator %d\n", mm->map_count, i);
3385a0768f6SMichel Lespinasse 		bug = 1;
3395a0768f6SMichel Lespinasse 	}
34096dad67fSSasha Levin 	VM_BUG_ON_MM(bug, mm);
3411da177e4SLinus Torvalds }
342524e00b3SLiam R. Howlett 
343524e00b3SLiam R. Howlett #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
3441da177e4SLinus Torvalds #define validate_mm(mm) do { } while (0)
345524e00b3SLiam R. Howlett #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
346d3737187SMichel Lespinasse 
347bf181b9fSMichel Lespinasse /*
348bf181b9fSMichel Lespinasse  * vma has some anon_vma assigned, and is already inserted on that
349bf181b9fSMichel Lespinasse  * anon_vma's interval trees.
350bf181b9fSMichel Lespinasse  *
351bf181b9fSMichel Lespinasse  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
352bf181b9fSMichel Lespinasse  * vma must be removed from the anon_vma's interval trees using
353bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_pre_update_vma().
354bf181b9fSMichel Lespinasse  *
355bf181b9fSMichel Lespinasse  * After the update, the vma will be reinserted using
356bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_post_update_vma().
357bf181b9fSMichel Lespinasse  *
358c1e8d7c6SMichel Lespinasse  * The entire update must be protected by exclusive mmap_lock and by
359bf181b9fSMichel Lespinasse  * the root anon_vma's mutex.
360bf181b9fSMichel Lespinasse  */
361bf181b9fSMichel Lespinasse static inline void
362bf181b9fSMichel Lespinasse anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
363bf181b9fSMichel Lespinasse {
364bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
365bf181b9fSMichel Lespinasse 
366bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
367bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
368bf181b9fSMichel Lespinasse }
369bf181b9fSMichel Lespinasse 
370bf181b9fSMichel Lespinasse static inline void
371bf181b9fSMichel Lespinasse anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
372bf181b9fSMichel Lespinasse {
373bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
374bf181b9fSMichel Lespinasse 
375bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
376bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
377bf181b9fSMichel Lespinasse }
378bf181b9fSMichel Lespinasse 
379e8420a8eSCyril Hrubis static unsigned long count_vma_pages_range(struct mm_struct *mm,
380e8420a8eSCyril Hrubis 		unsigned long addr, unsigned long end)
381e8420a8eSCyril Hrubis {
3822e3af1dbSMatthew Wilcox (Oracle) 	VMA_ITERATOR(vmi, mm, addr);
383e8420a8eSCyril Hrubis 	struct vm_area_struct *vma;
3842e3af1dbSMatthew Wilcox (Oracle) 	unsigned long nr_pages = 0;
385e8420a8eSCyril Hrubis 
3862e3af1dbSMatthew Wilcox (Oracle) 	for_each_vma_range(vmi, vma, end) {
3872e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_start = max(addr, vma->vm_start);
3882e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_end = min(end, vma->vm_end);
389e8420a8eSCyril Hrubis 
3902e3af1dbSMatthew Wilcox (Oracle) 		nr_pages += PHYS_PFN(vm_end - vm_start);
391e8420a8eSCyril Hrubis 	}
392e8420a8eSCyril Hrubis 
393e8420a8eSCyril Hrubis 	return nr_pages;
394e8420a8eSCyril Hrubis }
395e8420a8eSCyril Hrubis 
396c154124fSLiam R. Howlett static void __vma_link_file(struct vm_area_struct *vma,
397c154124fSLiam R. Howlett 			    struct address_space *mapping)
3981da177e4SLinus Torvalds {
3991da177e4SLinus Torvalds 	if (vma->vm_flags & VM_SHARED)
400cf508b58SMiaohe Lin 		mapping_allow_writable(mapping);
4011da177e4SLinus Torvalds 
4021da177e4SLinus Torvalds 	flush_dcache_mmap_lock(mapping);
4036b2dbba8SMichel Lespinasse 	vma_interval_tree_insert(vma, &mapping->i_mmap);
4041da177e4SLinus Torvalds 	flush_dcache_mmap_unlock(mapping);
4051da177e4SLinus Torvalds }
4061da177e4SLinus Torvalds 
407763ecb03SLiam R. Howlett static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
4081da177e4SLinus Torvalds {
40979e4f2caSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, 0);
4101da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
4111da177e4SLinus Torvalds 
41279e4f2caSLiam R. Howlett 	if (vma_iter_prealloc(&vmi))
413d4af56c5SLiam R. Howlett 		return -ENOMEM;
414d4af56c5SLiam R. Howlett 
4156852c46cSYu Ma 	vma_iter_store(&vmi, vma);
4166852c46cSYu Ma 
41764ac4940SHuang Shijie 	if (vma->vm_file) {
4181da177e4SLinus Torvalds 		mapping = vma->vm_file->f_mapping;
41983cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
420c154124fSLiam R. Howlett 		__vma_link_file(vma, mapping);
42183cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
422c154124fSLiam R. Howlett 	}
4231da177e4SLinus Torvalds 
4241da177e4SLinus Torvalds 	mm->map_count++;
4251da177e4SLinus Torvalds 	validate_mm(mm);
426d4af56c5SLiam R. Howlett 	return 0;
4271da177e4SLinus Torvalds }
4281da177e4SLinus Torvalds 
4291da177e4SLinus Torvalds /*
43068cefec5SLiam R. Howlett  * init_multi_vma_prep() - Initializer for struct vma_prepare
43168cefec5SLiam R. Howlett  * @vp: The vma_prepare struct
43268cefec5SLiam R. Howlett  * @vma: The vma that will be altered once locked
43368cefec5SLiam R. Howlett  * @next: The next vma if it is to be adjusted
43468cefec5SLiam R. Howlett  * @remove: The first vma to be removed
43568cefec5SLiam R. Howlett  * @remove2: The second vma to be removed
43668cefec5SLiam R. Howlett  */
43768cefec5SLiam R. Howlett static inline void init_multi_vma_prep(struct vma_prepare *vp,
43868cefec5SLiam R. Howlett 		struct vm_area_struct *vma, struct vm_area_struct *next,
43968cefec5SLiam R. Howlett 		struct vm_area_struct *remove, struct vm_area_struct *remove2)
44068cefec5SLiam R. Howlett {
44168cefec5SLiam R. Howlett 	memset(vp, 0, sizeof(struct vma_prepare));
44268cefec5SLiam R. Howlett 	vp->vma = vma;
44368cefec5SLiam R. Howlett 	vp->anon_vma = vma->anon_vma;
44468cefec5SLiam R. Howlett 	vp->remove = remove;
44568cefec5SLiam R. Howlett 	vp->remove2 = remove2;
44668cefec5SLiam R. Howlett 	vp->adj_next = next;
44768cefec5SLiam R. Howlett 	if (!vp->anon_vma && next)
44868cefec5SLiam R. Howlett 		vp->anon_vma = next->anon_vma;
44968cefec5SLiam R. Howlett 
45068cefec5SLiam R. Howlett 	vp->file = vma->vm_file;
45168cefec5SLiam R. Howlett 	if (vp->file)
45268cefec5SLiam R. Howlett 		vp->mapping = vma->vm_file->f_mapping;
45368cefec5SLiam R. Howlett 
45468cefec5SLiam R. Howlett }
45568cefec5SLiam R. Howlett 
45668cefec5SLiam R. Howlett /*
45768cefec5SLiam R. Howlett  * init_vma_prep() - Initializer wrapper for vma_prepare struct
45868cefec5SLiam R. Howlett  * @vp: The vma_prepare struct
45968cefec5SLiam R. Howlett  * @vma: The vma that will be altered once locked
46068cefec5SLiam R. Howlett  */
46168cefec5SLiam R. Howlett static inline void init_vma_prep(struct vma_prepare *vp,
46268cefec5SLiam R. Howlett 				 struct vm_area_struct *vma)
46368cefec5SLiam R. Howlett {
46468cefec5SLiam R. Howlett 	init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
46568cefec5SLiam R. Howlett }
46668cefec5SLiam R. Howlett 
46768cefec5SLiam R. Howlett 
46868cefec5SLiam R. Howlett /*
469440703e0SLiam R. Howlett  * vma_prepare() - Helper function for handling locking VMAs prior to altering
470440703e0SLiam R. Howlett  * @vp: The initialized vma_prepare struct
471440703e0SLiam R. Howlett  */
472440703e0SLiam R. Howlett static inline void vma_prepare(struct vma_prepare *vp)
473440703e0SLiam R. Howlett {
47410fca64aSSuren Baghdasaryan 	vma_start_write(vp->vma);
47510fca64aSSuren Baghdasaryan 	if (vp->adj_next)
47610fca64aSSuren Baghdasaryan 		vma_start_write(vp->adj_next);
47710fca64aSSuren Baghdasaryan 	/* vp->insert is always a newly created VMA, no need for locking */
47810fca64aSSuren Baghdasaryan 	if (vp->remove)
47910fca64aSSuren Baghdasaryan 		vma_start_write(vp->remove);
48010fca64aSSuren Baghdasaryan 	if (vp->remove2)
48110fca64aSSuren Baghdasaryan 		vma_start_write(vp->remove2);
48210fca64aSSuren Baghdasaryan 
483440703e0SLiam R. Howlett 	if (vp->file) {
484440703e0SLiam R. Howlett 		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
485440703e0SLiam R. Howlett 
486440703e0SLiam R. Howlett 		if (vp->adj_next)
487440703e0SLiam R. Howlett 			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
488440703e0SLiam R. Howlett 				      vp->adj_next->vm_end);
489440703e0SLiam R. Howlett 
490440703e0SLiam R. Howlett 		i_mmap_lock_write(vp->mapping);
491440703e0SLiam R. Howlett 		if (vp->insert && vp->insert->vm_file) {
492440703e0SLiam R. Howlett 			/*
493440703e0SLiam R. Howlett 			 * Put into interval tree now, so instantiated pages
494440703e0SLiam R. Howlett 			 * are visible to arm/parisc __flush_dcache_page
495440703e0SLiam R. Howlett 			 * throughout; but we cannot insert into address
496440703e0SLiam R. Howlett 			 * space until vma start or end is updated.
497440703e0SLiam R. Howlett 			 */
498440703e0SLiam R. Howlett 			__vma_link_file(vp->insert,
499440703e0SLiam R. Howlett 					vp->insert->vm_file->f_mapping);
500440703e0SLiam R. Howlett 		}
501440703e0SLiam R. Howlett 	}
502440703e0SLiam R. Howlett 
503440703e0SLiam R. Howlett 	if (vp->anon_vma) {
504440703e0SLiam R. Howlett 		anon_vma_lock_write(vp->anon_vma);
505440703e0SLiam R. Howlett 		anon_vma_interval_tree_pre_update_vma(vp->vma);
506440703e0SLiam R. Howlett 		if (vp->adj_next)
507440703e0SLiam R. Howlett 			anon_vma_interval_tree_pre_update_vma(vp->adj_next);
508440703e0SLiam R. Howlett 	}
509440703e0SLiam R. Howlett 
510440703e0SLiam R. Howlett 	if (vp->file) {
511440703e0SLiam R. Howlett 		flush_dcache_mmap_lock(vp->mapping);
512440703e0SLiam R. Howlett 		vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
513440703e0SLiam R. Howlett 		if (vp->adj_next)
514440703e0SLiam R. Howlett 			vma_interval_tree_remove(vp->adj_next,
515440703e0SLiam R. Howlett 						 &vp->mapping->i_mmap);
516440703e0SLiam R. Howlett 	}
517440703e0SLiam R. Howlett 
518440703e0SLiam R. Howlett }
519440703e0SLiam R. Howlett 
520440703e0SLiam R. Howlett /*
521440703e0SLiam R. Howlett  * vma_complete- Helper function for handling the unlocking after altering VMAs,
522440703e0SLiam R. Howlett  * or for inserting a VMA.
523440703e0SLiam R. Howlett  *
524440703e0SLiam R. Howlett  * @vp: The vma_prepare struct
525440703e0SLiam R. Howlett  * @vmi: The vma iterator
526440703e0SLiam R. Howlett  * @mm: The mm_struct
527440703e0SLiam R. Howlett  */
528440703e0SLiam R. Howlett static inline void vma_complete(struct vma_prepare *vp,
529440703e0SLiam R. Howlett 				struct vma_iterator *vmi, struct mm_struct *mm)
530440703e0SLiam R. Howlett {
531440703e0SLiam R. Howlett 	if (vp->file) {
532440703e0SLiam R. Howlett 		if (vp->adj_next)
533440703e0SLiam R. Howlett 			vma_interval_tree_insert(vp->adj_next,
534440703e0SLiam R. Howlett 						 &vp->mapping->i_mmap);
535440703e0SLiam R. Howlett 		vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
536440703e0SLiam R. Howlett 		flush_dcache_mmap_unlock(vp->mapping);
537440703e0SLiam R. Howlett 	}
538440703e0SLiam R. Howlett 
539440703e0SLiam R. Howlett 	if (vp->remove && vp->file) {
540440703e0SLiam R. Howlett 		__remove_shared_vm_struct(vp->remove, vp->file, vp->mapping);
541440703e0SLiam R. Howlett 		if (vp->remove2)
542440703e0SLiam R. Howlett 			__remove_shared_vm_struct(vp->remove2, vp->file,
543440703e0SLiam R. Howlett 						  vp->mapping);
544440703e0SLiam R. Howlett 	} else if (vp->insert) {
545440703e0SLiam R. Howlett 		/*
546440703e0SLiam R. Howlett 		 * split_vma has split insert from vma, and needs
547440703e0SLiam R. Howlett 		 * us to insert it before dropping the locks
548440703e0SLiam R. Howlett 		 * (it may either follow vma or precede it).
549440703e0SLiam R. Howlett 		 */
550440703e0SLiam R. Howlett 		vma_iter_store(vmi, vp->insert);
551440703e0SLiam R. Howlett 		mm->map_count++;
552440703e0SLiam R. Howlett 	}
553440703e0SLiam R. Howlett 
554440703e0SLiam R. Howlett 	if (vp->anon_vma) {
555440703e0SLiam R. Howlett 		anon_vma_interval_tree_post_update_vma(vp->vma);
556440703e0SLiam R. Howlett 		if (vp->adj_next)
557440703e0SLiam R. Howlett 			anon_vma_interval_tree_post_update_vma(vp->adj_next);
558440703e0SLiam R. Howlett 		anon_vma_unlock_write(vp->anon_vma);
559440703e0SLiam R. Howlett 	}
560440703e0SLiam R. Howlett 
561440703e0SLiam R. Howlett 	if (vp->file) {
562440703e0SLiam R. Howlett 		i_mmap_unlock_write(vp->mapping);
563440703e0SLiam R. Howlett 		uprobe_mmap(vp->vma);
564440703e0SLiam R. Howlett 
565440703e0SLiam R. Howlett 		if (vp->adj_next)
566440703e0SLiam R. Howlett 			uprobe_mmap(vp->adj_next);
567440703e0SLiam R. Howlett 	}
568440703e0SLiam R. Howlett 
569440703e0SLiam R. Howlett 	if (vp->remove) {
570440703e0SLiam R. Howlett again:
571457f67beSSuren Baghdasaryan 		vma_mark_detached(vp->remove, true);
572440703e0SLiam R. Howlett 		if (vp->file) {
573440703e0SLiam R. Howlett 			uprobe_munmap(vp->remove, vp->remove->vm_start,
574440703e0SLiam R. Howlett 				      vp->remove->vm_end);
575440703e0SLiam R. Howlett 			fput(vp->file);
576440703e0SLiam R. Howlett 		}
577440703e0SLiam R. Howlett 		if (vp->remove->anon_vma)
578440703e0SLiam R. Howlett 			anon_vma_merge(vp->vma, vp->remove);
579440703e0SLiam R. Howlett 		mm->map_count--;
580440703e0SLiam R. Howlett 		mpol_put(vma_policy(vp->remove));
581440703e0SLiam R. Howlett 		if (!vp->remove2)
582440703e0SLiam R. Howlett 			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
583440703e0SLiam R. Howlett 		vm_area_free(vp->remove);
584440703e0SLiam R. Howlett 
585440703e0SLiam R. Howlett 		/*
586440703e0SLiam R. Howlett 		 * In mprotect's case 6 (see comments on vma_merge),
5875ff783f1SVlastimil Babka 		 * we are removing both mid and next vmas
588440703e0SLiam R. Howlett 		 */
589440703e0SLiam R. Howlett 		if (vp->remove2) {
590440703e0SLiam R. Howlett 			vp->remove = vp->remove2;
591440703e0SLiam R. Howlett 			vp->remove2 = NULL;
592440703e0SLiam R. Howlett 			goto again;
593440703e0SLiam R. Howlett 		}
594440703e0SLiam R. Howlett 	}
595440703e0SLiam R. Howlett 	if (vp->insert && vp->file)
596440703e0SLiam R. Howlett 		uprobe_mmap(vp->insert);
5972574d5e4SLiam R. Howlett 	validate_mm(mm);
598440703e0SLiam R. Howlett }
599440703e0SLiam R. Howlett 
600440703e0SLiam R. Howlett /*
60104241ffeSLiam R. Howlett  * dup_anon_vma() - Helper function to duplicate anon_vma
60204241ffeSLiam R. Howlett  * @dst: The destination VMA
60304241ffeSLiam R. Howlett  * @src: The source VMA
60404241ffeSLiam R. Howlett  *
60504241ffeSLiam R. Howlett  * Returns: 0 on success.
60604241ffeSLiam R. Howlett  */
60704241ffeSLiam R. Howlett static inline int dup_anon_vma(struct vm_area_struct *dst,
60804241ffeSLiam R. Howlett 			       struct vm_area_struct *src)
60904241ffeSLiam R. Howlett {
61004241ffeSLiam R. Howlett 	/*
61104241ffeSLiam R. Howlett 	 * Easily overlooked: when mprotect shifts the boundary, make sure the
61204241ffeSLiam R. Howlett 	 * expanding vma has anon_vma set if the shrinking vma had, to cover any
61304241ffeSLiam R. Howlett 	 * anon pages imported.
61404241ffeSLiam R. Howlett 	 */
61504241ffeSLiam R. Howlett 	if (src->anon_vma && !dst->anon_vma) {
616d8ab9f7bSJann Horn 		vma_start_write(dst);
61704241ffeSLiam R. Howlett 		dst->anon_vma = src->anon_vma;
61804241ffeSLiam R. Howlett 		return anon_vma_clone(dst, src);
61904241ffeSLiam R. Howlett 	}
62004241ffeSLiam R. Howlett 
62104241ffeSLiam R. Howlett 	return 0;
62204241ffeSLiam R. Howlett }
62304241ffeSLiam R. Howlett 
62404241ffeSLiam R. Howlett /*
6259303d3e1SLiam R. Howlett  * vma_expand - Expand an existing VMA
6269303d3e1SLiam R. Howlett  *
6279303d3e1SLiam R. Howlett  * @vmi: The vma iterator
6289303d3e1SLiam R. Howlett  * @vma: The vma to expand
6299303d3e1SLiam R. Howlett  * @start: The start of the vma
6309303d3e1SLiam R. Howlett  * @end: The exclusive end of the vma
6319303d3e1SLiam R. Howlett  * @pgoff: The page offset of vma
6329303d3e1SLiam R. Howlett  * @next: The current of next vma.
6339303d3e1SLiam R. Howlett  *
6349303d3e1SLiam R. Howlett  * Expand @vma to @start and @end.  Can expand off the start and end.  Will
6359303d3e1SLiam R. Howlett  * expand over @next if it's different from @vma and @end == @next->vm_end.
6369303d3e1SLiam R. Howlett  * Checking if the @vma can expand and merge with @next needs to be handled by
6379303d3e1SLiam R. Howlett  * the caller.
6389303d3e1SLiam R. Howlett  *
6399303d3e1SLiam R. Howlett  * Returns: 0 on success
6409303d3e1SLiam R. Howlett  */
6417c9813e8SLiam R. Howlett int vma_expand(struct vma_iterator *vmi, struct vm_area_struct *vma,
6429303d3e1SLiam R. Howlett 	       unsigned long start, unsigned long end, pgoff_t pgoff,
6439303d3e1SLiam R. Howlett 	       struct vm_area_struct *next)
6449303d3e1SLiam R. Howlett {
64568cefec5SLiam R. Howlett 	bool remove_next = false;
6469303d3e1SLiam R. Howlett 	struct vma_prepare vp;
6479303d3e1SLiam R. Howlett 
6489303d3e1SLiam R. Howlett 	if (next && (vma != next) && (end == next->vm_end)) {
64904241ffeSLiam R. Howlett 		int ret;
6509303d3e1SLiam R. Howlett 
65104241ffeSLiam R. Howlett 		remove_next = true;
65204241ffeSLiam R. Howlett 		ret = dup_anon_vma(vma, next);
65304241ffeSLiam R. Howlett 		if (ret)
65404241ffeSLiam R. Howlett 			return ret;
6559303d3e1SLiam R. Howlett 	}
6569303d3e1SLiam R. Howlett 
65768cefec5SLiam R. Howlett 	init_multi_vma_prep(&vp, vma, NULL, remove_next ? next : NULL, NULL);
6589303d3e1SLiam R. Howlett 	/* Not merging but overwriting any part of next is not handled. */
6599303d3e1SLiam R. Howlett 	VM_WARN_ON(next && !vp.remove &&
6609303d3e1SLiam R. Howlett 		  next != vma && end > next->vm_start);
6619303d3e1SLiam R. Howlett 	/* Only handles expanding */
6629303d3e1SLiam R. Howlett 	VM_WARN_ON(vma->vm_start < start || vma->vm_end > end);
6639303d3e1SLiam R. Howlett 
6649303d3e1SLiam R. Howlett 	if (vma_iter_prealloc(vmi))
6659303d3e1SLiam R. Howlett 		goto nomem;
6669303d3e1SLiam R. Howlett 
667ccf1d78dSSuren Baghdasaryan 	vma_prepare(&vp);
6689303d3e1SLiam R. Howlett 	vma_adjust_trans_huge(vma, start, end, 0);
6699303d3e1SLiam R. Howlett 	/* VMA iterator points to previous, so set to start if necessary */
6709303d3e1SLiam R. Howlett 	if (vma_iter_addr(vmi) != start)
6719303d3e1SLiam R. Howlett 		vma_iter_set(vmi, start);
6729303d3e1SLiam R. Howlett 
6739303d3e1SLiam R. Howlett 	vma->vm_start = start;
6749303d3e1SLiam R. Howlett 	vma->vm_end = end;
6759303d3e1SLiam R. Howlett 	vma->vm_pgoff = pgoff;
6769303d3e1SLiam R. Howlett 	/* Note: mas must be pointing to the expanding VMA */
6779303d3e1SLiam R. Howlett 	vma_iter_store(vmi, vma);
6789303d3e1SLiam R. Howlett 
6799303d3e1SLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
6809303d3e1SLiam R. Howlett 	return 0;
6819303d3e1SLiam R. Howlett 
6829303d3e1SLiam R. Howlett nomem:
6839303d3e1SLiam R. Howlett 	return -ENOMEM;
6849303d3e1SLiam R. Howlett }
685cf51e86dSLiam R. Howlett 
686cf51e86dSLiam R. Howlett /*
687cf51e86dSLiam R. Howlett  * vma_shrink() - Reduce an existing VMAs memory area
688cf51e86dSLiam R. Howlett  * @vmi: The vma iterator
689cf51e86dSLiam R. Howlett  * @vma: The VMA to modify
690cf51e86dSLiam R. Howlett  * @start: The new start
691cf51e86dSLiam R. Howlett  * @end: The new end
692cf51e86dSLiam R. Howlett  *
693cf51e86dSLiam R. Howlett  * Returns: 0 on success, -ENOMEM otherwise
694cf51e86dSLiam R. Howlett  */
695cf51e86dSLiam R. Howlett int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
696cf51e86dSLiam R. Howlett 	       unsigned long start, unsigned long end, pgoff_t pgoff)
697cf51e86dSLiam R. Howlett {
698cf51e86dSLiam R. Howlett 	struct vma_prepare vp;
699cf51e86dSLiam R. Howlett 
700cf51e86dSLiam R. Howlett 	WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
701cf51e86dSLiam R. Howlett 
702cf51e86dSLiam R. Howlett 	if (vma_iter_prealloc(vmi))
703cf51e86dSLiam R. Howlett 		return -ENOMEM;
704cf51e86dSLiam R. Howlett 
705cf51e86dSLiam R. Howlett 	init_vma_prep(&vp, vma);
706cf51e86dSLiam R. Howlett 	vma_prepare(&vp);
707ccf1d78dSSuren Baghdasaryan 	vma_adjust_trans_huge(vma, start, end, 0);
708cf51e86dSLiam R. Howlett 
709cf51e86dSLiam R. Howlett 	if (vma->vm_start < start)
710cf51e86dSLiam R. Howlett 		vma_iter_clear(vmi, vma->vm_start, start);
711cf51e86dSLiam R. Howlett 
712cf51e86dSLiam R. Howlett 	if (vma->vm_end > end)
713cf51e86dSLiam R. Howlett 		vma_iter_clear(vmi, end, vma->vm_end);
714cf51e86dSLiam R. Howlett 
715cf51e86dSLiam R. Howlett 	vma->vm_start = start;
716cf51e86dSLiam R. Howlett 	vma->vm_end = end;
717cf51e86dSLiam R. Howlett 	vma->vm_pgoff = pgoff;
718cf51e86dSLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
719cf51e86dSLiam R. Howlett 	return 0;
720cf51e86dSLiam R. Howlett }
721cf51e86dSLiam R. Howlett 
7229303d3e1SLiam R. Howlett /*
7231da177e4SLinus Torvalds  * If the vma has a ->close operation then the driver probably needs to release
724714965caSVlastimil Babka  * per-vma resources, so we don't attempt to merge those if the caller indicates
725714965caSVlastimil Babka  * the current vma may be removed as part of the merge.
7261da177e4SLinus Torvalds  */
7272dbf4010SVlastimil Babka static inline bool is_mergeable_vma(struct vm_area_struct *vma,
72819a809afSAndrea Arcangeli 		struct file *file, unsigned long vm_flags,
7299a10064fSColin Cross 		struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
730714965caSVlastimil Babka 		struct anon_vma_name *anon_name, bool may_remove_vma)
7311da177e4SLinus Torvalds {
73234228d47SCyrill Gorcunov 	/*
73334228d47SCyrill Gorcunov 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
73434228d47SCyrill Gorcunov 	 * match the flags but dirty bit -- the caller should mark
73534228d47SCyrill Gorcunov 	 * merged VMA as dirty. If dirty bit won't be excluded from
7368bb4e7a2SWei Yang 	 * comparison, we increase pressure on the memory system forcing
73734228d47SCyrill Gorcunov 	 * the kernel to generate new VMAs when old one could be
73834228d47SCyrill Gorcunov 	 * extended instead.
73934228d47SCyrill Gorcunov 	 */
74034228d47SCyrill Gorcunov 	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
7412dbf4010SVlastimil Babka 		return false;
7421da177e4SLinus Torvalds 	if (vma->vm_file != file)
7432dbf4010SVlastimil Babka 		return false;
744714965caSVlastimil Babka 	if (may_remove_vma && vma->vm_ops && vma->vm_ops->close)
7452dbf4010SVlastimil Babka 		return false;
74619a809afSAndrea Arcangeli 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
7472dbf4010SVlastimil Babka 		return false;
7485c26f6acSSuren Baghdasaryan 	if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
7492dbf4010SVlastimil Babka 		return false;
7502dbf4010SVlastimil Babka 	return true;
7511da177e4SLinus Torvalds }
7521da177e4SLinus Torvalds 
7532dbf4010SVlastimil Babka static inline bool is_mergeable_anon_vma(struct anon_vma *anon_vma1,
7542dbf4010SVlastimil Babka 		 struct anon_vma *anon_vma2, struct vm_area_struct *vma)
7551da177e4SLinus Torvalds {
756965f55deSShaohua Li 	/*
757965f55deSShaohua Li 	 * The list_is_singular() test is to avoid merging VMA cloned from
758965f55deSShaohua Li 	 * parents. This can improve scalability caused by anon_vma lock.
759965f55deSShaohua Li 	 */
760965f55deSShaohua Li 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
761965f55deSShaohua Li 		list_is_singular(&vma->anon_vma_chain)))
7622dbf4010SVlastimil Babka 		return true;
763965f55deSShaohua Li 	return anon_vma1 == anon_vma2;
7641da177e4SLinus Torvalds }
7651da177e4SLinus Torvalds 
7661da177e4SLinus Torvalds /*
7671da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
7681da177e4SLinus Torvalds  * in front of (at a lower virtual address and file offset than) the vma.
7691da177e4SLinus Torvalds  *
7701da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
7711da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
7721da177e4SLinus Torvalds  *
7731da177e4SLinus Torvalds  * We don't check here for the merged mmap wrapping around the end of pagecache
77445e55300SPeter Collingbourne  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
7751da177e4SLinus Torvalds  * wrap, nor mmaps which cover the final page at index -1UL.
776714965caSVlastimil Babka  *
777714965caSVlastimil Babka  * We assume the vma may be removed as part of the merge.
7781da177e4SLinus Torvalds  */
7792dbf4010SVlastimil Babka static bool
7801da177e4SLinus Torvalds can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
78119a809afSAndrea Arcangeli 		struct anon_vma *anon_vma, struct file *file,
7822dbf4010SVlastimil Babka 		pgoff_t vm_pgoff, struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
7835c26f6acSSuren Baghdasaryan 		struct anon_vma_name *anon_name)
7841da177e4SLinus Torvalds {
785714965caSVlastimil Babka 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name, true) &&
786965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
7871da177e4SLinus Torvalds 		if (vma->vm_pgoff == vm_pgoff)
7882dbf4010SVlastimil Babka 			return true;
7891da177e4SLinus Torvalds 	}
7902dbf4010SVlastimil Babka 	return false;
7911da177e4SLinus Torvalds }
7921da177e4SLinus Torvalds 
7931da177e4SLinus Torvalds /*
7941da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
7951da177e4SLinus Torvalds  * beyond (at a higher virtual address and file offset than) the vma.
7961da177e4SLinus Torvalds  *
7971da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
7981da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
799714965caSVlastimil Babka  *
800714965caSVlastimil Babka  * We assume that vma is not removed as part of the merge.
8011da177e4SLinus Torvalds  */
8022dbf4010SVlastimil Babka static bool
8031da177e4SLinus Torvalds can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
80419a809afSAndrea Arcangeli 		struct anon_vma *anon_vma, struct file *file,
8052dbf4010SVlastimil Babka 		pgoff_t vm_pgoff, struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
8065c26f6acSSuren Baghdasaryan 		struct anon_vma_name *anon_name)
8071da177e4SLinus Torvalds {
808714965caSVlastimil Babka 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name, false) &&
809965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
8101da177e4SLinus Torvalds 		pgoff_t vm_pglen;
811d6e93217SLibin 		vm_pglen = vma_pages(vma);
8121da177e4SLinus Torvalds 		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
8132dbf4010SVlastimil Babka 			return true;
8141da177e4SLinus Torvalds 	}
8152dbf4010SVlastimil Babka 	return false;
8161da177e4SLinus Torvalds }
8171da177e4SLinus Torvalds 
8181da177e4SLinus Torvalds /*
8199a10064fSColin Cross  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
8209a10064fSColin Cross  * figure out whether that can be merged with its predecessor or its
8219a10064fSColin Cross  * successor.  Or both (it neatly fills a hole).
8221da177e4SLinus Torvalds  *
8231da177e4SLinus Torvalds  * In most cases - when called for mmap, brk or mremap - [addr,end) is
8241da177e4SLinus Torvalds  * certain not to be mapped by the time vma_merge is called; but when
8251da177e4SLinus Torvalds  * called for mprotect, it is certain to be already mapped (either at
8261da177e4SLinus Torvalds  * an offset within prev, or at the start of next), and the flags of
8271da177e4SLinus Torvalds  * this area are about to be changed to vm_flags - and the no-change
8281da177e4SLinus Torvalds  * case has already been eliminated.
8291da177e4SLinus Torvalds  *
830fcfccd91SLorenzo Stoakes  * The following mprotect cases have to be considered, where **** is
8311da177e4SLinus Torvalds  * the area passed down from mprotect_fixup, never extending beyond one
832fcfccd91SLorenzo Stoakes  * vma, PPPP is the previous vma, CCCC is a concurrent vma that starts
833fcfccd91SLorenzo Stoakes  * at the same address as **** and is of the same or larger span, and
834fcfccd91SLorenzo Stoakes  * NNNN the next vma after ****:
8351da177e4SLinus Torvalds  *
836fcfccd91SLorenzo Stoakes  *     ****             ****                   ****
837fcfccd91SLorenzo Stoakes  *    PPPPPPNNNNNN    PPPPPPNNNNNN       PPPPPPCCCCCC
8385d42ab29SWei Yang  *    cannot merge    might become       might become
839fcfccd91SLorenzo Stoakes  *                    PPNNNNNNNNNN       PPPPPPPPPPCC
8405d42ab29SWei Yang  *    mmap, brk or    case 4 below       case 5 below
8415d42ab29SWei Yang  *    mremap move:
842fcfccd91SLorenzo Stoakes  *                        ****               ****
843fcfccd91SLorenzo Stoakes  *                    PPPP    NNNN       PPPPCCCCNNNN
8445d42ab29SWei Yang  *                    might become       might become
8455d42ab29SWei Yang  *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
846fcfccd91SLorenzo Stoakes  *                    PPPPPPPPNNNN 2 or  PPPPPPPPNNNN 7 or
847fcfccd91SLorenzo Stoakes  *                    PPPPNNNNNNNN 3     PPPPNNNNNNNN 8
8481da177e4SLinus Torvalds  *
849fcfccd91SLorenzo Stoakes  * It is important for case 8 that the vma CCCC overlapping the
850fcfccd91SLorenzo Stoakes  * region **** is never going to extended over NNNN. Instead NNNN must
851fcfccd91SLorenzo Stoakes  * be extended in region **** and CCCC must be removed. This way in
8520503ea8fSLiam R. Howlett  * all cases where vma_merge succeeds, the moment vma_merge drops the
853e86f15eeSAndrea Arcangeli  * rmap_locks, the properties of the merged vma will be already
854e86f15eeSAndrea Arcangeli  * correct for the whole merged range. Some of those properties like
855e86f15eeSAndrea Arcangeli  * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
856e86f15eeSAndrea Arcangeli  * be correct for the whole merged range immediately after the
857fcfccd91SLorenzo Stoakes  * rmap_locks are released. Otherwise if NNNN would be removed and
858fcfccd91SLorenzo Stoakes  * CCCC would be extended over the NNNN range, remove_migration_ptes
859e86f15eeSAndrea Arcangeli  * or other rmap walkers (if working on addresses beyond the "end"
860fcfccd91SLorenzo Stoakes  * parameter) may establish ptes with the wrong permissions of CCCC
861fcfccd91SLorenzo Stoakes  * instead of the right permissions of NNNN.
8620503ea8fSLiam R. Howlett  *
8630503ea8fSLiam R. Howlett  * In the code below:
8640503ea8fSLiam R. Howlett  * PPPP is represented by *prev
865fcfccd91SLorenzo Stoakes  * CCCC is represented by *curr or not represented at all (NULL)
866fcfccd91SLorenzo Stoakes  * NNNN is represented by *next or not represented at all (NULL)
867fcfccd91SLorenzo Stoakes  * **** is not represented - it will be merged and the vma containing the
8689e8a39d2SVlastimil Babka  *      area is returned, or the function will return NULL
8691da177e4SLinus Torvalds  */
8709760ebffSLiam R. Howlett struct vm_area_struct *vma_merge(struct vma_iterator *vmi, struct mm_struct *mm,
8711da177e4SLinus Torvalds 			struct vm_area_struct *prev, unsigned long addr,
8721da177e4SLinus Torvalds 			unsigned long end, unsigned long vm_flags,
8731da177e4SLinus Torvalds 			struct anon_vma *anon_vma, struct file *file,
87419a809afSAndrea Arcangeli 			pgoff_t pgoff, struct mempolicy *policy,
8759a10064fSColin Cross 			struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
8765c26f6acSSuren Baghdasaryan 			struct anon_vma_name *anon_name)
8771da177e4SLinus Torvalds {
878b0729ae0SLorenzo Stoakes 	struct vm_area_struct *curr, *next, *res;
8790503ea8fSLiam R. Howlett 	struct vm_area_struct *vma, *adjust, *remove, *remove2;
8800173db4fSLorenzo Stoakes 	struct vma_prepare vp;
8810173db4fSLorenzo Stoakes 	pgoff_t vma_pgoff;
8820173db4fSLorenzo Stoakes 	int err = 0;
883eef19944SJakub Matěna 	bool merge_prev = false;
884eef19944SJakub Matěna 	bool merge_next = false;
8850503ea8fSLiam R. Howlett 	bool vma_expanded = false;
8860503ea8fSLiam R. Howlett 	unsigned long vma_start = addr;
8870173db4fSLorenzo Stoakes 	unsigned long vma_end = end;
8880173db4fSLorenzo Stoakes 	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
8890173db4fSLorenzo Stoakes 	long adj_start = 0;
8901da177e4SLinus Torvalds 
8911da177e4SLinus Torvalds 	/*
8921da177e4SLinus Torvalds 	 * We later require that vma->vm_flags == vm_flags,
8931da177e4SLinus Torvalds 	 * so this tests vma->vm_flags & VM_SPECIAL, too.
8941da177e4SLinus Torvalds 	 */
8951da177e4SLinus Torvalds 	if (vm_flags & VM_SPECIAL)
8961da177e4SLinus Torvalds 		return NULL;
8971da177e4SLinus Torvalds 
89800cd00a6SLorenzo Stoakes 	/* Does the input range span an existing VMA? (cases 5 - 8) */
89900cd00a6SLorenzo Stoakes 	curr = find_vma_intersection(mm, prev ? prev->vm_end : 0, end);
9001da177e4SLinus Torvalds 
90100cd00a6SLorenzo Stoakes 	if (!curr ||			/* cases 1 - 4 */
90200cd00a6SLorenzo Stoakes 	    end == curr->vm_end)	/* cases 6 - 8, adjacent VMA */
90300cd00a6SLorenzo Stoakes 		next = vma_lookup(mm, end);
90400cd00a6SLorenzo Stoakes 	else
90500cd00a6SLorenzo Stoakes 		next = NULL;		/* case 5 */
906e86f15eeSAndrea Arcangeli 
9070503ea8fSLiam R. Howlett 	if (prev) {
9080503ea8fSLiam R. Howlett 		vma_start = prev->vm_start;
9090503ea8fSLiam R. Howlett 		vma_pgoff = prev->vm_pgoff;
9100173db4fSLorenzo Stoakes 
911eef19944SJakub Matěna 		/* Can we merge the predecessor? */
9120173db4fSLorenzo Stoakes 		if (addr == prev->vm_end && mpol_equal(vma_policy(prev), policy)
9130503ea8fSLiam R. Howlett 		    && can_vma_merge_after(prev, vm_flags, anon_vma, file,
9140503ea8fSLiam R. Howlett 					   pgoff, vm_userfaultfd_ctx, anon_name)) {
915eef19944SJakub Matěna 			merge_prev = true;
91618b098afSLiam R. Howlett 			vma_prev(vmi);
9171da177e4SLinus Torvalds 		}
9180503ea8fSLiam R. Howlett 	}
919b0729ae0SLorenzo Stoakes 
920eef19944SJakub Matěna 	/* Can we merge the successor? */
92100cd00a6SLorenzo Stoakes 	if (next && mpol_equal(policy, vma_policy(next)) &&
9220173db4fSLorenzo Stoakes 	    can_vma_merge_before(next, vm_flags, anon_vma, file, pgoff+pglen,
9239a10064fSColin Cross 				 vm_userfaultfd_ctx, anon_name)) {
924eef19944SJakub Matěna 		merge_next = true;
925eef19944SJakub Matěna 	}
9260503ea8fSLiam R. Howlett 
92729417d29SLorenzo Stoakes 	/* Verify some invariant that must be enforced by the caller. */
92829417d29SLorenzo Stoakes 	VM_WARN_ON(prev && addr <= prev->vm_start);
92929417d29SLorenzo Stoakes 	VM_WARN_ON(curr && (addr != curr->vm_start || end > curr->vm_end));
93029417d29SLorenzo Stoakes 	VM_WARN_ON(addr >= end);
93129417d29SLorenzo Stoakes 
9320173db4fSLorenzo Stoakes 	if (!merge_prev && !merge_next)
9330173db4fSLorenzo Stoakes 		return NULL; /* Not mergeable. */
9340173db4fSLorenzo Stoakes 
9350173db4fSLorenzo Stoakes 	res = vma = prev;
9360503ea8fSLiam R. Howlett 	remove = remove2 = adjust = NULL;
9370173db4fSLorenzo Stoakes 
938eef19944SJakub Matěna 	/* Can we merge both the predecessor and the successor? */
939eef19944SJakub Matěna 	if (merge_prev && merge_next &&
9400503ea8fSLiam R. Howlett 	    is_mergeable_anon_vma(prev->anon_vma, next->anon_vma, NULL)) {
9415ff783f1SVlastimil Babka 		remove = next;				/* case 1 */
9420503ea8fSLiam R. Howlett 		vma_end = next->vm_end;
94350dac011SVlastimil Babka 		err = dup_anon_vma(prev, next);
944fcfccd91SLorenzo Stoakes 		if (curr) {				/* case 6 */
945fcfccd91SLorenzo Stoakes 			remove = curr;
9460503ea8fSLiam R. Howlett 			remove2 = next;
9475ff783f1SVlastimil Babka 			if (!next->anon_vma)
948fcfccd91SLorenzo Stoakes 				err = dup_anon_vma(prev, curr);
9490503ea8fSLiam R. Howlett 		}
9500173db4fSLorenzo Stoakes 	} else if (merge_prev) {			/* case 2 */
951fcfccd91SLorenzo Stoakes 		if (curr) {
952fcfccd91SLorenzo Stoakes 			err = dup_anon_vma(prev, curr);
953fcfccd91SLorenzo Stoakes 			if (end == curr->vm_end) {	/* case 7 */
954fcfccd91SLorenzo Stoakes 				remove = curr;
9550503ea8fSLiam R. Howlett 			} else {			/* case 5 */
956fcfccd91SLorenzo Stoakes 				adjust = curr;
957fcfccd91SLorenzo Stoakes 				adj_start = (end - curr->vm_start);
9580503ea8fSLiam R. Howlett 			}
9590503ea8fSLiam R. Howlett 		}
9600173db4fSLorenzo Stoakes 	} else { /* merge_next */
961eef19944SJakub Matěna 		res = next;
9620503ea8fSLiam R. Howlett 		if (prev && addr < prev->vm_end) {	/* case 4 */
9630503ea8fSLiam R. Howlett 			vma_end = addr;
964183b7a60SVlastimil Babka 			adjust = next;
9651e76454fSVlastimil Babka 			adj_start = -(prev->vm_end - addr);
966183b7a60SVlastimil Babka 			err = dup_anon_vma(next, prev);
9670503ea8fSLiam R. Howlett 		} else {
968b0729ae0SLorenzo Stoakes 			/*
969b0729ae0SLorenzo Stoakes 			 * Note that cases 3 and 8 are the ONLY ones where prev
970b0729ae0SLorenzo Stoakes 			 * is permitted to be (but is not necessarily) NULL.
971b0729ae0SLorenzo Stoakes 			 */
9720503ea8fSLiam R. Howlett 			vma = next;			/* case 3 */
9730503ea8fSLiam R. Howlett 			vma_start = addr;
9740503ea8fSLiam R. Howlett 			vma_end = next->vm_end;
9757e775787SVlastimil Babka 			vma_pgoff = next->vm_pgoff - pglen;
976fcfccd91SLorenzo Stoakes 			if (curr) {			/* case 8 */
977fcfccd91SLorenzo Stoakes 				vma_pgoff = curr->vm_pgoff;
978fcfccd91SLorenzo Stoakes 				remove = curr;
979fcfccd91SLorenzo Stoakes 				err = dup_anon_vma(next, curr);
9800503ea8fSLiam R. Howlett 			}
9810503ea8fSLiam R. Howlett 		}
9821da177e4SLinus Torvalds 	}
9831da177e4SLinus Torvalds 
9840173db4fSLorenzo Stoakes 	/* Error in anon_vma clone. */
985eef19944SJakub Matěna 	if (err)
9861da177e4SLinus Torvalds 		return NULL;
9870503ea8fSLiam R. Howlett 
9880503ea8fSLiam R. Howlett 	if (vma_iter_prealloc(vmi))
9890503ea8fSLiam R. Howlett 		return NULL;
9900503ea8fSLiam R. Howlett 
9910503ea8fSLiam R. Howlett 	init_multi_vma_prep(&vp, vma, adjust, remove, remove2);
9920503ea8fSLiam R. Howlett 	VM_WARN_ON(vp.anon_vma && adjust && adjust->anon_vma &&
9930503ea8fSLiam R. Howlett 		   vp.anon_vma != adjust->anon_vma);
9940503ea8fSLiam R. Howlett 
9950503ea8fSLiam R. Howlett 	vma_prepare(&vp);
996ccf1d78dSSuren Baghdasaryan 	vma_adjust_trans_huge(vma, vma_start, vma_end, adj_start);
9970503ea8fSLiam R. Howlett 	if (vma_start < vma->vm_start || vma_end > vma->vm_end)
9980503ea8fSLiam R. Howlett 		vma_expanded = true;
9990503ea8fSLiam R. Howlett 
10000503ea8fSLiam R. Howlett 	vma->vm_start = vma_start;
10010503ea8fSLiam R. Howlett 	vma->vm_end = vma_end;
10020503ea8fSLiam R. Howlett 	vma->vm_pgoff = vma_pgoff;
10030503ea8fSLiam R. Howlett 
10040503ea8fSLiam R. Howlett 	if (vma_expanded)
10050503ea8fSLiam R. Howlett 		vma_iter_store(vmi, vma);
10060503ea8fSLiam R. Howlett 
10071e76454fSVlastimil Babka 	if (adj_start) {
10081e76454fSVlastimil Babka 		adjust->vm_start += adj_start;
10091e76454fSVlastimil Babka 		adjust->vm_pgoff += adj_start >> PAGE_SHIFT;
10101e76454fSVlastimil Babka 		if (adj_start < 0) {
10110503ea8fSLiam R. Howlett 			WARN_ON(vma_expanded);
10120503ea8fSLiam R. Howlett 			vma_iter_store(vmi, next);
10130503ea8fSLiam R. Howlett 		}
10140503ea8fSLiam R. Howlett 	}
10150503ea8fSLiam R. Howlett 
10160503ea8fSLiam R. Howlett 	vma_complete(&vp, vmi, mm);
1017eef19944SJakub Matěna 	khugepaged_enter_vma(res, vm_flags);
10189760ebffSLiam R. Howlett 	return res;
1019f2ebfe43SLiam R. Howlett }
1020f2ebfe43SLiam R. Howlett 
10211da177e4SLinus Torvalds /*
1022b4f315b4SEthon Paul  * Rough compatibility check to quickly see if it's even worth looking
1023d0e9fe17SLinus Torvalds  * at sharing an anon_vma.
1024d0e9fe17SLinus Torvalds  *
1025d0e9fe17SLinus Torvalds  * They need to have the same vm_file, and the flags can only differ
1026d0e9fe17SLinus Torvalds  * in things that mprotect may change.
1027d0e9fe17SLinus Torvalds  *
1028d0e9fe17SLinus Torvalds  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1029d0e9fe17SLinus Torvalds  * we can merge the two vma's. For example, we refuse to merge a vma if
1030d0e9fe17SLinus Torvalds  * there is a vm_ops->close() function, because that indicates that the
1031d0e9fe17SLinus Torvalds  * driver is doing some kind of reference counting. But that doesn't
1032d0e9fe17SLinus Torvalds  * really matter for the anon_vma sharing case.
1033d0e9fe17SLinus Torvalds  */
1034d0e9fe17SLinus Torvalds static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1035d0e9fe17SLinus Torvalds {
1036d0e9fe17SLinus Torvalds 	return a->vm_end == b->vm_start &&
1037d0e9fe17SLinus Torvalds 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1038d0e9fe17SLinus Torvalds 		a->vm_file == b->vm_file &&
10396cb4d9a2SAnshuman Khandual 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1040d0e9fe17SLinus Torvalds 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1041d0e9fe17SLinus Torvalds }
1042d0e9fe17SLinus Torvalds 
1043d0e9fe17SLinus Torvalds /*
1044d0e9fe17SLinus Torvalds  * Do some basic sanity checking to see if we can re-use the anon_vma
1045d0e9fe17SLinus Torvalds  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1046d0e9fe17SLinus Torvalds  * the same as 'old', the other will be the new one that is trying
1047d0e9fe17SLinus Torvalds  * to share the anon_vma.
1048d0e9fe17SLinus Torvalds  *
10495b449489SFlorian Rommel  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1050d0e9fe17SLinus Torvalds  * the anon_vma of 'old' is concurrently in the process of being set up
1051d0e9fe17SLinus Torvalds  * by another page fault trying to merge _that_. But that's ok: if it
1052d0e9fe17SLinus Torvalds  * is being set up, that automatically means that it will be a singleton
1053d0e9fe17SLinus Torvalds  * acceptable for merging, so we can do all of this optimistically. But
10544db0c3c2SJason Low  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1055d0e9fe17SLinus Torvalds  *
1056d0e9fe17SLinus Torvalds  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1057d0e9fe17SLinus Torvalds  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1058d0e9fe17SLinus Torvalds  * is to return an anon_vma that is "complex" due to having gone through
1059d0e9fe17SLinus Torvalds  * a fork).
1060d0e9fe17SLinus Torvalds  *
1061d0e9fe17SLinus Torvalds  * We also make sure that the two vma's are compatible (adjacent,
1062d0e9fe17SLinus Torvalds  * and with the same memory policies). That's all stable, even with just
10635b449489SFlorian Rommel  * a read lock on the mmap_lock.
1064d0e9fe17SLinus Torvalds  */
1065d0e9fe17SLinus Torvalds static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1066d0e9fe17SLinus Torvalds {
1067d0e9fe17SLinus Torvalds 	if (anon_vma_compatible(a, b)) {
10684db0c3c2SJason Low 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1069d0e9fe17SLinus Torvalds 
1070d0e9fe17SLinus Torvalds 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1071d0e9fe17SLinus Torvalds 			return anon_vma;
1072d0e9fe17SLinus Torvalds 	}
1073d0e9fe17SLinus Torvalds 	return NULL;
1074d0e9fe17SLinus Torvalds }
1075d0e9fe17SLinus Torvalds 
1076d0e9fe17SLinus Torvalds /*
10771da177e4SLinus Torvalds  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
10781da177e4SLinus Torvalds  * neighbouring vmas for a suitable anon_vma, before it goes off
10791da177e4SLinus Torvalds  * to allocate a new anon_vma.  It checks because a repetitive
10801da177e4SLinus Torvalds  * sequence of mprotects and faults may otherwise lead to distinct
10811da177e4SLinus Torvalds  * anon_vmas being allocated, preventing vma merge in subsequent
10821da177e4SLinus Torvalds  * mprotect.
10831da177e4SLinus Torvalds  */
10841da177e4SLinus Torvalds struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
10851da177e4SLinus Torvalds {
1086763ecb03SLiam R. Howlett 	MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
1087a67c8caaSMiaohe Lin 	struct anon_vma *anon_vma = NULL;
1088763ecb03SLiam R. Howlett 	struct vm_area_struct *prev, *next;
10891da177e4SLinus Torvalds 
1090a67c8caaSMiaohe Lin 	/* Try next first. */
1091763ecb03SLiam R. Howlett 	next = mas_walk(&mas);
1092763ecb03SLiam R. Howlett 	if (next) {
1093763ecb03SLiam R. Howlett 		anon_vma = reusable_anon_vma(next, vma, next);
1094d0e9fe17SLinus Torvalds 		if (anon_vma)
1095d0e9fe17SLinus Torvalds 			return anon_vma;
1096a67c8caaSMiaohe Lin 	}
10971da177e4SLinus Torvalds 
1098763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
1099763ecb03SLiam R. Howlett 	VM_BUG_ON_VMA(prev != vma, vma);
1100763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
1101a67c8caaSMiaohe Lin 	/* Try prev next. */
1102763ecb03SLiam R. Howlett 	if (prev)
1103763ecb03SLiam R. Howlett 		anon_vma = reusable_anon_vma(prev, prev, vma);
1104a67c8caaSMiaohe Lin 
11051da177e4SLinus Torvalds 	/*
1106a67c8caaSMiaohe Lin 	 * We might reach here with anon_vma == NULL if we can't find
1107a67c8caaSMiaohe Lin 	 * any reusable anon_vma.
11081da177e4SLinus Torvalds 	 * There's no absolute need to look only at touching neighbours:
11091da177e4SLinus Torvalds 	 * we could search further afield for "compatible" anon_vmas.
11101da177e4SLinus Torvalds 	 * But it would probably just be a waste of time searching,
11111da177e4SLinus Torvalds 	 * or lead to too many vmas hanging off the same anon_vma.
11121da177e4SLinus Torvalds 	 * We're trying to allow mprotect remerging later on,
11131da177e4SLinus Torvalds 	 * not trying to minimize memory used for anon_vmas.
11141da177e4SLinus Torvalds 	 */
1115a67c8caaSMiaohe Lin 	return anon_vma;
11161da177e4SLinus Torvalds }
11171da177e4SLinus Torvalds 
11181da177e4SLinus Torvalds /*
111940401530SAl Viro  * If a hint addr is less than mmap_min_addr change hint to be as
112040401530SAl Viro  * low as possible but still greater than mmap_min_addr
112140401530SAl Viro  */
112240401530SAl Viro static inline unsigned long round_hint_to_min(unsigned long hint)
112340401530SAl Viro {
112440401530SAl Viro 	hint &= PAGE_MASK;
112540401530SAl Viro 	if (((void *)hint != NULL) &&
112640401530SAl Viro 	    (hint < mmap_min_addr))
112740401530SAl Viro 		return PAGE_ALIGN(mmap_min_addr);
112840401530SAl Viro 	return hint;
112940401530SAl Viro }
113040401530SAl Viro 
1131b0cc5e89SAndrew Morton bool mlock_future_ok(struct mm_struct *mm, unsigned long flags,
11323c54a298SLorenzo Stoakes 			unsigned long bytes)
1133363ee17fSDavidlohr Bueso {
11343c54a298SLorenzo Stoakes 	unsigned long locked_pages, limit_pages;
1135363ee17fSDavidlohr Bueso 
11363c54a298SLorenzo Stoakes 	if (!(flags & VM_LOCKED) || capable(CAP_IPC_LOCK))
11373c54a298SLorenzo Stoakes 		return true;
11383c54a298SLorenzo Stoakes 
11393c54a298SLorenzo Stoakes 	locked_pages = bytes >> PAGE_SHIFT;
11403c54a298SLorenzo Stoakes 	locked_pages += mm->locked_vm;
11413c54a298SLorenzo Stoakes 
11423c54a298SLorenzo Stoakes 	limit_pages = rlimit(RLIMIT_MEMLOCK);
11433c54a298SLorenzo Stoakes 	limit_pages >>= PAGE_SHIFT;
11443c54a298SLorenzo Stoakes 
11453c54a298SLorenzo Stoakes 	return locked_pages <= limit_pages;
1146363ee17fSDavidlohr Bueso }
1147363ee17fSDavidlohr Bueso 
1148be83bbf8SLinus Torvalds static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1149be83bbf8SLinus Torvalds {
1150be83bbf8SLinus Torvalds 	if (S_ISREG(inode->i_mode))
1151423913adSLinus Torvalds 		return MAX_LFS_FILESIZE;
1152be83bbf8SLinus Torvalds 
1153be83bbf8SLinus Torvalds 	if (S_ISBLK(inode->i_mode))
1154be83bbf8SLinus Torvalds 		return MAX_LFS_FILESIZE;
1155be83bbf8SLinus Torvalds 
115676f34950SIvan Khoronzhuk 	if (S_ISSOCK(inode->i_mode))
115776f34950SIvan Khoronzhuk 		return MAX_LFS_FILESIZE;
115876f34950SIvan Khoronzhuk 
1159be83bbf8SLinus Torvalds 	/* Special "we do even unsigned file positions" case */
1160be83bbf8SLinus Torvalds 	if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1161be83bbf8SLinus Torvalds 		return 0;
1162be83bbf8SLinus Torvalds 
1163be83bbf8SLinus Torvalds 	/* Yes, random drivers might want more. But I'm tired of buggy drivers */
1164be83bbf8SLinus Torvalds 	return ULONG_MAX;
1165be83bbf8SLinus Torvalds }
1166be83bbf8SLinus Torvalds 
1167be83bbf8SLinus Torvalds static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1168be83bbf8SLinus Torvalds 				unsigned long pgoff, unsigned long len)
1169be83bbf8SLinus Torvalds {
1170be83bbf8SLinus Torvalds 	u64 maxsize = file_mmap_size_max(file, inode);
1171be83bbf8SLinus Torvalds 
1172be83bbf8SLinus Torvalds 	if (maxsize && len > maxsize)
1173be83bbf8SLinus Torvalds 		return false;
1174be83bbf8SLinus Torvalds 	maxsize -= len;
1175be83bbf8SLinus Torvalds 	if (pgoff > maxsize >> PAGE_SHIFT)
1176be83bbf8SLinus Torvalds 		return false;
1177be83bbf8SLinus Torvalds 	return true;
1178be83bbf8SLinus Torvalds }
1179be83bbf8SLinus Torvalds 
118040401530SAl Viro /*
11813e4e28c5SMichel Lespinasse  * The caller must write-lock current->mm->mmap_lock.
11821da177e4SLinus Torvalds  */
11831fcfd8dbSOleg Nesterov unsigned long do_mmap(struct file *file, unsigned long addr,
11841da177e4SLinus Torvalds 			unsigned long len, unsigned long prot,
118545e55300SPeter Collingbourne 			unsigned long flags, unsigned long pgoff,
118645e55300SPeter Collingbourne 			unsigned long *populate, struct list_head *uf)
11871da177e4SLinus Torvalds {
11881da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
118945e55300SPeter Collingbourne 	vm_flags_t vm_flags;
119062b5f7d0SDave Hansen 	int pkey = 0;
11911da177e4SLinus Torvalds 
119241badc15SMichel Lespinasse 	*populate = 0;
1193bebeb3d6SMichel Lespinasse 
1194e37609bbSPiotr Kwapulinski 	if (!len)
1195e37609bbSPiotr Kwapulinski 		return -EINVAL;
1196e37609bbSPiotr Kwapulinski 
11971da177e4SLinus Torvalds 	/*
11981da177e4SLinus Torvalds 	 * Does the application expect PROT_READ to imply PROT_EXEC?
11991da177e4SLinus Torvalds 	 *
12001da177e4SLinus Torvalds 	 * (the exception is when the underlying filesystem is noexec
12011da177e4SLinus Torvalds 	 *  mounted, in which case we dont add PROT_EXEC.)
12021da177e4SLinus Torvalds 	 */
12031da177e4SLinus Torvalds 	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
120490f8572bSEric W. Biederman 		if (!(file && path_noexec(&file->f_path)))
12051da177e4SLinus Torvalds 			prot |= PROT_EXEC;
12061da177e4SLinus Torvalds 
1207a4ff8e86SMichal Hocko 	/* force arch specific MAP_FIXED handling in get_unmapped_area */
1208a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE)
1209a4ff8e86SMichal Hocko 		flags |= MAP_FIXED;
1210a4ff8e86SMichal Hocko 
12117cd94146SEric Paris 	if (!(flags & MAP_FIXED))
12127cd94146SEric Paris 		addr = round_hint_to_min(addr);
12137cd94146SEric Paris 
12141da177e4SLinus Torvalds 	/* Careful about overflows.. */
12151da177e4SLinus Torvalds 	len = PAGE_ALIGN(len);
12169206de95SAl Viro 	if (!len)
12171da177e4SLinus Torvalds 		return -ENOMEM;
12181da177e4SLinus Torvalds 
12191da177e4SLinus Torvalds 	/* offset overflow? */
12201da177e4SLinus Torvalds 	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
12211da177e4SLinus Torvalds 		return -EOVERFLOW;
12221da177e4SLinus Torvalds 
12231da177e4SLinus Torvalds 	/* Too many mappings? */
12241da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
12251da177e4SLinus Torvalds 		return -ENOMEM;
12261da177e4SLinus Torvalds 
12271da177e4SLinus Torvalds 	/* Obtain the address to map to. we verify (or select) it and ensure
12281da177e4SLinus Torvalds 	 * that it represents a valid section of the address space.
12291da177e4SLinus Torvalds 	 */
12301da177e4SLinus Torvalds 	addr = get_unmapped_area(file, addr, len, pgoff, flags);
1231ff68dac6SGaowei Pu 	if (IS_ERR_VALUE(addr))
12321da177e4SLinus Torvalds 		return addr;
12331da177e4SLinus Torvalds 
1234a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE) {
123535e43c5fSLiam Howlett 		if (find_vma_intersection(mm, addr, addr + len))
1236a4ff8e86SMichal Hocko 			return -EEXIST;
1237a4ff8e86SMichal Hocko 	}
1238a4ff8e86SMichal Hocko 
123962b5f7d0SDave Hansen 	if (prot == PROT_EXEC) {
124062b5f7d0SDave Hansen 		pkey = execute_only_pkey(mm);
124162b5f7d0SDave Hansen 		if (pkey < 0)
124262b5f7d0SDave Hansen 			pkey = 0;
124362b5f7d0SDave Hansen 	}
124462b5f7d0SDave Hansen 
12451da177e4SLinus Torvalds 	/* Do simple checking here so the lower-level routines won't have
12461da177e4SLinus Torvalds 	 * to. we assume access permissions have been handled by the open
12471da177e4SLinus Torvalds 	 * of the memory object, so we don't do any here.
12481da177e4SLinus Torvalds 	 */
124945e55300SPeter Collingbourne 	vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
12501da177e4SLinus Torvalds 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
12511da177e4SLinus Torvalds 
1252cdf7b341SHuang Shijie 	if (flags & MAP_LOCKED)
12531da177e4SLinus Torvalds 		if (!can_do_mlock())
12541da177e4SLinus Torvalds 			return -EPERM;
1255ba470de4SRik van Riel 
1256b0cc5e89SAndrew Morton 	if (!mlock_future_ok(mm, vm_flags, len))
12571da177e4SLinus Torvalds 		return -EAGAIN;
12581da177e4SLinus Torvalds 
12591da177e4SLinus Torvalds 	if (file) {
1260077bf22bSOleg Nesterov 		struct inode *inode = file_inode(file);
12611c972597SDan Williams 		unsigned long flags_mask;
12621c972597SDan Williams 
1263be83bbf8SLinus Torvalds 		if (!file_mmap_ok(file, inode, pgoff, len))
1264be83bbf8SLinus Torvalds 			return -EOVERFLOW;
1265be83bbf8SLinus Torvalds 
12661c972597SDan Williams 		flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1267077bf22bSOleg Nesterov 
12681da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
12691da177e4SLinus Torvalds 		case MAP_SHARED:
12701c972597SDan Williams 			/*
12711c972597SDan Williams 			 * Force use of MAP_SHARED_VALIDATE with non-legacy
12721c972597SDan Williams 			 * flags. E.g. MAP_SYNC is dangerous to use with
12731c972597SDan Williams 			 * MAP_SHARED as you don't know which consistency model
12741c972597SDan Williams 			 * you will get. We silently ignore unsupported flags
12751c972597SDan Williams 			 * with MAP_SHARED to preserve backward compatibility.
12761c972597SDan Williams 			 */
12771c972597SDan Williams 			flags &= LEGACY_MAP_MASK;
1278e4a9bc58SJoe Perches 			fallthrough;
12791c972597SDan Williams 		case MAP_SHARED_VALIDATE:
12801c972597SDan Williams 			if (flags & ~flags_mask)
12811c972597SDan Williams 				return -EOPNOTSUPP;
1282dc617f29SDarrick J. Wong 			if (prot & PROT_WRITE) {
1283dc617f29SDarrick J. Wong 				if (!(file->f_mode & FMODE_WRITE))
12841da177e4SLinus Torvalds 					return -EACCES;
1285dc617f29SDarrick J. Wong 				if (IS_SWAPFILE(file->f_mapping->host))
1286dc617f29SDarrick J. Wong 					return -ETXTBSY;
1287dc617f29SDarrick J. Wong 			}
12881da177e4SLinus Torvalds 
12891da177e4SLinus Torvalds 			/*
12901da177e4SLinus Torvalds 			 * Make sure we don't allow writing to an append-only
12911da177e4SLinus Torvalds 			 * file..
12921da177e4SLinus Torvalds 			 */
12931da177e4SLinus Torvalds 			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
12941da177e4SLinus Torvalds 				return -EACCES;
12951da177e4SLinus Torvalds 
12961da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
12971da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_WRITE))
12981da177e4SLinus Torvalds 				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1299e4a9bc58SJoe Perches 			fallthrough;
13001da177e4SLinus Torvalds 		case MAP_PRIVATE:
13011da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_READ))
13021da177e4SLinus Torvalds 				return -EACCES;
130390f8572bSEric W. Biederman 			if (path_noexec(&file->f_path)) {
130480c5606cSLinus Torvalds 				if (vm_flags & VM_EXEC)
130580c5606cSLinus Torvalds 					return -EPERM;
130680c5606cSLinus Torvalds 				vm_flags &= ~VM_MAYEXEC;
130780c5606cSLinus Torvalds 			}
130880c5606cSLinus Torvalds 
130972c2d531SAl Viro 			if (!file->f_op->mmap)
131080c5606cSLinus Torvalds 				return -ENODEV;
1311b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1312b2c56e4fSOleg Nesterov 				return -EINVAL;
13131da177e4SLinus Torvalds 			break;
13141da177e4SLinus Torvalds 
13151da177e4SLinus Torvalds 		default:
13161da177e4SLinus Torvalds 			return -EINVAL;
13171da177e4SLinus Torvalds 		}
13181da177e4SLinus Torvalds 	} else {
13191da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
13201da177e4SLinus Torvalds 		case MAP_SHARED:
1321b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1322b2c56e4fSOleg Nesterov 				return -EINVAL;
1323ce363942STejun Heo 			/*
1324ce363942STejun Heo 			 * Ignore pgoff.
1325ce363942STejun Heo 			 */
1326ce363942STejun Heo 			pgoff = 0;
13271da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
13281da177e4SLinus Torvalds 			break;
13291da177e4SLinus Torvalds 		case MAP_PRIVATE:
13301da177e4SLinus Torvalds 			/*
13311da177e4SLinus Torvalds 			 * Set pgoff according to addr for anon_vma.
13321da177e4SLinus Torvalds 			 */
13331da177e4SLinus Torvalds 			pgoff = addr >> PAGE_SHIFT;
13341da177e4SLinus Torvalds 			break;
13351da177e4SLinus Torvalds 		default:
13361da177e4SLinus Torvalds 			return -EINVAL;
13371da177e4SLinus Torvalds 		}
13381da177e4SLinus Torvalds 	}
13391da177e4SLinus Torvalds 
1340c22c0d63SMichel Lespinasse 	/*
1341c22c0d63SMichel Lespinasse 	 * Set 'VM_NORESERVE' if we should not account for the
1342c22c0d63SMichel Lespinasse 	 * memory use of this mapping.
1343c22c0d63SMichel Lespinasse 	 */
1344c22c0d63SMichel Lespinasse 	if (flags & MAP_NORESERVE) {
1345c22c0d63SMichel Lespinasse 		/* We honor MAP_NORESERVE if allowed to overcommit */
1346c22c0d63SMichel Lespinasse 		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1347c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1348c22c0d63SMichel Lespinasse 
1349c22c0d63SMichel Lespinasse 		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
1350c22c0d63SMichel Lespinasse 		if (file && is_file_hugepages(file))
1351c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1352c22c0d63SMichel Lespinasse 	}
1353c22c0d63SMichel Lespinasse 
1354897ab3e0SMike Rapoport 	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
135509a9f1d2SMichel Lespinasse 	if (!IS_ERR_VALUE(addr) &&
135609a9f1d2SMichel Lespinasse 	    ((vm_flags & VM_LOCKED) ||
135709a9f1d2SMichel Lespinasse 	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
135841badc15SMichel Lespinasse 		*populate = len;
1359bebeb3d6SMichel Lespinasse 	return addr;
13600165ab44SMiklos Szeredi }
13616be5ceb0SLinus Torvalds 
1362a90f590aSDominik Brodowski unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1363a90f590aSDominik Brodowski 			      unsigned long prot, unsigned long flags,
1364a90f590aSDominik Brodowski 			      unsigned long fd, unsigned long pgoff)
136566f0dc48SHugh Dickins {
136666f0dc48SHugh Dickins 	struct file *file = NULL;
13671e3ee14bSChen Gang 	unsigned long retval;
136866f0dc48SHugh Dickins 
136966f0dc48SHugh Dickins 	if (!(flags & MAP_ANONYMOUS)) {
1370120a795dSAl Viro 		audit_mmap_fd(fd, flags);
137166f0dc48SHugh Dickins 		file = fget(fd);
137266f0dc48SHugh Dickins 		if (!file)
13731e3ee14bSChen Gang 			return -EBADF;
13747bba8f0eSZhen Lei 		if (is_file_hugepages(file)) {
1375af73e4d9SNaoya Horiguchi 			len = ALIGN(len, huge_page_size(hstate_file(file)));
13767bba8f0eSZhen Lei 		} else if (unlikely(flags & MAP_HUGETLB)) {
1377493af578SJörn Engel 			retval = -EINVAL;
1378493af578SJörn Engel 			goto out_fput;
13797bba8f0eSZhen Lei 		}
138066f0dc48SHugh Dickins 	} else if (flags & MAP_HUGETLB) {
1381c103a4dcSAndrew Morton 		struct hstate *hs;
1382af73e4d9SNaoya Horiguchi 
138320ac2893SAnshuman Khandual 		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1384091d0d55SLi Zefan 		if (!hs)
1385091d0d55SLi Zefan 			return -EINVAL;
1386091d0d55SLi Zefan 
1387091d0d55SLi Zefan 		len = ALIGN(len, huge_page_size(hs));
138866f0dc48SHugh Dickins 		/*
138966f0dc48SHugh Dickins 		 * VM_NORESERVE is used because the reservations will be
139066f0dc48SHugh Dickins 		 * taken when vm_ops->mmap() is called
139166f0dc48SHugh Dickins 		 */
1392af73e4d9SNaoya Horiguchi 		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
139342d7395fSAndi Kleen 				VM_NORESERVE,
139483c1fd76Szhangyiru 				HUGETLB_ANONHUGE_INODE,
139542d7395fSAndi Kleen 				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
139666f0dc48SHugh Dickins 		if (IS_ERR(file))
139766f0dc48SHugh Dickins 			return PTR_ERR(file);
139866f0dc48SHugh Dickins 	}
139966f0dc48SHugh Dickins 
14009fbeb5abSMichal Hocko 	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1401493af578SJörn Engel out_fput:
140266f0dc48SHugh Dickins 	if (file)
140366f0dc48SHugh Dickins 		fput(file);
140466f0dc48SHugh Dickins 	return retval;
140566f0dc48SHugh Dickins }
140666f0dc48SHugh Dickins 
1407a90f590aSDominik Brodowski SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1408a90f590aSDominik Brodowski 		unsigned long, prot, unsigned long, flags,
1409a90f590aSDominik Brodowski 		unsigned long, fd, unsigned long, pgoff)
1410a90f590aSDominik Brodowski {
1411a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1412a90f590aSDominik Brodowski }
1413a90f590aSDominik Brodowski 
1414a4679373SChristoph Hellwig #ifdef __ARCH_WANT_SYS_OLD_MMAP
1415a4679373SChristoph Hellwig struct mmap_arg_struct {
1416a4679373SChristoph Hellwig 	unsigned long addr;
1417a4679373SChristoph Hellwig 	unsigned long len;
1418a4679373SChristoph Hellwig 	unsigned long prot;
1419a4679373SChristoph Hellwig 	unsigned long flags;
1420a4679373SChristoph Hellwig 	unsigned long fd;
1421a4679373SChristoph Hellwig 	unsigned long offset;
1422a4679373SChristoph Hellwig };
1423a4679373SChristoph Hellwig 
1424a4679373SChristoph Hellwig SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1425a4679373SChristoph Hellwig {
1426a4679373SChristoph Hellwig 	struct mmap_arg_struct a;
1427a4679373SChristoph Hellwig 
1428a4679373SChristoph Hellwig 	if (copy_from_user(&a, arg, sizeof(a)))
1429a4679373SChristoph Hellwig 		return -EFAULT;
1430de1741a1SAlexander Kuleshov 	if (offset_in_page(a.offset))
1431a4679373SChristoph Hellwig 		return -EINVAL;
1432a4679373SChristoph Hellwig 
1433a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1434a4679373SChristoph Hellwig 			       a.offset >> PAGE_SHIFT);
1435a4679373SChristoph Hellwig }
1436a4679373SChristoph Hellwig #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1437a4679373SChristoph Hellwig 
143854cbbbf3SLorenzo Stoakes static bool vm_ops_needs_writenotify(const struct vm_operations_struct *vm_ops)
143954cbbbf3SLorenzo Stoakes {
144054cbbbf3SLorenzo Stoakes 	return vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite);
144154cbbbf3SLorenzo Stoakes }
144254cbbbf3SLorenzo Stoakes 
144354cbbbf3SLorenzo Stoakes static bool vma_is_shared_writable(struct vm_area_struct *vma)
144454cbbbf3SLorenzo Stoakes {
144554cbbbf3SLorenzo Stoakes 	return (vma->vm_flags & (VM_WRITE | VM_SHARED)) ==
144654cbbbf3SLorenzo Stoakes 		(VM_WRITE | VM_SHARED);
144754cbbbf3SLorenzo Stoakes }
144854cbbbf3SLorenzo Stoakes 
144954cbbbf3SLorenzo Stoakes static bool vma_fs_can_writeback(struct vm_area_struct *vma)
145054cbbbf3SLorenzo Stoakes {
145154cbbbf3SLorenzo Stoakes 	/* No managed pages to writeback. */
145254cbbbf3SLorenzo Stoakes 	if (vma->vm_flags & VM_PFNMAP)
145354cbbbf3SLorenzo Stoakes 		return false;
145454cbbbf3SLorenzo Stoakes 
145554cbbbf3SLorenzo Stoakes 	return vma->vm_file && vma->vm_file->f_mapping &&
145654cbbbf3SLorenzo Stoakes 		mapping_can_writeback(vma->vm_file->f_mapping);
145754cbbbf3SLorenzo Stoakes }
145854cbbbf3SLorenzo Stoakes 
145954cbbbf3SLorenzo Stoakes /*
146054cbbbf3SLorenzo Stoakes  * Does this VMA require the underlying folios to have their dirty state
146154cbbbf3SLorenzo Stoakes  * tracked?
146254cbbbf3SLorenzo Stoakes  */
146354cbbbf3SLorenzo Stoakes bool vma_needs_dirty_tracking(struct vm_area_struct *vma)
146454cbbbf3SLorenzo Stoakes {
146554cbbbf3SLorenzo Stoakes 	/* Only shared, writable VMAs require dirty tracking. */
146654cbbbf3SLorenzo Stoakes 	if (!vma_is_shared_writable(vma))
146754cbbbf3SLorenzo Stoakes 		return false;
146854cbbbf3SLorenzo Stoakes 
146954cbbbf3SLorenzo Stoakes 	/* Does the filesystem need to be notified? */
147054cbbbf3SLorenzo Stoakes 	if (vm_ops_needs_writenotify(vma->vm_ops))
147154cbbbf3SLorenzo Stoakes 		return true;
147254cbbbf3SLorenzo Stoakes 
147354cbbbf3SLorenzo Stoakes 	/*
147454cbbbf3SLorenzo Stoakes 	 * Even if the filesystem doesn't indicate a need for writenotify, if it
147554cbbbf3SLorenzo Stoakes 	 * can writeback, dirty tracking is still required.
147654cbbbf3SLorenzo Stoakes 	 */
147754cbbbf3SLorenzo Stoakes 	return vma_fs_can_writeback(vma);
147854cbbbf3SLorenzo Stoakes }
147954cbbbf3SLorenzo Stoakes 
14804e950f6fSAlexey Dobriyan /*
14818bb4e7a2SWei Yang  * Some shared mappings will want the pages marked read-only
14824e950f6fSAlexey Dobriyan  * to track write events. If so, we'll downgrade vm_page_prot
14834e950f6fSAlexey Dobriyan  * to the private version (using protection_map[] without the
14844e950f6fSAlexey Dobriyan  * VM_SHARED bit).
14854e950f6fSAlexey Dobriyan  */
14866d2329f8SAndrea Arcangeli int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
14874e950f6fSAlexey Dobriyan {
14884e950f6fSAlexey Dobriyan 	/* If it was private or non-writable, the write bit is already clear */
148954cbbbf3SLorenzo Stoakes 	if (!vma_is_shared_writable(vma))
14904e950f6fSAlexey Dobriyan 		return 0;
14914e950f6fSAlexey Dobriyan 
14924e950f6fSAlexey Dobriyan 	/* The backer wishes to know when pages are first written to? */
149354cbbbf3SLorenzo Stoakes 	if (vm_ops_needs_writenotify(vma->vm_ops))
14944e950f6fSAlexey Dobriyan 		return 1;
14954e950f6fSAlexey Dobriyan 
149664e45507SPeter Feiner 	/* The open routine did something to the protections that pgprot_modify
149764e45507SPeter Feiner 	 * won't preserve? */
14986d2329f8SAndrea Arcangeli 	if (pgprot_val(vm_page_prot) !=
149954cbbbf3SLorenzo Stoakes 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vma->vm_flags)))
15004e950f6fSAlexey Dobriyan 		return 0;
15014e950f6fSAlexey Dobriyan 
1502f96f7a40SDavid Hildenbrand 	/*
1503f96f7a40SDavid Hildenbrand 	 * Do we need to track softdirty? hugetlb does not support softdirty
1504f96f7a40SDavid Hildenbrand 	 * tracking yet.
1505f96f7a40SDavid Hildenbrand 	 */
1506f96f7a40SDavid Hildenbrand 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
150764e45507SPeter Feiner 		return 1;
150864e45507SPeter Feiner 
150951d3d5ebSDavid Hildenbrand 	/* Do we need write faults for uffd-wp tracking? */
151051d3d5ebSDavid Hildenbrand 	if (userfaultfd_wp(vma))
151151d3d5ebSDavid Hildenbrand 		return 1;
151251d3d5ebSDavid Hildenbrand 
15134e950f6fSAlexey Dobriyan 	/* Can the mapping track the dirty pages? */
151454cbbbf3SLorenzo Stoakes 	return vma_fs_can_writeback(vma);
15154e950f6fSAlexey Dobriyan }
15164e950f6fSAlexey Dobriyan 
1517fc8744adSLinus Torvalds /*
1518fc8744adSLinus Torvalds  * We account for memory if it's a private writeable mapping,
15195a6fe125SMel Gorman  * not hugepages and VM_NORESERVE wasn't set.
1520fc8744adSLinus Torvalds  */
1521ca16d140SKOSAKI Motohiro static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1522fc8744adSLinus Torvalds {
15235a6fe125SMel Gorman 	/*
15245a6fe125SMel Gorman 	 * hugetlb has its own accounting separate from the core VM
15255a6fe125SMel Gorman 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
15265a6fe125SMel Gorman 	 */
15275a6fe125SMel Gorman 	if (file && is_file_hugepages(file))
15285a6fe125SMel Gorman 		return 0;
15295a6fe125SMel Gorman 
1530fc8744adSLinus Torvalds 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1531fc8744adSLinus Torvalds }
1532fc8744adSLinus Torvalds 
15333499a131SLiam R. Howlett /**
15343499a131SLiam R. Howlett  * unmapped_area() - Find an area between the low_limit and the high_limit with
15353499a131SLiam R. Howlett  * the correct alignment and offset, all from @info. Note: current->mm is used
15363499a131SLiam R. Howlett  * for the search.
15373499a131SLiam R. Howlett  *
153882b24936SVernon Yang  * @info: The unmapped area information including the range [low_limit -
153982b24936SVernon Yang  * high_limit), the alignment offset and mask.
15403499a131SLiam R. Howlett  *
15413499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
15423499a131SLiam R. Howlett  */
1543baceaf1cSJaewon Kim static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1544db4fbfb9SMichel Lespinasse {
15456b008640SLinus Torvalds 	unsigned long length, gap;
15466b008640SLinus Torvalds 	unsigned long low_limit, high_limit;
154758c5d0d6SLiam R. Howlett 	struct vm_area_struct *tmp;
1548db4fbfb9SMichel Lespinasse 
15493499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1550db4fbfb9SMichel Lespinasse 
1551db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1552db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1553db4fbfb9SMichel Lespinasse 	if (length < info->length)
1554db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1555db4fbfb9SMichel Lespinasse 
155658c5d0d6SLiam R. Howlett 	low_limit = info->low_limit;
15576b008640SLinus Torvalds 	if (low_limit < mmap_min_addr)
15586b008640SLinus Torvalds 		low_limit = mmap_min_addr;
15596b008640SLinus Torvalds 	high_limit = info->high_limit;
156058c5d0d6SLiam R. Howlett retry:
15616b008640SLinus Torvalds 	if (mas_empty_area(&mas, low_limit, high_limit - 1, length))
15623499a131SLiam R. Howlett 		return -ENOMEM;
15633499a131SLiam R. Howlett 
1564d4af56c5SLiam R. Howlett 	gap = mas.index;
1565d4af56c5SLiam R. Howlett 	gap += (info->align_offset - gap) & info->align_mask;
156658c5d0d6SLiam R. Howlett 	tmp = mas_next(&mas, ULONG_MAX);
156758c5d0d6SLiam R. Howlett 	if (tmp && (tmp->vm_flags & VM_GROWSDOWN)) { /* Avoid prev check if possible */
156858c5d0d6SLiam R. Howlett 		if (vm_start_gap(tmp) < gap + length - 1) {
156958c5d0d6SLiam R. Howlett 			low_limit = tmp->vm_end;
157058c5d0d6SLiam R. Howlett 			mas_reset(&mas);
157158c5d0d6SLiam R. Howlett 			goto retry;
157258c5d0d6SLiam R. Howlett 		}
157358c5d0d6SLiam R. Howlett 	} else {
157458c5d0d6SLiam R. Howlett 		tmp = mas_prev(&mas, 0);
157558c5d0d6SLiam R. Howlett 		if (tmp && vm_end_gap(tmp) > gap) {
157658c5d0d6SLiam R. Howlett 			low_limit = vm_end_gap(tmp);
157758c5d0d6SLiam R. Howlett 			mas_reset(&mas);
157858c5d0d6SLiam R. Howlett 			goto retry;
157958c5d0d6SLiam R. Howlett 		}
158058c5d0d6SLiam R. Howlett 	}
158158c5d0d6SLiam R. Howlett 
15823499a131SLiam R. Howlett 	return gap;
1583db4fbfb9SMichel Lespinasse }
1584db4fbfb9SMichel Lespinasse 
15853499a131SLiam R. Howlett /**
15863499a131SLiam R. Howlett  * unmapped_area_topdown() - Find an area between the low_limit and the
158782b24936SVernon Yang  * high_limit with the correct alignment and offset at the highest available
15883499a131SLiam R. Howlett  * address, all from @info. Note: current->mm is used for the search.
15893499a131SLiam R. Howlett  *
159082b24936SVernon Yang  * @info: The unmapped area information including the range [low_limit -
159182b24936SVernon Yang  * high_limit), the alignment offset and mask.
15923499a131SLiam R. Howlett  *
15933499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
15943499a131SLiam R. Howlett  */
1595baceaf1cSJaewon Kim static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1596db4fbfb9SMichel Lespinasse {
15976b008640SLinus Torvalds 	unsigned long length, gap, gap_end;
15986b008640SLinus Torvalds 	unsigned long low_limit, high_limit;
159958c5d0d6SLiam R. Howlett 	struct vm_area_struct *tmp;
1600d4af56c5SLiam R. Howlett 
16013499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1602db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1603db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1604db4fbfb9SMichel Lespinasse 	if (length < info->length)
1605db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1606db4fbfb9SMichel Lespinasse 
16076b008640SLinus Torvalds 	low_limit = info->low_limit;
16086b008640SLinus Torvalds 	if (low_limit < mmap_min_addr)
16096b008640SLinus Torvalds 		low_limit = mmap_min_addr;
161058c5d0d6SLiam R. Howlett 	high_limit = info->high_limit;
161158c5d0d6SLiam R. Howlett retry:
16126b008640SLinus Torvalds 	if (mas_empty_area_rev(&mas, low_limit, high_limit - 1, length))
16133499a131SLiam R. Howlett 		return -ENOMEM;
16143499a131SLiam R. Howlett 
1615d4af56c5SLiam R. Howlett 	gap = mas.last + 1 - info->length;
1616d4af56c5SLiam R. Howlett 	gap -= (gap - info->align_offset) & info->align_mask;
161758c5d0d6SLiam R. Howlett 	gap_end = mas.last;
161858c5d0d6SLiam R. Howlett 	tmp = mas_next(&mas, ULONG_MAX);
161958c5d0d6SLiam R. Howlett 	if (tmp && (tmp->vm_flags & VM_GROWSDOWN)) { /* Avoid prev check if possible */
162058c5d0d6SLiam R. Howlett 		if (vm_start_gap(tmp) <= gap_end) {
162158c5d0d6SLiam R. Howlett 			high_limit = vm_start_gap(tmp);
162258c5d0d6SLiam R. Howlett 			mas_reset(&mas);
162358c5d0d6SLiam R. Howlett 			goto retry;
162458c5d0d6SLiam R. Howlett 		}
162558c5d0d6SLiam R. Howlett 	} else {
162658c5d0d6SLiam R. Howlett 		tmp = mas_prev(&mas, 0);
162758c5d0d6SLiam R. Howlett 		if (tmp && vm_end_gap(tmp) > gap) {
162858c5d0d6SLiam R. Howlett 			high_limit = tmp->vm_start;
162958c5d0d6SLiam R. Howlett 			mas_reset(&mas);
163058c5d0d6SLiam R. Howlett 			goto retry;
163158c5d0d6SLiam R. Howlett 		}
163258c5d0d6SLiam R. Howlett 	}
163358c5d0d6SLiam R. Howlett 
16343499a131SLiam R. Howlett 	return gap;
1635db4fbfb9SMichel Lespinasse }
1636db4fbfb9SMichel Lespinasse 
1637baceaf1cSJaewon Kim /*
1638baceaf1cSJaewon Kim  * Search for an unmapped address range.
1639baceaf1cSJaewon Kim  *
1640baceaf1cSJaewon Kim  * We are looking for a range that:
1641baceaf1cSJaewon Kim  * - does not intersect with any VMA;
1642baceaf1cSJaewon Kim  * - is contained within the [low_limit, high_limit) interval;
1643baceaf1cSJaewon Kim  * - is at least the desired size.
1644baceaf1cSJaewon Kim  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
1645baceaf1cSJaewon Kim  */
1646baceaf1cSJaewon Kim unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
1647baceaf1cSJaewon Kim {
1648df529cabSJaewon Kim 	unsigned long addr;
1649df529cabSJaewon Kim 
1650baceaf1cSJaewon Kim 	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1651df529cabSJaewon Kim 		addr = unmapped_area_topdown(info);
1652baceaf1cSJaewon Kim 	else
1653df529cabSJaewon Kim 		addr = unmapped_area(info);
1654df529cabSJaewon Kim 
1655df529cabSJaewon Kim 	trace_vm_unmapped_area(addr, info);
1656df529cabSJaewon Kim 	return addr;
1657baceaf1cSJaewon Kim }
1658f6795053SSteve Capper 
16591da177e4SLinus Torvalds /* Get an address range which is currently unmapped.
16601da177e4SLinus Torvalds  * For shmat() with addr=0.
16611da177e4SLinus Torvalds  *
16621da177e4SLinus Torvalds  * Ugly calling convention alert:
16631da177e4SLinus Torvalds  * Return value with the low bits set means error value,
16641da177e4SLinus Torvalds  * ie
16651da177e4SLinus Torvalds  *	if (ret & ~PAGE_MASK)
16661da177e4SLinus Torvalds  *		error = ret;
16671da177e4SLinus Torvalds  *
16681da177e4SLinus Torvalds  * This function "knows" that -ENOMEM has the bits set.
16691da177e4SLinus Torvalds  */
16701da177e4SLinus Torvalds unsigned long
16714b439e25SChristophe Leroy generic_get_unmapped_area(struct file *filp, unsigned long addr,
16724b439e25SChristophe Leroy 			  unsigned long len, unsigned long pgoff,
16734b439e25SChristophe Leroy 			  unsigned long flags)
16741da177e4SLinus Torvalds {
16751da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
16761be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
1677db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
16782cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
16791da177e4SLinus Torvalds 
1680f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
16811da177e4SLinus Torvalds 		return -ENOMEM;
16821da177e4SLinus Torvalds 
168306abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
168406abdfb4SBenjamin Herrenschmidt 		return addr;
168506abdfb4SBenjamin Herrenschmidt 
16861da177e4SLinus Torvalds 	if (addr) {
16871da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
16881be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1689f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
16901be7107fSHugh Dickins 		    (!vma || addr + len <= vm_start_gap(vma)) &&
16911be7107fSHugh Dickins 		    (!prev || addr >= vm_end_gap(prev)))
16921da177e4SLinus Torvalds 			return addr;
16931da177e4SLinus Torvalds 	}
16941da177e4SLinus Torvalds 
1695db4fbfb9SMichel Lespinasse 	info.flags = 0;
1696db4fbfb9SMichel Lespinasse 	info.length = len;
16974e99b021SHeiko Carstens 	info.low_limit = mm->mmap_base;
1698f6795053SSteve Capper 	info.high_limit = mmap_end;
1699db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
170009ef5283SJaewon Kim 	info.align_offset = 0;
1701db4fbfb9SMichel Lespinasse 	return vm_unmapped_area(&info);
17021da177e4SLinus Torvalds }
17034b439e25SChristophe Leroy 
17044b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA
17054b439e25SChristophe Leroy unsigned long
17064b439e25SChristophe Leroy arch_get_unmapped_area(struct file *filp, unsigned long addr,
17074b439e25SChristophe Leroy 		       unsigned long len, unsigned long pgoff,
17084b439e25SChristophe Leroy 		       unsigned long flags)
17094b439e25SChristophe Leroy {
17104b439e25SChristophe Leroy 	return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
17114b439e25SChristophe Leroy }
17121da177e4SLinus Torvalds #endif
17131da177e4SLinus Torvalds 
17141da177e4SLinus Torvalds /*
17151da177e4SLinus Torvalds  * This mmap-allocator allocates new areas top-down from below the
17161da177e4SLinus Torvalds  * stack's low limit (the base):
17171da177e4SLinus Torvalds  */
17181da177e4SLinus Torvalds unsigned long
17194b439e25SChristophe Leroy generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
172043cca0b1SYang Fan 				  unsigned long len, unsigned long pgoff,
172143cca0b1SYang Fan 				  unsigned long flags)
17221da177e4SLinus Torvalds {
17231be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
17241da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1725db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
17262cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
17271da177e4SLinus Torvalds 
17281da177e4SLinus Torvalds 	/* requested length too big for entire address space */
1729f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
17301da177e4SLinus Torvalds 		return -ENOMEM;
17311da177e4SLinus Torvalds 
173206abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
173306abdfb4SBenjamin Herrenschmidt 		return addr;
173406abdfb4SBenjamin Herrenschmidt 
17351da177e4SLinus Torvalds 	/* requesting a specific address */
17361da177e4SLinus Torvalds 	if (addr) {
17371da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
17381be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1739f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
17401be7107fSHugh Dickins 				(!vma || addr + len <= vm_start_gap(vma)) &&
17411be7107fSHugh Dickins 				(!prev || addr >= vm_end_gap(prev)))
17421da177e4SLinus Torvalds 			return addr;
17431da177e4SLinus Torvalds 	}
17441da177e4SLinus Torvalds 
1745db4fbfb9SMichel Lespinasse 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1746db4fbfb9SMichel Lespinasse 	info.length = len;
17476b008640SLinus Torvalds 	info.low_limit = PAGE_SIZE;
1748f6795053SSteve Capper 	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1749db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
175009ef5283SJaewon Kim 	info.align_offset = 0;
1751db4fbfb9SMichel Lespinasse 	addr = vm_unmapped_area(&info);
1752b716ad95SXiao Guangrong 
17531da177e4SLinus Torvalds 	/*
17541da177e4SLinus Torvalds 	 * A failed mmap() very likely causes application failure,
17551da177e4SLinus Torvalds 	 * so fall back to the bottom-up function here. This scenario
17561da177e4SLinus Torvalds 	 * can happen with large stack limits and large mmap()
17571da177e4SLinus Torvalds 	 * allocations.
17581da177e4SLinus Torvalds 	 */
1759de1741a1SAlexander Kuleshov 	if (offset_in_page(addr)) {
1760db4fbfb9SMichel Lespinasse 		VM_BUG_ON(addr != -ENOMEM);
1761db4fbfb9SMichel Lespinasse 		info.flags = 0;
1762db4fbfb9SMichel Lespinasse 		info.low_limit = TASK_UNMAPPED_BASE;
1763f6795053SSteve Capper 		info.high_limit = mmap_end;
1764db4fbfb9SMichel Lespinasse 		addr = vm_unmapped_area(&info);
1765db4fbfb9SMichel Lespinasse 	}
17661da177e4SLinus Torvalds 
17671da177e4SLinus Torvalds 	return addr;
17681da177e4SLinus Torvalds }
17694b439e25SChristophe Leroy 
17704b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
17714b439e25SChristophe Leroy unsigned long
17724b439e25SChristophe Leroy arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
17734b439e25SChristophe Leroy 			       unsigned long len, unsigned long pgoff,
17744b439e25SChristophe Leroy 			       unsigned long flags)
17754b439e25SChristophe Leroy {
17764b439e25SChristophe Leroy 	return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
17774b439e25SChristophe Leroy }
17781da177e4SLinus Torvalds #endif
17791da177e4SLinus Torvalds 
17801da177e4SLinus Torvalds unsigned long
17811da177e4SLinus Torvalds get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
17821da177e4SLinus Torvalds 		unsigned long pgoff, unsigned long flags)
17831da177e4SLinus Torvalds {
178406abdfb4SBenjamin Herrenschmidt 	unsigned long (*get_area)(struct file *, unsigned long,
178506abdfb4SBenjamin Herrenschmidt 				  unsigned long, unsigned long, unsigned long);
178607ab67c8SLinus Torvalds 
17879206de95SAl Viro 	unsigned long error = arch_mmap_check(addr, len, flags);
17889206de95SAl Viro 	if (error)
17899206de95SAl Viro 		return error;
17909206de95SAl Viro 
17919206de95SAl Viro 	/* Careful about overflows.. */
17929206de95SAl Viro 	if (len > TASK_SIZE)
17939206de95SAl Viro 		return -ENOMEM;
17949206de95SAl Viro 
179507ab67c8SLinus Torvalds 	get_area = current->mm->get_unmapped_area;
1796c01d5b30SHugh Dickins 	if (file) {
1797c01d5b30SHugh Dickins 		if (file->f_op->get_unmapped_area)
179807ab67c8SLinus Torvalds 			get_area = file->f_op->get_unmapped_area;
1799c01d5b30SHugh Dickins 	} else if (flags & MAP_SHARED) {
1800c01d5b30SHugh Dickins 		/*
1801c01d5b30SHugh Dickins 		 * mmap_region() will call shmem_zero_setup() to create a file,
1802c01d5b30SHugh Dickins 		 * so use shmem's get_unmapped_area in case it can be huge.
180345e55300SPeter Collingbourne 		 * do_mmap() will clear pgoff, so match alignment.
1804c01d5b30SHugh Dickins 		 */
1805c01d5b30SHugh Dickins 		pgoff = 0;
1806c01d5b30SHugh Dickins 		get_area = shmem_get_unmapped_area;
1807c01d5b30SHugh Dickins 	}
1808c01d5b30SHugh Dickins 
180907ab67c8SLinus Torvalds 	addr = get_area(file, addr, len, pgoff, flags);
181007ab67c8SLinus Torvalds 	if (IS_ERR_VALUE(addr))
181107ab67c8SLinus Torvalds 		return addr;
181207ab67c8SLinus Torvalds 
18131da177e4SLinus Torvalds 	if (addr > TASK_SIZE - len)
18141da177e4SLinus Torvalds 		return -ENOMEM;
1815de1741a1SAlexander Kuleshov 	if (offset_in_page(addr))
18161da177e4SLinus Torvalds 		return -EINVAL;
181706abdfb4SBenjamin Herrenschmidt 
18189ac4ed4bSAl Viro 	error = security_mmap_addr(addr);
18199ac4ed4bSAl Viro 	return error ? error : addr;
18201da177e4SLinus Torvalds }
18211da177e4SLinus Torvalds 
18221da177e4SLinus Torvalds EXPORT_SYMBOL(get_unmapped_area);
18231da177e4SLinus Torvalds 
1824be8432e7SLiam R. Howlett /**
1825abdba2ddSLiam R. Howlett  * find_vma_intersection() - Look up the first VMA which intersects the interval
1826abdba2ddSLiam R. Howlett  * @mm: The process address space.
1827abdba2ddSLiam R. Howlett  * @start_addr: The inclusive start user address.
1828abdba2ddSLiam R. Howlett  * @end_addr: The exclusive end user address.
1829abdba2ddSLiam R. Howlett  *
1830abdba2ddSLiam R. Howlett  * Returns: The first VMA within the provided range, %NULL otherwise.  Assumes
1831abdba2ddSLiam R. Howlett  * start_addr < end_addr.
1832abdba2ddSLiam R. Howlett  */
1833abdba2ddSLiam R. Howlett struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
1834abdba2ddSLiam R. Howlett 					     unsigned long start_addr,
1835abdba2ddSLiam R. Howlett 					     unsigned long end_addr)
1836abdba2ddSLiam R. Howlett {
1837abdba2ddSLiam R. Howlett 	unsigned long index = start_addr;
1838abdba2ddSLiam R. Howlett 
1839abdba2ddSLiam R. Howlett 	mmap_assert_locked(mm);
18407964cf8cSLiam R. Howlett 	return mt_find(&mm->mm_mt, &index, end_addr - 1);
1841abdba2ddSLiam R. Howlett }
1842abdba2ddSLiam R. Howlett EXPORT_SYMBOL(find_vma_intersection);
1843abdba2ddSLiam R. Howlett 
1844abdba2ddSLiam R. Howlett /**
1845be8432e7SLiam R. Howlett  * find_vma() - Find the VMA for a given address, or the next VMA.
1846be8432e7SLiam R. Howlett  * @mm: The mm_struct to check
1847be8432e7SLiam R. Howlett  * @addr: The address
1848be8432e7SLiam R. Howlett  *
1849be8432e7SLiam R. Howlett  * Returns: The VMA associated with addr, or the next VMA.
1850be8432e7SLiam R. Howlett  * May return %NULL in the case of no VMA at addr or above.
1851be8432e7SLiam R. Howlett  */
18521da177e4SLinus Torvalds struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
18531da177e4SLinus Torvalds {
1854be8432e7SLiam R. Howlett 	unsigned long index = addr;
18551da177e4SLinus Torvalds 
18565b78ed24SLuigi Rizzo 	mmap_assert_locked(mm);
18577964cf8cSLiam R. Howlett 	return mt_find(&mm->mm_mt, &index, ULONG_MAX);
18581da177e4SLinus Torvalds }
18591da177e4SLinus Torvalds EXPORT_SYMBOL(find_vma);
18601da177e4SLinus Torvalds 
18617fdbd37dSLiam R. Howlett /**
18627fdbd37dSLiam R. Howlett  * find_vma_prev() - Find the VMA for a given address, or the next vma and
18637fdbd37dSLiam R. Howlett  * set %pprev to the previous VMA, if any.
18647fdbd37dSLiam R. Howlett  * @mm: The mm_struct to check
18657fdbd37dSLiam R. Howlett  * @addr: The address
18667fdbd37dSLiam R. Howlett  * @pprev: The pointer to set to the previous VMA
18677fdbd37dSLiam R. Howlett  *
18687fdbd37dSLiam R. Howlett  * Note that RCU lock is missing here since the external mmap_lock() is used
18697fdbd37dSLiam R. Howlett  * instead.
18707fdbd37dSLiam R. Howlett  *
18717fdbd37dSLiam R. Howlett  * Returns: The VMA associated with @addr, or the next vma.
18727fdbd37dSLiam R. Howlett  * May return %NULL in the case of no vma at addr or above.
18736bd4837dSKOSAKI Motohiro  */
18741da177e4SLinus Torvalds struct vm_area_struct *
18751da177e4SLinus Torvalds find_vma_prev(struct mm_struct *mm, unsigned long addr,
18761da177e4SLinus Torvalds 			struct vm_area_struct **pprev)
18771da177e4SLinus Torvalds {
18786bd4837dSKOSAKI Motohiro 	struct vm_area_struct *vma;
18797fdbd37dSLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, addr, addr);
18801da177e4SLinus Torvalds 
18817fdbd37dSLiam R. Howlett 	vma = mas_walk(&mas);
18827fdbd37dSLiam R. Howlett 	*pprev = mas_prev(&mas, 0);
18837fdbd37dSLiam R. Howlett 	if (!vma)
18847fdbd37dSLiam R. Howlett 		vma = mas_next(&mas, ULONG_MAX);
18856bd4837dSKOSAKI Motohiro 	return vma;
18861da177e4SLinus Torvalds }
18871da177e4SLinus Torvalds 
18881da177e4SLinus Torvalds /*
18891da177e4SLinus Torvalds  * Verify that the stack growth is acceptable and
18901da177e4SLinus Torvalds  * update accounting. This is shared with both the
18911da177e4SLinus Torvalds  * grow-up and grow-down cases.
18921da177e4SLinus Torvalds  */
18931be7107fSHugh Dickins static int acct_stack_growth(struct vm_area_struct *vma,
18941be7107fSHugh Dickins 			     unsigned long size, unsigned long grow)
18951da177e4SLinus Torvalds {
18961da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
18971be7107fSHugh Dickins 	unsigned long new_start;
18981da177e4SLinus Torvalds 
18991da177e4SLinus Torvalds 	/* address space limit tests */
190084638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vma->vm_flags, grow))
19011da177e4SLinus Torvalds 		return -ENOMEM;
19021da177e4SLinus Torvalds 
19031da177e4SLinus Torvalds 	/* Stack limit test */
190424c79d8eSKrzysztof Opasiak 	if (size > rlimit(RLIMIT_STACK))
19051da177e4SLinus Torvalds 		return -ENOMEM;
19061da177e4SLinus Torvalds 
19071da177e4SLinus Torvalds 	/* mlock limit tests */
1908b0cc5e89SAndrew Morton 	if (!mlock_future_ok(mm, vma->vm_flags, grow << PAGE_SHIFT))
19091da177e4SLinus Torvalds 		return -ENOMEM;
19101da177e4SLinus Torvalds 
19110d59a01bSAdam Litke 	/* Check to ensure the stack will not grow into a hugetlb-only region */
19120d59a01bSAdam Litke 	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
19130d59a01bSAdam Litke 			vma->vm_end - size;
19140d59a01bSAdam Litke 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
19150d59a01bSAdam Litke 		return -EFAULT;
19160d59a01bSAdam Litke 
19171da177e4SLinus Torvalds 	/*
19181da177e4SLinus Torvalds 	 * Overcommit..  This must be the final test, as it will
19191da177e4SLinus Torvalds 	 * update security statistics.
19201da177e4SLinus Torvalds 	 */
192105fa199dSHugh Dickins 	if (security_vm_enough_memory_mm(mm, grow))
19221da177e4SLinus Torvalds 		return -ENOMEM;
19231da177e4SLinus Torvalds 
19241da177e4SLinus Torvalds 	return 0;
19251da177e4SLinus Torvalds }
19261da177e4SLinus Torvalds 
192746dea3d0SHugh Dickins #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
19281da177e4SLinus Torvalds /*
192946dea3d0SHugh Dickins  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
193046dea3d0SHugh Dickins  * vma is the last one with address > vma->vm_end.  Have to extend vma.
19311da177e4SLinus Torvalds  */
19328d7071afSLinus Torvalds static int expand_upwards(struct vm_area_struct *vma, unsigned long address)
19331da177e4SLinus Torvalds {
193409357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
19351be7107fSHugh Dickins 	struct vm_area_struct *next;
19361be7107fSHugh Dickins 	unsigned long gap_addr;
193712352d3cSKonstantin Khlebnikov 	int error = 0;
1938d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
19391da177e4SLinus Torvalds 
19401da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSUP))
19411da177e4SLinus Torvalds 		return -EFAULT;
19421da177e4SLinus Torvalds 
1943bd726c90SHelge Deller 	/* Guard against exceeding limits of the address space. */
19441be7107fSHugh Dickins 	address &= PAGE_MASK;
194537511fb5SHelge Deller 	if (address >= (TASK_SIZE & PAGE_MASK))
194612352d3cSKonstantin Khlebnikov 		return -ENOMEM;
1947bd726c90SHelge Deller 	address += PAGE_SIZE;
194812352d3cSKonstantin Khlebnikov 
19491be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
19501be7107fSHugh Dickins 	gap_addr = address + stack_guard_gap;
1951bd726c90SHelge Deller 
1952bd726c90SHelge Deller 	/* Guard against overflow */
1953bd726c90SHelge Deller 	if (gap_addr < address || gap_addr > TASK_SIZE)
1954bd726c90SHelge Deller 		gap_addr = TASK_SIZE;
1955bd726c90SHelge Deller 
1956763ecb03SLiam R. Howlett 	next = find_vma_intersection(mm, vma->vm_end, gap_addr);
1957763ecb03SLiam R. Howlett 	if (next && vma_is_accessible(next)) {
19581be7107fSHugh Dickins 		if (!(next->vm_flags & VM_GROWSUP))
19591be7107fSHugh Dickins 			return -ENOMEM;
19601be7107fSHugh Dickins 		/* Check that both stack segments have the same anon_vma? */
19611be7107fSHugh Dickins 	}
19621be7107fSHugh Dickins 
1963*da089254SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
19641da177e4SLinus Torvalds 		return -ENOMEM;
19651da177e4SLinus Torvalds 
1966d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
1967d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
1968d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
1969d4af56c5SLiam R. Howlett 		return -ENOMEM;
1970d4af56c5SLiam R. Howlett 	}
1971d4af56c5SLiam R. Howlett 
1972c137381fSSuren Baghdasaryan 	/* Lock the VMA before expanding to prevent concurrent page faults */
1973c137381fSSuren Baghdasaryan 	vma_start_write(vma);
19741da177e4SLinus Torvalds 	/*
19751da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
1976c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
19771da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
19781da177e4SLinus Torvalds 	 */
197912352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
19801da177e4SLinus Torvalds 
19811da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
19821da177e4SLinus Torvalds 	if (address > vma->vm_end) {
19831da177e4SLinus Torvalds 		unsigned long size, grow;
19841da177e4SLinus Torvalds 
19851da177e4SLinus Torvalds 		size = address - vma->vm_start;
19861da177e4SLinus Torvalds 		grow = (address - vma->vm_end) >> PAGE_SHIFT;
19871da177e4SLinus Torvalds 
198842c36f63SHugh Dickins 		error = -ENOMEM;
198942c36f63SHugh Dickins 		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
19901da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
19913af9e859SEric B Munson 			if (!error) {
19924128997bSMichel Lespinasse 				/*
1993524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
1994524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
1995524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
1996524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
1997524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
1998524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
1999524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
20004128997bSMichel Lespinasse 				 */
200109357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
200287e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
200309357814SOleg Nesterov 					mm->locked_vm += grow;
200484638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2005bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
20061da177e4SLinus Torvalds 				vma->vm_end = address;
2007d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2008fbcc3104SLiam R. Howlett 				mas_set_range(&mas, vma->vm_start, address - 1);
2009fbcc3104SLiam R. Howlett 				mas_store_prealloc(&mas, vma);
2010bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
201109357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
20124128997bSMichel Lespinasse 
20133af9e859SEric B Munson 				perf_event_mmap(vma);
20143af9e859SEric B Munson 			}
20151da177e4SLinus Torvalds 		}
201642c36f63SHugh Dickins 	}
201712352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2018c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2019d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
20202574d5e4SLiam R. Howlett 	validate_mm(mm);
20211da177e4SLinus Torvalds 	return error;
20221da177e4SLinus Torvalds }
202346dea3d0SHugh Dickins #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
202446dea3d0SHugh Dickins 
20251da177e4SLinus Torvalds /*
20261da177e4SLinus Torvalds  * vma is the first one with address < vma->vm_start.  Have to extend vma.
20278d7071afSLinus Torvalds  * mmap_lock held for writing.
20281da177e4SLinus Torvalds  */
2029524e00b3SLiam R. Howlett int expand_downwards(struct vm_area_struct *vma, unsigned long address)
20301da177e4SLinus Torvalds {
203109357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
2032763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
20331be7107fSHugh Dickins 	struct vm_area_struct *prev;
20340a1d5299SJann Horn 	int error = 0;
20351da177e4SLinus Torvalds 
20368d7071afSLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSDOWN))
20378d7071afSLinus Torvalds 		return -EFAULT;
20388d7071afSLinus Torvalds 
20398869477aSEric Paris 	address &= PAGE_MASK;
20408b35ca3eSBen Hutchings 	if (address < mmap_min_addr || address < FIRST_USER_ADDRESS)
20410a1d5299SJann Horn 		return -EPERM;
20428869477aSEric Paris 
20431be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
2044763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
20451be7107fSHugh Dickins 	/* Check that both stack segments have the same anon_vma? */
2046f440fa1aSLiam R. Howlett 	if (prev) {
2047f440fa1aSLiam R. Howlett 		if (!(prev->vm_flags & VM_GROWSDOWN) &&
2048f440fa1aSLiam R. Howlett 		    vma_is_accessible(prev) &&
2049f440fa1aSLiam R. Howlett 		    (address - prev->vm_end < stack_guard_gap))
205032e4e6d5SOleg Nesterov 			return -ENOMEM;
20511be7107fSHugh Dickins 	}
20521be7107fSHugh Dickins 
2053*da089254SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
205412352d3cSKonstantin Khlebnikov 		return -ENOMEM;
20551da177e4SLinus Torvalds 
2056d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
2057d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
2058d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
2059d4af56c5SLiam R. Howlett 		return -ENOMEM;
2060d4af56c5SLiam R. Howlett 	}
2061d4af56c5SLiam R. Howlett 
2062c137381fSSuren Baghdasaryan 	/* Lock the VMA before expanding to prevent concurrent page faults */
2063c137381fSSuren Baghdasaryan 	vma_start_write(vma);
20641da177e4SLinus Torvalds 	/*
20651da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2066c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
20671da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
20681da177e4SLinus Torvalds 	 */
206912352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
20701da177e4SLinus Torvalds 
20711da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
20721da177e4SLinus Torvalds 	if (address < vma->vm_start) {
20731da177e4SLinus Torvalds 		unsigned long size, grow;
20741da177e4SLinus Torvalds 
20751da177e4SLinus Torvalds 		size = vma->vm_end - address;
20761da177e4SLinus Torvalds 		grow = (vma->vm_start - address) >> PAGE_SHIFT;
20771da177e4SLinus Torvalds 
2078a626ca6aSLinus Torvalds 		error = -ENOMEM;
2079a626ca6aSLinus Torvalds 		if (grow <= vma->vm_pgoff) {
20801da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
20811da177e4SLinus Torvalds 			if (!error) {
20824128997bSMichel Lespinasse 				/*
2083524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
2084524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
2085524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
2086524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
2087524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
2088524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
2089524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
20904128997bSMichel Lespinasse 				 */
209109357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
209287e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
209309357814SOleg Nesterov 					mm->locked_vm += grow;
209484638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2095bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
20961da177e4SLinus Torvalds 				vma->vm_start = address;
20971da177e4SLinus Torvalds 				vma->vm_pgoff -= grow;
2098d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2099fbcc3104SLiam R. Howlett 				mas_set_range(&mas, address, vma->vm_end - 1);
2100fbcc3104SLiam R. Howlett 				mas_store_prealloc(&mas, vma);
2101bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
210209357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
21034128997bSMichel Lespinasse 
21043af9e859SEric B Munson 				perf_event_mmap(vma);
21051da177e4SLinus Torvalds 			}
21061da177e4SLinus Torvalds 		}
2107a626ca6aSLinus Torvalds 	}
210812352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2109c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2110d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
21112574d5e4SLiam R. Howlett 	validate_mm(mm);
21121da177e4SLinus Torvalds 	return error;
21131da177e4SLinus Torvalds }
21141da177e4SLinus Torvalds 
21151be7107fSHugh Dickins /* enforced gap between the expanding stack and other mappings. */
21161be7107fSHugh Dickins unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
21171be7107fSHugh Dickins 
21181be7107fSHugh Dickins static int __init cmdline_parse_stack_guard_gap(char *p)
21191be7107fSHugh Dickins {
21201be7107fSHugh Dickins 	unsigned long val;
21211be7107fSHugh Dickins 	char *endptr;
21221be7107fSHugh Dickins 
21231be7107fSHugh Dickins 	val = simple_strtoul(p, &endptr, 10);
21241be7107fSHugh Dickins 	if (!*endptr)
21251be7107fSHugh Dickins 		stack_guard_gap = val << PAGE_SHIFT;
21261be7107fSHugh Dickins 
2127e6d09493SRandy Dunlap 	return 1;
21281be7107fSHugh Dickins }
21291be7107fSHugh Dickins __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
21301be7107fSHugh Dickins 
2131b6a2fea3SOllie Wild #ifdef CONFIG_STACK_GROWSUP
21328d7071afSLinus Torvalds int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
2133b6a2fea3SOllie Wild {
2134b6a2fea3SOllie Wild 	return expand_upwards(vma, address);
2135b6a2fea3SOllie Wild }
2136b6a2fea3SOllie Wild 
21378d7071afSLinus Torvalds struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
2138b6a2fea3SOllie Wild {
2139b6a2fea3SOllie Wild 	struct vm_area_struct *vma, *prev;
2140b6a2fea3SOllie Wild 
2141b6a2fea3SOllie Wild 	addr &= PAGE_MASK;
2142b6a2fea3SOllie Wild 	vma = find_vma_prev(mm, addr, &prev);
2143b6a2fea3SOllie Wild 	if (vma && (vma->vm_start <= addr))
2144b6a2fea3SOllie Wild 		return vma;
2145f440fa1aSLiam R. Howlett 	if (!prev)
2146f440fa1aSLiam R. Howlett 		return NULL;
21478d7071afSLinus Torvalds 	if (expand_stack_locked(prev, addr))
2148b6a2fea3SOllie Wild 		return NULL;
2149cea10a19SMichel Lespinasse 	if (prev->vm_flags & VM_LOCKED)
2150fc05f566SKirill A. Shutemov 		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2151b6a2fea3SOllie Wild 	return prev;
2152b6a2fea3SOllie Wild }
2153b6a2fea3SOllie Wild #else
21548d7071afSLinus Torvalds int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
2155b6a2fea3SOllie Wild {
2156f440fa1aSLiam R. Howlett 	if (unlikely(!(vma->vm_flags & VM_GROWSDOWN)))
2157f440fa1aSLiam R. Howlett 		return -EINVAL;
2158b6a2fea3SOllie Wild 	return expand_downwards(vma, address);
2159b6a2fea3SOllie Wild }
2160b6a2fea3SOllie Wild 
21618d7071afSLinus Torvalds struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
21621da177e4SLinus Torvalds {
21631da177e4SLinus Torvalds 	struct vm_area_struct *vma;
21641da177e4SLinus Torvalds 	unsigned long start;
21651da177e4SLinus Torvalds 
21661da177e4SLinus Torvalds 	addr &= PAGE_MASK;
21671da177e4SLinus Torvalds 	vma = find_vma(mm, addr);
21681da177e4SLinus Torvalds 	if (!vma)
21691da177e4SLinus Torvalds 		return NULL;
21701da177e4SLinus Torvalds 	if (vma->vm_start <= addr)
21711da177e4SLinus Torvalds 		return vma;
21721da177e4SLinus Torvalds 	start = vma->vm_start;
21738d7071afSLinus Torvalds 	if (expand_stack_locked(vma, addr))
21741da177e4SLinus Torvalds 		return NULL;
2175cea10a19SMichel Lespinasse 	if (vma->vm_flags & VM_LOCKED)
2176fc05f566SKirill A. Shutemov 		populate_vma_page_range(vma, addr, start, NULL);
21771da177e4SLinus Torvalds 	return vma;
21781da177e4SLinus Torvalds }
21791da177e4SLinus Torvalds #endif
21801da177e4SLinus Torvalds 
21818d7071afSLinus Torvalds /*
21828d7071afSLinus Torvalds  * IA64 has some horrid mapping rules: it can expand both up and down,
21838d7071afSLinus Torvalds  * but with various special rules.
21848d7071afSLinus Torvalds  *
21858d7071afSLinus Torvalds  * We'll get rid of this architecture eventually, so the ugliness is
21868d7071afSLinus Torvalds  * temporary.
21878d7071afSLinus Torvalds  */
21888d7071afSLinus Torvalds #ifdef CONFIG_IA64
21898d7071afSLinus Torvalds static inline bool vma_expand_ok(struct vm_area_struct *vma, unsigned long addr)
2190f440fa1aSLiam R. Howlett {
21918d7071afSLinus Torvalds 	return REGION_NUMBER(addr) == REGION_NUMBER(vma->vm_start) &&
21928d7071afSLinus Torvalds 		REGION_OFFSET(addr) < RGN_MAP_LIMIT;
2193f440fa1aSLiam R. Howlett }
21948d7071afSLinus Torvalds 
21958d7071afSLinus Torvalds /*
21968d7071afSLinus Torvalds  * IA64 stacks grow down, but there's a special register backing store
21978d7071afSLinus Torvalds  * that can grow up. Only sequentially, though, so the new address must
21988d7071afSLinus Torvalds  * match vm_end.
21998d7071afSLinus Torvalds  */
22008d7071afSLinus Torvalds static inline int vma_expand_up(struct vm_area_struct *vma, unsigned long addr)
22018d7071afSLinus Torvalds {
22028d7071afSLinus Torvalds 	if (!vma_expand_ok(vma, addr))
22038d7071afSLinus Torvalds 		return -EFAULT;
22048d7071afSLinus Torvalds 	if (vma->vm_end != (addr & PAGE_MASK))
22058d7071afSLinus Torvalds 		return -EFAULT;
22068d7071afSLinus Torvalds 	return expand_upwards(vma, addr);
22078d7071afSLinus Torvalds }
22088d7071afSLinus Torvalds 
22098d7071afSLinus Torvalds static inline bool vma_expand_down(struct vm_area_struct *vma, unsigned long addr)
22108d7071afSLinus Torvalds {
22118d7071afSLinus Torvalds 	if (!vma_expand_ok(vma, addr))
22128d7071afSLinus Torvalds 		return -EFAULT;
22138d7071afSLinus Torvalds 	return expand_downwards(vma, addr);
22148d7071afSLinus Torvalds }
22158d7071afSLinus Torvalds 
22168d7071afSLinus Torvalds #elif defined(CONFIG_STACK_GROWSUP)
22178d7071afSLinus Torvalds 
22188d7071afSLinus Torvalds #define vma_expand_up(vma,addr) expand_upwards(vma, addr)
22198d7071afSLinus Torvalds #define vma_expand_down(vma, addr) (-EFAULT)
22208d7071afSLinus Torvalds 
22218d7071afSLinus Torvalds #else
22228d7071afSLinus Torvalds 
22238d7071afSLinus Torvalds #define vma_expand_up(vma,addr) (-EFAULT)
22248d7071afSLinus Torvalds #define vma_expand_down(vma, addr) expand_downwards(vma, addr)
22258d7071afSLinus Torvalds 
22268d7071afSLinus Torvalds #endif
22278d7071afSLinus Torvalds 
22288d7071afSLinus Torvalds /*
22298d7071afSLinus Torvalds  * expand_stack(): legacy interface for page faulting. Don't use unless
22308d7071afSLinus Torvalds  * you have to.
22318d7071afSLinus Torvalds  *
22328d7071afSLinus Torvalds  * This is called with the mm locked for reading, drops the lock, takes
22338d7071afSLinus Torvalds  * the lock for writing, tries to look up a vma again, expands it if
22348d7071afSLinus Torvalds  * necessary, and downgrades the lock to reading again.
22358d7071afSLinus Torvalds  *
22368d7071afSLinus Torvalds  * If no vma is found or it can't be expanded, it returns NULL and has
22378d7071afSLinus Torvalds  * dropped the lock.
22388d7071afSLinus Torvalds  */
22398d7071afSLinus Torvalds struct vm_area_struct *expand_stack(struct mm_struct *mm, unsigned long addr)
22408d7071afSLinus Torvalds {
22418d7071afSLinus Torvalds 	struct vm_area_struct *vma, *prev;
22428d7071afSLinus Torvalds 
22438d7071afSLinus Torvalds 	mmap_read_unlock(mm);
22448d7071afSLinus Torvalds 	if (mmap_write_lock_killable(mm))
22458d7071afSLinus Torvalds 		return NULL;
22468d7071afSLinus Torvalds 
22478d7071afSLinus Torvalds 	vma = find_vma_prev(mm, addr, &prev);
22488d7071afSLinus Torvalds 	if (vma && vma->vm_start <= addr)
22498d7071afSLinus Torvalds 		goto success;
22508d7071afSLinus Torvalds 
22518d7071afSLinus Torvalds 	if (prev && !vma_expand_up(prev, addr)) {
22528d7071afSLinus Torvalds 		vma = prev;
22538d7071afSLinus Torvalds 		goto success;
22548d7071afSLinus Torvalds 	}
22558d7071afSLinus Torvalds 
22568d7071afSLinus Torvalds 	if (vma && !vma_expand_down(vma, addr))
22578d7071afSLinus Torvalds 		goto success;
22588d7071afSLinus Torvalds 
22598d7071afSLinus Torvalds 	mmap_write_unlock(mm);
22608d7071afSLinus Torvalds 	return NULL;
22618d7071afSLinus Torvalds 
22628d7071afSLinus Torvalds success:
22638d7071afSLinus Torvalds 	mmap_write_downgrade(mm);
22648d7071afSLinus Torvalds 	return vma;
22658d7071afSLinus Torvalds }
2266e1d6d01aSJesse Barnes 
22672c0b3814SHugh Dickins /*
2268763ecb03SLiam R. Howlett  * Ok - we have the memory areas we should free on a maple tree so release them,
2269763ecb03SLiam R. Howlett  * and do the vma updates.
22701da177e4SLinus Torvalds  *
22712c0b3814SHugh Dickins  * Called with the mm semaphore held.
22721da177e4SLinus Torvalds  */
2273763ecb03SLiam R. Howlett static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
22741da177e4SLinus Torvalds {
22754f74d2c8SLinus Torvalds 	unsigned long nr_accounted = 0;
2276763ecb03SLiam R. Howlett 	struct vm_area_struct *vma;
22774f74d2c8SLinus Torvalds 
2278365e9c87SHugh Dickins 	/* Update high watermark before we lower total_vm */
2279365e9c87SHugh Dickins 	update_hiwater_vm(mm);
2280763ecb03SLiam R. Howlett 	mas_for_each(mas, vma, ULONG_MAX) {
2281ab50b8edSHugh Dickins 		long nrpages = vma_pages(vma);
22821da177e4SLinus Torvalds 
22834f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
22844f74d2c8SLinus Torvalds 			nr_accounted += nrpages;
228584638335SKonstantin Khlebnikov 		vm_stat_account(mm, vma->vm_flags, -nrpages);
22860d2ebf9cSSuren Baghdasaryan 		remove_vma(vma, false);
2287763ecb03SLiam R. Howlett 	}
22884f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
22891da177e4SLinus Torvalds }
22901da177e4SLinus Torvalds 
22911da177e4SLinus Torvalds /*
22921da177e4SLinus Torvalds  * Get rid of page table information in the indicated region.
22931da177e4SLinus Torvalds  *
2294f10df686SPaolo 'Blaisorblade' Giarrusso  * Called with the mm semaphore held.
22951da177e4SLinus Torvalds  */
2296fd892593SLiam R. Howlett static void unmap_region(struct mm_struct *mm, struct ma_state *mas,
2297e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
2298fd892593SLiam R. Howlett 		struct vm_area_struct *next, unsigned long start,
2299fd892593SLiam R. Howlett 		unsigned long end, unsigned long tree_end, bool mm_wr_locked)
23001da177e4SLinus Torvalds {
2301d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
2302fd892593SLiam R. Howlett 	unsigned long mt_start = mas->index;
23031da177e4SLinus Torvalds 
23041da177e4SLinus Torvalds 	lru_add_drain();
2305a72afd87SWill Deacon 	tlb_gather_mmu(&tlb, mm);
2306365e9c87SHugh Dickins 	update_hiwater_rss(mm);
2307fd892593SLiam R. Howlett 	unmap_vmas(&tlb, mas, vma, start, end, tree_end, mm_wr_locked);
2308fd892593SLiam R. Howlett 	mas_set(mas, mt_start);
2309fd892593SLiam R. Howlett 	free_pgtables(&tlb, mas, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
231098e51a22SSuren Baghdasaryan 				 next ? next->vm_start : USER_PGTABLES_CEILING,
231198e51a22SSuren Baghdasaryan 				 mm_wr_locked);
2312ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
23131da177e4SLinus Torvalds }
23141da177e4SLinus Torvalds 
23151da177e4SLinus Torvalds /*
2316def5efe0SDavid Rientjes  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2317def5efe0SDavid Rientjes  * has already been checked or doesn't make sense to fail.
23180fd5a9e2SLiam R. Howlett  * VMA Iterator will point to the end VMA.
23191da177e4SLinus Torvalds  */
23209760ebffSLiam R. Howlett int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
23211da177e4SLinus Torvalds 		unsigned long addr, int new_below)
23221da177e4SLinus Torvalds {
2323b2b3b886SLiam R. Howlett 	struct vma_prepare vp;
23241da177e4SLinus Torvalds 	struct vm_area_struct *new;
2325e3975891SChen Gang 	int err;
23269760ebffSLiam R. Howlett 
2327b2b3b886SLiam R. Howlett 	WARN_ON(vma->vm_start >= addr);
2328b2b3b886SLiam R. Howlett 	WARN_ON(vma->vm_end <= addr);
2329b2b3b886SLiam R. Howlett 
2330dd3b614fSDmitry Safonov 	if (vma->vm_ops && vma->vm_ops->may_split) {
2331dd3b614fSDmitry Safonov 		err = vma->vm_ops->may_split(vma, addr);
233231383c68SDan Williams 		if (err)
233331383c68SDan Williams 			return err;
233431383c68SDan Williams 	}
23351da177e4SLinus Torvalds 
23363928d4f5SLinus Torvalds 	new = vm_area_dup(vma);
23371da177e4SLinus Torvalds 	if (!new)
2338e3975891SChen Gang 		return -ENOMEM;
23391da177e4SLinus Torvalds 
2340b2b3b886SLiam R. Howlett 	err = -ENOMEM;
2341b2b3b886SLiam R. Howlett 	if (vma_iter_prealloc(vmi))
2342b2b3b886SLiam R. Howlett 		goto out_free_vma;
2343b2b3b886SLiam R. Howlett 
2344b2b3b886SLiam R. Howlett 	if (new_below) {
23451da177e4SLinus Torvalds 		new->vm_end = addr;
2346b2b3b886SLiam R. Howlett 	} else {
23471da177e4SLinus Torvalds 		new->vm_start = addr;
23481da177e4SLinus Torvalds 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
23491da177e4SLinus Torvalds 	}
23501da177e4SLinus Torvalds 
2351ef0855d3SOleg Nesterov 	err = vma_dup_policy(vma, new);
2352ef0855d3SOleg Nesterov 	if (err)
2353b2b3b886SLiam R. Howlett 		goto out_free_vmi;
23541da177e4SLinus Torvalds 
2355c4ea95d7SDaniel Forrest 	err = anon_vma_clone(new, vma);
2356c4ea95d7SDaniel Forrest 	if (err)
23575beb4930SRik van Riel 		goto out_free_mpol;
23585beb4930SRik van Riel 
2359e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
23601da177e4SLinus Torvalds 		get_file(new->vm_file);
23611da177e4SLinus Torvalds 
23621da177e4SLinus Torvalds 	if (new->vm_ops && new->vm_ops->open)
23631da177e4SLinus Torvalds 		new->vm_ops->open(new);
23641da177e4SLinus Torvalds 
2365b2b3b886SLiam R. Howlett 	init_vma_prep(&vp, vma);
2366b2b3b886SLiam R. Howlett 	vp.insert = new;
2367b2b3b886SLiam R. Howlett 	vma_prepare(&vp);
2368ccf1d78dSSuren Baghdasaryan 	vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
23691da177e4SLinus Torvalds 
2370b2b3b886SLiam R. Howlett 	if (new_below) {
2371b2b3b886SLiam R. Howlett 		vma->vm_start = addr;
2372b2b3b886SLiam R. Howlett 		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
2373b2b3b886SLiam R. Howlett 	} else {
2374b2b3b886SLiam R. Howlett 		vma->vm_end = addr;
23759760ebffSLiam R. Howlett 	}
23765beb4930SRik van Riel 
2377b2b3b886SLiam R. Howlett 	/* vma_complete stores the new vma */
2378b2b3b886SLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
2379b2b3b886SLiam R. Howlett 
2380b2b3b886SLiam R. Howlett 	/* Success. */
2381b2b3b886SLiam R. Howlett 	if (new_below)
2382b2b3b886SLiam R. Howlett 		vma_next(vmi);
2383b2b3b886SLiam R. Howlett 	return 0;
2384b2b3b886SLiam R. Howlett 
23855beb4930SRik van Riel out_free_mpol:
2386ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new));
2387b2b3b886SLiam R. Howlett out_free_vmi:
2388b2b3b886SLiam R. Howlett 	vma_iter_free(vmi);
23895beb4930SRik van Riel out_free_vma:
23903928d4f5SLinus Torvalds 	vm_area_free(new);
23915beb4930SRik van Riel 	return err;
23921da177e4SLinus Torvalds }
23931da177e4SLinus Torvalds 
2394659ace58SKOSAKI Motohiro /*
2395659ace58SKOSAKI Motohiro  * Split a vma into two pieces at address 'addr', a new vma is allocated
2396659ace58SKOSAKI Motohiro  * either for the first part or the tail.
2397659ace58SKOSAKI Motohiro  */
23989760ebffSLiam R. Howlett int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2399659ace58SKOSAKI Motohiro 	      unsigned long addr, int new_below)
2400659ace58SKOSAKI Motohiro {
24019760ebffSLiam R. Howlett 	if (vma->vm_mm->map_count >= sysctl_max_map_count)
2402659ace58SKOSAKI Motohiro 		return -ENOMEM;
2403659ace58SKOSAKI Motohiro 
24049760ebffSLiam R. Howlett 	return __split_vma(vmi, vma, addr, new_below);
2405f2ebfe43SLiam R. Howlett }
2406f2ebfe43SLiam R. Howlett 
240711f9a21aSLiam R. Howlett /*
2408183654ceSLiam R. Howlett  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
2409183654ceSLiam R. Howlett  * @vmi: The vma iterator
241011f9a21aSLiam R. Howlett  * @vma: The starting vm_area_struct
241111f9a21aSLiam R. Howlett  * @mm: The mm_struct
241211f9a21aSLiam R. Howlett  * @start: The aligned start address to munmap.
241311f9a21aSLiam R. Howlett  * @end: The aligned end address to munmap.
241411f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
2415408579cdSLiam R. Howlett  * @unlock: Set to true to drop the mmap_lock.  unlocking only happens on
2416408579cdSLiam R. Howlett  * success.
241711f9a21aSLiam R. Howlett  *
2418408579cdSLiam R. Howlett  * Return: 0 on success and drops the lock if so directed, error and leaves the
2419408579cdSLiam R. Howlett  * lock held otherwise.
242011f9a21aSLiam R. Howlett  */
242111f9a21aSLiam R. Howlett static int
2422183654ceSLiam R. Howlett do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
242311f9a21aSLiam R. Howlett 		    struct mm_struct *mm, unsigned long start,
2424408579cdSLiam R. Howlett 		    unsigned long end, struct list_head *uf, bool unlock)
242511f9a21aSLiam R. Howlett {
2426763ecb03SLiam R. Howlett 	struct vm_area_struct *prev, *next = NULL;
2427763ecb03SLiam R. Howlett 	struct maple_tree mt_detach;
2428763ecb03SLiam R. Howlett 	int count = 0;
2429d4af56c5SLiam R. Howlett 	int error = -ENOMEM;
2430606c812eSLiam R. Howlett 	unsigned long locked_vm = 0;
2431763ecb03SLiam R. Howlett 	MA_STATE(mas_detach, &mt_detach, 0, 0);
24323dd44325SLiam R. Howlett 	mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
243302fdb25fSLiam R. Howlett 	mt_on_stack(mt_detach);
2434524e00b3SLiam R. Howlett 
24351da177e4SLinus Torvalds 	/*
24361da177e4SLinus Torvalds 	 * If we need to split any vma, do it now to save pain later.
24371da177e4SLinus Torvalds 	 *
24381da177e4SLinus Torvalds 	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
24391da177e4SLinus Torvalds 	 * unmapped vm_area_struct will remain in use: so lower split_vma
24401da177e4SLinus Torvalds 	 * places tmp vma above, and higher split_vma places tmp vma below.
24411da177e4SLinus Torvalds 	 */
2442763ecb03SLiam R. Howlett 
2443763ecb03SLiam R. Howlett 	/* Does it split the first one? */
2444146425a3SHugh Dickins 	if (start > vma->vm_start) {
2445659ace58SKOSAKI Motohiro 
2446659ace58SKOSAKI Motohiro 		/*
2447659ace58SKOSAKI Motohiro 		 * Make sure that map_count on return from munmap() will
2448659ace58SKOSAKI Motohiro 		 * not exceed its limit; but let map_count go just above
2449659ace58SKOSAKI Motohiro 		 * its limit temporarily, to help free resources as expected.
2450659ace58SKOSAKI Motohiro 		 */
2451659ace58SKOSAKI Motohiro 		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2452d4af56c5SLiam R. Howlett 			goto map_count_exceeded;
2453659ace58SKOSAKI Motohiro 
24549760ebffSLiam R. Howlett 		error = __split_vma(vmi, vma, start, 0);
24551da177e4SLinus Torvalds 		if (error)
2456763ecb03SLiam R. Howlett 			goto start_split_failed;
245711f9a21aSLiam R. Howlett 
24580fd5a9e2SLiam R. Howlett 		vma = vma_iter_load(vmi);
24591da177e4SLinus Torvalds 	}
24601da177e4SLinus Torvalds 
2461183654ceSLiam R. Howlett 	prev = vma_prev(vmi);
246211f9a21aSLiam R. Howlett 
2463763ecb03SLiam R. Howlett 	/*
2464763ecb03SLiam R. Howlett 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
2465763ecb03SLiam R. Howlett 	 * it is always overwritten.
2466763ecb03SLiam R. Howlett 	 */
2467183654ceSLiam R. Howlett 	for_each_vma_range(*vmi, next, end) {
2468763ecb03SLiam R. Howlett 		/* Does it split the end? */
2469763ecb03SLiam R. Howlett 		if (next->vm_end > end) {
24706b73cff2SLiam R. Howlett 			error = __split_vma(vmi, next, end, 0);
24711da177e4SLinus Torvalds 			if (error)
2472763ecb03SLiam R. Howlett 				goto end_split_failed;
247311f9a21aSLiam R. Howlett 		}
2474606c812eSLiam R. Howlett 		vma_start_write(next);
2475fd892593SLiam R. Howlett 		mas_set(&mas_detach, count);
24766c26bd43SDavid Woodhouse 		error = mas_store_gfp(&mas_detach, next, GFP_KERNEL);
24776c26bd43SDavid Woodhouse 		if (error)
2478606c812eSLiam R. Howlett 			goto munmap_gather_failed;
2479606c812eSLiam R. Howlett 		vma_mark_detached(next, true);
2480606c812eSLiam R. Howlett 		if (next->vm_flags & VM_LOCKED)
2481606c812eSLiam R. Howlett 			locked_vm += vma_pages(next);
2482763ecb03SLiam R. Howlett 
2483763ecb03SLiam R. Howlett 		count++;
24842376dd7cSAndrea Arcangeli 		if (unlikely(uf)) {
24852376dd7cSAndrea Arcangeli 			/*
24862376dd7cSAndrea Arcangeli 			 * If userfaultfd_unmap_prep returns an error the vmas
2487f0953a1bSIngo Molnar 			 * will remain split, but userland will get a
24882376dd7cSAndrea Arcangeli 			 * highly unexpected error anyway. This is no
24892376dd7cSAndrea Arcangeli 			 * different than the case where the first of the two
24902376dd7cSAndrea Arcangeli 			 * __split_vma fails, but we don't undo the first
24912376dd7cSAndrea Arcangeli 			 * split, despite we could. This is unlikely enough
24922376dd7cSAndrea Arcangeli 			 * failure that it's not worth optimizing it for.
24932376dd7cSAndrea Arcangeli 			 */
249465ac1320SLiam R. Howlett 			error = userfaultfd_unmap_prep(next, start, end, uf);
249511f9a21aSLiam R. Howlett 
24962376dd7cSAndrea Arcangeli 			if (error)
2497d4af56c5SLiam R. Howlett 				goto userfaultfd_error;
24982376dd7cSAndrea Arcangeli 		}
2499ba470de4SRik van Riel #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
2500ba470de4SRik van Riel 		BUG_ON(next->vm_start < start);
2501ba470de4SRik van Riel 		BUG_ON(next->vm_start > end);
25021da177e4SLinus Torvalds #endif
25031da177e4SLinus Torvalds 	}
2504146425a3SHugh Dickins 
250515c0c60bSLiam R. Howlett 	if (vma_iter_end(vmi) > end)
250615c0c60bSLiam R. Howlett 		next = vma_iter_load(vmi);
250715c0c60bSLiam R. Howlett 
250815c0c60bSLiam R. Howlett 	if (!next)
25091da177e4SLinus Torvalds 		next = vma_next(vmi);
25102376dd7cSAndrea Arcangeli 
2511763ecb03SLiam R. Howlett #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2512763ecb03SLiam R. Howlett 	/* Make sure no VMAs are about to be lost. */
2513763ecb03SLiam R. Howlett 	{
2514fd892593SLiam R. Howlett 		MA_STATE(test, &mt_detach, 0, 0);
2515763ecb03SLiam R. Howlett 		struct vm_area_struct *vma_mas, *vma_test;
2516763ecb03SLiam R. Howlett 		int test_count = 0;
2517763ecb03SLiam R. Howlett 
2518183654ceSLiam R. Howlett 		vma_iter_set(vmi, start);
2519763ecb03SLiam R. Howlett 		rcu_read_lock();
2520fd892593SLiam R. Howlett 		vma_test = mas_find(&test, count - 1);
2521183654ceSLiam R. Howlett 		for_each_vma_range(*vmi, vma_mas, end) {
2522763ecb03SLiam R. Howlett 			BUG_ON(vma_mas != vma_test);
2523763ecb03SLiam R. Howlett 			test_count++;
2524fd892593SLiam R. Howlett 			vma_test = mas_next(&test, count - 1);
2525763ecb03SLiam R. Howlett 		}
2526763ecb03SLiam R. Howlett 		rcu_read_unlock();
2527763ecb03SLiam R. Howlett 		BUG_ON(count != test_count);
2528763ecb03SLiam R. Howlett 	}
2529763ecb03SLiam R. Howlett #endif
2530183654ceSLiam R. Howlett 	vma_iter_set(vmi, start);
25316c26bd43SDavid Woodhouse 	error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
25326c26bd43SDavid Woodhouse 	if (error)
2533606c812eSLiam R. Howlett 		goto clear_tree_failed;
25340378c0a0SLiam R. Howlett 
25356c26bd43SDavid Woodhouse 	/* Point of no return */
2536606c812eSLiam R. Howlett 	mm->locked_vm -= locked_vm;
2537763ecb03SLiam R. Howlett 	mm->map_count -= count;
2538408579cdSLiam R. Howlett 	if (unlock)
2539d8ed45c5SMichel Lespinasse 		mmap_write_downgrade(mm);
2540dd2283f2SYang Shi 
254168f48381SSuren Baghdasaryan 	/*
254268f48381SSuren Baghdasaryan 	 * We can free page tables without write-locking mmap_lock because VMAs
254368f48381SSuren Baghdasaryan 	 * were isolated before we downgraded mmap_lock.
254468f48381SSuren Baghdasaryan 	 */
2545fd892593SLiam R. Howlett 	mas_set(&mas_detach, 1);
2546fd892593SLiam R. Howlett 	unmap_region(mm, &mas_detach, vma, prev, next, start, end, count,
2547fd892593SLiam R. Howlett 		     !unlock);
2548763ecb03SLiam R. Howlett 	/* Statistics and freeing VMAs */
2549fd892593SLiam R. Howlett 	mas_set(&mas_detach, 0);
2550763ecb03SLiam R. Howlett 	remove_mt(mm, &mas_detach);
2551ae80b404SLinus Torvalds 	validate_mm(mm);
2552408579cdSLiam R. Howlett 	if (unlock)
2553408579cdSLiam R. Howlett 		mmap_read_unlock(mm);
25541da177e4SLinus Torvalds 
255502fdb25fSLiam R. Howlett 	__mt_destroy(&mt_detach);
2556408579cdSLiam R. Howlett 	return 0;
2557d4af56c5SLiam R. Howlett 
2558606c812eSLiam R. Howlett clear_tree_failed:
2559d4af56c5SLiam R. Howlett userfaultfd_error:
2560606c812eSLiam R. Howlett munmap_gather_failed:
2561763ecb03SLiam R. Howlett end_split_failed:
2562606c812eSLiam R. Howlett 	mas_set(&mas_detach, 0);
2563606c812eSLiam R. Howlett 	mas_for_each(&mas_detach, next, end)
2564606c812eSLiam R. Howlett 		vma_mark_detached(next, false);
2565606c812eSLiam R. Howlett 
2566763ecb03SLiam R. Howlett 	__mt_destroy(&mt_detach);
2567763ecb03SLiam R. Howlett start_split_failed:
2568763ecb03SLiam R. Howlett map_count_exceeded:
2569b5641a5dSLinus Torvalds 	validate_mm(mm);
2570d4af56c5SLiam R. Howlett 	return error;
25711da177e4SLinus Torvalds }
25721da177e4SLinus Torvalds 
257311f9a21aSLiam R. Howlett /*
2574183654ceSLiam R. Howlett  * do_vmi_munmap() - munmap a given range.
2575183654ceSLiam R. Howlett  * @vmi: The vma iterator
257611f9a21aSLiam R. Howlett  * @mm: The mm_struct
257711f9a21aSLiam R. Howlett  * @start: The start address to munmap
257811f9a21aSLiam R. Howlett  * @len: The length of the range to munmap
257911f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
2580408579cdSLiam R. Howlett  * @unlock: set to true if the user wants to drop the mmap_lock on success
258111f9a21aSLiam R. Howlett  *
258211f9a21aSLiam R. Howlett  * This function takes a @mas that is either pointing to the previous VMA or set
258311f9a21aSLiam R. Howlett  * to MA_START and sets it up to remove the mapping(s).  The @len will be
258411f9a21aSLiam R. Howlett  * aligned and any arch_unmap work will be preformed.
258511f9a21aSLiam R. Howlett  *
2586408579cdSLiam R. Howlett  * Return: 0 on success and drops the lock if so directed, error and leaves the
2587408579cdSLiam R. Howlett  * lock held otherwise.
258811f9a21aSLiam R. Howlett  */
2589183654ceSLiam R. Howlett int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
259011f9a21aSLiam R. Howlett 		  unsigned long start, size_t len, struct list_head *uf,
2591408579cdSLiam R. Howlett 		  bool unlock)
259211f9a21aSLiam R. Howlett {
259311f9a21aSLiam R. Howlett 	unsigned long end;
259411f9a21aSLiam R. Howlett 	struct vm_area_struct *vma;
259511f9a21aSLiam R. Howlett 
259611f9a21aSLiam R. Howlett 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
259711f9a21aSLiam R. Howlett 		return -EINVAL;
259811f9a21aSLiam R. Howlett 
259911f9a21aSLiam R. Howlett 	end = start + PAGE_ALIGN(len);
260011f9a21aSLiam R. Howlett 	if (end == start)
260111f9a21aSLiam R. Howlett 		return -EINVAL;
260211f9a21aSLiam R. Howlett 
260311f9a21aSLiam R. Howlett 	 /* arch_unmap() might do unmaps itself.  */
260411f9a21aSLiam R. Howlett 	arch_unmap(mm, start, end);
260511f9a21aSLiam R. Howlett 
260611f9a21aSLiam R. Howlett 	/* Find the first overlapping VMA */
2607183654ceSLiam R. Howlett 	vma = vma_find(vmi, end);
2608408579cdSLiam R. Howlett 	if (!vma) {
2609408579cdSLiam R. Howlett 		if (unlock)
2610408579cdSLiam R. Howlett 			mmap_write_unlock(mm);
261111f9a21aSLiam R. Howlett 		return 0;
2612408579cdSLiam R. Howlett 	}
261311f9a21aSLiam R. Howlett 
2614408579cdSLiam R. Howlett 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
261511f9a21aSLiam R. Howlett }
261611f9a21aSLiam R. Howlett 
261711f9a21aSLiam R. Howlett /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
261811f9a21aSLiam R. Howlett  * @mm: The mm_struct
261911f9a21aSLiam R. Howlett  * @start: The start address to munmap
262011f9a21aSLiam R. Howlett  * @len: The length to be munmapped.
262111f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
2622408579cdSLiam R. Howlett  *
2623408579cdSLiam R. Howlett  * Return: 0 on success, error otherwise.
262411f9a21aSLiam R. Howlett  */
2625dd2283f2SYang Shi int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2626dd2283f2SYang Shi 	      struct list_head *uf)
2627dd2283f2SYang Shi {
2628183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, start);
262911f9a21aSLiam R. Howlett 
2630183654ceSLiam R. Howlett 	return do_vmi_munmap(&vmi, mm, start, len, uf, false);
2631dd2283f2SYang Shi }
2632dd2283f2SYang Shi 
2633e99668a5SLiam R. Howlett unsigned long mmap_region(struct file *file, unsigned long addr,
2634e99668a5SLiam R. Howlett 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2635e99668a5SLiam R. Howlett 		struct list_head *uf)
2636e99668a5SLiam R. Howlett {
2637e99668a5SLiam R. Howlett 	struct mm_struct *mm = current->mm;
2638e99668a5SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
2639e99668a5SLiam R. Howlett 	struct vm_area_struct *next, *prev, *merge;
2640e99668a5SLiam R. Howlett 	pgoff_t pglen = len >> PAGE_SHIFT;
2641e99668a5SLiam R. Howlett 	unsigned long charged = 0;
2642e99668a5SLiam R. Howlett 	unsigned long end = addr + len;
2643e99668a5SLiam R. Howlett 	unsigned long merge_start = addr, merge_end = end;
2644e99668a5SLiam R. Howlett 	pgoff_t vm_pgoff;
2645e99668a5SLiam R. Howlett 	int error;
2646183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
2647e99668a5SLiam R. Howlett 
2648e99668a5SLiam R. Howlett 	/* Check against address space limit. */
2649e99668a5SLiam R. Howlett 	if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2650e99668a5SLiam R. Howlett 		unsigned long nr_pages;
2651e99668a5SLiam R. Howlett 
2652e99668a5SLiam R. Howlett 		/*
2653e99668a5SLiam R. Howlett 		 * MAP_FIXED may remove pages of mappings that intersects with
2654e99668a5SLiam R. Howlett 		 * requested mapping. Account for the pages it would unmap.
2655e99668a5SLiam R. Howlett 		 */
2656e99668a5SLiam R. Howlett 		nr_pages = count_vma_pages_range(mm, addr, end);
2657e99668a5SLiam R. Howlett 
2658e99668a5SLiam R. Howlett 		if (!may_expand_vm(mm, vm_flags,
2659e99668a5SLiam R. Howlett 					(len >> PAGE_SHIFT) - nr_pages))
2660e99668a5SLiam R. Howlett 			return -ENOMEM;
2661e99668a5SLiam R. Howlett 	}
2662e99668a5SLiam R. Howlett 
2663e99668a5SLiam R. Howlett 	/* Unmap any existing mapping in the area */
2664183654ceSLiam R. Howlett 	if (do_vmi_munmap(&vmi, mm, addr, len, uf, false))
2665e99668a5SLiam R. Howlett 		return -ENOMEM;
2666e99668a5SLiam R. Howlett 
2667e99668a5SLiam R. Howlett 	/*
2668e99668a5SLiam R. Howlett 	 * Private writable mapping: check memory availability
2669e99668a5SLiam R. Howlett 	 */
2670e99668a5SLiam R. Howlett 	if (accountable_mapping(file, vm_flags)) {
2671e99668a5SLiam R. Howlett 		charged = len >> PAGE_SHIFT;
2672e99668a5SLiam R. Howlett 		if (security_vm_enough_memory_mm(mm, charged))
2673e99668a5SLiam R. Howlett 			return -ENOMEM;
2674e99668a5SLiam R. Howlett 		vm_flags |= VM_ACCOUNT;
2675e99668a5SLiam R. Howlett 	}
2676e99668a5SLiam R. Howlett 
2677183654ceSLiam R. Howlett 	next = vma_next(&vmi);
2678183654ceSLiam R. Howlett 	prev = vma_prev(&vmi);
267953bee98dSLiam R. Howlett 	if (vm_flags & VM_SPECIAL) {
268053bee98dSLiam R. Howlett 		if (prev)
268153bee98dSLiam R. Howlett 			vma_iter_next_range(&vmi);
2682e99668a5SLiam R. Howlett 		goto cannot_expand;
268353bee98dSLiam R. Howlett 	}
2684e99668a5SLiam R. Howlett 
2685e99668a5SLiam R. Howlett 	/* Attempt to expand an old mapping */
2686e99668a5SLiam R. Howlett 	/* Check next */
2687e99668a5SLiam R. Howlett 	if (next && next->vm_start == end && !vma_policy(next) &&
2688e99668a5SLiam R. Howlett 	    can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2689e99668a5SLiam R. Howlett 				 NULL_VM_UFFD_CTX, NULL)) {
2690e99668a5SLiam R. Howlett 		merge_end = next->vm_end;
2691e99668a5SLiam R. Howlett 		vma = next;
2692e99668a5SLiam R. Howlett 		vm_pgoff = next->vm_pgoff - pglen;
2693e99668a5SLiam R. Howlett 	}
2694e99668a5SLiam R. Howlett 
2695e99668a5SLiam R. Howlett 	/* Check prev */
2696e99668a5SLiam R. Howlett 	if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2697e99668a5SLiam R. Howlett 	    (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2698e99668a5SLiam R. Howlett 				       pgoff, vma->vm_userfaultfd_ctx, NULL) :
2699e99668a5SLiam R. Howlett 		   can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2700e99668a5SLiam R. Howlett 				       NULL_VM_UFFD_CTX, NULL))) {
2701e99668a5SLiam R. Howlett 		merge_start = prev->vm_start;
2702e99668a5SLiam R. Howlett 		vma = prev;
2703e99668a5SLiam R. Howlett 		vm_pgoff = prev->vm_pgoff;
270453bee98dSLiam R. Howlett 	} else if (prev) {
270553bee98dSLiam R. Howlett 		vma_iter_next_range(&vmi);
2706e99668a5SLiam R. Howlett 	}
2707e99668a5SLiam R. Howlett 
2708e99668a5SLiam R. Howlett 
2709e99668a5SLiam R. Howlett 	/* Actually expand, if possible */
2710e99668a5SLiam R. Howlett 	if (vma &&
27113c441ab7SLiam R. Howlett 	    !vma_expand(&vmi, vma, merge_start, merge_end, vm_pgoff, next)) {
2712e99668a5SLiam R. Howlett 		khugepaged_enter_vma(vma, vm_flags);
2713e99668a5SLiam R. Howlett 		goto expanded;
2714e99668a5SLiam R. Howlett 	}
2715e99668a5SLiam R. Howlett 
271653bee98dSLiam R. Howlett 	if (vma == prev)
271753bee98dSLiam R. Howlett 		vma_iter_set(&vmi, addr);
2718e99668a5SLiam R. Howlett cannot_expand:
27195c1c03deSLiam R. Howlett 
2720e99668a5SLiam R. Howlett 	/*
2721e99668a5SLiam R. Howlett 	 * Determine the object being mapped and call the appropriate
2722e99668a5SLiam R. Howlett 	 * specific mapper. the address has already been validated, but
2723e99668a5SLiam R. Howlett 	 * not unmapped, but the maps are removed from the list.
2724e99668a5SLiam R. Howlett 	 */
2725e99668a5SLiam R. Howlett 	vma = vm_area_alloc(mm);
2726e99668a5SLiam R. Howlett 	if (!vma) {
2727e99668a5SLiam R. Howlett 		error = -ENOMEM;
2728e99668a5SLiam R. Howlett 		goto unacct_error;
2729e99668a5SLiam R. Howlett 	}
2730e99668a5SLiam R. Howlett 
273153bee98dSLiam R. Howlett 	vma_iter_config(&vmi, addr, end);
2732e99668a5SLiam R. Howlett 	vma->vm_start = addr;
2733e99668a5SLiam R. Howlett 	vma->vm_end = end;
27341c71222eSSuren Baghdasaryan 	vm_flags_init(vma, vm_flags);
2735e99668a5SLiam R. Howlett 	vma->vm_page_prot = vm_get_page_prot(vm_flags);
2736e99668a5SLiam R. Howlett 	vma->vm_pgoff = pgoff;
2737e99668a5SLiam R. Howlett 
2738e99668a5SLiam R. Howlett 	if (file) {
2739e99668a5SLiam R. Howlett 		if (vm_flags & VM_SHARED) {
2740e99668a5SLiam R. Howlett 			error = mapping_map_writable(file->f_mapping);
2741e99668a5SLiam R. Howlett 			if (error)
2742e99668a5SLiam R. Howlett 				goto free_vma;
2743e99668a5SLiam R. Howlett 		}
2744e99668a5SLiam R. Howlett 
2745e99668a5SLiam R. Howlett 		vma->vm_file = get_file(file);
2746e99668a5SLiam R. Howlett 		error = call_mmap(file, vma);
2747e99668a5SLiam R. Howlett 		if (error)
2748e99668a5SLiam R. Howlett 			goto unmap_and_free_vma;
2749e99668a5SLiam R. Howlett 
2750a57b7051SLiam Howlett 		/*
2751a57b7051SLiam Howlett 		 * Expansion is handled above, merging is handled below.
2752a57b7051SLiam Howlett 		 * Drivers should not alter the address of the VMA.
2753e99668a5SLiam R. Howlett 		 */
2754a57b7051SLiam Howlett 		error = -EINVAL;
2755cc8d1b09SLiam R. Howlett 		if (WARN_ON((addr != vma->vm_start)))
2756a57b7051SLiam Howlett 			goto close_and_free_vma;
2757e99668a5SLiam R. Howlett 
275853bee98dSLiam R. Howlett 		vma_iter_config(&vmi, addr, end);
2759e99668a5SLiam R. Howlett 		/*
2760e99668a5SLiam R. Howlett 		 * If vm_flags changed after call_mmap(), we should try merge
2761e99668a5SLiam R. Howlett 		 * vma again as we may succeed this time.
2762e99668a5SLiam R. Howlett 		 */
2763e99668a5SLiam R. Howlett 		if (unlikely(vm_flags != vma->vm_flags && prev)) {
27649760ebffSLiam R. Howlett 			merge = vma_merge(&vmi, mm, prev, vma->vm_start,
27659760ebffSLiam R. Howlett 				    vma->vm_end, vma->vm_flags, NULL,
27669760ebffSLiam R. Howlett 				    vma->vm_file, vma->vm_pgoff, NULL,
27679760ebffSLiam R. Howlett 				    NULL_VM_UFFD_CTX, NULL);
2768e99668a5SLiam R. Howlett 			if (merge) {
2769e99668a5SLiam R. Howlett 				/*
2770e99668a5SLiam R. Howlett 				 * ->mmap() can change vma->vm_file and fput
2771e99668a5SLiam R. Howlett 				 * the original file. So fput the vma->vm_file
2772e99668a5SLiam R. Howlett 				 * here or we would add an extra fput for file
2773e99668a5SLiam R. Howlett 				 * and cause general protection fault
2774e99668a5SLiam R. Howlett 				 * ultimately.
2775e99668a5SLiam R. Howlett 				 */
2776e99668a5SLiam R. Howlett 				fput(vma->vm_file);
2777e99668a5SLiam R. Howlett 				vm_area_free(vma);
2778e99668a5SLiam R. Howlett 				vma = merge;
2779e99668a5SLiam R. Howlett 				/* Update vm_flags to pick up the change. */
2780e99668a5SLiam R. Howlett 				vm_flags = vma->vm_flags;
2781e99668a5SLiam R. Howlett 				goto unmap_writable;
2782e99668a5SLiam R. Howlett 			}
2783e99668a5SLiam R. Howlett 		}
2784e99668a5SLiam R. Howlett 
2785e99668a5SLiam R. Howlett 		vm_flags = vma->vm_flags;
2786e99668a5SLiam R. Howlett 	} else if (vm_flags & VM_SHARED) {
2787e99668a5SLiam R. Howlett 		error = shmem_zero_setup(vma);
2788e99668a5SLiam R. Howlett 		if (error)
2789e99668a5SLiam R. Howlett 			goto free_vma;
2790e99668a5SLiam R. Howlett 	} else {
2791e99668a5SLiam R. Howlett 		vma_set_anonymous(vma);
2792e99668a5SLiam R. Howlett 	}
2793e99668a5SLiam R. Howlett 
2794b507808eSJoey Gouly 	if (map_deny_write_exec(vma, vma->vm_flags)) {
2795b507808eSJoey Gouly 		error = -EACCES;
2796b507808eSJoey Gouly 		goto close_and_free_vma;
2797b507808eSJoey Gouly 	}
2798b507808eSJoey Gouly 
2799e99668a5SLiam R. Howlett 	/* Allow architectures to sanity-check the vm_flags */
2800e99668a5SLiam R. Howlett 	error = -EINVAL;
2801cc8d1b09SLiam R. Howlett 	if (!arch_validate_flags(vma->vm_flags))
2802deb0f656SCarlos Llamas 		goto close_and_free_vma;
2803e99668a5SLiam R. Howlett 
2804e99668a5SLiam R. Howlett 	error = -ENOMEM;
2805cc8d1b09SLiam R. Howlett 	if (vma_iter_prealloc(&vmi))
28065789151eSMike Kravetz 		goto close_and_free_vma;
2807e99668a5SLiam R. Howlett 
28081c7873e3SHugh Dickins 	/* Lock the VMA since it is modified after insertion into VMA tree */
28091c7873e3SHugh Dickins 	vma_start_write(vma);
2810183654ceSLiam R. Howlett 	vma_iter_store(&vmi, vma);
2811e99668a5SLiam R. Howlett 	mm->map_count++;
2812e99668a5SLiam R. Howlett 	if (vma->vm_file) {
28136852c46cSYu Ma 		i_mmap_lock_write(vma->vm_file->f_mapping);
2814e99668a5SLiam R. Howlett 		if (vma->vm_flags & VM_SHARED)
2815e99668a5SLiam R. Howlett 			mapping_allow_writable(vma->vm_file->f_mapping);
2816e99668a5SLiam R. Howlett 
2817e99668a5SLiam R. Howlett 		flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2818e99668a5SLiam R. Howlett 		vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2819e99668a5SLiam R. Howlett 		flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2820e99668a5SLiam R. Howlett 		i_mmap_unlock_write(vma->vm_file->f_mapping);
2821e99668a5SLiam R. Howlett 	}
2822e99668a5SLiam R. Howlett 
2823e99668a5SLiam R. Howlett 	/*
2824e99668a5SLiam R. Howlett 	 * vma_merge() calls khugepaged_enter_vma() either, the below
2825e99668a5SLiam R. Howlett 	 * call covers the non-merge case.
2826e99668a5SLiam R. Howlett 	 */
2827e99668a5SLiam R. Howlett 	khugepaged_enter_vma(vma, vma->vm_flags);
2828e99668a5SLiam R. Howlett 
2829e99668a5SLiam R. Howlett 	/* Once vma denies write, undo our temporary denial count */
2830e99668a5SLiam R. Howlett unmap_writable:
2831e99668a5SLiam R. Howlett 	if (file && vm_flags & VM_SHARED)
2832e99668a5SLiam R. Howlett 		mapping_unmap_writable(file->f_mapping);
2833e99668a5SLiam R. Howlett 	file = vma->vm_file;
2834d7597f59SStefan Roesch 	ksm_add_vma(vma);
2835e99668a5SLiam R. Howlett expanded:
2836e99668a5SLiam R. Howlett 	perf_event_mmap(vma);
2837e99668a5SLiam R. Howlett 
2838e99668a5SLiam R. Howlett 	vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2839e99668a5SLiam R. Howlett 	if (vm_flags & VM_LOCKED) {
2840e99668a5SLiam R. Howlett 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2841e99668a5SLiam R. Howlett 					is_vm_hugetlb_page(vma) ||
2842e99668a5SLiam R. Howlett 					vma == get_gate_vma(current->mm))
2843e430a95aSSuren Baghdasaryan 			vm_flags_clear(vma, VM_LOCKED_MASK);
2844e99668a5SLiam R. Howlett 		else
2845e99668a5SLiam R. Howlett 			mm->locked_vm += (len >> PAGE_SHIFT);
2846e99668a5SLiam R. Howlett 	}
2847e99668a5SLiam R. Howlett 
2848e99668a5SLiam R. Howlett 	if (file)
2849e99668a5SLiam R. Howlett 		uprobe_mmap(vma);
2850e99668a5SLiam R. Howlett 
2851e99668a5SLiam R. Howlett 	/*
2852e99668a5SLiam R. Howlett 	 * New (or expanded) vma always get soft dirty status.
2853e99668a5SLiam R. Howlett 	 * Otherwise user-space soft-dirty page tracker won't
2854e99668a5SLiam R. Howlett 	 * be able to distinguish situation when vma area unmapped,
2855e99668a5SLiam R. Howlett 	 * then new mapped in-place (which must be aimed as
2856e99668a5SLiam R. Howlett 	 * a completely new data area).
2857e99668a5SLiam R. Howlett 	 */
28581c71222eSSuren Baghdasaryan 	vm_flags_set(vma, VM_SOFTDIRTY);
2859e99668a5SLiam R. Howlett 
2860e99668a5SLiam R. Howlett 	vma_set_page_prot(vma);
2861e99668a5SLiam R. Howlett 
2862e99668a5SLiam R. Howlett 	validate_mm(mm);
2863e99668a5SLiam R. Howlett 	return addr;
2864e99668a5SLiam R. Howlett 
2865deb0f656SCarlos Llamas close_and_free_vma:
2866cc8d1b09SLiam R. Howlett 	if (file && vma->vm_ops && vma->vm_ops->close)
2867deb0f656SCarlos Llamas 		vma->vm_ops->close(vma);
2868cc8d1b09SLiam R. Howlett 
2869cc8d1b09SLiam R. Howlett 	if (file || vma->vm_file) {
2870e99668a5SLiam R. Howlett unmap_and_free_vma:
2871e99668a5SLiam R. Howlett 		fput(vma->vm_file);
2872e99668a5SLiam R. Howlett 		vma->vm_file = NULL;
2873e99668a5SLiam R. Howlett 
2874fd892593SLiam R. Howlett 		vma_iter_set(&vmi, vma->vm_end);
2875e99668a5SLiam R. Howlett 		/* Undo any partial mapping done by a device driver. */
2876fd892593SLiam R. Howlett 		unmap_region(mm, &vmi.mas, vma, prev, next, vma->vm_start,
2877fd892593SLiam R. Howlett 			     vma->vm_end, vma->vm_end, true);
2878cc8d1b09SLiam R. Howlett 	}
2879cc674ab3SLi Zetao 	if (file && (vm_flags & VM_SHARED))
2880e99668a5SLiam R. Howlett 		mapping_unmap_writable(file->f_mapping);
2881e99668a5SLiam R. Howlett free_vma:
2882e99668a5SLiam R. Howlett 	vm_area_free(vma);
2883e99668a5SLiam R. Howlett unacct_error:
2884e99668a5SLiam R. Howlett 	if (charged)
2885e99668a5SLiam R. Howlett 		vm_unacct_memory(charged);
2886e99668a5SLiam R. Howlett 	validate_mm(mm);
2887e99668a5SLiam R. Howlett 	return error;
2888e99668a5SLiam R. Howlett }
2889e99668a5SLiam R. Howlett 
2890408579cdSLiam R. Howlett static int __vm_munmap(unsigned long start, size_t len, bool unlock)
2891a46ef99dSLinus Torvalds {
2892a46ef99dSLinus Torvalds 	int ret;
2893bfce281cSAl Viro 	struct mm_struct *mm = current->mm;
2894897ab3e0SMike Rapoport 	LIST_HEAD(uf);
2895183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, start);
2896a46ef99dSLinus Torvalds 
2897d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2898ae798783SMichal Hocko 		return -EINTR;
2899ae798783SMichal Hocko 
2900408579cdSLiam R. Howlett 	ret = do_vmi_munmap(&vmi, mm, start, len, &uf, unlock);
2901408579cdSLiam R. Howlett 	if (ret || !unlock)
2902d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
2903dd2283f2SYang Shi 
2904897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
2905a46ef99dSLinus Torvalds 	return ret;
2906a46ef99dSLinus Torvalds }
2907dd2283f2SYang Shi 
2908dd2283f2SYang Shi int vm_munmap(unsigned long start, size_t len)
2909dd2283f2SYang Shi {
2910dd2283f2SYang Shi 	return __vm_munmap(start, len, false);
2911dd2283f2SYang Shi }
2912a46ef99dSLinus Torvalds EXPORT_SYMBOL(vm_munmap);
2913a46ef99dSLinus Torvalds 
29146a6160a7SHeiko Carstens SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
29151da177e4SLinus Torvalds {
2916ce18d171SCatalin Marinas 	addr = untagged_addr(addr);
2917dd2283f2SYang Shi 	return __vm_munmap(addr, len, true);
29181da177e4SLinus Torvalds }
29191da177e4SLinus Torvalds 
2920c8d78c18SKirill A. Shutemov 
2921c8d78c18SKirill A. Shutemov /*
2922c8d78c18SKirill A. Shutemov  * Emulation of deprecated remap_file_pages() syscall.
2923c8d78c18SKirill A. Shutemov  */
2924c8d78c18SKirill A. Shutemov SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2925c8d78c18SKirill A. Shutemov 		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2926c8d78c18SKirill A. Shutemov {
2927c8d78c18SKirill A. Shutemov 
2928c8d78c18SKirill A. Shutemov 	struct mm_struct *mm = current->mm;
2929c8d78c18SKirill A. Shutemov 	struct vm_area_struct *vma;
2930c8d78c18SKirill A. Shutemov 	unsigned long populate = 0;
2931c8d78c18SKirill A. Shutemov 	unsigned long ret = -EINVAL;
2932c8d78c18SKirill A. Shutemov 	struct file *file;
2933c8d78c18SKirill A. Shutemov 
2934ee65728eSMike Rapoport 	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2935c8d78c18SKirill A. Shutemov 		     current->comm, current->pid);
2936c8d78c18SKirill A. Shutemov 
2937c8d78c18SKirill A. Shutemov 	if (prot)
2938c8d78c18SKirill A. Shutemov 		return ret;
2939c8d78c18SKirill A. Shutemov 	start = start & PAGE_MASK;
2940c8d78c18SKirill A. Shutemov 	size = size & PAGE_MASK;
2941c8d78c18SKirill A. Shutemov 
2942c8d78c18SKirill A. Shutemov 	if (start + size <= start)
2943c8d78c18SKirill A. Shutemov 		return ret;
2944c8d78c18SKirill A. Shutemov 
2945c8d78c18SKirill A. Shutemov 	/* Does pgoff wrap? */
2946c8d78c18SKirill A. Shutemov 	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2947c8d78c18SKirill A. Shutemov 		return ret;
2948c8d78c18SKirill A. Shutemov 
2949d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2950dc0ef0dfSMichal Hocko 		return -EINTR;
2951dc0ef0dfSMichal Hocko 
29529b593cb2SLiam R. Howlett 	vma = vma_lookup(mm, start);
2953c8d78c18SKirill A. Shutemov 
2954c8d78c18SKirill A. Shutemov 	if (!vma || !(vma->vm_flags & VM_SHARED))
2955c8d78c18SKirill A. Shutemov 		goto out;
2956c8d78c18SKirill A. Shutemov 
295748f7df32SKirill A. Shutemov 	if (start + size > vma->vm_end) {
2958763ecb03SLiam R. Howlett 		VMA_ITERATOR(vmi, mm, vma->vm_end);
2959763ecb03SLiam R. Howlett 		struct vm_area_struct *next, *prev = vma;
296048f7df32SKirill A. Shutemov 
2961763ecb03SLiam R. Howlett 		for_each_vma_range(vmi, next, start + size) {
296248f7df32SKirill A. Shutemov 			/* hole between vmas ? */
2963763ecb03SLiam R. Howlett 			if (next->vm_start != prev->vm_end)
296448f7df32SKirill A. Shutemov 				goto out;
296548f7df32SKirill A. Shutemov 
296648f7df32SKirill A. Shutemov 			if (next->vm_file != vma->vm_file)
296748f7df32SKirill A. Shutemov 				goto out;
296848f7df32SKirill A. Shutemov 
296948f7df32SKirill A. Shutemov 			if (next->vm_flags != vma->vm_flags)
297048f7df32SKirill A. Shutemov 				goto out;
297148f7df32SKirill A. Shutemov 
29721db43d3fSLiam Howlett 			if (start + size <= next->vm_end)
29731db43d3fSLiam Howlett 				break;
29741db43d3fSLiam Howlett 
2975763ecb03SLiam R. Howlett 			prev = next;
297648f7df32SKirill A. Shutemov 		}
297748f7df32SKirill A. Shutemov 
297848f7df32SKirill A. Shutemov 		if (!next)
2979c8d78c18SKirill A. Shutemov 			goto out;
2980c8d78c18SKirill A. Shutemov 	}
2981c8d78c18SKirill A. Shutemov 
2982c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2983c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2984c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2985c8d78c18SKirill A. Shutemov 
2986c8d78c18SKirill A. Shutemov 	flags &= MAP_NONBLOCK;
2987c8d78c18SKirill A. Shutemov 	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2988fce000b1SLiam Howlett 	if (vma->vm_flags & VM_LOCKED)
2989c8d78c18SKirill A. Shutemov 		flags |= MAP_LOCKED;
299048f7df32SKirill A. Shutemov 
2991c8d78c18SKirill A. Shutemov 	file = get_file(vma->vm_file);
299245e55300SPeter Collingbourne 	ret = do_mmap(vma->vm_file, start, size,
2993897ab3e0SMike Rapoport 			prot, flags, pgoff, &populate, NULL);
2994c8d78c18SKirill A. Shutemov 	fput(file);
2995c8d78c18SKirill A. Shutemov out:
2996d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
2997c8d78c18SKirill A. Shutemov 	if (populate)
2998c8d78c18SKirill A. Shutemov 		mm_populate(ret, populate);
2999c8d78c18SKirill A. Shutemov 	if (!IS_ERR_VALUE(ret))
3000c8d78c18SKirill A. Shutemov 		ret = 0;
3001c8d78c18SKirill A. Shutemov 	return ret;
3002c8d78c18SKirill A. Shutemov }
3003c8d78c18SKirill A. Shutemov 
30041da177e4SLinus Torvalds /*
300527b26701SLiam R. Howlett  * do_vma_munmap() - Unmap a full or partial vma.
300627b26701SLiam R. Howlett  * @vmi: The vma iterator pointing at the vma
300727b26701SLiam R. Howlett  * @vma: The first vma to be munmapped
300827b26701SLiam R. Howlett  * @start: the start of the address to unmap
300927b26701SLiam R. Howlett  * @end: The end of the address to unmap
30102e7ce7d3SLiam R. Howlett  * @uf: The userfaultfd list_head
3011408579cdSLiam R. Howlett  * @unlock: Drop the lock on success
30122e7ce7d3SLiam R. Howlett  *
301327b26701SLiam R. Howlett  * unmaps a VMA mapping when the vma iterator is already in position.
301427b26701SLiam R. Howlett  * Does not handle alignment.
3015408579cdSLiam R. Howlett  *
3016408579cdSLiam R. Howlett  * Return: 0 on success drops the lock of so directed, error on failure and will
3017408579cdSLiam R. Howlett  * still hold the lock.
30181da177e4SLinus Torvalds  */
301927b26701SLiam R. Howlett int do_vma_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
3020408579cdSLiam R. Howlett 		unsigned long start, unsigned long end, struct list_head *uf,
3021408579cdSLiam R. Howlett 		bool unlock)
30222e7ce7d3SLiam R. Howlett {
30232e7ce7d3SLiam R. Howlett 	struct mm_struct *mm = vma->vm_mm;
30242e7ce7d3SLiam R. Howlett 
302527b26701SLiam R. Howlett 	arch_unmap(mm, start, end);
3026b5641a5dSLinus Torvalds 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
30272e7ce7d3SLiam R. Howlett }
30282e7ce7d3SLiam R. Howlett 
30292e7ce7d3SLiam R. Howlett /*
30302e7ce7d3SLiam R. Howlett  * do_brk_flags() - Increase the brk vma if the flags match.
303192fed820SLiam R. Howlett  * @vmi: The vma iterator
30322e7ce7d3SLiam R. Howlett  * @addr: The start address
30332e7ce7d3SLiam R. Howlett  * @len: The length of the increase
30342e7ce7d3SLiam R. Howlett  * @vma: The vma,
30352e7ce7d3SLiam R. Howlett  * @flags: The VMA Flags
30362e7ce7d3SLiam R. Howlett  *
30372e7ce7d3SLiam R. Howlett  * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
30382e7ce7d3SLiam R. Howlett  * do not match then create a new anonymous VMA.  Eventually we may be able to
30392e7ce7d3SLiam R. Howlett  * do some brk-specific accounting here.
30402e7ce7d3SLiam R. Howlett  */
304192fed820SLiam R. Howlett static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
3042763ecb03SLiam R. Howlett 		unsigned long addr, unsigned long len, unsigned long flags)
30431da177e4SLinus Torvalds {
30441da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
3045287051b1SLiam R. Howlett 	struct vma_prepare vp;
30462e7ce7d3SLiam R. Howlett 
30472e7ce7d3SLiam R. Howlett 	/*
30482e7ce7d3SLiam R. Howlett 	 * Check against address space limits by the changed size
30492e7ce7d3SLiam R. Howlett 	 * Note: This happens *after* clearing old mappings in some code paths.
30502e7ce7d3SLiam R. Howlett 	 */
305116e72e9bSDenys Vlasenko 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
305284638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
30531da177e4SLinus Torvalds 		return -ENOMEM;
30541da177e4SLinus Torvalds 
30551da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
30561da177e4SLinus Torvalds 		return -ENOMEM;
30571da177e4SLinus Torvalds 
3058191c5424SAl Viro 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
30591da177e4SLinus Torvalds 		return -ENOMEM;
30601da177e4SLinus Torvalds 
30611da177e4SLinus Torvalds 	/*
30622e7ce7d3SLiam R. Howlett 	 * Expand the existing vma if possible; Note that singular lists do not
30632e7ce7d3SLiam R. Howlett 	 * occur after forking, so the expand will only happen on new VMAs.
30641da177e4SLinus Torvalds 	 */
30656c28ca64SLiam Howlett 	if (vma && vma->vm_end == addr && !vma_policy(vma) &&
30666c28ca64SLiam Howlett 	    can_vma_merge_after(vma, flags, NULL, NULL,
30676c28ca64SLiam Howlett 				addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
306892fed820SLiam R. Howlett 		if (vma_iter_prealloc(vmi))
3069675eaca1SAlistair Popple 			goto unacct_fail;
307028c5609fSLiam Howlett 
3071287051b1SLiam R. Howlett 		init_vma_prep(&vp, vma);
3072287051b1SLiam R. Howlett 		vma_prepare(&vp);
3073ccf1d78dSSuren Baghdasaryan 		vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
30742e7ce7d3SLiam R. Howlett 		vma->vm_end = addr + len;
30751c71222eSSuren Baghdasaryan 		vm_flags_set(vma, VM_SOFTDIRTY);
307692fed820SLiam R. Howlett 		vma_iter_store(vmi, vma);
30772e7ce7d3SLiam R. Howlett 
3078287051b1SLiam R. Howlett 		vma_complete(&vp, vmi, mm);
30792e7ce7d3SLiam R. Howlett 		khugepaged_enter_vma(vma, flags);
30802e7ce7d3SLiam R. Howlett 		goto out;
30812e7ce7d3SLiam R. Howlett 	}
30822e7ce7d3SLiam R. Howlett 
30832e7ce7d3SLiam R. Howlett 	/* create a vma struct for an anonymous mapping */
30842e7ce7d3SLiam R. Howlett 	vma = vm_area_alloc(mm);
30852e7ce7d3SLiam R. Howlett 	if (!vma)
3086675eaca1SAlistair Popple 		goto unacct_fail;
30871da177e4SLinus Torvalds 
3088bfd40eafSKirill A. Shutemov 	vma_set_anonymous(vma);
30891da177e4SLinus Torvalds 	vma->vm_start = addr;
30901da177e4SLinus Torvalds 	vma->vm_end = addr + len;
30912e7ce7d3SLiam R. Howlett 	vma->vm_pgoff = addr >> PAGE_SHIFT;
30921c71222eSSuren Baghdasaryan 	vm_flags_init(vma, flags);
30933ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(flags);
309492fed820SLiam R. Howlett 	if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
30952e7ce7d3SLiam R. Howlett 		goto mas_store_fail;
3096d4af56c5SLiam R. Howlett 
30972e7ce7d3SLiam R. Howlett 	mm->map_count++;
30982574d5e4SLiam R. Howlett 	validate_mm(mm);
3099d7597f59SStefan Roesch 	ksm_add_vma(vma);
31001da177e4SLinus Torvalds out:
31013af9e859SEric B Munson 	perf_event_mmap(vma);
31021da177e4SLinus Torvalds 	mm->total_vm += len >> PAGE_SHIFT;
310384638335SKonstantin Khlebnikov 	mm->data_vm += len >> PAGE_SHIFT;
3104128557ffSMichel Lespinasse 	if (flags & VM_LOCKED)
3105ba470de4SRik van Riel 		mm->locked_vm += (len >> PAGE_SHIFT);
31061c71222eSSuren Baghdasaryan 	vm_flags_set(vma, VM_SOFTDIRTY);
31075d22fc25SLinus Torvalds 	return 0;
3108d4af56c5SLiam R. Howlett 
31092e7ce7d3SLiam R. Howlett mas_store_fail:
3110d4af56c5SLiam R. Howlett 	vm_area_free(vma);
3111675eaca1SAlistair Popple unacct_fail:
31122e7ce7d3SLiam R. Howlett 	vm_unacct_memory(len >> PAGE_SHIFT);
31132e7ce7d3SLiam R. Howlett 	return -ENOMEM;
31141da177e4SLinus Torvalds }
31151da177e4SLinus Torvalds 
3116bb177a73SMichal Hocko int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3117e4eb1ff6SLinus Torvalds {
3118e4eb1ff6SLinus Torvalds 	struct mm_struct *mm = current->mm;
31192e7ce7d3SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
3120bb177a73SMichal Hocko 	unsigned long len;
31215d22fc25SLinus Torvalds 	int ret;
3122128557ffSMichel Lespinasse 	bool populate;
3123897ab3e0SMike Rapoport 	LIST_HEAD(uf);
312492fed820SLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
3125e4eb1ff6SLinus Torvalds 
3126bb177a73SMichal Hocko 	len = PAGE_ALIGN(request);
3127bb177a73SMichal Hocko 	if (len < request)
3128bb177a73SMichal Hocko 		return -ENOMEM;
3129bb177a73SMichal Hocko 	if (!len)
3130bb177a73SMichal Hocko 		return 0;
3131bb177a73SMichal Hocko 
3132d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
31332d6c9282SMichal Hocko 		return -EINTR;
31342d6c9282SMichal Hocko 
31352e7ce7d3SLiam R. Howlett 	/* Until we need other flags, refuse anything except VM_EXEC. */
31362e7ce7d3SLiam R. Howlett 	if ((flags & (~VM_EXEC)) != 0)
31372e7ce7d3SLiam R. Howlett 		return -EINVAL;
31382e7ce7d3SLiam R. Howlett 
31392e7ce7d3SLiam R. Howlett 	ret = check_brk_limits(addr, len);
31402e7ce7d3SLiam R. Howlett 	if (ret)
31412e7ce7d3SLiam R. Howlett 		goto limits_failed;
31422e7ce7d3SLiam R. Howlett 
3143183654ceSLiam R. Howlett 	ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
31442e7ce7d3SLiam R. Howlett 	if (ret)
31452e7ce7d3SLiam R. Howlett 		goto munmap_failed;
31462e7ce7d3SLiam R. Howlett 
314792fed820SLiam R. Howlett 	vma = vma_prev(&vmi);
314892fed820SLiam R. Howlett 	ret = do_brk_flags(&vmi, vma, addr, len, flags);
3149128557ffSMichel Lespinasse 	populate = ((mm->def_flags & VM_LOCKED) != 0);
3150d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
3151897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
31525d22fc25SLinus Torvalds 	if (populate && !ret)
3153128557ffSMichel Lespinasse 		mm_populate(addr, len);
3154e4eb1ff6SLinus Torvalds 	return ret;
31552e7ce7d3SLiam R. Howlett 
31562e7ce7d3SLiam R. Howlett munmap_failed:
31572e7ce7d3SLiam R. Howlett limits_failed:
31582e7ce7d3SLiam R. Howlett 	mmap_write_unlock(mm);
31592e7ce7d3SLiam R. Howlett 	return ret;
3160e4eb1ff6SLinus Torvalds }
316116e72e9bSDenys Vlasenko EXPORT_SYMBOL(vm_brk_flags);
316216e72e9bSDenys Vlasenko 
316316e72e9bSDenys Vlasenko int vm_brk(unsigned long addr, unsigned long len)
316416e72e9bSDenys Vlasenko {
316516e72e9bSDenys Vlasenko 	return vm_brk_flags(addr, len, 0);
316616e72e9bSDenys Vlasenko }
3167e4eb1ff6SLinus Torvalds EXPORT_SYMBOL(vm_brk);
31681da177e4SLinus Torvalds 
31691da177e4SLinus Torvalds /* Release all mmaps. */
31701da177e4SLinus Torvalds void exit_mmap(struct mm_struct *mm)
31711da177e4SLinus Torvalds {
3172d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
3173ba470de4SRik van Riel 	struct vm_area_struct *vma;
31741da177e4SLinus Torvalds 	unsigned long nr_accounted = 0;
3175763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
3176763ecb03SLiam R. Howlett 	int count = 0;
31771da177e4SLinus Torvalds 
3178d6dd61c8SJeremy Fitzhardinge 	/* mm's last user has gone, and its about to be pulled down */
3179cddb8a5cSAndrea Arcangeli 	mmu_notifier_release(mm);
3180d6dd61c8SJeremy Fitzhardinge 
3181bf3980c8SSuren Baghdasaryan 	mmap_read_lock(mm);
31829480c53eSJeremy Fitzhardinge 	arch_exit_mmap(mm);
31839480c53eSJeremy Fitzhardinge 
3184763ecb03SLiam R. Howlett 	vma = mas_find(&mas, ULONG_MAX);
318564591e86SSuren Baghdasaryan 	if (!vma) {
318664591e86SSuren Baghdasaryan 		/* Can happen if dup_mmap() received an OOM */
3187bf3980c8SSuren Baghdasaryan 		mmap_read_unlock(mm);
31889480c53eSJeremy Fitzhardinge 		return;
318964591e86SSuren Baghdasaryan 	}
31909480c53eSJeremy Fitzhardinge 
31911da177e4SLinus Torvalds 	lru_add_drain();
31921da177e4SLinus Torvalds 	flush_cache_mm(mm);
3193d8b45053SWill Deacon 	tlb_gather_mmu_fullmm(&tlb, mm);
3194901608d9SOleg Nesterov 	/* update_hiwater_rss(mm) here? but nobody should be looking */
3195763ecb03SLiam R. Howlett 	/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
3196fd892593SLiam R. Howlett 	unmap_vmas(&tlb, &mas, vma, 0, ULONG_MAX, ULONG_MAX, false);
3197bf3980c8SSuren Baghdasaryan 	mmap_read_unlock(mm);
3198bf3980c8SSuren Baghdasaryan 
3199bf3980c8SSuren Baghdasaryan 	/*
3200bf3980c8SSuren Baghdasaryan 	 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
3201b3541d91SSuren Baghdasaryan 	 * because the memory has been already freed.
3202bf3980c8SSuren Baghdasaryan 	 */
3203bf3980c8SSuren Baghdasaryan 	set_bit(MMF_OOM_SKIP, &mm->flags);
3204bf3980c8SSuren Baghdasaryan 	mmap_write_lock(mm);
32053dd44325SLiam R. Howlett 	mt_clear_in_rcu(&mm->mm_mt);
3206fd892593SLiam R. Howlett 	mas_set(&mas, vma->vm_end);
3207fd892593SLiam R. Howlett 	free_pgtables(&tlb, &mas, vma, FIRST_USER_ADDRESS,
320898e51a22SSuren Baghdasaryan 		      USER_PGTABLES_CEILING, true);
3209ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
32101da177e4SLinus Torvalds 
3211763ecb03SLiam R. Howlett 	/*
3212763ecb03SLiam R. Howlett 	 * Walk the list again, actually closing and freeing it, with preemption
3213763ecb03SLiam R. Howlett 	 * enabled, without holding any MM locks besides the unreachable
3214763ecb03SLiam R. Howlett 	 * mmap_write_lock.
3215763ecb03SLiam R. Howlett 	 */
3216fd892593SLiam R. Howlett 	mas_set(&mas, vma->vm_end);
3217763ecb03SLiam R. Howlett 	do {
32184f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
32194f74d2c8SLinus Torvalds 			nr_accounted += vma_pages(vma);
32200d2ebf9cSSuren Baghdasaryan 		remove_vma(vma, true);
3221763ecb03SLiam R. Howlett 		count++;
32220a3b3c25SPaul E. McKenney 		cond_resched();
3223763ecb03SLiam R. Howlett 	} while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);
3224763ecb03SLiam R. Howlett 
3225763ecb03SLiam R. Howlett 	BUG_ON(count != mm->map_count);
3226d4af56c5SLiam R. Howlett 
3227d4af56c5SLiam R. Howlett 	trace_exit_mmap(mm);
3228d4af56c5SLiam R. Howlett 	__mt_destroy(&mm->mm_mt);
322964591e86SSuren Baghdasaryan 	mmap_write_unlock(mm);
32304f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
32311da177e4SLinus Torvalds }
32321da177e4SLinus Torvalds 
32331da177e4SLinus Torvalds /* Insert vm structure into process list sorted by address
32341da177e4SLinus Torvalds  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3235c8c06efaSDavidlohr Bueso  * then i_mmap_rwsem is taken here.
32361da177e4SLinus Torvalds  */
32371da177e4SLinus Torvalds int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
32381da177e4SLinus Torvalds {
3239d4af56c5SLiam R. Howlett 	unsigned long charged = vma_pages(vma);
32401da177e4SLinus Torvalds 
3241d4af56c5SLiam R. Howlett 
3242d0601a50SLiam R. Howlett 	if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3243c9d13f5fSChen Gang 		return -ENOMEM;
3244d4af56c5SLiam R. Howlett 
3245c9d13f5fSChen Gang 	if ((vma->vm_flags & VM_ACCOUNT) &&
3246d4af56c5SLiam R. Howlett 	     security_vm_enough_memory_mm(mm, charged))
3247c9d13f5fSChen Gang 		return -ENOMEM;
3248c9d13f5fSChen Gang 
32491da177e4SLinus Torvalds 	/*
32501da177e4SLinus Torvalds 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
32511da177e4SLinus Torvalds 	 * until its first write fault, when page's anon_vma and index
32521da177e4SLinus Torvalds 	 * are set.  But now set the vm_pgoff it will almost certainly
32531da177e4SLinus Torvalds 	 * end up with (unless mremap moves it elsewhere before that
32541da177e4SLinus Torvalds 	 * first wfault), so /proc/pid/maps tells a consistent story.
32551da177e4SLinus Torvalds 	 *
32561da177e4SLinus Torvalds 	 * By setting it to reflect the virtual start address of the
32571da177e4SLinus Torvalds 	 * vma, merges and splits can happen in a seamless way, just
32581da177e4SLinus Torvalds 	 * using the existing file pgoff checks and manipulations.
32598332326eSLiao Pingfang 	 * Similarly in do_mmap and in do_brk_flags.
32601da177e4SLinus Torvalds 	 */
32618a9cc3b5SOleg Nesterov 	if (vma_is_anonymous(vma)) {
32621da177e4SLinus Torvalds 		BUG_ON(vma->anon_vma);
32631da177e4SLinus Torvalds 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
32641da177e4SLinus Torvalds 	}
32652b144498SSrikar Dronamraju 
3266763ecb03SLiam R. Howlett 	if (vma_link(mm, vma)) {
3267d4af56c5SLiam R. Howlett 		vm_unacct_memory(charged);
3268d4af56c5SLiam R. Howlett 		return -ENOMEM;
3269d4af56c5SLiam R. Howlett 	}
3270d4af56c5SLiam R. Howlett 
32711da177e4SLinus Torvalds 	return 0;
32721da177e4SLinus Torvalds }
32731da177e4SLinus Torvalds 
32741da177e4SLinus Torvalds /*
32751da177e4SLinus Torvalds  * Copy the vma structure to a new location in the same mm,
32761da177e4SLinus Torvalds  * prior to moving page table entries, to effect an mremap move.
32771da177e4SLinus Torvalds  */
32781da177e4SLinus Torvalds struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
327938a76013SMichel Lespinasse 	unsigned long addr, unsigned long len, pgoff_t pgoff,
328038a76013SMichel Lespinasse 	bool *need_rmap_locks)
32811da177e4SLinus Torvalds {
32821da177e4SLinus Torvalds 	struct vm_area_struct *vma = *vmap;
32831da177e4SLinus Torvalds 	unsigned long vma_start = vma->vm_start;
32841da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
32851da177e4SLinus Torvalds 	struct vm_area_struct *new_vma, *prev;
3286948f017bSAndrea Arcangeli 	bool faulted_in_anon_vma = true;
3287076f16bfSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
32881da177e4SLinus Torvalds 
32891da177e4SLinus Torvalds 	/*
32901da177e4SLinus Torvalds 	 * If anonymous vma has not yet been faulted, update new pgoff
32911da177e4SLinus Torvalds 	 * to match new location, to increase its chance of merging.
32921da177e4SLinus Torvalds 	 */
3293ce75799bSOleg Nesterov 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
32941da177e4SLinus Torvalds 		pgoff = addr >> PAGE_SHIFT;
3295948f017bSAndrea Arcangeli 		faulted_in_anon_vma = false;
3296948f017bSAndrea Arcangeli 	}
32971da177e4SLinus Torvalds 
3298763ecb03SLiam R. Howlett 	new_vma = find_vma_prev(mm, addr, &prev);
3299763ecb03SLiam R. Howlett 	if (new_vma && new_vma->vm_start < addr + len)
33006597d783SHugh Dickins 		return NULL;	/* should never get here */
3301524e00b3SLiam R. Howlett 
33029760ebffSLiam R. Howlett 	new_vma = vma_merge(&vmi, mm, prev, addr, addr + len, vma->vm_flags,
330319a809afSAndrea Arcangeli 			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
33045c26f6acSSuren Baghdasaryan 			    vma->vm_userfaultfd_ctx, anon_vma_name(vma));
33051da177e4SLinus Torvalds 	if (new_vma) {
33061da177e4SLinus Torvalds 		/*
33071da177e4SLinus Torvalds 		 * Source vma may have been merged into new_vma
33081da177e4SLinus Torvalds 		 */
3309948f017bSAndrea Arcangeli 		if (unlikely(vma_start >= new_vma->vm_start &&
3310948f017bSAndrea Arcangeli 			     vma_start < new_vma->vm_end)) {
3311948f017bSAndrea Arcangeli 			/*
3312948f017bSAndrea Arcangeli 			 * The only way we can get a vma_merge with
3313948f017bSAndrea Arcangeli 			 * self during an mremap is if the vma hasn't
3314948f017bSAndrea Arcangeli 			 * been faulted in yet and we were allowed to
3315948f017bSAndrea Arcangeli 			 * reset the dst vma->vm_pgoff to the
3316948f017bSAndrea Arcangeli 			 * destination address of the mremap to allow
3317948f017bSAndrea Arcangeli 			 * the merge to happen. mremap must change the
3318948f017bSAndrea Arcangeli 			 * vm_pgoff linearity between src and dst vmas
3319948f017bSAndrea Arcangeli 			 * (in turn preventing a vma_merge) to be
3320948f017bSAndrea Arcangeli 			 * safe. It is only safe to keep the vm_pgoff
3321948f017bSAndrea Arcangeli 			 * linear if there are no pages mapped yet.
3322948f017bSAndrea Arcangeli 			 */
332381d1b09cSSasha Levin 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
332438a76013SMichel Lespinasse 			*vmap = vma = new_vma;
3325108d6642SMichel Lespinasse 		}
332638a76013SMichel Lespinasse 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
33271da177e4SLinus Torvalds 	} else {
33283928d4f5SLinus Torvalds 		new_vma = vm_area_dup(vma);
3329e3975891SChen Gang 		if (!new_vma)
3330e3975891SChen Gang 			goto out;
33311da177e4SLinus Torvalds 		new_vma->vm_start = addr;
33321da177e4SLinus Torvalds 		new_vma->vm_end = addr + len;
33331da177e4SLinus Torvalds 		new_vma->vm_pgoff = pgoff;
3334ef0855d3SOleg Nesterov 		if (vma_dup_policy(vma, new_vma))
3335523d4e20SMichel Lespinasse 			goto out_free_vma;
3336523d4e20SMichel Lespinasse 		if (anon_vma_clone(new_vma, vma))
3337523d4e20SMichel Lespinasse 			goto out_free_mempol;
3338e9714acfSKonstantin Khlebnikov 		if (new_vma->vm_file)
33391da177e4SLinus Torvalds 			get_file(new_vma->vm_file);
33401da177e4SLinus Torvalds 		if (new_vma->vm_ops && new_vma->vm_ops->open)
33411da177e4SLinus Torvalds 			new_vma->vm_ops->open(new_vma);
3342d6ac235dSSuren Baghdasaryan 		vma_start_write(new_vma);
3343763ecb03SLiam R. Howlett 		if (vma_link(mm, new_vma))
3344524e00b3SLiam R. Howlett 			goto out_vma_link;
334538a76013SMichel Lespinasse 		*need_rmap_locks = false;
33461da177e4SLinus Torvalds 	}
33471da177e4SLinus Torvalds 	return new_vma;
33485beb4930SRik van Riel 
3349524e00b3SLiam R. Howlett out_vma_link:
3350524e00b3SLiam R. Howlett 	if (new_vma->vm_ops && new_vma->vm_ops->close)
3351524e00b3SLiam R. Howlett 		new_vma->vm_ops->close(new_vma);
335292b73996SLiam Howlett 
335392b73996SLiam Howlett 	if (new_vma->vm_file)
335492b73996SLiam Howlett 		fput(new_vma->vm_file);
335592b73996SLiam Howlett 
335692b73996SLiam Howlett 	unlink_anon_vmas(new_vma);
33575beb4930SRik van Riel out_free_mempol:
3358ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new_vma));
33595beb4930SRik van Riel out_free_vma:
33603928d4f5SLinus Torvalds 	vm_area_free(new_vma);
3361e3975891SChen Gang out:
33625beb4930SRik van Riel 	return NULL;
33631da177e4SLinus Torvalds }
3364119f657cSakpm@osdl.org 
3365119f657cSakpm@osdl.org /*
3366119f657cSakpm@osdl.org  * Return true if the calling process may expand its vm space by the passed
3367119f657cSakpm@osdl.org  * number of pages
3368119f657cSakpm@osdl.org  */
336984638335SKonstantin Khlebnikov bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3370119f657cSakpm@osdl.org {
337184638335SKonstantin Khlebnikov 	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
337284638335SKonstantin Khlebnikov 		return false;
3373119f657cSakpm@osdl.org 
3374d977d56cSKonstantin Khlebnikov 	if (is_data_mapping(flags) &&
3375d977d56cSKonstantin Khlebnikov 	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3376f4fcd558SKonstantin Khlebnikov 		/* Workaround for Valgrind */
3377f4fcd558SKonstantin Khlebnikov 		if (rlimit(RLIMIT_DATA) == 0 &&
3378f4fcd558SKonstantin Khlebnikov 		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3379f4fcd558SKonstantin Khlebnikov 			return true;
338057a7702bSDavid Woodhouse 
338157a7702bSDavid Woodhouse 		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3382d977d56cSKonstantin Khlebnikov 			     current->comm, current->pid,
3383d977d56cSKonstantin Khlebnikov 			     (mm->data_vm + npages) << PAGE_SHIFT,
338457a7702bSDavid Woodhouse 			     rlimit(RLIMIT_DATA),
338557a7702bSDavid Woodhouse 			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
338657a7702bSDavid Woodhouse 
338757a7702bSDavid Woodhouse 		if (!ignore_rlimit_data)
3388d977d56cSKonstantin Khlebnikov 			return false;
3389d977d56cSKonstantin Khlebnikov 	}
3390119f657cSakpm@osdl.org 
339184638335SKonstantin Khlebnikov 	return true;
339284638335SKonstantin Khlebnikov }
339384638335SKonstantin Khlebnikov 
339484638335SKonstantin Khlebnikov void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
339584638335SKonstantin Khlebnikov {
33967866076bSPeng Liu 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
339784638335SKonstantin Khlebnikov 
3398d977d56cSKonstantin Khlebnikov 	if (is_exec_mapping(flags))
339984638335SKonstantin Khlebnikov 		mm->exec_vm += npages;
3400d977d56cSKonstantin Khlebnikov 	else if (is_stack_mapping(flags))
340184638335SKonstantin Khlebnikov 		mm->stack_vm += npages;
3402d977d56cSKonstantin Khlebnikov 	else if (is_data_mapping(flags))
340384638335SKonstantin Khlebnikov 		mm->data_vm += npages;
3404119f657cSakpm@osdl.org }
3405fa5dc22fSRoland McGrath 
3406b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3407a62c34bdSAndy Lutomirski 
3408a62c34bdSAndy Lutomirski /*
3409a62c34bdSAndy Lutomirski  * Having a close hook prevents vma merging regardless of flags.
3410a62c34bdSAndy Lutomirski  */
3411a62c34bdSAndy Lutomirski static void special_mapping_close(struct vm_area_struct *vma)
3412a62c34bdSAndy Lutomirski {
3413a62c34bdSAndy Lutomirski }
3414a62c34bdSAndy Lutomirski 
3415a62c34bdSAndy Lutomirski static const char *special_mapping_name(struct vm_area_struct *vma)
3416a62c34bdSAndy Lutomirski {
3417a62c34bdSAndy Lutomirski 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3418a62c34bdSAndy Lutomirski }
3419a62c34bdSAndy Lutomirski 
342014d07113SBrian Geffon static int special_mapping_mremap(struct vm_area_struct *new_vma)
3421b059a453SDmitry Safonov {
3422b059a453SDmitry Safonov 	struct vm_special_mapping *sm = new_vma->vm_private_data;
3423b059a453SDmitry Safonov 
3424280e87e9SDmitry Safonov 	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3425280e87e9SDmitry Safonov 		return -EFAULT;
3426280e87e9SDmitry Safonov 
3427b059a453SDmitry Safonov 	if (sm->mremap)
3428b059a453SDmitry Safonov 		return sm->mremap(sm, new_vma);
3429280e87e9SDmitry Safonov 
3430b059a453SDmitry Safonov 	return 0;
3431b059a453SDmitry Safonov }
3432b059a453SDmitry Safonov 
3433871402e0SDmitry Safonov static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3434871402e0SDmitry Safonov {
3435871402e0SDmitry Safonov 	/*
3436871402e0SDmitry Safonov 	 * Forbid splitting special mappings - kernel has expectations over
3437871402e0SDmitry Safonov 	 * the number of pages in mapping. Together with VM_DONTEXPAND
3438871402e0SDmitry Safonov 	 * the size of vma should stay the same over the special mapping's
3439871402e0SDmitry Safonov 	 * lifetime.
3440871402e0SDmitry Safonov 	 */
3441871402e0SDmitry Safonov 	return -EINVAL;
3442871402e0SDmitry Safonov }
3443871402e0SDmitry Safonov 
3444a62c34bdSAndy Lutomirski static const struct vm_operations_struct special_mapping_vmops = {
3445a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3446a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3447b059a453SDmitry Safonov 	.mremap = special_mapping_mremap,
3448a62c34bdSAndy Lutomirski 	.name = special_mapping_name,
3449af34ebebSDmitry Safonov 	/* vDSO code relies that VVAR can't be accessed remotely */
3450af34ebebSDmitry Safonov 	.access = NULL,
3451871402e0SDmitry Safonov 	.may_split = special_mapping_split,
3452a62c34bdSAndy Lutomirski };
3453a62c34bdSAndy Lutomirski 
3454a62c34bdSAndy Lutomirski static const struct vm_operations_struct legacy_special_mapping_vmops = {
3455a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3456a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3457a62c34bdSAndy Lutomirski };
3458fa5dc22fSRoland McGrath 
3459b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3460fa5dc22fSRoland McGrath {
346111bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
3462b1d0e4f5SNick Piggin 	pgoff_t pgoff;
3463fa5dc22fSRoland McGrath 	struct page **pages;
3464fa5dc22fSRoland McGrath 
3465f872f540SAndy Lutomirski 	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3466a62c34bdSAndy Lutomirski 		pages = vma->vm_private_data;
3467f872f540SAndy Lutomirski 	} else {
3468f872f540SAndy Lutomirski 		struct vm_special_mapping *sm = vma->vm_private_data;
3469f872f540SAndy Lutomirski 
3470f872f540SAndy Lutomirski 		if (sm->fault)
347111bac800SDave Jiang 			return sm->fault(sm, vmf->vma, vmf);
3472f872f540SAndy Lutomirski 
3473f872f540SAndy Lutomirski 		pages = sm->pages;
3474f872f540SAndy Lutomirski 	}
3475a62c34bdSAndy Lutomirski 
34768a9cc3b5SOleg Nesterov 	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3477b1d0e4f5SNick Piggin 		pgoff--;
3478fa5dc22fSRoland McGrath 
3479fa5dc22fSRoland McGrath 	if (*pages) {
3480fa5dc22fSRoland McGrath 		struct page *page = *pages;
3481fa5dc22fSRoland McGrath 		get_page(page);
3482b1d0e4f5SNick Piggin 		vmf->page = page;
3483b1d0e4f5SNick Piggin 		return 0;
3484fa5dc22fSRoland McGrath 	}
3485fa5dc22fSRoland McGrath 
3486b1d0e4f5SNick Piggin 	return VM_FAULT_SIGBUS;
3487fa5dc22fSRoland McGrath }
3488fa5dc22fSRoland McGrath 
3489a62c34bdSAndy Lutomirski static struct vm_area_struct *__install_special_mapping(
3490a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3491fa5dc22fSRoland McGrath 	unsigned long addr, unsigned long len,
349227f28b97SChen Gang 	unsigned long vm_flags, void *priv,
349327f28b97SChen Gang 	const struct vm_operations_struct *ops)
3494fa5dc22fSRoland McGrath {
3495462e635eSTavis Ormandy 	int ret;
3496fa5dc22fSRoland McGrath 	struct vm_area_struct *vma;
3497fa5dc22fSRoland McGrath 
3498490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
3499fa5dc22fSRoland McGrath 	if (unlikely(vma == NULL))
35003935ed6aSStefani Seibold 		return ERR_PTR(-ENOMEM);
3501fa5dc22fSRoland McGrath 
3502fa5dc22fSRoland McGrath 	vma->vm_start = addr;
3503fa5dc22fSRoland McGrath 	vma->vm_end = addr + len;
3504fa5dc22fSRoland McGrath 
3505e430a95aSSuren Baghdasaryan 	vm_flags_init(vma, (vm_flags | mm->def_flags |
3506e430a95aSSuren Baghdasaryan 		      VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
35073ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3508fa5dc22fSRoland McGrath 
3509a62c34bdSAndy Lutomirski 	vma->vm_ops = ops;
3510a62c34bdSAndy Lutomirski 	vma->vm_private_data = priv;
3511fa5dc22fSRoland McGrath 
3512462e635eSTavis Ormandy 	ret = insert_vm_struct(mm, vma);
3513462e635eSTavis Ormandy 	if (ret)
3514462e635eSTavis Ormandy 		goto out;
3515fa5dc22fSRoland McGrath 
351684638335SKonstantin Khlebnikov 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3517fa5dc22fSRoland McGrath 
3518cdd6c482SIngo Molnar 	perf_event_mmap(vma);
3519089dd79dSPeter Zijlstra 
35203935ed6aSStefani Seibold 	return vma;
3521462e635eSTavis Ormandy 
3522462e635eSTavis Ormandy out:
35233928d4f5SLinus Torvalds 	vm_area_free(vma);
35243935ed6aSStefani Seibold 	return ERR_PTR(ret);
35253935ed6aSStefani Seibold }
35263935ed6aSStefani Seibold 
35272eefd878SDmitry Safonov bool vma_is_special_mapping(const struct vm_area_struct *vma,
35282eefd878SDmitry Safonov 	const struct vm_special_mapping *sm)
35292eefd878SDmitry Safonov {
35302eefd878SDmitry Safonov 	return vma->vm_private_data == sm &&
35312eefd878SDmitry Safonov 		(vma->vm_ops == &special_mapping_vmops ||
35322eefd878SDmitry Safonov 		 vma->vm_ops == &legacy_special_mapping_vmops);
35332eefd878SDmitry Safonov }
35342eefd878SDmitry Safonov 
3535a62c34bdSAndy Lutomirski /*
3536c1e8d7c6SMichel Lespinasse  * Called with mm->mmap_lock held for writing.
3537a62c34bdSAndy Lutomirski  * Insert a new vma covering the given region, with the given flags.
3538a62c34bdSAndy Lutomirski  * Its pages are supplied by the given array of struct page *.
3539a62c34bdSAndy Lutomirski  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3540a62c34bdSAndy Lutomirski  * The region past the last page supplied will always produce SIGBUS.
3541a62c34bdSAndy Lutomirski  * The array pointer and the pages it points to are assumed to stay alive
3542a62c34bdSAndy Lutomirski  * for as long as this mapping might exist.
3543a62c34bdSAndy Lutomirski  */
3544a62c34bdSAndy Lutomirski struct vm_area_struct *_install_special_mapping(
3545a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3546a62c34bdSAndy Lutomirski 	unsigned long addr, unsigned long len,
3547a62c34bdSAndy Lutomirski 	unsigned long vm_flags, const struct vm_special_mapping *spec)
3548a62c34bdSAndy Lutomirski {
354927f28b97SChen Gang 	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
355027f28b97SChen Gang 					&special_mapping_vmops);
3551a62c34bdSAndy Lutomirski }
3552a62c34bdSAndy Lutomirski 
35533935ed6aSStefani Seibold int install_special_mapping(struct mm_struct *mm,
35543935ed6aSStefani Seibold 			    unsigned long addr, unsigned long len,
35553935ed6aSStefani Seibold 			    unsigned long vm_flags, struct page **pages)
35563935ed6aSStefani Seibold {
3557a62c34bdSAndy Lutomirski 	struct vm_area_struct *vma = __install_special_mapping(
355827f28b97SChen Gang 		mm, addr, len, vm_flags, (void *)pages,
355927f28b97SChen Gang 		&legacy_special_mapping_vmops);
35603935ed6aSStefani Seibold 
356114bd5b45SDuan Jiong 	return PTR_ERR_OR_ZERO(vma);
3562fa5dc22fSRoland McGrath }
35637906d00cSAndrea Arcangeli 
35647906d00cSAndrea Arcangeli static DEFINE_MUTEX(mm_all_locks_mutex);
35657906d00cSAndrea Arcangeli 
3566454ed842SPeter Zijlstra static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
35677906d00cSAndrea Arcangeli {
3568f808c13fSDavidlohr Bueso 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
35697906d00cSAndrea Arcangeli 		/*
35707906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change from under us
35717906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
35727906d00cSAndrea Arcangeli 		 */
3573da1c55f1SMichel Lespinasse 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
35747906d00cSAndrea Arcangeli 		/*
35757906d00cSAndrea Arcangeli 		 * We can safely modify head.next after taking the
35765a505085SIngo Molnar 		 * anon_vma->root->rwsem. If some other vma in this mm shares
35777906d00cSAndrea Arcangeli 		 * the same anon_vma we won't take it again.
35787906d00cSAndrea Arcangeli 		 *
35797906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
35807906d00cSAndrea Arcangeli 		 * can't change from under us thanks to the
35815a505085SIngo Molnar 		 * anon_vma->root->rwsem.
35827906d00cSAndrea Arcangeli 		 */
35837906d00cSAndrea Arcangeli 		if (__test_and_set_bit(0, (unsigned long *)
3584f808c13fSDavidlohr Bueso 				       &anon_vma->root->rb_root.rb_root.rb_node))
35857906d00cSAndrea Arcangeli 			BUG();
35867906d00cSAndrea Arcangeli 	}
35877906d00cSAndrea Arcangeli }
35887906d00cSAndrea Arcangeli 
3589454ed842SPeter Zijlstra static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
35907906d00cSAndrea Arcangeli {
35917906d00cSAndrea Arcangeli 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
35927906d00cSAndrea Arcangeli 		/*
35937906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change from under us because
35947906d00cSAndrea Arcangeli 		 * we hold the mm_all_locks_mutex.
35957906d00cSAndrea Arcangeli 		 *
35967906d00cSAndrea Arcangeli 		 * Operations on ->flags have to be atomic because
35977906d00cSAndrea Arcangeli 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
35987906d00cSAndrea Arcangeli 		 * mm_all_locks_mutex, there may be other cpus
35997906d00cSAndrea Arcangeli 		 * changing other bitflags in parallel to us.
36007906d00cSAndrea Arcangeli 		 */
36017906d00cSAndrea Arcangeli 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
36027906d00cSAndrea Arcangeli 			BUG();
3603da1c55f1SMichel Lespinasse 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
36047906d00cSAndrea Arcangeli 	}
36057906d00cSAndrea Arcangeli }
36067906d00cSAndrea Arcangeli 
36077906d00cSAndrea Arcangeli /*
36087906d00cSAndrea Arcangeli  * This operation locks against the VM for all pte/vma/mm related
36097906d00cSAndrea Arcangeli  * operations that could ever happen on a certain mm. This includes
36107906d00cSAndrea Arcangeli  * vmtruncate, try_to_unmap, and all page faults.
36117906d00cSAndrea Arcangeli  *
3612c1e8d7c6SMichel Lespinasse  * The caller must take the mmap_lock in write mode before calling
36137906d00cSAndrea Arcangeli  * mm_take_all_locks(). The caller isn't allowed to release the
3614c1e8d7c6SMichel Lespinasse  * mmap_lock until mm_drop_all_locks() returns.
36157906d00cSAndrea Arcangeli  *
3616c1e8d7c6SMichel Lespinasse  * mmap_lock in write mode is required in order to block all operations
36177906d00cSAndrea Arcangeli  * that could modify pagetables and free pages without need of
361827ba0644SKirill A. Shutemov  * altering the vma layout. It's also needed in write mode to avoid new
36197906d00cSAndrea Arcangeli  * anon_vmas to be associated with existing vmas.
36207906d00cSAndrea Arcangeli  *
36217906d00cSAndrea Arcangeli  * A single task can't take more than one mm_take_all_locks() in a row
36227906d00cSAndrea Arcangeli  * or it would deadlock.
36237906d00cSAndrea Arcangeli  *
3624bf181b9fSMichel Lespinasse  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
36257906d00cSAndrea Arcangeli  * mapping->flags avoid to take the same lock twice, if more than one
36267906d00cSAndrea Arcangeli  * vma in this mm is backed by the same anon_vma or address_space.
36277906d00cSAndrea Arcangeli  *
362888f306b6SKirill A. Shutemov  * We take locks in following order, accordingly to comment at beginning
362988f306b6SKirill A. Shutemov  * of mm/rmap.c:
363088f306b6SKirill A. Shutemov  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
363188f306b6SKirill A. Shutemov  *     hugetlb mapping);
3632eeff9a5dSSuren Baghdasaryan  *   - all vmas marked locked
363388f306b6SKirill A. Shutemov  *   - all i_mmap_rwsem locks;
363488f306b6SKirill A. Shutemov  *   - all anon_vma->rwseml
363588f306b6SKirill A. Shutemov  *
363688f306b6SKirill A. Shutemov  * We can take all locks within these types randomly because the VM code
363788f306b6SKirill A. Shutemov  * doesn't nest them and we protected from parallel mm_take_all_locks() by
363888f306b6SKirill A. Shutemov  * mm_all_locks_mutex.
36397906d00cSAndrea Arcangeli  *
36407906d00cSAndrea Arcangeli  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
36417906d00cSAndrea Arcangeli  * that may have to take thousand of locks.
36427906d00cSAndrea Arcangeli  *
36437906d00cSAndrea Arcangeli  * mm_take_all_locks() can fail if it's interrupted by signals.
36447906d00cSAndrea Arcangeli  */
36457906d00cSAndrea Arcangeli int mm_take_all_locks(struct mm_struct *mm)
36467906d00cSAndrea Arcangeli {
36477906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
36485beb4930SRik van Riel 	struct anon_vma_chain *avc;
3649763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
36507906d00cSAndrea Arcangeli 
3651325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
36527906d00cSAndrea Arcangeli 
36537906d00cSAndrea Arcangeli 	mutex_lock(&mm_all_locks_mutex);
36547906d00cSAndrea Arcangeli 
365590717566SJann Horn 	/*
365690717566SJann Horn 	 * vma_start_write() does not have a complement in mm_drop_all_locks()
365790717566SJann Horn 	 * because vma_start_write() is always asymmetrical; it marks a VMA as
365890717566SJann Horn 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
365990717566SJann Horn 	 * is reached.
366090717566SJann Horn 	 */
3661763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
36627906d00cSAndrea Arcangeli 		if (signal_pending(current))
36637906d00cSAndrea Arcangeli 			goto out_unlock;
3664eeff9a5dSSuren Baghdasaryan 		vma_start_write(vma);
3665eeff9a5dSSuren Baghdasaryan 	}
3666eeff9a5dSSuren Baghdasaryan 
3667eeff9a5dSSuren Baghdasaryan 	mas_set(&mas, 0);
3668eeff9a5dSSuren Baghdasaryan 	mas_for_each(&mas, vma, ULONG_MAX) {
3669eeff9a5dSSuren Baghdasaryan 		if (signal_pending(current))
3670eeff9a5dSSuren Baghdasaryan 			goto out_unlock;
367188f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
367288f306b6SKirill A. Shutemov 				is_vm_hugetlb_page(vma))
367388f306b6SKirill A. Shutemov 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
367488f306b6SKirill A. Shutemov 	}
367588f306b6SKirill A. Shutemov 
3676763ecb03SLiam R. Howlett 	mas_set(&mas, 0);
3677763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
367888f306b6SKirill A. Shutemov 		if (signal_pending(current))
367988f306b6SKirill A. Shutemov 			goto out_unlock;
368088f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
368188f306b6SKirill A. Shutemov 				!is_vm_hugetlb_page(vma))
3682454ed842SPeter Zijlstra 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
36837906d00cSAndrea Arcangeli 	}
36847cd5a02fSPeter Zijlstra 
3685763ecb03SLiam R. Howlett 	mas_set(&mas, 0);
3686763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
36877cd5a02fSPeter Zijlstra 		if (signal_pending(current))
36887cd5a02fSPeter Zijlstra 			goto out_unlock;
36897cd5a02fSPeter Zijlstra 		if (vma->anon_vma)
36905beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
36915beb4930SRik van Riel 				vm_lock_anon_vma(mm, avc->anon_vma);
36927cd5a02fSPeter Zijlstra 	}
36937cd5a02fSPeter Zijlstra 
3694584cff54SKautuk Consul 	return 0;
36957906d00cSAndrea Arcangeli 
36967906d00cSAndrea Arcangeli out_unlock:
36977906d00cSAndrea Arcangeli 	mm_drop_all_locks(mm);
3698584cff54SKautuk Consul 	return -EINTR;
36997906d00cSAndrea Arcangeli }
37007906d00cSAndrea Arcangeli 
37017906d00cSAndrea Arcangeli static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
37027906d00cSAndrea Arcangeli {
3703f808c13fSDavidlohr Bueso 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
37047906d00cSAndrea Arcangeli 		/*
37057906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change to 0 from under
37067906d00cSAndrea Arcangeli 		 * us because we hold the mm_all_locks_mutex.
37077906d00cSAndrea Arcangeli 		 *
37087906d00cSAndrea Arcangeli 		 * We must however clear the bitflag before unlocking
3709bf181b9fSMichel Lespinasse 		 * the vma so the users using the anon_vma->rb_root will
37107906d00cSAndrea Arcangeli 		 * never see our bitflag.
37117906d00cSAndrea Arcangeli 		 *
37127906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
37137906d00cSAndrea Arcangeli 		 * can't change from under us until we release the
37145a505085SIngo Molnar 		 * anon_vma->root->rwsem.
37157906d00cSAndrea Arcangeli 		 */
37167906d00cSAndrea Arcangeli 		if (!__test_and_clear_bit(0, (unsigned long *)
3717f808c13fSDavidlohr Bueso 					  &anon_vma->root->rb_root.rb_root.rb_node))
37187906d00cSAndrea Arcangeli 			BUG();
371908b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
37207906d00cSAndrea Arcangeli 	}
37217906d00cSAndrea Arcangeli }
37227906d00cSAndrea Arcangeli 
37237906d00cSAndrea Arcangeli static void vm_unlock_mapping(struct address_space *mapping)
37247906d00cSAndrea Arcangeli {
37257906d00cSAndrea Arcangeli 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
37267906d00cSAndrea Arcangeli 		/*
37277906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
37287906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
37297906d00cSAndrea Arcangeli 		 */
373083cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
37317906d00cSAndrea Arcangeli 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
37327906d00cSAndrea Arcangeli 					&mapping->flags))
37337906d00cSAndrea Arcangeli 			BUG();
37347906d00cSAndrea Arcangeli 	}
37357906d00cSAndrea Arcangeli }
37367906d00cSAndrea Arcangeli 
37377906d00cSAndrea Arcangeli /*
3738c1e8d7c6SMichel Lespinasse  * The mmap_lock cannot be released by the caller until
37397906d00cSAndrea Arcangeli  * mm_drop_all_locks() returns.
37407906d00cSAndrea Arcangeli  */
37417906d00cSAndrea Arcangeli void mm_drop_all_locks(struct mm_struct *mm)
37427906d00cSAndrea Arcangeli {
37437906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
37445beb4930SRik van Riel 	struct anon_vma_chain *avc;
3745763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
37467906d00cSAndrea Arcangeli 
3747325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
37487906d00cSAndrea Arcangeli 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
37497906d00cSAndrea Arcangeli 
3750763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
37517906d00cSAndrea Arcangeli 		if (vma->anon_vma)
37525beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
37535beb4930SRik van Riel 				vm_unlock_anon_vma(avc->anon_vma);
37547906d00cSAndrea Arcangeli 		if (vma->vm_file && vma->vm_file->f_mapping)
37557906d00cSAndrea Arcangeli 			vm_unlock_mapping(vma->vm_file->f_mapping);
37567906d00cSAndrea Arcangeli 	}
37577906d00cSAndrea Arcangeli 
37587906d00cSAndrea Arcangeli 	mutex_unlock(&mm_all_locks_mutex);
37597906d00cSAndrea Arcangeli }
37608feae131SDavid Howells 
37618feae131SDavid Howells /*
37623edf41d8Sseokhoon.yoon  * initialise the percpu counter for VM
37638feae131SDavid Howells  */
37648feae131SDavid Howells void __init mmap_init(void)
37658feae131SDavid Howells {
376600a62ce9SKOSAKI Motohiro 	int ret;
376700a62ce9SKOSAKI Motohiro 
3768908c7f19STejun Heo 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
376900a62ce9SKOSAKI Motohiro 	VM_BUG_ON(ret);
37708feae131SDavid Howells }
3771c9b1d098SAndrew Shewmaker 
3772c9b1d098SAndrew Shewmaker /*
3773c9b1d098SAndrew Shewmaker  * Initialise sysctl_user_reserve_kbytes.
3774c9b1d098SAndrew Shewmaker  *
3775c9b1d098SAndrew Shewmaker  * This is intended to prevent a user from starting a single memory hogging
3776c9b1d098SAndrew Shewmaker  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3777c9b1d098SAndrew Shewmaker  * mode.
3778c9b1d098SAndrew Shewmaker  *
3779c9b1d098SAndrew Shewmaker  * The default value is min(3% of free memory, 128MB)
3780c9b1d098SAndrew Shewmaker  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3781c9b1d098SAndrew Shewmaker  */
37821640879aSAndrew Shewmaker static int init_user_reserve(void)
3783c9b1d098SAndrew Shewmaker {
3784c9b1d098SAndrew Shewmaker 	unsigned long free_kbytes;
3785c9b1d098SAndrew Shewmaker 
3786c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3787c9b1d098SAndrew Shewmaker 
3788c9b1d098SAndrew Shewmaker 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3789c9b1d098SAndrew Shewmaker 	return 0;
3790c9b1d098SAndrew Shewmaker }
3791a64fb3cdSPaul Gortmaker subsys_initcall(init_user_reserve);
37924eeab4f5SAndrew Shewmaker 
37934eeab4f5SAndrew Shewmaker /*
37944eeab4f5SAndrew Shewmaker  * Initialise sysctl_admin_reserve_kbytes.
37954eeab4f5SAndrew Shewmaker  *
37964eeab4f5SAndrew Shewmaker  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
37974eeab4f5SAndrew Shewmaker  * to log in and kill a memory hogging process.
37984eeab4f5SAndrew Shewmaker  *
37994eeab4f5SAndrew Shewmaker  * Systems with more than 256MB will reserve 8MB, enough to recover
38004eeab4f5SAndrew Shewmaker  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
38014eeab4f5SAndrew Shewmaker  * only reserve 3% of free pages by default.
38024eeab4f5SAndrew Shewmaker  */
38031640879aSAndrew Shewmaker static int init_admin_reserve(void)
38044eeab4f5SAndrew Shewmaker {
38054eeab4f5SAndrew Shewmaker 	unsigned long free_kbytes;
38064eeab4f5SAndrew Shewmaker 
3807c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
38084eeab4f5SAndrew Shewmaker 
38094eeab4f5SAndrew Shewmaker 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
38104eeab4f5SAndrew Shewmaker 	return 0;
38114eeab4f5SAndrew Shewmaker }
3812a64fb3cdSPaul Gortmaker subsys_initcall(init_admin_reserve);
38131640879aSAndrew Shewmaker 
38141640879aSAndrew Shewmaker /*
38151640879aSAndrew Shewmaker  * Reinititalise user and admin reserves if memory is added or removed.
38161640879aSAndrew Shewmaker  *
38171640879aSAndrew Shewmaker  * The default user reserve max is 128MB, and the default max for the
38181640879aSAndrew Shewmaker  * admin reserve is 8MB. These are usually, but not always, enough to
38191640879aSAndrew Shewmaker  * enable recovery from a memory hogging process using login/sshd, a shell,
38201640879aSAndrew Shewmaker  * and tools like top. It may make sense to increase or even disable the
38211640879aSAndrew Shewmaker  * reserve depending on the existence of swap or variations in the recovery
38221640879aSAndrew Shewmaker  * tools. So, the admin may have changed them.
38231640879aSAndrew Shewmaker  *
38241640879aSAndrew Shewmaker  * If memory is added and the reserves have been eliminated or increased above
38251640879aSAndrew Shewmaker  * the default max, then we'll trust the admin.
38261640879aSAndrew Shewmaker  *
38271640879aSAndrew Shewmaker  * If memory is removed and there isn't enough free memory, then we
38281640879aSAndrew Shewmaker  * need to reset the reserves.
38291640879aSAndrew Shewmaker  *
38301640879aSAndrew Shewmaker  * Otherwise keep the reserve set by the admin.
38311640879aSAndrew Shewmaker  */
38321640879aSAndrew Shewmaker static int reserve_mem_notifier(struct notifier_block *nb,
38331640879aSAndrew Shewmaker 			     unsigned long action, void *data)
38341640879aSAndrew Shewmaker {
38351640879aSAndrew Shewmaker 	unsigned long tmp, free_kbytes;
38361640879aSAndrew Shewmaker 
38371640879aSAndrew Shewmaker 	switch (action) {
38381640879aSAndrew Shewmaker 	case MEM_ONLINE:
38391640879aSAndrew Shewmaker 		/* Default max is 128MB. Leave alone if modified by operator. */
38401640879aSAndrew Shewmaker 		tmp = sysctl_user_reserve_kbytes;
38411640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 17))
38421640879aSAndrew Shewmaker 			init_user_reserve();
38431640879aSAndrew Shewmaker 
38441640879aSAndrew Shewmaker 		/* Default max is 8MB.  Leave alone if modified by operator. */
38451640879aSAndrew Shewmaker 		tmp = sysctl_admin_reserve_kbytes;
38461640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 13))
38471640879aSAndrew Shewmaker 			init_admin_reserve();
38481640879aSAndrew Shewmaker 
38491640879aSAndrew Shewmaker 		break;
38501640879aSAndrew Shewmaker 	case MEM_OFFLINE:
3851c41f012aSMichal Hocko 		free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
38521640879aSAndrew Shewmaker 
38531640879aSAndrew Shewmaker 		if (sysctl_user_reserve_kbytes > free_kbytes) {
38541640879aSAndrew Shewmaker 			init_user_reserve();
38551640879aSAndrew Shewmaker 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
38561640879aSAndrew Shewmaker 				sysctl_user_reserve_kbytes);
38571640879aSAndrew Shewmaker 		}
38581640879aSAndrew Shewmaker 
38591640879aSAndrew Shewmaker 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
38601640879aSAndrew Shewmaker 			init_admin_reserve();
38611640879aSAndrew Shewmaker 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
38621640879aSAndrew Shewmaker 				sysctl_admin_reserve_kbytes);
38631640879aSAndrew Shewmaker 		}
38641640879aSAndrew Shewmaker 		break;
38651640879aSAndrew Shewmaker 	default:
38661640879aSAndrew Shewmaker 		break;
38671640879aSAndrew Shewmaker 	}
38681640879aSAndrew Shewmaker 	return NOTIFY_OK;
38691640879aSAndrew Shewmaker }
38701640879aSAndrew Shewmaker 
38711640879aSAndrew Shewmaker static int __meminit init_reserve_notifier(void)
38721640879aSAndrew Shewmaker {
38731eeaa4fdSLiu Shixin 	if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
3874b1de0d13SMitchel Humpherys 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
38751640879aSAndrew Shewmaker 
38761640879aSAndrew Shewmaker 	return 0;
38771640879aSAndrew Shewmaker }
3878a64fb3cdSPaul Gortmaker subsys_initcall(init_reserve_notifier);
3879