xref: /openbmc/linux/mm/mmap.c (revision b9349432)
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 
vm_pgprot_modify(pgprot_t oldprot,unsigned long vm_flags)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. */
vma_set_page_prot(struct vm_area_struct * vma)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  */
__remove_shared_vm_struct(struct vm_area_struct * vma,struct file * file,struct address_space * mapping)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  */
unlink_file_vma(struct vm_area_struct * vma)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  */
remove_vma(struct vm_area_struct * vma,bool unreachable)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 
vma_prev_limit(struct vma_iterator * vmi,unsigned long min)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 
1572e7ce7d3SLiam R. Howlett /*
1582e7ce7d3SLiam R. Howlett  * check_brk_limits() - Use platform specific check of range & verify mlock
1592e7ce7d3SLiam R. Howlett  * limits.
1602e7ce7d3SLiam R. Howlett  * @addr: The address to check
1612e7ce7d3SLiam R. Howlett  * @len: The size of increase.
1622e7ce7d3SLiam R. Howlett  *
1632e7ce7d3SLiam R. Howlett  * Return: 0 on success.
1642e7ce7d3SLiam R. Howlett  */
check_brk_limits(unsigned long addr,unsigned long len)1652e7ce7d3SLiam R. Howlett static int check_brk_limits(unsigned long addr, unsigned long len)
1662e7ce7d3SLiam R. Howlett {
1672e7ce7d3SLiam R. Howlett 	unsigned long mapped_addr;
1682e7ce7d3SLiam R. Howlett 
1692e7ce7d3SLiam R. Howlett 	mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
1702e7ce7d3SLiam R. Howlett 	if (IS_ERR_VALUE(mapped_addr))
1712e7ce7d3SLiam R. Howlett 		return mapped_addr;
1722e7ce7d3SLiam R. Howlett 
173b0cc5e89SAndrew Morton 	return mlock_future_ok(current->mm, current->mm->def_flags, len)
1743c54a298SLorenzo Stoakes 		? 0 : -EAGAIN;
1752e7ce7d3SLiam R. Howlett }
17692fed820SLiam R. Howlett static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma,
177763ecb03SLiam R. Howlett 		unsigned long addr, unsigned long request, unsigned long flags);
SYSCALL_DEFINE1(brk,unsigned long,brk)1786a6160a7SHeiko Carstens SYSCALL_DEFINE1(brk, unsigned long, brk)
1791da177e4SLinus Torvalds {
1809bc8039eSYang Shi 	unsigned long newbrk, oldbrk, origbrk;
1811da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1822e7ce7d3SLiam R. Howlett 	struct vm_area_struct *brkvma, *next = NULL;
183a5b4592cSJiri Kosina 	unsigned long min_brk;
184408579cdSLiam R. Howlett 	bool populate = false;
185897ab3e0SMike Rapoport 	LIST_HEAD(uf);
18692fed820SLiam R. Howlett 	struct vma_iterator vmi;
1871da177e4SLinus Torvalds 
188d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
189dc0ef0dfSMichal Hocko 		return -EINTR;
1901da177e4SLinus Torvalds 
1919bc8039eSYang Shi 	origbrk = mm->brk;
1929bc8039eSYang Shi 
193a5b4592cSJiri Kosina #ifdef CONFIG_COMPAT_BRK
1945520e894SJiri Kosina 	/*
1955520e894SJiri Kosina 	 * CONFIG_COMPAT_BRK can still be overridden by setting
1965520e894SJiri Kosina 	 * randomize_va_space to 2, which will still cause mm->start_brk
1975520e894SJiri Kosina 	 * to be arbitrarily shifted
1985520e894SJiri Kosina 	 */
1994471a675SJiri Kosina 	if (current->brk_randomized)
2005520e894SJiri Kosina 		min_brk = mm->start_brk;
2015520e894SJiri Kosina 	else
2025520e894SJiri Kosina 		min_brk = mm->end_data;
203a5b4592cSJiri Kosina #else
204a5b4592cSJiri Kosina 	min_brk = mm->start_brk;
205a5b4592cSJiri Kosina #endif
206a5b4592cSJiri Kosina 	if (brk < min_brk)
2071da177e4SLinus Torvalds 		goto out;
2081e624196SRam Gupta 
2091e624196SRam Gupta 	/*
2101e624196SRam Gupta 	 * Check against rlimit here. If this check is done later after the test
2111e624196SRam Gupta 	 * of oldbrk with newbrk then it can escape the test and let the data
2121e624196SRam Gupta 	 * segment grow beyond its set limit the in case where the limit is
2131e624196SRam Gupta 	 * not page aligned -Ram Gupta
2141e624196SRam Gupta 	 */
2158764b338SCyrill Gorcunov 	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
2168764b338SCyrill Gorcunov 			      mm->end_data, mm->start_data))
2171e624196SRam Gupta 		goto out;
2181e624196SRam Gupta 
2191da177e4SLinus Torvalds 	newbrk = PAGE_ALIGN(brk);
2201da177e4SLinus Torvalds 	oldbrk = PAGE_ALIGN(mm->brk);
2219bc8039eSYang Shi 	if (oldbrk == newbrk) {
2229bc8039eSYang Shi 		mm->brk = brk;
2239bc8039eSYang Shi 		goto success;
2249bc8039eSYang Shi 	}
2251da177e4SLinus Torvalds 
226408579cdSLiam R. Howlett 	/* Always allow shrinking brk. */
2271da177e4SLinus Torvalds 	if (brk <= mm->brk) {
2282e7ce7d3SLiam R. Howlett 		/* Search one past newbrk */
22992fed820SLiam R. Howlett 		vma_iter_init(&vmi, mm, newbrk);
23092fed820SLiam R. Howlett 		brkvma = vma_find(&vmi, oldbrk);
231f5ad5083SJason A. Donenfeld 		if (!brkvma || brkvma->vm_start >= oldbrk)
2322e7ce7d3SLiam R. Howlett 			goto out; /* mapping intersects with an existing non-brk vma. */
2339bc8039eSYang Shi 		/*
2342e7ce7d3SLiam R. Howlett 		 * mm->brk must be protected by write mmap_lock.
235408579cdSLiam R. Howlett 		 * do_vma_munmap() will drop the lock on success,  so update it
23627b26701SLiam R. Howlett 		 * before calling do_vma_munmap().
2379bc8039eSYang Shi 		 */
2389bc8039eSYang Shi 		mm->brk = brk;
239408579cdSLiam R. Howlett 		if (do_vma_munmap(&vmi, brkvma, newbrk, oldbrk, &uf, true))
2401da177e4SLinus Torvalds 			goto out;
241408579cdSLiam R. Howlett 
242408579cdSLiam R. Howlett 		goto success_unlocked;
2431da177e4SLinus Torvalds 	}
2441da177e4SLinus Torvalds 
2452e7ce7d3SLiam R. Howlett 	if (check_brk_limits(oldbrk, newbrk - oldbrk))
2462e7ce7d3SLiam R. Howlett 		goto out;
2472e7ce7d3SLiam R. Howlett 
2482e7ce7d3SLiam R. Howlett 	/*
2492e7ce7d3SLiam R. Howlett 	 * Only check if the next VMA is within the stack_guard_gap of the
2502e7ce7d3SLiam R. Howlett 	 * expansion area
2512e7ce7d3SLiam R. Howlett 	 */
25292fed820SLiam R. Howlett 	vma_iter_init(&vmi, mm, oldbrk);
25392fed820SLiam R. Howlett 	next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
2541be7107fSHugh Dickins 	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
2551da177e4SLinus Torvalds 		goto out;
2561da177e4SLinus Torvalds 
25792fed820SLiam R. Howlett 	brkvma = vma_prev_limit(&vmi, mm->start_brk);
2581da177e4SLinus Torvalds 	/* Ok, looks good - let it rip. */
25992fed820SLiam R. Howlett 	if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
2601da177e4SLinus Torvalds 		goto out;
2612e7ce7d3SLiam R. Howlett 
2621da177e4SLinus Torvalds 	mm->brk = brk;
263408579cdSLiam R. Howlett 	if (mm->def_flags & VM_LOCKED)
264408579cdSLiam R. Howlett 		populate = true;
2659bc8039eSYang Shi 
2669bc8039eSYang Shi success:
267d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
268408579cdSLiam R. Howlett success_unlocked:
269897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
270128557ffSMichel Lespinasse 	if (populate)
271128557ffSMichel Lespinasse 		mm_populate(oldbrk, newbrk - oldbrk);
272128557ffSMichel Lespinasse 	return brk;
273128557ffSMichel Lespinasse 
2741da177e4SLinus Torvalds out:
275408579cdSLiam R. Howlett 	mm->brk = origbrk;
276d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
277b7204006SAdrian Huang 	return origbrk;
2781da177e4SLinus Torvalds }
2791da177e4SLinus Torvalds 
280d4af56c5SLiam R. Howlett #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
validate_mm(struct mm_struct * mm)281eafd4dc4SRashika Kheria static void validate_mm(struct mm_struct *mm)
2821da177e4SLinus Torvalds {
2831da177e4SLinus Torvalds 	int bug = 0;
2841da177e4SLinus Torvalds 	int i = 0;
285763ecb03SLiam R. Howlett 	struct vm_area_struct *vma;
286b50e195fSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, 0);
287ff26f70fSAndrew Morton 
288b50e195fSLiam R. Howlett 	mt_validate(&mm->mm_mt);
289b50e195fSLiam R. Howlett 	for_each_vma(vmi, vma) {
290524e00b3SLiam R. Howlett #ifdef CONFIG_DEBUG_VM_RB
29112352d3cSKonstantin Khlebnikov 		struct anon_vma *anon_vma = vma->anon_vma;
292ed8ea815SMichel Lespinasse 		struct anon_vma_chain *avc;
293b50e195fSLiam R. Howlett #endif
294b50e195fSLiam R. Howlett 		unsigned long vmi_start, vmi_end;
295b50e195fSLiam R. Howlett 		bool warn = 0;
296ff26f70fSAndrew Morton 
297b50e195fSLiam R. Howlett 		vmi_start = vma_iter_addr(&vmi);
298b50e195fSLiam R. Howlett 		vmi_end = vma_iter_end(&vmi);
299b50e195fSLiam R. Howlett 		if (VM_WARN_ON_ONCE_MM(vma->vm_end != vmi_end, mm))
300b50e195fSLiam R. Howlett 			warn = 1;
301b50e195fSLiam R. Howlett 
302b50e195fSLiam R. Howlett 		if (VM_WARN_ON_ONCE_MM(vma->vm_start != vmi_start, mm))
303b50e195fSLiam R. Howlett 			warn = 1;
304b50e195fSLiam R. Howlett 
305b50e195fSLiam R. Howlett 		if (warn) {
306b50e195fSLiam R. Howlett 			pr_emerg("issue in %s\n", current->comm);
307b50e195fSLiam R. Howlett 			dump_stack();
308b50e195fSLiam R. Howlett 			dump_vma(vma);
309b50e195fSLiam R. Howlett 			pr_emerg("tree range: %px start %lx end %lx\n", vma,
310b50e195fSLiam R. Howlett 				 vmi_start, vmi_end - 1);
311b50e195fSLiam R. Howlett 			vma_iter_dump_tree(&vmi);
312b50e195fSLiam R. Howlett 		}
313b50e195fSLiam R. Howlett 
314b50e195fSLiam R. Howlett #ifdef CONFIG_DEBUG_VM_RB
31512352d3cSKonstantin Khlebnikov 		if (anon_vma) {
31612352d3cSKonstantin Khlebnikov 			anon_vma_lock_read(anon_vma);
317ed8ea815SMichel Lespinasse 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
318ed8ea815SMichel Lespinasse 				anon_vma_interval_tree_verify(avc);
31912352d3cSKonstantin Khlebnikov 			anon_vma_unlock_read(anon_vma);
32012352d3cSKonstantin Khlebnikov 		}
321524e00b3SLiam R. Howlett #endif
3221da177e4SLinus Torvalds 		i++;
3231da177e4SLinus Torvalds 	}
3245a0768f6SMichel Lespinasse 	if (i != mm->map_count) {
325b50e195fSLiam R. Howlett 		pr_emerg("map_count %d vma iterator %d\n", mm->map_count, i);
3265a0768f6SMichel Lespinasse 		bug = 1;
3275a0768f6SMichel Lespinasse 	}
32896dad67fSSasha Levin 	VM_BUG_ON_MM(bug, mm);
3291da177e4SLinus Torvalds }
330524e00b3SLiam R. Howlett 
331524e00b3SLiam R. Howlett #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
3321da177e4SLinus Torvalds #define validate_mm(mm) do { } while (0)
333524e00b3SLiam R. Howlett #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
334d3737187SMichel Lespinasse 
335bf181b9fSMichel Lespinasse /*
336bf181b9fSMichel Lespinasse  * vma has some anon_vma assigned, and is already inserted on that
337bf181b9fSMichel Lespinasse  * anon_vma's interval trees.
338bf181b9fSMichel Lespinasse  *
339bf181b9fSMichel Lespinasse  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
340bf181b9fSMichel Lespinasse  * vma must be removed from the anon_vma's interval trees using
341bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_pre_update_vma().
342bf181b9fSMichel Lespinasse  *
343bf181b9fSMichel Lespinasse  * After the update, the vma will be reinserted using
344bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_post_update_vma().
345bf181b9fSMichel Lespinasse  *
346c1e8d7c6SMichel Lespinasse  * The entire update must be protected by exclusive mmap_lock and by
347bf181b9fSMichel Lespinasse  * the root anon_vma's mutex.
348bf181b9fSMichel Lespinasse  */
349bf181b9fSMichel Lespinasse static inline void
anon_vma_interval_tree_pre_update_vma(struct vm_area_struct * vma)350bf181b9fSMichel Lespinasse anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
351bf181b9fSMichel Lespinasse {
352bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
353bf181b9fSMichel Lespinasse 
354bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
355bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
356bf181b9fSMichel Lespinasse }
357bf181b9fSMichel Lespinasse 
358bf181b9fSMichel Lespinasse static inline void
anon_vma_interval_tree_post_update_vma(struct vm_area_struct * vma)359bf181b9fSMichel Lespinasse anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
360bf181b9fSMichel Lespinasse {
361bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
362bf181b9fSMichel Lespinasse 
363bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
364bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
365bf181b9fSMichel Lespinasse }
366bf181b9fSMichel Lespinasse 
count_vma_pages_range(struct mm_struct * mm,unsigned long addr,unsigned long end)367e8420a8eSCyril Hrubis static unsigned long count_vma_pages_range(struct mm_struct *mm,
368e8420a8eSCyril Hrubis 		unsigned long addr, unsigned long end)
369e8420a8eSCyril Hrubis {
3702e3af1dbSMatthew Wilcox (Oracle) 	VMA_ITERATOR(vmi, mm, addr);
371e8420a8eSCyril Hrubis 	struct vm_area_struct *vma;
3722e3af1dbSMatthew Wilcox (Oracle) 	unsigned long nr_pages = 0;
373e8420a8eSCyril Hrubis 
3742e3af1dbSMatthew Wilcox (Oracle) 	for_each_vma_range(vmi, vma, end) {
3752e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_start = max(addr, vma->vm_start);
3762e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_end = min(end, vma->vm_end);
377e8420a8eSCyril Hrubis 
3782e3af1dbSMatthew Wilcox (Oracle) 		nr_pages += PHYS_PFN(vm_end - vm_start);
379e8420a8eSCyril Hrubis 	}
380e8420a8eSCyril Hrubis 
381e8420a8eSCyril Hrubis 	return nr_pages;
382e8420a8eSCyril Hrubis }
383e8420a8eSCyril Hrubis 
__vma_link_file(struct vm_area_struct * vma,struct address_space * mapping)384c154124fSLiam R. Howlett static void __vma_link_file(struct vm_area_struct *vma,
385c154124fSLiam R. Howlett 			    struct address_space *mapping)
3861da177e4SLinus Torvalds {
3871da177e4SLinus Torvalds 	if (vma->vm_flags & VM_SHARED)
388cf508b58SMiaohe Lin 		mapping_allow_writable(mapping);
3891da177e4SLinus Torvalds 
3901da177e4SLinus Torvalds 	flush_dcache_mmap_lock(mapping);
3916b2dbba8SMichel Lespinasse 	vma_interval_tree_insert(vma, &mapping->i_mmap);
3921da177e4SLinus Torvalds 	flush_dcache_mmap_unlock(mapping);
3931da177e4SLinus Torvalds }
3941da177e4SLinus Torvalds 
vma_link(struct mm_struct * mm,struct vm_area_struct * vma)395763ecb03SLiam R. Howlett static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
3961da177e4SLinus Torvalds {
39779e4f2caSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, 0);
3981da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
3991da177e4SLinus Torvalds 
400b5df0922SLiam R. Howlett 	vma_iter_config(&vmi, vma->vm_start, vma->vm_end);
401b5df0922SLiam R. Howlett 	if (vma_iter_prealloc(&vmi, vma))
402d4af56c5SLiam R. Howlett 		return -ENOMEM;
403d4af56c5SLiam R. Howlett 
404ad9f0063SSuren Baghdasaryan 	vma_start_write(vma);
405ad9f0063SSuren Baghdasaryan 
4066852c46cSYu Ma 	vma_iter_store(&vmi, vma);
4076852c46cSYu Ma 
40864ac4940SHuang Shijie 	if (vma->vm_file) {
4091da177e4SLinus Torvalds 		mapping = vma->vm_file->f_mapping;
41083cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
411c154124fSLiam R. Howlett 		__vma_link_file(vma, mapping);
41283cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
413c154124fSLiam R. Howlett 	}
4141da177e4SLinus Torvalds 
4151da177e4SLinus Torvalds 	mm->map_count++;
4161da177e4SLinus Torvalds 	validate_mm(mm);
417d4af56c5SLiam R. Howlett 	return 0;
4181da177e4SLinus Torvalds }
4191da177e4SLinus Torvalds 
4201da177e4SLinus Torvalds /*
42168cefec5SLiam R. Howlett  * init_multi_vma_prep() - Initializer for struct vma_prepare
42268cefec5SLiam R. Howlett  * @vp: The vma_prepare struct
42368cefec5SLiam R. Howlett  * @vma: The vma that will be altered once locked
42468cefec5SLiam R. Howlett  * @next: The next vma if it is to be adjusted
42568cefec5SLiam R. Howlett  * @remove: The first vma to be removed
42668cefec5SLiam R. Howlett  * @remove2: The second vma to be removed
42768cefec5SLiam R. Howlett  */
init_multi_vma_prep(struct vma_prepare * vp,struct vm_area_struct * vma,struct vm_area_struct * next,struct vm_area_struct * remove,struct vm_area_struct * remove2)42868cefec5SLiam R. Howlett static inline void init_multi_vma_prep(struct vma_prepare *vp,
42968cefec5SLiam R. Howlett 		struct vm_area_struct *vma, struct vm_area_struct *next,
43068cefec5SLiam R. Howlett 		struct vm_area_struct *remove, struct vm_area_struct *remove2)
43168cefec5SLiam R. Howlett {
43268cefec5SLiam R. Howlett 	memset(vp, 0, sizeof(struct vma_prepare));
43368cefec5SLiam R. Howlett 	vp->vma = vma;
43468cefec5SLiam R. Howlett 	vp->anon_vma = vma->anon_vma;
43568cefec5SLiam R. Howlett 	vp->remove = remove;
43668cefec5SLiam R. Howlett 	vp->remove2 = remove2;
43768cefec5SLiam R. Howlett 	vp->adj_next = next;
43868cefec5SLiam R. Howlett 	if (!vp->anon_vma && next)
43968cefec5SLiam R. Howlett 		vp->anon_vma = next->anon_vma;
44068cefec5SLiam R. Howlett 
44168cefec5SLiam R. Howlett 	vp->file = vma->vm_file;
44268cefec5SLiam R. Howlett 	if (vp->file)
44368cefec5SLiam R. Howlett 		vp->mapping = vma->vm_file->f_mapping;
44468cefec5SLiam R. Howlett 
44568cefec5SLiam R. Howlett }
44668cefec5SLiam R. Howlett 
44768cefec5SLiam R. Howlett /*
44868cefec5SLiam R. Howlett  * init_vma_prep() - Initializer wrapper for vma_prepare struct
44968cefec5SLiam R. Howlett  * @vp: The vma_prepare struct
45068cefec5SLiam R. Howlett  * @vma: The vma that will be altered once locked
45168cefec5SLiam R. Howlett  */
init_vma_prep(struct vma_prepare * vp,struct vm_area_struct * vma)45268cefec5SLiam R. Howlett static inline void init_vma_prep(struct vma_prepare *vp,
45368cefec5SLiam R. Howlett 				 struct vm_area_struct *vma)
45468cefec5SLiam R. Howlett {
45568cefec5SLiam R. Howlett 	init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
45668cefec5SLiam R. Howlett }
45768cefec5SLiam R. Howlett 
45868cefec5SLiam R. Howlett 
45968cefec5SLiam R. Howlett /*
460440703e0SLiam R. Howlett  * vma_prepare() - Helper function for handling locking VMAs prior to altering
461440703e0SLiam R. Howlett  * @vp: The initialized vma_prepare struct
462440703e0SLiam R. Howlett  */
vma_prepare(struct vma_prepare * vp)463440703e0SLiam R. Howlett static inline void vma_prepare(struct vma_prepare *vp)
464440703e0SLiam R. Howlett {
465440703e0SLiam R. Howlett 	if (vp->file) {
466440703e0SLiam R. Howlett 		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
467440703e0SLiam R. Howlett 
468440703e0SLiam R. Howlett 		if (vp->adj_next)
469440703e0SLiam R. Howlett 			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
470440703e0SLiam R. Howlett 				      vp->adj_next->vm_end);
471440703e0SLiam R. Howlett 
472440703e0SLiam R. Howlett 		i_mmap_lock_write(vp->mapping);
473440703e0SLiam R. Howlett 		if (vp->insert && vp->insert->vm_file) {
474440703e0SLiam R. Howlett 			/*
475440703e0SLiam R. Howlett 			 * Put into interval tree now, so instantiated pages
476440703e0SLiam R. Howlett 			 * are visible to arm/parisc __flush_dcache_page
477440703e0SLiam R. Howlett 			 * throughout; but we cannot insert into address
478440703e0SLiam R. Howlett 			 * space until vma start or end is updated.
479440703e0SLiam R. Howlett 			 */
480440703e0SLiam R. Howlett 			__vma_link_file(vp->insert,
481440703e0SLiam R. Howlett 					vp->insert->vm_file->f_mapping);
482440703e0SLiam R. Howlett 		}
483440703e0SLiam R. Howlett 	}
484440703e0SLiam R. Howlett 
485440703e0SLiam R. Howlett 	if (vp->anon_vma) {
486440703e0SLiam R. Howlett 		anon_vma_lock_write(vp->anon_vma);
487440703e0SLiam R. Howlett 		anon_vma_interval_tree_pre_update_vma(vp->vma);
488440703e0SLiam R. Howlett 		if (vp->adj_next)
489440703e0SLiam R. Howlett 			anon_vma_interval_tree_pre_update_vma(vp->adj_next);
490440703e0SLiam R. Howlett 	}
491440703e0SLiam R. Howlett 
492440703e0SLiam R. Howlett 	if (vp->file) {
493440703e0SLiam R. Howlett 		flush_dcache_mmap_lock(vp->mapping);
494440703e0SLiam R. Howlett 		vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
495440703e0SLiam R. Howlett 		if (vp->adj_next)
496440703e0SLiam R. Howlett 			vma_interval_tree_remove(vp->adj_next,
497440703e0SLiam R. Howlett 						 &vp->mapping->i_mmap);
498440703e0SLiam R. Howlett 	}
499440703e0SLiam R. Howlett 
500440703e0SLiam R. Howlett }
501440703e0SLiam R. Howlett 
502440703e0SLiam R. Howlett /*
503440703e0SLiam R. Howlett  * vma_complete- Helper function for handling the unlocking after altering VMAs,
504440703e0SLiam R. Howlett  * or for inserting a VMA.
505440703e0SLiam R. Howlett  *
506440703e0SLiam R. Howlett  * @vp: The vma_prepare struct
507440703e0SLiam R. Howlett  * @vmi: The vma iterator
508440703e0SLiam R. Howlett  * @mm: The mm_struct
509440703e0SLiam R. Howlett  */
vma_complete(struct vma_prepare * vp,struct vma_iterator * vmi,struct mm_struct * mm)510440703e0SLiam R. Howlett static inline void vma_complete(struct vma_prepare *vp,
511440703e0SLiam R. Howlett 				struct vma_iterator *vmi, struct mm_struct *mm)
512440703e0SLiam R. Howlett {
513440703e0SLiam R. Howlett 	if (vp->file) {
514440703e0SLiam R. Howlett 		if (vp->adj_next)
515440703e0SLiam R. Howlett 			vma_interval_tree_insert(vp->adj_next,
516440703e0SLiam R. Howlett 						 &vp->mapping->i_mmap);
517440703e0SLiam R. Howlett 		vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
518440703e0SLiam R. Howlett 		flush_dcache_mmap_unlock(vp->mapping);
519440703e0SLiam R. Howlett 	}
520440703e0SLiam R. Howlett 
521440703e0SLiam R. Howlett 	if (vp->remove && vp->file) {
522440703e0SLiam R. Howlett 		__remove_shared_vm_struct(vp->remove, vp->file, vp->mapping);
523440703e0SLiam R. Howlett 		if (vp->remove2)
524440703e0SLiam R. Howlett 			__remove_shared_vm_struct(vp->remove2, vp->file,
525440703e0SLiam R. Howlett 						  vp->mapping);
526440703e0SLiam R. Howlett 	} else if (vp->insert) {
527440703e0SLiam R. Howlett 		/*
528440703e0SLiam R. Howlett 		 * split_vma has split insert from vma, and needs
529440703e0SLiam R. Howlett 		 * us to insert it before dropping the locks
530440703e0SLiam R. Howlett 		 * (it may either follow vma or precede it).
531440703e0SLiam R. Howlett 		 */
532440703e0SLiam R. Howlett 		vma_iter_store(vmi, vp->insert);
533440703e0SLiam R. Howlett 		mm->map_count++;
534440703e0SLiam R. Howlett 	}
535440703e0SLiam R. Howlett 
536440703e0SLiam R. Howlett 	if (vp->anon_vma) {
537440703e0SLiam R. Howlett 		anon_vma_interval_tree_post_update_vma(vp->vma);
538440703e0SLiam R. Howlett 		if (vp->adj_next)
539440703e0SLiam R. Howlett 			anon_vma_interval_tree_post_update_vma(vp->adj_next);
540440703e0SLiam R. Howlett 		anon_vma_unlock_write(vp->anon_vma);
541440703e0SLiam R. Howlett 	}
542440703e0SLiam R. Howlett 
543440703e0SLiam R. Howlett 	if (vp->file) {
544440703e0SLiam R. Howlett 		i_mmap_unlock_write(vp->mapping);
545440703e0SLiam R. Howlett 		uprobe_mmap(vp->vma);
546440703e0SLiam R. Howlett 
547440703e0SLiam R. Howlett 		if (vp->adj_next)
548440703e0SLiam R. Howlett 			uprobe_mmap(vp->adj_next);
549440703e0SLiam R. Howlett 	}
550440703e0SLiam R. Howlett 
551440703e0SLiam R. Howlett 	if (vp->remove) {
552440703e0SLiam R. Howlett again:
553457f67beSSuren Baghdasaryan 		vma_mark_detached(vp->remove, true);
554440703e0SLiam R. Howlett 		if (vp->file) {
555440703e0SLiam R. Howlett 			uprobe_munmap(vp->remove, vp->remove->vm_start,
556440703e0SLiam R. Howlett 				      vp->remove->vm_end);
557440703e0SLiam R. Howlett 			fput(vp->file);
558440703e0SLiam R. Howlett 		}
559440703e0SLiam R. Howlett 		if (vp->remove->anon_vma)
560440703e0SLiam R. Howlett 			anon_vma_merge(vp->vma, vp->remove);
561440703e0SLiam R. Howlett 		mm->map_count--;
562440703e0SLiam R. Howlett 		mpol_put(vma_policy(vp->remove));
563440703e0SLiam R. Howlett 		if (!vp->remove2)
564440703e0SLiam R. Howlett 			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
565440703e0SLiam R. Howlett 		vm_area_free(vp->remove);
566440703e0SLiam R. Howlett 
567440703e0SLiam R. Howlett 		/*
568440703e0SLiam R. Howlett 		 * In mprotect's case 6 (see comments on vma_merge),
5695ff783f1SVlastimil Babka 		 * we are removing both mid and next vmas
570440703e0SLiam R. Howlett 		 */
571440703e0SLiam R. Howlett 		if (vp->remove2) {
572440703e0SLiam R. Howlett 			vp->remove = vp->remove2;
573440703e0SLiam R. Howlett 			vp->remove2 = NULL;
574440703e0SLiam R. Howlett 			goto again;
575440703e0SLiam R. Howlett 		}
576440703e0SLiam R. Howlett 	}
577440703e0SLiam R. Howlett 	if (vp->insert && vp->file)
578440703e0SLiam R. Howlett 		uprobe_mmap(vp->insert);
5792574d5e4SLiam R. Howlett 	validate_mm(mm);
580440703e0SLiam R. Howlett }
581440703e0SLiam R. Howlett 
582440703e0SLiam R. Howlett /*
58304241ffeSLiam R. Howlett  * dup_anon_vma() - Helper function to duplicate anon_vma
58404241ffeSLiam R. Howlett  * @dst: The destination VMA
58504241ffeSLiam R. Howlett  * @src: The source VMA
586824135c4SLiam R. Howlett  * @dup: Pointer to the destination VMA when successful.
58704241ffeSLiam R. Howlett  *
58804241ffeSLiam R. Howlett  * Returns: 0 on success.
58904241ffeSLiam R. Howlett  */
dup_anon_vma(struct vm_area_struct * dst,struct vm_area_struct * src,struct vm_area_struct ** dup)59004241ffeSLiam R. Howlett static inline int dup_anon_vma(struct vm_area_struct *dst,
591824135c4SLiam R. Howlett 		struct vm_area_struct *src, struct vm_area_struct **dup)
59204241ffeSLiam R. Howlett {
59304241ffeSLiam R. Howlett 	/*
59404241ffeSLiam R. Howlett 	 * Easily overlooked: when mprotect shifts the boundary, make sure the
59504241ffeSLiam R. Howlett 	 * expanding vma has anon_vma set if the shrinking vma had, to cover any
59604241ffeSLiam R. Howlett 	 * anon pages imported.
59704241ffeSLiam R. Howlett 	 */
59804241ffeSLiam R. Howlett 	if (src->anon_vma && !dst->anon_vma) {
599824135c4SLiam R. Howlett 		int ret;
600824135c4SLiam R. Howlett 
601c9d6e982SSuren Baghdasaryan 		vma_assert_write_locked(dst);
60204241ffeSLiam R. Howlett 		dst->anon_vma = src->anon_vma;
603824135c4SLiam R. Howlett 		ret = anon_vma_clone(dst, src);
604824135c4SLiam R. Howlett 		if (ret)
605824135c4SLiam R. Howlett 			return ret;
606824135c4SLiam R. Howlett 
607824135c4SLiam R. Howlett 		*dup = dst;
60804241ffeSLiam R. Howlett 	}
60904241ffeSLiam R. Howlett 
61004241ffeSLiam R. Howlett 	return 0;
61104241ffeSLiam R. Howlett }
61204241ffeSLiam R. Howlett 
61304241ffeSLiam R. Howlett /*
6149303d3e1SLiam R. Howlett  * vma_expand - Expand an existing VMA
6159303d3e1SLiam R. Howlett  *
6169303d3e1SLiam R. Howlett  * @vmi: The vma iterator
6179303d3e1SLiam R. Howlett  * @vma: The vma to expand
6189303d3e1SLiam R. Howlett  * @start: The start of the vma
6199303d3e1SLiam R. Howlett  * @end: The exclusive end of the vma
6209303d3e1SLiam R. Howlett  * @pgoff: The page offset of vma
6219303d3e1SLiam R. Howlett  * @next: The current of next vma.
6229303d3e1SLiam R. Howlett  *
6239303d3e1SLiam R. Howlett  * Expand @vma to @start and @end.  Can expand off the start and end.  Will
6249303d3e1SLiam R. Howlett  * expand over @next if it's different from @vma and @end == @next->vm_end.
6259303d3e1SLiam R. Howlett  * Checking if the @vma can expand and merge with @next needs to be handled by
6269303d3e1SLiam R. Howlett  * the caller.
6279303d3e1SLiam R. Howlett  *
6289303d3e1SLiam R. Howlett  * Returns: 0 on success
6299303d3e1SLiam R. Howlett  */
vma_expand(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long start,unsigned long end,pgoff_t pgoff,struct vm_area_struct * next)6307c9813e8SLiam R. Howlett int vma_expand(struct vma_iterator *vmi, struct vm_area_struct *vma,
6319303d3e1SLiam R. Howlett 	       unsigned long start, unsigned long end, pgoff_t pgoff,
6329303d3e1SLiam R. Howlett 	       struct vm_area_struct *next)
6339303d3e1SLiam R. Howlett {
634824135c4SLiam R. Howlett 	struct vm_area_struct *anon_dup = NULL;
63568cefec5SLiam R. Howlett 	bool remove_next = false;
6369303d3e1SLiam R. Howlett 	struct vma_prepare vp;
6379303d3e1SLiam R. Howlett 
638c9d6e982SSuren Baghdasaryan 	vma_start_write(vma);
6399303d3e1SLiam R. Howlett 	if (next && (vma != next) && (end == next->vm_end)) {
64004241ffeSLiam R. Howlett 		int ret;
6419303d3e1SLiam R. Howlett 
64204241ffeSLiam R. Howlett 		remove_next = true;
643c9d6e982SSuren Baghdasaryan 		vma_start_write(next);
644824135c4SLiam R. Howlett 		ret = dup_anon_vma(vma, next, &anon_dup);
64504241ffeSLiam R. Howlett 		if (ret)
64604241ffeSLiam R. Howlett 			return ret;
6479303d3e1SLiam R. Howlett 	}
6489303d3e1SLiam R. Howlett 
64968cefec5SLiam R. Howlett 	init_multi_vma_prep(&vp, vma, NULL, remove_next ? next : NULL, NULL);
6509303d3e1SLiam R. Howlett 	/* Not merging but overwriting any part of next is not handled. */
6519303d3e1SLiam R. Howlett 	VM_WARN_ON(next && !vp.remove &&
6529303d3e1SLiam R. Howlett 		  next != vma && end > next->vm_start);
6539303d3e1SLiam R. Howlett 	/* Only handles expanding */
6549303d3e1SLiam R. Howlett 	VM_WARN_ON(vma->vm_start < start || vma->vm_end > end);
6559303d3e1SLiam R. Howlett 
656b5df0922SLiam R. Howlett 	/* Note: vma iterator must be pointing to 'start' */
657b5df0922SLiam R. Howlett 	vma_iter_config(vmi, start, end);
658b5df0922SLiam R. Howlett 	if (vma_iter_prealloc(vmi, vma))
6599303d3e1SLiam R. Howlett 		goto nomem;
6609303d3e1SLiam R. Howlett 
661ccf1d78dSSuren Baghdasaryan 	vma_prepare(&vp);
6629303d3e1SLiam R. Howlett 	vma_adjust_trans_huge(vma, start, end, 0);
6639303d3e1SLiam R. Howlett 	vma->vm_start = start;
6649303d3e1SLiam R. Howlett 	vma->vm_end = end;
6659303d3e1SLiam R. Howlett 	vma->vm_pgoff = pgoff;
6669303d3e1SLiam R. Howlett 	vma_iter_store(vmi, vma);
6679303d3e1SLiam R. Howlett 
6689303d3e1SLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
6699303d3e1SLiam R. Howlett 	return 0;
6709303d3e1SLiam R. Howlett 
6719303d3e1SLiam R. Howlett nomem:
672824135c4SLiam R. Howlett 	if (anon_dup)
673824135c4SLiam R. Howlett 		unlink_anon_vmas(anon_dup);
6749303d3e1SLiam R. Howlett 	return -ENOMEM;
6759303d3e1SLiam R. Howlett }
676cf51e86dSLiam R. Howlett 
677cf51e86dSLiam R. Howlett /*
678cf51e86dSLiam R. Howlett  * vma_shrink() - Reduce an existing VMAs memory area
679cf51e86dSLiam R. Howlett  * @vmi: The vma iterator
680cf51e86dSLiam R. Howlett  * @vma: The VMA to modify
681cf51e86dSLiam R. Howlett  * @start: The new start
682cf51e86dSLiam R. Howlett  * @end: The new end
683cf51e86dSLiam R. Howlett  *
684cf51e86dSLiam R. Howlett  * Returns: 0 on success, -ENOMEM otherwise
685cf51e86dSLiam R. Howlett  */
vma_shrink(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long start,unsigned long end,pgoff_t pgoff)686cf51e86dSLiam R. Howlett int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
687cf51e86dSLiam R. Howlett 	       unsigned long start, unsigned long end, pgoff_t pgoff)
688cf51e86dSLiam R. Howlett {
689cf51e86dSLiam R. Howlett 	struct vma_prepare vp;
690cf51e86dSLiam R. Howlett 
691cf51e86dSLiam R. Howlett 	WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
692cf51e86dSLiam R. Howlett 
693b5df0922SLiam R. Howlett 	if (vma->vm_start < start)
694b5df0922SLiam R. Howlett 		vma_iter_config(vmi, vma->vm_start, start);
695b5df0922SLiam R. Howlett 	else
696b5df0922SLiam R. Howlett 		vma_iter_config(vmi, end, vma->vm_end);
697b5df0922SLiam R. Howlett 
698b5df0922SLiam R. Howlett 	if (vma_iter_prealloc(vmi, NULL))
699cf51e86dSLiam R. Howlett 		return -ENOMEM;
700cf51e86dSLiam R. Howlett 
701c9d6e982SSuren Baghdasaryan 	vma_start_write(vma);
702c9d6e982SSuren Baghdasaryan 
703cf51e86dSLiam R. Howlett 	init_vma_prep(&vp, vma);
704cf51e86dSLiam R. Howlett 	vma_prepare(&vp);
705ccf1d78dSSuren Baghdasaryan 	vma_adjust_trans_huge(vma, start, end, 0);
706cf51e86dSLiam R. Howlett 
707b5df0922SLiam R. Howlett 	vma_iter_clear(vmi);
708cf51e86dSLiam R. Howlett 	vma->vm_start = start;
709cf51e86dSLiam R. Howlett 	vma->vm_end = end;
710cf51e86dSLiam R. Howlett 	vma->vm_pgoff = pgoff;
711cf51e86dSLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
712cf51e86dSLiam R. Howlett 	return 0;
713cf51e86dSLiam R. Howlett }
714cf51e86dSLiam R. Howlett 
7159303d3e1SLiam R. Howlett /*
7161da177e4SLinus Torvalds  * If the vma has a ->close operation then the driver probably needs to release
717714965caSVlastimil Babka  * per-vma resources, so we don't attempt to merge those if the caller indicates
718714965caSVlastimil Babka  * the current vma may be removed as part of the merge.
7191da177e4SLinus Torvalds  */
is_mergeable_vma(struct vm_area_struct * vma,struct file * file,unsigned long vm_flags,struct vm_userfaultfd_ctx vm_userfaultfd_ctx,struct anon_vma_name * anon_name,bool may_remove_vma)7202dbf4010SVlastimil Babka static inline bool is_mergeable_vma(struct vm_area_struct *vma,
72119a809afSAndrea Arcangeli 		struct file *file, unsigned long vm_flags,
7229a10064fSColin Cross 		struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
723714965caSVlastimil Babka 		struct anon_vma_name *anon_name, bool may_remove_vma)
7241da177e4SLinus Torvalds {
72534228d47SCyrill Gorcunov 	/*
72634228d47SCyrill Gorcunov 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
72734228d47SCyrill Gorcunov 	 * match the flags but dirty bit -- the caller should mark
72834228d47SCyrill Gorcunov 	 * merged VMA as dirty. If dirty bit won't be excluded from
7298bb4e7a2SWei Yang 	 * comparison, we increase pressure on the memory system forcing
73034228d47SCyrill Gorcunov 	 * the kernel to generate new VMAs when old one could be
73134228d47SCyrill Gorcunov 	 * extended instead.
73234228d47SCyrill Gorcunov 	 */
73334228d47SCyrill Gorcunov 	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
7342dbf4010SVlastimil Babka 		return false;
7351da177e4SLinus Torvalds 	if (vma->vm_file != file)
7362dbf4010SVlastimil Babka 		return false;
737714965caSVlastimil Babka 	if (may_remove_vma && vma->vm_ops && vma->vm_ops->close)
7382dbf4010SVlastimil Babka 		return false;
73919a809afSAndrea Arcangeli 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
7402dbf4010SVlastimil Babka 		return false;
7415c26f6acSSuren Baghdasaryan 	if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
7422dbf4010SVlastimil Babka 		return false;
7432dbf4010SVlastimil Babka 	return true;
7441da177e4SLinus Torvalds }
7451da177e4SLinus Torvalds 
is_mergeable_anon_vma(struct anon_vma * anon_vma1,struct anon_vma * anon_vma2,struct vm_area_struct * vma)7462dbf4010SVlastimil Babka static inline bool is_mergeable_anon_vma(struct anon_vma *anon_vma1,
7472dbf4010SVlastimil Babka 		 struct anon_vma *anon_vma2, struct vm_area_struct *vma)
7481da177e4SLinus Torvalds {
749965f55deSShaohua Li 	/*
750965f55deSShaohua Li 	 * The list_is_singular() test is to avoid merging VMA cloned from
751965f55deSShaohua Li 	 * parents. This can improve scalability caused by anon_vma lock.
752965f55deSShaohua Li 	 */
753965f55deSShaohua Li 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
754965f55deSShaohua Li 		list_is_singular(&vma->anon_vma_chain)))
7552dbf4010SVlastimil Babka 		return true;
756965f55deSShaohua Li 	return anon_vma1 == anon_vma2;
7571da177e4SLinus Torvalds }
7581da177e4SLinus Torvalds 
7591da177e4SLinus Torvalds /*
7601da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
7611da177e4SLinus Torvalds  * in front of (at a lower virtual address and file offset than) the vma.
7621da177e4SLinus Torvalds  *
7631da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
7641da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
7651da177e4SLinus Torvalds  *
7661da177e4SLinus Torvalds  * We don't check here for the merged mmap wrapping around the end of pagecache
76745e55300SPeter Collingbourne  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
7681da177e4SLinus Torvalds  * wrap, nor mmaps which cover the final page at index -1UL.
769714965caSVlastimil Babka  *
770714965caSVlastimil Babka  * We assume the vma may be removed as part of the merge.
7711da177e4SLinus Torvalds  */
7722dbf4010SVlastimil Babka static bool
can_vma_merge_before(struct vm_area_struct * vma,unsigned long vm_flags,struct anon_vma * anon_vma,struct file * file,pgoff_t vm_pgoff,struct vm_userfaultfd_ctx vm_userfaultfd_ctx,struct anon_vma_name * anon_name)7731da177e4SLinus Torvalds can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
77419a809afSAndrea Arcangeli 		struct anon_vma *anon_vma, struct file *file,
7752dbf4010SVlastimil Babka 		pgoff_t vm_pgoff, struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
7765c26f6acSSuren Baghdasaryan 		struct anon_vma_name *anon_name)
7771da177e4SLinus Torvalds {
778714965caSVlastimil Babka 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name, true) &&
779965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
7801da177e4SLinus Torvalds 		if (vma->vm_pgoff == vm_pgoff)
7812dbf4010SVlastimil Babka 			return true;
7821da177e4SLinus Torvalds 	}
7832dbf4010SVlastimil Babka 	return false;
7841da177e4SLinus Torvalds }
7851da177e4SLinus Torvalds 
7861da177e4SLinus Torvalds /*
7871da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
7881da177e4SLinus Torvalds  * beyond (at a higher virtual address and file offset than) the vma.
7891da177e4SLinus Torvalds  *
7901da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
7911da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
792714965caSVlastimil Babka  *
793714965caSVlastimil Babka  * We assume that vma is not removed as part of the merge.
7941da177e4SLinus Torvalds  */
7952dbf4010SVlastimil Babka static bool
can_vma_merge_after(struct vm_area_struct * vma,unsigned long vm_flags,struct anon_vma * anon_vma,struct file * file,pgoff_t vm_pgoff,struct vm_userfaultfd_ctx vm_userfaultfd_ctx,struct anon_vma_name * anon_name)7961da177e4SLinus Torvalds can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
79719a809afSAndrea Arcangeli 		struct anon_vma *anon_vma, struct file *file,
7982dbf4010SVlastimil Babka 		pgoff_t vm_pgoff, struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
7995c26f6acSSuren Baghdasaryan 		struct anon_vma_name *anon_name)
8001da177e4SLinus Torvalds {
801714965caSVlastimil Babka 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name, false) &&
802965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
8031da177e4SLinus Torvalds 		pgoff_t vm_pglen;
804d6e93217SLibin 		vm_pglen = vma_pages(vma);
8051da177e4SLinus Torvalds 		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
8062dbf4010SVlastimil Babka 			return true;
8071da177e4SLinus Torvalds 	}
8082dbf4010SVlastimil Babka 	return false;
8091da177e4SLinus Torvalds }
8101da177e4SLinus Torvalds 
8111da177e4SLinus Torvalds /*
8129a10064fSColin Cross  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
8139a10064fSColin Cross  * figure out whether that can be merged with its predecessor or its
8149a10064fSColin Cross  * successor.  Or both (it neatly fills a hole).
8151da177e4SLinus Torvalds  *
8161da177e4SLinus Torvalds  * In most cases - when called for mmap, brk or mremap - [addr,end) is
8171da177e4SLinus Torvalds  * certain not to be mapped by the time vma_merge is called; but when
8181da177e4SLinus Torvalds  * called for mprotect, it is certain to be already mapped (either at
8191da177e4SLinus Torvalds  * an offset within prev, or at the start of next), and the flags of
8201da177e4SLinus Torvalds  * this area are about to be changed to vm_flags - and the no-change
8211da177e4SLinus Torvalds  * case has already been eliminated.
8221da177e4SLinus Torvalds  *
823fcfccd91SLorenzo Stoakes  * The following mprotect cases have to be considered, where **** is
8241da177e4SLinus Torvalds  * the area passed down from mprotect_fixup, never extending beyond one
825fcfccd91SLorenzo Stoakes  * vma, PPPP is the previous vma, CCCC is a concurrent vma that starts
826fcfccd91SLorenzo Stoakes  * at the same address as **** and is of the same or larger span, and
827fcfccd91SLorenzo Stoakes  * NNNN the next vma after ****:
8281da177e4SLinus Torvalds  *
829fcfccd91SLorenzo Stoakes  *     ****             ****                   ****
830fcfccd91SLorenzo Stoakes  *    PPPPPPNNNNNN    PPPPPPNNNNNN       PPPPPPCCCCCC
8315d42ab29SWei Yang  *    cannot merge    might become       might become
832fcfccd91SLorenzo Stoakes  *                    PPNNNNNNNNNN       PPPPPPPPPPCC
8335d42ab29SWei Yang  *    mmap, brk or    case 4 below       case 5 below
8345d42ab29SWei Yang  *    mremap move:
835fcfccd91SLorenzo Stoakes  *                        ****               ****
836fcfccd91SLorenzo Stoakes  *                    PPPP    NNNN       PPPPCCCCNNNN
8375d42ab29SWei Yang  *                    might become       might become
8385d42ab29SWei Yang  *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
839fcfccd91SLorenzo Stoakes  *                    PPPPPPPPNNNN 2 or  PPPPPPPPNNNN 7 or
840fcfccd91SLorenzo Stoakes  *                    PPPPNNNNNNNN 3     PPPPNNNNNNNN 8
8411da177e4SLinus Torvalds  *
842fcfccd91SLorenzo Stoakes  * It is important for case 8 that the vma CCCC overlapping the
843fcfccd91SLorenzo Stoakes  * region **** is never going to extended over NNNN. Instead NNNN must
844fcfccd91SLorenzo Stoakes  * be extended in region **** and CCCC must be removed. This way in
8450503ea8fSLiam R. Howlett  * all cases where vma_merge succeeds, the moment vma_merge drops the
846e86f15eeSAndrea Arcangeli  * rmap_locks, the properties of the merged vma will be already
847e86f15eeSAndrea Arcangeli  * correct for the whole merged range. Some of those properties like
848e86f15eeSAndrea Arcangeli  * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
849e86f15eeSAndrea Arcangeli  * be correct for the whole merged range immediately after the
850fcfccd91SLorenzo Stoakes  * rmap_locks are released. Otherwise if NNNN would be removed and
851fcfccd91SLorenzo Stoakes  * CCCC would be extended over the NNNN range, remove_migration_ptes
852e86f15eeSAndrea Arcangeli  * or other rmap walkers (if working on addresses beyond the "end"
853fcfccd91SLorenzo Stoakes  * parameter) may establish ptes with the wrong permissions of CCCC
854fcfccd91SLorenzo Stoakes  * instead of the right permissions of NNNN.
8550503ea8fSLiam R. Howlett  *
8560503ea8fSLiam R. Howlett  * In the code below:
8570503ea8fSLiam R. Howlett  * PPPP is represented by *prev
858fcfccd91SLorenzo Stoakes  * CCCC is represented by *curr or not represented at all (NULL)
859fcfccd91SLorenzo Stoakes  * NNNN is represented by *next or not represented at all (NULL)
860fcfccd91SLorenzo Stoakes  * **** is not represented - it will be merged and the vma containing the
8619e8a39d2SVlastimil Babka  *      area is returned, or the function will return NULL
8621da177e4SLinus Torvalds  */
vma_merge(struct vma_iterator * vmi,struct mm_struct * mm,struct vm_area_struct * prev,unsigned long addr,unsigned long end,unsigned long vm_flags,struct anon_vma * anon_vma,struct file * file,pgoff_t pgoff,struct mempolicy * policy,struct vm_userfaultfd_ctx vm_userfaultfd_ctx,struct anon_vma_name * anon_name)8639760ebffSLiam R. Howlett struct vm_area_struct *vma_merge(struct vma_iterator *vmi, struct mm_struct *mm,
8641da177e4SLinus Torvalds 			struct vm_area_struct *prev, unsigned long addr,
8651da177e4SLinus Torvalds 			unsigned long end, unsigned long vm_flags,
8661da177e4SLinus Torvalds 			struct anon_vma *anon_vma, struct file *file,
86719a809afSAndrea Arcangeli 			pgoff_t pgoff, struct mempolicy *policy,
8689a10064fSColin Cross 			struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
8695c26f6acSSuren Baghdasaryan 			struct anon_vma_name *anon_name)
8701da177e4SLinus Torvalds {
871b0729ae0SLorenzo Stoakes 	struct vm_area_struct *curr, *next, *res;
8720503ea8fSLiam R. Howlett 	struct vm_area_struct *vma, *adjust, *remove, *remove2;
873824135c4SLiam R. Howlett 	struct vm_area_struct *anon_dup = NULL;
8740173db4fSLorenzo Stoakes 	struct vma_prepare vp;
8750173db4fSLorenzo Stoakes 	pgoff_t vma_pgoff;
8760173db4fSLorenzo Stoakes 	int err = 0;
877eef19944SJakub Matěna 	bool merge_prev = false;
878eef19944SJakub Matěna 	bool merge_next = false;
8790503ea8fSLiam R. Howlett 	bool vma_expanded = false;
8800503ea8fSLiam R. Howlett 	unsigned long vma_start = addr;
8810173db4fSLorenzo Stoakes 	unsigned long vma_end = end;
8820173db4fSLorenzo Stoakes 	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
8830173db4fSLorenzo Stoakes 	long adj_start = 0;
8841da177e4SLinus Torvalds 
8851da177e4SLinus Torvalds 	/*
8861da177e4SLinus Torvalds 	 * We later require that vma->vm_flags == vm_flags,
8871da177e4SLinus Torvalds 	 * so this tests vma->vm_flags & VM_SPECIAL, too.
8881da177e4SLinus Torvalds 	 */
8891da177e4SLinus Torvalds 	if (vm_flags & VM_SPECIAL)
8901da177e4SLinus Torvalds 		return NULL;
8911da177e4SLinus Torvalds 
89200cd00a6SLorenzo Stoakes 	/* Does the input range span an existing VMA? (cases 5 - 8) */
89300cd00a6SLorenzo Stoakes 	curr = find_vma_intersection(mm, prev ? prev->vm_end : 0, end);
8941da177e4SLinus Torvalds 
89500cd00a6SLorenzo Stoakes 	if (!curr ||			/* cases 1 - 4 */
89600cd00a6SLorenzo Stoakes 	    end == curr->vm_end)	/* cases 6 - 8, adjacent VMA */
89700cd00a6SLorenzo Stoakes 		next = vma_lookup(mm, end);
89800cd00a6SLorenzo Stoakes 	else
89900cd00a6SLorenzo Stoakes 		next = NULL;		/* case 5 */
900e86f15eeSAndrea Arcangeli 
9010503ea8fSLiam R. Howlett 	if (prev) {
9020503ea8fSLiam R. Howlett 		vma_start = prev->vm_start;
9030503ea8fSLiam R. Howlett 		vma_pgoff = prev->vm_pgoff;
9040173db4fSLorenzo Stoakes 
905eef19944SJakub Matěna 		/* Can we merge the predecessor? */
9060173db4fSLorenzo Stoakes 		if (addr == prev->vm_end && mpol_equal(vma_policy(prev), policy)
9070503ea8fSLiam R. Howlett 		    && can_vma_merge_after(prev, vm_flags, anon_vma, file,
9080503ea8fSLiam R. Howlett 					   pgoff, vm_userfaultfd_ctx, anon_name)) {
909eef19944SJakub Matěna 			merge_prev = true;
91018b098afSLiam R. Howlett 			vma_prev(vmi);
9111da177e4SLinus Torvalds 		}
9120503ea8fSLiam R. Howlett 	}
913b0729ae0SLorenzo Stoakes 
914eef19944SJakub Matěna 	/* Can we merge the successor? */
91500cd00a6SLorenzo Stoakes 	if (next && mpol_equal(policy, vma_policy(next)) &&
9160173db4fSLorenzo Stoakes 	    can_vma_merge_before(next, vm_flags, anon_vma, file, pgoff+pglen,
9179a10064fSColin Cross 				 vm_userfaultfd_ctx, anon_name)) {
918eef19944SJakub Matěna 		merge_next = true;
919eef19944SJakub Matěna 	}
9200503ea8fSLiam R. Howlett 
92129417d29SLorenzo Stoakes 	/* Verify some invariant that must be enforced by the caller. */
92229417d29SLorenzo Stoakes 	VM_WARN_ON(prev && addr <= prev->vm_start);
92329417d29SLorenzo Stoakes 	VM_WARN_ON(curr && (addr != curr->vm_start || end > curr->vm_end));
92429417d29SLorenzo Stoakes 	VM_WARN_ON(addr >= end);
92529417d29SLorenzo Stoakes 
9260173db4fSLorenzo Stoakes 	if (!merge_prev && !merge_next)
9270173db4fSLorenzo Stoakes 		return NULL; /* Not mergeable. */
9280173db4fSLorenzo Stoakes 
929c9d6e982SSuren Baghdasaryan 	if (merge_prev)
930c9d6e982SSuren Baghdasaryan 		vma_start_write(prev);
931c9d6e982SSuren Baghdasaryan 
9320173db4fSLorenzo Stoakes 	res = vma = prev;
9330503ea8fSLiam R. Howlett 	remove = remove2 = adjust = NULL;
9340173db4fSLorenzo Stoakes 
935eef19944SJakub Matěna 	/* Can we merge both the predecessor and the successor? */
936eef19944SJakub Matěna 	if (merge_prev && merge_next &&
9370503ea8fSLiam R. Howlett 	    is_mergeable_anon_vma(prev->anon_vma, next->anon_vma, NULL)) {
938c9d6e982SSuren Baghdasaryan 		vma_start_write(next);
9395ff783f1SVlastimil Babka 		remove = next;				/* case 1 */
9400503ea8fSLiam R. Howlett 		vma_end = next->vm_end;
941824135c4SLiam R. Howlett 		err = dup_anon_vma(prev, next, &anon_dup);
942fcfccd91SLorenzo Stoakes 		if (curr) {				/* case 6 */
943c9d6e982SSuren Baghdasaryan 			vma_start_write(curr);
944fcfccd91SLorenzo Stoakes 			remove = curr;
9450503ea8fSLiam R. Howlett 			remove2 = next;
9465ff783f1SVlastimil Babka 			if (!next->anon_vma)
947824135c4SLiam R. Howlett 				err = dup_anon_vma(prev, curr, &anon_dup);
9480503ea8fSLiam R. Howlett 		}
9490173db4fSLorenzo Stoakes 	} else if (merge_prev) {			/* case 2 */
950fcfccd91SLorenzo Stoakes 		if (curr) {
951c9d6e982SSuren Baghdasaryan 			vma_start_write(curr);
952fcfccd91SLorenzo Stoakes 			if (end == curr->vm_end) {	/* case 7 */
953b9349432SVlastimil Babka 				/*
954b9349432SVlastimil Babka 				 * can_vma_merge_after() assumed we would not be
955b9349432SVlastimil Babka 				 * removing prev vma, so it skipped the check
956b9349432SVlastimil Babka 				 * for vm_ops->close, but we are removing curr
957b9349432SVlastimil Babka 				 */
958b9349432SVlastimil Babka 				if (curr->vm_ops && curr->vm_ops->close)
959b9349432SVlastimil Babka 					err = -EINVAL;
960fcfccd91SLorenzo Stoakes 				remove = curr;
9610503ea8fSLiam R. Howlett 			} else {			/* case 5 */
962fcfccd91SLorenzo Stoakes 				adjust = curr;
963fcfccd91SLorenzo Stoakes 				adj_start = (end - curr->vm_start);
9640503ea8fSLiam R. Howlett 			}
965b9349432SVlastimil Babka 			if (!err)
966b9349432SVlastimil Babka 				err = dup_anon_vma(prev, curr, &anon_dup);
9670503ea8fSLiam R. Howlett 		}
9680173db4fSLorenzo Stoakes 	} else { /* merge_next */
969c9d6e982SSuren Baghdasaryan 		vma_start_write(next);
970eef19944SJakub Matěna 		res = next;
9710503ea8fSLiam R. Howlett 		if (prev && addr < prev->vm_end) {	/* case 4 */
972c9d6e982SSuren Baghdasaryan 			vma_start_write(prev);
9730503ea8fSLiam R. Howlett 			vma_end = addr;
974183b7a60SVlastimil Babka 			adjust = next;
9751e76454fSVlastimil Babka 			adj_start = -(prev->vm_end - addr);
976824135c4SLiam R. Howlett 			err = dup_anon_vma(next, prev, &anon_dup);
9770503ea8fSLiam R. Howlett 		} else {
978b0729ae0SLorenzo Stoakes 			/*
979b0729ae0SLorenzo Stoakes 			 * Note that cases 3 and 8 are the ONLY ones where prev
980b0729ae0SLorenzo Stoakes 			 * is permitted to be (but is not necessarily) NULL.
981b0729ae0SLorenzo Stoakes 			 */
9820503ea8fSLiam R. Howlett 			vma = next;			/* case 3 */
9830503ea8fSLiam R. Howlett 			vma_start = addr;
9840503ea8fSLiam R. Howlett 			vma_end = next->vm_end;
9857e775787SVlastimil Babka 			vma_pgoff = next->vm_pgoff - pglen;
986fcfccd91SLorenzo Stoakes 			if (curr) {			/* case 8 */
987fcfccd91SLorenzo Stoakes 				vma_pgoff = curr->vm_pgoff;
988c9d6e982SSuren Baghdasaryan 				vma_start_write(curr);
989fcfccd91SLorenzo Stoakes 				remove = curr;
990824135c4SLiam R. Howlett 				err = dup_anon_vma(next, curr, &anon_dup);
9910503ea8fSLiam R. Howlett 			}
9920503ea8fSLiam R. Howlett 		}
9931da177e4SLinus Torvalds 	}
9941da177e4SLinus Torvalds 
9950173db4fSLorenzo Stoakes 	/* Error in anon_vma clone. */
996eef19944SJakub Matěna 	if (err)
9971419430cSLiam R. Howlett 		goto anon_vma_fail;
9980503ea8fSLiam R. Howlett 
999b5df0922SLiam R. Howlett 	if (vma_start < vma->vm_start || vma_end > vma->vm_end)
1000b5df0922SLiam R. Howlett 		vma_expanded = true;
1001b5df0922SLiam R. Howlett 
1002b5df0922SLiam R. Howlett 	if (vma_expanded) {
1003b5df0922SLiam R. Howlett 		vma_iter_config(vmi, vma_start, vma_end);
1004b5df0922SLiam R. Howlett 	} else {
1005b5df0922SLiam R. Howlett 		vma_iter_config(vmi, adjust->vm_start + adj_start,
1006b5df0922SLiam R. Howlett 				adjust->vm_end);
1007b5df0922SLiam R. Howlett 	}
1008b5df0922SLiam R. Howlett 
1009b5df0922SLiam R. Howlett 	if (vma_iter_prealloc(vmi, vma))
10101419430cSLiam R. Howlett 		goto prealloc_fail;
10110503ea8fSLiam R. Howlett 
10120503ea8fSLiam R. Howlett 	init_multi_vma_prep(&vp, vma, adjust, remove, remove2);
10130503ea8fSLiam R. Howlett 	VM_WARN_ON(vp.anon_vma && adjust && adjust->anon_vma &&
10140503ea8fSLiam R. Howlett 		   vp.anon_vma != adjust->anon_vma);
10150503ea8fSLiam R. Howlett 
10160503ea8fSLiam R. Howlett 	vma_prepare(&vp);
1017ccf1d78dSSuren Baghdasaryan 	vma_adjust_trans_huge(vma, vma_start, vma_end, adj_start);
10180503ea8fSLiam R. Howlett 
10190503ea8fSLiam R. Howlett 	vma->vm_start = vma_start;
10200503ea8fSLiam R. Howlett 	vma->vm_end = vma_end;
10210503ea8fSLiam R. Howlett 	vma->vm_pgoff = vma_pgoff;
10220503ea8fSLiam R. Howlett 
10230503ea8fSLiam R. Howlett 	if (vma_expanded)
10240503ea8fSLiam R. Howlett 		vma_iter_store(vmi, vma);
10250503ea8fSLiam R. Howlett 
10261e76454fSVlastimil Babka 	if (adj_start) {
10271e76454fSVlastimil Babka 		adjust->vm_start += adj_start;
10281e76454fSVlastimil Babka 		adjust->vm_pgoff += adj_start >> PAGE_SHIFT;
10291e76454fSVlastimil Babka 		if (adj_start < 0) {
10300503ea8fSLiam R. Howlett 			WARN_ON(vma_expanded);
10310503ea8fSLiam R. Howlett 			vma_iter_store(vmi, next);
10320503ea8fSLiam R. Howlett 		}
10330503ea8fSLiam R. Howlett 	}
10340503ea8fSLiam R. Howlett 
10350503ea8fSLiam R. Howlett 	vma_complete(&vp, vmi, mm);
1036eef19944SJakub Matěna 	khugepaged_enter_vma(res, vm_flags);
10379760ebffSLiam R. Howlett 	return res;
10381419430cSLiam R. Howlett 
10391419430cSLiam R. Howlett prealloc_fail:
1040824135c4SLiam R. Howlett 	if (anon_dup)
1041824135c4SLiam R. Howlett 		unlink_anon_vmas(anon_dup);
1042824135c4SLiam R. Howlett 
10431419430cSLiam R. Howlett anon_vma_fail:
10441419430cSLiam R. Howlett 	vma_iter_set(vmi, addr);
10451419430cSLiam R. Howlett 	vma_iter_load(vmi);
10461419430cSLiam R. Howlett 	return NULL;
1047f2ebfe43SLiam R. Howlett }
1048f2ebfe43SLiam R. Howlett 
10491da177e4SLinus Torvalds /*
1050b4f315b4SEthon Paul  * Rough compatibility check to quickly see if it's even worth looking
1051d0e9fe17SLinus Torvalds  * at sharing an anon_vma.
1052d0e9fe17SLinus Torvalds  *
1053d0e9fe17SLinus Torvalds  * They need to have the same vm_file, and the flags can only differ
1054d0e9fe17SLinus Torvalds  * in things that mprotect may change.
1055d0e9fe17SLinus Torvalds  *
1056d0e9fe17SLinus Torvalds  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1057d0e9fe17SLinus Torvalds  * we can merge the two vma's. For example, we refuse to merge a vma if
1058d0e9fe17SLinus Torvalds  * there is a vm_ops->close() function, because that indicates that the
1059d0e9fe17SLinus Torvalds  * driver is doing some kind of reference counting. But that doesn't
1060d0e9fe17SLinus Torvalds  * really matter for the anon_vma sharing case.
1061d0e9fe17SLinus Torvalds  */
anon_vma_compatible(struct vm_area_struct * a,struct vm_area_struct * b)1062d0e9fe17SLinus Torvalds static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1063d0e9fe17SLinus Torvalds {
1064d0e9fe17SLinus Torvalds 	return a->vm_end == b->vm_start &&
1065d0e9fe17SLinus Torvalds 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1066d0e9fe17SLinus Torvalds 		a->vm_file == b->vm_file &&
10676cb4d9a2SAnshuman Khandual 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1068d0e9fe17SLinus Torvalds 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1069d0e9fe17SLinus Torvalds }
1070d0e9fe17SLinus Torvalds 
1071d0e9fe17SLinus Torvalds /*
1072d0e9fe17SLinus Torvalds  * Do some basic sanity checking to see if we can re-use the anon_vma
1073d0e9fe17SLinus Torvalds  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1074d0e9fe17SLinus Torvalds  * the same as 'old', the other will be the new one that is trying
1075d0e9fe17SLinus Torvalds  * to share the anon_vma.
1076d0e9fe17SLinus Torvalds  *
10775b449489SFlorian Rommel  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1078d0e9fe17SLinus Torvalds  * the anon_vma of 'old' is concurrently in the process of being set up
1079d0e9fe17SLinus Torvalds  * by another page fault trying to merge _that_. But that's ok: if it
1080d0e9fe17SLinus Torvalds  * is being set up, that automatically means that it will be a singleton
1081d0e9fe17SLinus Torvalds  * acceptable for merging, so we can do all of this optimistically. But
10824db0c3c2SJason Low  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1083d0e9fe17SLinus Torvalds  *
1084d0e9fe17SLinus Torvalds  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1085d0e9fe17SLinus Torvalds  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1086d0e9fe17SLinus Torvalds  * is to return an anon_vma that is "complex" due to having gone through
1087d0e9fe17SLinus Torvalds  * a fork).
1088d0e9fe17SLinus Torvalds  *
1089d0e9fe17SLinus Torvalds  * We also make sure that the two vma's are compatible (adjacent,
1090d0e9fe17SLinus Torvalds  * and with the same memory policies). That's all stable, even with just
10915b449489SFlorian Rommel  * a read lock on the mmap_lock.
1092d0e9fe17SLinus Torvalds  */
reusable_anon_vma(struct vm_area_struct * old,struct vm_area_struct * a,struct vm_area_struct * b)1093d0e9fe17SLinus Torvalds static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1094d0e9fe17SLinus Torvalds {
1095d0e9fe17SLinus Torvalds 	if (anon_vma_compatible(a, b)) {
10964db0c3c2SJason Low 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1097d0e9fe17SLinus Torvalds 
1098d0e9fe17SLinus Torvalds 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1099d0e9fe17SLinus Torvalds 			return anon_vma;
1100d0e9fe17SLinus Torvalds 	}
1101d0e9fe17SLinus Torvalds 	return NULL;
1102d0e9fe17SLinus Torvalds }
1103d0e9fe17SLinus Torvalds 
1104d0e9fe17SLinus Torvalds /*
11051da177e4SLinus Torvalds  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
11061da177e4SLinus Torvalds  * neighbouring vmas for a suitable anon_vma, before it goes off
11071da177e4SLinus Torvalds  * to allocate a new anon_vma.  It checks because a repetitive
11081da177e4SLinus Torvalds  * sequence of mprotects and faults may otherwise lead to distinct
11091da177e4SLinus Torvalds  * anon_vmas being allocated, preventing vma merge in subsequent
11101da177e4SLinus Torvalds  * mprotect.
11111da177e4SLinus Torvalds  */
find_mergeable_anon_vma(struct vm_area_struct * vma)11121da177e4SLinus Torvalds struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
11131da177e4SLinus Torvalds {
1114763ecb03SLiam R. Howlett 	MA_STATE(mas, &vma->vm_mm->mm_mt, vma->vm_end, vma->vm_end);
1115a67c8caaSMiaohe Lin 	struct anon_vma *anon_vma = NULL;
1116763ecb03SLiam R. Howlett 	struct vm_area_struct *prev, *next;
11171da177e4SLinus Torvalds 
1118a67c8caaSMiaohe Lin 	/* Try next first. */
1119763ecb03SLiam R. Howlett 	next = mas_walk(&mas);
1120763ecb03SLiam R. Howlett 	if (next) {
1121763ecb03SLiam R. Howlett 		anon_vma = reusable_anon_vma(next, vma, next);
1122d0e9fe17SLinus Torvalds 		if (anon_vma)
1123d0e9fe17SLinus Torvalds 			return anon_vma;
1124a67c8caaSMiaohe Lin 	}
11251da177e4SLinus Torvalds 
1126763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
1127763ecb03SLiam R. Howlett 	VM_BUG_ON_VMA(prev != vma, vma);
1128763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
1129a67c8caaSMiaohe Lin 	/* Try prev next. */
1130763ecb03SLiam R. Howlett 	if (prev)
1131763ecb03SLiam R. Howlett 		anon_vma = reusable_anon_vma(prev, prev, vma);
1132a67c8caaSMiaohe Lin 
11331da177e4SLinus Torvalds 	/*
1134a67c8caaSMiaohe Lin 	 * We might reach here with anon_vma == NULL if we can't find
1135a67c8caaSMiaohe Lin 	 * any reusable anon_vma.
11361da177e4SLinus Torvalds 	 * There's no absolute need to look only at touching neighbours:
11371da177e4SLinus Torvalds 	 * we could search further afield for "compatible" anon_vmas.
11381da177e4SLinus Torvalds 	 * But it would probably just be a waste of time searching,
11391da177e4SLinus Torvalds 	 * or lead to too many vmas hanging off the same anon_vma.
11401da177e4SLinus Torvalds 	 * We're trying to allow mprotect remerging later on,
11411da177e4SLinus Torvalds 	 * not trying to minimize memory used for anon_vmas.
11421da177e4SLinus Torvalds 	 */
1143a67c8caaSMiaohe Lin 	return anon_vma;
11441da177e4SLinus Torvalds }
11451da177e4SLinus Torvalds 
11461da177e4SLinus Torvalds /*
114740401530SAl Viro  * If a hint addr is less than mmap_min_addr change hint to be as
114840401530SAl Viro  * low as possible but still greater than mmap_min_addr
114940401530SAl Viro  */
round_hint_to_min(unsigned long hint)115040401530SAl Viro static inline unsigned long round_hint_to_min(unsigned long hint)
115140401530SAl Viro {
115240401530SAl Viro 	hint &= PAGE_MASK;
115340401530SAl Viro 	if (((void *)hint != NULL) &&
115440401530SAl Viro 	    (hint < mmap_min_addr))
115540401530SAl Viro 		return PAGE_ALIGN(mmap_min_addr);
115640401530SAl Viro 	return hint;
115740401530SAl Viro }
115840401530SAl Viro 
mlock_future_ok(struct mm_struct * mm,unsigned long flags,unsigned long bytes)1159b0cc5e89SAndrew Morton bool mlock_future_ok(struct mm_struct *mm, unsigned long flags,
11603c54a298SLorenzo Stoakes 			unsigned long bytes)
1161363ee17fSDavidlohr Bueso {
11623c54a298SLorenzo Stoakes 	unsigned long locked_pages, limit_pages;
1163363ee17fSDavidlohr Bueso 
11643c54a298SLorenzo Stoakes 	if (!(flags & VM_LOCKED) || capable(CAP_IPC_LOCK))
11653c54a298SLorenzo Stoakes 		return true;
11663c54a298SLorenzo Stoakes 
11673c54a298SLorenzo Stoakes 	locked_pages = bytes >> PAGE_SHIFT;
11683c54a298SLorenzo Stoakes 	locked_pages += mm->locked_vm;
11693c54a298SLorenzo Stoakes 
11703c54a298SLorenzo Stoakes 	limit_pages = rlimit(RLIMIT_MEMLOCK);
11713c54a298SLorenzo Stoakes 	limit_pages >>= PAGE_SHIFT;
11723c54a298SLorenzo Stoakes 
11733c54a298SLorenzo Stoakes 	return locked_pages <= limit_pages;
1174363ee17fSDavidlohr Bueso }
1175363ee17fSDavidlohr Bueso 
file_mmap_size_max(struct file * file,struct inode * inode)1176be83bbf8SLinus Torvalds static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1177be83bbf8SLinus Torvalds {
1178be83bbf8SLinus Torvalds 	if (S_ISREG(inode->i_mode))
1179423913adSLinus Torvalds 		return MAX_LFS_FILESIZE;
1180be83bbf8SLinus Torvalds 
1181be83bbf8SLinus Torvalds 	if (S_ISBLK(inode->i_mode))
1182be83bbf8SLinus Torvalds 		return MAX_LFS_FILESIZE;
1183be83bbf8SLinus Torvalds 
118476f34950SIvan Khoronzhuk 	if (S_ISSOCK(inode->i_mode))
118576f34950SIvan Khoronzhuk 		return MAX_LFS_FILESIZE;
118676f34950SIvan Khoronzhuk 
1187be83bbf8SLinus Torvalds 	/* Special "we do even unsigned file positions" case */
1188be83bbf8SLinus Torvalds 	if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1189be83bbf8SLinus Torvalds 		return 0;
1190be83bbf8SLinus Torvalds 
1191be83bbf8SLinus Torvalds 	/* Yes, random drivers might want more. But I'm tired of buggy drivers */
1192be83bbf8SLinus Torvalds 	return ULONG_MAX;
1193be83bbf8SLinus Torvalds }
1194be83bbf8SLinus Torvalds 
file_mmap_ok(struct file * file,struct inode * inode,unsigned long pgoff,unsigned long len)1195be83bbf8SLinus Torvalds static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1196be83bbf8SLinus Torvalds 				unsigned long pgoff, unsigned long len)
1197be83bbf8SLinus Torvalds {
1198be83bbf8SLinus Torvalds 	u64 maxsize = file_mmap_size_max(file, inode);
1199be83bbf8SLinus Torvalds 
1200be83bbf8SLinus Torvalds 	if (maxsize && len > maxsize)
1201be83bbf8SLinus Torvalds 		return false;
1202be83bbf8SLinus Torvalds 	maxsize -= len;
1203be83bbf8SLinus Torvalds 	if (pgoff > maxsize >> PAGE_SHIFT)
1204be83bbf8SLinus Torvalds 		return false;
1205be83bbf8SLinus Torvalds 	return true;
1206be83bbf8SLinus Torvalds }
1207be83bbf8SLinus Torvalds 
120840401530SAl Viro /*
12093e4e28c5SMichel Lespinasse  * The caller must write-lock current->mm->mmap_lock.
12101da177e4SLinus Torvalds  */
do_mmap(struct file * file,unsigned long addr,unsigned long len,unsigned long prot,unsigned long flags,vm_flags_t vm_flags,unsigned long pgoff,unsigned long * populate,struct list_head * uf)12111fcfd8dbSOleg Nesterov unsigned long do_mmap(struct file *file, unsigned long addr,
12121da177e4SLinus Torvalds 			unsigned long len, unsigned long prot,
1213592b5fadSYu-cheng Yu 			unsigned long flags, vm_flags_t vm_flags,
1214592b5fadSYu-cheng Yu 			unsigned long pgoff, unsigned long *populate,
1215592b5fadSYu-cheng Yu 			struct list_head *uf)
12161da177e4SLinus Torvalds {
12171da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
121862b5f7d0SDave Hansen 	int pkey = 0;
12191da177e4SLinus Torvalds 
122041badc15SMichel Lespinasse 	*populate = 0;
1221bebeb3d6SMichel Lespinasse 
1222e37609bbSPiotr Kwapulinski 	if (!len)
1223e37609bbSPiotr Kwapulinski 		return -EINVAL;
1224e37609bbSPiotr Kwapulinski 
12251da177e4SLinus Torvalds 	/*
12261da177e4SLinus Torvalds 	 * Does the application expect PROT_READ to imply PROT_EXEC?
12271da177e4SLinus Torvalds 	 *
12281da177e4SLinus Torvalds 	 * (the exception is when the underlying filesystem is noexec
12291da177e4SLinus Torvalds 	 *  mounted, in which case we dont add PROT_EXEC.)
12301da177e4SLinus Torvalds 	 */
12311da177e4SLinus Torvalds 	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
123290f8572bSEric W. Biederman 		if (!(file && path_noexec(&file->f_path)))
12331da177e4SLinus Torvalds 			prot |= PROT_EXEC;
12341da177e4SLinus Torvalds 
1235a4ff8e86SMichal Hocko 	/* force arch specific MAP_FIXED handling in get_unmapped_area */
1236a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE)
1237a4ff8e86SMichal Hocko 		flags |= MAP_FIXED;
1238a4ff8e86SMichal Hocko 
12397cd94146SEric Paris 	if (!(flags & MAP_FIXED))
12407cd94146SEric Paris 		addr = round_hint_to_min(addr);
12417cd94146SEric Paris 
12421da177e4SLinus Torvalds 	/* Careful about overflows.. */
12431da177e4SLinus Torvalds 	len = PAGE_ALIGN(len);
12449206de95SAl Viro 	if (!len)
12451da177e4SLinus Torvalds 		return -ENOMEM;
12461da177e4SLinus Torvalds 
12471da177e4SLinus Torvalds 	/* offset overflow? */
12481da177e4SLinus Torvalds 	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
12491da177e4SLinus Torvalds 		return -EOVERFLOW;
12501da177e4SLinus Torvalds 
12511da177e4SLinus Torvalds 	/* Too many mappings? */
12521da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
12531da177e4SLinus Torvalds 		return -ENOMEM;
12541da177e4SLinus Torvalds 
12551da177e4SLinus Torvalds 	/* Obtain the address to map to. we verify (or select) it and ensure
12561da177e4SLinus Torvalds 	 * that it represents a valid section of the address space.
12571da177e4SLinus Torvalds 	 */
12581da177e4SLinus Torvalds 	addr = get_unmapped_area(file, addr, len, pgoff, flags);
1259ff68dac6SGaowei Pu 	if (IS_ERR_VALUE(addr))
12601da177e4SLinus Torvalds 		return addr;
12611da177e4SLinus Torvalds 
1262a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE) {
126335e43c5fSLiam Howlett 		if (find_vma_intersection(mm, addr, addr + len))
1264a4ff8e86SMichal Hocko 			return -EEXIST;
1265a4ff8e86SMichal Hocko 	}
1266a4ff8e86SMichal Hocko 
126762b5f7d0SDave Hansen 	if (prot == PROT_EXEC) {
126862b5f7d0SDave Hansen 		pkey = execute_only_pkey(mm);
126962b5f7d0SDave Hansen 		if (pkey < 0)
127062b5f7d0SDave Hansen 			pkey = 0;
127162b5f7d0SDave Hansen 	}
127262b5f7d0SDave Hansen 
12731da177e4SLinus Torvalds 	/* Do simple checking here so the lower-level routines won't have
12741da177e4SLinus Torvalds 	 * to. we assume access permissions have been handled by the open
12751da177e4SLinus Torvalds 	 * of the memory object, so we don't do any here.
12761da177e4SLinus Torvalds 	 */
1277592b5fadSYu-cheng Yu 	vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
12781da177e4SLinus Torvalds 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
12791da177e4SLinus Torvalds 
1280cdf7b341SHuang Shijie 	if (flags & MAP_LOCKED)
12811da177e4SLinus Torvalds 		if (!can_do_mlock())
12821da177e4SLinus Torvalds 			return -EPERM;
1283ba470de4SRik van Riel 
1284b0cc5e89SAndrew Morton 	if (!mlock_future_ok(mm, vm_flags, len))
12851da177e4SLinus Torvalds 		return -EAGAIN;
12861da177e4SLinus Torvalds 
12871da177e4SLinus Torvalds 	if (file) {
1288077bf22bSOleg Nesterov 		struct inode *inode = file_inode(file);
12891c972597SDan Williams 		unsigned long flags_mask;
12901c972597SDan Williams 
1291be83bbf8SLinus Torvalds 		if (!file_mmap_ok(file, inode, pgoff, len))
1292be83bbf8SLinus Torvalds 			return -EOVERFLOW;
1293be83bbf8SLinus Torvalds 
12941c972597SDan Williams 		flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1295077bf22bSOleg Nesterov 
12961da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
12971da177e4SLinus Torvalds 		case MAP_SHARED:
12981c972597SDan Williams 			/*
12991c972597SDan Williams 			 * Force use of MAP_SHARED_VALIDATE with non-legacy
13001c972597SDan Williams 			 * flags. E.g. MAP_SYNC is dangerous to use with
13011c972597SDan Williams 			 * MAP_SHARED as you don't know which consistency model
13021c972597SDan Williams 			 * you will get. We silently ignore unsupported flags
13031c972597SDan Williams 			 * with MAP_SHARED to preserve backward compatibility.
13041c972597SDan Williams 			 */
13051c972597SDan Williams 			flags &= LEGACY_MAP_MASK;
1306e4a9bc58SJoe Perches 			fallthrough;
13071c972597SDan Williams 		case MAP_SHARED_VALIDATE:
13081c972597SDan Williams 			if (flags & ~flags_mask)
13091c972597SDan Williams 				return -EOPNOTSUPP;
1310dc617f29SDarrick J. Wong 			if (prot & PROT_WRITE) {
1311dc617f29SDarrick J. Wong 				if (!(file->f_mode & FMODE_WRITE))
13121da177e4SLinus Torvalds 					return -EACCES;
1313dc617f29SDarrick J. Wong 				if (IS_SWAPFILE(file->f_mapping->host))
1314dc617f29SDarrick J. Wong 					return -ETXTBSY;
1315dc617f29SDarrick J. Wong 			}
13161da177e4SLinus Torvalds 
13171da177e4SLinus Torvalds 			/*
13181da177e4SLinus Torvalds 			 * Make sure we don't allow writing to an append-only
13191da177e4SLinus Torvalds 			 * file..
13201da177e4SLinus Torvalds 			 */
13211da177e4SLinus Torvalds 			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
13221da177e4SLinus Torvalds 				return -EACCES;
13231da177e4SLinus Torvalds 
13241da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
13251da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_WRITE))
13261da177e4SLinus Torvalds 				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1327e4a9bc58SJoe Perches 			fallthrough;
13281da177e4SLinus Torvalds 		case MAP_PRIVATE:
13291da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_READ))
13301da177e4SLinus Torvalds 				return -EACCES;
133190f8572bSEric W. Biederman 			if (path_noexec(&file->f_path)) {
133280c5606cSLinus Torvalds 				if (vm_flags & VM_EXEC)
133380c5606cSLinus Torvalds 					return -EPERM;
133480c5606cSLinus Torvalds 				vm_flags &= ~VM_MAYEXEC;
133580c5606cSLinus Torvalds 			}
133680c5606cSLinus Torvalds 
133772c2d531SAl Viro 			if (!file->f_op->mmap)
133880c5606cSLinus Torvalds 				return -ENODEV;
1339b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1340b2c56e4fSOleg Nesterov 				return -EINVAL;
13411da177e4SLinus Torvalds 			break;
13421da177e4SLinus Torvalds 
13431da177e4SLinus Torvalds 		default:
13441da177e4SLinus Torvalds 			return -EINVAL;
13451da177e4SLinus Torvalds 		}
13461da177e4SLinus Torvalds 	} else {
13471da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
13481da177e4SLinus Torvalds 		case MAP_SHARED:
1349b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1350b2c56e4fSOleg Nesterov 				return -EINVAL;
1351ce363942STejun Heo 			/*
1352ce363942STejun Heo 			 * Ignore pgoff.
1353ce363942STejun Heo 			 */
1354ce363942STejun Heo 			pgoff = 0;
13551da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
13561da177e4SLinus Torvalds 			break;
13571da177e4SLinus Torvalds 		case MAP_PRIVATE:
13581da177e4SLinus Torvalds 			/*
13591da177e4SLinus Torvalds 			 * Set pgoff according to addr for anon_vma.
13601da177e4SLinus Torvalds 			 */
13611da177e4SLinus Torvalds 			pgoff = addr >> PAGE_SHIFT;
13621da177e4SLinus Torvalds 			break;
13631da177e4SLinus Torvalds 		default:
13641da177e4SLinus Torvalds 			return -EINVAL;
13651da177e4SLinus Torvalds 		}
13661da177e4SLinus Torvalds 	}
13671da177e4SLinus Torvalds 
1368c22c0d63SMichel Lespinasse 	/*
1369c22c0d63SMichel Lespinasse 	 * Set 'VM_NORESERVE' if we should not account for the
1370c22c0d63SMichel Lespinasse 	 * memory use of this mapping.
1371c22c0d63SMichel Lespinasse 	 */
1372c22c0d63SMichel Lespinasse 	if (flags & MAP_NORESERVE) {
1373c22c0d63SMichel Lespinasse 		/* We honor MAP_NORESERVE if allowed to overcommit */
1374c22c0d63SMichel Lespinasse 		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1375c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1376c22c0d63SMichel Lespinasse 
1377c22c0d63SMichel Lespinasse 		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
1378c22c0d63SMichel Lespinasse 		if (file && is_file_hugepages(file))
1379c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1380c22c0d63SMichel Lespinasse 	}
1381c22c0d63SMichel Lespinasse 
1382897ab3e0SMike Rapoport 	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
138309a9f1d2SMichel Lespinasse 	if (!IS_ERR_VALUE(addr) &&
138409a9f1d2SMichel Lespinasse 	    ((vm_flags & VM_LOCKED) ||
138509a9f1d2SMichel Lespinasse 	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
138641badc15SMichel Lespinasse 		*populate = len;
1387bebeb3d6SMichel Lespinasse 	return addr;
13880165ab44SMiklos Szeredi }
13896be5ceb0SLinus Torvalds 
ksys_mmap_pgoff(unsigned long addr,unsigned long len,unsigned long prot,unsigned long flags,unsigned long fd,unsigned long pgoff)1390a90f590aSDominik Brodowski unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1391a90f590aSDominik Brodowski 			      unsigned long prot, unsigned long flags,
1392a90f590aSDominik Brodowski 			      unsigned long fd, unsigned long pgoff)
139366f0dc48SHugh Dickins {
139466f0dc48SHugh Dickins 	struct file *file = NULL;
13951e3ee14bSChen Gang 	unsigned long retval;
139666f0dc48SHugh Dickins 
139766f0dc48SHugh Dickins 	if (!(flags & MAP_ANONYMOUS)) {
1398120a795dSAl Viro 		audit_mmap_fd(fd, flags);
139966f0dc48SHugh Dickins 		file = fget(fd);
140066f0dc48SHugh Dickins 		if (!file)
14011e3ee14bSChen Gang 			return -EBADF;
14027bba8f0eSZhen Lei 		if (is_file_hugepages(file)) {
1403af73e4d9SNaoya Horiguchi 			len = ALIGN(len, huge_page_size(hstate_file(file)));
14047bba8f0eSZhen Lei 		} else if (unlikely(flags & MAP_HUGETLB)) {
1405493af578SJörn Engel 			retval = -EINVAL;
1406493af578SJörn Engel 			goto out_fput;
14077bba8f0eSZhen Lei 		}
140866f0dc48SHugh Dickins 	} else if (flags & MAP_HUGETLB) {
1409c103a4dcSAndrew Morton 		struct hstate *hs;
1410af73e4d9SNaoya Horiguchi 
141120ac2893SAnshuman Khandual 		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1412091d0d55SLi Zefan 		if (!hs)
1413091d0d55SLi Zefan 			return -EINVAL;
1414091d0d55SLi Zefan 
1415091d0d55SLi Zefan 		len = ALIGN(len, huge_page_size(hs));
141666f0dc48SHugh Dickins 		/*
141766f0dc48SHugh Dickins 		 * VM_NORESERVE is used because the reservations will be
141866f0dc48SHugh Dickins 		 * taken when vm_ops->mmap() is called
141966f0dc48SHugh Dickins 		 */
1420af73e4d9SNaoya Horiguchi 		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
142142d7395fSAndi Kleen 				VM_NORESERVE,
142283c1fd76Szhangyiru 				HUGETLB_ANONHUGE_INODE,
142342d7395fSAndi Kleen 				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
142466f0dc48SHugh Dickins 		if (IS_ERR(file))
142566f0dc48SHugh Dickins 			return PTR_ERR(file);
142666f0dc48SHugh Dickins 	}
142766f0dc48SHugh Dickins 
14289fbeb5abSMichal Hocko 	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1429493af578SJörn Engel out_fput:
143066f0dc48SHugh Dickins 	if (file)
143166f0dc48SHugh Dickins 		fput(file);
143266f0dc48SHugh Dickins 	return retval;
143366f0dc48SHugh Dickins }
143466f0dc48SHugh Dickins 
SYSCALL_DEFINE6(mmap_pgoff,unsigned long,addr,unsigned long,len,unsigned long,prot,unsigned long,flags,unsigned long,fd,unsigned long,pgoff)1435a90f590aSDominik Brodowski SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1436a90f590aSDominik Brodowski 		unsigned long, prot, unsigned long, flags,
1437a90f590aSDominik Brodowski 		unsigned long, fd, unsigned long, pgoff)
1438a90f590aSDominik Brodowski {
1439a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1440a90f590aSDominik Brodowski }
1441a90f590aSDominik Brodowski 
1442a4679373SChristoph Hellwig #ifdef __ARCH_WANT_SYS_OLD_MMAP
1443a4679373SChristoph Hellwig struct mmap_arg_struct {
1444a4679373SChristoph Hellwig 	unsigned long addr;
1445a4679373SChristoph Hellwig 	unsigned long len;
1446a4679373SChristoph Hellwig 	unsigned long prot;
1447a4679373SChristoph Hellwig 	unsigned long flags;
1448a4679373SChristoph Hellwig 	unsigned long fd;
1449a4679373SChristoph Hellwig 	unsigned long offset;
1450a4679373SChristoph Hellwig };
1451a4679373SChristoph Hellwig 
SYSCALL_DEFINE1(old_mmap,struct mmap_arg_struct __user *,arg)1452a4679373SChristoph Hellwig SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1453a4679373SChristoph Hellwig {
1454a4679373SChristoph Hellwig 	struct mmap_arg_struct a;
1455a4679373SChristoph Hellwig 
1456a4679373SChristoph Hellwig 	if (copy_from_user(&a, arg, sizeof(a)))
1457a4679373SChristoph Hellwig 		return -EFAULT;
1458de1741a1SAlexander Kuleshov 	if (offset_in_page(a.offset))
1459a4679373SChristoph Hellwig 		return -EINVAL;
1460a4679373SChristoph Hellwig 
1461a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1462a4679373SChristoph Hellwig 			       a.offset >> PAGE_SHIFT);
1463a4679373SChristoph Hellwig }
1464a4679373SChristoph Hellwig #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1465a4679373SChristoph Hellwig 
vm_ops_needs_writenotify(const struct vm_operations_struct * vm_ops)146654cbbbf3SLorenzo Stoakes static bool vm_ops_needs_writenotify(const struct vm_operations_struct *vm_ops)
146754cbbbf3SLorenzo Stoakes {
146854cbbbf3SLorenzo Stoakes 	return vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite);
146954cbbbf3SLorenzo Stoakes }
147054cbbbf3SLorenzo Stoakes 
vma_is_shared_writable(struct vm_area_struct * vma)147154cbbbf3SLorenzo Stoakes static bool vma_is_shared_writable(struct vm_area_struct *vma)
147254cbbbf3SLorenzo Stoakes {
147354cbbbf3SLorenzo Stoakes 	return (vma->vm_flags & (VM_WRITE | VM_SHARED)) ==
147454cbbbf3SLorenzo Stoakes 		(VM_WRITE | VM_SHARED);
147554cbbbf3SLorenzo Stoakes }
147654cbbbf3SLorenzo Stoakes 
vma_fs_can_writeback(struct vm_area_struct * vma)147754cbbbf3SLorenzo Stoakes static bool vma_fs_can_writeback(struct vm_area_struct *vma)
147854cbbbf3SLorenzo Stoakes {
147954cbbbf3SLorenzo Stoakes 	/* No managed pages to writeback. */
148054cbbbf3SLorenzo Stoakes 	if (vma->vm_flags & VM_PFNMAP)
148154cbbbf3SLorenzo Stoakes 		return false;
148254cbbbf3SLorenzo Stoakes 
148354cbbbf3SLorenzo Stoakes 	return vma->vm_file && vma->vm_file->f_mapping &&
148454cbbbf3SLorenzo Stoakes 		mapping_can_writeback(vma->vm_file->f_mapping);
148554cbbbf3SLorenzo Stoakes }
148654cbbbf3SLorenzo Stoakes 
148754cbbbf3SLorenzo Stoakes /*
148854cbbbf3SLorenzo Stoakes  * Does this VMA require the underlying folios to have their dirty state
148954cbbbf3SLorenzo Stoakes  * tracked?
149054cbbbf3SLorenzo Stoakes  */
vma_needs_dirty_tracking(struct vm_area_struct * vma)149154cbbbf3SLorenzo Stoakes bool vma_needs_dirty_tracking(struct vm_area_struct *vma)
149254cbbbf3SLorenzo Stoakes {
149354cbbbf3SLorenzo Stoakes 	/* Only shared, writable VMAs require dirty tracking. */
149454cbbbf3SLorenzo Stoakes 	if (!vma_is_shared_writable(vma))
149554cbbbf3SLorenzo Stoakes 		return false;
149654cbbbf3SLorenzo Stoakes 
149754cbbbf3SLorenzo Stoakes 	/* Does the filesystem need to be notified? */
149854cbbbf3SLorenzo Stoakes 	if (vm_ops_needs_writenotify(vma->vm_ops))
149954cbbbf3SLorenzo Stoakes 		return true;
150054cbbbf3SLorenzo Stoakes 
150154cbbbf3SLorenzo Stoakes 	/*
150254cbbbf3SLorenzo Stoakes 	 * Even if the filesystem doesn't indicate a need for writenotify, if it
150354cbbbf3SLorenzo Stoakes 	 * can writeback, dirty tracking is still required.
150454cbbbf3SLorenzo Stoakes 	 */
150554cbbbf3SLorenzo Stoakes 	return vma_fs_can_writeback(vma);
150654cbbbf3SLorenzo Stoakes }
150754cbbbf3SLorenzo Stoakes 
15084e950f6fSAlexey Dobriyan /*
15098bb4e7a2SWei Yang  * Some shared mappings will want the pages marked read-only
15104e950f6fSAlexey Dobriyan  * to track write events. If so, we'll downgrade vm_page_prot
15114e950f6fSAlexey Dobriyan  * to the private version (using protection_map[] without the
15124e950f6fSAlexey Dobriyan  * VM_SHARED bit).
15134e950f6fSAlexey Dobriyan  */
vma_wants_writenotify(struct vm_area_struct * vma,pgprot_t vm_page_prot)15146d2329f8SAndrea Arcangeli int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
15154e950f6fSAlexey Dobriyan {
15164e950f6fSAlexey Dobriyan 	/* If it was private or non-writable, the write bit is already clear */
151754cbbbf3SLorenzo Stoakes 	if (!vma_is_shared_writable(vma))
15184e950f6fSAlexey Dobriyan 		return 0;
15194e950f6fSAlexey Dobriyan 
15204e950f6fSAlexey Dobriyan 	/* The backer wishes to know when pages are first written to? */
152154cbbbf3SLorenzo Stoakes 	if (vm_ops_needs_writenotify(vma->vm_ops))
15224e950f6fSAlexey Dobriyan 		return 1;
15234e950f6fSAlexey Dobriyan 
152464e45507SPeter Feiner 	/* The open routine did something to the protections that pgprot_modify
152564e45507SPeter Feiner 	 * won't preserve? */
15266d2329f8SAndrea Arcangeli 	if (pgprot_val(vm_page_prot) !=
152754cbbbf3SLorenzo Stoakes 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vma->vm_flags)))
15284e950f6fSAlexey Dobriyan 		return 0;
15294e950f6fSAlexey Dobriyan 
1530f96f7a40SDavid Hildenbrand 	/*
1531f96f7a40SDavid Hildenbrand 	 * Do we need to track softdirty? hugetlb does not support softdirty
1532f96f7a40SDavid Hildenbrand 	 * tracking yet.
1533f96f7a40SDavid Hildenbrand 	 */
1534f96f7a40SDavid Hildenbrand 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
153564e45507SPeter Feiner 		return 1;
153664e45507SPeter Feiner 
153751d3d5ebSDavid Hildenbrand 	/* Do we need write faults for uffd-wp tracking? */
153851d3d5ebSDavid Hildenbrand 	if (userfaultfd_wp(vma))
153951d3d5ebSDavid Hildenbrand 		return 1;
154051d3d5ebSDavid Hildenbrand 
15414e950f6fSAlexey Dobriyan 	/* Can the mapping track the dirty pages? */
154254cbbbf3SLorenzo Stoakes 	return vma_fs_can_writeback(vma);
15434e950f6fSAlexey Dobriyan }
15444e950f6fSAlexey Dobriyan 
1545fc8744adSLinus Torvalds /*
1546fc8744adSLinus Torvalds  * We account for memory if it's a private writeable mapping,
15475a6fe125SMel Gorman  * not hugepages and VM_NORESERVE wasn't set.
1548fc8744adSLinus Torvalds  */
accountable_mapping(struct file * file,vm_flags_t vm_flags)1549ca16d140SKOSAKI Motohiro static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1550fc8744adSLinus Torvalds {
15515a6fe125SMel Gorman 	/*
15525a6fe125SMel Gorman 	 * hugetlb has its own accounting separate from the core VM
15535a6fe125SMel Gorman 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
15545a6fe125SMel Gorman 	 */
15555a6fe125SMel Gorman 	if (file && is_file_hugepages(file))
15565a6fe125SMel Gorman 		return 0;
15575a6fe125SMel Gorman 
1558fc8744adSLinus Torvalds 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1559fc8744adSLinus Torvalds }
1560fc8744adSLinus Torvalds 
15613499a131SLiam R. Howlett /**
15623499a131SLiam R. Howlett  * unmapped_area() - Find an area between the low_limit and the high_limit with
15633499a131SLiam R. Howlett  * the correct alignment and offset, all from @info. Note: current->mm is used
15643499a131SLiam R. Howlett  * for the search.
15653499a131SLiam R. Howlett  *
156682b24936SVernon Yang  * @info: The unmapped area information including the range [low_limit -
156782b24936SVernon Yang  * high_limit), the alignment offset and mask.
15683499a131SLiam R. Howlett  *
15693499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
15703499a131SLiam R. Howlett  */
unmapped_area(struct vm_unmapped_area_info * info)1571baceaf1cSJaewon Kim static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1572db4fbfb9SMichel Lespinasse {
15736b008640SLinus Torvalds 	unsigned long length, gap;
15746b008640SLinus Torvalds 	unsigned long low_limit, high_limit;
157558c5d0d6SLiam R. Howlett 	struct vm_area_struct *tmp;
1576db4fbfb9SMichel Lespinasse 
15773499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1578db4fbfb9SMichel Lespinasse 
1579db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1580db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1581db4fbfb9SMichel Lespinasse 	if (length < info->length)
1582db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1583db4fbfb9SMichel Lespinasse 
158458c5d0d6SLiam R. Howlett 	low_limit = info->low_limit;
15856b008640SLinus Torvalds 	if (low_limit < mmap_min_addr)
15866b008640SLinus Torvalds 		low_limit = mmap_min_addr;
15876b008640SLinus Torvalds 	high_limit = info->high_limit;
158858c5d0d6SLiam R. Howlett retry:
15896b008640SLinus Torvalds 	if (mas_empty_area(&mas, low_limit, high_limit - 1, length))
15903499a131SLiam R. Howlett 		return -ENOMEM;
15913499a131SLiam R. Howlett 
1592d4af56c5SLiam R. Howlett 	gap = mas.index;
1593d4af56c5SLiam R. Howlett 	gap += (info->align_offset - gap) & info->align_mask;
159458c5d0d6SLiam R. Howlett 	tmp = mas_next(&mas, ULONG_MAX);
15950266e7c5SRick Edgecombe 	if (tmp && (tmp->vm_flags & VM_STARTGAP_FLAGS)) { /* Avoid prev check if possible */
159658c5d0d6SLiam R. Howlett 		if (vm_start_gap(tmp) < gap + length - 1) {
159758c5d0d6SLiam R. Howlett 			low_limit = tmp->vm_end;
159858c5d0d6SLiam R. Howlett 			mas_reset(&mas);
159958c5d0d6SLiam R. Howlett 			goto retry;
160058c5d0d6SLiam R. Howlett 		}
160158c5d0d6SLiam R. Howlett 	} else {
160258c5d0d6SLiam R. Howlett 		tmp = mas_prev(&mas, 0);
160358c5d0d6SLiam R. Howlett 		if (tmp && vm_end_gap(tmp) > gap) {
160458c5d0d6SLiam R. Howlett 			low_limit = vm_end_gap(tmp);
160558c5d0d6SLiam R. Howlett 			mas_reset(&mas);
160658c5d0d6SLiam R. Howlett 			goto retry;
160758c5d0d6SLiam R. Howlett 		}
160858c5d0d6SLiam R. Howlett 	}
160958c5d0d6SLiam R. Howlett 
16103499a131SLiam R. Howlett 	return gap;
1611db4fbfb9SMichel Lespinasse }
1612db4fbfb9SMichel Lespinasse 
16133499a131SLiam R. Howlett /**
16143499a131SLiam R. Howlett  * unmapped_area_topdown() - Find an area between the low_limit and the
161582b24936SVernon Yang  * high_limit with the correct alignment and offset at the highest available
16163499a131SLiam R. Howlett  * address, all from @info. Note: current->mm is used for the search.
16173499a131SLiam R. Howlett  *
161882b24936SVernon Yang  * @info: The unmapped area information including the range [low_limit -
161982b24936SVernon Yang  * high_limit), the alignment offset and mask.
16203499a131SLiam R. Howlett  *
16213499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
16223499a131SLiam R. Howlett  */
unmapped_area_topdown(struct vm_unmapped_area_info * info)1623baceaf1cSJaewon Kim static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1624db4fbfb9SMichel Lespinasse {
16256b008640SLinus Torvalds 	unsigned long length, gap, gap_end;
16266b008640SLinus Torvalds 	unsigned long low_limit, high_limit;
162758c5d0d6SLiam R. Howlett 	struct vm_area_struct *tmp;
1628d4af56c5SLiam R. Howlett 
16293499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1630db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1631db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1632db4fbfb9SMichel Lespinasse 	if (length < info->length)
1633db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1634db4fbfb9SMichel Lespinasse 
16356b008640SLinus Torvalds 	low_limit = info->low_limit;
16366b008640SLinus Torvalds 	if (low_limit < mmap_min_addr)
16376b008640SLinus Torvalds 		low_limit = mmap_min_addr;
163858c5d0d6SLiam R. Howlett 	high_limit = info->high_limit;
163958c5d0d6SLiam R. Howlett retry:
16406b008640SLinus Torvalds 	if (mas_empty_area_rev(&mas, low_limit, high_limit - 1, length))
16413499a131SLiam R. Howlett 		return -ENOMEM;
16423499a131SLiam R. Howlett 
1643d4af56c5SLiam R. Howlett 	gap = mas.last + 1 - info->length;
1644d4af56c5SLiam R. Howlett 	gap -= (gap - info->align_offset) & info->align_mask;
164558c5d0d6SLiam R. Howlett 	gap_end = mas.last;
164658c5d0d6SLiam R. Howlett 	tmp = mas_next(&mas, ULONG_MAX);
16470266e7c5SRick Edgecombe 	if (tmp && (tmp->vm_flags & VM_STARTGAP_FLAGS)) { /* Avoid prev check if possible */
164858c5d0d6SLiam R. Howlett 		if (vm_start_gap(tmp) <= gap_end) {
164958c5d0d6SLiam R. Howlett 			high_limit = vm_start_gap(tmp);
165058c5d0d6SLiam R. Howlett 			mas_reset(&mas);
165158c5d0d6SLiam R. Howlett 			goto retry;
165258c5d0d6SLiam R. Howlett 		}
165358c5d0d6SLiam R. Howlett 	} else {
165458c5d0d6SLiam R. Howlett 		tmp = mas_prev(&mas, 0);
165558c5d0d6SLiam R. Howlett 		if (tmp && vm_end_gap(tmp) > gap) {
165658c5d0d6SLiam R. Howlett 			high_limit = tmp->vm_start;
165758c5d0d6SLiam R. Howlett 			mas_reset(&mas);
165858c5d0d6SLiam R. Howlett 			goto retry;
165958c5d0d6SLiam R. Howlett 		}
166058c5d0d6SLiam R. Howlett 	}
166158c5d0d6SLiam R. Howlett 
16623499a131SLiam R. Howlett 	return gap;
1663db4fbfb9SMichel Lespinasse }
1664db4fbfb9SMichel Lespinasse 
1665baceaf1cSJaewon Kim /*
1666baceaf1cSJaewon Kim  * Search for an unmapped address range.
1667baceaf1cSJaewon Kim  *
1668baceaf1cSJaewon Kim  * We are looking for a range that:
1669baceaf1cSJaewon Kim  * - does not intersect with any VMA;
1670baceaf1cSJaewon Kim  * - is contained within the [low_limit, high_limit) interval;
1671baceaf1cSJaewon Kim  * - is at least the desired size.
1672baceaf1cSJaewon Kim  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
1673baceaf1cSJaewon Kim  */
vm_unmapped_area(struct vm_unmapped_area_info * info)1674baceaf1cSJaewon Kim unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
1675baceaf1cSJaewon Kim {
1676df529cabSJaewon Kim 	unsigned long addr;
1677df529cabSJaewon Kim 
1678baceaf1cSJaewon Kim 	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1679df529cabSJaewon Kim 		addr = unmapped_area_topdown(info);
1680baceaf1cSJaewon Kim 	else
1681df529cabSJaewon Kim 		addr = unmapped_area(info);
1682df529cabSJaewon Kim 
1683df529cabSJaewon Kim 	trace_vm_unmapped_area(addr, info);
1684df529cabSJaewon Kim 	return addr;
1685baceaf1cSJaewon Kim }
1686f6795053SSteve Capper 
16871da177e4SLinus Torvalds /* Get an address range which is currently unmapped.
16881da177e4SLinus Torvalds  * For shmat() with addr=0.
16891da177e4SLinus Torvalds  *
16901da177e4SLinus Torvalds  * Ugly calling convention alert:
16911da177e4SLinus Torvalds  * Return value with the low bits set means error value,
16921da177e4SLinus Torvalds  * ie
16931da177e4SLinus Torvalds  *	if (ret & ~PAGE_MASK)
16941da177e4SLinus Torvalds  *		error = ret;
16951da177e4SLinus Torvalds  *
16961da177e4SLinus Torvalds  * This function "knows" that -ENOMEM has the bits set.
16971da177e4SLinus Torvalds  */
16981da177e4SLinus Torvalds unsigned long
generic_get_unmapped_area(struct file * filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)16994b439e25SChristophe Leroy generic_get_unmapped_area(struct file *filp, unsigned long addr,
17004b439e25SChristophe Leroy 			  unsigned long len, unsigned long pgoff,
17014b439e25SChristophe Leroy 			  unsigned long flags)
17021da177e4SLinus Torvalds {
17031da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
17041be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
1705db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
17062cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
17071da177e4SLinus Torvalds 
1708f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
17091da177e4SLinus Torvalds 		return -ENOMEM;
17101da177e4SLinus Torvalds 
171106abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
171206abdfb4SBenjamin Herrenschmidt 		return addr;
171306abdfb4SBenjamin Herrenschmidt 
17141da177e4SLinus Torvalds 	if (addr) {
17151da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
17161be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1717f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
17181be7107fSHugh Dickins 		    (!vma || addr + len <= vm_start_gap(vma)) &&
17191be7107fSHugh Dickins 		    (!prev || addr >= vm_end_gap(prev)))
17201da177e4SLinus Torvalds 			return addr;
17211da177e4SLinus Torvalds 	}
17221da177e4SLinus Torvalds 
1723db4fbfb9SMichel Lespinasse 	info.flags = 0;
1724db4fbfb9SMichel Lespinasse 	info.length = len;
17254e99b021SHeiko Carstens 	info.low_limit = mm->mmap_base;
1726f6795053SSteve Capper 	info.high_limit = mmap_end;
1727db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
172809ef5283SJaewon Kim 	info.align_offset = 0;
1729db4fbfb9SMichel Lespinasse 	return vm_unmapped_area(&info);
17301da177e4SLinus Torvalds }
17314b439e25SChristophe Leroy 
17324b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA
17334b439e25SChristophe Leroy unsigned long
arch_get_unmapped_area(struct file * filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)17344b439e25SChristophe Leroy arch_get_unmapped_area(struct file *filp, unsigned long addr,
17354b439e25SChristophe Leroy 		       unsigned long len, unsigned long pgoff,
17364b439e25SChristophe Leroy 		       unsigned long flags)
17374b439e25SChristophe Leroy {
17384b439e25SChristophe Leroy 	return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
17394b439e25SChristophe Leroy }
17401da177e4SLinus Torvalds #endif
17411da177e4SLinus Torvalds 
17421da177e4SLinus Torvalds /*
17431da177e4SLinus Torvalds  * This mmap-allocator allocates new areas top-down from below the
17441da177e4SLinus Torvalds  * stack's low limit (the base):
17451da177e4SLinus Torvalds  */
17461da177e4SLinus Torvalds unsigned long
generic_get_unmapped_area_topdown(struct file * filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)17474b439e25SChristophe Leroy generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
174843cca0b1SYang Fan 				  unsigned long len, unsigned long pgoff,
174943cca0b1SYang Fan 				  unsigned long flags)
17501da177e4SLinus Torvalds {
17511be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
17521da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1753db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
17542cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
17551da177e4SLinus Torvalds 
17561da177e4SLinus Torvalds 	/* requested length too big for entire address space */
1757f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
17581da177e4SLinus Torvalds 		return -ENOMEM;
17591da177e4SLinus Torvalds 
176006abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
176106abdfb4SBenjamin Herrenschmidt 		return addr;
176206abdfb4SBenjamin Herrenschmidt 
17631da177e4SLinus Torvalds 	/* requesting a specific address */
17641da177e4SLinus Torvalds 	if (addr) {
17651da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
17661be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1767f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
17681be7107fSHugh Dickins 				(!vma || addr + len <= vm_start_gap(vma)) &&
17691be7107fSHugh Dickins 				(!prev || addr >= vm_end_gap(prev)))
17701da177e4SLinus Torvalds 			return addr;
17711da177e4SLinus Torvalds 	}
17721da177e4SLinus Torvalds 
1773db4fbfb9SMichel Lespinasse 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1774db4fbfb9SMichel Lespinasse 	info.length = len;
17756b008640SLinus Torvalds 	info.low_limit = PAGE_SIZE;
1776f6795053SSteve Capper 	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1777db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
177809ef5283SJaewon Kim 	info.align_offset = 0;
1779db4fbfb9SMichel Lespinasse 	addr = vm_unmapped_area(&info);
1780b716ad95SXiao Guangrong 
17811da177e4SLinus Torvalds 	/*
17821da177e4SLinus Torvalds 	 * A failed mmap() very likely causes application failure,
17831da177e4SLinus Torvalds 	 * so fall back to the bottom-up function here. This scenario
17841da177e4SLinus Torvalds 	 * can happen with large stack limits and large mmap()
17851da177e4SLinus Torvalds 	 * allocations.
17861da177e4SLinus Torvalds 	 */
1787de1741a1SAlexander Kuleshov 	if (offset_in_page(addr)) {
1788db4fbfb9SMichel Lespinasse 		VM_BUG_ON(addr != -ENOMEM);
1789db4fbfb9SMichel Lespinasse 		info.flags = 0;
1790db4fbfb9SMichel Lespinasse 		info.low_limit = TASK_UNMAPPED_BASE;
1791f6795053SSteve Capper 		info.high_limit = mmap_end;
1792db4fbfb9SMichel Lespinasse 		addr = vm_unmapped_area(&info);
1793db4fbfb9SMichel Lespinasse 	}
17941da177e4SLinus Torvalds 
17951da177e4SLinus Torvalds 	return addr;
17961da177e4SLinus Torvalds }
17974b439e25SChristophe Leroy 
17984b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
17994b439e25SChristophe Leroy unsigned long
arch_get_unmapped_area_topdown(struct file * filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)18004b439e25SChristophe Leroy arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
18014b439e25SChristophe Leroy 			       unsigned long len, unsigned long pgoff,
18024b439e25SChristophe Leroy 			       unsigned long flags)
18034b439e25SChristophe Leroy {
18044b439e25SChristophe Leroy 	return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
18054b439e25SChristophe Leroy }
18061da177e4SLinus Torvalds #endif
18071da177e4SLinus Torvalds 
18081da177e4SLinus Torvalds unsigned long
get_unmapped_area(struct file * file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)18091da177e4SLinus Torvalds get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
18101da177e4SLinus Torvalds 		unsigned long pgoff, unsigned long flags)
18111da177e4SLinus Torvalds {
181206abdfb4SBenjamin Herrenschmidt 	unsigned long (*get_area)(struct file *, unsigned long,
181306abdfb4SBenjamin Herrenschmidt 				  unsigned long, unsigned long, unsigned long);
181407ab67c8SLinus Torvalds 
18159206de95SAl Viro 	unsigned long error = arch_mmap_check(addr, len, flags);
18169206de95SAl Viro 	if (error)
18179206de95SAl Viro 		return error;
18189206de95SAl Viro 
18199206de95SAl Viro 	/* Careful about overflows.. */
18209206de95SAl Viro 	if (len > TASK_SIZE)
18219206de95SAl Viro 		return -ENOMEM;
18229206de95SAl Viro 
182307ab67c8SLinus Torvalds 	get_area = current->mm->get_unmapped_area;
1824c01d5b30SHugh Dickins 	if (file) {
1825c01d5b30SHugh Dickins 		if (file->f_op->get_unmapped_area)
182607ab67c8SLinus Torvalds 			get_area = file->f_op->get_unmapped_area;
1827c01d5b30SHugh Dickins 	} else if (flags & MAP_SHARED) {
1828c01d5b30SHugh Dickins 		/*
1829c01d5b30SHugh Dickins 		 * mmap_region() will call shmem_zero_setup() to create a file,
1830c01d5b30SHugh Dickins 		 * so use shmem's get_unmapped_area in case it can be huge.
183145e55300SPeter Collingbourne 		 * do_mmap() will clear pgoff, so match alignment.
1832c01d5b30SHugh Dickins 		 */
1833c01d5b30SHugh Dickins 		pgoff = 0;
1834c01d5b30SHugh Dickins 		get_area = shmem_get_unmapped_area;
1835c01d5b30SHugh Dickins 	}
1836c01d5b30SHugh Dickins 
183707ab67c8SLinus Torvalds 	addr = get_area(file, addr, len, pgoff, flags);
183807ab67c8SLinus Torvalds 	if (IS_ERR_VALUE(addr))
183907ab67c8SLinus Torvalds 		return addr;
184007ab67c8SLinus Torvalds 
18411da177e4SLinus Torvalds 	if (addr > TASK_SIZE - len)
18421da177e4SLinus Torvalds 		return -ENOMEM;
1843de1741a1SAlexander Kuleshov 	if (offset_in_page(addr))
18441da177e4SLinus Torvalds 		return -EINVAL;
184506abdfb4SBenjamin Herrenschmidt 
18469ac4ed4bSAl Viro 	error = security_mmap_addr(addr);
18479ac4ed4bSAl Viro 	return error ? error : addr;
18481da177e4SLinus Torvalds }
18491da177e4SLinus Torvalds 
18501da177e4SLinus Torvalds EXPORT_SYMBOL(get_unmapped_area);
18511da177e4SLinus Torvalds 
1852be8432e7SLiam R. Howlett /**
1853abdba2ddSLiam R. Howlett  * find_vma_intersection() - Look up the first VMA which intersects the interval
1854abdba2ddSLiam R. Howlett  * @mm: The process address space.
1855abdba2ddSLiam R. Howlett  * @start_addr: The inclusive start user address.
1856abdba2ddSLiam R. Howlett  * @end_addr: The exclusive end user address.
1857abdba2ddSLiam R. Howlett  *
1858abdba2ddSLiam R. Howlett  * Returns: The first VMA within the provided range, %NULL otherwise.  Assumes
1859abdba2ddSLiam R. Howlett  * start_addr < end_addr.
1860abdba2ddSLiam R. Howlett  */
find_vma_intersection(struct mm_struct * mm,unsigned long start_addr,unsigned long end_addr)1861abdba2ddSLiam R. Howlett struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
1862abdba2ddSLiam R. Howlett 					     unsigned long start_addr,
1863abdba2ddSLiam R. Howlett 					     unsigned long end_addr)
1864abdba2ddSLiam R. Howlett {
1865abdba2ddSLiam R. Howlett 	unsigned long index = start_addr;
1866abdba2ddSLiam R. Howlett 
1867abdba2ddSLiam R. Howlett 	mmap_assert_locked(mm);
18687964cf8cSLiam R. Howlett 	return mt_find(&mm->mm_mt, &index, end_addr - 1);
1869abdba2ddSLiam R. Howlett }
1870abdba2ddSLiam R. Howlett EXPORT_SYMBOL(find_vma_intersection);
1871abdba2ddSLiam R. Howlett 
1872abdba2ddSLiam R. Howlett /**
1873be8432e7SLiam R. Howlett  * find_vma() - Find the VMA for a given address, or the next VMA.
1874be8432e7SLiam R. Howlett  * @mm: The mm_struct to check
1875be8432e7SLiam R. Howlett  * @addr: The address
1876be8432e7SLiam R. Howlett  *
1877be8432e7SLiam R. Howlett  * Returns: The VMA associated with addr, or the next VMA.
1878be8432e7SLiam R. Howlett  * May return %NULL in the case of no VMA at addr or above.
1879be8432e7SLiam R. Howlett  */
find_vma(struct mm_struct * mm,unsigned long addr)18801da177e4SLinus Torvalds struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
18811da177e4SLinus Torvalds {
1882be8432e7SLiam R. Howlett 	unsigned long index = addr;
18831da177e4SLinus Torvalds 
18845b78ed24SLuigi Rizzo 	mmap_assert_locked(mm);
18857964cf8cSLiam R. Howlett 	return mt_find(&mm->mm_mt, &index, ULONG_MAX);
18861da177e4SLinus Torvalds }
18871da177e4SLinus Torvalds EXPORT_SYMBOL(find_vma);
18881da177e4SLinus Torvalds 
18897fdbd37dSLiam R. Howlett /**
18907fdbd37dSLiam R. Howlett  * find_vma_prev() - Find the VMA for a given address, or the next vma and
18917fdbd37dSLiam R. Howlett  * set %pprev to the previous VMA, if any.
18927fdbd37dSLiam R. Howlett  * @mm: The mm_struct to check
18937fdbd37dSLiam R. Howlett  * @addr: The address
18947fdbd37dSLiam R. Howlett  * @pprev: The pointer to set to the previous VMA
18957fdbd37dSLiam R. Howlett  *
18967fdbd37dSLiam R. Howlett  * Note that RCU lock is missing here since the external mmap_lock() is used
18977fdbd37dSLiam R. Howlett  * instead.
18987fdbd37dSLiam R. Howlett  *
18997fdbd37dSLiam R. Howlett  * Returns: The VMA associated with @addr, or the next vma.
19007fdbd37dSLiam R. Howlett  * May return %NULL in the case of no vma at addr or above.
19016bd4837dSKOSAKI Motohiro  */
19021da177e4SLinus Torvalds struct vm_area_struct *
find_vma_prev(struct mm_struct * mm,unsigned long addr,struct vm_area_struct ** pprev)19031da177e4SLinus Torvalds find_vma_prev(struct mm_struct *mm, unsigned long addr,
19041da177e4SLinus Torvalds 			struct vm_area_struct **pprev)
19051da177e4SLinus Torvalds {
19066bd4837dSKOSAKI Motohiro 	struct vm_area_struct *vma;
19077fdbd37dSLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, addr, addr);
19081da177e4SLinus Torvalds 
19097fdbd37dSLiam R. Howlett 	vma = mas_walk(&mas);
19107fdbd37dSLiam R. Howlett 	*pprev = mas_prev(&mas, 0);
19117fdbd37dSLiam R. Howlett 	if (!vma)
19127fdbd37dSLiam R. Howlett 		vma = mas_next(&mas, ULONG_MAX);
19136bd4837dSKOSAKI Motohiro 	return vma;
19141da177e4SLinus Torvalds }
19151da177e4SLinus Torvalds 
19161da177e4SLinus Torvalds /*
19171da177e4SLinus Torvalds  * Verify that the stack growth is acceptable and
19181da177e4SLinus Torvalds  * update accounting. This is shared with both the
19191da177e4SLinus Torvalds  * grow-up and grow-down cases.
19201da177e4SLinus Torvalds  */
acct_stack_growth(struct vm_area_struct * vma,unsigned long size,unsigned long grow)19211be7107fSHugh Dickins static int acct_stack_growth(struct vm_area_struct *vma,
19221be7107fSHugh Dickins 			     unsigned long size, unsigned long grow)
19231da177e4SLinus Torvalds {
19241da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
19251be7107fSHugh Dickins 	unsigned long new_start;
19261da177e4SLinus Torvalds 
19271da177e4SLinus Torvalds 	/* address space limit tests */
192884638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vma->vm_flags, grow))
19291da177e4SLinus Torvalds 		return -ENOMEM;
19301da177e4SLinus Torvalds 
19311da177e4SLinus Torvalds 	/* Stack limit test */
193224c79d8eSKrzysztof Opasiak 	if (size > rlimit(RLIMIT_STACK))
19331da177e4SLinus Torvalds 		return -ENOMEM;
19341da177e4SLinus Torvalds 
19351da177e4SLinus Torvalds 	/* mlock limit tests */
1936b0cc5e89SAndrew Morton 	if (!mlock_future_ok(mm, vma->vm_flags, grow << PAGE_SHIFT))
19371da177e4SLinus Torvalds 		return -ENOMEM;
19381da177e4SLinus Torvalds 
19390d59a01bSAdam Litke 	/* Check to ensure the stack will not grow into a hugetlb-only region */
19400d59a01bSAdam Litke 	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
19410d59a01bSAdam Litke 			vma->vm_end - size;
19420d59a01bSAdam Litke 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
19430d59a01bSAdam Litke 		return -EFAULT;
19440d59a01bSAdam Litke 
19451da177e4SLinus Torvalds 	/*
19461da177e4SLinus Torvalds 	 * Overcommit..  This must be the final test, as it will
19471da177e4SLinus Torvalds 	 * update security statistics.
19481da177e4SLinus Torvalds 	 */
194905fa199dSHugh Dickins 	if (security_vm_enough_memory_mm(mm, grow))
19501da177e4SLinus Torvalds 		return -ENOMEM;
19511da177e4SLinus Torvalds 
19521da177e4SLinus Torvalds 	return 0;
19531da177e4SLinus Torvalds }
19541da177e4SLinus Torvalds 
195546dea3d0SHugh Dickins #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
19561da177e4SLinus Torvalds /*
195746dea3d0SHugh Dickins  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
195846dea3d0SHugh Dickins  * vma is the last one with address > vma->vm_end.  Have to extend vma.
19591da177e4SLinus Torvalds  */
expand_upwards(struct vm_area_struct * vma,unsigned long address)19608d7071afSLinus Torvalds static int expand_upwards(struct vm_area_struct *vma, unsigned long address)
19611da177e4SLinus Torvalds {
196209357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
19631be7107fSHugh Dickins 	struct vm_area_struct *next;
19641be7107fSHugh Dickins 	unsigned long gap_addr;
196512352d3cSKonstantin Khlebnikov 	int error = 0;
1966b5df0922SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, vma->vm_start, address);
19671da177e4SLinus Torvalds 
19681da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSUP))
19691da177e4SLinus Torvalds 		return -EFAULT;
19701da177e4SLinus Torvalds 
1971bd726c90SHelge Deller 	/* Guard against exceeding limits of the address space. */
19721be7107fSHugh Dickins 	address &= PAGE_MASK;
197337511fb5SHelge Deller 	if (address >= (TASK_SIZE & PAGE_MASK))
197412352d3cSKonstantin Khlebnikov 		return -ENOMEM;
1975bd726c90SHelge Deller 	address += PAGE_SIZE;
197612352d3cSKonstantin Khlebnikov 
19771be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
19781be7107fSHugh Dickins 	gap_addr = address + stack_guard_gap;
1979bd726c90SHelge Deller 
1980bd726c90SHelge Deller 	/* Guard against overflow */
1981bd726c90SHelge Deller 	if (gap_addr < address || gap_addr > TASK_SIZE)
1982bd726c90SHelge Deller 		gap_addr = TASK_SIZE;
1983bd726c90SHelge Deller 
1984763ecb03SLiam R. Howlett 	next = find_vma_intersection(mm, vma->vm_end, gap_addr);
1985763ecb03SLiam R. Howlett 	if (next && vma_is_accessible(next)) {
19861be7107fSHugh Dickins 		if (!(next->vm_flags & VM_GROWSUP))
19871be7107fSHugh Dickins 			return -ENOMEM;
19881be7107fSHugh Dickins 		/* Check that both stack segments have the same anon_vma? */
19891be7107fSHugh Dickins 	}
19901be7107fSHugh Dickins 
1991b5df0922SLiam R. Howlett 	if (next)
1992b5df0922SLiam R. Howlett 		mas_prev_range(&mas, address);
1993b5df0922SLiam R. Howlett 
1994b5df0922SLiam R. Howlett 	__mas_set_range(&mas, vma->vm_start, address - 1);
1995da089254SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
19961da177e4SLinus Torvalds 		return -ENOMEM;
19971da177e4SLinus Torvalds 
1998d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
1999d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
2000d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
2001d4af56c5SLiam R. Howlett 		return -ENOMEM;
2002d4af56c5SLiam R. Howlett 	}
2003d4af56c5SLiam R. Howlett 
2004c137381fSSuren Baghdasaryan 	/* Lock the VMA before expanding to prevent concurrent page faults */
2005c137381fSSuren Baghdasaryan 	vma_start_write(vma);
20061da177e4SLinus Torvalds 	/*
20071da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2008c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
20091da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
20101da177e4SLinus Torvalds 	 */
201112352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
20121da177e4SLinus Torvalds 
20131da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
20141da177e4SLinus Torvalds 	if (address > vma->vm_end) {
20151da177e4SLinus Torvalds 		unsigned long size, grow;
20161da177e4SLinus Torvalds 
20171da177e4SLinus Torvalds 		size = address - vma->vm_start;
20181da177e4SLinus Torvalds 		grow = (address - vma->vm_end) >> PAGE_SHIFT;
20191da177e4SLinus Torvalds 
202042c36f63SHugh Dickins 		error = -ENOMEM;
202142c36f63SHugh Dickins 		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
20221da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
20233af9e859SEric B Munson 			if (!error) {
20244128997bSMichel Lespinasse 				/*
2025524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
2026524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
2027524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
2028524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
2029524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
2030524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
2031524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
20324128997bSMichel Lespinasse 				 */
203309357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
203487e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
203509357814SOleg Nesterov 					mm->locked_vm += grow;
203684638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2037bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
20381da177e4SLinus Torvalds 				vma->vm_end = address;
2039d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2040fbcc3104SLiam R. Howlett 				mas_store_prealloc(&mas, vma);
2041bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
204209357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
20434128997bSMichel Lespinasse 
20443af9e859SEric B Munson 				perf_event_mmap(vma);
20453af9e859SEric B Munson 			}
20461da177e4SLinus Torvalds 		}
204742c36f63SHugh Dickins 	}
204812352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2049c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2050d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
20512574d5e4SLiam R. Howlett 	validate_mm(mm);
20521da177e4SLinus Torvalds 	return error;
20531da177e4SLinus Torvalds }
205446dea3d0SHugh Dickins #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
205546dea3d0SHugh Dickins 
20561da177e4SLinus Torvalds /*
20571da177e4SLinus Torvalds  * vma is the first one with address < vma->vm_start.  Have to extend vma.
20588d7071afSLinus Torvalds  * mmap_lock held for writing.
20591da177e4SLinus Torvalds  */
expand_downwards(struct vm_area_struct * vma,unsigned long address)2060524e00b3SLiam R. Howlett int expand_downwards(struct vm_area_struct *vma, unsigned long address)
20611da177e4SLinus Torvalds {
206209357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
2063763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, vma->vm_start, vma->vm_start);
20641be7107fSHugh Dickins 	struct vm_area_struct *prev;
20650a1d5299SJann Horn 	int error = 0;
20661da177e4SLinus Torvalds 
20678d7071afSLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSDOWN))
20688d7071afSLinus Torvalds 		return -EFAULT;
20698d7071afSLinus Torvalds 
20708869477aSEric Paris 	address &= PAGE_MASK;
20718b35ca3eSBen Hutchings 	if (address < mmap_min_addr || address < FIRST_USER_ADDRESS)
20720a1d5299SJann Horn 		return -EPERM;
20738869477aSEric Paris 
20741be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
2075763ecb03SLiam R. Howlett 	prev = mas_prev(&mas, 0);
20761be7107fSHugh Dickins 	/* Check that both stack segments have the same anon_vma? */
2077f440fa1aSLiam R. Howlett 	if (prev) {
2078f440fa1aSLiam R. Howlett 		if (!(prev->vm_flags & VM_GROWSDOWN) &&
2079f440fa1aSLiam R. Howlett 		    vma_is_accessible(prev) &&
2080f440fa1aSLiam R. Howlett 		    (address - prev->vm_end < stack_guard_gap))
208132e4e6d5SOleg Nesterov 			return -ENOMEM;
20821be7107fSHugh Dickins 	}
20831be7107fSHugh Dickins 
2084b5df0922SLiam R. Howlett 	if (prev)
2085b5df0922SLiam R. Howlett 		mas_next_range(&mas, vma->vm_start);
2086b5df0922SLiam R. Howlett 
2087b5df0922SLiam R. Howlett 	__mas_set_range(&mas, address, vma->vm_end - 1);
2088da089254SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
208912352d3cSKonstantin Khlebnikov 		return -ENOMEM;
20901da177e4SLinus Torvalds 
2091d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
2092d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
2093d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
2094d4af56c5SLiam R. Howlett 		return -ENOMEM;
2095d4af56c5SLiam R. Howlett 	}
2096d4af56c5SLiam R. Howlett 
2097c137381fSSuren Baghdasaryan 	/* Lock the VMA before expanding to prevent concurrent page faults */
2098c137381fSSuren Baghdasaryan 	vma_start_write(vma);
20991da177e4SLinus Torvalds 	/*
21001da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2101c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
21021da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
21031da177e4SLinus Torvalds 	 */
210412352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
21051da177e4SLinus Torvalds 
21061da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
21071da177e4SLinus Torvalds 	if (address < vma->vm_start) {
21081da177e4SLinus Torvalds 		unsigned long size, grow;
21091da177e4SLinus Torvalds 
21101da177e4SLinus Torvalds 		size = vma->vm_end - address;
21111da177e4SLinus Torvalds 		grow = (vma->vm_start - address) >> PAGE_SHIFT;
21121da177e4SLinus Torvalds 
2113a626ca6aSLinus Torvalds 		error = -ENOMEM;
2114a626ca6aSLinus Torvalds 		if (grow <= vma->vm_pgoff) {
21151da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
21161da177e4SLinus Torvalds 			if (!error) {
21174128997bSMichel Lespinasse 				/*
2118524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
2119524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
2120524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
2121524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
2122524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
2123524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
2124524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
21254128997bSMichel Lespinasse 				 */
212609357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
212787e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
212809357814SOleg Nesterov 					mm->locked_vm += grow;
212984638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2130bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
21311da177e4SLinus Torvalds 				vma->vm_start = address;
21321da177e4SLinus Torvalds 				vma->vm_pgoff -= grow;
2133d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2134fbcc3104SLiam R. Howlett 				mas_store_prealloc(&mas, vma);
2135bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
213609357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
21374128997bSMichel Lespinasse 
21383af9e859SEric B Munson 				perf_event_mmap(vma);
21391da177e4SLinus Torvalds 			}
21401da177e4SLinus Torvalds 		}
2141a626ca6aSLinus Torvalds 	}
214212352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2143c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2144d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
21452574d5e4SLiam R. Howlett 	validate_mm(mm);
21461da177e4SLinus Torvalds 	return error;
21471da177e4SLinus Torvalds }
21481da177e4SLinus Torvalds 
21491be7107fSHugh Dickins /* enforced gap between the expanding stack and other mappings. */
21501be7107fSHugh Dickins unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
21511be7107fSHugh Dickins 
cmdline_parse_stack_guard_gap(char * p)21521be7107fSHugh Dickins static int __init cmdline_parse_stack_guard_gap(char *p)
21531be7107fSHugh Dickins {
21541be7107fSHugh Dickins 	unsigned long val;
21551be7107fSHugh Dickins 	char *endptr;
21561be7107fSHugh Dickins 
21571be7107fSHugh Dickins 	val = simple_strtoul(p, &endptr, 10);
21581be7107fSHugh Dickins 	if (!*endptr)
21591be7107fSHugh Dickins 		stack_guard_gap = val << PAGE_SHIFT;
21601be7107fSHugh Dickins 
2161e6d09493SRandy Dunlap 	return 1;
21621be7107fSHugh Dickins }
21631be7107fSHugh Dickins __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
21641be7107fSHugh Dickins 
2165b6a2fea3SOllie Wild #ifdef CONFIG_STACK_GROWSUP
expand_stack_locked(struct vm_area_struct * vma,unsigned long address)21668d7071afSLinus Torvalds int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
2167b6a2fea3SOllie Wild {
2168b6a2fea3SOllie Wild 	return expand_upwards(vma, address);
2169b6a2fea3SOllie Wild }
2170b6a2fea3SOllie Wild 
find_extend_vma_locked(struct mm_struct * mm,unsigned long addr)21718d7071afSLinus Torvalds struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
2172b6a2fea3SOllie Wild {
2173b6a2fea3SOllie Wild 	struct vm_area_struct *vma, *prev;
2174b6a2fea3SOllie Wild 
2175b6a2fea3SOllie Wild 	addr &= PAGE_MASK;
2176b6a2fea3SOllie Wild 	vma = find_vma_prev(mm, addr, &prev);
2177b6a2fea3SOllie Wild 	if (vma && (vma->vm_start <= addr))
2178b6a2fea3SOllie Wild 		return vma;
2179f440fa1aSLiam R. Howlett 	if (!prev)
2180f440fa1aSLiam R. Howlett 		return NULL;
21818d7071afSLinus Torvalds 	if (expand_stack_locked(prev, addr))
2182b6a2fea3SOllie Wild 		return NULL;
2183cea10a19SMichel Lespinasse 	if (prev->vm_flags & VM_LOCKED)
2184fc05f566SKirill A. Shutemov 		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2185b6a2fea3SOllie Wild 	return prev;
2186b6a2fea3SOllie Wild }
2187b6a2fea3SOllie Wild #else
expand_stack_locked(struct vm_area_struct * vma,unsigned long address)21888d7071afSLinus Torvalds int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
2189b6a2fea3SOllie Wild {
2190f440fa1aSLiam R. Howlett 	if (unlikely(!(vma->vm_flags & VM_GROWSDOWN)))
2191f440fa1aSLiam R. Howlett 		return -EINVAL;
2192b6a2fea3SOllie Wild 	return expand_downwards(vma, address);
2193b6a2fea3SOllie Wild }
2194b6a2fea3SOllie Wild 
find_extend_vma_locked(struct mm_struct * mm,unsigned long addr)21958d7071afSLinus Torvalds struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
21961da177e4SLinus Torvalds {
21971da177e4SLinus Torvalds 	struct vm_area_struct *vma;
21981da177e4SLinus Torvalds 	unsigned long start;
21991da177e4SLinus Torvalds 
22001da177e4SLinus Torvalds 	addr &= PAGE_MASK;
22011da177e4SLinus Torvalds 	vma = find_vma(mm, addr);
22021da177e4SLinus Torvalds 	if (!vma)
22031da177e4SLinus Torvalds 		return NULL;
22041da177e4SLinus Torvalds 	if (vma->vm_start <= addr)
22051da177e4SLinus Torvalds 		return vma;
22061da177e4SLinus Torvalds 	start = vma->vm_start;
22078d7071afSLinus Torvalds 	if (expand_stack_locked(vma, addr))
22081da177e4SLinus Torvalds 		return NULL;
2209cea10a19SMichel Lespinasse 	if (vma->vm_flags & VM_LOCKED)
2210fc05f566SKirill A. Shutemov 		populate_vma_page_range(vma, addr, start, NULL);
22111da177e4SLinus Torvalds 	return vma;
22121da177e4SLinus Torvalds }
22131da177e4SLinus Torvalds #endif
22141da177e4SLinus Torvalds 
22158d7071afSLinus Torvalds /*
22168d7071afSLinus Torvalds  * IA64 has some horrid mapping rules: it can expand both up and down,
22178d7071afSLinus Torvalds  * but with various special rules.
22188d7071afSLinus Torvalds  *
22198d7071afSLinus Torvalds  * We'll get rid of this architecture eventually, so the ugliness is
22208d7071afSLinus Torvalds  * temporary.
22218d7071afSLinus Torvalds  */
22228d7071afSLinus Torvalds #ifdef CONFIG_IA64
vma_expand_ok(struct vm_area_struct * vma,unsigned long addr)22238d7071afSLinus Torvalds static inline bool vma_expand_ok(struct vm_area_struct *vma, unsigned long addr)
2224f440fa1aSLiam R. Howlett {
22258d7071afSLinus Torvalds 	return REGION_NUMBER(addr) == REGION_NUMBER(vma->vm_start) &&
22268d7071afSLinus Torvalds 		REGION_OFFSET(addr) < RGN_MAP_LIMIT;
2227f440fa1aSLiam R. Howlett }
22288d7071afSLinus Torvalds 
22298d7071afSLinus Torvalds /*
22308d7071afSLinus Torvalds  * IA64 stacks grow down, but there's a special register backing store
22318d7071afSLinus Torvalds  * that can grow up. Only sequentially, though, so the new address must
22328d7071afSLinus Torvalds  * match vm_end.
22338d7071afSLinus Torvalds  */
vma_expand_up(struct vm_area_struct * vma,unsigned long addr)22348d7071afSLinus Torvalds static inline int vma_expand_up(struct vm_area_struct *vma, unsigned long addr)
22358d7071afSLinus Torvalds {
22368d7071afSLinus Torvalds 	if (!vma_expand_ok(vma, addr))
22378d7071afSLinus Torvalds 		return -EFAULT;
22388d7071afSLinus Torvalds 	if (vma->vm_end != (addr & PAGE_MASK))
22398d7071afSLinus Torvalds 		return -EFAULT;
22408d7071afSLinus Torvalds 	return expand_upwards(vma, addr);
22418d7071afSLinus Torvalds }
22428d7071afSLinus Torvalds 
vma_expand_down(struct vm_area_struct * vma,unsigned long addr)22438d7071afSLinus Torvalds static inline bool vma_expand_down(struct vm_area_struct *vma, unsigned long addr)
22448d7071afSLinus Torvalds {
22458d7071afSLinus Torvalds 	if (!vma_expand_ok(vma, addr))
22468d7071afSLinus Torvalds 		return -EFAULT;
22478d7071afSLinus Torvalds 	return expand_downwards(vma, addr);
22488d7071afSLinus Torvalds }
22498d7071afSLinus Torvalds 
22508d7071afSLinus Torvalds #elif defined(CONFIG_STACK_GROWSUP)
22518d7071afSLinus Torvalds 
22528d7071afSLinus Torvalds #define vma_expand_up(vma,addr) expand_upwards(vma, addr)
22538d7071afSLinus Torvalds #define vma_expand_down(vma, addr) (-EFAULT)
22548d7071afSLinus Torvalds 
22558d7071afSLinus Torvalds #else
22568d7071afSLinus Torvalds 
22578d7071afSLinus Torvalds #define vma_expand_up(vma,addr) (-EFAULT)
22588d7071afSLinus Torvalds #define vma_expand_down(vma, addr) expand_downwards(vma, addr)
22598d7071afSLinus Torvalds 
22608d7071afSLinus Torvalds #endif
22618d7071afSLinus Torvalds 
22628d7071afSLinus Torvalds /*
22638d7071afSLinus Torvalds  * expand_stack(): legacy interface for page faulting. Don't use unless
22648d7071afSLinus Torvalds  * you have to.
22658d7071afSLinus Torvalds  *
22668d7071afSLinus Torvalds  * This is called with the mm locked for reading, drops the lock, takes
22678d7071afSLinus Torvalds  * the lock for writing, tries to look up a vma again, expands it if
22688d7071afSLinus Torvalds  * necessary, and downgrades the lock to reading again.
22698d7071afSLinus Torvalds  *
22708d7071afSLinus Torvalds  * If no vma is found or it can't be expanded, it returns NULL and has
22718d7071afSLinus Torvalds  * dropped the lock.
22728d7071afSLinus Torvalds  */
expand_stack(struct mm_struct * mm,unsigned long addr)22738d7071afSLinus Torvalds struct vm_area_struct *expand_stack(struct mm_struct *mm, unsigned long addr)
22748d7071afSLinus Torvalds {
22758d7071afSLinus Torvalds 	struct vm_area_struct *vma, *prev;
22768d7071afSLinus Torvalds 
22778d7071afSLinus Torvalds 	mmap_read_unlock(mm);
22788d7071afSLinus Torvalds 	if (mmap_write_lock_killable(mm))
22798d7071afSLinus Torvalds 		return NULL;
22808d7071afSLinus Torvalds 
22818d7071afSLinus Torvalds 	vma = find_vma_prev(mm, addr, &prev);
22828d7071afSLinus Torvalds 	if (vma && vma->vm_start <= addr)
22838d7071afSLinus Torvalds 		goto success;
22848d7071afSLinus Torvalds 
22858d7071afSLinus Torvalds 	if (prev && !vma_expand_up(prev, addr)) {
22868d7071afSLinus Torvalds 		vma = prev;
22878d7071afSLinus Torvalds 		goto success;
22888d7071afSLinus Torvalds 	}
22898d7071afSLinus Torvalds 
22908d7071afSLinus Torvalds 	if (vma && !vma_expand_down(vma, addr))
22918d7071afSLinus Torvalds 		goto success;
22928d7071afSLinus Torvalds 
22938d7071afSLinus Torvalds 	mmap_write_unlock(mm);
22948d7071afSLinus Torvalds 	return NULL;
22958d7071afSLinus Torvalds 
22968d7071afSLinus Torvalds success:
22978d7071afSLinus Torvalds 	mmap_write_downgrade(mm);
22988d7071afSLinus Torvalds 	return vma;
22998d7071afSLinus Torvalds }
2300e1d6d01aSJesse Barnes 
23012c0b3814SHugh Dickins /*
2302763ecb03SLiam R. Howlett  * Ok - we have the memory areas we should free on a maple tree so release them,
2303763ecb03SLiam R. Howlett  * and do the vma updates.
23041da177e4SLinus Torvalds  *
23052c0b3814SHugh Dickins  * Called with the mm semaphore held.
23061da177e4SLinus Torvalds  */
remove_mt(struct mm_struct * mm,struct ma_state * mas)2307763ecb03SLiam R. Howlett static inline void remove_mt(struct mm_struct *mm, struct ma_state *mas)
23081da177e4SLinus Torvalds {
23094f74d2c8SLinus Torvalds 	unsigned long nr_accounted = 0;
2310763ecb03SLiam R. Howlett 	struct vm_area_struct *vma;
23114f74d2c8SLinus Torvalds 
2312365e9c87SHugh Dickins 	/* Update high watermark before we lower total_vm */
2313365e9c87SHugh Dickins 	update_hiwater_vm(mm);
2314763ecb03SLiam R. Howlett 	mas_for_each(mas, vma, ULONG_MAX) {
2315ab50b8edSHugh Dickins 		long nrpages = vma_pages(vma);
23161da177e4SLinus Torvalds 
23174f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
23184f74d2c8SLinus Torvalds 			nr_accounted += nrpages;
231984638335SKonstantin Khlebnikov 		vm_stat_account(mm, vma->vm_flags, -nrpages);
23200d2ebf9cSSuren Baghdasaryan 		remove_vma(vma, false);
2321763ecb03SLiam R. Howlett 	}
23224f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
23231da177e4SLinus Torvalds }
23241da177e4SLinus Torvalds 
23251da177e4SLinus Torvalds /*
23261da177e4SLinus Torvalds  * Get rid of page table information in the indicated region.
23271da177e4SLinus Torvalds  *
2328f10df686SPaolo 'Blaisorblade' Giarrusso  * Called with the mm semaphore held.
23291da177e4SLinus Torvalds  */
unmap_region(struct mm_struct * mm,struct ma_state * mas,struct vm_area_struct * vma,struct vm_area_struct * prev,struct vm_area_struct * next,unsigned long start,unsigned long end,unsigned long tree_end,bool mm_wr_locked)2330fd892593SLiam R. Howlett static void unmap_region(struct mm_struct *mm, struct ma_state *mas,
2331e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
2332fd892593SLiam R. Howlett 		struct vm_area_struct *next, unsigned long start,
2333fd892593SLiam R. Howlett 		unsigned long end, unsigned long tree_end, bool mm_wr_locked)
23341da177e4SLinus Torvalds {
2335d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
2336fd892593SLiam R. Howlett 	unsigned long mt_start = mas->index;
23371da177e4SLinus Torvalds 
23381da177e4SLinus Torvalds 	lru_add_drain();
2339a72afd87SWill Deacon 	tlb_gather_mmu(&tlb, mm);
2340365e9c87SHugh Dickins 	update_hiwater_rss(mm);
2341fd892593SLiam R. Howlett 	unmap_vmas(&tlb, mas, vma, start, end, tree_end, mm_wr_locked);
2342fd892593SLiam R. Howlett 	mas_set(mas, mt_start);
2343fd892593SLiam R. Howlett 	free_pgtables(&tlb, mas, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
234498e51a22SSuren Baghdasaryan 				 next ? next->vm_start : USER_PGTABLES_CEILING,
234598e51a22SSuren Baghdasaryan 				 mm_wr_locked);
2346ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
23471da177e4SLinus Torvalds }
23481da177e4SLinus Torvalds 
23491da177e4SLinus Torvalds /*
2350def5efe0SDavid Rientjes  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2351def5efe0SDavid Rientjes  * has already been checked or doesn't make sense to fail.
23520fd5a9e2SLiam R. Howlett  * VMA Iterator will point to the end VMA.
23531da177e4SLinus Torvalds  */
__split_vma(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long addr,int new_below)23549760ebffSLiam R. Howlett int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
23551da177e4SLinus Torvalds 		unsigned long addr, int new_below)
23561da177e4SLinus Torvalds {
2357b2b3b886SLiam R. Howlett 	struct vma_prepare vp;
23581da177e4SLinus Torvalds 	struct vm_area_struct *new;
2359e3975891SChen Gang 	int err;
23609760ebffSLiam R. Howlett 
2361b2b3b886SLiam R. Howlett 	WARN_ON(vma->vm_start >= addr);
2362b2b3b886SLiam R. Howlett 	WARN_ON(vma->vm_end <= addr);
2363b2b3b886SLiam R. Howlett 
2364dd3b614fSDmitry Safonov 	if (vma->vm_ops && vma->vm_ops->may_split) {
2365dd3b614fSDmitry Safonov 		err = vma->vm_ops->may_split(vma, addr);
236631383c68SDan Williams 		if (err)
236731383c68SDan Williams 			return err;
236831383c68SDan Williams 	}
23691da177e4SLinus Torvalds 
23703928d4f5SLinus Torvalds 	new = vm_area_dup(vma);
23711da177e4SLinus Torvalds 	if (!new)
2372e3975891SChen Gang 		return -ENOMEM;
23731da177e4SLinus Torvalds 
2374b2b3b886SLiam R. Howlett 	if (new_below) {
23751da177e4SLinus Torvalds 		new->vm_end = addr;
2376b2b3b886SLiam R. Howlett 	} else {
23771da177e4SLinus Torvalds 		new->vm_start = addr;
23781da177e4SLinus Torvalds 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
23791da177e4SLinus Torvalds 	}
23801da177e4SLinus Torvalds 
2381b5df0922SLiam R. Howlett 	err = -ENOMEM;
2382b5df0922SLiam R. Howlett 	vma_iter_config(vmi, new->vm_start, new->vm_end);
2383b5df0922SLiam R. Howlett 	if (vma_iter_prealloc(vmi, new))
2384b5df0922SLiam R. Howlett 		goto out_free_vma;
2385b5df0922SLiam R. Howlett 
2386ef0855d3SOleg Nesterov 	err = vma_dup_policy(vma, new);
2387ef0855d3SOleg Nesterov 	if (err)
2388b2b3b886SLiam R. Howlett 		goto out_free_vmi;
23891da177e4SLinus Torvalds 
2390c4ea95d7SDaniel Forrest 	err = anon_vma_clone(new, vma);
2391c4ea95d7SDaniel Forrest 	if (err)
23925beb4930SRik van Riel 		goto out_free_mpol;
23935beb4930SRik van Riel 
2394e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
23951da177e4SLinus Torvalds 		get_file(new->vm_file);
23961da177e4SLinus Torvalds 
23971da177e4SLinus Torvalds 	if (new->vm_ops && new->vm_ops->open)
23981da177e4SLinus Torvalds 		new->vm_ops->open(new);
23991da177e4SLinus Torvalds 
2400c9d6e982SSuren Baghdasaryan 	vma_start_write(vma);
2401c9d6e982SSuren Baghdasaryan 	vma_start_write(new);
2402c9d6e982SSuren Baghdasaryan 
2403b2b3b886SLiam R. Howlett 	init_vma_prep(&vp, vma);
2404b2b3b886SLiam R. Howlett 	vp.insert = new;
2405b2b3b886SLiam R. Howlett 	vma_prepare(&vp);
2406ccf1d78dSSuren Baghdasaryan 	vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
24071da177e4SLinus Torvalds 
2408b2b3b886SLiam R. Howlett 	if (new_below) {
2409b2b3b886SLiam R. Howlett 		vma->vm_start = addr;
2410b2b3b886SLiam R. Howlett 		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
2411b2b3b886SLiam R. Howlett 	} else {
2412b2b3b886SLiam R. Howlett 		vma->vm_end = addr;
24139760ebffSLiam R. Howlett 	}
24145beb4930SRik van Riel 
2415b2b3b886SLiam R. Howlett 	/* vma_complete stores the new vma */
2416b2b3b886SLiam R. Howlett 	vma_complete(&vp, vmi, vma->vm_mm);
2417b2b3b886SLiam R. Howlett 
2418b2b3b886SLiam R. Howlett 	/* Success. */
2419b2b3b886SLiam R. Howlett 	if (new_below)
2420b2b3b886SLiam R. Howlett 		vma_next(vmi);
2421b2b3b886SLiam R. Howlett 	return 0;
2422b2b3b886SLiam R. Howlett 
24235beb4930SRik van Riel out_free_mpol:
2424ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new));
2425b2b3b886SLiam R. Howlett out_free_vmi:
2426b2b3b886SLiam R. Howlett 	vma_iter_free(vmi);
24275beb4930SRik van Riel out_free_vma:
24283928d4f5SLinus Torvalds 	vm_area_free(new);
24295beb4930SRik van Riel 	return err;
24301da177e4SLinus Torvalds }
24311da177e4SLinus Torvalds 
2432659ace58SKOSAKI Motohiro /*
2433659ace58SKOSAKI Motohiro  * Split a vma into two pieces at address 'addr', a new vma is allocated
2434659ace58SKOSAKI Motohiro  * either for the first part or the tail.
2435659ace58SKOSAKI Motohiro  */
split_vma(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long addr,int new_below)24369760ebffSLiam R. Howlett int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2437659ace58SKOSAKI Motohiro 	      unsigned long addr, int new_below)
2438659ace58SKOSAKI Motohiro {
24399760ebffSLiam R. Howlett 	if (vma->vm_mm->map_count >= sysctl_max_map_count)
2440659ace58SKOSAKI Motohiro 		return -ENOMEM;
2441659ace58SKOSAKI Motohiro 
24429760ebffSLiam R. Howlett 	return __split_vma(vmi, vma, addr, new_below);
2443f2ebfe43SLiam R. Howlett }
2444f2ebfe43SLiam R. Howlett 
244511f9a21aSLiam R. Howlett /*
2446183654ceSLiam R. Howlett  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
2447183654ceSLiam R. Howlett  * @vmi: The vma iterator
244811f9a21aSLiam R. Howlett  * @vma: The starting vm_area_struct
244911f9a21aSLiam R. Howlett  * @mm: The mm_struct
245011f9a21aSLiam R. Howlett  * @start: The aligned start address to munmap.
245111f9a21aSLiam R. Howlett  * @end: The aligned end address to munmap.
245211f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
2453408579cdSLiam R. Howlett  * @unlock: Set to true to drop the mmap_lock.  unlocking only happens on
2454408579cdSLiam R. Howlett  * success.
245511f9a21aSLiam R. Howlett  *
2456408579cdSLiam R. Howlett  * Return: 0 on success and drops the lock if so directed, error and leaves the
2457408579cdSLiam R. Howlett  * lock held otherwise.
245811f9a21aSLiam R. Howlett  */
245911f9a21aSLiam R. Howlett static int
do_vmi_align_munmap(struct vma_iterator * vmi,struct vm_area_struct * vma,struct mm_struct * mm,unsigned long start,unsigned long end,struct list_head * uf,bool unlock)2460183654ceSLiam R. Howlett do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
246111f9a21aSLiam R. Howlett 		    struct mm_struct *mm, unsigned long start,
2462408579cdSLiam R. Howlett 		    unsigned long end, struct list_head *uf, bool unlock)
246311f9a21aSLiam R. Howlett {
2464763ecb03SLiam R. Howlett 	struct vm_area_struct *prev, *next = NULL;
2465763ecb03SLiam R. Howlett 	struct maple_tree mt_detach;
2466763ecb03SLiam R. Howlett 	int count = 0;
2467d4af56c5SLiam R. Howlett 	int error = -ENOMEM;
2468606c812eSLiam R. Howlett 	unsigned long locked_vm = 0;
2469763ecb03SLiam R. Howlett 	MA_STATE(mas_detach, &mt_detach, 0, 0);
24703dd44325SLiam R. Howlett 	mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
247102fdb25fSLiam R. Howlett 	mt_on_stack(mt_detach);
2472524e00b3SLiam R. Howlett 
24731da177e4SLinus Torvalds 	/*
24741da177e4SLinus Torvalds 	 * If we need to split any vma, do it now to save pain later.
24751da177e4SLinus Torvalds 	 *
24761da177e4SLinus Torvalds 	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
24771da177e4SLinus Torvalds 	 * unmapped vm_area_struct will remain in use: so lower split_vma
24781da177e4SLinus Torvalds 	 * places tmp vma above, and higher split_vma places tmp vma below.
24791da177e4SLinus Torvalds 	 */
2480763ecb03SLiam R. Howlett 
2481763ecb03SLiam R. Howlett 	/* Does it split the first one? */
2482146425a3SHugh Dickins 	if (start > vma->vm_start) {
2483659ace58SKOSAKI Motohiro 
2484659ace58SKOSAKI Motohiro 		/*
2485659ace58SKOSAKI Motohiro 		 * Make sure that map_count on return from munmap() will
2486659ace58SKOSAKI Motohiro 		 * not exceed its limit; but let map_count go just above
2487659ace58SKOSAKI Motohiro 		 * its limit temporarily, to help free resources as expected.
2488659ace58SKOSAKI Motohiro 		 */
2489659ace58SKOSAKI Motohiro 		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2490d4af56c5SLiam R. Howlett 			goto map_count_exceeded;
2491659ace58SKOSAKI Motohiro 
24926935e052SLiam R. Howlett 		error = __split_vma(vmi, vma, start, 1);
24931da177e4SLinus Torvalds 		if (error)
2494763ecb03SLiam R. Howlett 			goto start_split_failed;
24951da177e4SLinus Torvalds 	}
24961da177e4SLinus Torvalds 
2497763ecb03SLiam R. Howlett 	/*
2498763ecb03SLiam R. Howlett 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
2499763ecb03SLiam R. Howlett 	 * it is always overwritten.
2500763ecb03SLiam R. Howlett 	 */
25016935e052SLiam R. Howlett 	next = vma;
25026935e052SLiam R. Howlett 	do {
2503763ecb03SLiam R. Howlett 		/* Does it split the end? */
2504763ecb03SLiam R. Howlett 		if (next->vm_end > end) {
25056b73cff2SLiam R. Howlett 			error = __split_vma(vmi, next, end, 0);
25061da177e4SLinus Torvalds 			if (error)
2507763ecb03SLiam R. Howlett 				goto end_split_failed;
250811f9a21aSLiam R. Howlett 		}
2509606c812eSLiam R. Howlett 		vma_start_write(next);
2510fd892593SLiam R. Howlett 		mas_set(&mas_detach, count);
25116c26bd43SDavid Woodhouse 		error = mas_store_gfp(&mas_detach, next, GFP_KERNEL);
25126c26bd43SDavid Woodhouse 		if (error)
2513606c812eSLiam R. Howlett 			goto munmap_gather_failed;
2514606c812eSLiam R. Howlett 		vma_mark_detached(next, true);
2515606c812eSLiam R. Howlett 		if (next->vm_flags & VM_LOCKED)
2516606c812eSLiam R. Howlett 			locked_vm += vma_pages(next);
2517763ecb03SLiam R. Howlett 
2518763ecb03SLiam R. Howlett 		count++;
25192376dd7cSAndrea Arcangeli 		if (unlikely(uf)) {
25202376dd7cSAndrea Arcangeli 			/*
25212376dd7cSAndrea Arcangeli 			 * If userfaultfd_unmap_prep returns an error the vmas
2522f0953a1bSIngo Molnar 			 * will remain split, but userland will get a
25232376dd7cSAndrea Arcangeli 			 * highly unexpected error anyway. This is no
25242376dd7cSAndrea Arcangeli 			 * different than the case where the first of the two
25252376dd7cSAndrea Arcangeli 			 * __split_vma fails, but we don't undo the first
25262376dd7cSAndrea Arcangeli 			 * split, despite we could. This is unlikely enough
25272376dd7cSAndrea Arcangeli 			 * failure that it's not worth optimizing it for.
25282376dd7cSAndrea Arcangeli 			 */
252965ac1320SLiam R. Howlett 			error = userfaultfd_unmap_prep(next, start, end, uf);
253011f9a21aSLiam R. Howlett 
25312376dd7cSAndrea Arcangeli 			if (error)
2532d4af56c5SLiam R. Howlett 				goto userfaultfd_error;
25332376dd7cSAndrea Arcangeli 		}
2534ba470de4SRik van Riel #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
2535ba470de4SRik van Riel 		BUG_ON(next->vm_start < start);
2536ba470de4SRik van Riel 		BUG_ON(next->vm_start > end);
25371da177e4SLinus Torvalds #endif
25386935e052SLiam R. Howlett 	} for_each_vma_range(*vmi, next, end);
25392376dd7cSAndrea Arcangeli 
2540763ecb03SLiam R. Howlett #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2541763ecb03SLiam R. Howlett 	/* Make sure no VMAs are about to be lost. */
2542763ecb03SLiam R. Howlett 	{
2543fd892593SLiam R. Howlett 		MA_STATE(test, &mt_detach, 0, 0);
2544763ecb03SLiam R. Howlett 		struct vm_area_struct *vma_mas, *vma_test;
2545763ecb03SLiam R. Howlett 		int test_count = 0;
2546763ecb03SLiam R. Howlett 
2547183654ceSLiam R. Howlett 		vma_iter_set(vmi, start);
2548763ecb03SLiam R. Howlett 		rcu_read_lock();
2549fd892593SLiam R. Howlett 		vma_test = mas_find(&test, count - 1);
2550183654ceSLiam R. Howlett 		for_each_vma_range(*vmi, vma_mas, end) {
2551763ecb03SLiam R. Howlett 			BUG_ON(vma_mas != vma_test);
2552763ecb03SLiam R. Howlett 			test_count++;
2553fd892593SLiam R. Howlett 			vma_test = mas_next(&test, count - 1);
2554763ecb03SLiam R. Howlett 		}
2555763ecb03SLiam R. Howlett 		rcu_read_unlock();
2556763ecb03SLiam R. Howlett 		BUG_ON(count != test_count);
2557763ecb03SLiam R. Howlett 	}
2558763ecb03SLiam R. Howlett #endif
25596935e052SLiam R. Howlett 
25606935e052SLiam R. Howlett 	while (vma_iter_addr(vmi) > start)
25616935e052SLiam R. Howlett 		vma_iter_prev_range(vmi);
25626935e052SLiam R. Howlett 
25636c26bd43SDavid Woodhouse 	error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
25646c26bd43SDavid Woodhouse 	if (error)
2565606c812eSLiam R. Howlett 		goto clear_tree_failed;
25660378c0a0SLiam R. Howlett 
25676c26bd43SDavid Woodhouse 	/* Point of no return */
2568606c812eSLiam R. Howlett 	mm->locked_vm -= locked_vm;
2569763ecb03SLiam R. Howlett 	mm->map_count -= count;
2570408579cdSLiam R. Howlett 	if (unlock)
2571d8ed45c5SMichel Lespinasse 		mmap_write_downgrade(mm);
2572dd2283f2SYang Shi 
25736935e052SLiam R. Howlett 	prev = vma_iter_prev_range(vmi);
25746935e052SLiam R. Howlett 	next = vma_next(vmi);
25756935e052SLiam R. Howlett 	if (next)
25766935e052SLiam R. Howlett 		vma_iter_prev_range(vmi);
25776935e052SLiam R. Howlett 
257868f48381SSuren Baghdasaryan 	/*
257968f48381SSuren Baghdasaryan 	 * We can free page tables without write-locking mmap_lock because VMAs
258068f48381SSuren Baghdasaryan 	 * were isolated before we downgraded mmap_lock.
258168f48381SSuren Baghdasaryan 	 */
2582fd892593SLiam R. Howlett 	mas_set(&mas_detach, 1);
2583fd892593SLiam R. Howlett 	unmap_region(mm, &mas_detach, vma, prev, next, start, end, count,
2584fd892593SLiam R. Howlett 		     !unlock);
2585763ecb03SLiam R. Howlett 	/* Statistics and freeing VMAs */
2586fd892593SLiam R. Howlett 	mas_set(&mas_detach, 0);
2587763ecb03SLiam R. Howlett 	remove_mt(mm, &mas_detach);
2588ae80b404SLinus Torvalds 	validate_mm(mm);
2589408579cdSLiam R. Howlett 	if (unlock)
2590408579cdSLiam R. Howlett 		mmap_read_unlock(mm);
25911da177e4SLinus Torvalds 
259202fdb25fSLiam R. Howlett 	__mt_destroy(&mt_detach);
2593408579cdSLiam R. Howlett 	return 0;
2594d4af56c5SLiam R. Howlett 
2595606c812eSLiam R. Howlett clear_tree_failed:
2596d4af56c5SLiam R. Howlett userfaultfd_error:
2597606c812eSLiam R. Howlett munmap_gather_failed:
2598763ecb03SLiam R. Howlett end_split_failed:
2599606c812eSLiam R. Howlett 	mas_set(&mas_detach, 0);
2600606c812eSLiam R. Howlett 	mas_for_each(&mas_detach, next, end)
2601606c812eSLiam R. Howlett 		vma_mark_detached(next, false);
2602606c812eSLiam R. Howlett 
2603763ecb03SLiam R. Howlett 	__mt_destroy(&mt_detach);
2604763ecb03SLiam R. Howlett start_split_failed:
2605763ecb03SLiam R. Howlett map_count_exceeded:
2606b5641a5dSLinus Torvalds 	validate_mm(mm);
2607d4af56c5SLiam R. Howlett 	return error;
26081da177e4SLinus Torvalds }
26091da177e4SLinus Torvalds 
261011f9a21aSLiam R. Howlett /*
2611183654ceSLiam R. Howlett  * do_vmi_munmap() - munmap a given range.
2612183654ceSLiam R. Howlett  * @vmi: The vma iterator
261311f9a21aSLiam R. Howlett  * @mm: The mm_struct
261411f9a21aSLiam R. Howlett  * @start: The start address to munmap
261511f9a21aSLiam R. Howlett  * @len: The length of the range to munmap
261611f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
2617408579cdSLiam R. Howlett  * @unlock: set to true if the user wants to drop the mmap_lock on success
261811f9a21aSLiam R. Howlett  *
261911f9a21aSLiam R. Howlett  * This function takes a @mas that is either pointing to the previous VMA or set
262011f9a21aSLiam R. Howlett  * to MA_START and sets it up to remove the mapping(s).  The @len will be
262111f9a21aSLiam R. Howlett  * aligned and any arch_unmap work will be preformed.
262211f9a21aSLiam R. Howlett  *
2623408579cdSLiam R. Howlett  * Return: 0 on success and drops the lock if so directed, error and leaves the
2624408579cdSLiam R. Howlett  * lock held otherwise.
262511f9a21aSLiam R. Howlett  */
do_vmi_munmap(struct vma_iterator * vmi,struct mm_struct * mm,unsigned long start,size_t len,struct list_head * uf,bool unlock)2626183654ceSLiam R. Howlett int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
262711f9a21aSLiam R. Howlett 		  unsigned long start, size_t len, struct list_head *uf,
2628408579cdSLiam R. Howlett 		  bool unlock)
262911f9a21aSLiam R. Howlett {
263011f9a21aSLiam R. Howlett 	unsigned long end;
263111f9a21aSLiam R. Howlett 	struct vm_area_struct *vma;
263211f9a21aSLiam R. Howlett 
263311f9a21aSLiam R. Howlett 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
263411f9a21aSLiam R. Howlett 		return -EINVAL;
263511f9a21aSLiam R. Howlett 
263611f9a21aSLiam R. Howlett 	end = start + PAGE_ALIGN(len);
263711f9a21aSLiam R. Howlett 	if (end == start)
263811f9a21aSLiam R. Howlett 		return -EINVAL;
263911f9a21aSLiam R. Howlett 
264011f9a21aSLiam R. Howlett 	 /* arch_unmap() might do unmaps itself.  */
264111f9a21aSLiam R. Howlett 	arch_unmap(mm, start, end);
264211f9a21aSLiam R. Howlett 
264311f9a21aSLiam R. Howlett 	/* Find the first overlapping VMA */
2644183654ceSLiam R. Howlett 	vma = vma_find(vmi, end);
2645408579cdSLiam R. Howlett 	if (!vma) {
2646408579cdSLiam R. Howlett 		if (unlock)
2647408579cdSLiam R. Howlett 			mmap_write_unlock(mm);
264811f9a21aSLiam R. Howlett 		return 0;
2649408579cdSLiam R. Howlett 	}
265011f9a21aSLiam R. Howlett 
2651408579cdSLiam R. Howlett 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
265211f9a21aSLiam R. Howlett }
265311f9a21aSLiam R. Howlett 
265411f9a21aSLiam R. Howlett /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
265511f9a21aSLiam R. Howlett  * @mm: The mm_struct
265611f9a21aSLiam R. Howlett  * @start: The start address to munmap
265711f9a21aSLiam R. Howlett  * @len: The length to be munmapped.
265811f9a21aSLiam R. Howlett  * @uf: The userfaultfd list_head
2659408579cdSLiam R. Howlett  *
2660408579cdSLiam R. Howlett  * Return: 0 on success, error otherwise.
266111f9a21aSLiam R. Howlett  */
do_munmap(struct mm_struct * mm,unsigned long start,size_t len,struct list_head * uf)2662dd2283f2SYang Shi int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2663dd2283f2SYang Shi 	      struct list_head *uf)
2664dd2283f2SYang Shi {
2665183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, start);
266611f9a21aSLiam R. Howlett 
2667183654ceSLiam R. Howlett 	return do_vmi_munmap(&vmi, mm, start, len, uf, false);
2668dd2283f2SYang Shi }
2669dd2283f2SYang Shi 
mmap_region(struct file * file,unsigned long addr,unsigned long len,vm_flags_t vm_flags,unsigned long pgoff,struct list_head * uf)2670e99668a5SLiam R. Howlett unsigned long mmap_region(struct file *file, unsigned long addr,
2671e99668a5SLiam R. Howlett 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2672e99668a5SLiam R. Howlett 		struct list_head *uf)
2673e99668a5SLiam R. Howlett {
2674e99668a5SLiam R. Howlett 	struct mm_struct *mm = current->mm;
2675e99668a5SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
2676e99668a5SLiam R. Howlett 	struct vm_area_struct *next, *prev, *merge;
2677e99668a5SLiam R. Howlett 	pgoff_t pglen = len >> PAGE_SHIFT;
2678e99668a5SLiam R. Howlett 	unsigned long charged = 0;
2679e99668a5SLiam R. Howlett 	unsigned long end = addr + len;
2680e99668a5SLiam R. Howlett 	unsigned long merge_start = addr, merge_end = end;
2681e99668a5SLiam R. Howlett 	pgoff_t vm_pgoff;
2682e99668a5SLiam R. Howlett 	int error;
2683183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
2684e99668a5SLiam R. Howlett 
2685e99668a5SLiam R. Howlett 	/* Check against address space limit. */
2686e99668a5SLiam R. Howlett 	if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2687e99668a5SLiam R. Howlett 		unsigned long nr_pages;
2688e99668a5SLiam R. Howlett 
2689e99668a5SLiam R. Howlett 		/*
2690e99668a5SLiam R. Howlett 		 * MAP_FIXED may remove pages of mappings that intersects with
2691e99668a5SLiam R. Howlett 		 * requested mapping. Account for the pages it would unmap.
2692e99668a5SLiam R. Howlett 		 */
2693e99668a5SLiam R. Howlett 		nr_pages = count_vma_pages_range(mm, addr, end);
2694e99668a5SLiam R. Howlett 
2695e99668a5SLiam R. Howlett 		if (!may_expand_vm(mm, vm_flags,
2696e99668a5SLiam R. Howlett 					(len >> PAGE_SHIFT) - nr_pages))
2697e99668a5SLiam R. Howlett 			return -ENOMEM;
2698e99668a5SLiam R. Howlett 	}
2699e99668a5SLiam R. Howlett 
2700e99668a5SLiam R. Howlett 	/* Unmap any existing mapping in the area */
2701183654ceSLiam R. Howlett 	if (do_vmi_munmap(&vmi, mm, addr, len, uf, false))
2702e99668a5SLiam R. Howlett 		return -ENOMEM;
2703e99668a5SLiam R. Howlett 
2704e99668a5SLiam R. Howlett 	/*
2705e99668a5SLiam R. Howlett 	 * Private writable mapping: check memory availability
2706e99668a5SLiam R. Howlett 	 */
2707e99668a5SLiam R. Howlett 	if (accountable_mapping(file, vm_flags)) {
2708e99668a5SLiam R. Howlett 		charged = len >> PAGE_SHIFT;
2709e99668a5SLiam R. Howlett 		if (security_vm_enough_memory_mm(mm, charged))
2710e99668a5SLiam R. Howlett 			return -ENOMEM;
2711e99668a5SLiam R. Howlett 		vm_flags |= VM_ACCOUNT;
2712e99668a5SLiam R. Howlett 	}
2713e99668a5SLiam R. Howlett 
2714183654ceSLiam R. Howlett 	next = vma_next(&vmi);
2715183654ceSLiam R. Howlett 	prev = vma_prev(&vmi);
271653bee98dSLiam R. Howlett 	if (vm_flags & VM_SPECIAL) {
271753bee98dSLiam R. Howlett 		if (prev)
271853bee98dSLiam R. Howlett 			vma_iter_next_range(&vmi);
2719e99668a5SLiam R. Howlett 		goto cannot_expand;
272053bee98dSLiam R. Howlett 	}
2721e99668a5SLiam R. Howlett 
2722e99668a5SLiam R. Howlett 	/* Attempt to expand an old mapping */
2723e99668a5SLiam R. Howlett 	/* Check next */
2724e99668a5SLiam R. Howlett 	if (next && next->vm_start == end && !vma_policy(next) &&
2725e99668a5SLiam R. Howlett 	    can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2726e99668a5SLiam R. Howlett 				 NULL_VM_UFFD_CTX, NULL)) {
2727e99668a5SLiam R. Howlett 		merge_end = next->vm_end;
2728e99668a5SLiam R. Howlett 		vma = next;
2729e99668a5SLiam R. Howlett 		vm_pgoff = next->vm_pgoff - pglen;
2730e99668a5SLiam R. Howlett 	}
2731e99668a5SLiam R. Howlett 
2732e99668a5SLiam R. Howlett 	/* Check prev */
2733e99668a5SLiam R. Howlett 	if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2734e99668a5SLiam R. Howlett 	    (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2735e99668a5SLiam R. Howlett 				       pgoff, vma->vm_userfaultfd_ctx, NULL) :
2736e99668a5SLiam R. Howlett 		   can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2737e99668a5SLiam R. Howlett 				       NULL_VM_UFFD_CTX, NULL))) {
2738e99668a5SLiam R. Howlett 		merge_start = prev->vm_start;
2739e99668a5SLiam R. Howlett 		vma = prev;
2740e99668a5SLiam R. Howlett 		vm_pgoff = prev->vm_pgoff;
274153bee98dSLiam R. Howlett 	} else if (prev) {
274253bee98dSLiam R. Howlett 		vma_iter_next_range(&vmi);
2743e99668a5SLiam R. Howlett 	}
2744e99668a5SLiam R. Howlett 
2745e99668a5SLiam R. Howlett 	/* Actually expand, if possible */
2746e99668a5SLiam R. Howlett 	if (vma &&
27473c441ab7SLiam R. Howlett 	    !vma_expand(&vmi, vma, merge_start, merge_end, vm_pgoff, next)) {
2748e99668a5SLiam R. Howlett 		khugepaged_enter_vma(vma, vm_flags);
2749e99668a5SLiam R. Howlett 		goto expanded;
2750e99668a5SLiam R. Howlett 	}
2751e99668a5SLiam R. Howlett 
275253bee98dSLiam R. Howlett 	if (vma == prev)
275353bee98dSLiam R. Howlett 		vma_iter_set(&vmi, addr);
2754e99668a5SLiam R. Howlett cannot_expand:
27555c1c03deSLiam R. Howlett 
2756e99668a5SLiam R. Howlett 	/*
2757e99668a5SLiam R. Howlett 	 * Determine the object being mapped and call the appropriate
2758e99668a5SLiam R. Howlett 	 * specific mapper. the address has already been validated, but
2759e99668a5SLiam R. Howlett 	 * not unmapped, but the maps are removed from the list.
2760e99668a5SLiam R. Howlett 	 */
2761e99668a5SLiam R. Howlett 	vma = vm_area_alloc(mm);
2762e99668a5SLiam R. Howlett 	if (!vma) {
2763e99668a5SLiam R. Howlett 		error = -ENOMEM;
2764e99668a5SLiam R. Howlett 		goto unacct_error;
2765e99668a5SLiam R. Howlett 	}
2766e99668a5SLiam R. Howlett 
276753bee98dSLiam R. Howlett 	vma_iter_config(&vmi, addr, end);
2768e99668a5SLiam R. Howlett 	vma->vm_start = addr;
2769e99668a5SLiam R. Howlett 	vma->vm_end = end;
27701c71222eSSuren Baghdasaryan 	vm_flags_init(vma, vm_flags);
2771e99668a5SLiam R. Howlett 	vma->vm_page_prot = vm_get_page_prot(vm_flags);
2772e99668a5SLiam R. Howlett 	vma->vm_pgoff = pgoff;
2773e99668a5SLiam R. Howlett 
2774e99668a5SLiam R. Howlett 	if (file) {
2775e99668a5SLiam R. Howlett 		if (vm_flags & VM_SHARED) {
2776e99668a5SLiam R. Howlett 			error = mapping_map_writable(file->f_mapping);
2777e99668a5SLiam R. Howlett 			if (error)
2778e99668a5SLiam R. Howlett 				goto free_vma;
2779e99668a5SLiam R. Howlett 		}
2780e99668a5SLiam R. Howlett 
2781e99668a5SLiam R. Howlett 		vma->vm_file = get_file(file);
2782e99668a5SLiam R. Howlett 		error = call_mmap(file, vma);
2783e99668a5SLiam R. Howlett 		if (error)
2784e99668a5SLiam R. Howlett 			goto unmap_and_free_vma;
2785e99668a5SLiam R. Howlett 
2786a57b7051SLiam Howlett 		/*
2787a57b7051SLiam Howlett 		 * Expansion is handled above, merging is handled below.
2788a57b7051SLiam Howlett 		 * Drivers should not alter the address of the VMA.
2789e99668a5SLiam R. Howlett 		 */
2790a57b7051SLiam Howlett 		error = -EINVAL;
2791cc8d1b09SLiam R. Howlett 		if (WARN_ON((addr != vma->vm_start)))
2792a57b7051SLiam Howlett 			goto close_and_free_vma;
2793e99668a5SLiam R. Howlett 
279453bee98dSLiam R. Howlett 		vma_iter_config(&vmi, addr, end);
2795e99668a5SLiam R. Howlett 		/*
2796e99668a5SLiam R. Howlett 		 * If vm_flags changed after call_mmap(), we should try merge
2797e99668a5SLiam R. Howlett 		 * vma again as we may succeed this time.
2798e99668a5SLiam R. Howlett 		 */
2799e99668a5SLiam R. Howlett 		if (unlikely(vm_flags != vma->vm_flags && prev)) {
28009760ebffSLiam R. Howlett 			merge = vma_merge(&vmi, mm, prev, vma->vm_start,
28019760ebffSLiam R. Howlett 				    vma->vm_end, vma->vm_flags, NULL,
28029760ebffSLiam R. Howlett 				    vma->vm_file, vma->vm_pgoff, NULL,
28039760ebffSLiam R. Howlett 				    NULL_VM_UFFD_CTX, NULL);
2804e99668a5SLiam R. Howlett 			if (merge) {
2805e99668a5SLiam R. Howlett 				/*
2806e99668a5SLiam R. Howlett 				 * ->mmap() can change vma->vm_file and fput
2807e99668a5SLiam R. Howlett 				 * the original file. So fput the vma->vm_file
2808e99668a5SLiam R. Howlett 				 * here or we would add an extra fput for file
2809e99668a5SLiam R. Howlett 				 * and cause general protection fault
2810e99668a5SLiam R. Howlett 				 * ultimately.
2811e99668a5SLiam R. Howlett 				 */
2812e99668a5SLiam R. Howlett 				fput(vma->vm_file);
2813e99668a5SLiam R. Howlett 				vm_area_free(vma);
2814e99668a5SLiam R. Howlett 				vma = merge;
2815e99668a5SLiam R. Howlett 				/* Update vm_flags to pick up the change. */
2816e99668a5SLiam R. Howlett 				vm_flags = vma->vm_flags;
2817e99668a5SLiam R. Howlett 				goto unmap_writable;
2818e99668a5SLiam R. Howlett 			}
2819e99668a5SLiam R. Howlett 		}
2820e99668a5SLiam R. Howlett 
2821e99668a5SLiam R. Howlett 		vm_flags = vma->vm_flags;
2822e99668a5SLiam R. Howlett 	} else if (vm_flags & VM_SHARED) {
2823e99668a5SLiam R. Howlett 		error = shmem_zero_setup(vma);
2824e99668a5SLiam R. Howlett 		if (error)
2825e99668a5SLiam R. Howlett 			goto free_vma;
2826e99668a5SLiam R. Howlett 	} else {
2827e99668a5SLiam R. Howlett 		vma_set_anonymous(vma);
2828e99668a5SLiam R. Howlett 	}
2829e99668a5SLiam R. Howlett 
2830b507808eSJoey Gouly 	if (map_deny_write_exec(vma, vma->vm_flags)) {
2831b507808eSJoey Gouly 		error = -EACCES;
2832b507808eSJoey Gouly 		goto close_and_free_vma;
2833b507808eSJoey Gouly 	}
2834b507808eSJoey Gouly 
2835e99668a5SLiam R. Howlett 	/* Allow architectures to sanity-check the vm_flags */
2836e99668a5SLiam R. Howlett 	error = -EINVAL;
2837cc8d1b09SLiam R. Howlett 	if (!arch_validate_flags(vma->vm_flags))
2838deb0f656SCarlos Llamas 		goto close_and_free_vma;
2839e99668a5SLiam R. Howlett 
2840e99668a5SLiam R. Howlett 	error = -ENOMEM;
2841b5df0922SLiam R. Howlett 	if (vma_iter_prealloc(&vmi, vma))
28425789151eSMike Kravetz 		goto close_and_free_vma;
2843e99668a5SLiam R. Howlett 
28441c7873e3SHugh Dickins 	/* Lock the VMA since it is modified after insertion into VMA tree */
28451c7873e3SHugh Dickins 	vma_start_write(vma);
2846183654ceSLiam R. Howlett 	vma_iter_store(&vmi, vma);
2847e99668a5SLiam R. Howlett 	mm->map_count++;
2848e99668a5SLiam R. Howlett 	if (vma->vm_file) {
28496852c46cSYu Ma 		i_mmap_lock_write(vma->vm_file->f_mapping);
2850e99668a5SLiam R. Howlett 		if (vma->vm_flags & VM_SHARED)
2851e99668a5SLiam R. Howlett 			mapping_allow_writable(vma->vm_file->f_mapping);
2852e99668a5SLiam R. Howlett 
2853e99668a5SLiam R. Howlett 		flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2854e99668a5SLiam R. Howlett 		vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2855e99668a5SLiam R. Howlett 		flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2856e99668a5SLiam R. Howlett 		i_mmap_unlock_write(vma->vm_file->f_mapping);
2857e99668a5SLiam R. Howlett 	}
2858e99668a5SLiam R. Howlett 
2859e99668a5SLiam R. Howlett 	/*
2860e99668a5SLiam R. Howlett 	 * vma_merge() calls khugepaged_enter_vma() either, the below
2861e99668a5SLiam R. Howlett 	 * call covers the non-merge case.
2862e99668a5SLiam R. Howlett 	 */
2863e99668a5SLiam R. Howlett 	khugepaged_enter_vma(vma, vma->vm_flags);
2864e99668a5SLiam R. Howlett 
2865e99668a5SLiam R. Howlett 	/* Once vma denies write, undo our temporary denial count */
2866e99668a5SLiam R. Howlett unmap_writable:
2867e99668a5SLiam R. Howlett 	if (file && vm_flags & VM_SHARED)
2868e99668a5SLiam R. Howlett 		mapping_unmap_writable(file->f_mapping);
2869e99668a5SLiam R. Howlett 	file = vma->vm_file;
2870d7597f59SStefan Roesch 	ksm_add_vma(vma);
2871e99668a5SLiam R. Howlett expanded:
2872e99668a5SLiam R. Howlett 	perf_event_mmap(vma);
2873e99668a5SLiam R. Howlett 
2874e99668a5SLiam R. Howlett 	vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2875e99668a5SLiam R. Howlett 	if (vm_flags & VM_LOCKED) {
2876e99668a5SLiam R. Howlett 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2877e99668a5SLiam R. Howlett 					is_vm_hugetlb_page(vma) ||
2878e99668a5SLiam R. Howlett 					vma == get_gate_vma(current->mm))
2879e430a95aSSuren Baghdasaryan 			vm_flags_clear(vma, VM_LOCKED_MASK);
2880e99668a5SLiam R. Howlett 		else
2881e99668a5SLiam R. Howlett 			mm->locked_vm += (len >> PAGE_SHIFT);
2882e99668a5SLiam R. Howlett 	}
2883e99668a5SLiam R. Howlett 
2884e99668a5SLiam R. Howlett 	if (file)
2885e99668a5SLiam R. Howlett 		uprobe_mmap(vma);
2886e99668a5SLiam R. Howlett 
2887e99668a5SLiam R. Howlett 	/*
2888e99668a5SLiam R. Howlett 	 * New (or expanded) vma always get soft dirty status.
2889e99668a5SLiam R. Howlett 	 * Otherwise user-space soft-dirty page tracker won't
2890e99668a5SLiam R. Howlett 	 * be able to distinguish situation when vma area unmapped,
2891e99668a5SLiam R. Howlett 	 * then new mapped in-place (which must be aimed as
2892e99668a5SLiam R. Howlett 	 * a completely new data area).
2893e99668a5SLiam R. Howlett 	 */
28941c71222eSSuren Baghdasaryan 	vm_flags_set(vma, VM_SOFTDIRTY);
2895e99668a5SLiam R. Howlett 
2896e99668a5SLiam R. Howlett 	vma_set_page_prot(vma);
2897e99668a5SLiam R. Howlett 
2898e99668a5SLiam R. Howlett 	validate_mm(mm);
2899e99668a5SLiam R. Howlett 	return addr;
2900e99668a5SLiam R. Howlett 
2901deb0f656SCarlos Llamas close_and_free_vma:
2902cc8d1b09SLiam R. Howlett 	if (file && vma->vm_ops && vma->vm_ops->close)
2903deb0f656SCarlos Llamas 		vma->vm_ops->close(vma);
2904cc8d1b09SLiam R. Howlett 
2905cc8d1b09SLiam R. Howlett 	if (file || vma->vm_file) {
2906e99668a5SLiam R. Howlett unmap_and_free_vma:
2907e99668a5SLiam R. Howlett 		fput(vma->vm_file);
2908e99668a5SLiam R. Howlett 		vma->vm_file = NULL;
2909e99668a5SLiam R. Howlett 
2910fd892593SLiam R. Howlett 		vma_iter_set(&vmi, vma->vm_end);
2911e99668a5SLiam R. Howlett 		/* Undo any partial mapping done by a device driver. */
2912fd892593SLiam R. Howlett 		unmap_region(mm, &vmi.mas, vma, prev, next, vma->vm_start,
2913fd892593SLiam R. Howlett 			     vma->vm_end, vma->vm_end, true);
2914cc8d1b09SLiam R. Howlett 	}
2915cc674ab3SLi Zetao 	if (file && (vm_flags & VM_SHARED))
2916e99668a5SLiam R. Howlett 		mapping_unmap_writable(file->f_mapping);
2917e99668a5SLiam R. Howlett free_vma:
2918e99668a5SLiam R. Howlett 	vm_area_free(vma);
2919e99668a5SLiam R. Howlett unacct_error:
2920e99668a5SLiam R. Howlett 	if (charged)
2921e99668a5SLiam R. Howlett 		vm_unacct_memory(charged);
2922e99668a5SLiam R. Howlett 	validate_mm(mm);
2923e99668a5SLiam R. Howlett 	return error;
2924e99668a5SLiam R. Howlett }
2925e99668a5SLiam R. Howlett 
__vm_munmap(unsigned long start,size_t len,bool unlock)2926408579cdSLiam R. Howlett static int __vm_munmap(unsigned long start, size_t len, bool unlock)
2927a46ef99dSLinus Torvalds {
2928a46ef99dSLinus Torvalds 	int ret;
2929bfce281cSAl Viro 	struct mm_struct *mm = current->mm;
2930897ab3e0SMike Rapoport 	LIST_HEAD(uf);
2931183654ceSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, start);
2932a46ef99dSLinus Torvalds 
2933d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2934ae798783SMichal Hocko 		return -EINTR;
2935ae798783SMichal Hocko 
2936408579cdSLiam R. Howlett 	ret = do_vmi_munmap(&vmi, mm, start, len, &uf, unlock);
2937408579cdSLiam R. Howlett 	if (ret || !unlock)
2938d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
2939dd2283f2SYang Shi 
2940897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
2941a46ef99dSLinus Torvalds 	return ret;
2942a46ef99dSLinus Torvalds }
2943dd2283f2SYang Shi 
vm_munmap(unsigned long start,size_t len)2944dd2283f2SYang Shi int vm_munmap(unsigned long start, size_t len)
2945dd2283f2SYang Shi {
2946dd2283f2SYang Shi 	return __vm_munmap(start, len, false);
2947dd2283f2SYang Shi }
2948a46ef99dSLinus Torvalds EXPORT_SYMBOL(vm_munmap);
2949a46ef99dSLinus Torvalds 
SYSCALL_DEFINE2(munmap,unsigned long,addr,size_t,len)29506a6160a7SHeiko Carstens SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
29511da177e4SLinus Torvalds {
2952ce18d171SCatalin Marinas 	addr = untagged_addr(addr);
2953dd2283f2SYang Shi 	return __vm_munmap(addr, len, true);
29541da177e4SLinus Torvalds }
29551da177e4SLinus Torvalds 
2956c8d78c18SKirill A. Shutemov 
2957c8d78c18SKirill A. Shutemov /*
2958c8d78c18SKirill A. Shutemov  * Emulation of deprecated remap_file_pages() syscall.
2959c8d78c18SKirill A. Shutemov  */
SYSCALL_DEFINE5(remap_file_pages,unsigned long,start,unsigned long,size,unsigned long,prot,unsigned long,pgoff,unsigned long,flags)2960c8d78c18SKirill A. Shutemov SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2961c8d78c18SKirill A. Shutemov 		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2962c8d78c18SKirill A. Shutemov {
2963c8d78c18SKirill A. Shutemov 
2964c8d78c18SKirill A. Shutemov 	struct mm_struct *mm = current->mm;
2965c8d78c18SKirill A. Shutemov 	struct vm_area_struct *vma;
2966c8d78c18SKirill A. Shutemov 	unsigned long populate = 0;
2967c8d78c18SKirill A. Shutemov 	unsigned long ret = -EINVAL;
2968c8d78c18SKirill A. Shutemov 	struct file *file;
2969c8d78c18SKirill A. Shutemov 
2970ee65728eSMike Rapoport 	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2971c8d78c18SKirill A. Shutemov 		     current->comm, current->pid);
2972c8d78c18SKirill A. Shutemov 
2973c8d78c18SKirill A. Shutemov 	if (prot)
2974c8d78c18SKirill A. Shutemov 		return ret;
2975c8d78c18SKirill A. Shutemov 	start = start & PAGE_MASK;
2976c8d78c18SKirill A. Shutemov 	size = size & PAGE_MASK;
2977c8d78c18SKirill A. Shutemov 
2978c8d78c18SKirill A. Shutemov 	if (start + size <= start)
2979c8d78c18SKirill A. Shutemov 		return ret;
2980c8d78c18SKirill A. Shutemov 
2981c8d78c18SKirill A. Shutemov 	/* Does pgoff wrap? */
2982c8d78c18SKirill A. Shutemov 	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2983c8d78c18SKirill A. Shutemov 		return ret;
2984c8d78c18SKirill A. Shutemov 
2985d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2986dc0ef0dfSMichal Hocko 		return -EINTR;
2987dc0ef0dfSMichal Hocko 
29889b593cb2SLiam R. Howlett 	vma = vma_lookup(mm, start);
2989c8d78c18SKirill A. Shutemov 
2990c8d78c18SKirill A. Shutemov 	if (!vma || !(vma->vm_flags & VM_SHARED))
2991c8d78c18SKirill A. Shutemov 		goto out;
2992c8d78c18SKirill A. Shutemov 
299348f7df32SKirill A. Shutemov 	if (start + size > vma->vm_end) {
2994763ecb03SLiam R. Howlett 		VMA_ITERATOR(vmi, mm, vma->vm_end);
2995763ecb03SLiam R. Howlett 		struct vm_area_struct *next, *prev = vma;
299648f7df32SKirill A. Shutemov 
2997763ecb03SLiam R. Howlett 		for_each_vma_range(vmi, next, start + size) {
299848f7df32SKirill A. Shutemov 			/* hole between vmas ? */
2999763ecb03SLiam R. Howlett 			if (next->vm_start != prev->vm_end)
300048f7df32SKirill A. Shutemov 				goto out;
300148f7df32SKirill A. Shutemov 
300248f7df32SKirill A. Shutemov 			if (next->vm_file != vma->vm_file)
300348f7df32SKirill A. Shutemov 				goto out;
300448f7df32SKirill A. Shutemov 
300548f7df32SKirill A. Shutemov 			if (next->vm_flags != vma->vm_flags)
300648f7df32SKirill A. Shutemov 				goto out;
300748f7df32SKirill A. Shutemov 
30081db43d3fSLiam Howlett 			if (start + size <= next->vm_end)
30091db43d3fSLiam Howlett 				break;
30101db43d3fSLiam Howlett 
3011763ecb03SLiam R. Howlett 			prev = next;
301248f7df32SKirill A. Shutemov 		}
301348f7df32SKirill A. Shutemov 
301448f7df32SKirill A. Shutemov 		if (!next)
3015c8d78c18SKirill A. Shutemov 			goto out;
3016c8d78c18SKirill A. Shutemov 	}
3017c8d78c18SKirill A. Shutemov 
3018c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
3019c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
3020c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
3021c8d78c18SKirill A. Shutemov 
3022c8d78c18SKirill A. Shutemov 	flags &= MAP_NONBLOCK;
3023c8d78c18SKirill A. Shutemov 	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
3024fce000b1SLiam Howlett 	if (vma->vm_flags & VM_LOCKED)
3025c8d78c18SKirill A. Shutemov 		flags |= MAP_LOCKED;
302648f7df32SKirill A. Shutemov 
3027c8d78c18SKirill A. Shutemov 	file = get_file(vma->vm_file);
302845e55300SPeter Collingbourne 	ret = do_mmap(vma->vm_file, start, size,
3029592b5fadSYu-cheng Yu 			prot, flags, 0, pgoff, &populate, NULL);
3030c8d78c18SKirill A. Shutemov 	fput(file);
3031c8d78c18SKirill A. Shutemov out:
3032d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
3033c8d78c18SKirill A. Shutemov 	if (populate)
3034c8d78c18SKirill A. Shutemov 		mm_populate(ret, populate);
3035c8d78c18SKirill A. Shutemov 	if (!IS_ERR_VALUE(ret))
3036c8d78c18SKirill A. Shutemov 		ret = 0;
3037c8d78c18SKirill A. Shutemov 	return ret;
3038c8d78c18SKirill A. Shutemov }
3039c8d78c18SKirill A. Shutemov 
30401da177e4SLinus Torvalds /*
304127b26701SLiam R. Howlett  * do_vma_munmap() - Unmap a full or partial vma.
304227b26701SLiam R. Howlett  * @vmi: The vma iterator pointing at the vma
304327b26701SLiam R. Howlett  * @vma: The first vma to be munmapped
304427b26701SLiam R. Howlett  * @start: the start of the address to unmap
304527b26701SLiam R. Howlett  * @end: The end of the address to unmap
30462e7ce7d3SLiam R. Howlett  * @uf: The userfaultfd list_head
3047408579cdSLiam R. Howlett  * @unlock: Drop the lock on success
30482e7ce7d3SLiam R. Howlett  *
304927b26701SLiam R. Howlett  * unmaps a VMA mapping when the vma iterator is already in position.
305027b26701SLiam R. Howlett  * Does not handle alignment.
3051408579cdSLiam R. Howlett  *
3052408579cdSLiam R. Howlett  * Return: 0 on success drops the lock of so directed, error on failure and will
3053408579cdSLiam R. Howlett  * still hold the lock.
30541da177e4SLinus Torvalds  */
do_vma_munmap(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long start,unsigned long end,struct list_head * uf,bool unlock)305527b26701SLiam R. Howlett int do_vma_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
3056408579cdSLiam R. Howlett 		unsigned long start, unsigned long end, struct list_head *uf,
3057408579cdSLiam R. Howlett 		bool unlock)
30582e7ce7d3SLiam R. Howlett {
30592e7ce7d3SLiam R. Howlett 	struct mm_struct *mm = vma->vm_mm;
30602e7ce7d3SLiam R. Howlett 
306127b26701SLiam R. Howlett 	arch_unmap(mm, start, end);
3062b5641a5dSLinus Torvalds 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
30632e7ce7d3SLiam R. Howlett }
30642e7ce7d3SLiam R. Howlett 
30652e7ce7d3SLiam R. Howlett /*
30662e7ce7d3SLiam R. Howlett  * do_brk_flags() - Increase the brk vma if the flags match.
306792fed820SLiam R. Howlett  * @vmi: The vma iterator
30682e7ce7d3SLiam R. Howlett  * @addr: The start address
30692e7ce7d3SLiam R. Howlett  * @len: The length of the increase
30702e7ce7d3SLiam R. Howlett  * @vma: The vma,
30712e7ce7d3SLiam R. Howlett  * @flags: The VMA Flags
30722e7ce7d3SLiam R. Howlett  *
30732e7ce7d3SLiam R. Howlett  * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
30742e7ce7d3SLiam R. Howlett  * do not match then create a new anonymous VMA.  Eventually we may be able to
30752e7ce7d3SLiam R. Howlett  * do some brk-specific accounting here.
30762e7ce7d3SLiam R. Howlett  */
do_brk_flags(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long addr,unsigned long len,unsigned long flags)307792fed820SLiam R. Howlett static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
3078763ecb03SLiam R. Howlett 		unsigned long addr, unsigned long len, unsigned long flags)
30791da177e4SLinus Torvalds {
30801da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
3081287051b1SLiam R. Howlett 	struct vma_prepare vp;
30822e7ce7d3SLiam R. Howlett 
30832e7ce7d3SLiam R. Howlett 	/*
30842e7ce7d3SLiam R. Howlett 	 * Check against address space limits by the changed size
30852e7ce7d3SLiam R. Howlett 	 * Note: This happens *after* clearing old mappings in some code paths.
30862e7ce7d3SLiam R. Howlett 	 */
308716e72e9bSDenys Vlasenko 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
308884638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
30891da177e4SLinus Torvalds 		return -ENOMEM;
30901da177e4SLinus Torvalds 
30911da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
30921da177e4SLinus Torvalds 		return -ENOMEM;
30931da177e4SLinus Torvalds 
3094191c5424SAl Viro 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
30951da177e4SLinus Torvalds 		return -ENOMEM;
30961da177e4SLinus Torvalds 
30971da177e4SLinus Torvalds 	/*
30982e7ce7d3SLiam R. Howlett 	 * Expand the existing vma if possible; Note that singular lists do not
30992e7ce7d3SLiam R. Howlett 	 * occur after forking, so the expand will only happen on new VMAs.
31001da177e4SLinus Torvalds 	 */
31016c28ca64SLiam Howlett 	if (vma && vma->vm_end == addr && !vma_policy(vma) &&
31026c28ca64SLiam Howlett 	    can_vma_merge_after(vma, flags, NULL, NULL,
31036c28ca64SLiam Howlett 				addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
3104b5df0922SLiam R. Howlett 		vma_iter_config(vmi, vma->vm_start, addr + len);
3105b5df0922SLiam R. Howlett 		if (vma_iter_prealloc(vmi, vma))
3106675eaca1SAlistair Popple 			goto unacct_fail;
310728c5609fSLiam Howlett 
3108c9d6e982SSuren Baghdasaryan 		vma_start_write(vma);
3109c9d6e982SSuren Baghdasaryan 
3110287051b1SLiam R. Howlett 		init_vma_prep(&vp, vma);
3111287051b1SLiam R. Howlett 		vma_prepare(&vp);
3112ccf1d78dSSuren Baghdasaryan 		vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
31132e7ce7d3SLiam R. Howlett 		vma->vm_end = addr + len;
31141c71222eSSuren Baghdasaryan 		vm_flags_set(vma, VM_SOFTDIRTY);
311592fed820SLiam R. Howlett 		vma_iter_store(vmi, vma);
31162e7ce7d3SLiam R. Howlett 
3117287051b1SLiam R. Howlett 		vma_complete(&vp, vmi, mm);
31182e7ce7d3SLiam R. Howlett 		khugepaged_enter_vma(vma, flags);
31192e7ce7d3SLiam R. Howlett 		goto out;
31202e7ce7d3SLiam R. Howlett 	}
31212e7ce7d3SLiam R. Howlett 
3122b5df0922SLiam R. Howlett 	if (vma)
3123b5df0922SLiam R. Howlett 		vma_iter_next_range(vmi);
31242e7ce7d3SLiam R. Howlett 	/* create a vma struct for an anonymous mapping */
31252e7ce7d3SLiam R. Howlett 	vma = vm_area_alloc(mm);
31262e7ce7d3SLiam R. Howlett 	if (!vma)
3127675eaca1SAlistair Popple 		goto unacct_fail;
31281da177e4SLinus Torvalds 
3129bfd40eafSKirill A. Shutemov 	vma_set_anonymous(vma);
31301da177e4SLinus Torvalds 	vma->vm_start = addr;
31311da177e4SLinus Torvalds 	vma->vm_end = addr + len;
31322e7ce7d3SLiam R. Howlett 	vma->vm_pgoff = addr >> PAGE_SHIFT;
31331c71222eSSuren Baghdasaryan 	vm_flags_init(vma, flags);
31343ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(flags);
3135ad9f0063SSuren Baghdasaryan 	vma_start_write(vma);
313692fed820SLiam R. Howlett 	if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
31372e7ce7d3SLiam R. Howlett 		goto mas_store_fail;
3138d4af56c5SLiam R. Howlett 
31392e7ce7d3SLiam R. Howlett 	mm->map_count++;
31402574d5e4SLiam R. Howlett 	validate_mm(mm);
3141d7597f59SStefan Roesch 	ksm_add_vma(vma);
31421da177e4SLinus Torvalds out:
31433af9e859SEric B Munson 	perf_event_mmap(vma);
31441da177e4SLinus Torvalds 	mm->total_vm += len >> PAGE_SHIFT;
314584638335SKonstantin Khlebnikov 	mm->data_vm += len >> PAGE_SHIFT;
3146128557ffSMichel Lespinasse 	if (flags & VM_LOCKED)
3147ba470de4SRik van Riel 		mm->locked_vm += (len >> PAGE_SHIFT);
31481c71222eSSuren Baghdasaryan 	vm_flags_set(vma, VM_SOFTDIRTY);
31495d22fc25SLinus Torvalds 	return 0;
3150d4af56c5SLiam R. Howlett 
31512e7ce7d3SLiam R. Howlett mas_store_fail:
3152d4af56c5SLiam R. Howlett 	vm_area_free(vma);
3153675eaca1SAlistair Popple unacct_fail:
31542e7ce7d3SLiam R. Howlett 	vm_unacct_memory(len >> PAGE_SHIFT);
31552e7ce7d3SLiam R. Howlett 	return -ENOMEM;
31561da177e4SLinus Torvalds }
31571da177e4SLinus Torvalds 
vm_brk_flags(unsigned long addr,unsigned long request,unsigned long flags)3158bb177a73SMichal Hocko int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3159e4eb1ff6SLinus Torvalds {
3160e4eb1ff6SLinus Torvalds 	struct mm_struct *mm = current->mm;
31612e7ce7d3SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
3162bb177a73SMichal Hocko 	unsigned long len;
31635d22fc25SLinus Torvalds 	int ret;
3164128557ffSMichel Lespinasse 	bool populate;
3165897ab3e0SMike Rapoport 	LIST_HEAD(uf);
316692fed820SLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
3167e4eb1ff6SLinus Torvalds 
3168bb177a73SMichal Hocko 	len = PAGE_ALIGN(request);
3169bb177a73SMichal Hocko 	if (len < request)
3170bb177a73SMichal Hocko 		return -ENOMEM;
3171bb177a73SMichal Hocko 	if (!len)
3172bb177a73SMichal Hocko 		return 0;
3173bb177a73SMichal Hocko 
31742e7ce7d3SLiam R. Howlett 	/* Until we need other flags, refuse anything except VM_EXEC. */
31752e7ce7d3SLiam R. Howlett 	if ((flags & (~VM_EXEC)) != 0)
31762e7ce7d3SLiam R. Howlett 		return -EINVAL;
31772e7ce7d3SLiam R. Howlett 
3178e0f81ab1SSebastian Ott 	if (mmap_write_lock_killable(mm))
3179e0f81ab1SSebastian Ott 		return -EINTR;
3180e0f81ab1SSebastian Ott 
31812e7ce7d3SLiam R. Howlett 	ret = check_brk_limits(addr, len);
31822e7ce7d3SLiam R. Howlett 	if (ret)
31832e7ce7d3SLiam R. Howlett 		goto limits_failed;
31842e7ce7d3SLiam R. Howlett 
3185183654ceSLiam R. Howlett 	ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
31862e7ce7d3SLiam R. Howlett 	if (ret)
31872e7ce7d3SLiam R. Howlett 		goto munmap_failed;
31882e7ce7d3SLiam R. Howlett 
318992fed820SLiam R. Howlett 	vma = vma_prev(&vmi);
319092fed820SLiam R. Howlett 	ret = do_brk_flags(&vmi, vma, addr, len, flags);
3191128557ffSMichel Lespinasse 	populate = ((mm->def_flags & VM_LOCKED) != 0);
3192d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
3193897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
31945d22fc25SLinus Torvalds 	if (populate && !ret)
3195128557ffSMichel Lespinasse 		mm_populate(addr, len);
3196e4eb1ff6SLinus Torvalds 	return ret;
31972e7ce7d3SLiam R. Howlett 
31982e7ce7d3SLiam R. Howlett munmap_failed:
31992e7ce7d3SLiam R. Howlett limits_failed:
32002e7ce7d3SLiam R. Howlett 	mmap_write_unlock(mm);
32012e7ce7d3SLiam R. Howlett 	return ret;
3202e4eb1ff6SLinus Torvalds }
320316e72e9bSDenys Vlasenko EXPORT_SYMBOL(vm_brk_flags);
320416e72e9bSDenys Vlasenko 
vm_brk(unsigned long addr,unsigned long len)320516e72e9bSDenys Vlasenko int vm_brk(unsigned long addr, unsigned long len)
320616e72e9bSDenys Vlasenko {
320716e72e9bSDenys Vlasenko 	return vm_brk_flags(addr, len, 0);
320816e72e9bSDenys Vlasenko }
3209e4eb1ff6SLinus Torvalds EXPORT_SYMBOL(vm_brk);
32101da177e4SLinus Torvalds 
32111da177e4SLinus Torvalds /* Release all mmaps. */
exit_mmap(struct mm_struct * mm)32121da177e4SLinus Torvalds void exit_mmap(struct mm_struct *mm)
32131da177e4SLinus Torvalds {
3214d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
3215ba470de4SRik van Riel 	struct vm_area_struct *vma;
32161da177e4SLinus Torvalds 	unsigned long nr_accounted = 0;
3217763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
3218763ecb03SLiam R. Howlett 	int count = 0;
32191da177e4SLinus Torvalds 
3220d6dd61c8SJeremy Fitzhardinge 	/* mm's last user has gone, and its about to be pulled down */
3221cddb8a5cSAndrea Arcangeli 	mmu_notifier_release(mm);
3222d6dd61c8SJeremy Fitzhardinge 
3223bf3980c8SSuren Baghdasaryan 	mmap_read_lock(mm);
32249480c53eSJeremy Fitzhardinge 	arch_exit_mmap(mm);
32259480c53eSJeremy Fitzhardinge 
3226763ecb03SLiam R. Howlett 	vma = mas_find(&mas, ULONG_MAX);
322764591e86SSuren Baghdasaryan 	if (!vma) {
322864591e86SSuren Baghdasaryan 		/* Can happen if dup_mmap() received an OOM */
3229bf3980c8SSuren Baghdasaryan 		mmap_read_unlock(mm);
32309480c53eSJeremy Fitzhardinge 		return;
323164591e86SSuren Baghdasaryan 	}
32329480c53eSJeremy Fitzhardinge 
32331da177e4SLinus Torvalds 	lru_add_drain();
32341da177e4SLinus Torvalds 	flush_cache_mm(mm);
3235d8b45053SWill Deacon 	tlb_gather_mmu_fullmm(&tlb, mm);
3236901608d9SOleg Nesterov 	/* update_hiwater_rss(mm) here? but nobody should be looking */
3237763ecb03SLiam R. Howlett 	/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
3238fd892593SLiam R. Howlett 	unmap_vmas(&tlb, &mas, vma, 0, ULONG_MAX, ULONG_MAX, false);
3239bf3980c8SSuren Baghdasaryan 	mmap_read_unlock(mm);
3240bf3980c8SSuren Baghdasaryan 
3241bf3980c8SSuren Baghdasaryan 	/*
3242bf3980c8SSuren Baghdasaryan 	 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
3243b3541d91SSuren Baghdasaryan 	 * because the memory has been already freed.
3244bf3980c8SSuren Baghdasaryan 	 */
3245bf3980c8SSuren Baghdasaryan 	set_bit(MMF_OOM_SKIP, &mm->flags);
3246bf3980c8SSuren Baghdasaryan 	mmap_write_lock(mm);
32473dd44325SLiam R. Howlett 	mt_clear_in_rcu(&mm->mm_mt);
3248fd892593SLiam R. Howlett 	mas_set(&mas, vma->vm_end);
3249fd892593SLiam R. Howlett 	free_pgtables(&tlb, &mas, vma, FIRST_USER_ADDRESS,
325098e51a22SSuren Baghdasaryan 		      USER_PGTABLES_CEILING, true);
3251ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
32521da177e4SLinus Torvalds 
3253763ecb03SLiam R. Howlett 	/*
3254763ecb03SLiam R. Howlett 	 * Walk the list again, actually closing and freeing it, with preemption
3255763ecb03SLiam R. Howlett 	 * enabled, without holding any MM locks besides the unreachable
3256763ecb03SLiam R. Howlett 	 * mmap_write_lock.
3257763ecb03SLiam R. Howlett 	 */
3258fd892593SLiam R. Howlett 	mas_set(&mas, vma->vm_end);
3259763ecb03SLiam R. Howlett 	do {
32604f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
32614f74d2c8SLinus Torvalds 			nr_accounted += vma_pages(vma);
32620d2ebf9cSSuren Baghdasaryan 		remove_vma(vma, true);
3263763ecb03SLiam R. Howlett 		count++;
32640a3b3c25SPaul E. McKenney 		cond_resched();
3265763ecb03SLiam R. Howlett 	} while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);
3266763ecb03SLiam R. Howlett 
3267763ecb03SLiam R. Howlett 	BUG_ON(count != mm->map_count);
3268d4af56c5SLiam R. Howlett 
3269d4af56c5SLiam R. Howlett 	trace_exit_mmap(mm);
3270d4af56c5SLiam R. Howlett 	__mt_destroy(&mm->mm_mt);
327164591e86SSuren Baghdasaryan 	mmap_write_unlock(mm);
32724f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
32731da177e4SLinus Torvalds }
32741da177e4SLinus Torvalds 
32751da177e4SLinus Torvalds /* Insert vm structure into process list sorted by address
32761da177e4SLinus Torvalds  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3277c8c06efaSDavidlohr Bueso  * then i_mmap_rwsem is taken here.
32781da177e4SLinus Torvalds  */
insert_vm_struct(struct mm_struct * mm,struct vm_area_struct * vma)32791da177e4SLinus Torvalds int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
32801da177e4SLinus Torvalds {
3281d4af56c5SLiam R. Howlett 	unsigned long charged = vma_pages(vma);
32821da177e4SLinus Torvalds 
3283d4af56c5SLiam R. Howlett 
3284d0601a50SLiam R. Howlett 	if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3285c9d13f5fSChen Gang 		return -ENOMEM;
3286d4af56c5SLiam R. Howlett 
3287c9d13f5fSChen Gang 	if ((vma->vm_flags & VM_ACCOUNT) &&
3288d4af56c5SLiam R. Howlett 	     security_vm_enough_memory_mm(mm, charged))
3289c9d13f5fSChen Gang 		return -ENOMEM;
3290c9d13f5fSChen Gang 
32911da177e4SLinus Torvalds 	/*
32921da177e4SLinus Torvalds 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
32931da177e4SLinus Torvalds 	 * until its first write fault, when page's anon_vma and index
32941da177e4SLinus Torvalds 	 * are set.  But now set the vm_pgoff it will almost certainly
32951da177e4SLinus Torvalds 	 * end up with (unless mremap moves it elsewhere before that
32961da177e4SLinus Torvalds 	 * first wfault), so /proc/pid/maps tells a consistent story.
32971da177e4SLinus Torvalds 	 *
32981da177e4SLinus Torvalds 	 * By setting it to reflect the virtual start address of the
32991da177e4SLinus Torvalds 	 * vma, merges and splits can happen in a seamless way, just
33001da177e4SLinus Torvalds 	 * using the existing file pgoff checks and manipulations.
33018332326eSLiao Pingfang 	 * Similarly in do_mmap and in do_brk_flags.
33021da177e4SLinus Torvalds 	 */
33038a9cc3b5SOleg Nesterov 	if (vma_is_anonymous(vma)) {
33041da177e4SLinus Torvalds 		BUG_ON(vma->anon_vma);
33051da177e4SLinus Torvalds 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
33061da177e4SLinus Torvalds 	}
33072b144498SSrikar Dronamraju 
3308763ecb03SLiam R. Howlett 	if (vma_link(mm, vma)) {
3309d4af56c5SLiam R. Howlett 		vm_unacct_memory(charged);
3310d4af56c5SLiam R. Howlett 		return -ENOMEM;
3311d4af56c5SLiam R. Howlett 	}
3312d4af56c5SLiam R. Howlett 
33131da177e4SLinus Torvalds 	return 0;
33141da177e4SLinus Torvalds }
33151da177e4SLinus Torvalds 
33161da177e4SLinus Torvalds /*
33171da177e4SLinus Torvalds  * Copy the vma structure to a new location in the same mm,
33181da177e4SLinus Torvalds  * prior to moving page table entries, to effect an mremap move.
33191da177e4SLinus Torvalds  */
copy_vma(struct vm_area_struct ** vmap,unsigned long addr,unsigned long len,pgoff_t pgoff,bool * need_rmap_locks)33201da177e4SLinus Torvalds struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
332138a76013SMichel Lespinasse 	unsigned long addr, unsigned long len, pgoff_t pgoff,
332238a76013SMichel Lespinasse 	bool *need_rmap_locks)
33231da177e4SLinus Torvalds {
33241da177e4SLinus Torvalds 	struct vm_area_struct *vma = *vmap;
33251da177e4SLinus Torvalds 	unsigned long vma_start = vma->vm_start;
33261da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
33271da177e4SLinus Torvalds 	struct vm_area_struct *new_vma, *prev;
3328948f017bSAndrea Arcangeli 	bool faulted_in_anon_vma = true;
3329076f16bfSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, addr);
33301da177e4SLinus Torvalds 
33311da177e4SLinus Torvalds 	/*
33321da177e4SLinus Torvalds 	 * If anonymous vma has not yet been faulted, update new pgoff
33331da177e4SLinus Torvalds 	 * to match new location, to increase its chance of merging.
33341da177e4SLinus Torvalds 	 */
3335ce75799bSOleg Nesterov 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
33361da177e4SLinus Torvalds 		pgoff = addr >> PAGE_SHIFT;
3337948f017bSAndrea Arcangeli 		faulted_in_anon_vma = false;
3338948f017bSAndrea Arcangeli 	}
33391da177e4SLinus Torvalds 
3340763ecb03SLiam R. Howlett 	new_vma = find_vma_prev(mm, addr, &prev);
3341763ecb03SLiam R. Howlett 	if (new_vma && new_vma->vm_start < addr + len)
33426597d783SHugh Dickins 		return NULL;	/* should never get here */
3343524e00b3SLiam R. Howlett 
33449760ebffSLiam R. Howlett 	new_vma = vma_merge(&vmi, mm, prev, addr, addr + len, vma->vm_flags,
334519a809afSAndrea Arcangeli 			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
33465c26f6acSSuren Baghdasaryan 			    vma->vm_userfaultfd_ctx, anon_vma_name(vma));
33471da177e4SLinus Torvalds 	if (new_vma) {
33481da177e4SLinus Torvalds 		/*
33491da177e4SLinus Torvalds 		 * Source vma may have been merged into new_vma
33501da177e4SLinus Torvalds 		 */
3351948f017bSAndrea Arcangeli 		if (unlikely(vma_start >= new_vma->vm_start &&
3352948f017bSAndrea Arcangeli 			     vma_start < new_vma->vm_end)) {
3353948f017bSAndrea Arcangeli 			/*
3354948f017bSAndrea Arcangeli 			 * The only way we can get a vma_merge with
3355948f017bSAndrea Arcangeli 			 * self during an mremap is if the vma hasn't
3356948f017bSAndrea Arcangeli 			 * been faulted in yet and we were allowed to
3357948f017bSAndrea Arcangeli 			 * reset the dst vma->vm_pgoff to the
3358948f017bSAndrea Arcangeli 			 * destination address of the mremap to allow
3359948f017bSAndrea Arcangeli 			 * the merge to happen. mremap must change the
3360948f017bSAndrea Arcangeli 			 * vm_pgoff linearity between src and dst vmas
3361948f017bSAndrea Arcangeli 			 * (in turn preventing a vma_merge) to be
3362948f017bSAndrea Arcangeli 			 * safe. It is only safe to keep the vm_pgoff
3363948f017bSAndrea Arcangeli 			 * linear if there are no pages mapped yet.
3364948f017bSAndrea Arcangeli 			 */
336581d1b09cSSasha Levin 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
336638a76013SMichel Lespinasse 			*vmap = vma = new_vma;
3367108d6642SMichel Lespinasse 		}
336838a76013SMichel Lespinasse 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
33691da177e4SLinus Torvalds 	} else {
33703928d4f5SLinus Torvalds 		new_vma = vm_area_dup(vma);
3371e3975891SChen Gang 		if (!new_vma)
3372e3975891SChen Gang 			goto out;
33731da177e4SLinus Torvalds 		new_vma->vm_start = addr;
33741da177e4SLinus Torvalds 		new_vma->vm_end = addr + len;
33751da177e4SLinus Torvalds 		new_vma->vm_pgoff = pgoff;
3376ef0855d3SOleg Nesterov 		if (vma_dup_policy(vma, new_vma))
3377523d4e20SMichel Lespinasse 			goto out_free_vma;
3378523d4e20SMichel Lespinasse 		if (anon_vma_clone(new_vma, vma))
3379523d4e20SMichel Lespinasse 			goto out_free_mempol;
3380e9714acfSKonstantin Khlebnikov 		if (new_vma->vm_file)
33811da177e4SLinus Torvalds 			get_file(new_vma->vm_file);
33821da177e4SLinus Torvalds 		if (new_vma->vm_ops && new_vma->vm_ops->open)
33831da177e4SLinus Torvalds 			new_vma->vm_ops->open(new_vma);
3384763ecb03SLiam R. Howlett 		if (vma_link(mm, new_vma))
3385524e00b3SLiam R. Howlett 			goto out_vma_link;
338638a76013SMichel Lespinasse 		*need_rmap_locks = false;
33871da177e4SLinus Torvalds 	}
33881da177e4SLinus Torvalds 	return new_vma;
33895beb4930SRik van Riel 
3390524e00b3SLiam R. Howlett out_vma_link:
3391524e00b3SLiam R. Howlett 	if (new_vma->vm_ops && new_vma->vm_ops->close)
3392524e00b3SLiam R. Howlett 		new_vma->vm_ops->close(new_vma);
339392b73996SLiam Howlett 
339492b73996SLiam Howlett 	if (new_vma->vm_file)
339592b73996SLiam Howlett 		fput(new_vma->vm_file);
339692b73996SLiam Howlett 
339792b73996SLiam Howlett 	unlink_anon_vmas(new_vma);
33985beb4930SRik van Riel out_free_mempol:
3399ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new_vma));
34005beb4930SRik van Riel out_free_vma:
34013928d4f5SLinus Torvalds 	vm_area_free(new_vma);
3402e3975891SChen Gang out:
34035beb4930SRik van Riel 	return NULL;
34041da177e4SLinus Torvalds }
3405119f657cSakpm@osdl.org 
3406119f657cSakpm@osdl.org /*
3407119f657cSakpm@osdl.org  * Return true if the calling process may expand its vm space by the passed
3408119f657cSakpm@osdl.org  * number of pages
3409119f657cSakpm@osdl.org  */
may_expand_vm(struct mm_struct * mm,vm_flags_t flags,unsigned long npages)341084638335SKonstantin Khlebnikov bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3411119f657cSakpm@osdl.org {
341284638335SKonstantin Khlebnikov 	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
341384638335SKonstantin Khlebnikov 		return false;
3414119f657cSakpm@osdl.org 
3415d977d56cSKonstantin Khlebnikov 	if (is_data_mapping(flags) &&
3416d977d56cSKonstantin Khlebnikov 	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3417f4fcd558SKonstantin Khlebnikov 		/* Workaround for Valgrind */
3418f4fcd558SKonstantin Khlebnikov 		if (rlimit(RLIMIT_DATA) == 0 &&
3419f4fcd558SKonstantin Khlebnikov 		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3420f4fcd558SKonstantin Khlebnikov 			return true;
342157a7702bSDavid Woodhouse 
342257a7702bSDavid Woodhouse 		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3423d977d56cSKonstantin Khlebnikov 			     current->comm, current->pid,
3424d977d56cSKonstantin Khlebnikov 			     (mm->data_vm + npages) << PAGE_SHIFT,
342557a7702bSDavid Woodhouse 			     rlimit(RLIMIT_DATA),
342657a7702bSDavid Woodhouse 			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
342757a7702bSDavid Woodhouse 
342857a7702bSDavid Woodhouse 		if (!ignore_rlimit_data)
3429d977d56cSKonstantin Khlebnikov 			return false;
3430d977d56cSKonstantin Khlebnikov 	}
3431119f657cSakpm@osdl.org 
343284638335SKonstantin Khlebnikov 	return true;
343384638335SKonstantin Khlebnikov }
343484638335SKonstantin Khlebnikov 
vm_stat_account(struct mm_struct * mm,vm_flags_t flags,long npages)343584638335SKonstantin Khlebnikov void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
343684638335SKonstantin Khlebnikov {
34377866076bSPeng Liu 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
343884638335SKonstantin Khlebnikov 
3439d977d56cSKonstantin Khlebnikov 	if (is_exec_mapping(flags))
344084638335SKonstantin Khlebnikov 		mm->exec_vm += npages;
3441d977d56cSKonstantin Khlebnikov 	else if (is_stack_mapping(flags))
344284638335SKonstantin Khlebnikov 		mm->stack_vm += npages;
3443d977d56cSKonstantin Khlebnikov 	else if (is_data_mapping(flags))
344484638335SKonstantin Khlebnikov 		mm->data_vm += npages;
3445119f657cSakpm@osdl.org }
3446fa5dc22fSRoland McGrath 
3447b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3448a62c34bdSAndy Lutomirski 
3449a62c34bdSAndy Lutomirski /*
3450a62c34bdSAndy Lutomirski  * Having a close hook prevents vma merging regardless of flags.
3451a62c34bdSAndy Lutomirski  */
special_mapping_close(struct vm_area_struct * vma)3452a62c34bdSAndy Lutomirski static void special_mapping_close(struct vm_area_struct *vma)
3453a62c34bdSAndy Lutomirski {
3454a62c34bdSAndy Lutomirski }
3455a62c34bdSAndy Lutomirski 
special_mapping_name(struct vm_area_struct * vma)3456a62c34bdSAndy Lutomirski static const char *special_mapping_name(struct vm_area_struct *vma)
3457a62c34bdSAndy Lutomirski {
3458a62c34bdSAndy Lutomirski 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3459a62c34bdSAndy Lutomirski }
3460a62c34bdSAndy Lutomirski 
special_mapping_mremap(struct vm_area_struct * new_vma)346114d07113SBrian Geffon static int special_mapping_mremap(struct vm_area_struct *new_vma)
3462b059a453SDmitry Safonov {
3463b059a453SDmitry Safonov 	struct vm_special_mapping *sm = new_vma->vm_private_data;
3464b059a453SDmitry Safonov 
3465280e87e9SDmitry Safonov 	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3466280e87e9SDmitry Safonov 		return -EFAULT;
3467280e87e9SDmitry Safonov 
3468b059a453SDmitry Safonov 	if (sm->mremap)
3469b059a453SDmitry Safonov 		return sm->mremap(sm, new_vma);
3470280e87e9SDmitry Safonov 
3471b059a453SDmitry Safonov 	return 0;
3472b059a453SDmitry Safonov }
3473b059a453SDmitry Safonov 
special_mapping_split(struct vm_area_struct * vma,unsigned long addr)3474871402e0SDmitry Safonov static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3475871402e0SDmitry Safonov {
3476871402e0SDmitry Safonov 	/*
3477871402e0SDmitry Safonov 	 * Forbid splitting special mappings - kernel has expectations over
3478871402e0SDmitry Safonov 	 * the number of pages in mapping. Together with VM_DONTEXPAND
3479871402e0SDmitry Safonov 	 * the size of vma should stay the same over the special mapping's
3480871402e0SDmitry Safonov 	 * lifetime.
3481871402e0SDmitry Safonov 	 */
3482871402e0SDmitry Safonov 	return -EINVAL;
3483871402e0SDmitry Safonov }
3484871402e0SDmitry Safonov 
3485a62c34bdSAndy Lutomirski static const struct vm_operations_struct special_mapping_vmops = {
3486a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3487a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3488b059a453SDmitry Safonov 	.mremap = special_mapping_mremap,
3489a62c34bdSAndy Lutomirski 	.name = special_mapping_name,
3490af34ebebSDmitry Safonov 	/* vDSO code relies that VVAR can't be accessed remotely */
3491af34ebebSDmitry Safonov 	.access = NULL,
3492871402e0SDmitry Safonov 	.may_split = special_mapping_split,
3493a62c34bdSAndy Lutomirski };
3494a62c34bdSAndy Lutomirski 
3495a62c34bdSAndy Lutomirski static const struct vm_operations_struct legacy_special_mapping_vmops = {
3496a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3497a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3498a62c34bdSAndy Lutomirski };
3499fa5dc22fSRoland McGrath 
special_mapping_fault(struct vm_fault * vmf)3500b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3501fa5dc22fSRoland McGrath {
350211bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
3503b1d0e4f5SNick Piggin 	pgoff_t pgoff;
3504fa5dc22fSRoland McGrath 	struct page **pages;
3505fa5dc22fSRoland McGrath 
3506f872f540SAndy Lutomirski 	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3507a62c34bdSAndy Lutomirski 		pages = vma->vm_private_data;
3508f872f540SAndy Lutomirski 	} else {
3509f872f540SAndy Lutomirski 		struct vm_special_mapping *sm = vma->vm_private_data;
3510f872f540SAndy Lutomirski 
3511f872f540SAndy Lutomirski 		if (sm->fault)
351211bac800SDave Jiang 			return sm->fault(sm, vmf->vma, vmf);
3513f872f540SAndy Lutomirski 
3514f872f540SAndy Lutomirski 		pages = sm->pages;
3515f872f540SAndy Lutomirski 	}
3516a62c34bdSAndy Lutomirski 
35178a9cc3b5SOleg Nesterov 	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3518b1d0e4f5SNick Piggin 		pgoff--;
3519fa5dc22fSRoland McGrath 
3520fa5dc22fSRoland McGrath 	if (*pages) {
3521fa5dc22fSRoland McGrath 		struct page *page = *pages;
3522fa5dc22fSRoland McGrath 		get_page(page);
3523b1d0e4f5SNick Piggin 		vmf->page = page;
3524b1d0e4f5SNick Piggin 		return 0;
3525fa5dc22fSRoland McGrath 	}
3526fa5dc22fSRoland McGrath 
3527b1d0e4f5SNick Piggin 	return VM_FAULT_SIGBUS;
3528fa5dc22fSRoland McGrath }
3529fa5dc22fSRoland McGrath 
__install_special_mapping(struct mm_struct * mm,unsigned long addr,unsigned long len,unsigned long vm_flags,void * priv,const struct vm_operations_struct * ops)3530a62c34bdSAndy Lutomirski static struct vm_area_struct *__install_special_mapping(
3531a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3532fa5dc22fSRoland McGrath 	unsigned long addr, unsigned long len,
353327f28b97SChen Gang 	unsigned long vm_flags, void *priv,
353427f28b97SChen Gang 	const struct vm_operations_struct *ops)
3535fa5dc22fSRoland McGrath {
3536462e635eSTavis Ormandy 	int ret;
3537fa5dc22fSRoland McGrath 	struct vm_area_struct *vma;
3538fa5dc22fSRoland McGrath 
3539490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
3540fa5dc22fSRoland McGrath 	if (unlikely(vma == NULL))
35413935ed6aSStefani Seibold 		return ERR_PTR(-ENOMEM);
3542fa5dc22fSRoland McGrath 
3543fa5dc22fSRoland McGrath 	vma->vm_start = addr;
3544fa5dc22fSRoland McGrath 	vma->vm_end = addr + len;
3545fa5dc22fSRoland McGrath 
3546e430a95aSSuren Baghdasaryan 	vm_flags_init(vma, (vm_flags | mm->def_flags |
3547e430a95aSSuren Baghdasaryan 		      VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
35483ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3549fa5dc22fSRoland McGrath 
3550a62c34bdSAndy Lutomirski 	vma->vm_ops = ops;
3551a62c34bdSAndy Lutomirski 	vma->vm_private_data = priv;
3552fa5dc22fSRoland McGrath 
3553462e635eSTavis Ormandy 	ret = insert_vm_struct(mm, vma);
3554462e635eSTavis Ormandy 	if (ret)
3555462e635eSTavis Ormandy 		goto out;
3556fa5dc22fSRoland McGrath 
355784638335SKonstantin Khlebnikov 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3558fa5dc22fSRoland McGrath 
3559cdd6c482SIngo Molnar 	perf_event_mmap(vma);
3560089dd79dSPeter Zijlstra 
35613935ed6aSStefani Seibold 	return vma;
3562462e635eSTavis Ormandy 
3563462e635eSTavis Ormandy out:
35643928d4f5SLinus Torvalds 	vm_area_free(vma);
35653935ed6aSStefani Seibold 	return ERR_PTR(ret);
35663935ed6aSStefani Seibold }
35673935ed6aSStefani Seibold 
vma_is_special_mapping(const struct vm_area_struct * vma,const struct vm_special_mapping * sm)35682eefd878SDmitry Safonov bool vma_is_special_mapping(const struct vm_area_struct *vma,
35692eefd878SDmitry Safonov 	const struct vm_special_mapping *sm)
35702eefd878SDmitry Safonov {
35712eefd878SDmitry Safonov 	return vma->vm_private_data == sm &&
35722eefd878SDmitry Safonov 		(vma->vm_ops == &special_mapping_vmops ||
35732eefd878SDmitry Safonov 		 vma->vm_ops == &legacy_special_mapping_vmops);
35742eefd878SDmitry Safonov }
35752eefd878SDmitry Safonov 
3576a62c34bdSAndy Lutomirski /*
3577c1e8d7c6SMichel Lespinasse  * Called with mm->mmap_lock held for writing.
3578a62c34bdSAndy Lutomirski  * Insert a new vma covering the given region, with the given flags.
3579a62c34bdSAndy Lutomirski  * Its pages are supplied by the given array of struct page *.
3580a62c34bdSAndy Lutomirski  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3581a62c34bdSAndy Lutomirski  * The region past the last page supplied will always produce SIGBUS.
3582a62c34bdSAndy Lutomirski  * The array pointer and the pages it points to are assumed to stay alive
3583a62c34bdSAndy Lutomirski  * for as long as this mapping might exist.
3584a62c34bdSAndy Lutomirski  */
_install_special_mapping(struct mm_struct * mm,unsigned long addr,unsigned long len,unsigned long vm_flags,const struct vm_special_mapping * spec)3585a62c34bdSAndy Lutomirski struct vm_area_struct *_install_special_mapping(
3586a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3587a62c34bdSAndy Lutomirski 	unsigned long addr, unsigned long len,
3588a62c34bdSAndy Lutomirski 	unsigned long vm_flags, const struct vm_special_mapping *spec)
3589a62c34bdSAndy Lutomirski {
359027f28b97SChen Gang 	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
359127f28b97SChen Gang 					&special_mapping_vmops);
3592a62c34bdSAndy Lutomirski }
3593a62c34bdSAndy Lutomirski 
install_special_mapping(struct mm_struct * mm,unsigned long addr,unsigned long len,unsigned long vm_flags,struct page ** pages)35943935ed6aSStefani Seibold int install_special_mapping(struct mm_struct *mm,
35953935ed6aSStefani Seibold 			    unsigned long addr, unsigned long len,
35963935ed6aSStefani Seibold 			    unsigned long vm_flags, struct page **pages)
35973935ed6aSStefani Seibold {
3598a62c34bdSAndy Lutomirski 	struct vm_area_struct *vma = __install_special_mapping(
359927f28b97SChen Gang 		mm, addr, len, vm_flags, (void *)pages,
360027f28b97SChen Gang 		&legacy_special_mapping_vmops);
36013935ed6aSStefani Seibold 
360214bd5b45SDuan Jiong 	return PTR_ERR_OR_ZERO(vma);
3603fa5dc22fSRoland McGrath }
36047906d00cSAndrea Arcangeli 
36057906d00cSAndrea Arcangeli static DEFINE_MUTEX(mm_all_locks_mutex);
36067906d00cSAndrea Arcangeli 
vm_lock_anon_vma(struct mm_struct * mm,struct anon_vma * anon_vma)3607454ed842SPeter Zijlstra static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
36087906d00cSAndrea Arcangeli {
3609f808c13fSDavidlohr Bueso 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
36107906d00cSAndrea Arcangeli 		/*
36117906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change from under us
36127906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
36137906d00cSAndrea Arcangeli 		 */
3614da1c55f1SMichel Lespinasse 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
36157906d00cSAndrea Arcangeli 		/*
36167906d00cSAndrea Arcangeli 		 * We can safely modify head.next after taking the
36175a505085SIngo Molnar 		 * anon_vma->root->rwsem. If some other vma in this mm shares
36187906d00cSAndrea Arcangeli 		 * the same anon_vma we won't take it again.
36197906d00cSAndrea Arcangeli 		 *
36207906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
36217906d00cSAndrea Arcangeli 		 * can't change from under us thanks to the
36225a505085SIngo Molnar 		 * anon_vma->root->rwsem.
36237906d00cSAndrea Arcangeli 		 */
36247906d00cSAndrea Arcangeli 		if (__test_and_set_bit(0, (unsigned long *)
3625f808c13fSDavidlohr Bueso 				       &anon_vma->root->rb_root.rb_root.rb_node))
36267906d00cSAndrea Arcangeli 			BUG();
36277906d00cSAndrea Arcangeli 	}
36287906d00cSAndrea Arcangeli }
36297906d00cSAndrea Arcangeli 
vm_lock_mapping(struct mm_struct * mm,struct address_space * mapping)3630454ed842SPeter Zijlstra static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
36317906d00cSAndrea Arcangeli {
36327906d00cSAndrea Arcangeli 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
36337906d00cSAndrea Arcangeli 		/*
36347906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change from under us because
36357906d00cSAndrea Arcangeli 		 * we hold the mm_all_locks_mutex.
36367906d00cSAndrea Arcangeli 		 *
36377906d00cSAndrea Arcangeli 		 * Operations on ->flags have to be atomic because
36387906d00cSAndrea Arcangeli 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
36397906d00cSAndrea Arcangeli 		 * mm_all_locks_mutex, there may be other cpus
36407906d00cSAndrea Arcangeli 		 * changing other bitflags in parallel to us.
36417906d00cSAndrea Arcangeli 		 */
36427906d00cSAndrea Arcangeli 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
36437906d00cSAndrea Arcangeli 			BUG();
3644da1c55f1SMichel Lespinasse 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
36457906d00cSAndrea Arcangeli 	}
36467906d00cSAndrea Arcangeli }
36477906d00cSAndrea Arcangeli 
36487906d00cSAndrea Arcangeli /*
36497906d00cSAndrea Arcangeli  * This operation locks against the VM for all pte/vma/mm related
36507906d00cSAndrea Arcangeli  * operations that could ever happen on a certain mm. This includes
36517906d00cSAndrea Arcangeli  * vmtruncate, try_to_unmap, and all page faults.
36527906d00cSAndrea Arcangeli  *
3653c1e8d7c6SMichel Lespinasse  * The caller must take the mmap_lock in write mode before calling
36547906d00cSAndrea Arcangeli  * mm_take_all_locks(). The caller isn't allowed to release the
3655c1e8d7c6SMichel Lespinasse  * mmap_lock until mm_drop_all_locks() returns.
36567906d00cSAndrea Arcangeli  *
3657c1e8d7c6SMichel Lespinasse  * mmap_lock in write mode is required in order to block all operations
36587906d00cSAndrea Arcangeli  * that could modify pagetables and free pages without need of
365927ba0644SKirill A. Shutemov  * altering the vma layout. It's also needed in write mode to avoid new
36607906d00cSAndrea Arcangeli  * anon_vmas to be associated with existing vmas.
36617906d00cSAndrea Arcangeli  *
36627906d00cSAndrea Arcangeli  * A single task can't take more than one mm_take_all_locks() in a row
36637906d00cSAndrea Arcangeli  * or it would deadlock.
36647906d00cSAndrea Arcangeli  *
3665bf181b9fSMichel Lespinasse  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
36667906d00cSAndrea Arcangeli  * mapping->flags avoid to take the same lock twice, if more than one
36677906d00cSAndrea Arcangeli  * vma in this mm is backed by the same anon_vma or address_space.
36687906d00cSAndrea Arcangeli  *
366988f306b6SKirill A. Shutemov  * We take locks in following order, accordingly to comment at beginning
367088f306b6SKirill A. Shutemov  * of mm/rmap.c:
367188f306b6SKirill A. Shutemov  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
367288f306b6SKirill A. Shutemov  *     hugetlb mapping);
3673eeff9a5dSSuren Baghdasaryan  *   - all vmas marked locked
367488f306b6SKirill A. Shutemov  *   - all i_mmap_rwsem locks;
367588f306b6SKirill A. Shutemov  *   - all anon_vma->rwseml
367688f306b6SKirill A. Shutemov  *
367788f306b6SKirill A. Shutemov  * We can take all locks within these types randomly because the VM code
367888f306b6SKirill A. Shutemov  * doesn't nest them and we protected from parallel mm_take_all_locks() by
367988f306b6SKirill A. Shutemov  * mm_all_locks_mutex.
36807906d00cSAndrea Arcangeli  *
36817906d00cSAndrea Arcangeli  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
36827906d00cSAndrea Arcangeli  * that may have to take thousand of locks.
36837906d00cSAndrea Arcangeli  *
36847906d00cSAndrea Arcangeli  * mm_take_all_locks() can fail if it's interrupted by signals.
36857906d00cSAndrea Arcangeli  */
mm_take_all_locks(struct mm_struct * mm)36867906d00cSAndrea Arcangeli int mm_take_all_locks(struct mm_struct *mm)
36877906d00cSAndrea Arcangeli {
36887906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
36895beb4930SRik van Riel 	struct anon_vma_chain *avc;
3690763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
36917906d00cSAndrea Arcangeli 
3692325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
36937906d00cSAndrea Arcangeli 
36947906d00cSAndrea Arcangeli 	mutex_lock(&mm_all_locks_mutex);
36957906d00cSAndrea Arcangeli 
369690717566SJann Horn 	/*
369790717566SJann Horn 	 * vma_start_write() does not have a complement in mm_drop_all_locks()
369890717566SJann Horn 	 * because vma_start_write() is always asymmetrical; it marks a VMA as
369990717566SJann Horn 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
370090717566SJann Horn 	 * is reached.
370190717566SJann Horn 	 */
3702763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
37037906d00cSAndrea Arcangeli 		if (signal_pending(current))
37047906d00cSAndrea Arcangeli 			goto out_unlock;
3705eeff9a5dSSuren Baghdasaryan 		vma_start_write(vma);
3706eeff9a5dSSuren Baghdasaryan 	}
3707eeff9a5dSSuren Baghdasaryan 
3708eeff9a5dSSuren Baghdasaryan 	mas_set(&mas, 0);
3709eeff9a5dSSuren Baghdasaryan 	mas_for_each(&mas, vma, ULONG_MAX) {
3710eeff9a5dSSuren Baghdasaryan 		if (signal_pending(current))
3711eeff9a5dSSuren Baghdasaryan 			goto out_unlock;
371288f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
371388f306b6SKirill A. Shutemov 				is_vm_hugetlb_page(vma))
371488f306b6SKirill A. Shutemov 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
371588f306b6SKirill A. Shutemov 	}
371688f306b6SKirill A. Shutemov 
3717763ecb03SLiam R. Howlett 	mas_set(&mas, 0);
3718763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
371988f306b6SKirill A. Shutemov 		if (signal_pending(current))
372088f306b6SKirill A. Shutemov 			goto out_unlock;
372188f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
372288f306b6SKirill A. Shutemov 				!is_vm_hugetlb_page(vma))
3723454ed842SPeter Zijlstra 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
37247906d00cSAndrea Arcangeli 	}
37257cd5a02fSPeter Zijlstra 
3726763ecb03SLiam R. Howlett 	mas_set(&mas, 0);
3727763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
37287cd5a02fSPeter Zijlstra 		if (signal_pending(current))
37297cd5a02fSPeter Zijlstra 			goto out_unlock;
37307cd5a02fSPeter Zijlstra 		if (vma->anon_vma)
37315beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
37325beb4930SRik van Riel 				vm_lock_anon_vma(mm, avc->anon_vma);
37337cd5a02fSPeter Zijlstra 	}
37347cd5a02fSPeter Zijlstra 
3735584cff54SKautuk Consul 	return 0;
37367906d00cSAndrea Arcangeli 
37377906d00cSAndrea Arcangeli out_unlock:
37387906d00cSAndrea Arcangeli 	mm_drop_all_locks(mm);
3739584cff54SKautuk Consul 	return -EINTR;
37407906d00cSAndrea Arcangeli }
37417906d00cSAndrea Arcangeli 
vm_unlock_anon_vma(struct anon_vma * anon_vma)37427906d00cSAndrea Arcangeli static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
37437906d00cSAndrea Arcangeli {
3744f808c13fSDavidlohr Bueso 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
37457906d00cSAndrea Arcangeli 		/*
37467906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change to 0 from under
37477906d00cSAndrea Arcangeli 		 * us because we hold the mm_all_locks_mutex.
37487906d00cSAndrea Arcangeli 		 *
37497906d00cSAndrea Arcangeli 		 * We must however clear the bitflag before unlocking
3750bf181b9fSMichel Lespinasse 		 * the vma so the users using the anon_vma->rb_root will
37517906d00cSAndrea Arcangeli 		 * never see our bitflag.
37527906d00cSAndrea Arcangeli 		 *
37537906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
37547906d00cSAndrea Arcangeli 		 * can't change from under us until we release the
37555a505085SIngo Molnar 		 * anon_vma->root->rwsem.
37567906d00cSAndrea Arcangeli 		 */
37577906d00cSAndrea Arcangeli 		if (!__test_and_clear_bit(0, (unsigned long *)
3758f808c13fSDavidlohr Bueso 					  &anon_vma->root->rb_root.rb_root.rb_node))
37597906d00cSAndrea Arcangeli 			BUG();
376008b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
37617906d00cSAndrea Arcangeli 	}
37627906d00cSAndrea Arcangeli }
37637906d00cSAndrea Arcangeli 
vm_unlock_mapping(struct address_space * mapping)37647906d00cSAndrea Arcangeli static void vm_unlock_mapping(struct address_space *mapping)
37657906d00cSAndrea Arcangeli {
37667906d00cSAndrea Arcangeli 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
37677906d00cSAndrea Arcangeli 		/*
37687906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
37697906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
37707906d00cSAndrea Arcangeli 		 */
377183cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
37727906d00cSAndrea Arcangeli 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
37737906d00cSAndrea Arcangeli 					&mapping->flags))
37747906d00cSAndrea Arcangeli 			BUG();
37757906d00cSAndrea Arcangeli 	}
37767906d00cSAndrea Arcangeli }
37777906d00cSAndrea Arcangeli 
37787906d00cSAndrea Arcangeli /*
3779c1e8d7c6SMichel Lespinasse  * The mmap_lock cannot be released by the caller until
37807906d00cSAndrea Arcangeli  * mm_drop_all_locks() returns.
37817906d00cSAndrea Arcangeli  */
mm_drop_all_locks(struct mm_struct * mm)37827906d00cSAndrea Arcangeli void mm_drop_all_locks(struct mm_struct *mm)
37837906d00cSAndrea Arcangeli {
37847906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
37855beb4930SRik van Riel 	struct anon_vma_chain *avc;
3786763ecb03SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
37877906d00cSAndrea Arcangeli 
3788325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
37897906d00cSAndrea Arcangeli 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
37907906d00cSAndrea Arcangeli 
3791763ecb03SLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
37927906d00cSAndrea Arcangeli 		if (vma->anon_vma)
37935beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
37945beb4930SRik van Riel 				vm_unlock_anon_vma(avc->anon_vma);
37957906d00cSAndrea Arcangeli 		if (vma->vm_file && vma->vm_file->f_mapping)
37967906d00cSAndrea Arcangeli 			vm_unlock_mapping(vma->vm_file->f_mapping);
37977906d00cSAndrea Arcangeli 	}
37987906d00cSAndrea Arcangeli 
37997906d00cSAndrea Arcangeli 	mutex_unlock(&mm_all_locks_mutex);
38007906d00cSAndrea Arcangeli }
38018feae131SDavid Howells 
38028feae131SDavid Howells /*
38033edf41d8Sseokhoon.yoon  * initialise the percpu counter for VM
38048feae131SDavid Howells  */
mmap_init(void)38058feae131SDavid Howells void __init mmap_init(void)
38068feae131SDavid Howells {
380700a62ce9SKOSAKI Motohiro 	int ret;
380800a62ce9SKOSAKI Motohiro 
3809908c7f19STejun Heo 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
381000a62ce9SKOSAKI Motohiro 	VM_BUG_ON(ret);
38118feae131SDavid Howells }
3812c9b1d098SAndrew Shewmaker 
3813c9b1d098SAndrew Shewmaker /*
3814c9b1d098SAndrew Shewmaker  * Initialise sysctl_user_reserve_kbytes.
3815c9b1d098SAndrew Shewmaker  *
3816c9b1d098SAndrew Shewmaker  * This is intended to prevent a user from starting a single memory hogging
3817c9b1d098SAndrew Shewmaker  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3818c9b1d098SAndrew Shewmaker  * mode.
3819c9b1d098SAndrew Shewmaker  *
3820c9b1d098SAndrew Shewmaker  * The default value is min(3% of free memory, 128MB)
3821c9b1d098SAndrew Shewmaker  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3822c9b1d098SAndrew Shewmaker  */
init_user_reserve(void)38231640879aSAndrew Shewmaker static int init_user_reserve(void)
3824c9b1d098SAndrew Shewmaker {
3825c9b1d098SAndrew Shewmaker 	unsigned long free_kbytes;
3826c9b1d098SAndrew Shewmaker 
3827b1773e0eSZhangPeng 	free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
3828c9b1d098SAndrew Shewmaker 
3829c9b1d098SAndrew Shewmaker 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3830c9b1d098SAndrew Shewmaker 	return 0;
3831c9b1d098SAndrew Shewmaker }
3832a64fb3cdSPaul Gortmaker subsys_initcall(init_user_reserve);
38334eeab4f5SAndrew Shewmaker 
38344eeab4f5SAndrew Shewmaker /*
38354eeab4f5SAndrew Shewmaker  * Initialise sysctl_admin_reserve_kbytes.
38364eeab4f5SAndrew Shewmaker  *
38374eeab4f5SAndrew Shewmaker  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
38384eeab4f5SAndrew Shewmaker  * to log in and kill a memory hogging process.
38394eeab4f5SAndrew Shewmaker  *
38404eeab4f5SAndrew Shewmaker  * Systems with more than 256MB will reserve 8MB, enough to recover
38414eeab4f5SAndrew Shewmaker  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
38424eeab4f5SAndrew Shewmaker  * only reserve 3% of free pages by default.
38434eeab4f5SAndrew Shewmaker  */
init_admin_reserve(void)38441640879aSAndrew Shewmaker static int init_admin_reserve(void)
38454eeab4f5SAndrew Shewmaker {
38464eeab4f5SAndrew Shewmaker 	unsigned long free_kbytes;
38474eeab4f5SAndrew Shewmaker 
3848b1773e0eSZhangPeng 	free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
38494eeab4f5SAndrew Shewmaker 
38504eeab4f5SAndrew Shewmaker 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
38514eeab4f5SAndrew Shewmaker 	return 0;
38524eeab4f5SAndrew Shewmaker }
3853a64fb3cdSPaul Gortmaker subsys_initcall(init_admin_reserve);
38541640879aSAndrew Shewmaker 
38551640879aSAndrew Shewmaker /*
38561640879aSAndrew Shewmaker  * Reinititalise user and admin reserves if memory is added or removed.
38571640879aSAndrew Shewmaker  *
38581640879aSAndrew Shewmaker  * The default user reserve max is 128MB, and the default max for the
38591640879aSAndrew Shewmaker  * admin reserve is 8MB. These are usually, but not always, enough to
38601640879aSAndrew Shewmaker  * enable recovery from a memory hogging process using login/sshd, a shell,
38611640879aSAndrew Shewmaker  * and tools like top. It may make sense to increase or even disable the
38621640879aSAndrew Shewmaker  * reserve depending on the existence of swap or variations in the recovery
38631640879aSAndrew Shewmaker  * tools. So, the admin may have changed them.
38641640879aSAndrew Shewmaker  *
38651640879aSAndrew Shewmaker  * If memory is added and the reserves have been eliminated or increased above
38661640879aSAndrew Shewmaker  * the default max, then we'll trust the admin.
38671640879aSAndrew Shewmaker  *
38681640879aSAndrew Shewmaker  * If memory is removed and there isn't enough free memory, then we
38691640879aSAndrew Shewmaker  * need to reset the reserves.
38701640879aSAndrew Shewmaker  *
38711640879aSAndrew Shewmaker  * Otherwise keep the reserve set by the admin.
38721640879aSAndrew Shewmaker  */
reserve_mem_notifier(struct notifier_block * nb,unsigned long action,void * data)38731640879aSAndrew Shewmaker static int reserve_mem_notifier(struct notifier_block *nb,
38741640879aSAndrew Shewmaker 			     unsigned long action, void *data)
38751640879aSAndrew Shewmaker {
38761640879aSAndrew Shewmaker 	unsigned long tmp, free_kbytes;
38771640879aSAndrew Shewmaker 
38781640879aSAndrew Shewmaker 	switch (action) {
38791640879aSAndrew Shewmaker 	case MEM_ONLINE:
38801640879aSAndrew Shewmaker 		/* Default max is 128MB. Leave alone if modified by operator. */
38811640879aSAndrew Shewmaker 		tmp = sysctl_user_reserve_kbytes;
38821640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 17))
38831640879aSAndrew Shewmaker 			init_user_reserve();
38841640879aSAndrew Shewmaker 
38851640879aSAndrew Shewmaker 		/* Default max is 8MB.  Leave alone if modified by operator. */
38861640879aSAndrew Shewmaker 		tmp = sysctl_admin_reserve_kbytes;
38871640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 13))
38881640879aSAndrew Shewmaker 			init_admin_reserve();
38891640879aSAndrew Shewmaker 
38901640879aSAndrew Shewmaker 		break;
38911640879aSAndrew Shewmaker 	case MEM_OFFLINE:
3892b1773e0eSZhangPeng 		free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
38931640879aSAndrew Shewmaker 
38941640879aSAndrew Shewmaker 		if (sysctl_user_reserve_kbytes > free_kbytes) {
38951640879aSAndrew Shewmaker 			init_user_reserve();
38961640879aSAndrew Shewmaker 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
38971640879aSAndrew Shewmaker 				sysctl_user_reserve_kbytes);
38981640879aSAndrew Shewmaker 		}
38991640879aSAndrew Shewmaker 
39001640879aSAndrew Shewmaker 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
39011640879aSAndrew Shewmaker 			init_admin_reserve();
39021640879aSAndrew Shewmaker 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
39031640879aSAndrew Shewmaker 				sysctl_admin_reserve_kbytes);
39041640879aSAndrew Shewmaker 		}
39051640879aSAndrew Shewmaker 		break;
39061640879aSAndrew Shewmaker 	default:
39071640879aSAndrew Shewmaker 		break;
39081640879aSAndrew Shewmaker 	}
39091640879aSAndrew Shewmaker 	return NOTIFY_OK;
39101640879aSAndrew Shewmaker }
39111640879aSAndrew Shewmaker 
init_reserve_notifier(void)39121640879aSAndrew Shewmaker static int __meminit init_reserve_notifier(void)
39131640879aSAndrew Shewmaker {
39141eeaa4fdSLiu Shixin 	if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
3915b1de0d13SMitchel Humpherys 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
39161640879aSAndrew Shewmaker 
39171640879aSAndrew Shewmaker 	return 0;
39181640879aSAndrew Shewmaker }
3919a64fb3cdSPaul Gortmaker subsys_initcall(init_reserve_notifier);
3920