xref: /linux/mm/mmap.c (revision e99668a56430a25a871113bcd3989ed20eae1cfc)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * mm/mmap.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  * Written by obz.
61da177e4SLinus Torvalds  *
7046c6884SAlan Cox  * Address space accounting code	<alan@lxorguk.ukuu.org.uk>
81da177e4SLinus Torvalds  */
91da177e4SLinus Torvalds 
10b1de0d13SMitchel Humpherys #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11b1de0d13SMitchel Humpherys 
12e8420a8eSCyril Hrubis #include <linux/kernel.h>
131da177e4SLinus Torvalds #include <linux/slab.h>
144af3c9ccSAlexey Dobriyan #include <linux/backing-dev.h>
151da177e4SLinus Torvalds #include <linux/mm.h>
1617fca131SArnd Bergmann #include <linux/mm_inline.h>
171da177e4SLinus Torvalds #include <linux/shm.h>
181da177e4SLinus Torvalds #include <linux/mman.h>
191da177e4SLinus Torvalds #include <linux/pagemap.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/syscalls.h>
22c59ede7bSRandy.Dunlap #include <linux/capability.h>
231da177e4SLinus Torvalds #include <linux/init.h>
241da177e4SLinus Torvalds #include <linux/file.h>
251da177e4SLinus Torvalds #include <linux/fs.h>
261da177e4SLinus Torvalds #include <linux/personality.h>
271da177e4SLinus Torvalds #include <linux/security.h>
281da177e4SLinus Torvalds #include <linux/hugetlb.h>
29c01d5b30SHugh Dickins #include <linux/shmem_fs.h>
301da177e4SLinus Torvalds #include <linux/profile.h>
31b95f1b31SPaul Gortmaker #include <linux/export.h>
321da177e4SLinus Torvalds #include <linux/mount.h>
331da177e4SLinus Torvalds #include <linux/mempolicy.h>
341da177e4SLinus Torvalds #include <linux/rmap.h>
35cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
3682f71ae4SKonstantin Khlebnikov #include <linux/mmdebug.h>
37cdd6c482SIngo Molnar #include <linux/perf_event.h>
38120a795dSAl Viro #include <linux/audit.h>
39b15d00b6SAndrea Arcangeli #include <linux/khugepaged.h>
402b144498SSrikar Dronamraju #include <linux/uprobes.h>
411640879aSAndrew Shewmaker #include <linux/notifier.h>
421640879aSAndrew Shewmaker #include <linux/memory.h>
43b1de0d13SMitchel Humpherys #include <linux/printk.h>
4419a809afSAndrea Arcangeli #include <linux/userfaultfd_k.h>
45d977d56cSKonstantin Khlebnikov #include <linux/moduleparam.h>
4662b5f7d0SDave Hansen #include <linux/pkeys.h>
4721292580SAndrea Arcangeli #include <linux/oom.h>
4804f5866eSAndrea Arcangeli #include <linux/sched/mm.h>
491da177e4SLinus Torvalds 
507c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
511da177e4SLinus Torvalds #include <asm/cacheflush.h>
521da177e4SLinus Torvalds #include <asm/tlb.h>
53d6dd61c8SJeremy Fitzhardinge #include <asm/mmu_context.h>
541da177e4SLinus Torvalds 
55df529cabSJaewon Kim #define CREATE_TRACE_POINTS
56df529cabSJaewon Kim #include <trace/events/mmap.h>
57df529cabSJaewon Kim 
5842b77728SJan Beulich #include "internal.h"
5942b77728SJan Beulich 
603a459756SKirill Korotaev #ifndef arch_mmap_check
613a459756SKirill Korotaev #define arch_mmap_check(addr, len, flags)	(0)
623a459756SKirill Korotaev #endif
633a459756SKirill Korotaev 
64d07e2259SDaniel Cashman #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
65d07e2259SDaniel Cashman const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
66d07e2259SDaniel Cashman const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
67d07e2259SDaniel Cashman int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
68d07e2259SDaniel Cashman #endif
69d07e2259SDaniel Cashman #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
70d07e2259SDaniel Cashman const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
71d07e2259SDaniel Cashman const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
72d07e2259SDaniel Cashman int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
73d07e2259SDaniel Cashman #endif
74d07e2259SDaniel Cashman 
75f4fcd558SKonstantin Khlebnikov static bool ignore_rlimit_data;
76d977d56cSKonstantin Khlebnikov core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
77d07e2259SDaniel Cashman 
78e0da382cSHugh Dickins static void unmap_region(struct mm_struct *mm,
79e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
80e0da382cSHugh Dickins 		unsigned long start, unsigned long end);
81e0da382cSHugh Dickins 
8264e45507SPeter Feiner static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
8364e45507SPeter Feiner {
8464e45507SPeter Feiner 	return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
8564e45507SPeter Feiner }
8664e45507SPeter Feiner 
8764e45507SPeter Feiner /* Update vma->vm_page_prot to reflect vma->vm_flags. */
8864e45507SPeter Feiner void vma_set_page_prot(struct vm_area_struct *vma)
8964e45507SPeter Feiner {
9064e45507SPeter Feiner 	unsigned long vm_flags = vma->vm_flags;
916d2329f8SAndrea Arcangeli 	pgprot_t vm_page_prot;
9264e45507SPeter Feiner 
936d2329f8SAndrea Arcangeli 	vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
946d2329f8SAndrea Arcangeli 	if (vma_wants_writenotify(vma, vm_page_prot)) {
9564e45507SPeter Feiner 		vm_flags &= ~VM_SHARED;
966d2329f8SAndrea Arcangeli 		vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
9764e45507SPeter Feiner 	}
98c1e8d7c6SMichel Lespinasse 	/* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
996d2329f8SAndrea Arcangeli 	WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
10064e45507SPeter Feiner }
10164e45507SPeter Feiner 
1021da177e4SLinus Torvalds /*
103c8c06efaSDavidlohr Bueso  * Requires inode->i_mapping->i_mmap_rwsem
1041da177e4SLinus Torvalds  */
1051da177e4SLinus Torvalds static void __remove_shared_vm_struct(struct vm_area_struct *vma,
1061da177e4SLinus Torvalds 		struct file *file, struct address_space *mapping)
1071da177e4SLinus Torvalds {
1081da177e4SLinus Torvalds 	if (vma->vm_flags & VM_SHARED)
1094bb5f5d9SDavid Herrmann 		mapping_unmap_writable(mapping);
1101da177e4SLinus Torvalds 
1111da177e4SLinus Torvalds 	flush_dcache_mmap_lock(mapping);
1126b2dbba8SMichel Lespinasse 	vma_interval_tree_remove(vma, &mapping->i_mmap);
1131da177e4SLinus Torvalds 	flush_dcache_mmap_unlock(mapping);
1141da177e4SLinus Torvalds }
1151da177e4SLinus Torvalds 
1161da177e4SLinus Torvalds /*
1176b2dbba8SMichel Lespinasse  * Unlink a file-based vm structure from its interval tree, to hide
118a8fb5618SHugh Dickins  * vma from rmap and vmtruncate before freeing its page tables.
1191da177e4SLinus Torvalds  */
120a8fb5618SHugh Dickins void unlink_file_vma(struct vm_area_struct *vma)
1211da177e4SLinus Torvalds {
1221da177e4SLinus Torvalds 	struct file *file = vma->vm_file;
1231da177e4SLinus Torvalds 
1241da177e4SLinus Torvalds 	if (file) {
1251da177e4SLinus Torvalds 		struct address_space *mapping = file->f_mapping;
12683cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
1271da177e4SLinus Torvalds 		__remove_shared_vm_struct(vma, file, mapping);
12883cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
1291da177e4SLinus Torvalds 	}
130a8fb5618SHugh Dickins }
131a8fb5618SHugh Dickins 
132a8fb5618SHugh Dickins /*
133a8fb5618SHugh Dickins  * Close a vm structure and free it, returning the next.
134a8fb5618SHugh Dickins  */
135a8fb5618SHugh Dickins static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
136a8fb5618SHugh Dickins {
137a8fb5618SHugh Dickins 	struct vm_area_struct *next = vma->vm_next;
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));
1453928d4f5SLinus Torvalds 	vm_area_free(vma);
146a8fb5618SHugh Dickins 	return next;
1471da177e4SLinus Torvalds }
1481da177e4SLinus Torvalds 
1492e7ce7d3SLiam R. Howlett /*
1502e7ce7d3SLiam R. Howlett  * check_brk_limits() - Use platform specific check of range & verify mlock
1512e7ce7d3SLiam R. Howlett  * limits.
1522e7ce7d3SLiam R. Howlett  * @addr: The address to check
1532e7ce7d3SLiam R. Howlett  * @len: The size of increase.
1542e7ce7d3SLiam R. Howlett  *
1552e7ce7d3SLiam R. Howlett  * Return: 0 on success.
1562e7ce7d3SLiam R. Howlett  */
1572e7ce7d3SLiam R. Howlett static int check_brk_limits(unsigned long addr, unsigned long len)
1582e7ce7d3SLiam R. Howlett {
1592e7ce7d3SLiam R. Howlett 	unsigned long mapped_addr;
1602e7ce7d3SLiam R. Howlett 
1612e7ce7d3SLiam R. Howlett 	mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
1622e7ce7d3SLiam R. Howlett 	if (IS_ERR_VALUE(mapped_addr))
1632e7ce7d3SLiam R. Howlett 		return mapped_addr;
1642e7ce7d3SLiam R. Howlett 
1652e7ce7d3SLiam R. Howlett 	return mlock_future_check(current->mm, current->mm->def_flags, len);
1662e7ce7d3SLiam R. Howlett }
1672e7ce7d3SLiam R. Howlett static int do_brk_munmap(struct ma_state *mas, struct vm_area_struct *vma,
1682e7ce7d3SLiam R. Howlett 			 unsigned long newbrk, unsigned long oldbrk,
169bb177a73SMichal Hocko 			 struct list_head *uf);
1702e7ce7d3SLiam R. Howlett static int do_brk_flags(struct ma_state *mas, struct vm_area_struct *brkvma,
1712e7ce7d3SLiam R. Howlett 			unsigned long addr, unsigned long request,
1722e7ce7d3SLiam R. Howlett 			unsigned long flags);
1736a6160a7SHeiko Carstens SYSCALL_DEFINE1(brk, unsigned long, brk)
1741da177e4SLinus Torvalds {
1759bc8039eSYang Shi 	unsigned long newbrk, oldbrk, origbrk;
1761da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1772e7ce7d3SLiam R. Howlett 	struct vm_area_struct *brkvma, *next = NULL;
178a5b4592cSJiri Kosina 	unsigned long min_brk;
179128557ffSMichel Lespinasse 	bool populate;
1809bc8039eSYang Shi 	bool downgraded = false;
181897ab3e0SMike Rapoport 	LIST_HEAD(uf);
1822e7ce7d3SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
1831da177e4SLinus Torvalds 
184d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
185dc0ef0dfSMichal Hocko 		return -EINTR;
1861da177e4SLinus Torvalds 
1879bc8039eSYang Shi 	origbrk = mm->brk;
1889bc8039eSYang Shi 
189a5b4592cSJiri Kosina #ifdef CONFIG_COMPAT_BRK
1905520e894SJiri Kosina 	/*
1915520e894SJiri Kosina 	 * CONFIG_COMPAT_BRK can still be overridden by setting
1925520e894SJiri Kosina 	 * randomize_va_space to 2, which will still cause mm->start_brk
1935520e894SJiri Kosina 	 * to be arbitrarily shifted
1945520e894SJiri Kosina 	 */
1954471a675SJiri Kosina 	if (current->brk_randomized)
1965520e894SJiri Kosina 		min_brk = mm->start_brk;
1975520e894SJiri Kosina 	else
1985520e894SJiri Kosina 		min_brk = mm->end_data;
199a5b4592cSJiri Kosina #else
200a5b4592cSJiri Kosina 	min_brk = mm->start_brk;
201a5b4592cSJiri Kosina #endif
202a5b4592cSJiri Kosina 	if (brk < min_brk)
2031da177e4SLinus Torvalds 		goto out;
2041e624196SRam Gupta 
2051e624196SRam Gupta 	/*
2061e624196SRam Gupta 	 * Check against rlimit here. If this check is done later after the test
2071e624196SRam Gupta 	 * of oldbrk with newbrk then it can escape the test and let the data
2081e624196SRam Gupta 	 * segment grow beyond its set limit the in case where the limit is
2091e624196SRam Gupta 	 * not page aligned -Ram Gupta
2101e624196SRam Gupta 	 */
2118764b338SCyrill Gorcunov 	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
2128764b338SCyrill Gorcunov 			      mm->end_data, mm->start_data))
2131e624196SRam Gupta 		goto out;
2141e624196SRam Gupta 
2151da177e4SLinus Torvalds 	newbrk = PAGE_ALIGN(brk);
2161da177e4SLinus Torvalds 	oldbrk = PAGE_ALIGN(mm->brk);
2179bc8039eSYang Shi 	if (oldbrk == newbrk) {
2189bc8039eSYang Shi 		mm->brk = brk;
2199bc8039eSYang Shi 		goto success;
2209bc8039eSYang Shi 	}
2211da177e4SLinus Torvalds 
2229bc8039eSYang Shi 	/*
2239bc8039eSYang Shi 	 * Always allow shrinking brk.
2242e7ce7d3SLiam R. Howlett 	 * do_brk_munmap() may downgrade mmap_lock to read.
2259bc8039eSYang Shi 	 */
2261da177e4SLinus Torvalds 	if (brk <= mm->brk) {
2279bc8039eSYang Shi 		int ret;
2289bc8039eSYang Shi 
2292e7ce7d3SLiam R. Howlett 		/* Search one past newbrk */
2302e7ce7d3SLiam R. Howlett 		mas_set(&mas, newbrk);
2312e7ce7d3SLiam R. Howlett 		brkvma = mas_find(&mas, oldbrk);
2322e7ce7d3SLiam R. Howlett 		BUG_ON(brkvma == NULL);
2332e7ce7d3SLiam R. Howlett 		if (brkvma->vm_start >= oldbrk)
2342e7ce7d3SLiam R. Howlett 			goto out; /* mapping intersects with an existing non-brk vma. */
2359bc8039eSYang Shi 		/*
2362e7ce7d3SLiam R. Howlett 		 * mm->brk must be protected by write mmap_lock.
2372e7ce7d3SLiam R. Howlett 		 * do_brk_munmap() may downgrade the lock,  so update it
2382e7ce7d3SLiam R. Howlett 		 * before calling do_brk_munmap().
2399bc8039eSYang Shi 		 */
2409bc8039eSYang Shi 		mm->brk = brk;
2412e7ce7d3SLiam R. Howlett 		mas.last = oldbrk - 1;
2422e7ce7d3SLiam R. Howlett 		ret = do_brk_munmap(&mas, brkvma, newbrk, oldbrk, &uf);
2432e7ce7d3SLiam R. Howlett 		if (ret == 1)  {
2442e7ce7d3SLiam R. Howlett 			downgraded = true;
2452e7ce7d3SLiam R. Howlett 			goto success;
2462e7ce7d3SLiam R. Howlett 		} else if (!ret)
2472e7ce7d3SLiam R. Howlett 			goto success;
2482e7ce7d3SLiam R. Howlett 
2499bc8039eSYang Shi 		mm->brk = origbrk;
2501da177e4SLinus Torvalds 		goto out;
2511da177e4SLinus Torvalds 	}
2521da177e4SLinus Torvalds 
2532e7ce7d3SLiam R. Howlett 	if (check_brk_limits(oldbrk, newbrk - oldbrk))
2542e7ce7d3SLiam R. Howlett 		goto out;
2552e7ce7d3SLiam R. Howlett 
2562e7ce7d3SLiam R. Howlett 	/*
2572e7ce7d3SLiam R. Howlett 	 * Only check if the next VMA is within the stack_guard_gap of the
2582e7ce7d3SLiam R. Howlett 	 * expansion area
2592e7ce7d3SLiam R. Howlett 	 */
2602e7ce7d3SLiam R. Howlett 	mas_set(&mas, oldbrk);
2612e7ce7d3SLiam R. Howlett 	next = mas_find(&mas, newbrk - 1 + PAGE_SIZE + stack_guard_gap);
2621be7107fSHugh Dickins 	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
2631da177e4SLinus Torvalds 		goto out;
2641da177e4SLinus Torvalds 
2652e7ce7d3SLiam R. Howlett 	brkvma = mas_prev(&mas, mm->start_brk);
2661da177e4SLinus Torvalds 	/* Ok, looks good - let it rip. */
2672e7ce7d3SLiam R. Howlett 	if (do_brk_flags(&mas, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
2681da177e4SLinus Torvalds 		goto out;
2692e7ce7d3SLiam R. Howlett 
2701da177e4SLinus Torvalds 	mm->brk = brk;
2719bc8039eSYang Shi 
2729bc8039eSYang Shi success:
273128557ffSMichel Lespinasse 	populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
2749bc8039eSYang Shi 	if (downgraded)
275d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
2769bc8039eSYang Shi 	else
277d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
278897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
279128557ffSMichel Lespinasse 	if (populate)
280128557ffSMichel Lespinasse 		mm_populate(oldbrk, newbrk - oldbrk);
281128557ffSMichel Lespinasse 	return brk;
282128557ffSMichel Lespinasse 
2831da177e4SLinus Torvalds out:
284d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
285b7204006SAdrian Huang 	return origbrk;
2861da177e4SLinus Torvalds }
2871da177e4SLinus Torvalds 
288d4af56c5SLiam R. Howlett #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
289d4af56c5SLiam R. Howlett extern void mt_validate(struct maple_tree *mt);
290d4af56c5SLiam R. Howlett extern void mt_dump(const struct maple_tree *mt);
2911da177e4SLinus Torvalds 
292d4af56c5SLiam R. Howlett /* Validate the maple tree */
293d4af56c5SLiam R. Howlett static void validate_mm_mt(struct mm_struct *mm)
294d4af56c5SLiam R. Howlett {
295d4af56c5SLiam R. Howlett 	struct maple_tree *mt = &mm->mm_mt;
296d4af56c5SLiam R. Howlett 	struct vm_area_struct *vma_mt, *vma = mm->mmap;
297d4af56c5SLiam R. Howlett 
298d4af56c5SLiam R. Howlett 	MA_STATE(mas, mt, 0, 0);
299d4af56c5SLiam R. Howlett 
300d4af56c5SLiam R. Howlett 	mt_validate(&mm->mm_mt);
301d4af56c5SLiam R. Howlett 	mas_for_each(&mas, vma_mt, ULONG_MAX) {
302d4af56c5SLiam R. Howlett 		if (xa_is_zero(vma_mt))
303d4af56c5SLiam R. Howlett 			continue;
304d4af56c5SLiam R. Howlett 
305d4af56c5SLiam R. Howlett 		if (!vma)
306d4af56c5SLiam R. Howlett 			break;
307d4af56c5SLiam R. Howlett 
308d4af56c5SLiam R. Howlett 		if ((vma != vma_mt) ||
309d4af56c5SLiam R. Howlett 		    (vma->vm_start != vma_mt->vm_start) ||
310d4af56c5SLiam R. Howlett 		    (vma->vm_end != vma_mt->vm_end) ||
311d4af56c5SLiam R. Howlett 		    (vma->vm_start != mas.index) ||
312d4af56c5SLiam R. Howlett 		    (vma->vm_end - 1 != mas.last)) {
313d4af56c5SLiam R. Howlett 			pr_emerg("issue in %s\n", current->comm);
314d4af56c5SLiam R. Howlett 			dump_stack();
315d4af56c5SLiam R. Howlett 			dump_vma(vma_mt);
316524e00b3SLiam R. Howlett 			pr_emerg("and vm_next\n");
317d4af56c5SLiam R. Howlett 			dump_vma(vma->vm_next);
318d4af56c5SLiam R. Howlett 			pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
319d4af56c5SLiam R. Howlett 				 mas.index, mas.last);
320d4af56c5SLiam R. Howlett 			pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
321d4af56c5SLiam R. Howlett 				 vma_mt->vm_start, vma_mt->vm_end);
322524e00b3SLiam R. Howlett 			if (vma->vm_prev) {
323524e00b3SLiam R. Howlett 				pr_emerg("ll prev: %p %lu - %lu\n",
324524e00b3SLiam R. Howlett 					 vma->vm_prev, vma->vm_prev->vm_start,
325524e00b3SLiam R. Howlett 					 vma->vm_prev->vm_end);
326524e00b3SLiam R. Howlett 			}
327524e00b3SLiam R. Howlett 			pr_emerg("ll vma: %p %lu - %lu\n", vma,
328d4af56c5SLiam R. Howlett 				 vma->vm_start, vma->vm_end);
329524e00b3SLiam R. Howlett 			if (vma->vm_next) {
330524e00b3SLiam R. Howlett 				pr_emerg("ll next: %p %lu - %lu\n",
331524e00b3SLiam R. Howlett 					 vma->vm_next, vma->vm_next->vm_start,
332524e00b3SLiam R. Howlett 					 vma->vm_next->vm_end);
333524e00b3SLiam R. Howlett 			}
334d4af56c5SLiam R. Howlett 
335d4af56c5SLiam R. Howlett 			mt_dump(mas.tree);
336d4af56c5SLiam R. Howlett 			if (vma_mt->vm_end != mas.last + 1) {
337d4af56c5SLiam R. Howlett 				pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
338d4af56c5SLiam R. Howlett 						mm, vma_mt->vm_start, vma_mt->vm_end,
339d4af56c5SLiam R. Howlett 						mas.index, mas.last);
340d4af56c5SLiam R. Howlett 				mt_dump(mas.tree);
341d4af56c5SLiam R. Howlett 			}
342d4af56c5SLiam R. Howlett 			VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
343d4af56c5SLiam R. Howlett 			if (vma_mt->vm_start != mas.index) {
344d4af56c5SLiam R. Howlett 				pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
345d4af56c5SLiam R. Howlett 						mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
346d4af56c5SLiam R. Howlett 				mt_dump(mas.tree);
347d4af56c5SLiam R. Howlett 			}
348d4af56c5SLiam R. Howlett 			VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
349d4af56c5SLiam R. Howlett 		}
350d4af56c5SLiam R. Howlett 		VM_BUG_ON(vma != vma_mt);
351d4af56c5SLiam R. Howlett 		vma = vma->vm_next;
352d4af56c5SLiam R. Howlett 
353d4af56c5SLiam R. Howlett 	}
354d4af56c5SLiam R. Howlett 	VM_BUG_ON(vma);
355d4af56c5SLiam R. Howlett }
3561da177e4SLinus Torvalds 
357eafd4dc4SRashika Kheria static void validate_mm(struct mm_struct *mm)
3581da177e4SLinus Torvalds {
3591da177e4SLinus Torvalds 	int bug = 0;
3601da177e4SLinus Torvalds 	int i = 0;
3615a0768f6SMichel Lespinasse 	unsigned long highest_address = 0;
362ed8ea815SMichel Lespinasse 	struct vm_area_struct *vma = mm->mmap;
363ff26f70fSAndrew Morton 
364524e00b3SLiam R. Howlett 	validate_mm_mt(mm);
365524e00b3SLiam R. Howlett 
366ed8ea815SMichel Lespinasse 	while (vma) {
367524e00b3SLiam R. Howlett #ifdef CONFIG_DEBUG_VM_RB
36812352d3cSKonstantin Khlebnikov 		struct anon_vma *anon_vma = vma->anon_vma;
369ed8ea815SMichel Lespinasse 		struct anon_vma_chain *avc;
370ff26f70fSAndrew Morton 
37112352d3cSKonstantin Khlebnikov 		if (anon_vma) {
37212352d3cSKonstantin Khlebnikov 			anon_vma_lock_read(anon_vma);
373ed8ea815SMichel Lespinasse 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
374ed8ea815SMichel Lespinasse 				anon_vma_interval_tree_verify(avc);
37512352d3cSKonstantin Khlebnikov 			anon_vma_unlock_read(anon_vma);
37612352d3cSKonstantin Khlebnikov 		}
377524e00b3SLiam R. Howlett #endif
37812352d3cSKonstantin Khlebnikov 
3791be7107fSHugh Dickins 		highest_address = vm_end_gap(vma);
380ed8ea815SMichel Lespinasse 		vma = vma->vm_next;
3811da177e4SLinus Torvalds 		i++;
3821da177e4SLinus Torvalds 	}
3835a0768f6SMichel Lespinasse 	if (i != mm->map_count) {
3848542bdfcSSasha Levin 		pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
3855a0768f6SMichel Lespinasse 		bug = 1;
3865a0768f6SMichel Lespinasse 	}
3875a0768f6SMichel Lespinasse 	if (highest_address != mm->highest_vm_end) {
3888542bdfcSSasha Levin 		pr_emerg("mm->highest_vm_end %lx, found %lx\n",
3895a0768f6SMichel Lespinasse 			  mm->highest_vm_end, highest_address);
3905a0768f6SMichel Lespinasse 		bug = 1;
3915a0768f6SMichel Lespinasse 	}
39296dad67fSSasha Levin 	VM_BUG_ON_MM(bug, mm);
3931da177e4SLinus Torvalds }
394524e00b3SLiam R. Howlett 
395524e00b3SLiam R. Howlett #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
396d4af56c5SLiam R. Howlett #define validate_mm_mt(root) do { } while (0)
3971da177e4SLinus Torvalds #define validate_mm(mm) do { } while (0)
398524e00b3SLiam R. Howlett #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
399d3737187SMichel Lespinasse 
400bf181b9fSMichel Lespinasse /*
401bf181b9fSMichel Lespinasse  * vma has some anon_vma assigned, and is already inserted on that
402bf181b9fSMichel Lespinasse  * anon_vma's interval trees.
403bf181b9fSMichel Lespinasse  *
404bf181b9fSMichel Lespinasse  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
405bf181b9fSMichel Lespinasse  * vma must be removed from the anon_vma's interval trees using
406bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_pre_update_vma().
407bf181b9fSMichel Lespinasse  *
408bf181b9fSMichel Lespinasse  * After the update, the vma will be reinserted using
409bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_post_update_vma().
410bf181b9fSMichel Lespinasse  *
411c1e8d7c6SMichel Lespinasse  * The entire update must be protected by exclusive mmap_lock and by
412bf181b9fSMichel Lespinasse  * the root anon_vma's mutex.
413bf181b9fSMichel Lespinasse  */
414bf181b9fSMichel Lespinasse static inline void
415bf181b9fSMichel Lespinasse anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
416bf181b9fSMichel Lespinasse {
417bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
418bf181b9fSMichel Lespinasse 
419bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
420bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
421bf181b9fSMichel Lespinasse }
422bf181b9fSMichel Lespinasse 
423bf181b9fSMichel Lespinasse static inline void
424bf181b9fSMichel Lespinasse anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
425bf181b9fSMichel Lespinasse {
426bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
427bf181b9fSMichel Lespinasse 
428bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
429bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
430bf181b9fSMichel Lespinasse }
431bf181b9fSMichel Lespinasse 
432524e00b3SLiam R. Howlett /*
433524e00b3SLiam R. Howlett  * range_has_overlap() - Check the @start - @end range for overlapping VMAs and
434524e00b3SLiam R. Howlett  * sets up a pointer to the previous VMA
435524e00b3SLiam R. Howlett  * @mm: the mm struct
436524e00b3SLiam R. Howlett  * @start: the start address of the range
437524e00b3SLiam R. Howlett  * @end: the end address of the range
438524e00b3SLiam R. Howlett  * @pprev: the pointer to the pointer of the previous VMA
439524e00b3SLiam R. Howlett  *
440524e00b3SLiam R. Howlett  * Returns: True if there is an overlapping VMA, false otherwise
441524e00b3SLiam R. Howlett  */
442524e00b3SLiam R. Howlett static inline
443524e00b3SLiam R. Howlett bool range_has_overlap(struct mm_struct *mm, unsigned long start,
444524e00b3SLiam R. Howlett 		       unsigned long end, struct vm_area_struct **pprev)
4451da177e4SLinus Torvalds {
446524e00b3SLiam R. Howlett 	struct vm_area_struct *existing;
4471da177e4SLinus Torvalds 
448524e00b3SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, start, start);
449524e00b3SLiam R. Howlett 	existing = mas_find(&mas, end - 1);
450524e00b3SLiam R. Howlett 	*pprev = mas_prev(&mas, 0);
451524e00b3SLiam R. Howlett 	return existing ? true : false;
4521da177e4SLinus Torvalds }
4531da177e4SLinus Torvalds 
4543903b55aSLiam R. Howlett /*
455f39af059SMatthew Wilcox (Oracle)  * __vma_next() - Get the next VMA.
4563903b55aSLiam R. Howlett  * @mm: The mm_struct.
4573903b55aSLiam R. Howlett  * @vma: The current vma.
4583903b55aSLiam R. Howlett  *
4593903b55aSLiam R. Howlett  * If @vma is NULL, return the first vma in the mm.
4603903b55aSLiam R. Howlett  *
4613903b55aSLiam R. Howlett  * Returns: The next VMA after @vma.
4623903b55aSLiam R. Howlett  */
463f39af059SMatthew Wilcox (Oracle) static inline struct vm_area_struct *__vma_next(struct mm_struct *mm,
4643903b55aSLiam R. Howlett 					 struct vm_area_struct *vma)
4653903b55aSLiam R. Howlett {
4663903b55aSLiam R. Howlett 	if (!vma)
4673903b55aSLiam R. Howlett 		return mm->mmap;
4683903b55aSLiam R. Howlett 
4693903b55aSLiam R. Howlett 	return vma->vm_next;
4703903b55aSLiam R. Howlett }
471fb8090b6SLiam R. Howlett 
472e8420a8eSCyril Hrubis static unsigned long count_vma_pages_range(struct mm_struct *mm,
473e8420a8eSCyril Hrubis 		unsigned long addr, unsigned long end)
474e8420a8eSCyril Hrubis {
4752e3af1dbSMatthew Wilcox (Oracle) 	VMA_ITERATOR(vmi, mm, addr);
476e8420a8eSCyril Hrubis 	struct vm_area_struct *vma;
4772e3af1dbSMatthew Wilcox (Oracle) 	unsigned long nr_pages = 0;
478e8420a8eSCyril Hrubis 
4792e3af1dbSMatthew Wilcox (Oracle) 	for_each_vma_range(vmi, vma, end) {
4802e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_start = max(addr, vma->vm_start);
4812e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_end = min(end, vma->vm_end);
482e8420a8eSCyril Hrubis 
4832e3af1dbSMatthew Wilcox (Oracle) 		nr_pages += PHYS_PFN(vm_end - vm_start);
484e8420a8eSCyril Hrubis 	}
485e8420a8eSCyril Hrubis 
486e8420a8eSCyril Hrubis 	return nr_pages;
487e8420a8eSCyril Hrubis }
488e8420a8eSCyril Hrubis 
489cb8f488cSDenys Vlasenko static void __vma_link_file(struct vm_area_struct *vma)
4901da177e4SLinus Torvalds {
4911da177e4SLinus Torvalds 	struct file *file;
4921da177e4SLinus Torvalds 
4931da177e4SLinus Torvalds 	file = vma->vm_file;
4941da177e4SLinus Torvalds 	if (file) {
4951da177e4SLinus Torvalds 		struct address_space *mapping = file->f_mapping;
4961da177e4SLinus Torvalds 
4971da177e4SLinus Torvalds 		if (vma->vm_flags & VM_SHARED)
498cf508b58SMiaohe Lin 			mapping_allow_writable(mapping);
4991da177e4SLinus Torvalds 
5001da177e4SLinus Torvalds 		flush_dcache_mmap_lock(mapping);
5016b2dbba8SMichel Lespinasse 		vma_interval_tree_insert(vma, &mapping->i_mmap);
5021da177e4SLinus Torvalds 		flush_dcache_mmap_unlock(mapping);
5031da177e4SLinus Torvalds 	}
5041da177e4SLinus Torvalds }
5051da177e4SLinus Torvalds 
506d4af56c5SLiam R. Howlett /*
507d4af56c5SLiam R. Howlett  * vma_mas_store() - Store a VMA in the maple tree.
508d4af56c5SLiam R. Howlett  * @vma: The vm_area_struct
509d4af56c5SLiam R. Howlett  * @mas: The maple state
510d4af56c5SLiam R. Howlett  *
511d4af56c5SLiam R. Howlett  * Efficient way to store a VMA in the maple tree when the @mas has already
512d4af56c5SLiam R. Howlett  * walked to the correct location.
513d4af56c5SLiam R. Howlett  *
514d4af56c5SLiam R. Howlett  * Note: the end address is inclusive in the maple tree.
515d4af56c5SLiam R. Howlett  */
516d4af56c5SLiam R. Howlett void vma_mas_store(struct vm_area_struct *vma, struct ma_state *mas)
517d4af56c5SLiam R. Howlett {
518d4af56c5SLiam R. Howlett 	trace_vma_store(mas->tree, vma);
519d4af56c5SLiam R. Howlett 	mas_set_range(mas, vma->vm_start, vma->vm_end - 1);
520d4af56c5SLiam R. Howlett 	mas_store_prealloc(mas, vma);
521d4af56c5SLiam R. Howlett }
522d4af56c5SLiam R. Howlett 
523d4af56c5SLiam R. Howlett /*
524d4af56c5SLiam R. Howlett  * vma_mas_remove() - Remove a VMA from the maple tree.
525d4af56c5SLiam R. Howlett  * @vma: The vm_area_struct
526d4af56c5SLiam R. Howlett  * @mas: The maple state
527d4af56c5SLiam R. Howlett  *
528d4af56c5SLiam R. Howlett  * Efficient way to remove a VMA from the maple tree when the @mas has already
529d4af56c5SLiam R. Howlett  * been established and points to the correct location.
530d4af56c5SLiam R. Howlett  * Note: the end address is inclusive in the maple tree.
531d4af56c5SLiam R. Howlett  */
532d4af56c5SLiam R. Howlett void vma_mas_remove(struct vm_area_struct *vma, struct ma_state *mas)
533d4af56c5SLiam R. Howlett {
534d4af56c5SLiam R. Howlett 	trace_vma_mas_szero(mas->tree, vma->vm_start, vma->vm_end - 1);
535d4af56c5SLiam R. Howlett 	mas->index = vma->vm_start;
536d4af56c5SLiam R. Howlett 	mas->last = vma->vm_end - 1;
537d4af56c5SLiam R. Howlett 	mas_store_prealloc(mas, NULL);
538d4af56c5SLiam R. Howlett }
539d4af56c5SLiam R. Howlett 
540d4af56c5SLiam R. Howlett /*
541d4af56c5SLiam R. Howlett  * vma_mas_szero() - Set a given range to zero.  Used when modifying a
542d4af56c5SLiam R. Howlett  * vm_area_struct start or end.
543d4af56c5SLiam R. Howlett  *
544d4af56c5SLiam R. Howlett  * @mm: The struct_mm
545d4af56c5SLiam R. Howlett  * @start: The start address to zero
546d4af56c5SLiam R. Howlett  * @end: The end address to zero.
547d4af56c5SLiam R. Howlett  */
548d4af56c5SLiam R. Howlett static inline void vma_mas_szero(struct ma_state *mas, unsigned long start,
549d4af56c5SLiam R. Howlett 				unsigned long end)
550d4af56c5SLiam R. Howlett {
551d4af56c5SLiam R. Howlett 	trace_vma_mas_szero(mas->tree, start, end - 1);
552d4af56c5SLiam R. Howlett 	mas_set_range(mas, start, end - 1);
553d4af56c5SLiam R. Howlett 	mas_store_prealloc(mas, NULL);
554d4af56c5SLiam R. Howlett }
555d4af56c5SLiam R. Howlett 
556d4af56c5SLiam R. Howlett static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
557524e00b3SLiam R. Howlett 			struct vm_area_struct *prev)
5581da177e4SLinus Torvalds {
559d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
5601da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
5611da177e4SLinus Torvalds 
562d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
563d4af56c5SLiam R. Howlett 		return -ENOMEM;
564d4af56c5SLiam R. Howlett 
56564ac4940SHuang Shijie 	if (vma->vm_file) {
5661da177e4SLinus Torvalds 		mapping = vma->vm_file->f_mapping;
56783cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
56864ac4940SHuang Shijie 	}
5691da177e4SLinus Torvalds 
570d4af56c5SLiam R. Howlett 	vma_mas_store(vma, &mas);
571524e00b3SLiam R. Howlett 	__vma_link_list(mm, vma, prev);
5721da177e4SLinus Torvalds 	__vma_link_file(vma);
5731da177e4SLinus Torvalds 
5741da177e4SLinus Torvalds 	if (mapping)
57583cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
5761da177e4SLinus Torvalds 
5771da177e4SLinus Torvalds 	mm->map_count++;
5781da177e4SLinus Torvalds 	validate_mm(mm);
579d4af56c5SLiam R. Howlett 	return 0;
5801da177e4SLinus Torvalds }
5811da177e4SLinus Torvalds 
5821da177e4SLinus Torvalds /*
58388f6b4c3SKautuk Consul  * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
584524e00b3SLiam R. Howlett  * mm's list and the mm tree.  It has already been inserted into the interval tree.
5851da177e4SLinus Torvalds  */
586d4af56c5SLiam R. Howlett static void __insert_vm_struct(struct mm_struct *mm, struct ma_state *mas,
5873b0e81a1SLiam R. Howlett 		struct vm_area_struct *vma, unsigned long location)
5881da177e4SLinus Torvalds {
5896597d783SHugh Dickins 	struct vm_area_struct *prev;
5901da177e4SLinus Torvalds 
5913b0e81a1SLiam R. Howlett 	mas_set(mas, location);
592524e00b3SLiam R. Howlett 	prev = mas_prev(mas, 0);
593d4af56c5SLiam R. Howlett 	vma_mas_store(vma, mas);
594d4af56c5SLiam R. Howlett 	__vma_link_list(mm, vma, prev);
5951da177e4SLinus Torvalds 	mm->map_count++;
5961da177e4SLinus Torvalds }
5971da177e4SLinus Torvalds 
5981da177e4SLinus Torvalds /*
5994dd1b841SLiam R. Howlett  * vma_expand - Expand an existing VMA
6004dd1b841SLiam R. Howlett  *
6014dd1b841SLiam R. Howlett  * @mas: The maple state
6024dd1b841SLiam R. Howlett  * @vma: The vma to expand
6034dd1b841SLiam R. Howlett  * @start: The start of the vma
6044dd1b841SLiam R. Howlett  * @end: The exclusive end of the vma
6054dd1b841SLiam R. Howlett  * @pgoff: The page offset of vma
6064dd1b841SLiam R. Howlett  * @next: The current of next vma.
6074dd1b841SLiam R. Howlett  *
6084dd1b841SLiam R. Howlett  * Expand @vma to @start and @end.  Can expand off the start and end.  Will
6094dd1b841SLiam R. Howlett  * expand over @next if it's different from @vma and @end == @next->vm_end.
6104dd1b841SLiam R. Howlett  * Checking if the @vma can expand and merge with @next needs to be handled by
6114dd1b841SLiam R. Howlett  * the caller.
6124dd1b841SLiam R. Howlett  *
6134dd1b841SLiam R. Howlett  * Returns: 0 on success
6144dd1b841SLiam R. Howlett  */
6154dd1b841SLiam R. Howlett inline int vma_expand(struct ma_state *mas, struct vm_area_struct *vma,
6164dd1b841SLiam R. Howlett 		      unsigned long start, unsigned long end, pgoff_t pgoff,
6174dd1b841SLiam R. Howlett 		      struct vm_area_struct *next)
6184dd1b841SLiam R. Howlett {
6194dd1b841SLiam R. Howlett 	struct mm_struct *mm = vma->vm_mm;
6204dd1b841SLiam R. Howlett 	struct address_space *mapping = NULL;
6214dd1b841SLiam R. Howlett 	struct rb_root_cached *root = NULL;
6224dd1b841SLiam R. Howlett 	struct anon_vma *anon_vma = vma->anon_vma;
6234dd1b841SLiam R. Howlett 	struct file *file = vma->vm_file;
6244dd1b841SLiam R. Howlett 	bool remove_next = false;
6254dd1b841SLiam R. Howlett 
6264dd1b841SLiam R. Howlett 	if (next && (vma != next) && (end == next->vm_end)) {
6274dd1b841SLiam R. Howlett 		remove_next = true;
6284dd1b841SLiam R. Howlett 		if (next->anon_vma && !vma->anon_vma) {
6294dd1b841SLiam R. Howlett 			int error;
6304dd1b841SLiam R. Howlett 
6314dd1b841SLiam R. Howlett 			anon_vma = next->anon_vma;
6324dd1b841SLiam R. Howlett 			vma->anon_vma = anon_vma;
6334dd1b841SLiam R. Howlett 			error = anon_vma_clone(vma, next);
6344dd1b841SLiam R. Howlett 			if (error)
6354dd1b841SLiam R. Howlett 				return error;
6364dd1b841SLiam R. Howlett 		}
6374dd1b841SLiam R. Howlett 	}
6384dd1b841SLiam R. Howlett 
6394dd1b841SLiam R. Howlett 	/* Not merging but overwriting any part of next is not handled. */
6404dd1b841SLiam R. Howlett 	VM_BUG_ON(next && !remove_next && next != vma && end > next->vm_start);
6414dd1b841SLiam R. Howlett 	/* Only handles expanding */
6424dd1b841SLiam R. Howlett 	VM_BUG_ON(vma->vm_start < start || vma->vm_end > end);
6434dd1b841SLiam R. Howlett 
6444dd1b841SLiam R. Howlett 	if (mas_preallocate(mas, vma, GFP_KERNEL))
6454dd1b841SLiam R. Howlett 		goto nomem;
6464dd1b841SLiam R. Howlett 
6474dd1b841SLiam R. Howlett 	vma_adjust_trans_huge(vma, start, end, 0);
6484dd1b841SLiam R. Howlett 
6494dd1b841SLiam R. Howlett 	if (file) {
6504dd1b841SLiam R. Howlett 		mapping = file->f_mapping;
6514dd1b841SLiam R. Howlett 		root = &mapping->i_mmap;
6524dd1b841SLiam R. Howlett 		uprobe_munmap(vma, vma->vm_start, vma->vm_end);
6534dd1b841SLiam R. Howlett 		i_mmap_lock_write(mapping);
6544dd1b841SLiam R. Howlett 	}
6554dd1b841SLiam R. Howlett 
6564dd1b841SLiam R. Howlett 	if (anon_vma) {
6574dd1b841SLiam R. Howlett 		anon_vma_lock_write(anon_vma);
6584dd1b841SLiam R. Howlett 		anon_vma_interval_tree_pre_update_vma(vma);
6594dd1b841SLiam R. Howlett 	}
6604dd1b841SLiam R. Howlett 
6614dd1b841SLiam R. Howlett 	if (file) {
6624dd1b841SLiam R. Howlett 		flush_dcache_mmap_lock(mapping);
6634dd1b841SLiam R. Howlett 		vma_interval_tree_remove(vma, root);
6644dd1b841SLiam R. Howlett 	}
6654dd1b841SLiam R. Howlett 
6664dd1b841SLiam R. Howlett 	vma->vm_start = start;
6674dd1b841SLiam R. Howlett 	vma->vm_end = end;
6684dd1b841SLiam R. Howlett 	vma->vm_pgoff = pgoff;
6694dd1b841SLiam R. Howlett 	/* Note: mas must be pointing to the expanding VMA */
6704dd1b841SLiam R. Howlett 	vma_mas_store(vma, mas);
6714dd1b841SLiam R. Howlett 
6724dd1b841SLiam R. Howlett 	if (file) {
6734dd1b841SLiam R. Howlett 		vma_interval_tree_insert(vma, root);
6744dd1b841SLiam R. Howlett 		flush_dcache_mmap_unlock(mapping);
6754dd1b841SLiam R. Howlett 	}
6764dd1b841SLiam R. Howlett 
6774dd1b841SLiam R. Howlett 	/* Expanding over the next vma */
6784dd1b841SLiam R. Howlett 	if (remove_next) {
6794dd1b841SLiam R. Howlett 		/* Remove from mm linked list - also updates highest_vm_end */
6804dd1b841SLiam R. Howlett 		__vma_unlink_list(mm, next);
6814dd1b841SLiam R. Howlett 
6824dd1b841SLiam R. Howlett 		if (file)
6834dd1b841SLiam R. Howlett 			__remove_shared_vm_struct(next, file, mapping);
6844dd1b841SLiam R. Howlett 
6854dd1b841SLiam R. Howlett 	} else if (!next) {
6864dd1b841SLiam R. Howlett 		mm->highest_vm_end = vm_end_gap(vma);
6874dd1b841SLiam R. Howlett 	}
6884dd1b841SLiam R. Howlett 
6894dd1b841SLiam R. Howlett 	if (anon_vma) {
6904dd1b841SLiam R. Howlett 		anon_vma_interval_tree_post_update_vma(vma);
6914dd1b841SLiam R. Howlett 		anon_vma_unlock_write(anon_vma);
6924dd1b841SLiam R. Howlett 	}
6934dd1b841SLiam R. Howlett 
6944dd1b841SLiam R. Howlett 	if (file) {
6954dd1b841SLiam R. Howlett 		i_mmap_unlock_write(mapping);
6964dd1b841SLiam R. Howlett 		uprobe_mmap(vma);
6974dd1b841SLiam R. Howlett 	}
6984dd1b841SLiam R. Howlett 
6994dd1b841SLiam R. Howlett 	if (remove_next) {
7004dd1b841SLiam R. Howlett 		if (file) {
7014dd1b841SLiam R. Howlett 			uprobe_munmap(next, next->vm_start, next->vm_end);
7024dd1b841SLiam R. Howlett 			fput(file);
7034dd1b841SLiam R. Howlett 		}
7044dd1b841SLiam R. Howlett 		if (next->anon_vma)
7054dd1b841SLiam R. Howlett 			anon_vma_merge(vma, next);
7064dd1b841SLiam R. Howlett 		mm->map_count--;
7074dd1b841SLiam R. Howlett 		mpol_put(vma_policy(next));
7084dd1b841SLiam R. Howlett 		vm_area_free(next);
7094dd1b841SLiam R. Howlett 	}
7104dd1b841SLiam R. Howlett 
7114dd1b841SLiam R. Howlett 	validate_mm(mm);
7124dd1b841SLiam R. Howlett 	return 0;
7134dd1b841SLiam R. Howlett 
7144dd1b841SLiam R. Howlett nomem:
7154dd1b841SLiam R. Howlett 	return -ENOMEM;
7164dd1b841SLiam R. Howlett }
7174dd1b841SLiam R. Howlett 
7184dd1b841SLiam R. Howlett /*
7191da177e4SLinus Torvalds  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
7201da177e4SLinus Torvalds  * is already present in an i_mmap tree without adjusting the tree.
7211da177e4SLinus Torvalds  * The following helper function should be used when such adjustments
7221da177e4SLinus Torvalds  * are necessary.  The "insert" vma (if any) is to be inserted
7231da177e4SLinus Torvalds  * before we drop the necessary locks.
7241da177e4SLinus Torvalds  */
725e86f15eeSAndrea Arcangeli int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
726e86f15eeSAndrea Arcangeli 	unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
727e86f15eeSAndrea Arcangeli 	struct vm_area_struct *expand)
7281da177e4SLinus Torvalds {
7291da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
730524e00b3SLiam R. Howlett 	struct vm_area_struct *next_next, *next = find_vma(mm, vma->vm_end);
731524e00b3SLiam R. Howlett 	struct vm_area_struct *orig_vma = vma;
7321da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
733f808c13fSDavidlohr Bueso 	struct rb_root_cached *root = NULL;
734012f1800SRik van Riel 	struct anon_vma *anon_vma = NULL;
7351da177e4SLinus Torvalds 	struct file *file = vma->vm_file;
736524e00b3SLiam R. Howlett 	bool vma_changed = false;
7371da177e4SLinus Torvalds 	long adjust_next = 0;
7381da177e4SLinus Torvalds 	int remove_next = 0;
739d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
740734537c9SKirill A. Shutemov 	struct vm_area_struct *exporter = NULL, *importer = NULL;
7413b0e81a1SLiam R. Howlett 	unsigned long ll_prev = vma->vm_start; /* linked list prev. */
742287d97acSLinus Torvalds 
743d4af56c5SLiam R. Howlett 	if (next && !insert) {
7441da177e4SLinus Torvalds 		if (end >= next->vm_end) {
7451da177e4SLinus Torvalds 			/*
7461da177e4SLinus Torvalds 			 * vma expands, overlapping all the next, and
7471da177e4SLinus Torvalds 			 * perhaps the one after too (mprotect case 6).
74886d12e47SAndrea Arcangeli 			 * The only other cases that gets here are
749e86f15eeSAndrea Arcangeli 			 * case 1, case 7 and case 8.
750e86f15eeSAndrea Arcangeli 			 */
751e86f15eeSAndrea Arcangeli 			if (next == expand) {
752e86f15eeSAndrea Arcangeli 				/*
753e86f15eeSAndrea Arcangeli 				 * The only case where we don't expand "vma"
754e86f15eeSAndrea Arcangeli 				 * and we expand "next" instead is case 8.
755e86f15eeSAndrea Arcangeli 				 */
756e86f15eeSAndrea Arcangeli 				VM_WARN_ON(end != next->vm_end);
757e86f15eeSAndrea Arcangeli 				/*
758e86f15eeSAndrea Arcangeli 				 * remove_next == 3 means we're
759e86f15eeSAndrea Arcangeli 				 * removing "vma" and that to do so we
760e86f15eeSAndrea Arcangeli 				 * swapped "vma" and "next".
761e86f15eeSAndrea Arcangeli 				 */
762e86f15eeSAndrea Arcangeli 				remove_next = 3;
763e86f15eeSAndrea Arcangeli 				VM_WARN_ON(file != next->vm_file);
764e86f15eeSAndrea Arcangeli 				swap(vma, next);
765e86f15eeSAndrea Arcangeli 			} else {
766e86f15eeSAndrea Arcangeli 				VM_WARN_ON(expand != vma);
767e86f15eeSAndrea Arcangeli 				/*
768e86f15eeSAndrea Arcangeli 				 * case 1, 6, 7, remove_next == 2 is case 6,
769e86f15eeSAndrea Arcangeli 				 * remove_next == 1 is case 1 or 7.
7701da177e4SLinus Torvalds 				 */
771734537c9SKirill A. Shutemov 				remove_next = 1 + (end > next->vm_end);
772d4af56c5SLiam R. Howlett 				if (remove_next == 2)
773d4af56c5SLiam R. Howlett 					next_next = find_vma(mm, next->vm_end);
774d4af56c5SLiam R. Howlett 
775e86f15eeSAndrea Arcangeli 				VM_WARN_ON(remove_next == 2 &&
776e86f15eeSAndrea Arcangeli 					   end != next->vm_next->vm_end);
777e86f15eeSAndrea Arcangeli 			}
778e86f15eeSAndrea Arcangeli 
779287d97acSLinus Torvalds 			exporter = next;
7801da177e4SLinus Torvalds 			importer = vma;
781734537c9SKirill A. Shutemov 
782734537c9SKirill A. Shutemov 			/*
783734537c9SKirill A. Shutemov 			 * If next doesn't have anon_vma, import from vma after
784734537c9SKirill A. Shutemov 			 * next, if the vma overlaps with it.
785734537c9SKirill A. Shutemov 			 */
78697a42cd4SAndrea Arcangeli 			if (remove_next == 2 && !next->anon_vma)
787734537c9SKirill A. Shutemov 				exporter = next->vm_next;
788734537c9SKirill A. Shutemov 
7891da177e4SLinus Torvalds 		} else if (end > next->vm_start) {
7901da177e4SLinus Torvalds 			/*
7911da177e4SLinus Torvalds 			 * vma expands, overlapping part of the next:
7921da177e4SLinus Torvalds 			 * mprotect case 5 shifting the boundary up.
7931da177e4SLinus Torvalds 			 */
794f9d86a60SWei Yang 			adjust_next = (end - next->vm_start);
795287d97acSLinus Torvalds 			exporter = next;
7961da177e4SLinus Torvalds 			importer = vma;
797e86f15eeSAndrea Arcangeli 			VM_WARN_ON(expand != importer);
7981da177e4SLinus Torvalds 		} else if (end < vma->vm_end) {
7991da177e4SLinus Torvalds 			/*
8001da177e4SLinus Torvalds 			 * vma shrinks, and !insert tells it's not
8011da177e4SLinus Torvalds 			 * split_vma inserting another: so it must be
8021da177e4SLinus Torvalds 			 * mprotect case 4 shifting the boundary down.
8031da177e4SLinus Torvalds 			 */
804f9d86a60SWei Yang 			adjust_next = -(vma->vm_end - end);
805287d97acSLinus Torvalds 			exporter = vma;
8061da177e4SLinus Torvalds 			importer = next;
807e86f15eeSAndrea Arcangeli 			VM_WARN_ON(expand != importer);
8081da177e4SLinus Torvalds 		}
8091da177e4SLinus Torvalds 
8105beb4930SRik van Riel 		/*
8115beb4930SRik van Riel 		 * Easily overlooked: when mprotect shifts the boundary,
8125beb4930SRik van Riel 		 * make sure the expanding vma has anon_vma set if the
8135beb4930SRik van Riel 		 * shrinking vma had, to cover any anon pages imported.
8145beb4930SRik van Riel 		 */
815287d97acSLinus Torvalds 		if (exporter && exporter->anon_vma && !importer->anon_vma) {
816c4ea95d7SDaniel Forrest 			int error;
817c4ea95d7SDaniel Forrest 
818287d97acSLinus Torvalds 			importer->anon_vma = exporter->anon_vma;
819b800c91aSKonstantin Khlebnikov 			error = anon_vma_clone(importer, exporter);
8203fe89b3eSLeon Yu 			if (error)
821b800c91aSKonstantin Khlebnikov 				return error;
822b800c91aSKonstantin Khlebnikov 		}
8235beb4930SRik van Riel 	}
82437f9f559SKirill A. Shutemov 
825d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
826d4af56c5SLiam R. Howlett 		return -ENOMEM;
827d4af56c5SLiam R. Howlett 
828d4af56c5SLiam R. Howlett 	vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
8291da177e4SLinus Torvalds 	if (file) {
8301da177e4SLinus Torvalds 		mapping = file->f_mapping;
8311da177e4SLinus Torvalds 		root = &mapping->i_mmap;
832cbc91f71SSrikar Dronamraju 		uprobe_munmap(vma, vma->vm_start, vma->vm_end);
833682968e0SSrikar Dronamraju 
834682968e0SSrikar Dronamraju 		if (adjust_next)
83527ba0644SKirill A. Shutemov 			uprobe_munmap(next, next->vm_start, next->vm_end);
836682968e0SSrikar Dronamraju 
83783cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
8381da177e4SLinus Torvalds 		if (insert) {
8391da177e4SLinus Torvalds 			/*
8406b2dbba8SMichel Lespinasse 			 * Put into interval tree now, so instantiated pages
8411da177e4SLinus Torvalds 			 * are visible to arm/parisc __flush_dcache_page
8421da177e4SLinus Torvalds 			 * throughout; but we cannot insert into address
8431da177e4SLinus Torvalds 			 * space until vma start or end is updated.
8441da177e4SLinus Torvalds 			 */
8451da177e4SLinus Torvalds 			__vma_link_file(insert);
8461da177e4SLinus Torvalds 		}
8471da177e4SLinus Torvalds 	}
8481da177e4SLinus Torvalds 
849012f1800SRik van Riel 	anon_vma = vma->anon_vma;
850bf181b9fSMichel Lespinasse 	if (!anon_vma && adjust_next)
851bf181b9fSMichel Lespinasse 		anon_vma = next->anon_vma;
852bf181b9fSMichel Lespinasse 	if (anon_vma) {
853e86f15eeSAndrea Arcangeli 		VM_WARN_ON(adjust_next && next->anon_vma &&
854e86f15eeSAndrea Arcangeli 			   anon_vma != next->anon_vma);
8554fc3f1d6SIngo Molnar 		anon_vma_lock_write(anon_vma);
856bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_pre_update_vma(vma);
857bf181b9fSMichel Lespinasse 		if (adjust_next)
858bf181b9fSMichel Lespinasse 			anon_vma_interval_tree_pre_update_vma(next);
859bf181b9fSMichel Lespinasse 	}
860012f1800SRik van Riel 
8610fc48a6eSWei Yang 	if (file) {
8621da177e4SLinus Torvalds 		flush_dcache_mmap_lock(mapping);
8636b2dbba8SMichel Lespinasse 		vma_interval_tree_remove(vma, root);
8641da177e4SLinus Torvalds 		if (adjust_next)
8656b2dbba8SMichel Lespinasse 			vma_interval_tree_remove(next, root);
8661da177e4SLinus Torvalds 	}
8671da177e4SLinus Torvalds 
868d3737187SMichel Lespinasse 	if (start != vma->vm_start) {
8693b0e81a1SLiam R. Howlett 		if ((vma->vm_start < start) &&
8703b0e81a1SLiam R. Howlett 		    (!insert || (insert->vm_end != start))) {
871524e00b3SLiam R. Howlett 			vma_mas_szero(&mas, vma->vm_start, start);
8723b0e81a1SLiam R. Howlett 			VM_WARN_ON(insert && insert->vm_start > vma->vm_start);
8733b0e81a1SLiam R. Howlett 		} else {
874524e00b3SLiam R. Howlett 			vma_changed = true;
8753b0e81a1SLiam R. Howlett 		}
8761da177e4SLinus Torvalds 		vma->vm_start = start;
877d3737187SMichel Lespinasse 	}
878d3737187SMichel Lespinasse 	if (end != vma->vm_end) {
8793b0e81a1SLiam R. Howlett 		if (vma->vm_end > end) {
8803b0e81a1SLiam R. Howlett 			if (!insert || (insert->vm_start != end)) {
881524e00b3SLiam R. Howlett 				vma_mas_szero(&mas, end, vma->vm_end);
8823b0e81a1SLiam R. Howlett 				VM_WARN_ON(insert &&
8833b0e81a1SLiam R. Howlett 					   insert->vm_end < vma->vm_end);
8843b0e81a1SLiam R. Howlett 			} else if (insert->vm_start == end) {
8853b0e81a1SLiam R. Howlett 				ll_prev = vma->vm_end;
8863b0e81a1SLiam R. Howlett 			}
8873b0e81a1SLiam R. Howlett 		} else {
888524e00b3SLiam R. Howlett 			vma_changed = true;
8893b0e81a1SLiam R. Howlett 		}
8901da177e4SLinus Torvalds 		vma->vm_end = end;
891524e00b3SLiam R. Howlett 		if (!next)
892524e00b3SLiam R. Howlett 			mm->highest_vm_end = vm_end_gap(vma);
893d3737187SMichel Lespinasse 	}
894d4af56c5SLiam R. Howlett 
895524e00b3SLiam R. Howlett 	if (vma_changed)
896d4af56c5SLiam R. Howlett 		vma_mas_store(vma, &mas);
897d4af56c5SLiam R. Howlett 
8981da177e4SLinus Torvalds 	vma->vm_pgoff = pgoff;
8991da177e4SLinus Torvalds 	if (adjust_next) {
900f9d86a60SWei Yang 		next->vm_start += adjust_next;
901f9d86a60SWei Yang 		next->vm_pgoff += adjust_next >> PAGE_SHIFT;
902d4af56c5SLiam R. Howlett 		vma_mas_store(next, &mas);
9031da177e4SLinus Torvalds 	}
9041da177e4SLinus Torvalds 
9050fc48a6eSWei Yang 	if (file) {
9061da177e4SLinus Torvalds 		if (adjust_next)
9076b2dbba8SMichel Lespinasse 			vma_interval_tree_insert(next, root);
9086b2dbba8SMichel Lespinasse 		vma_interval_tree_insert(vma, root);
9091da177e4SLinus Torvalds 		flush_dcache_mmap_unlock(mapping);
9101da177e4SLinus Torvalds 	}
9111da177e4SLinus Torvalds 
9121da177e4SLinus Torvalds 	if (remove_next) {
9131da177e4SLinus Torvalds 		/*
9141da177e4SLinus Torvalds 		 * vma_merge has merged next into vma, and needs
9151da177e4SLinus Torvalds 		 * us to remove next before dropping the locks.
916d4af56c5SLiam R. Howlett 		 * Since we have expanded over this vma, the maple tree will
917d4af56c5SLiam R. Howlett 		 * have overwritten by storing the value
9181da177e4SLinus Torvalds 		 */
919524e00b3SLiam R. Howlett 		__vma_unlink_list(mm, next);
920d4af56c5SLiam R. Howlett 		if (remove_next == 2)
921524e00b3SLiam R. Howlett 			__vma_unlink_list(mm, next_next);
922524e00b3SLiam R. Howlett 
923d4af56c5SLiam R. Howlett 		if (file) {
9241da177e4SLinus Torvalds 			__remove_shared_vm_struct(next, file, mapping);
925d4af56c5SLiam R. Howlett 			if (remove_next == 2)
926d4af56c5SLiam R. Howlett 				__remove_shared_vm_struct(next_next, file, mapping);
927d4af56c5SLiam R. Howlett 		}
9281da177e4SLinus Torvalds 	} else if (insert) {
9291da177e4SLinus Torvalds 		/*
9301da177e4SLinus Torvalds 		 * split_vma has split insert from vma, and needs
9311da177e4SLinus Torvalds 		 * us to insert it before dropping the locks
9321da177e4SLinus Torvalds 		 * (it may either follow vma or precede it).
9331da177e4SLinus Torvalds 		 */
9343b0e81a1SLiam R. Howlett 		__insert_vm_struct(mm, &mas, insert, ll_prev);
9351da177e4SLinus Torvalds 	}
9361da177e4SLinus Torvalds 
937bf181b9fSMichel Lespinasse 	if (anon_vma) {
938bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_post_update_vma(vma);
939bf181b9fSMichel Lespinasse 		if (adjust_next)
940bf181b9fSMichel Lespinasse 			anon_vma_interval_tree_post_update_vma(next);
94108b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
942bf181b9fSMichel Lespinasse 	}
9431da177e4SLinus Torvalds 
9440fc48a6eSWei Yang 	if (file) {
945808fbdbeSWei Yang 		i_mmap_unlock_write(mapping);
9467b2d81d4SIngo Molnar 		uprobe_mmap(vma);
9472b144498SSrikar Dronamraju 
9482b144498SSrikar Dronamraju 		if (adjust_next)
9497b2d81d4SIngo Molnar 			uprobe_mmap(next);
9502b144498SSrikar Dronamraju 	}
9512b144498SSrikar Dronamraju 
9521da177e4SLinus Torvalds 	if (remove_next) {
953d4af56c5SLiam R. Howlett again:
954925d1c40SMatt Helsley 		if (file) {
955cbc91f71SSrikar Dronamraju 			uprobe_munmap(next, next->vm_start, next->vm_end);
9561da177e4SLinus Torvalds 			fput(file);
957925d1c40SMatt Helsley 		}
9585beb4930SRik van Riel 		if (next->anon_vma)
9595beb4930SRik van Riel 			anon_vma_merge(vma, next);
9601da177e4SLinus Torvalds 		mm->map_count--;
9613964acd0SOleg Nesterov 		mpol_put(vma_policy(next));
962524e00b3SLiam R. Howlett 		if (remove_next != 2)
963524e00b3SLiam R. Howlett 			BUG_ON(vma->vm_end < next->vm_end);
9643928d4f5SLinus Torvalds 		vm_area_free(next);
965524e00b3SLiam R. Howlett 
9661da177e4SLinus Torvalds 		/*
9671da177e4SLinus Torvalds 		 * In mprotect's case 6 (see comments on vma_merge),
9681da177e4SLinus Torvalds 		 * we must remove another next too. It would clutter
9691da177e4SLinus Torvalds 		 * up the code too much to do both in one go.
9701da177e4SLinus Torvalds 		 */
971e86f15eeSAndrea Arcangeli 		if (remove_next != 3) {
972e86f15eeSAndrea Arcangeli 			/*
973e86f15eeSAndrea Arcangeli 			 * If "next" was removed and vma->vm_end was
974e86f15eeSAndrea Arcangeli 			 * expanded (up) over it, in turn
975e86f15eeSAndrea Arcangeli 			 * "next->vm_prev->vm_end" changed and the
976e86f15eeSAndrea Arcangeli 			 * "vma->vm_next" gap must be updated.
977e86f15eeSAndrea Arcangeli 			 */
978d4af56c5SLiam R. Howlett 			next = next_next;
979e86f15eeSAndrea Arcangeli 		} else {
980e86f15eeSAndrea Arcangeli 			/*
981e86f15eeSAndrea Arcangeli 			 * For the scope of the comment "next" and
982e86f15eeSAndrea Arcangeli 			 * "vma" considered pre-swap(): if "vma" was
983e86f15eeSAndrea Arcangeli 			 * removed, next->vm_start was expanded (down)
984e86f15eeSAndrea Arcangeli 			 * over it and the "next" gap must be updated.
985e86f15eeSAndrea Arcangeli 			 * Because of the swap() the post-swap() "vma"
986e86f15eeSAndrea Arcangeli 			 * actually points to pre-swap() "next"
987e86f15eeSAndrea Arcangeli 			 * (post-swap() "next" as opposed is now a
988e86f15eeSAndrea Arcangeli 			 * dangling pointer).
989e86f15eeSAndrea Arcangeli 			 */
990e86f15eeSAndrea Arcangeli 			next = vma;
991e86f15eeSAndrea Arcangeli 		}
992734537c9SKirill A. Shutemov 		if (remove_next == 2) {
993734537c9SKirill A. Shutemov 			remove_next = 1;
9941da177e4SLinus Torvalds 			goto again;
995524e00b3SLiam R. Howlett 		} else if (!next) {
996fb8c41e9SAndrea Arcangeli 			/*
997fb8c41e9SAndrea Arcangeli 			 * If remove_next == 2 we obviously can't
998fb8c41e9SAndrea Arcangeli 			 * reach this path.
999fb8c41e9SAndrea Arcangeli 			 *
1000fb8c41e9SAndrea Arcangeli 			 * If remove_next == 3 we can't reach this
1001fb8c41e9SAndrea Arcangeli 			 * path because pre-swap() next is always not
1002fb8c41e9SAndrea Arcangeli 			 * NULL. pre-swap() "next" is not being
1003fb8c41e9SAndrea Arcangeli 			 * removed and its next->vm_end is not altered
1004fb8c41e9SAndrea Arcangeli 			 * (and furthermore "end" already matches
1005fb8c41e9SAndrea Arcangeli 			 * next->vm_end in remove_next == 3).
1006fb8c41e9SAndrea Arcangeli 			 *
1007fb8c41e9SAndrea Arcangeli 			 * We reach this only in the remove_next == 1
1008fb8c41e9SAndrea Arcangeli 			 * case if the "next" vma that was removed was
1009fb8c41e9SAndrea Arcangeli 			 * the highest vma of the mm. However in such
1010fb8c41e9SAndrea Arcangeli 			 * case next->vm_end == "end" and the extended
1011fb8c41e9SAndrea Arcangeli 			 * "vma" has vma->vm_end == next->vm_end so
1012fb8c41e9SAndrea Arcangeli 			 * mm->highest_vm_end doesn't need any update
1013fb8c41e9SAndrea Arcangeli 			 * in remove_next == 1 case.
1014fb8c41e9SAndrea Arcangeli 			 */
10151be7107fSHugh Dickins 			VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
1016fb8c41e9SAndrea Arcangeli 		}
10171da177e4SLinus Torvalds 	}
10182b144498SSrikar Dronamraju 	if (insert && file)
10197b2d81d4SIngo Molnar 		uprobe_mmap(insert);
10201da177e4SLinus Torvalds 
10213b0e81a1SLiam R. Howlett 	mas_destroy(&mas);
10221da177e4SLinus Torvalds 	validate_mm(mm);
10235beb4930SRik van Riel 	return 0;
10241da177e4SLinus Torvalds }
10251da177e4SLinus Torvalds 
10261da177e4SLinus Torvalds /*
10271da177e4SLinus Torvalds  * If the vma has a ->close operation then the driver probably needs to release
10281da177e4SLinus Torvalds  * per-vma resources, so we don't attempt to merge those.
10291da177e4SLinus Torvalds  */
10301da177e4SLinus Torvalds static inline int is_mergeable_vma(struct vm_area_struct *vma,
103119a809afSAndrea Arcangeli 				struct file *file, unsigned long vm_flags,
10329a10064fSColin Cross 				struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
10335c26f6acSSuren Baghdasaryan 				struct anon_vma_name *anon_name)
10341da177e4SLinus Torvalds {
103534228d47SCyrill Gorcunov 	/*
103634228d47SCyrill Gorcunov 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
103734228d47SCyrill Gorcunov 	 * match the flags but dirty bit -- the caller should mark
103834228d47SCyrill Gorcunov 	 * merged VMA as dirty. If dirty bit won't be excluded from
10398bb4e7a2SWei Yang 	 * comparison, we increase pressure on the memory system forcing
104034228d47SCyrill Gorcunov 	 * the kernel to generate new VMAs when old one could be
104134228d47SCyrill Gorcunov 	 * extended instead.
104234228d47SCyrill Gorcunov 	 */
104334228d47SCyrill Gorcunov 	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
10441da177e4SLinus Torvalds 		return 0;
10451da177e4SLinus Torvalds 	if (vma->vm_file != file)
10461da177e4SLinus Torvalds 		return 0;
10471da177e4SLinus Torvalds 	if (vma->vm_ops && vma->vm_ops->close)
10481da177e4SLinus Torvalds 		return 0;
104919a809afSAndrea Arcangeli 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
105019a809afSAndrea Arcangeli 		return 0;
10515c26f6acSSuren Baghdasaryan 	if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
10529a10064fSColin Cross 		return 0;
10531da177e4SLinus Torvalds 	return 1;
10541da177e4SLinus Torvalds }
10551da177e4SLinus Torvalds 
10561da177e4SLinus Torvalds static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
1057965f55deSShaohua Li 					struct anon_vma *anon_vma2,
1058965f55deSShaohua Li 					struct vm_area_struct *vma)
10591da177e4SLinus Torvalds {
1060965f55deSShaohua Li 	/*
1061965f55deSShaohua Li 	 * The list_is_singular() test is to avoid merging VMA cloned from
1062965f55deSShaohua Li 	 * parents. This can improve scalability caused by anon_vma lock.
1063965f55deSShaohua Li 	 */
1064965f55deSShaohua Li 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
1065965f55deSShaohua Li 		list_is_singular(&vma->anon_vma_chain)))
1066965f55deSShaohua Li 		return 1;
1067965f55deSShaohua Li 	return anon_vma1 == anon_vma2;
10681da177e4SLinus Torvalds }
10691da177e4SLinus Torvalds 
10701da177e4SLinus Torvalds /*
10711da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
10721da177e4SLinus Torvalds  * in front of (at a lower virtual address and file offset than) the vma.
10731da177e4SLinus Torvalds  *
10741da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
10751da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
10761da177e4SLinus Torvalds  *
10771da177e4SLinus Torvalds  * We don't check here for the merged mmap wrapping around the end of pagecache
107845e55300SPeter Collingbourne  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
10791da177e4SLinus Torvalds  * wrap, nor mmaps which cover the final page at index -1UL.
10801da177e4SLinus Torvalds  */
10811da177e4SLinus Torvalds static int
10821da177e4SLinus Torvalds can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
108319a809afSAndrea Arcangeli 		     struct anon_vma *anon_vma, struct file *file,
108419a809afSAndrea Arcangeli 		     pgoff_t vm_pgoff,
10859a10064fSColin Cross 		     struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
10865c26f6acSSuren Baghdasaryan 		     struct anon_vma_name *anon_name)
10871da177e4SLinus Torvalds {
10889a10064fSColin Cross 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1089965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
10901da177e4SLinus Torvalds 		if (vma->vm_pgoff == vm_pgoff)
10911da177e4SLinus Torvalds 			return 1;
10921da177e4SLinus Torvalds 	}
10931da177e4SLinus Torvalds 	return 0;
10941da177e4SLinus Torvalds }
10951da177e4SLinus Torvalds 
10961da177e4SLinus Torvalds /*
10971da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
10981da177e4SLinus Torvalds  * beyond (at a higher virtual address and file offset than) the vma.
10991da177e4SLinus Torvalds  *
11001da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
11011da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
11021da177e4SLinus Torvalds  */
11031da177e4SLinus Torvalds static int
11041da177e4SLinus Torvalds can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
110519a809afSAndrea Arcangeli 		    struct anon_vma *anon_vma, struct file *file,
110619a809afSAndrea Arcangeli 		    pgoff_t vm_pgoff,
11079a10064fSColin Cross 		    struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
11085c26f6acSSuren Baghdasaryan 		    struct anon_vma_name *anon_name)
11091da177e4SLinus Torvalds {
11109a10064fSColin Cross 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1111965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
11121da177e4SLinus Torvalds 		pgoff_t vm_pglen;
1113d6e93217SLibin 		vm_pglen = vma_pages(vma);
11141da177e4SLinus Torvalds 		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
11151da177e4SLinus Torvalds 			return 1;
11161da177e4SLinus Torvalds 	}
11171da177e4SLinus Torvalds 	return 0;
11181da177e4SLinus Torvalds }
11191da177e4SLinus Torvalds 
11201da177e4SLinus Torvalds /*
11219a10064fSColin Cross  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
11229a10064fSColin Cross  * figure out whether that can be merged with its predecessor or its
11239a10064fSColin Cross  * successor.  Or both (it neatly fills a hole).
11241da177e4SLinus Torvalds  *
11251da177e4SLinus Torvalds  * In most cases - when called for mmap, brk or mremap - [addr,end) is
11261da177e4SLinus Torvalds  * certain not to be mapped by the time vma_merge is called; but when
11271da177e4SLinus Torvalds  * called for mprotect, it is certain to be already mapped (either at
11281da177e4SLinus Torvalds  * an offset within prev, or at the start of next), and the flags of
11291da177e4SLinus Torvalds  * this area are about to be changed to vm_flags - and the no-change
11301da177e4SLinus Torvalds  * case has already been eliminated.
11311da177e4SLinus Torvalds  *
11321da177e4SLinus Torvalds  * The following mprotect cases have to be considered, where AAAA is
11331da177e4SLinus Torvalds  * the area passed down from mprotect_fixup, never extending beyond one
11341da177e4SLinus Torvalds  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
11351da177e4SLinus Torvalds  *
11365d42ab29SWei Yang  *     AAAA             AAAA                   AAAA
11375d42ab29SWei Yang  *    PPPPPPNNNNNN    PPPPPPNNNNNN       PPPPPPNNNNNN
11385d42ab29SWei Yang  *    cannot merge    might become       might become
11395d42ab29SWei Yang  *                    PPNNNNNNNNNN       PPPPPPPPPPNN
11405d42ab29SWei Yang  *    mmap, brk or    case 4 below       case 5 below
11415d42ab29SWei Yang  *    mremap move:
11425d42ab29SWei Yang  *                        AAAA               AAAA
11435d42ab29SWei Yang  *                    PPPP    NNNN       PPPPNNNNXXXX
11445d42ab29SWei Yang  *                    might become       might become
11455d42ab29SWei Yang  *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
11465d42ab29SWei Yang  *                    PPPPPPPPNNNN 2 or  PPPPPPPPXXXX 7 or
11475d42ab29SWei Yang  *                    PPPPNNNNNNNN 3     PPPPXXXXXXXX 8
11481da177e4SLinus Torvalds  *
11498bb4e7a2SWei Yang  * It is important for case 8 that the vma NNNN overlapping the
1150e86f15eeSAndrea Arcangeli  * region AAAA is never going to extended over XXXX. Instead XXXX must
1151e86f15eeSAndrea Arcangeli  * be extended in region AAAA and NNNN must be removed. This way in
1152e86f15eeSAndrea Arcangeli  * all cases where vma_merge succeeds, the moment vma_adjust drops the
1153e86f15eeSAndrea Arcangeli  * rmap_locks, the properties of the merged vma will be already
1154e86f15eeSAndrea Arcangeli  * correct for the whole merged range. Some of those properties like
1155e86f15eeSAndrea Arcangeli  * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
1156e86f15eeSAndrea Arcangeli  * be correct for the whole merged range immediately after the
1157e86f15eeSAndrea Arcangeli  * rmap_locks are released. Otherwise if XXXX would be removed and
1158e86f15eeSAndrea Arcangeli  * NNNN would be extended over the XXXX range, remove_migration_ptes
1159e86f15eeSAndrea Arcangeli  * or other rmap walkers (if working on addresses beyond the "end"
1160e86f15eeSAndrea Arcangeli  * parameter) may establish ptes with the wrong permissions of NNNN
1161e86f15eeSAndrea Arcangeli  * instead of the right permissions of XXXX.
11621da177e4SLinus Torvalds  */
11631da177e4SLinus Torvalds struct vm_area_struct *vma_merge(struct mm_struct *mm,
11641da177e4SLinus Torvalds 			struct vm_area_struct *prev, unsigned long addr,
11651da177e4SLinus Torvalds 			unsigned long end, unsigned long vm_flags,
11661da177e4SLinus Torvalds 			struct anon_vma *anon_vma, struct file *file,
116719a809afSAndrea Arcangeli 			pgoff_t pgoff, struct mempolicy *policy,
11689a10064fSColin Cross 			struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
11695c26f6acSSuren Baghdasaryan 			struct anon_vma_name *anon_name)
11701da177e4SLinus Torvalds {
11711da177e4SLinus Torvalds 	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
11721da177e4SLinus Torvalds 	struct vm_area_struct *area, *next;
11735beb4930SRik van Riel 	int err;
11741da177e4SLinus Torvalds 
11751da177e4SLinus Torvalds 	/*
11761da177e4SLinus Torvalds 	 * We later require that vma->vm_flags == vm_flags,
11771da177e4SLinus Torvalds 	 * so this tests vma->vm_flags & VM_SPECIAL, too.
11781da177e4SLinus Torvalds 	 */
11791da177e4SLinus Torvalds 	if (vm_flags & VM_SPECIAL)
11801da177e4SLinus Torvalds 		return NULL;
11811da177e4SLinus Torvalds 
1182f39af059SMatthew Wilcox (Oracle) 	next = __vma_next(mm, prev);
11831da177e4SLinus Torvalds 	area = next;
1184e86f15eeSAndrea Arcangeli 	if (area && area->vm_end == end)		/* cases 6, 7, 8 */
11851da177e4SLinus Torvalds 		next = next->vm_next;
11861da177e4SLinus Torvalds 
1187e86f15eeSAndrea Arcangeli 	/* verify some invariant that must be enforced by the caller */
1188e86f15eeSAndrea Arcangeli 	VM_WARN_ON(prev && addr <= prev->vm_start);
1189e86f15eeSAndrea Arcangeli 	VM_WARN_ON(area && end > area->vm_end);
1190e86f15eeSAndrea Arcangeli 	VM_WARN_ON(addr >= end);
1191e86f15eeSAndrea Arcangeli 
11921da177e4SLinus Torvalds 	/*
11931da177e4SLinus Torvalds 	 * Can it merge with the predecessor?
11941da177e4SLinus Torvalds 	 */
11951da177e4SLinus Torvalds 	if (prev && prev->vm_end == addr &&
11961da177e4SLinus Torvalds 			mpol_equal(vma_policy(prev), policy) &&
11971da177e4SLinus Torvalds 			can_vma_merge_after(prev, vm_flags,
119819a809afSAndrea Arcangeli 					    anon_vma, file, pgoff,
11999a10064fSColin Cross 					    vm_userfaultfd_ctx, anon_name)) {
12001da177e4SLinus Torvalds 		/*
12011da177e4SLinus Torvalds 		 * OK, it can.  Can we now merge in the successor as well?
12021da177e4SLinus Torvalds 		 */
12031da177e4SLinus Torvalds 		if (next && end == next->vm_start &&
12041da177e4SLinus Torvalds 				mpol_equal(policy, vma_policy(next)) &&
12051da177e4SLinus Torvalds 				can_vma_merge_before(next, vm_flags,
120619a809afSAndrea Arcangeli 						     anon_vma, file,
120719a809afSAndrea Arcangeli 						     pgoff+pglen,
12089a10064fSColin Cross 						     vm_userfaultfd_ctx, anon_name) &&
12091da177e4SLinus Torvalds 				is_mergeable_anon_vma(prev->anon_vma,
1210965f55deSShaohua Li 						      next->anon_vma, NULL)) {
12111da177e4SLinus Torvalds 							/* cases 1, 6 */
1212e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1213e86f15eeSAndrea Arcangeli 					 next->vm_end, prev->vm_pgoff, NULL,
1214e86f15eeSAndrea Arcangeli 					 prev);
12151da177e4SLinus Torvalds 		} else					/* cases 2, 5, 7 */
1216e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1217e86f15eeSAndrea Arcangeli 					 end, prev->vm_pgoff, NULL, prev);
12185beb4930SRik van Riel 		if (err)
12195beb4930SRik van Riel 			return NULL;
1220c791576cSYang Shi 		khugepaged_enter_vma(prev, vm_flags);
12211da177e4SLinus Torvalds 		return prev;
12221da177e4SLinus Torvalds 	}
12231da177e4SLinus Torvalds 
12241da177e4SLinus Torvalds 	/*
12251da177e4SLinus Torvalds 	 * Can this new request be merged in front of next?
12261da177e4SLinus Torvalds 	 */
12271da177e4SLinus Torvalds 	if (next && end == next->vm_start &&
12281da177e4SLinus Torvalds 			mpol_equal(policy, vma_policy(next)) &&
12291da177e4SLinus Torvalds 			can_vma_merge_before(next, vm_flags,
123019a809afSAndrea Arcangeli 					     anon_vma, file, pgoff+pglen,
12319a10064fSColin Cross 					     vm_userfaultfd_ctx, anon_name)) {
12321da177e4SLinus Torvalds 		if (prev && addr < prev->vm_end)	/* case 4 */
1233e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1234e86f15eeSAndrea Arcangeli 					 addr, prev->vm_pgoff, NULL, next);
1235e86f15eeSAndrea Arcangeli 		else {					/* cases 3, 8 */
1236e86f15eeSAndrea Arcangeli 			err = __vma_adjust(area, addr, next->vm_end,
1237e86f15eeSAndrea Arcangeli 					 next->vm_pgoff - pglen, NULL, next);
1238e86f15eeSAndrea Arcangeli 			/*
1239e86f15eeSAndrea Arcangeli 			 * In case 3 area is already equal to next and
1240e86f15eeSAndrea Arcangeli 			 * this is a noop, but in case 8 "area" has
1241e86f15eeSAndrea Arcangeli 			 * been removed and next was expanded over it.
1242e86f15eeSAndrea Arcangeli 			 */
1243e86f15eeSAndrea Arcangeli 			area = next;
1244e86f15eeSAndrea Arcangeli 		}
12455beb4930SRik van Riel 		if (err)
12465beb4930SRik van Riel 			return NULL;
1247c791576cSYang Shi 		khugepaged_enter_vma(area, vm_flags);
12481da177e4SLinus Torvalds 		return area;
12491da177e4SLinus Torvalds 	}
12501da177e4SLinus Torvalds 
12511da177e4SLinus Torvalds 	return NULL;
12521da177e4SLinus Torvalds }
12531da177e4SLinus Torvalds 
12541da177e4SLinus Torvalds /*
1255b4f315b4SEthon Paul  * Rough compatibility check to quickly see if it's even worth looking
1256d0e9fe17SLinus Torvalds  * at sharing an anon_vma.
1257d0e9fe17SLinus Torvalds  *
1258d0e9fe17SLinus Torvalds  * They need to have the same vm_file, and the flags can only differ
1259d0e9fe17SLinus Torvalds  * in things that mprotect may change.
1260d0e9fe17SLinus Torvalds  *
1261d0e9fe17SLinus Torvalds  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1262d0e9fe17SLinus Torvalds  * we can merge the two vma's. For example, we refuse to merge a vma if
1263d0e9fe17SLinus Torvalds  * there is a vm_ops->close() function, because that indicates that the
1264d0e9fe17SLinus Torvalds  * driver is doing some kind of reference counting. But that doesn't
1265d0e9fe17SLinus Torvalds  * really matter for the anon_vma sharing case.
1266d0e9fe17SLinus Torvalds  */
1267d0e9fe17SLinus Torvalds static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1268d0e9fe17SLinus Torvalds {
1269d0e9fe17SLinus Torvalds 	return a->vm_end == b->vm_start &&
1270d0e9fe17SLinus Torvalds 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1271d0e9fe17SLinus Torvalds 		a->vm_file == b->vm_file &&
12726cb4d9a2SAnshuman Khandual 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1273d0e9fe17SLinus Torvalds 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1274d0e9fe17SLinus Torvalds }
1275d0e9fe17SLinus Torvalds 
1276d0e9fe17SLinus Torvalds /*
1277d0e9fe17SLinus Torvalds  * Do some basic sanity checking to see if we can re-use the anon_vma
1278d0e9fe17SLinus Torvalds  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1279d0e9fe17SLinus Torvalds  * the same as 'old', the other will be the new one that is trying
1280d0e9fe17SLinus Torvalds  * to share the anon_vma.
1281d0e9fe17SLinus Torvalds  *
12825b449489SFlorian Rommel  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1283d0e9fe17SLinus Torvalds  * the anon_vma of 'old' is concurrently in the process of being set up
1284d0e9fe17SLinus Torvalds  * by another page fault trying to merge _that_. But that's ok: if it
1285d0e9fe17SLinus Torvalds  * is being set up, that automatically means that it will be a singleton
1286d0e9fe17SLinus Torvalds  * acceptable for merging, so we can do all of this optimistically. But
12874db0c3c2SJason Low  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1288d0e9fe17SLinus Torvalds  *
1289d0e9fe17SLinus Torvalds  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1290d0e9fe17SLinus Torvalds  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1291d0e9fe17SLinus Torvalds  * is to return an anon_vma that is "complex" due to having gone through
1292d0e9fe17SLinus Torvalds  * a fork).
1293d0e9fe17SLinus Torvalds  *
1294d0e9fe17SLinus Torvalds  * We also make sure that the two vma's are compatible (adjacent,
1295d0e9fe17SLinus Torvalds  * and with the same memory policies). That's all stable, even with just
12965b449489SFlorian Rommel  * a read lock on the mmap_lock.
1297d0e9fe17SLinus Torvalds  */
1298d0e9fe17SLinus Torvalds static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1299d0e9fe17SLinus Torvalds {
1300d0e9fe17SLinus Torvalds 	if (anon_vma_compatible(a, b)) {
13014db0c3c2SJason Low 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1302d0e9fe17SLinus Torvalds 
1303d0e9fe17SLinus Torvalds 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1304d0e9fe17SLinus Torvalds 			return anon_vma;
1305d0e9fe17SLinus Torvalds 	}
1306d0e9fe17SLinus Torvalds 	return NULL;
1307d0e9fe17SLinus Torvalds }
1308d0e9fe17SLinus Torvalds 
1309d0e9fe17SLinus Torvalds /*
13101da177e4SLinus Torvalds  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
13111da177e4SLinus Torvalds  * neighbouring vmas for a suitable anon_vma, before it goes off
13121da177e4SLinus Torvalds  * to allocate a new anon_vma.  It checks because a repetitive
13131da177e4SLinus Torvalds  * sequence of mprotects and faults may otherwise lead to distinct
13141da177e4SLinus Torvalds  * anon_vmas being allocated, preventing vma merge in subsequent
13151da177e4SLinus Torvalds  * mprotect.
13161da177e4SLinus Torvalds  */
13171da177e4SLinus Torvalds struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
13181da177e4SLinus Torvalds {
1319a67c8caaSMiaohe Lin 	struct anon_vma *anon_vma = NULL;
13201da177e4SLinus Torvalds 
1321a67c8caaSMiaohe Lin 	/* Try next first. */
1322a67c8caaSMiaohe Lin 	if (vma->vm_next) {
1323a67c8caaSMiaohe Lin 		anon_vma = reusable_anon_vma(vma->vm_next, vma, vma->vm_next);
1324d0e9fe17SLinus Torvalds 		if (anon_vma)
1325d0e9fe17SLinus Torvalds 			return anon_vma;
1326a67c8caaSMiaohe Lin 	}
13271da177e4SLinus Torvalds 
1328a67c8caaSMiaohe Lin 	/* Try prev next. */
1329a67c8caaSMiaohe Lin 	if (vma->vm_prev)
1330a67c8caaSMiaohe Lin 		anon_vma = reusable_anon_vma(vma->vm_prev, vma->vm_prev, vma);
1331a67c8caaSMiaohe Lin 
13321da177e4SLinus Torvalds 	/*
1333a67c8caaSMiaohe Lin 	 * We might reach here with anon_vma == NULL if we can't find
1334a67c8caaSMiaohe Lin 	 * any reusable anon_vma.
13351da177e4SLinus Torvalds 	 * There's no absolute need to look only at touching neighbours:
13361da177e4SLinus Torvalds 	 * we could search further afield for "compatible" anon_vmas.
13371da177e4SLinus Torvalds 	 * But it would probably just be a waste of time searching,
13381da177e4SLinus Torvalds 	 * or lead to too many vmas hanging off the same anon_vma.
13391da177e4SLinus Torvalds 	 * We're trying to allow mprotect remerging later on,
13401da177e4SLinus Torvalds 	 * not trying to minimize memory used for anon_vmas.
13411da177e4SLinus Torvalds 	 */
1342a67c8caaSMiaohe Lin 	return anon_vma;
13431da177e4SLinus Torvalds }
13441da177e4SLinus Torvalds 
13451da177e4SLinus Torvalds /*
134640401530SAl Viro  * If a hint addr is less than mmap_min_addr change hint to be as
134740401530SAl Viro  * low as possible but still greater than mmap_min_addr
134840401530SAl Viro  */
134940401530SAl Viro static inline unsigned long round_hint_to_min(unsigned long hint)
135040401530SAl Viro {
135140401530SAl Viro 	hint &= PAGE_MASK;
135240401530SAl Viro 	if (((void *)hint != NULL) &&
135340401530SAl Viro 	    (hint < mmap_min_addr))
135440401530SAl Viro 		return PAGE_ALIGN(mmap_min_addr);
135540401530SAl Viro 	return hint;
135640401530SAl Viro }
135740401530SAl Viro 
13586aeb2542SMike Rapoport int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1359363ee17fSDavidlohr Bueso 		       unsigned long len)
1360363ee17fSDavidlohr Bueso {
1361363ee17fSDavidlohr Bueso 	unsigned long locked, lock_limit;
1362363ee17fSDavidlohr Bueso 
1363363ee17fSDavidlohr Bueso 	/*  mlock MCL_FUTURE? */
1364363ee17fSDavidlohr Bueso 	if (flags & VM_LOCKED) {
1365363ee17fSDavidlohr Bueso 		locked = len >> PAGE_SHIFT;
1366363ee17fSDavidlohr Bueso 		locked += mm->locked_vm;
1367363ee17fSDavidlohr Bueso 		lock_limit = rlimit(RLIMIT_MEMLOCK);
1368363ee17fSDavidlohr Bueso 		lock_limit >>= PAGE_SHIFT;
1369363ee17fSDavidlohr Bueso 		if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1370363ee17fSDavidlohr Bueso 			return -EAGAIN;
1371363ee17fSDavidlohr Bueso 	}
1372363ee17fSDavidlohr Bueso 	return 0;
1373363ee17fSDavidlohr Bueso }
1374363ee17fSDavidlohr Bueso 
1375be83bbf8SLinus Torvalds static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1376be83bbf8SLinus Torvalds {
1377be83bbf8SLinus Torvalds 	if (S_ISREG(inode->i_mode))
1378423913adSLinus Torvalds 		return MAX_LFS_FILESIZE;
1379be83bbf8SLinus Torvalds 
1380be83bbf8SLinus Torvalds 	if (S_ISBLK(inode->i_mode))
1381be83bbf8SLinus Torvalds 		return MAX_LFS_FILESIZE;
1382be83bbf8SLinus Torvalds 
138376f34950SIvan Khoronzhuk 	if (S_ISSOCK(inode->i_mode))
138476f34950SIvan Khoronzhuk 		return MAX_LFS_FILESIZE;
138576f34950SIvan Khoronzhuk 
1386be83bbf8SLinus Torvalds 	/* Special "we do even unsigned file positions" case */
1387be83bbf8SLinus Torvalds 	if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1388be83bbf8SLinus Torvalds 		return 0;
1389be83bbf8SLinus Torvalds 
1390be83bbf8SLinus Torvalds 	/* Yes, random drivers might want more. But I'm tired of buggy drivers */
1391be83bbf8SLinus Torvalds 	return ULONG_MAX;
1392be83bbf8SLinus Torvalds }
1393be83bbf8SLinus Torvalds 
1394be83bbf8SLinus Torvalds static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1395be83bbf8SLinus Torvalds 				unsigned long pgoff, unsigned long len)
1396be83bbf8SLinus Torvalds {
1397be83bbf8SLinus Torvalds 	u64 maxsize = file_mmap_size_max(file, inode);
1398be83bbf8SLinus Torvalds 
1399be83bbf8SLinus Torvalds 	if (maxsize && len > maxsize)
1400be83bbf8SLinus Torvalds 		return false;
1401be83bbf8SLinus Torvalds 	maxsize -= len;
1402be83bbf8SLinus Torvalds 	if (pgoff > maxsize >> PAGE_SHIFT)
1403be83bbf8SLinus Torvalds 		return false;
1404be83bbf8SLinus Torvalds 	return true;
1405be83bbf8SLinus Torvalds }
1406be83bbf8SLinus Torvalds 
140740401530SAl Viro /*
14083e4e28c5SMichel Lespinasse  * The caller must write-lock current->mm->mmap_lock.
14091da177e4SLinus Torvalds  */
14101fcfd8dbSOleg Nesterov unsigned long do_mmap(struct file *file, unsigned long addr,
14111da177e4SLinus Torvalds 			unsigned long len, unsigned long prot,
141245e55300SPeter Collingbourne 			unsigned long flags, unsigned long pgoff,
141345e55300SPeter Collingbourne 			unsigned long *populate, struct list_head *uf)
14141da177e4SLinus Torvalds {
14151da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
141645e55300SPeter Collingbourne 	vm_flags_t vm_flags;
141762b5f7d0SDave Hansen 	int pkey = 0;
14181da177e4SLinus Torvalds 
1419524e00b3SLiam R. Howlett 	validate_mm(mm);
142041badc15SMichel Lespinasse 	*populate = 0;
1421bebeb3d6SMichel Lespinasse 
1422e37609bbSPiotr Kwapulinski 	if (!len)
1423e37609bbSPiotr Kwapulinski 		return -EINVAL;
1424e37609bbSPiotr Kwapulinski 
14251da177e4SLinus Torvalds 	/*
14261da177e4SLinus Torvalds 	 * Does the application expect PROT_READ to imply PROT_EXEC?
14271da177e4SLinus Torvalds 	 *
14281da177e4SLinus Torvalds 	 * (the exception is when the underlying filesystem is noexec
14291da177e4SLinus Torvalds 	 *  mounted, in which case we dont add PROT_EXEC.)
14301da177e4SLinus Torvalds 	 */
14311da177e4SLinus Torvalds 	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
143290f8572bSEric W. Biederman 		if (!(file && path_noexec(&file->f_path)))
14331da177e4SLinus Torvalds 			prot |= PROT_EXEC;
14341da177e4SLinus Torvalds 
1435a4ff8e86SMichal Hocko 	/* force arch specific MAP_FIXED handling in get_unmapped_area */
1436a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE)
1437a4ff8e86SMichal Hocko 		flags |= MAP_FIXED;
1438a4ff8e86SMichal Hocko 
14397cd94146SEric Paris 	if (!(flags & MAP_FIXED))
14407cd94146SEric Paris 		addr = round_hint_to_min(addr);
14417cd94146SEric Paris 
14421da177e4SLinus Torvalds 	/* Careful about overflows.. */
14431da177e4SLinus Torvalds 	len = PAGE_ALIGN(len);
14449206de95SAl Viro 	if (!len)
14451da177e4SLinus Torvalds 		return -ENOMEM;
14461da177e4SLinus Torvalds 
14471da177e4SLinus Torvalds 	/* offset overflow? */
14481da177e4SLinus Torvalds 	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
14491da177e4SLinus Torvalds 		return -EOVERFLOW;
14501da177e4SLinus Torvalds 
14511da177e4SLinus Torvalds 	/* Too many mappings? */
14521da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
14531da177e4SLinus Torvalds 		return -ENOMEM;
14541da177e4SLinus Torvalds 
14551da177e4SLinus Torvalds 	/* Obtain the address to map to. we verify (or select) it and ensure
14561da177e4SLinus Torvalds 	 * that it represents a valid section of the address space.
14571da177e4SLinus Torvalds 	 */
14581da177e4SLinus Torvalds 	addr = get_unmapped_area(file, addr, len, pgoff, flags);
1459ff68dac6SGaowei Pu 	if (IS_ERR_VALUE(addr))
14601da177e4SLinus Torvalds 		return addr;
14611da177e4SLinus Torvalds 
1462a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE) {
146335e43c5fSLiam Howlett 		if (find_vma_intersection(mm, addr, addr + len))
1464a4ff8e86SMichal Hocko 			return -EEXIST;
1465a4ff8e86SMichal Hocko 	}
1466a4ff8e86SMichal Hocko 
146762b5f7d0SDave Hansen 	if (prot == PROT_EXEC) {
146862b5f7d0SDave Hansen 		pkey = execute_only_pkey(mm);
146962b5f7d0SDave Hansen 		if (pkey < 0)
147062b5f7d0SDave Hansen 			pkey = 0;
147162b5f7d0SDave Hansen 	}
147262b5f7d0SDave Hansen 
14731da177e4SLinus Torvalds 	/* Do simple checking here so the lower-level routines won't have
14741da177e4SLinus Torvalds 	 * to. we assume access permissions have been handled by the open
14751da177e4SLinus Torvalds 	 * of the memory object, so we don't do any here.
14761da177e4SLinus Torvalds 	 */
147745e55300SPeter Collingbourne 	vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
14781da177e4SLinus Torvalds 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
14791da177e4SLinus Torvalds 
1480cdf7b341SHuang Shijie 	if (flags & MAP_LOCKED)
14811da177e4SLinus Torvalds 		if (!can_do_mlock())
14821da177e4SLinus Torvalds 			return -EPERM;
1483ba470de4SRik van Riel 
1484363ee17fSDavidlohr Bueso 	if (mlock_future_check(mm, vm_flags, len))
14851da177e4SLinus Torvalds 		return -EAGAIN;
14861da177e4SLinus Torvalds 
14871da177e4SLinus Torvalds 	if (file) {
1488077bf22bSOleg Nesterov 		struct inode *inode = file_inode(file);
14891c972597SDan Williams 		unsigned long flags_mask;
14901c972597SDan Williams 
1491be83bbf8SLinus Torvalds 		if (!file_mmap_ok(file, inode, pgoff, len))
1492be83bbf8SLinus Torvalds 			return -EOVERFLOW;
1493be83bbf8SLinus Torvalds 
14941c972597SDan Williams 		flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1495077bf22bSOleg Nesterov 
14961da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
14971da177e4SLinus Torvalds 		case MAP_SHARED:
14981c972597SDan Williams 			/*
14991c972597SDan Williams 			 * Force use of MAP_SHARED_VALIDATE with non-legacy
15001c972597SDan Williams 			 * flags. E.g. MAP_SYNC is dangerous to use with
15011c972597SDan Williams 			 * MAP_SHARED as you don't know which consistency model
15021c972597SDan Williams 			 * you will get. We silently ignore unsupported flags
15031c972597SDan Williams 			 * with MAP_SHARED to preserve backward compatibility.
15041c972597SDan Williams 			 */
15051c972597SDan Williams 			flags &= LEGACY_MAP_MASK;
1506e4a9bc58SJoe Perches 			fallthrough;
15071c972597SDan Williams 		case MAP_SHARED_VALIDATE:
15081c972597SDan Williams 			if (flags & ~flags_mask)
15091c972597SDan Williams 				return -EOPNOTSUPP;
1510dc617f29SDarrick J. Wong 			if (prot & PROT_WRITE) {
1511dc617f29SDarrick J. Wong 				if (!(file->f_mode & FMODE_WRITE))
15121da177e4SLinus Torvalds 					return -EACCES;
1513dc617f29SDarrick J. Wong 				if (IS_SWAPFILE(file->f_mapping->host))
1514dc617f29SDarrick J. Wong 					return -ETXTBSY;
1515dc617f29SDarrick J. Wong 			}
15161da177e4SLinus Torvalds 
15171da177e4SLinus Torvalds 			/*
15181da177e4SLinus Torvalds 			 * Make sure we don't allow writing to an append-only
15191da177e4SLinus Torvalds 			 * file..
15201da177e4SLinus Torvalds 			 */
15211da177e4SLinus Torvalds 			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
15221da177e4SLinus Torvalds 				return -EACCES;
15231da177e4SLinus Torvalds 
15241da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
15251da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_WRITE))
15261da177e4SLinus Torvalds 				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1527e4a9bc58SJoe Perches 			fallthrough;
15281da177e4SLinus Torvalds 		case MAP_PRIVATE:
15291da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_READ))
15301da177e4SLinus Torvalds 				return -EACCES;
153190f8572bSEric W. Biederman 			if (path_noexec(&file->f_path)) {
153280c5606cSLinus Torvalds 				if (vm_flags & VM_EXEC)
153380c5606cSLinus Torvalds 					return -EPERM;
153480c5606cSLinus Torvalds 				vm_flags &= ~VM_MAYEXEC;
153580c5606cSLinus Torvalds 			}
153680c5606cSLinus Torvalds 
153772c2d531SAl Viro 			if (!file->f_op->mmap)
153880c5606cSLinus Torvalds 				return -ENODEV;
1539b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1540b2c56e4fSOleg Nesterov 				return -EINVAL;
15411da177e4SLinus Torvalds 			break;
15421da177e4SLinus Torvalds 
15431da177e4SLinus Torvalds 		default:
15441da177e4SLinus Torvalds 			return -EINVAL;
15451da177e4SLinus Torvalds 		}
15461da177e4SLinus Torvalds 	} else {
15471da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
15481da177e4SLinus Torvalds 		case MAP_SHARED:
1549b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1550b2c56e4fSOleg Nesterov 				return -EINVAL;
1551ce363942STejun Heo 			/*
1552ce363942STejun Heo 			 * Ignore pgoff.
1553ce363942STejun Heo 			 */
1554ce363942STejun Heo 			pgoff = 0;
15551da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
15561da177e4SLinus Torvalds 			break;
15571da177e4SLinus Torvalds 		case MAP_PRIVATE:
15581da177e4SLinus Torvalds 			/*
15591da177e4SLinus Torvalds 			 * Set pgoff according to addr for anon_vma.
15601da177e4SLinus Torvalds 			 */
15611da177e4SLinus Torvalds 			pgoff = addr >> PAGE_SHIFT;
15621da177e4SLinus Torvalds 			break;
15631da177e4SLinus Torvalds 		default:
15641da177e4SLinus Torvalds 			return -EINVAL;
15651da177e4SLinus Torvalds 		}
15661da177e4SLinus Torvalds 	}
15671da177e4SLinus Torvalds 
1568c22c0d63SMichel Lespinasse 	/*
1569c22c0d63SMichel Lespinasse 	 * Set 'VM_NORESERVE' if we should not account for the
1570c22c0d63SMichel Lespinasse 	 * memory use of this mapping.
1571c22c0d63SMichel Lespinasse 	 */
1572c22c0d63SMichel Lespinasse 	if (flags & MAP_NORESERVE) {
1573c22c0d63SMichel Lespinasse 		/* We honor MAP_NORESERVE if allowed to overcommit */
1574c22c0d63SMichel Lespinasse 		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1575c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1576c22c0d63SMichel Lespinasse 
1577c22c0d63SMichel Lespinasse 		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
1578c22c0d63SMichel Lespinasse 		if (file && is_file_hugepages(file))
1579c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1580c22c0d63SMichel Lespinasse 	}
1581c22c0d63SMichel Lespinasse 
1582897ab3e0SMike Rapoport 	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
158309a9f1d2SMichel Lespinasse 	if (!IS_ERR_VALUE(addr) &&
158409a9f1d2SMichel Lespinasse 	    ((vm_flags & VM_LOCKED) ||
158509a9f1d2SMichel Lespinasse 	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
158641badc15SMichel Lespinasse 		*populate = len;
1587bebeb3d6SMichel Lespinasse 	return addr;
15880165ab44SMiklos Szeredi }
15896be5ceb0SLinus Torvalds 
1590a90f590aSDominik Brodowski unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1591a90f590aSDominik Brodowski 			      unsigned long prot, unsigned long flags,
1592a90f590aSDominik Brodowski 			      unsigned long fd, unsigned long pgoff)
159366f0dc48SHugh Dickins {
159466f0dc48SHugh Dickins 	struct file *file = NULL;
15951e3ee14bSChen Gang 	unsigned long retval;
159666f0dc48SHugh Dickins 
159766f0dc48SHugh Dickins 	if (!(flags & MAP_ANONYMOUS)) {
1598120a795dSAl Viro 		audit_mmap_fd(fd, flags);
159966f0dc48SHugh Dickins 		file = fget(fd);
160066f0dc48SHugh Dickins 		if (!file)
16011e3ee14bSChen Gang 			return -EBADF;
16027bba8f0eSZhen Lei 		if (is_file_hugepages(file)) {
1603af73e4d9SNaoya Horiguchi 			len = ALIGN(len, huge_page_size(hstate_file(file)));
16047bba8f0eSZhen Lei 		} else if (unlikely(flags & MAP_HUGETLB)) {
1605493af578SJörn Engel 			retval = -EINVAL;
1606493af578SJörn Engel 			goto out_fput;
16077bba8f0eSZhen Lei 		}
160866f0dc48SHugh Dickins 	} else if (flags & MAP_HUGETLB) {
1609c103a4dcSAndrew Morton 		struct hstate *hs;
1610af73e4d9SNaoya Horiguchi 
161120ac2893SAnshuman Khandual 		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1612091d0d55SLi Zefan 		if (!hs)
1613091d0d55SLi Zefan 			return -EINVAL;
1614091d0d55SLi Zefan 
1615091d0d55SLi Zefan 		len = ALIGN(len, huge_page_size(hs));
161666f0dc48SHugh Dickins 		/*
161766f0dc48SHugh Dickins 		 * VM_NORESERVE is used because the reservations will be
161866f0dc48SHugh Dickins 		 * taken when vm_ops->mmap() is called
161966f0dc48SHugh Dickins 		 */
1620af73e4d9SNaoya Horiguchi 		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
162142d7395fSAndi Kleen 				VM_NORESERVE,
162283c1fd76Szhangyiru 				HUGETLB_ANONHUGE_INODE,
162342d7395fSAndi Kleen 				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
162466f0dc48SHugh Dickins 		if (IS_ERR(file))
162566f0dc48SHugh Dickins 			return PTR_ERR(file);
162666f0dc48SHugh Dickins 	}
162766f0dc48SHugh Dickins 
16289fbeb5abSMichal Hocko 	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1629493af578SJörn Engel out_fput:
163066f0dc48SHugh Dickins 	if (file)
163166f0dc48SHugh Dickins 		fput(file);
163266f0dc48SHugh Dickins 	return retval;
163366f0dc48SHugh Dickins }
163466f0dc48SHugh Dickins 
1635a90f590aSDominik Brodowski SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1636a90f590aSDominik Brodowski 		unsigned long, prot, unsigned long, flags,
1637a90f590aSDominik Brodowski 		unsigned long, fd, unsigned long, pgoff)
1638a90f590aSDominik Brodowski {
1639a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1640a90f590aSDominik Brodowski }
1641a90f590aSDominik Brodowski 
1642a4679373SChristoph Hellwig #ifdef __ARCH_WANT_SYS_OLD_MMAP
1643a4679373SChristoph Hellwig struct mmap_arg_struct {
1644a4679373SChristoph Hellwig 	unsigned long addr;
1645a4679373SChristoph Hellwig 	unsigned long len;
1646a4679373SChristoph Hellwig 	unsigned long prot;
1647a4679373SChristoph Hellwig 	unsigned long flags;
1648a4679373SChristoph Hellwig 	unsigned long fd;
1649a4679373SChristoph Hellwig 	unsigned long offset;
1650a4679373SChristoph Hellwig };
1651a4679373SChristoph Hellwig 
1652a4679373SChristoph Hellwig SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1653a4679373SChristoph Hellwig {
1654a4679373SChristoph Hellwig 	struct mmap_arg_struct a;
1655a4679373SChristoph Hellwig 
1656a4679373SChristoph Hellwig 	if (copy_from_user(&a, arg, sizeof(a)))
1657a4679373SChristoph Hellwig 		return -EFAULT;
1658de1741a1SAlexander Kuleshov 	if (offset_in_page(a.offset))
1659a4679373SChristoph Hellwig 		return -EINVAL;
1660a4679373SChristoph Hellwig 
1661a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1662a4679373SChristoph Hellwig 			       a.offset >> PAGE_SHIFT);
1663a4679373SChristoph Hellwig }
1664a4679373SChristoph Hellwig #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1665a4679373SChristoph Hellwig 
16664e950f6fSAlexey Dobriyan /*
16678bb4e7a2SWei Yang  * Some shared mappings will want the pages marked read-only
16684e950f6fSAlexey Dobriyan  * to track write events. If so, we'll downgrade vm_page_prot
16694e950f6fSAlexey Dobriyan  * to the private version (using protection_map[] without the
16704e950f6fSAlexey Dobriyan  * VM_SHARED bit).
16714e950f6fSAlexey Dobriyan  */
16726d2329f8SAndrea Arcangeli int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
16734e950f6fSAlexey Dobriyan {
1674ca16d140SKOSAKI Motohiro 	vm_flags_t vm_flags = vma->vm_flags;
16758a04446aSKirill A. Shutemov 	const struct vm_operations_struct *vm_ops = vma->vm_ops;
16764e950f6fSAlexey Dobriyan 
16774e950f6fSAlexey Dobriyan 	/* If it was private or non-writable, the write bit is already clear */
16784e950f6fSAlexey Dobriyan 	if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
16794e950f6fSAlexey Dobriyan 		return 0;
16804e950f6fSAlexey Dobriyan 
16814e950f6fSAlexey Dobriyan 	/* The backer wishes to know when pages are first written to? */
16828a04446aSKirill A. Shutemov 	if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
16834e950f6fSAlexey Dobriyan 		return 1;
16844e950f6fSAlexey Dobriyan 
168564e45507SPeter Feiner 	/* The open routine did something to the protections that pgprot_modify
168664e45507SPeter Feiner 	 * won't preserve? */
16876d2329f8SAndrea Arcangeli 	if (pgprot_val(vm_page_prot) !=
16886d2329f8SAndrea Arcangeli 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
16894e950f6fSAlexey Dobriyan 		return 0;
16904e950f6fSAlexey Dobriyan 
1691f96f7a40SDavid Hildenbrand 	/*
1692f96f7a40SDavid Hildenbrand 	 * Do we need to track softdirty? hugetlb does not support softdirty
1693f96f7a40SDavid Hildenbrand 	 * tracking yet.
1694f96f7a40SDavid Hildenbrand 	 */
1695f96f7a40SDavid Hildenbrand 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
169664e45507SPeter Feiner 		return 1;
169764e45507SPeter Feiner 
16984e950f6fSAlexey Dobriyan 	/* Specialty mapping? */
16994b6e1e37SKonstantin Khlebnikov 	if (vm_flags & VM_PFNMAP)
17004e950f6fSAlexey Dobriyan 		return 0;
17014e950f6fSAlexey Dobriyan 
17024e950f6fSAlexey Dobriyan 	/* Can the mapping track the dirty pages? */
17034e950f6fSAlexey Dobriyan 	return vma->vm_file && vma->vm_file->f_mapping &&
1704f56753acSChristoph Hellwig 		mapping_can_writeback(vma->vm_file->f_mapping);
17054e950f6fSAlexey Dobriyan }
17064e950f6fSAlexey Dobriyan 
1707fc8744adSLinus Torvalds /*
1708fc8744adSLinus Torvalds  * We account for memory if it's a private writeable mapping,
17095a6fe125SMel Gorman  * not hugepages and VM_NORESERVE wasn't set.
1710fc8744adSLinus Torvalds  */
1711ca16d140SKOSAKI Motohiro static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1712fc8744adSLinus Torvalds {
17135a6fe125SMel Gorman 	/*
17145a6fe125SMel Gorman 	 * hugetlb has its own accounting separate from the core VM
17155a6fe125SMel Gorman 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
17165a6fe125SMel Gorman 	 */
17175a6fe125SMel Gorman 	if (file && is_file_hugepages(file))
17185a6fe125SMel Gorman 		return 0;
17195a6fe125SMel Gorman 
1720fc8744adSLinus Torvalds 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1721fc8744adSLinus Torvalds }
1722fc8744adSLinus Torvalds 
17233499a131SLiam R. Howlett /**
17243499a131SLiam R. Howlett  * unmapped_area() - Find an area between the low_limit and the high_limit with
17253499a131SLiam R. Howlett  * the correct alignment and offset, all from @info. Note: current->mm is used
17263499a131SLiam R. Howlett  * for the search.
17273499a131SLiam R. Howlett  *
17283499a131SLiam R. Howlett  * @info: The unmapped area information including the range (low_limit -
17293499a131SLiam R. Howlett  * hight_limit), the alignment offset and mask.
17303499a131SLiam R. Howlett  *
17313499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
17323499a131SLiam R. Howlett  */
1733baceaf1cSJaewon Kim static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1734db4fbfb9SMichel Lespinasse {
17353499a131SLiam R. Howlett 	unsigned long length, gap;
1736db4fbfb9SMichel Lespinasse 
17373499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1738db4fbfb9SMichel Lespinasse 
1739db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1740db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1741db4fbfb9SMichel Lespinasse 	if (length < info->length)
1742db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1743db4fbfb9SMichel Lespinasse 
17443499a131SLiam R. Howlett 	if (mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
17453499a131SLiam R. Howlett 				  length))
17463499a131SLiam R. Howlett 		return -ENOMEM;
17473499a131SLiam R. Howlett 
1748d4af56c5SLiam R. Howlett 	gap = mas.index;
1749d4af56c5SLiam R. Howlett 	gap += (info->align_offset - gap) & info->align_mask;
17503499a131SLiam R. Howlett 	return gap;
1751db4fbfb9SMichel Lespinasse }
1752db4fbfb9SMichel Lespinasse 
17533499a131SLiam R. Howlett /**
17543499a131SLiam R. Howlett  * unmapped_area_topdown() - Find an area between the low_limit and the
17553499a131SLiam R. Howlett  * high_limit with * the correct alignment and offset at the highest available
17563499a131SLiam R. Howlett  * address, all from @info. Note: current->mm is used for the search.
17573499a131SLiam R. Howlett  *
17583499a131SLiam R. Howlett  * @info: The unmapped area information including the range (low_limit -
17593499a131SLiam R. Howlett  * hight_limit), the alignment offset and mask.
17603499a131SLiam R. Howlett  *
17613499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
17623499a131SLiam R. Howlett  */
1763baceaf1cSJaewon Kim static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1764db4fbfb9SMichel Lespinasse {
17653499a131SLiam R. Howlett 	unsigned long length, gap;
1766d4af56c5SLiam R. Howlett 
17673499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1768db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1769db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1770db4fbfb9SMichel Lespinasse 	if (length < info->length)
1771db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1772db4fbfb9SMichel Lespinasse 
17733499a131SLiam R. Howlett 	if (mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
17743499a131SLiam R. Howlett 				length))
17753499a131SLiam R. Howlett 		return -ENOMEM;
17763499a131SLiam R. Howlett 
1777d4af56c5SLiam R. Howlett 	gap = mas.last + 1 - info->length;
1778d4af56c5SLiam R. Howlett 	gap -= (gap - info->align_offset) & info->align_mask;
17793499a131SLiam R. Howlett 	return gap;
1780db4fbfb9SMichel Lespinasse }
1781db4fbfb9SMichel Lespinasse 
1782baceaf1cSJaewon Kim /*
1783baceaf1cSJaewon Kim  * Search for an unmapped address range.
1784baceaf1cSJaewon Kim  *
1785baceaf1cSJaewon Kim  * We are looking for a range that:
1786baceaf1cSJaewon Kim  * - does not intersect with any VMA;
1787baceaf1cSJaewon Kim  * - is contained within the [low_limit, high_limit) interval;
1788baceaf1cSJaewon Kim  * - is at least the desired size.
1789baceaf1cSJaewon Kim  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
1790baceaf1cSJaewon Kim  */
1791baceaf1cSJaewon Kim unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
1792baceaf1cSJaewon Kim {
1793df529cabSJaewon Kim 	unsigned long addr;
1794df529cabSJaewon Kim 
1795baceaf1cSJaewon Kim 	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1796df529cabSJaewon Kim 		addr = unmapped_area_topdown(info);
1797baceaf1cSJaewon Kim 	else
1798df529cabSJaewon Kim 		addr = unmapped_area(info);
1799df529cabSJaewon Kim 
1800df529cabSJaewon Kim 	trace_vm_unmapped_area(addr, info);
1801df529cabSJaewon Kim 	return addr;
1802baceaf1cSJaewon Kim }
1803f6795053SSteve Capper 
18041da177e4SLinus Torvalds /* Get an address range which is currently unmapped.
18051da177e4SLinus Torvalds  * For shmat() with addr=0.
18061da177e4SLinus Torvalds  *
18071da177e4SLinus Torvalds  * Ugly calling convention alert:
18081da177e4SLinus Torvalds  * Return value with the low bits set means error value,
18091da177e4SLinus Torvalds  * ie
18101da177e4SLinus Torvalds  *	if (ret & ~PAGE_MASK)
18111da177e4SLinus Torvalds  *		error = ret;
18121da177e4SLinus Torvalds  *
18131da177e4SLinus Torvalds  * This function "knows" that -ENOMEM has the bits set.
18141da177e4SLinus Torvalds  */
18151da177e4SLinus Torvalds unsigned long
18164b439e25SChristophe Leroy generic_get_unmapped_area(struct file *filp, unsigned long addr,
18174b439e25SChristophe Leroy 			  unsigned long len, unsigned long pgoff,
18184b439e25SChristophe Leroy 			  unsigned long flags)
18191da177e4SLinus Torvalds {
18201da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
18211be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
1822db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
18232cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
18241da177e4SLinus Torvalds 
1825f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
18261da177e4SLinus Torvalds 		return -ENOMEM;
18271da177e4SLinus Torvalds 
182806abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
182906abdfb4SBenjamin Herrenschmidt 		return addr;
183006abdfb4SBenjamin Herrenschmidt 
18311da177e4SLinus Torvalds 	if (addr) {
18321da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
18331be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1834f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
18351be7107fSHugh Dickins 		    (!vma || addr + len <= vm_start_gap(vma)) &&
18361be7107fSHugh Dickins 		    (!prev || addr >= vm_end_gap(prev)))
18371da177e4SLinus Torvalds 			return addr;
18381da177e4SLinus Torvalds 	}
18391da177e4SLinus Torvalds 
1840db4fbfb9SMichel Lespinasse 	info.flags = 0;
1841db4fbfb9SMichel Lespinasse 	info.length = len;
18424e99b021SHeiko Carstens 	info.low_limit = mm->mmap_base;
1843f6795053SSteve Capper 	info.high_limit = mmap_end;
1844db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
184509ef5283SJaewon Kim 	info.align_offset = 0;
1846db4fbfb9SMichel Lespinasse 	return vm_unmapped_area(&info);
18471da177e4SLinus Torvalds }
18484b439e25SChristophe Leroy 
18494b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA
18504b439e25SChristophe Leroy unsigned long
18514b439e25SChristophe Leroy arch_get_unmapped_area(struct file *filp, unsigned long addr,
18524b439e25SChristophe Leroy 		       unsigned long len, unsigned long pgoff,
18534b439e25SChristophe Leroy 		       unsigned long flags)
18544b439e25SChristophe Leroy {
18554b439e25SChristophe Leroy 	return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
18564b439e25SChristophe Leroy }
18571da177e4SLinus Torvalds #endif
18581da177e4SLinus Torvalds 
18591da177e4SLinus Torvalds /*
18601da177e4SLinus Torvalds  * This mmap-allocator allocates new areas top-down from below the
18611da177e4SLinus Torvalds  * stack's low limit (the base):
18621da177e4SLinus Torvalds  */
18631da177e4SLinus Torvalds unsigned long
18644b439e25SChristophe Leroy generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
186543cca0b1SYang Fan 				  unsigned long len, unsigned long pgoff,
186643cca0b1SYang Fan 				  unsigned long flags)
18671da177e4SLinus Torvalds {
18681be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
18691da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1870db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
18712cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
18721da177e4SLinus Torvalds 
18731da177e4SLinus Torvalds 	/* requested length too big for entire address space */
1874f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
18751da177e4SLinus Torvalds 		return -ENOMEM;
18761da177e4SLinus Torvalds 
187706abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
187806abdfb4SBenjamin Herrenschmidt 		return addr;
187906abdfb4SBenjamin Herrenschmidt 
18801da177e4SLinus Torvalds 	/* requesting a specific address */
18811da177e4SLinus Torvalds 	if (addr) {
18821da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
18831be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1884f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
18851be7107fSHugh Dickins 				(!vma || addr + len <= vm_start_gap(vma)) &&
18861be7107fSHugh Dickins 				(!prev || addr >= vm_end_gap(prev)))
18871da177e4SLinus Torvalds 			return addr;
18881da177e4SLinus Torvalds 	}
18891da177e4SLinus Torvalds 
1890db4fbfb9SMichel Lespinasse 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1891db4fbfb9SMichel Lespinasse 	info.length = len;
18922afc745fSAkira Takeuchi 	info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1893f6795053SSteve Capper 	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1894db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
189509ef5283SJaewon Kim 	info.align_offset = 0;
1896db4fbfb9SMichel Lespinasse 	addr = vm_unmapped_area(&info);
1897b716ad95SXiao Guangrong 
18981da177e4SLinus Torvalds 	/*
18991da177e4SLinus Torvalds 	 * A failed mmap() very likely causes application failure,
19001da177e4SLinus Torvalds 	 * so fall back to the bottom-up function here. This scenario
19011da177e4SLinus Torvalds 	 * can happen with large stack limits and large mmap()
19021da177e4SLinus Torvalds 	 * allocations.
19031da177e4SLinus Torvalds 	 */
1904de1741a1SAlexander Kuleshov 	if (offset_in_page(addr)) {
1905db4fbfb9SMichel Lespinasse 		VM_BUG_ON(addr != -ENOMEM);
1906db4fbfb9SMichel Lespinasse 		info.flags = 0;
1907db4fbfb9SMichel Lespinasse 		info.low_limit = TASK_UNMAPPED_BASE;
1908f6795053SSteve Capper 		info.high_limit = mmap_end;
1909db4fbfb9SMichel Lespinasse 		addr = vm_unmapped_area(&info);
1910db4fbfb9SMichel Lespinasse 	}
19111da177e4SLinus Torvalds 
19121da177e4SLinus Torvalds 	return addr;
19131da177e4SLinus Torvalds }
19144b439e25SChristophe Leroy 
19154b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
19164b439e25SChristophe Leroy unsigned long
19174b439e25SChristophe Leroy arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
19184b439e25SChristophe Leroy 			       unsigned long len, unsigned long pgoff,
19194b439e25SChristophe Leroy 			       unsigned long flags)
19204b439e25SChristophe Leroy {
19214b439e25SChristophe Leroy 	return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
19224b439e25SChristophe Leroy }
19231da177e4SLinus Torvalds #endif
19241da177e4SLinus Torvalds 
19251da177e4SLinus Torvalds unsigned long
19261da177e4SLinus Torvalds get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
19271da177e4SLinus Torvalds 		unsigned long pgoff, unsigned long flags)
19281da177e4SLinus Torvalds {
192906abdfb4SBenjamin Herrenschmidt 	unsigned long (*get_area)(struct file *, unsigned long,
193006abdfb4SBenjamin Herrenschmidt 				  unsigned long, unsigned long, unsigned long);
193107ab67c8SLinus Torvalds 
19329206de95SAl Viro 	unsigned long error = arch_mmap_check(addr, len, flags);
19339206de95SAl Viro 	if (error)
19349206de95SAl Viro 		return error;
19359206de95SAl Viro 
19369206de95SAl Viro 	/* Careful about overflows.. */
19379206de95SAl Viro 	if (len > TASK_SIZE)
19389206de95SAl Viro 		return -ENOMEM;
19399206de95SAl Viro 
194007ab67c8SLinus Torvalds 	get_area = current->mm->get_unmapped_area;
1941c01d5b30SHugh Dickins 	if (file) {
1942c01d5b30SHugh Dickins 		if (file->f_op->get_unmapped_area)
194307ab67c8SLinus Torvalds 			get_area = file->f_op->get_unmapped_area;
1944c01d5b30SHugh Dickins 	} else if (flags & MAP_SHARED) {
1945c01d5b30SHugh Dickins 		/*
1946c01d5b30SHugh Dickins 		 * mmap_region() will call shmem_zero_setup() to create a file,
1947c01d5b30SHugh Dickins 		 * so use shmem's get_unmapped_area in case it can be huge.
194845e55300SPeter Collingbourne 		 * do_mmap() will clear pgoff, so match alignment.
1949c01d5b30SHugh Dickins 		 */
1950c01d5b30SHugh Dickins 		pgoff = 0;
1951c01d5b30SHugh Dickins 		get_area = shmem_get_unmapped_area;
1952f35b5d7dSRik van Riel 	} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
1953f35b5d7dSRik van Riel 		/* Ensures that larger anonymous mappings are THP aligned. */
1954f35b5d7dSRik van Riel 		get_area = thp_get_unmapped_area;
1955c01d5b30SHugh Dickins 	}
1956c01d5b30SHugh Dickins 
195707ab67c8SLinus Torvalds 	addr = get_area(file, addr, len, pgoff, flags);
195807ab67c8SLinus Torvalds 	if (IS_ERR_VALUE(addr))
195907ab67c8SLinus Torvalds 		return addr;
196007ab67c8SLinus Torvalds 
19611da177e4SLinus Torvalds 	if (addr > TASK_SIZE - len)
19621da177e4SLinus Torvalds 		return -ENOMEM;
1963de1741a1SAlexander Kuleshov 	if (offset_in_page(addr))
19641da177e4SLinus Torvalds 		return -EINVAL;
196506abdfb4SBenjamin Herrenschmidt 
19669ac4ed4bSAl Viro 	error = security_mmap_addr(addr);
19679ac4ed4bSAl Viro 	return error ? error : addr;
19681da177e4SLinus Torvalds }
19691da177e4SLinus Torvalds 
19701da177e4SLinus Torvalds EXPORT_SYMBOL(get_unmapped_area);
19711da177e4SLinus Torvalds 
1972be8432e7SLiam R. Howlett /**
1973abdba2ddSLiam R. Howlett  * find_vma_intersection() - Look up the first VMA which intersects the interval
1974abdba2ddSLiam R. Howlett  * @mm: The process address space.
1975abdba2ddSLiam R. Howlett  * @start_addr: The inclusive start user address.
1976abdba2ddSLiam R. Howlett  * @end_addr: The exclusive end user address.
1977abdba2ddSLiam R. Howlett  *
1978abdba2ddSLiam R. Howlett  * Returns: The first VMA within the provided range, %NULL otherwise.  Assumes
1979abdba2ddSLiam R. Howlett  * start_addr < end_addr.
1980abdba2ddSLiam R. Howlett  */
1981abdba2ddSLiam R. Howlett struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
1982abdba2ddSLiam R. Howlett 					     unsigned long start_addr,
1983abdba2ddSLiam R. Howlett 					     unsigned long end_addr)
1984abdba2ddSLiam R. Howlett {
1985abdba2ddSLiam R. Howlett 	unsigned long index = start_addr;
1986abdba2ddSLiam R. Howlett 
1987abdba2ddSLiam R. Howlett 	mmap_assert_locked(mm);
19887964cf8cSLiam R. Howlett 	return mt_find(&mm->mm_mt, &index, end_addr - 1);
1989abdba2ddSLiam R. Howlett }
1990abdba2ddSLiam R. Howlett EXPORT_SYMBOL(find_vma_intersection);
1991abdba2ddSLiam R. Howlett 
1992abdba2ddSLiam R. Howlett /**
1993be8432e7SLiam R. Howlett  * find_vma() - Find the VMA for a given address, or the next VMA.
1994be8432e7SLiam R. Howlett  * @mm: The mm_struct to check
1995be8432e7SLiam R. Howlett  * @addr: The address
1996be8432e7SLiam R. Howlett  *
1997be8432e7SLiam R. Howlett  * Returns: The VMA associated with addr, or the next VMA.
1998be8432e7SLiam R. Howlett  * May return %NULL in the case of no VMA at addr or above.
1999be8432e7SLiam R. Howlett  */
20001da177e4SLinus Torvalds struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
20011da177e4SLinus Torvalds {
2002be8432e7SLiam R. Howlett 	unsigned long index = addr;
20031da177e4SLinus Torvalds 
20045b78ed24SLuigi Rizzo 	mmap_assert_locked(mm);
20057964cf8cSLiam R. Howlett 	return mt_find(&mm->mm_mt, &index, ULONG_MAX);
20061da177e4SLinus Torvalds }
20071da177e4SLinus Torvalds EXPORT_SYMBOL(find_vma);
20081da177e4SLinus Torvalds 
20097fdbd37dSLiam R. Howlett /**
20107fdbd37dSLiam R. Howlett  * find_vma_prev() - Find the VMA for a given address, or the next vma and
20117fdbd37dSLiam R. Howlett  * set %pprev to the previous VMA, if any.
20127fdbd37dSLiam R. Howlett  * @mm: The mm_struct to check
20137fdbd37dSLiam R. Howlett  * @addr: The address
20147fdbd37dSLiam R. Howlett  * @pprev: The pointer to set to the previous VMA
20157fdbd37dSLiam R. Howlett  *
20167fdbd37dSLiam R. Howlett  * Note that RCU lock is missing here since the external mmap_lock() is used
20177fdbd37dSLiam R. Howlett  * instead.
20187fdbd37dSLiam R. Howlett  *
20197fdbd37dSLiam R. Howlett  * Returns: The VMA associated with @addr, or the next vma.
20207fdbd37dSLiam R. Howlett  * May return %NULL in the case of no vma at addr or above.
20216bd4837dSKOSAKI Motohiro  */
20221da177e4SLinus Torvalds struct vm_area_struct *
20231da177e4SLinus Torvalds find_vma_prev(struct mm_struct *mm, unsigned long addr,
20241da177e4SLinus Torvalds 			struct vm_area_struct **pprev)
20251da177e4SLinus Torvalds {
20266bd4837dSKOSAKI Motohiro 	struct vm_area_struct *vma;
20277fdbd37dSLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, addr, addr);
20281da177e4SLinus Torvalds 
20297fdbd37dSLiam R. Howlett 	vma = mas_walk(&mas);
20307fdbd37dSLiam R. Howlett 	*pprev = mas_prev(&mas, 0);
20317fdbd37dSLiam R. Howlett 	if (!vma)
20327fdbd37dSLiam R. Howlett 		vma = mas_next(&mas, ULONG_MAX);
20336bd4837dSKOSAKI Motohiro 	return vma;
20341da177e4SLinus Torvalds }
20351da177e4SLinus Torvalds 
20361da177e4SLinus Torvalds /*
20371da177e4SLinus Torvalds  * Verify that the stack growth is acceptable and
20381da177e4SLinus Torvalds  * update accounting. This is shared with both the
20391da177e4SLinus Torvalds  * grow-up and grow-down cases.
20401da177e4SLinus Torvalds  */
20411be7107fSHugh Dickins static int acct_stack_growth(struct vm_area_struct *vma,
20421be7107fSHugh Dickins 			     unsigned long size, unsigned long grow)
20431da177e4SLinus Torvalds {
20441da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
20451be7107fSHugh Dickins 	unsigned long new_start;
20461da177e4SLinus Torvalds 
20471da177e4SLinus Torvalds 	/* address space limit tests */
204884638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vma->vm_flags, grow))
20491da177e4SLinus Torvalds 		return -ENOMEM;
20501da177e4SLinus Torvalds 
20511da177e4SLinus Torvalds 	/* Stack limit test */
205224c79d8eSKrzysztof Opasiak 	if (size > rlimit(RLIMIT_STACK))
20531da177e4SLinus Torvalds 		return -ENOMEM;
20541da177e4SLinus Torvalds 
20551da177e4SLinus Torvalds 	/* mlock limit tests */
2056c5d8a364SMiaohe Lin 	if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
20571da177e4SLinus Torvalds 		return -ENOMEM;
20581da177e4SLinus Torvalds 
20590d59a01bSAdam Litke 	/* Check to ensure the stack will not grow into a hugetlb-only region */
20600d59a01bSAdam Litke 	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
20610d59a01bSAdam Litke 			vma->vm_end - size;
20620d59a01bSAdam Litke 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
20630d59a01bSAdam Litke 		return -EFAULT;
20640d59a01bSAdam Litke 
20651da177e4SLinus Torvalds 	/*
20661da177e4SLinus Torvalds 	 * Overcommit..  This must be the final test, as it will
20671da177e4SLinus Torvalds 	 * update security statistics.
20681da177e4SLinus Torvalds 	 */
206905fa199dSHugh Dickins 	if (security_vm_enough_memory_mm(mm, grow))
20701da177e4SLinus Torvalds 		return -ENOMEM;
20711da177e4SLinus Torvalds 
20721da177e4SLinus Torvalds 	return 0;
20731da177e4SLinus Torvalds }
20741da177e4SLinus Torvalds 
207546dea3d0SHugh Dickins #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
20761da177e4SLinus Torvalds /*
207746dea3d0SHugh Dickins  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
207846dea3d0SHugh Dickins  * vma is the last one with address > vma->vm_end.  Have to extend vma.
20791da177e4SLinus Torvalds  */
208046dea3d0SHugh Dickins int expand_upwards(struct vm_area_struct *vma, unsigned long address)
20811da177e4SLinus Torvalds {
208209357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
20831be7107fSHugh Dickins 	struct vm_area_struct *next;
20841be7107fSHugh Dickins 	unsigned long gap_addr;
208512352d3cSKonstantin Khlebnikov 	int error = 0;
2086d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
20871da177e4SLinus Torvalds 
20881da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSUP))
20891da177e4SLinus Torvalds 		return -EFAULT;
20901da177e4SLinus Torvalds 
2091bd726c90SHelge Deller 	/* Guard against exceeding limits of the address space. */
20921be7107fSHugh Dickins 	address &= PAGE_MASK;
209337511fb5SHelge Deller 	if (address >= (TASK_SIZE & PAGE_MASK))
209412352d3cSKonstantin Khlebnikov 		return -ENOMEM;
2095bd726c90SHelge Deller 	address += PAGE_SIZE;
209612352d3cSKonstantin Khlebnikov 
20971be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
20981be7107fSHugh Dickins 	gap_addr = address + stack_guard_gap;
2099bd726c90SHelge Deller 
2100bd726c90SHelge Deller 	/* Guard against overflow */
2101bd726c90SHelge Deller 	if (gap_addr < address || gap_addr > TASK_SIZE)
2102bd726c90SHelge Deller 		gap_addr = TASK_SIZE;
2103bd726c90SHelge Deller 
21041be7107fSHugh Dickins 	next = vma->vm_next;
21053122e80eSAnshuman Khandual 	if (next && next->vm_start < gap_addr && vma_is_accessible(next)) {
21061be7107fSHugh Dickins 		if (!(next->vm_flags & VM_GROWSUP))
21071be7107fSHugh Dickins 			return -ENOMEM;
21081be7107fSHugh Dickins 		/* Check that both stack segments have the same anon_vma? */
21091be7107fSHugh Dickins 	}
21101be7107fSHugh Dickins 
2111d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
21121da177e4SLinus Torvalds 		return -ENOMEM;
21131da177e4SLinus Torvalds 
2114d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
2115d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
2116d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
2117d4af56c5SLiam R. Howlett 		return -ENOMEM;
2118d4af56c5SLiam R. Howlett 	}
2119d4af56c5SLiam R. Howlett 
21201da177e4SLinus Torvalds 	/*
21211da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2122c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
21231da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
21241da177e4SLinus Torvalds 	 */
212512352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
21261da177e4SLinus Torvalds 
21271da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
21281da177e4SLinus Torvalds 	if (address > vma->vm_end) {
21291da177e4SLinus Torvalds 		unsigned long size, grow;
21301da177e4SLinus Torvalds 
21311da177e4SLinus Torvalds 		size = address - vma->vm_start;
21321da177e4SLinus Torvalds 		grow = (address - vma->vm_end) >> PAGE_SHIFT;
21331da177e4SLinus Torvalds 
213442c36f63SHugh Dickins 		error = -ENOMEM;
213542c36f63SHugh Dickins 		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
21361da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
21373af9e859SEric B Munson 			if (!error) {
21384128997bSMichel Lespinasse 				/*
2139524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
2140524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
2141524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
2142524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
2143524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
2144524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
2145524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
21464128997bSMichel Lespinasse 				 */
214709357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
214887e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
214909357814SOleg Nesterov 					mm->locked_vm += grow;
215084638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2151bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
21521da177e4SLinus Torvalds 				vma->vm_end = address;
2153d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2154d4af56c5SLiam R. Howlett 				vma_mas_store(vma, &mas);
2155bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
2156524e00b3SLiam R. Howlett 				if (!vma->vm_next)
21571be7107fSHugh Dickins 					mm->highest_vm_end = vm_end_gap(vma);
215809357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
21594128997bSMichel Lespinasse 
21603af9e859SEric B Munson 				perf_event_mmap(vma);
21613af9e859SEric B Munson 			}
21621da177e4SLinus Torvalds 		}
216342c36f63SHugh Dickins 	}
216412352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2165c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2166d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
21671da177e4SLinus Torvalds 	return error;
21681da177e4SLinus Torvalds }
216946dea3d0SHugh Dickins #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
217046dea3d0SHugh Dickins 
21711da177e4SLinus Torvalds /*
21721da177e4SLinus Torvalds  * vma is the first one with address < vma->vm_start.  Have to extend vma.
21731da177e4SLinus Torvalds  */
2174524e00b3SLiam R. Howlett int expand_downwards(struct vm_area_struct *vma, unsigned long address)
21751da177e4SLinus Torvalds {
217609357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
21771be7107fSHugh Dickins 	struct vm_area_struct *prev;
21780a1d5299SJann Horn 	int error = 0;
2179d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
21801da177e4SLinus Torvalds 
21818869477aSEric Paris 	address &= PAGE_MASK;
21820a1d5299SJann Horn 	if (address < mmap_min_addr)
21830a1d5299SJann Horn 		return -EPERM;
21848869477aSEric Paris 
21851be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
21861be7107fSHugh Dickins 	prev = vma->vm_prev;
21871be7107fSHugh Dickins 	/* Check that both stack segments have the same anon_vma? */
218832e4e6d5SOleg Nesterov 	if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
21893122e80eSAnshuman Khandual 			vma_is_accessible(prev)) {
219032e4e6d5SOleg Nesterov 		if (address - prev->vm_end < stack_guard_gap)
219132e4e6d5SOleg Nesterov 			return -ENOMEM;
21921be7107fSHugh Dickins 	}
21931be7107fSHugh Dickins 
2194d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
219512352d3cSKonstantin Khlebnikov 		return -ENOMEM;
21961da177e4SLinus Torvalds 
2197d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
2198d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
2199d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
2200d4af56c5SLiam R. Howlett 		return -ENOMEM;
2201d4af56c5SLiam R. Howlett 	}
2202d4af56c5SLiam R. Howlett 
22031da177e4SLinus Torvalds 	/*
22041da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2205c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
22061da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
22071da177e4SLinus Torvalds 	 */
220812352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
22091da177e4SLinus Torvalds 
22101da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
22111da177e4SLinus Torvalds 	if (address < vma->vm_start) {
22121da177e4SLinus Torvalds 		unsigned long size, grow;
22131da177e4SLinus Torvalds 
22141da177e4SLinus Torvalds 		size = vma->vm_end - address;
22151da177e4SLinus Torvalds 		grow = (vma->vm_start - address) >> PAGE_SHIFT;
22161da177e4SLinus Torvalds 
2217a626ca6aSLinus Torvalds 		error = -ENOMEM;
2218a626ca6aSLinus Torvalds 		if (grow <= vma->vm_pgoff) {
22191da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
22201da177e4SLinus Torvalds 			if (!error) {
22214128997bSMichel Lespinasse 				/*
2222524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
2223524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
2224524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
2225524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
2226524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
2227524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
2228524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
22294128997bSMichel Lespinasse 				 */
223009357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
223187e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
223209357814SOleg Nesterov 					mm->locked_vm += grow;
223384638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2234bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
22351da177e4SLinus Torvalds 				vma->vm_start = address;
22361da177e4SLinus Torvalds 				vma->vm_pgoff -= grow;
2237d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2238d4af56c5SLiam R. Howlett 				vma_mas_store(vma, &mas);
2239bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
224009357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
22414128997bSMichel Lespinasse 
22423af9e859SEric B Munson 				perf_event_mmap(vma);
22431da177e4SLinus Torvalds 			}
22441da177e4SLinus Torvalds 		}
2245a626ca6aSLinus Torvalds 	}
224612352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2247c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2248d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
22491da177e4SLinus Torvalds 	return error;
22501da177e4SLinus Torvalds }
22511da177e4SLinus Torvalds 
22521be7107fSHugh Dickins /* enforced gap between the expanding stack and other mappings. */
22531be7107fSHugh Dickins unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
22541be7107fSHugh Dickins 
22551be7107fSHugh Dickins static int __init cmdline_parse_stack_guard_gap(char *p)
22561be7107fSHugh Dickins {
22571be7107fSHugh Dickins 	unsigned long val;
22581be7107fSHugh Dickins 	char *endptr;
22591be7107fSHugh Dickins 
22601be7107fSHugh Dickins 	val = simple_strtoul(p, &endptr, 10);
22611be7107fSHugh Dickins 	if (!*endptr)
22621be7107fSHugh Dickins 		stack_guard_gap = val << PAGE_SHIFT;
22631be7107fSHugh Dickins 
2264e6d09493SRandy Dunlap 	return 1;
22651be7107fSHugh Dickins }
22661be7107fSHugh Dickins __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
22671be7107fSHugh Dickins 
2268b6a2fea3SOllie Wild #ifdef CONFIG_STACK_GROWSUP
2269b6a2fea3SOllie Wild int expand_stack(struct vm_area_struct *vma, unsigned long address)
2270b6a2fea3SOllie Wild {
2271b6a2fea3SOllie Wild 	return expand_upwards(vma, address);
2272b6a2fea3SOllie Wild }
2273b6a2fea3SOllie Wild 
2274b6a2fea3SOllie Wild struct vm_area_struct *
2275b6a2fea3SOllie Wild find_extend_vma(struct mm_struct *mm, unsigned long addr)
2276b6a2fea3SOllie Wild {
2277b6a2fea3SOllie Wild 	struct vm_area_struct *vma, *prev;
2278b6a2fea3SOllie Wild 
2279b6a2fea3SOllie Wild 	addr &= PAGE_MASK;
2280b6a2fea3SOllie Wild 	vma = find_vma_prev(mm, addr, &prev);
2281b6a2fea3SOllie Wild 	if (vma && (vma->vm_start <= addr))
2282b6a2fea3SOllie Wild 		return vma;
22834d45e75aSJann Horn 	if (!prev || expand_stack(prev, addr))
2284b6a2fea3SOllie Wild 		return NULL;
2285cea10a19SMichel Lespinasse 	if (prev->vm_flags & VM_LOCKED)
2286fc05f566SKirill A. Shutemov 		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2287b6a2fea3SOllie Wild 	return prev;
2288b6a2fea3SOllie Wild }
2289b6a2fea3SOllie Wild #else
2290b6a2fea3SOllie Wild int expand_stack(struct vm_area_struct *vma, unsigned long address)
2291b6a2fea3SOllie Wild {
2292b6a2fea3SOllie Wild 	return expand_downwards(vma, address);
2293b6a2fea3SOllie Wild }
2294b6a2fea3SOllie Wild 
22951da177e4SLinus Torvalds struct vm_area_struct *
22961da177e4SLinus Torvalds find_extend_vma(struct mm_struct *mm, unsigned long addr)
22971da177e4SLinus Torvalds {
22981da177e4SLinus Torvalds 	struct vm_area_struct *vma;
22991da177e4SLinus Torvalds 	unsigned long start;
23001da177e4SLinus Torvalds 
23011da177e4SLinus Torvalds 	addr &= PAGE_MASK;
23021da177e4SLinus Torvalds 	vma = find_vma(mm, addr);
23031da177e4SLinus Torvalds 	if (!vma)
23041da177e4SLinus Torvalds 		return NULL;
23051da177e4SLinus Torvalds 	if (vma->vm_start <= addr)
23061da177e4SLinus Torvalds 		return vma;
23071da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSDOWN))
23081da177e4SLinus Torvalds 		return NULL;
23091da177e4SLinus Torvalds 	start = vma->vm_start;
23101da177e4SLinus Torvalds 	if (expand_stack(vma, addr))
23111da177e4SLinus Torvalds 		return NULL;
2312cea10a19SMichel Lespinasse 	if (vma->vm_flags & VM_LOCKED)
2313fc05f566SKirill A. Shutemov 		populate_vma_page_range(vma, addr, start, NULL);
23141da177e4SLinus Torvalds 	return vma;
23151da177e4SLinus Torvalds }
23161da177e4SLinus Torvalds #endif
23171da177e4SLinus Torvalds 
2318e1d6d01aSJesse Barnes EXPORT_SYMBOL_GPL(find_extend_vma);
2319e1d6d01aSJesse Barnes 
23202c0b3814SHugh Dickins /*
23212c0b3814SHugh Dickins  * Ok - we have the memory areas we should free on the vma list,
23222c0b3814SHugh Dickins  * so release them, and do the vma updates.
23231da177e4SLinus Torvalds  *
23242c0b3814SHugh Dickins  * Called with the mm semaphore held.
23251da177e4SLinus Torvalds  */
23262c0b3814SHugh Dickins static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
23271da177e4SLinus Torvalds {
23284f74d2c8SLinus Torvalds 	unsigned long nr_accounted = 0;
23294f74d2c8SLinus Torvalds 
2330365e9c87SHugh Dickins 	/* Update high watermark before we lower total_vm */
2331365e9c87SHugh Dickins 	update_hiwater_vm(mm);
23322c0b3814SHugh Dickins 	do {
2333ab50b8edSHugh Dickins 		long nrpages = vma_pages(vma);
23341da177e4SLinus Torvalds 
23354f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
23364f74d2c8SLinus Torvalds 			nr_accounted += nrpages;
233784638335SKonstantin Khlebnikov 		vm_stat_account(mm, vma->vm_flags, -nrpages);
2338a8fb5618SHugh Dickins 		vma = remove_vma(vma);
2339146425a3SHugh Dickins 	} while (vma);
23404f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
23411da177e4SLinus Torvalds 	validate_mm(mm);
23421da177e4SLinus Torvalds }
23431da177e4SLinus Torvalds 
23441da177e4SLinus Torvalds /*
23451da177e4SLinus Torvalds  * Get rid of page table information in the indicated region.
23461da177e4SLinus Torvalds  *
2347f10df686SPaolo 'Blaisorblade' Giarrusso  * Called with the mm semaphore held.
23481da177e4SLinus Torvalds  */
23491da177e4SLinus Torvalds static void unmap_region(struct mm_struct *mm,
2350e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
2351e0da382cSHugh Dickins 		unsigned long start, unsigned long end)
23521da177e4SLinus Torvalds {
2353f39af059SMatthew Wilcox (Oracle) 	struct vm_area_struct *next = __vma_next(mm, prev);
2354d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
23551da177e4SLinus Torvalds 
23561da177e4SLinus Torvalds 	lru_add_drain();
2357a72afd87SWill Deacon 	tlb_gather_mmu(&tlb, mm);
2358365e9c87SHugh Dickins 	update_hiwater_rss(mm);
23594f74d2c8SLinus Torvalds 	unmap_vmas(&tlb, vma, start, end);
2360d16dfc55SPeter Zijlstra 	free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
23616ee8630eSHugh Dickins 				 next ? next->vm_start : USER_PGTABLES_CEILING);
2362ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
23631da177e4SLinus Torvalds }
23641da177e4SLinus Torvalds 
23651da177e4SLinus Torvalds /*
23661da177e4SLinus Torvalds  * Create a list of vma's touched by the unmap, removing them from the mm's
23671da177e4SLinus Torvalds  * vma list as we go..
23681da177e4SLinus Torvalds  */
2369246c320aSKirill A. Shutemov static bool
2370d4af56c5SLiam R. Howlett detach_vmas_to_be_unmapped(struct mm_struct *mm, struct ma_state *mas,
2371d4af56c5SLiam R. Howlett 	struct vm_area_struct *vma, struct vm_area_struct *prev,
2372d4af56c5SLiam R. Howlett 	unsigned long end)
23731da177e4SLinus Torvalds {
23741da177e4SLinus Torvalds 	struct vm_area_struct **insertion_point;
23751da177e4SLinus Torvalds 	struct vm_area_struct *tail_vma = NULL;
23761da177e4SLinus Torvalds 
23771da177e4SLinus Torvalds 	insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2378297c5eeeSLinus Torvalds 	vma->vm_prev = NULL;
2379524e00b3SLiam R. Howlett 	vma_mas_szero(mas, vma->vm_start, end);
23801da177e4SLinus Torvalds 	do {
2381a213e5cfSHugh Dickins 		if (vma->vm_flags & VM_LOCKED)
2382a213e5cfSHugh Dickins 			mm->locked_vm -= vma_pages(vma);
23831da177e4SLinus Torvalds 		mm->map_count--;
23841da177e4SLinus Torvalds 		tail_vma = vma;
23851da177e4SLinus Torvalds 		vma = vma->vm_next;
23861da177e4SLinus Torvalds 	} while (vma && vma->vm_start < end);
23871da177e4SLinus Torvalds 	*insertion_point = vma;
2388524e00b3SLiam R. Howlett 	if (vma)
2389297c5eeeSLinus Torvalds 		vma->vm_prev = prev;
2390524e00b3SLiam R. Howlett 	else
23911be7107fSHugh Dickins 		mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
23921da177e4SLinus Torvalds 	tail_vma->vm_next = NULL;
2393615d6e87SDavidlohr Bueso 
2394246c320aSKirill A. Shutemov 	/*
2395246c320aSKirill A. Shutemov 	 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2396246c320aSKirill A. Shutemov 	 * VM_GROWSUP VMA. Such VMAs can change their size under
2397246c320aSKirill A. Shutemov 	 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2398246c320aSKirill A. Shutemov 	 */
2399246c320aSKirill A. Shutemov 	if (vma && (vma->vm_flags & VM_GROWSDOWN))
2400246c320aSKirill A. Shutemov 		return false;
2401246c320aSKirill A. Shutemov 	if (prev && (prev->vm_flags & VM_GROWSUP))
2402246c320aSKirill A. Shutemov 		return false;
2403246c320aSKirill A. Shutemov 	return true;
24041da177e4SLinus Torvalds }
24051da177e4SLinus Torvalds 
24061da177e4SLinus Torvalds /*
2407def5efe0SDavid Rientjes  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2408def5efe0SDavid Rientjes  * has already been checked or doesn't make sense to fail.
24091da177e4SLinus Torvalds  */
2410def5efe0SDavid Rientjes int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
24111da177e4SLinus Torvalds 		unsigned long addr, int new_below)
24121da177e4SLinus Torvalds {
24131da177e4SLinus Torvalds 	struct vm_area_struct *new;
2414e3975891SChen Gang 	int err;
2415d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
24161da177e4SLinus Torvalds 
2417dd3b614fSDmitry Safonov 	if (vma->vm_ops && vma->vm_ops->may_split) {
2418dd3b614fSDmitry Safonov 		err = vma->vm_ops->may_split(vma, addr);
241931383c68SDan Williams 		if (err)
242031383c68SDan Williams 			return err;
242131383c68SDan Williams 	}
24221da177e4SLinus Torvalds 
24233928d4f5SLinus Torvalds 	new = vm_area_dup(vma);
24241da177e4SLinus Torvalds 	if (!new)
2425e3975891SChen Gang 		return -ENOMEM;
24261da177e4SLinus Torvalds 
24271da177e4SLinus Torvalds 	if (new_below)
24281da177e4SLinus Torvalds 		new->vm_end = addr;
24291da177e4SLinus Torvalds 	else {
24301da177e4SLinus Torvalds 		new->vm_start = addr;
24311da177e4SLinus Torvalds 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
24321da177e4SLinus Torvalds 	}
24331da177e4SLinus Torvalds 
2434ef0855d3SOleg Nesterov 	err = vma_dup_policy(vma, new);
2435ef0855d3SOleg Nesterov 	if (err)
24365beb4930SRik van Riel 		goto out_free_vma;
24371da177e4SLinus Torvalds 
2438c4ea95d7SDaniel Forrest 	err = anon_vma_clone(new, vma);
2439c4ea95d7SDaniel Forrest 	if (err)
24405beb4930SRik van Riel 		goto out_free_mpol;
24415beb4930SRik van Riel 
2442e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
24431da177e4SLinus Torvalds 		get_file(new->vm_file);
24441da177e4SLinus Torvalds 
24451da177e4SLinus Torvalds 	if (new->vm_ops && new->vm_ops->open)
24461da177e4SLinus Torvalds 		new->vm_ops->open(new);
24471da177e4SLinus Torvalds 
24481da177e4SLinus Torvalds 	if (new_below)
24495beb4930SRik van Riel 		err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
24501da177e4SLinus Torvalds 			((addr - new->vm_start) >> PAGE_SHIFT), new);
24511da177e4SLinus Torvalds 	else
24525beb4930SRik van Riel 		err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
24531da177e4SLinus Torvalds 
24545beb4930SRik van Riel 	/* Success. */
24555beb4930SRik van Riel 	if (!err)
24561da177e4SLinus Torvalds 		return 0;
24575beb4930SRik van Riel 
2458d4af56c5SLiam R. Howlett 	/* Avoid vm accounting in close() operation */
2459d4af56c5SLiam R. Howlett 	new->vm_start = new->vm_end;
2460d4af56c5SLiam R. Howlett 	new->vm_pgoff = 0;
24615beb4930SRik van Riel 	/* Clean everything up if vma_adjust failed. */
246258927533SRik van Riel 	if (new->vm_ops && new->vm_ops->close)
24635beb4930SRik van Riel 		new->vm_ops->close(new);
2464e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
24655beb4930SRik van Riel 		fput(new->vm_file);
24662aeadc30SAndrea Arcangeli 	unlink_anon_vmas(new);
24675beb4930SRik van Riel  out_free_mpol:
2468ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new));
24695beb4930SRik van Riel  out_free_vma:
24703928d4f5SLinus Torvalds 	vm_area_free(new);
2471d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
24725beb4930SRik van Riel 	return err;
24731da177e4SLinus Torvalds }
24741da177e4SLinus Torvalds 
2475659ace58SKOSAKI Motohiro /*
2476659ace58SKOSAKI Motohiro  * Split a vma into two pieces at address 'addr', a new vma is allocated
2477659ace58SKOSAKI Motohiro  * either for the first part or the tail.
2478659ace58SKOSAKI Motohiro  */
2479659ace58SKOSAKI Motohiro int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2480659ace58SKOSAKI Motohiro 	      unsigned long addr, int new_below)
2481659ace58SKOSAKI Motohiro {
2482659ace58SKOSAKI Motohiro 	if (mm->map_count >= sysctl_max_map_count)
2483659ace58SKOSAKI Motohiro 		return -ENOMEM;
2484659ace58SKOSAKI Motohiro 
2485659ace58SKOSAKI Motohiro 	return __split_vma(mm, vma, addr, new_below);
2486659ace58SKOSAKI Motohiro }
2487659ace58SKOSAKI Motohiro 
24881da177e4SLinus Torvalds /* Munmap is split into 2 main parts -- this part which finds
24891da177e4SLinus Torvalds  * what needs doing, and the areas themselves, which do the
24901da177e4SLinus Torvalds  * work.  This now handles partial unmappings.
24911da177e4SLinus Torvalds  * Jeremy Fitzhardinge <jeremy@goop.org>
24921da177e4SLinus Torvalds  */
249385a06835SYang Shi int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2494dd2283f2SYang Shi 		struct list_head *uf, bool downgrade)
24951da177e4SLinus Torvalds {
24961da177e4SLinus Torvalds 	unsigned long end;
2497146425a3SHugh Dickins 	struct vm_area_struct *vma, *prev, *last;
2498d4af56c5SLiam R. Howlett 	int error = -ENOMEM;
2499d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
25001da177e4SLinus Torvalds 
2501de1741a1SAlexander Kuleshov 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
25021da177e4SLinus Torvalds 		return -EINVAL;
25031da177e4SLinus Torvalds 
2504cc71aba3Svishnu.ps 	len = PAGE_ALIGN(len);
25055a28fc94SDave Hansen 	end = start + len;
2506cc71aba3Svishnu.ps 	if (len == 0)
25071da177e4SLinus Torvalds 		return -EINVAL;
25081da177e4SLinus Torvalds 
2509524e00b3SLiam R. Howlett 	 /* arch_unmap() might do unmaps itself.  */
25105a28fc94SDave Hansen 	arch_unmap(mm, start, end);
25115a28fc94SDave Hansen 
251278d9cf60SGonzalo Matias Juarez Tello 	/* Find the first overlapping VMA where start < vma->vm_end */
251378d9cf60SGonzalo Matias Juarez Tello 	vma = find_vma_intersection(mm, start, end);
2514146425a3SHugh Dickins 	if (!vma)
25151da177e4SLinus Torvalds 		return 0;
2516d4af56c5SLiam R. Howlett 
2517d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
2518d4af56c5SLiam R. Howlett 		return -ENOMEM;
25199be34c9dSLinus Torvalds 	prev = vma->vm_prev;
2520524e00b3SLiam R. Howlett 	/* we have start < vma->vm_end  */
2521524e00b3SLiam R. Howlett 
25221da177e4SLinus Torvalds 	/*
25231da177e4SLinus Torvalds 	 * If we need to split any vma, do it now to save pain later.
25241da177e4SLinus Torvalds 	 *
25251da177e4SLinus Torvalds 	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
25261da177e4SLinus Torvalds 	 * unmapped vm_area_struct will remain in use: so lower split_vma
25271da177e4SLinus Torvalds 	 * places tmp vma above, and higher split_vma places tmp vma below.
25281da177e4SLinus Torvalds 	 */
2529146425a3SHugh Dickins 	if (start > vma->vm_start) {
2530659ace58SKOSAKI Motohiro 
2531659ace58SKOSAKI Motohiro 		/*
2532659ace58SKOSAKI Motohiro 		 * Make sure that map_count on return from munmap() will
2533659ace58SKOSAKI Motohiro 		 * not exceed its limit; but let map_count go just above
2534659ace58SKOSAKI Motohiro 		 * its limit temporarily, to help free resources as expected.
2535659ace58SKOSAKI Motohiro 		 */
2536659ace58SKOSAKI Motohiro 		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2537d4af56c5SLiam R. Howlett 			goto map_count_exceeded;
2538659ace58SKOSAKI Motohiro 
2539659ace58SKOSAKI Motohiro 		error = __split_vma(mm, vma, start, 0);
25401da177e4SLinus Torvalds 		if (error)
2541d4af56c5SLiam R. Howlett 			goto split_failed;
2542146425a3SHugh Dickins 		prev = vma;
25431da177e4SLinus Torvalds 	}
25441da177e4SLinus Torvalds 
25451da177e4SLinus Torvalds 	/* Does it split the last one? */
25461da177e4SLinus Torvalds 	last = find_vma(mm, end);
25471da177e4SLinus Torvalds 	if (last && end > last->vm_start) {
2548d4af56c5SLiam R. Howlett 		error = __split_vma(mm, last, end, 1);
25491da177e4SLinus Torvalds 		if (error)
2550d4af56c5SLiam R. Howlett 			goto split_failed;
25511da177e4SLinus Torvalds 	}
2552f39af059SMatthew Wilcox (Oracle) 	vma = __vma_next(mm, prev);
25531da177e4SLinus Torvalds 
25542376dd7cSAndrea Arcangeli 	if (unlikely(uf)) {
25552376dd7cSAndrea Arcangeli 		/*
25562376dd7cSAndrea Arcangeli 		 * If userfaultfd_unmap_prep returns an error the vmas
2557f0953a1bSIngo Molnar 		 * will remain split, but userland will get a
25582376dd7cSAndrea Arcangeli 		 * highly unexpected error anyway. This is no
25592376dd7cSAndrea Arcangeli 		 * different than the case where the first of the two
25602376dd7cSAndrea Arcangeli 		 * __split_vma fails, but we don't undo the first
25612376dd7cSAndrea Arcangeli 		 * split, despite we could. This is unlikely enough
25622376dd7cSAndrea Arcangeli 		 * failure that it's not worth optimizing it for.
25632376dd7cSAndrea Arcangeli 		 */
2564d4af56c5SLiam R. Howlett 		error = userfaultfd_unmap_prep(vma, start, end, uf);
25652376dd7cSAndrea Arcangeli 		if (error)
2566d4af56c5SLiam R. Howlett 			goto userfaultfd_error;
25672376dd7cSAndrea Arcangeli 	}
25682376dd7cSAndrea Arcangeli 
2569dd2283f2SYang Shi 	/* Detach vmas from rbtree */
2570d4af56c5SLiam R. Howlett 	if (!detach_vmas_to_be_unmapped(mm, &mas, vma, prev, end))
2571246c320aSKirill A. Shutemov 		downgrade = false;
25721da177e4SLinus Torvalds 
2573dd2283f2SYang Shi 	if (downgrade)
2574d8ed45c5SMichel Lespinasse 		mmap_write_downgrade(mm);
2575dd2283f2SYang Shi 
2576dd2283f2SYang Shi 	unmap_region(mm, vma, prev, start, end);
2577dd2283f2SYang Shi 
25781da177e4SLinus Torvalds 	/* Fix up all other VM information */
25792c0b3814SHugh Dickins 	remove_vma_list(mm, vma);
25801da177e4SLinus Torvalds 
2581524e00b3SLiam R. Howlett 
2582524e00b3SLiam R. Howlett 	validate_mm(mm);
2583dd2283f2SYang Shi 	return downgrade ? 1 : 0;
2584d4af56c5SLiam R. Howlett 
2585d4af56c5SLiam R. Howlett map_count_exceeded:
2586d4af56c5SLiam R. Howlett split_failed:
2587d4af56c5SLiam R. Howlett userfaultfd_error:
2588d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
2589d4af56c5SLiam R. Howlett 	return error;
25901da177e4SLinus Torvalds }
25911da177e4SLinus Torvalds 
2592dd2283f2SYang Shi int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2593dd2283f2SYang Shi 	      struct list_head *uf)
2594dd2283f2SYang Shi {
2595dd2283f2SYang Shi 	return __do_munmap(mm, start, len, uf, false);
2596dd2283f2SYang Shi }
2597dd2283f2SYang Shi 
2598*e99668a5SLiam R. Howlett unsigned long mmap_region(struct file *file, unsigned long addr,
2599*e99668a5SLiam R. Howlett 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2600*e99668a5SLiam R. Howlett 		struct list_head *uf)
2601*e99668a5SLiam R. Howlett {
2602*e99668a5SLiam R. Howlett 	struct mm_struct *mm = current->mm;
2603*e99668a5SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
2604*e99668a5SLiam R. Howlett 	struct vm_area_struct *next, *prev, *merge;
2605*e99668a5SLiam R. Howlett 	pgoff_t pglen = len >> PAGE_SHIFT;
2606*e99668a5SLiam R. Howlett 	unsigned long charged = 0;
2607*e99668a5SLiam R. Howlett 	unsigned long end = addr + len;
2608*e99668a5SLiam R. Howlett 	unsigned long merge_start = addr, merge_end = end;
2609*e99668a5SLiam R. Howlett 	pgoff_t vm_pgoff;
2610*e99668a5SLiam R. Howlett 	int error;
2611*e99668a5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, addr, end - 1);
2612*e99668a5SLiam R. Howlett 
2613*e99668a5SLiam R. Howlett 	/* Check against address space limit. */
2614*e99668a5SLiam R. Howlett 	if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2615*e99668a5SLiam R. Howlett 		unsigned long nr_pages;
2616*e99668a5SLiam R. Howlett 
2617*e99668a5SLiam R. Howlett 		/*
2618*e99668a5SLiam R. Howlett 		 * MAP_FIXED may remove pages of mappings that intersects with
2619*e99668a5SLiam R. Howlett 		 * requested mapping. Account for the pages it would unmap.
2620*e99668a5SLiam R. Howlett 		 */
2621*e99668a5SLiam R. Howlett 		nr_pages = count_vma_pages_range(mm, addr, end);
2622*e99668a5SLiam R. Howlett 
2623*e99668a5SLiam R. Howlett 		if (!may_expand_vm(mm, vm_flags,
2624*e99668a5SLiam R. Howlett 					(len >> PAGE_SHIFT) - nr_pages))
2625*e99668a5SLiam R. Howlett 			return -ENOMEM;
2626*e99668a5SLiam R. Howlett 	}
2627*e99668a5SLiam R. Howlett 
2628*e99668a5SLiam R. Howlett 	/* Unmap any existing mapping in the area */
2629*e99668a5SLiam R. Howlett 	if (do_munmap(mm, addr, len, uf))
2630*e99668a5SLiam R. Howlett 		return -ENOMEM;
2631*e99668a5SLiam R. Howlett 
2632*e99668a5SLiam R. Howlett 	/*
2633*e99668a5SLiam R. Howlett 	 * Private writable mapping: check memory availability
2634*e99668a5SLiam R. Howlett 	 */
2635*e99668a5SLiam R. Howlett 	if (accountable_mapping(file, vm_flags)) {
2636*e99668a5SLiam R. Howlett 		charged = len >> PAGE_SHIFT;
2637*e99668a5SLiam R. Howlett 		if (security_vm_enough_memory_mm(mm, charged))
2638*e99668a5SLiam R. Howlett 			return -ENOMEM;
2639*e99668a5SLiam R. Howlett 		vm_flags |= VM_ACCOUNT;
2640*e99668a5SLiam R. Howlett 	}
2641*e99668a5SLiam R. Howlett 
2642*e99668a5SLiam R. Howlett 	next = mas_next(&mas, ULONG_MAX);
2643*e99668a5SLiam R. Howlett 	prev = mas_prev(&mas, 0);
2644*e99668a5SLiam R. Howlett 	if (vm_flags & VM_SPECIAL)
2645*e99668a5SLiam R. Howlett 		goto cannot_expand;
2646*e99668a5SLiam R. Howlett 
2647*e99668a5SLiam R. Howlett 	/* Attempt to expand an old mapping */
2648*e99668a5SLiam R. Howlett 	/* Check next */
2649*e99668a5SLiam R. Howlett 	if (next && next->vm_start == end && !vma_policy(next) &&
2650*e99668a5SLiam R. Howlett 	    can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2651*e99668a5SLiam R. Howlett 				 NULL_VM_UFFD_CTX, NULL)) {
2652*e99668a5SLiam R. Howlett 		merge_end = next->vm_end;
2653*e99668a5SLiam R. Howlett 		vma = next;
2654*e99668a5SLiam R. Howlett 		vm_pgoff = next->vm_pgoff - pglen;
2655*e99668a5SLiam R. Howlett 	}
2656*e99668a5SLiam R. Howlett 
2657*e99668a5SLiam R. Howlett 	/* Check prev */
2658*e99668a5SLiam R. Howlett 	if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2659*e99668a5SLiam R. Howlett 	    (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2660*e99668a5SLiam R. Howlett 				       pgoff, vma->vm_userfaultfd_ctx, NULL) :
2661*e99668a5SLiam R. Howlett 		   can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2662*e99668a5SLiam R. Howlett 				       NULL_VM_UFFD_CTX, NULL))) {
2663*e99668a5SLiam R. Howlett 		merge_start = prev->vm_start;
2664*e99668a5SLiam R. Howlett 		vma = prev;
2665*e99668a5SLiam R. Howlett 		vm_pgoff = prev->vm_pgoff;
2666*e99668a5SLiam R. Howlett 	}
2667*e99668a5SLiam R. Howlett 
2668*e99668a5SLiam R. Howlett 
2669*e99668a5SLiam R. Howlett 	/* Actually expand, if possible */
2670*e99668a5SLiam R. Howlett 	if (vma &&
2671*e99668a5SLiam R. Howlett 	    !vma_expand(&mas, vma, merge_start, merge_end, vm_pgoff, next)) {
2672*e99668a5SLiam R. Howlett 		khugepaged_enter_vma(vma, vm_flags);
2673*e99668a5SLiam R. Howlett 		goto expanded;
2674*e99668a5SLiam R. Howlett 	}
2675*e99668a5SLiam R. Howlett 
2676*e99668a5SLiam R. Howlett 	mas.index = addr;
2677*e99668a5SLiam R. Howlett 	mas.last = end - 1;
2678*e99668a5SLiam R. Howlett cannot_expand:
2679*e99668a5SLiam R. Howlett 	/*
2680*e99668a5SLiam R. Howlett 	 * Determine the object being mapped and call the appropriate
2681*e99668a5SLiam R. Howlett 	 * specific mapper. the address has already been validated, but
2682*e99668a5SLiam R. Howlett 	 * not unmapped, but the maps are removed from the list.
2683*e99668a5SLiam R. Howlett 	 */
2684*e99668a5SLiam R. Howlett 	vma = vm_area_alloc(mm);
2685*e99668a5SLiam R. Howlett 	if (!vma) {
2686*e99668a5SLiam R. Howlett 		error = -ENOMEM;
2687*e99668a5SLiam R. Howlett 		goto unacct_error;
2688*e99668a5SLiam R. Howlett 	}
2689*e99668a5SLiam R. Howlett 
2690*e99668a5SLiam R. Howlett 	vma->vm_start = addr;
2691*e99668a5SLiam R. Howlett 	vma->vm_end = end;
2692*e99668a5SLiam R. Howlett 	vma->vm_flags = vm_flags;
2693*e99668a5SLiam R. Howlett 	vma->vm_page_prot = vm_get_page_prot(vm_flags);
2694*e99668a5SLiam R. Howlett 	vma->vm_pgoff = pgoff;
2695*e99668a5SLiam R. Howlett 
2696*e99668a5SLiam R. Howlett 	if (file) {
2697*e99668a5SLiam R. Howlett 		if (vm_flags & VM_SHARED) {
2698*e99668a5SLiam R. Howlett 			error = mapping_map_writable(file->f_mapping);
2699*e99668a5SLiam R. Howlett 			if (error)
2700*e99668a5SLiam R. Howlett 				goto free_vma;
2701*e99668a5SLiam R. Howlett 		}
2702*e99668a5SLiam R. Howlett 
2703*e99668a5SLiam R. Howlett 		vma->vm_file = get_file(file);
2704*e99668a5SLiam R. Howlett 		error = call_mmap(file, vma);
2705*e99668a5SLiam R. Howlett 		if (error)
2706*e99668a5SLiam R. Howlett 			goto unmap_and_free_vma;
2707*e99668a5SLiam R. Howlett 
2708*e99668a5SLiam R. Howlett 		/* Can addr have changed??
2709*e99668a5SLiam R. Howlett 		 *
2710*e99668a5SLiam R. Howlett 		 * Answer: Yes, several device drivers can do it in their
2711*e99668a5SLiam R. Howlett 		 *         f_op->mmap method. -DaveM
2712*e99668a5SLiam R. Howlett 		 */
2713*e99668a5SLiam R. Howlett 		WARN_ON_ONCE(addr != vma->vm_start);
2714*e99668a5SLiam R. Howlett 
2715*e99668a5SLiam R. Howlett 		addr = vma->vm_start;
2716*e99668a5SLiam R. Howlett 		mas_reset(&mas);
2717*e99668a5SLiam R. Howlett 
2718*e99668a5SLiam R. Howlett 		/*
2719*e99668a5SLiam R. Howlett 		 * If vm_flags changed after call_mmap(), we should try merge
2720*e99668a5SLiam R. Howlett 		 * vma again as we may succeed this time.
2721*e99668a5SLiam R. Howlett 		 */
2722*e99668a5SLiam R. Howlett 		if (unlikely(vm_flags != vma->vm_flags && prev)) {
2723*e99668a5SLiam R. Howlett 			merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
2724*e99668a5SLiam R. Howlett 				NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
2725*e99668a5SLiam R. Howlett 			if (merge) {
2726*e99668a5SLiam R. Howlett 				/*
2727*e99668a5SLiam R. Howlett 				 * ->mmap() can change vma->vm_file and fput
2728*e99668a5SLiam R. Howlett 				 * the original file. So fput the vma->vm_file
2729*e99668a5SLiam R. Howlett 				 * here or we would add an extra fput for file
2730*e99668a5SLiam R. Howlett 				 * and cause general protection fault
2731*e99668a5SLiam R. Howlett 				 * ultimately.
2732*e99668a5SLiam R. Howlett 				 */
2733*e99668a5SLiam R. Howlett 				fput(vma->vm_file);
2734*e99668a5SLiam R. Howlett 				vm_area_free(vma);
2735*e99668a5SLiam R. Howlett 				vma = merge;
2736*e99668a5SLiam R. Howlett 				/* Update vm_flags to pick up the change. */
2737*e99668a5SLiam R. Howlett 				addr = vma->vm_start;
2738*e99668a5SLiam R. Howlett 				vm_flags = vma->vm_flags;
2739*e99668a5SLiam R. Howlett 				goto unmap_writable;
2740*e99668a5SLiam R. Howlett 			}
2741*e99668a5SLiam R. Howlett 		}
2742*e99668a5SLiam R. Howlett 
2743*e99668a5SLiam R. Howlett 		vm_flags = vma->vm_flags;
2744*e99668a5SLiam R. Howlett 	} else if (vm_flags & VM_SHARED) {
2745*e99668a5SLiam R. Howlett 		error = shmem_zero_setup(vma);
2746*e99668a5SLiam R. Howlett 		if (error)
2747*e99668a5SLiam R. Howlett 			goto free_vma;
2748*e99668a5SLiam R. Howlett 	} else {
2749*e99668a5SLiam R. Howlett 		vma_set_anonymous(vma);
2750*e99668a5SLiam R. Howlett 	}
2751*e99668a5SLiam R. Howlett 
2752*e99668a5SLiam R. Howlett 	/* Allow architectures to sanity-check the vm_flags */
2753*e99668a5SLiam R. Howlett 	if (!arch_validate_flags(vma->vm_flags)) {
2754*e99668a5SLiam R. Howlett 		error = -EINVAL;
2755*e99668a5SLiam R. Howlett 		if (file)
2756*e99668a5SLiam R. Howlett 			goto unmap_and_free_vma;
2757*e99668a5SLiam R. Howlett 		else
2758*e99668a5SLiam R. Howlett 			goto free_vma;
2759*e99668a5SLiam R. Howlett 	}
2760*e99668a5SLiam R. Howlett 
2761*e99668a5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL)) {
2762*e99668a5SLiam R. Howlett 		error = -ENOMEM;
2763*e99668a5SLiam R. Howlett 		if (file)
2764*e99668a5SLiam R. Howlett 			goto unmap_and_free_vma;
2765*e99668a5SLiam R. Howlett 		else
2766*e99668a5SLiam R. Howlett 			goto free_vma;
2767*e99668a5SLiam R. Howlett 	}
2768*e99668a5SLiam R. Howlett 
2769*e99668a5SLiam R. Howlett 	if (vma->vm_file)
2770*e99668a5SLiam R. Howlett 		i_mmap_lock_write(vma->vm_file->f_mapping);
2771*e99668a5SLiam R. Howlett 
2772*e99668a5SLiam R. Howlett 	vma_mas_store(vma, &mas);
2773*e99668a5SLiam R. Howlett 	__vma_link_list(mm, vma, prev);
2774*e99668a5SLiam R. Howlett 	mm->map_count++;
2775*e99668a5SLiam R. Howlett 	if (vma->vm_file) {
2776*e99668a5SLiam R. Howlett 		if (vma->vm_flags & VM_SHARED)
2777*e99668a5SLiam R. Howlett 			mapping_allow_writable(vma->vm_file->f_mapping);
2778*e99668a5SLiam R. Howlett 
2779*e99668a5SLiam R. Howlett 		flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2780*e99668a5SLiam R. Howlett 		vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2781*e99668a5SLiam R. Howlett 		flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2782*e99668a5SLiam R. Howlett 		i_mmap_unlock_write(vma->vm_file->f_mapping);
2783*e99668a5SLiam R. Howlett 	}
2784*e99668a5SLiam R. Howlett 
2785*e99668a5SLiam R. Howlett 	/*
2786*e99668a5SLiam R. Howlett 	 * vma_merge() calls khugepaged_enter_vma() either, the below
2787*e99668a5SLiam R. Howlett 	 * call covers the non-merge case.
2788*e99668a5SLiam R. Howlett 	 */
2789*e99668a5SLiam R. Howlett 	khugepaged_enter_vma(vma, vma->vm_flags);
2790*e99668a5SLiam R. Howlett 
2791*e99668a5SLiam R. Howlett 	/* Once vma denies write, undo our temporary denial count */
2792*e99668a5SLiam R. Howlett unmap_writable:
2793*e99668a5SLiam R. Howlett 	if (file && vm_flags & VM_SHARED)
2794*e99668a5SLiam R. Howlett 		mapping_unmap_writable(file->f_mapping);
2795*e99668a5SLiam R. Howlett 	file = vma->vm_file;
2796*e99668a5SLiam R. Howlett expanded:
2797*e99668a5SLiam R. Howlett 	perf_event_mmap(vma);
2798*e99668a5SLiam R. Howlett 
2799*e99668a5SLiam R. Howlett 	vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2800*e99668a5SLiam R. Howlett 	if (vm_flags & VM_LOCKED) {
2801*e99668a5SLiam R. Howlett 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2802*e99668a5SLiam R. Howlett 					is_vm_hugetlb_page(vma) ||
2803*e99668a5SLiam R. Howlett 					vma == get_gate_vma(current->mm))
2804*e99668a5SLiam R. Howlett 			vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
2805*e99668a5SLiam R. Howlett 		else
2806*e99668a5SLiam R. Howlett 			mm->locked_vm += (len >> PAGE_SHIFT);
2807*e99668a5SLiam R. Howlett 	}
2808*e99668a5SLiam R. Howlett 
2809*e99668a5SLiam R. Howlett 	if (file)
2810*e99668a5SLiam R. Howlett 		uprobe_mmap(vma);
2811*e99668a5SLiam R. Howlett 
2812*e99668a5SLiam R. Howlett 	/*
2813*e99668a5SLiam R. Howlett 	 * New (or expanded) vma always get soft dirty status.
2814*e99668a5SLiam R. Howlett 	 * Otherwise user-space soft-dirty page tracker won't
2815*e99668a5SLiam R. Howlett 	 * be able to distinguish situation when vma area unmapped,
2816*e99668a5SLiam R. Howlett 	 * then new mapped in-place (which must be aimed as
2817*e99668a5SLiam R. Howlett 	 * a completely new data area).
2818*e99668a5SLiam R. Howlett 	 */
2819*e99668a5SLiam R. Howlett 	vma->vm_flags |= VM_SOFTDIRTY;
2820*e99668a5SLiam R. Howlett 
2821*e99668a5SLiam R. Howlett 	vma_set_page_prot(vma);
2822*e99668a5SLiam R. Howlett 
2823*e99668a5SLiam R. Howlett 	validate_mm(mm);
2824*e99668a5SLiam R. Howlett 	return addr;
2825*e99668a5SLiam R. Howlett 
2826*e99668a5SLiam R. Howlett unmap_and_free_vma:
2827*e99668a5SLiam R. Howlett 	fput(vma->vm_file);
2828*e99668a5SLiam R. Howlett 	vma->vm_file = NULL;
2829*e99668a5SLiam R. Howlett 
2830*e99668a5SLiam R. Howlett 	/* Undo any partial mapping done by a device driver. */
2831*e99668a5SLiam R. Howlett 	unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
2832*e99668a5SLiam R. Howlett 	if (vm_flags & VM_SHARED)
2833*e99668a5SLiam R. Howlett 		mapping_unmap_writable(file->f_mapping);
2834*e99668a5SLiam R. Howlett free_vma:
2835*e99668a5SLiam R. Howlett 	vm_area_free(vma);
2836*e99668a5SLiam R. Howlett unacct_error:
2837*e99668a5SLiam R. Howlett 	if (charged)
2838*e99668a5SLiam R. Howlett 		vm_unacct_memory(charged);
2839*e99668a5SLiam R. Howlett 	validate_mm(mm);
2840*e99668a5SLiam R. Howlett 	return error;
2841*e99668a5SLiam R. Howlett }
2842*e99668a5SLiam R. Howlett 
2843dd2283f2SYang Shi static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2844a46ef99dSLinus Torvalds {
2845a46ef99dSLinus Torvalds 	int ret;
2846bfce281cSAl Viro 	struct mm_struct *mm = current->mm;
2847897ab3e0SMike Rapoport 	LIST_HEAD(uf);
2848a46ef99dSLinus Torvalds 
2849d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2850ae798783SMichal Hocko 		return -EINTR;
2851ae798783SMichal Hocko 
2852dd2283f2SYang Shi 	ret = __do_munmap(mm, start, len, &uf, downgrade);
2853dd2283f2SYang Shi 	/*
2854c1e8d7c6SMichel Lespinasse 	 * Returning 1 indicates mmap_lock is downgraded.
2855dd2283f2SYang Shi 	 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2856dd2283f2SYang Shi 	 * it to 0 before return.
2857dd2283f2SYang Shi 	 */
2858dd2283f2SYang Shi 	if (ret == 1) {
2859d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
2860dd2283f2SYang Shi 		ret = 0;
2861dd2283f2SYang Shi 	} else
2862d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
2863dd2283f2SYang Shi 
2864897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
2865a46ef99dSLinus Torvalds 	return ret;
2866a46ef99dSLinus Torvalds }
2867dd2283f2SYang Shi 
2868dd2283f2SYang Shi int vm_munmap(unsigned long start, size_t len)
2869dd2283f2SYang Shi {
2870dd2283f2SYang Shi 	return __vm_munmap(start, len, false);
2871dd2283f2SYang Shi }
2872a46ef99dSLinus Torvalds EXPORT_SYMBOL(vm_munmap);
2873a46ef99dSLinus Torvalds 
28746a6160a7SHeiko Carstens SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
28751da177e4SLinus Torvalds {
2876ce18d171SCatalin Marinas 	addr = untagged_addr(addr);
2877dd2283f2SYang Shi 	return __vm_munmap(addr, len, true);
28781da177e4SLinus Torvalds }
28791da177e4SLinus Torvalds 
2880c8d78c18SKirill A. Shutemov 
2881c8d78c18SKirill A. Shutemov /*
2882c8d78c18SKirill A. Shutemov  * Emulation of deprecated remap_file_pages() syscall.
2883c8d78c18SKirill A. Shutemov  */
2884c8d78c18SKirill A. Shutemov SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2885c8d78c18SKirill A. Shutemov 		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2886c8d78c18SKirill A. Shutemov {
2887c8d78c18SKirill A. Shutemov 
2888c8d78c18SKirill A. Shutemov 	struct mm_struct *mm = current->mm;
2889c8d78c18SKirill A. Shutemov 	struct vm_area_struct *vma;
2890c8d78c18SKirill A. Shutemov 	unsigned long populate = 0;
2891c8d78c18SKirill A. Shutemov 	unsigned long ret = -EINVAL;
2892c8d78c18SKirill A. Shutemov 	struct file *file;
2893c8d78c18SKirill A. Shutemov 
2894ee65728eSMike Rapoport 	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2895c8d78c18SKirill A. Shutemov 		     current->comm, current->pid);
2896c8d78c18SKirill A. Shutemov 
2897c8d78c18SKirill A. Shutemov 	if (prot)
2898c8d78c18SKirill A. Shutemov 		return ret;
2899c8d78c18SKirill A. Shutemov 	start = start & PAGE_MASK;
2900c8d78c18SKirill A. Shutemov 	size = size & PAGE_MASK;
2901c8d78c18SKirill A. Shutemov 
2902c8d78c18SKirill A. Shutemov 	if (start + size <= start)
2903c8d78c18SKirill A. Shutemov 		return ret;
2904c8d78c18SKirill A. Shutemov 
2905c8d78c18SKirill A. Shutemov 	/* Does pgoff wrap? */
2906c8d78c18SKirill A. Shutemov 	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2907c8d78c18SKirill A. Shutemov 		return ret;
2908c8d78c18SKirill A. Shutemov 
2909d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2910dc0ef0dfSMichal Hocko 		return -EINTR;
2911dc0ef0dfSMichal Hocko 
29129b593cb2SLiam R. Howlett 	vma = vma_lookup(mm, start);
2913c8d78c18SKirill A. Shutemov 
2914c8d78c18SKirill A. Shutemov 	if (!vma || !(vma->vm_flags & VM_SHARED))
2915c8d78c18SKirill A. Shutemov 		goto out;
2916c8d78c18SKirill A. Shutemov 
291748f7df32SKirill A. Shutemov 	if (start + size > vma->vm_end) {
291848f7df32SKirill A. Shutemov 		struct vm_area_struct *next;
291948f7df32SKirill A. Shutemov 
292048f7df32SKirill A. Shutemov 		for (next = vma->vm_next; next; next = next->vm_next) {
292148f7df32SKirill A. Shutemov 			/* hole between vmas ? */
292248f7df32SKirill A. Shutemov 			if (next->vm_start != next->vm_prev->vm_end)
292348f7df32SKirill A. Shutemov 				goto out;
292448f7df32SKirill A. Shutemov 
292548f7df32SKirill A. Shutemov 			if (next->vm_file != vma->vm_file)
292648f7df32SKirill A. Shutemov 				goto out;
292748f7df32SKirill A. Shutemov 
292848f7df32SKirill A. Shutemov 			if (next->vm_flags != vma->vm_flags)
292948f7df32SKirill A. Shutemov 				goto out;
293048f7df32SKirill A. Shutemov 
293148f7df32SKirill A. Shutemov 			if (start + size <= next->vm_end)
293248f7df32SKirill A. Shutemov 				break;
293348f7df32SKirill A. Shutemov 		}
293448f7df32SKirill A. Shutemov 
293548f7df32SKirill A. Shutemov 		if (!next)
2936c8d78c18SKirill A. Shutemov 			goto out;
2937c8d78c18SKirill A. Shutemov 	}
2938c8d78c18SKirill A. Shutemov 
2939c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2940c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2941c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2942c8d78c18SKirill A. Shutemov 
2943c8d78c18SKirill A. Shutemov 	flags &= MAP_NONBLOCK;
2944c8d78c18SKirill A. Shutemov 	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2945fce000b1SLiam Howlett 	if (vma->vm_flags & VM_LOCKED)
2946c8d78c18SKirill A. Shutemov 		flags |= MAP_LOCKED;
294748f7df32SKirill A. Shutemov 
2948c8d78c18SKirill A. Shutemov 	file = get_file(vma->vm_file);
294945e55300SPeter Collingbourne 	ret = do_mmap(vma->vm_file, start, size,
2950897ab3e0SMike Rapoport 			prot, flags, pgoff, &populate, NULL);
2951c8d78c18SKirill A. Shutemov 	fput(file);
2952c8d78c18SKirill A. Shutemov out:
2953d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
2954c8d78c18SKirill A. Shutemov 	if (populate)
2955c8d78c18SKirill A. Shutemov 		mm_populate(ret, populate);
2956c8d78c18SKirill A. Shutemov 	if (!IS_ERR_VALUE(ret))
2957c8d78c18SKirill A. Shutemov 		ret = 0;
2958c8d78c18SKirill A. Shutemov 	return ret;
2959c8d78c18SKirill A. Shutemov }
2960c8d78c18SKirill A. Shutemov 
29611da177e4SLinus Torvalds /*
29622e7ce7d3SLiam R. Howlett  * brk_munmap() - Unmap a parital vma.
29632e7ce7d3SLiam R. Howlett  * @mas: The maple tree state.
29642e7ce7d3SLiam R. Howlett  * @vma: The vma to be modified
29652e7ce7d3SLiam R. Howlett  * @newbrk: the start of the address to unmap
29662e7ce7d3SLiam R. Howlett  * @oldbrk: The end of the address to unmap
29672e7ce7d3SLiam R. Howlett  * @uf: The userfaultfd list_head
29682e7ce7d3SLiam R. Howlett  *
29692e7ce7d3SLiam R. Howlett  * Returns: 1 on success.
29702e7ce7d3SLiam R. Howlett  * unmaps a partial VMA mapping.  Does not handle alignment, downgrades lock if
29712e7ce7d3SLiam R. Howlett  * possible.
29721da177e4SLinus Torvalds  */
29732e7ce7d3SLiam R. Howlett static int do_brk_munmap(struct ma_state *mas, struct vm_area_struct *vma,
29742e7ce7d3SLiam R. Howlett 			 unsigned long newbrk, unsigned long oldbrk,
29752e7ce7d3SLiam R. Howlett 			 struct list_head *uf)
29762e7ce7d3SLiam R. Howlett {
29772e7ce7d3SLiam R. Howlett 	struct mm_struct *mm = vma->vm_mm;
29782e7ce7d3SLiam R. Howlett 	int ret;
29792e7ce7d3SLiam R. Howlett 
29802e7ce7d3SLiam R. Howlett 	arch_unmap(mm, newbrk, oldbrk);
29812e7ce7d3SLiam R. Howlett 	ret = __do_munmap(mm, newbrk, oldbrk - newbrk, uf, true);
29822e7ce7d3SLiam R. Howlett 	validate_mm_mt(mm);
29832e7ce7d3SLiam R. Howlett 	return ret;
29842e7ce7d3SLiam R. Howlett }
29852e7ce7d3SLiam R. Howlett 
29862e7ce7d3SLiam R. Howlett /*
29872e7ce7d3SLiam R. Howlett  * do_brk_flags() - Increase the brk vma if the flags match.
29882e7ce7d3SLiam R. Howlett  * @mas: The maple tree state.
29892e7ce7d3SLiam R. Howlett  * @addr: The start address
29902e7ce7d3SLiam R. Howlett  * @len: The length of the increase
29912e7ce7d3SLiam R. Howlett  * @vma: The vma,
29922e7ce7d3SLiam R. Howlett  * @flags: The VMA Flags
29932e7ce7d3SLiam R. Howlett  *
29942e7ce7d3SLiam R. Howlett  * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
29952e7ce7d3SLiam R. Howlett  * do not match then create a new anonymous VMA.  Eventually we may be able to
29962e7ce7d3SLiam R. Howlett  * do some brk-specific accounting here.
29972e7ce7d3SLiam R. Howlett  */
29982e7ce7d3SLiam R. Howlett static int do_brk_flags(struct ma_state *mas, struct vm_area_struct *vma,
29992e7ce7d3SLiam R. Howlett 			unsigned long addr, unsigned long len,
30002e7ce7d3SLiam R. Howlett 			unsigned long flags)
30011da177e4SLinus Torvalds {
30021da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
30032e7ce7d3SLiam R. Howlett 	struct vm_area_struct *prev = NULL;
30042e7ce7d3SLiam R. Howlett 
3005d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
30062e7ce7d3SLiam R. Howlett 	/*
30072e7ce7d3SLiam R. Howlett 	 * Check against address space limits by the changed size
30082e7ce7d3SLiam R. Howlett 	 * Note: This happens *after* clearing old mappings in some code paths.
30092e7ce7d3SLiam R. Howlett 	 */
301016e72e9bSDenys Vlasenko 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
301184638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
30121da177e4SLinus Torvalds 		return -ENOMEM;
30131da177e4SLinus Torvalds 
30141da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
30151da177e4SLinus Torvalds 		return -ENOMEM;
30161da177e4SLinus Torvalds 
3017191c5424SAl Viro 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
30181da177e4SLinus Torvalds 		return -ENOMEM;
30191da177e4SLinus Torvalds 
30201da177e4SLinus Torvalds 	/*
30212e7ce7d3SLiam R. Howlett 	 * Expand the existing vma if possible; Note that singular lists do not
30222e7ce7d3SLiam R. Howlett 	 * occur after forking, so the expand will only happen on new VMAs.
30231da177e4SLinus Torvalds 	 */
30242e7ce7d3SLiam R. Howlett 	if (vma &&
30252e7ce7d3SLiam R. Howlett 	    (!vma->anon_vma || list_is_singular(&vma->anon_vma_chain)) &&
30262e7ce7d3SLiam R. Howlett 	    ((vma->vm_flags & ~VM_SOFTDIRTY) == flags)) {
30272e7ce7d3SLiam R. Howlett 		mas->index = vma->vm_start;
30282e7ce7d3SLiam R. Howlett 		mas->last = addr + len - 1;
30292e7ce7d3SLiam R. Howlett 		vma_adjust_trans_huge(vma, addr, addr + len, 0);
30302e7ce7d3SLiam R. Howlett 		if (vma->anon_vma) {
30312e7ce7d3SLiam R. Howlett 			anon_vma_lock_write(vma->anon_vma);
30322e7ce7d3SLiam R. Howlett 			anon_vma_interval_tree_pre_update_vma(vma);
30331da177e4SLinus Torvalds 		}
30342e7ce7d3SLiam R. Howlett 		vma->vm_end = addr + len;
30352e7ce7d3SLiam R. Howlett 		vma->vm_flags |= VM_SOFTDIRTY;
30362e7ce7d3SLiam R. Howlett 		if (mas_store_gfp(mas, vma, GFP_KERNEL))
30372e7ce7d3SLiam R. Howlett 			goto mas_expand_failed;
30382e7ce7d3SLiam R. Howlett 
30392e7ce7d3SLiam R. Howlett 		if (vma->anon_vma) {
30402e7ce7d3SLiam R. Howlett 			anon_vma_interval_tree_post_update_vma(vma);
30412e7ce7d3SLiam R. Howlett 			anon_vma_unlock_write(vma->anon_vma);
30422e7ce7d3SLiam R. Howlett 		}
30432e7ce7d3SLiam R. Howlett 		khugepaged_enter_vma(vma, flags);
30442e7ce7d3SLiam R. Howlett 		goto out;
30452e7ce7d3SLiam R. Howlett 	}
30462e7ce7d3SLiam R. Howlett 	prev = vma;
30472e7ce7d3SLiam R. Howlett 
30482e7ce7d3SLiam R. Howlett 	/* create a vma struct for an anonymous mapping */
30492e7ce7d3SLiam R. Howlett 	vma = vm_area_alloc(mm);
30502e7ce7d3SLiam R. Howlett 	if (!vma)
30512e7ce7d3SLiam R. Howlett 		goto vma_alloc_fail;
30521da177e4SLinus Torvalds 
3053bfd40eafSKirill A. Shutemov 	vma_set_anonymous(vma);
30541da177e4SLinus Torvalds 	vma->vm_start = addr;
30551da177e4SLinus Torvalds 	vma->vm_end = addr + len;
30562e7ce7d3SLiam R. Howlett 	vma->vm_pgoff = addr >> PAGE_SHIFT;
30571da177e4SLinus Torvalds 	vma->vm_flags = flags;
30583ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(flags);
30592e7ce7d3SLiam R. Howlett 	mas_set_range(mas, vma->vm_start, addr + len - 1);
30602e7ce7d3SLiam R. Howlett 	if (mas_store_gfp(mas, vma, GFP_KERNEL))
30612e7ce7d3SLiam R. Howlett 		goto mas_store_fail;
3062d4af56c5SLiam R. Howlett 
30632e7ce7d3SLiam R. Howlett 	if (!prev)
30642e7ce7d3SLiam R. Howlett 		prev = mas_prev(mas, 0);
30652e7ce7d3SLiam R. Howlett 
30662e7ce7d3SLiam R. Howlett 	__vma_link_list(mm, vma, prev);
30672e7ce7d3SLiam R. Howlett 	mm->map_count++;
30681da177e4SLinus Torvalds out:
30693af9e859SEric B Munson 	perf_event_mmap(vma);
30701da177e4SLinus Torvalds 	mm->total_vm += len >> PAGE_SHIFT;
307184638335SKonstantin Khlebnikov 	mm->data_vm += len >> PAGE_SHIFT;
3072128557ffSMichel Lespinasse 	if (flags & VM_LOCKED)
3073ba470de4SRik van Riel 		mm->locked_vm += (len >> PAGE_SHIFT);
3074d9104d1cSCyrill Gorcunov 	vma->vm_flags |= VM_SOFTDIRTY;
3075d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
30765d22fc25SLinus Torvalds 	return 0;
3077d4af56c5SLiam R. Howlett 
30782e7ce7d3SLiam R. Howlett mas_store_fail:
3079d4af56c5SLiam R. Howlett 	vm_area_free(vma);
30802e7ce7d3SLiam R. Howlett vma_alloc_fail:
30812e7ce7d3SLiam R. Howlett 	vm_unacct_memory(len >> PAGE_SHIFT);
30822e7ce7d3SLiam R. Howlett 	return -ENOMEM;
30832e7ce7d3SLiam R. Howlett 
30842e7ce7d3SLiam R. Howlett mas_expand_failed:
30852e7ce7d3SLiam R. Howlett 	if (vma->anon_vma) {
30862e7ce7d3SLiam R. Howlett 		anon_vma_interval_tree_post_update_vma(vma);
30872e7ce7d3SLiam R. Howlett 		anon_vma_unlock_write(vma->anon_vma);
30882e7ce7d3SLiam R. Howlett 	}
3089d4af56c5SLiam R. Howlett 	return -ENOMEM;
30901da177e4SLinus Torvalds }
30911da177e4SLinus Torvalds 
3092bb177a73SMichal Hocko int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3093e4eb1ff6SLinus Torvalds {
3094e4eb1ff6SLinus Torvalds 	struct mm_struct *mm = current->mm;
30952e7ce7d3SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
3096bb177a73SMichal Hocko 	unsigned long len;
30975d22fc25SLinus Torvalds 	int ret;
3098128557ffSMichel Lespinasse 	bool populate;
3099897ab3e0SMike Rapoport 	LIST_HEAD(uf);
31002e7ce7d3SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, addr, addr);
3101e4eb1ff6SLinus Torvalds 
3102bb177a73SMichal Hocko 	len = PAGE_ALIGN(request);
3103bb177a73SMichal Hocko 	if (len < request)
3104bb177a73SMichal Hocko 		return -ENOMEM;
3105bb177a73SMichal Hocko 	if (!len)
3106bb177a73SMichal Hocko 		return 0;
3107bb177a73SMichal Hocko 
3108d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
31092d6c9282SMichal Hocko 		return -EINTR;
31102d6c9282SMichal Hocko 
31112e7ce7d3SLiam R. Howlett 	/* Until we need other flags, refuse anything except VM_EXEC. */
31122e7ce7d3SLiam R. Howlett 	if ((flags & (~VM_EXEC)) != 0)
31132e7ce7d3SLiam R. Howlett 		return -EINVAL;
31142e7ce7d3SLiam R. Howlett 
31152e7ce7d3SLiam R. Howlett 	ret = check_brk_limits(addr, len);
31162e7ce7d3SLiam R. Howlett 	if (ret)
31172e7ce7d3SLiam R. Howlett 		goto limits_failed;
31182e7ce7d3SLiam R. Howlett 
31192e7ce7d3SLiam R. Howlett 	if (find_vma_intersection(mm, addr, addr + len))
31202e7ce7d3SLiam R. Howlett 		ret = do_munmap(mm, addr, len, &uf);
31212e7ce7d3SLiam R. Howlett 
31222e7ce7d3SLiam R. Howlett 	if (ret)
31232e7ce7d3SLiam R. Howlett 		goto munmap_failed;
31242e7ce7d3SLiam R. Howlett 
31252e7ce7d3SLiam R. Howlett 	vma = mas_prev(&mas, 0);
31262e7ce7d3SLiam R. Howlett 	if (!vma || vma->vm_end != addr || vma_policy(vma) ||
31272e7ce7d3SLiam R. Howlett 	    !can_vma_merge_after(vma, flags, NULL, NULL,
31282e7ce7d3SLiam R. Howlett 				 addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL))
31292e7ce7d3SLiam R. Howlett 		vma = NULL;
31302e7ce7d3SLiam R. Howlett 
31312e7ce7d3SLiam R. Howlett 	ret = do_brk_flags(&mas, vma, addr, len, flags);
3132128557ffSMichel Lespinasse 	populate = ((mm->def_flags & VM_LOCKED) != 0);
3133d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
3134897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
31355d22fc25SLinus Torvalds 	if (populate && !ret)
3136128557ffSMichel Lespinasse 		mm_populate(addr, len);
3137e4eb1ff6SLinus Torvalds 	return ret;
31382e7ce7d3SLiam R. Howlett 
31392e7ce7d3SLiam R. Howlett munmap_failed:
31402e7ce7d3SLiam R. Howlett limits_failed:
31412e7ce7d3SLiam R. Howlett 	mmap_write_unlock(mm);
31422e7ce7d3SLiam R. Howlett 	return ret;
3143e4eb1ff6SLinus Torvalds }
314416e72e9bSDenys Vlasenko EXPORT_SYMBOL(vm_brk_flags);
314516e72e9bSDenys Vlasenko 
314616e72e9bSDenys Vlasenko int vm_brk(unsigned long addr, unsigned long len)
314716e72e9bSDenys Vlasenko {
314816e72e9bSDenys Vlasenko 	return vm_brk_flags(addr, len, 0);
314916e72e9bSDenys Vlasenko }
3150e4eb1ff6SLinus Torvalds EXPORT_SYMBOL(vm_brk);
31511da177e4SLinus Torvalds 
31521da177e4SLinus Torvalds /* Release all mmaps. */
31531da177e4SLinus Torvalds void exit_mmap(struct mm_struct *mm)
31541da177e4SLinus Torvalds {
3155d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
3156ba470de4SRik van Riel 	struct vm_area_struct *vma;
31571da177e4SLinus Torvalds 	unsigned long nr_accounted = 0;
31581da177e4SLinus Torvalds 
3159d6dd61c8SJeremy Fitzhardinge 	/* mm's last user has gone, and its about to be pulled down */
3160cddb8a5cSAndrea Arcangeli 	mmu_notifier_release(mm);
3161d6dd61c8SJeremy Fitzhardinge 
316227ae357fSDavid Rientjes 	if (unlikely(mm_is_oom_victim(mm))) {
316327ae357fSDavid Rientjes 		/*
316427ae357fSDavid Rientjes 		 * Manually reap the mm to free as much memory as possible.
316527ae357fSDavid Rientjes 		 * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3166c1e8d7c6SMichel Lespinasse 		 * this mm from further consideration.  Taking mm->mmap_lock for
316727ae357fSDavid Rientjes 		 * write after setting MMF_OOM_SKIP will guarantee that the oom
3168c1e8d7c6SMichel Lespinasse 		 * reaper will not run on this mm again after mmap_lock is
316927ae357fSDavid Rientjes 		 * dropped.
317027ae357fSDavid Rientjes 		 *
3171c1e8d7c6SMichel Lespinasse 		 * Nothing can be holding mm->mmap_lock here and the above call
317227ae357fSDavid Rientjes 		 * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
317327ae357fSDavid Rientjes 		 * __oom_reap_task_mm() will not block.
317427ae357fSDavid Rientjes 		 */
317593065ac7SMichal Hocko 		(void)__oom_reap_task_mm(mm);
317627ae357fSDavid Rientjes 		set_bit(MMF_OOM_SKIP, &mm->flags);
317727ae357fSDavid Rientjes 	}
317827ae357fSDavid Rientjes 
317964591e86SSuren Baghdasaryan 	mmap_write_lock(mm);
31809480c53eSJeremy Fitzhardinge 	arch_exit_mmap(mm);
31819480c53eSJeremy Fitzhardinge 
3182ba470de4SRik van Riel 	vma = mm->mmap;
318364591e86SSuren Baghdasaryan 	if (!vma) {
318464591e86SSuren Baghdasaryan 		/* Can happen if dup_mmap() received an OOM */
318564591e86SSuren Baghdasaryan 		mmap_write_unlock(mm);
31869480c53eSJeremy Fitzhardinge 		return;
318764591e86SSuren Baghdasaryan 	}
31889480c53eSJeremy Fitzhardinge 
31891da177e4SLinus Torvalds 	lru_add_drain();
31901da177e4SLinus Torvalds 	flush_cache_mm(mm);
3191d8b45053SWill Deacon 	tlb_gather_mmu_fullmm(&tlb, mm);
3192901608d9SOleg Nesterov 	/* update_hiwater_rss(mm) here? but nobody should be looking */
3193e0da382cSHugh Dickins 	/* Use -1 here to ensure all VMAs in the mm are unmapped */
31944f74d2c8SLinus Torvalds 	unmap_vmas(&tlb, vma, 0, -1);
31956ee8630eSHugh Dickins 	free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3196ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
31971da177e4SLinus Torvalds 
319864591e86SSuren Baghdasaryan 	/* Walk the list again, actually closing and freeing it. */
31994f74d2c8SLinus Torvalds 	while (vma) {
32004f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
32014f74d2c8SLinus Torvalds 			nr_accounted += vma_pages(vma);
3202a8fb5618SHugh Dickins 		vma = remove_vma(vma);
32030a3b3c25SPaul E. McKenney 		cond_resched();
32044f74d2c8SLinus Torvalds 	}
3205d4af56c5SLiam R. Howlett 
3206d4af56c5SLiam R. Howlett 	trace_exit_mmap(mm);
3207d4af56c5SLiam R. Howlett 	__mt_destroy(&mm->mm_mt);
3208f798a1d4SSuren Baghdasaryan 	mm->mmap = NULL;
320964591e86SSuren Baghdasaryan 	mmap_write_unlock(mm);
32104f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
32111da177e4SLinus Torvalds }
32121da177e4SLinus Torvalds 
32131da177e4SLinus Torvalds /* Insert vm structure into process list sorted by address
32141da177e4SLinus Torvalds  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3215c8c06efaSDavidlohr Bueso  * then i_mmap_rwsem is taken here.
32161da177e4SLinus Torvalds  */
32171da177e4SLinus Torvalds int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
32181da177e4SLinus Torvalds {
32196597d783SHugh Dickins 	struct vm_area_struct *prev;
3220d4af56c5SLiam R. Howlett 	unsigned long charged = vma_pages(vma);
32211da177e4SLinus Torvalds 
3222d4af56c5SLiam R. Howlett 
3223524e00b3SLiam R. Howlett 	if (range_has_overlap(mm, vma->vm_start, vma->vm_end, &prev))
3224c9d13f5fSChen Gang 		return -ENOMEM;
3225d4af56c5SLiam R. Howlett 
3226c9d13f5fSChen Gang 	if ((vma->vm_flags & VM_ACCOUNT) &&
3227d4af56c5SLiam R. Howlett 	     security_vm_enough_memory_mm(mm, charged))
3228c9d13f5fSChen Gang 		return -ENOMEM;
3229c9d13f5fSChen Gang 
32301da177e4SLinus Torvalds 	/*
32311da177e4SLinus Torvalds 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
32321da177e4SLinus Torvalds 	 * until its first write fault, when page's anon_vma and index
32331da177e4SLinus Torvalds 	 * are set.  But now set the vm_pgoff it will almost certainly
32341da177e4SLinus Torvalds 	 * end up with (unless mremap moves it elsewhere before that
32351da177e4SLinus Torvalds 	 * first wfault), so /proc/pid/maps tells a consistent story.
32361da177e4SLinus Torvalds 	 *
32371da177e4SLinus Torvalds 	 * By setting it to reflect the virtual start address of the
32381da177e4SLinus Torvalds 	 * vma, merges and splits can happen in a seamless way, just
32391da177e4SLinus Torvalds 	 * using the existing file pgoff checks and manipulations.
32408332326eSLiao Pingfang 	 * Similarly in do_mmap and in do_brk_flags.
32411da177e4SLinus Torvalds 	 */
32428a9cc3b5SOleg Nesterov 	if (vma_is_anonymous(vma)) {
32431da177e4SLinus Torvalds 		BUG_ON(vma->anon_vma);
32441da177e4SLinus Torvalds 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
32451da177e4SLinus Torvalds 	}
32462b144498SSrikar Dronamraju 
3247524e00b3SLiam R. Howlett 	if (vma_link(mm, vma, prev)) {
3248d4af56c5SLiam R. Howlett 		vm_unacct_memory(charged);
3249d4af56c5SLiam R. Howlett 		return -ENOMEM;
3250d4af56c5SLiam R. Howlett 	}
3251d4af56c5SLiam R. Howlett 
32521da177e4SLinus Torvalds 	return 0;
32531da177e4SLinus Torvalds }
32541da177e4SLinus Torvalds 
32551da177e4SLinus Torvalds /*
32561da177e4SLinus Torvalds  * Copy the vma structure to a new location in the same mm,
32571da177e4SLinus Torvalds  * prior to moving page table entries, to effect an mremap move.
32581da177e4SLinus Torvalds  */
32591da177e4SLinus Torvalds struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
326038a76013SMichel Lespinasse 	unsigned long addr, unsigned long len, pgoff_t pgoff,
326138a76013SMichel Lespinasse 	bool *need_rmap_locks)
32621da177e4SLinus Torvalds {
32631da177e4SLinus Torvalds 	struct vm_area_struct *vma = *vmap;
32641da177e4SLinus Torvalds 	unsigned long vma_start = vma->vm_start;
32651da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
32661da177e4SLinus Torvalds 	struct vm_area_struct *new_vma, *prev;
3267948f017bSAndrea Arcangeli 	bool faulted_in_anon_vma = true;
32681da177e4SLinus Torvalds 
3269d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
32701da177e4SLinus Torvalds 	/*
32711da177e4SLinus Torvalds 	 * If anonymous vma has not yet been faulted, update new pgoff
32721da177e4SLinus Torvalds 	 * to match new location, to increase its chance of merging.
32731da177e4SLinus Torvalds 	 */
3274ce75799bSOleg Nesterov 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
32751da177e4SLinus Torvalds 		pgoff = addr >> PAGE_SHIFT;
3276948f017bSAndrea Arcangeli 		faulted_in_anon_vma = false;
3277948f017bSAndrea Arcangeli 	}
32781da177e4SLinus Torvalds 
3279524e00b3SLiam R. Howlett 	if (range_has_overlap(mm, addr, addr + len, &prev))
32806597d783SHugh Dickins 		return NULL;	/* should never get here */
3281524e00b3SLiam R. Howlett 
32821da177e4SLinus Torvalds 	new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
328319a809afSAndrea Arcangeli 			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
32845c26f6acSSuren Baghdasaryan 			    vma->vm_userfaultfd_ctx, anon_vma_name(vma));
32851da177e4SLinus Torvalds 	if (new_vma) {
32861da177e4SLinus Torvalds 		/*
32871da177e4SLinus Torvalds 		 * Source vma may have been merged into new_vma
32881da177e4SLinus Torvalds 		 */
3289948f017bSAndrea Arcangeli 		if (unlikely(vma_start >= new_vma->vm_start &&
3290948f017bSAndrea Arcangeli 			     vma_start < new_vma->vm_end)) {
3291948f017bSAndrea Arcangeli 			/*
3292948f017bSAndrea Arcangeli 			 * The only way we can get a vma_merge with
3293948f017bSAndrea Arcangeli 			 * self during an mremap is if the vma hasn't
3294948f017bSAndrea Arcangeli 			 * been faulted in yet and we were allowed to
3295948f017bSAndrea Arcangeli 			 * reset the dst vma->vm_pgoff to the
3296948f017bSAndrea Arcangeli 			 * destination address of the mremap to allow
3297948f017bSAndrea Arcangeli 			 * the merge to happen. mremap must change the
3298948f017bSAndrea Arcangeli 			 * vm_pgoff linearity between src and dst vmas
3299948f017bSAndrea Arcangeli 			 * (in turn preventing a vma_merge) to be
3300948f017bSAndrea Arcangeli 			 * safe. It is only safe to keep the vm_pgoff
3301948f017bSAndrea Arcangeli 			 * linear if there are no pages mapped yet.
3302948f017bSAndrea Arcangeli 			 */
330381d1b09cSSasha Levin 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
330438a76013SMichel Lespinasse 			*vmap = vma = new_vma;
3305108d6642SMichel Lespinasse 		}
330638a76013SMichel Lespinasse 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
33071da177e4SLinus Torvalds 	} else {
33083928d4f5SLinus Torvalds 		new_vma = vm_area_dup(vma);
3309e3975891SChen Gang 		if (!new_vma)
3310e3975891SChen Gang 			goto out;
33111da177e4SLinus Torvalds 		new_vma->vm_start = addr;
33121da177e4SLinus Torvalds 		new_vma->vm_end = addr + len;
33131da177e4SLinus Torvalds 		new_vma->vm_pgoff = pgoff;
3314ef0855d3SOleg Nesterov 		if (vma_dup_policy(vma, new_vma))
3315523d4e20SMichel Lespinasse 			goto out_free_vma;
3316523d4e20SMichel Lespinasse 		if (anon_vma_clone(new_vma, vma))
3317523d4e20SMichel Lespinasse 			goto out_free_mempol;
3318e9714acfSKonstantin Khlebnikov 		if (new_vma->vm_file)
33191da177e4SLinus Torvalds 			get_file(new_vma->vm_file);
33201da177e4SLinus Torvalds 		if (new_vma->vm_ops && new_vma->vm_ops->open)
33211da177e4SLinus Torvalds 			new_vma->vm_ops->open(new_vma);
3322524e00b3SLiam R. Howlett 		if (vma_link(mm, new_vma, prev))
3323524e00b3SLiam R. Howlett 			goto out_vma_link;
332438a76013SMichel Lespinasse 		*need_rmap_locks = false;
33251da177e4SLinus Torvalds 	}
3326d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
33271da177e4SLinus Torvalds 	return new_vma;
33285beb4930SRik van Riel 
3329524e00b3SLiam R. Howlett out_vma_link:
3330524e00b3SLiam R. Howlett 	if (new_vma->vm_ops && new_vma->vm_ops->close)
3331524e00b3SLiam R. Howlett 		new_vma->vm_ops->close(new_vma);
33325beb4930SRik van Riel out_free_mempol:
3333ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new_vma));
33345beb4930SRik van Riel out_free_vma:
33353928d4f5SLinus Torvalds 	vm_area_free(new_vma);
3336e3975891SChen Gang out:
3337d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
33385beb4930SRik van Riel 	return NULL;
33391da177e4SLinus Torvalds }
3340119f657cSakpm@osdl.org 
3341119f657cSakpm@osdl.org /*
3342119f657cSakpm@osdl.org  * Return true if the calling process may expand its vm space by the passed
3343119f657cSakpm@osdl.org  * number of pages
3344119f657cSakpm@osdl.org  */
334584638335SKonstantin Khlebnikov bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3346119f657cSakpm@osdl.org {
334784638335SKonstantin Khlebnikov 	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
334884638335SKonstantin Khlebnikov 		return false;
3349119f657cSakpm@osdl.org 
3350d977d56cSKonstantin Khlebnikov 	if (is_data_mapping(flags) &&
3351d977d56cSKonstantin Khlebnikov 	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3352f4fcd558SKonstantin Khlebnikov 		/* Workaround for Valgrind */
3353f4fcd558SKonstantin Khlebnikov 		if (rlimit(RLIMIT_DATA) == 0 &&
3354f4fcd558SKonstantin Khlebnikov 		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3355f4fcd558SKonstantin Khlebnikov 			return true;
335657a7702bSDavid Woodhouse 
335757a7702bSDavid Woodhouse 		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3358d977d56cSKonstantin Khlebnikov 			     current->comm, current->pid,
3359d977d56cSKonstantin Khlebnikov 			     (mm->data_vm + npages) << PAGE_SHIFT,
336057a7702bSDavid Woodhouse 			     rlimit(RLIMIT_DATA),
336157a7702bSDavid Woodhouse 			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
336257a7702bSDavid Woodhouse 
336357a7702bSDavid Woodhouse 		if (!ignore_rlimit_data)
3364d977d56cSKonstantin Khlebnikov 			return false;
3365d977d56cSKonstantin Khlebnikov 	}
3366119f657cSakpm@osdl.org 
336784638335SKonstantin Khlebnikov 	return true;
336884638335SKonstantin Khlebnikov }
336984638335SKonstantin Khlebnikov 
337084638335SKonstantin Khlebnikov void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
337184638335SKonstantin Khlebnikov {
33727866076bSPeng Liu 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
337384638335SKonstantin Khlebnikov 
3374d977d56cSKonstantin Khlebnikov 	if (is_exec_mapping(flags))
337584638335SKonstantin Khlebnikov 		mm->exec_vm += npages;
3376d977d56cSKonstantin Khlebnikov 	else if (is_stack_mapping(flags))
337784638335SKonstantin Khlebnikov 		mm->stack_vm += npages;
3378d977d56cSKonstantin Khlebnikov 	else if (is_data_mapping(flags))
337984638335SKonstantin Khlebnikov 		mm->data_vm += npages;
3380119f657cSakpm@osdl.org }
3381fa5dc22fSRoland McGrath 
3382b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3383a62c34bdSAndy Lutomirski 
3384a62c34bdSAndy Lutomirski /*
3385a62c34bdSAndy Lutomirski  * Having a close hook prevents vma merging regardless of flags.
3386a62c34bdSAndy Lutomirski  */
3387a62c34bdSAndy Lutomirski static void special_mapping_close(struct vm_area_struct *vma)
3388a62c34bdSAndy Lutomirski {
3389a62c34bdSAndy Lutomirski }
3390a62c34bdSAndy Lutomirski 
3391a62c34bdSAndy Lutomirski static const char *special_mapping_name(struct vm_area_struct *vma)
3392a62c34bdSAndy Lutomirski {
3393a62c34bdSAndy Lutomirski 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3394a62c34bdSAndy Lutomirski }
3395a62c34bdSAndy Lutomirski 
339614d07113SBrian Geffon static int special_mapping_mremap(struct vm_area_struct *new_vma)
3397b059a453SDmitry Safonov {
3398b059a453SDmitry Safonov 	struct vm_special_mapping *sm = new_vma->vm_private_data;
3399b059a453SDmitry Safonov 
3400280e87e9SDmitry Safonov 	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3401280e87e9SDmitry Safonov 		return -EFAULT;
3402280e87e9SDmitry Safonov 
3403b059a453SDmitry Safonov 	if (sm->mremap)
3404b059a453SDmitry Safonov 		return sm->mremap(sm, new_vma);
3405280e87e9SDmitry Safonov 
3406b059a453SDmitry Safonov 	return 0;
3407b059a453SDmitry Safonov }
3408b059a453SDmitry Safonov 
3409871402e0SDmitry Safonov static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3410871402e0SDmitry Safonov {
3411871402e0SDmitry Safonov 	/*
3412871402e0SDmitry Safonov 	 * Forbid splitting special mappings - kernel has expectations over
3413871402e0SDmitry Safonov 	 * the number of pages in mapping. Together with VM_DONTEXPAND
3414871402e0SDmitry Safonov 	 * the size of vma should stay the same over the special mapping's
3415871402e0SDmitry Safonov 	 * lifetime.
3416871402e0SDmitry Safonov 	 */
3417871402e0SDmitry Safonov 	return -EINVAL;
3418871402e0SDmitry Safonov }
3419871402e0SDmitry Safonov 
3420a62c34bdSAndy Lutomirski static const struct vm_operations_struct special_mapping_vmops = {
3421a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3422a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3423b059a453SDmitry Safonov 	.mremap = special_mapping_mremap,
3424a62c34bdSAndy Lutomirski 	.name = special_mapping_name,
3425af34ebebSDmitry Safonov 	/* vDSO code relies that VVAR can't be accessed remotely */
3426af34ebebSDmitry Safonov 	.access = NULL,
3427871402e0SDmitry Safonov 	.may_split = special_mapping_split,
3428a62c34bdSAndy Lutomirski };
3429a62c34bdSAndy Lutomirski 
3430a62c34bdSAndy Lutomirski static const struct vm_operations_struct legacy_special_mapping_vmops = {
3431a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3432a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3433a62c34bdSAndy Lutomirski };
3434fa5dc22fSRoland McGrath 
3435b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3436fa5dc22fSRoland McGrath {
343711bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
3438b1d0e4f5SNick Piggin 	pgoff_t pgoff;
3439fa5dc22fSRoland McGrath 	struct page **pages;
3440fa5dc22fSRoland McGrath 
3441f872f540SAndy Lutomirski 	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3442a62c34bdSAndy Lutomirski 		pages = vma->vm_private_data;
3443f872f540SAndy Lutomirski 	} else {
3444f872f540SAndy Lutomirski 		struct vm_special_mapping *sm = vma->vm_private_data;
3445f872f540SAndy Lutomirski 
3446f872f540SAndy Lutomirski 		if (sm->fault)
344711bac800SDave Jiang 			return sm->fault(sm, vmf->vma, vmf);
3448f872f540SAndy Lutomirski 
3449f872f540SAndy Lutomirski 		pages = sm->pages;
3450f872f540SAndy Lutomirski 	}
3451a62c34bdSAndy Lutomirski 
34528a9cc3b5SOleg Nesterov 	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3453b1d0e4f5SNick Piggin 		pgoff--;
3454fa5dc22fSRoland McGrath 
3455fa5dc22fSRoland McGrath 	if (*pages) {
3456fa5dc22fSRoland McGrath 		struct page *page = *pages;
3457fa5dc22fSRoland McGrath 		get_page(page);
3458b1d0e4f5SNick Piggin 		vmf->page = page;
3459b1d0e4f5SNick Piggin 		return 0;
3460fa5dc22fSRoland McGrath 	}
3461fa5dc22fSRoland McGrath 
3462b1d0e4f5SNick Piggin 	return VM_FAULT_SIGBUS;
3463fa5dc22fSRoland McGrath }
3464fa5dc22fSRoland McGrath 
3465a62c34bdSAndy Lutomirski static struct vm_area_struct *__install_special_mapping(
3466a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3467fa5dc22fSRoland McGrath 	unsigned long addr, unsigned long len,
346827f28b97SChen Gang 	unsigned long vm_flags, void *priv,
346927f28b97SChen Gang 	const struct vm_operations_struct *ops)
3470fa5dc22fSRoland McGrath {
3471462e635eSTavis Ormandy 	int ret;
3472fa5dc22fSRoland McGrath 	struct vm_area_struct *vma;
3473fa5dc22fSRoland McGrath 
3474d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
3475490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
3476fa5dc22fSRoland McGrath 	if (unlikely(vma == NULL))
34773935ed6aSStefani Seibold 		return ERR_PTR(-ENOMEM);
3478fa5dc22fSRoland McGrath 
3479fa5dc22fSRoland McGrath 	vma->vm_start = addr;
3480fa5dc22fSRoland McGrath 	vma->vm_end = addr + len;
3481fa5dc22fSRoland McGrath 
3482d9104d1cSCyrill Gorcunov 	vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
34831fc09228SHugh Dickins 	vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
34843ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3485fa5dc22fSRoland McGrath 
3486a62c34bdSAndy Lutomirski 	vma->vm_ops = ops;
3487a62c34bdSAndy Lutomirski 	vma->vm_private_data = priv;
3488fa5dc22fSRoland McGrath 
3489462e635eSTavis Ormandy 	ret = insert_vm_struct(mm, vma);
3490462e635eSTavis Ormandy 	if (ret)
3491462e635eSTavis Ormandy 		goto out;
3492fa5dc22fSRoland McGrath 
349384638335SKonstantin Khlebnikov 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3494fa5dc22fSRoland McGrath 
3495cdd6c482SIngo Molnar 	perf_event_mmap(vma);
3496089dd79dSPeter Zijlstra 
3497d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
34983935ed6aSStefani Seibold 	return vma;
3499462e635eSTavis Ormandy 
3500462e635eSTavis Ormandy out:
35013928d4f5SLinus Torvalds 	vm_area_free(vma);
3502d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
35033935ed6aSStefani Seibold 	return ERR_PTR(ret);
35043935ed6aSStefani Seibold }
35053935ed6aSStefani Seibold 
35062eefd878SDmitry Safonov bool vma_is_special_mapping(const struct vm_area_struct *vma,
35072eefd878SDmitry Safonov 	const struct vm_special_mapping *sm)
35082eefd878SDmitry Safonov {
35092eefd878SDmitry Safonov 	return vma->vm_private_data == sm &&
35102eefd878SDmitry Safonov 		(vma->vm_ops == &special_mapping_vmops ||
35112eefd878SDmitry Safonov 		 vma->vm_ops == &legacy_special_mapping_vmops);
35122eefd878SDmitry Safonov }
35132eefd878SDmitry Safonov 
3514a62c34bdSAndy Lutomirski /*
3515c1e8d7c6SMichel Lespinasse  * Called with mm->mmap_lock held for writing.
3516a62c34bdSAndy Lutomirski  * Insert a new vma covering the given region, with the given flags.
3517a62c34bdSAndy Lutomirski  * Its pages are supplied by the given array of struct page *.
3518a62c34bdSAndy Lutomirski  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3519a62c34bdSAndy Lutomirski  * The region past the last page supplied will always produce SIGBUS.
3520a62c34bdSAndy Lutomirski  * The array pointer and the pages it points to are assumed to stay alive
3521a62c34bdSAndy Lutomirski  * for as long as this mapping might exist.
3522a62c34bdSAndy Lutomirski  */
3523a62c34bdSAndy Lutomirski struct vm_area_struct *_install_special_mapping(
3524a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3525a62c34bdSAndy Lutomirski 	unsigned long addr, unsigned long len,
3526a62c34bdSAndy Lutomirski 	unsigned long vm_flags, const struct vm_special_mapping *spec)
3527a62c34bdSAndy Lutomirski {
352827f28b97SChen Gang 	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
352927f28b97SChen Gang 					&special_mapping_vmops);
3530a62c34bdSAndy Lutomirski }
3531a62c34bdSAndy Lutomirski 
35323935ed6aSStefani Seibold int install_special_mapping(struct mm_struct *mm,
35333935ed6aSStefani Seibold 			    unsigned long addr, unsigned long len,
35343935ed6aSStefani Seibold 			    unsigned long vm_flags, struct page **pages)
35353935ed6aSStefani Seibold {
3536a62c34bdSAndy Lutomirski 	struct vm_area_struct *vma = __install_special_mapping(
353727f28b97SChen Gang 		mm, addr, len, vm_flags, (void *)pages,
353827f28b97SChen Gang 		&legacy_special_mapping_vmops);
35393935ed6aSStefani Seibold 
354014bd5b45SDuan Jiong 	return PTR_ERR_OR_ZERO(vma);
3541fa5dc22fSRoland McGrath }
35427906d00cSAndrea Arcangeli 
35437906d00cSAndrea Arcangeli static DEFINE_MUTEX(mm_all_locks_mutex);
35447906d00cSAndrea Arcangeli 
3545454ed842SPeter Zijlstra static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
35467906d00cSAndrea Arcangeli {
3547f808c13fSDavidlohr Bueso 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
35487906d00cSAndrea Arcangeli 		/*
35497906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change from under us
35507906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
35517906d00cSAndrea Arcangeli 		 */
3552da1c55f1SMichel Lespinasse 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
35537906d00cSAndrea Arcangeli 		/*
35547906d00cSAndrea Arcangeli 		 * We can safely modify head.next after taking the
35555a505085SIngo Molnar 		 * anon_vma->root->rwsem. If some other vma in this mm shares
35567906d00cSAndrea Arcangeli 		 * the same anon_vma we won't take it again.
35577906d00cSAndrea Arcangeli 		 *
35587906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
35597906d00cSAndrea Arcangeli 		 * can't change from under us thanks to the
35605a505085SIngo Molnar 		 * anon_vma->root->rwsem.
35617906d00cSAndrea Arcangeli 		 */
35627906d00cSAndrea Arcangeli 		if (__test_and_set_bit(0, (unsigned long *)
3563f808c13fSDavidlohr Bueso 				       &anon_vma->root->rb_root.rb_root.rb_node))
35647906d00cSAndrea Arcangeli 			BUG();
35657906d00cSAndrea Arcangeli 	}
35667906d00cSAndrea Arcangeli }
35677906d00cSAndrea Arcangeli 
3568454ed842SPeter Zijlstra static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
35697906d00cSAndrea Arcangeli {
35707906d00cSAndrea Arcangeli 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
35717906d00cSAndrea Arcangeli 		/*
35727906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change from under us because
35737906d00cSAndrea Arcangeli 		 * we hold the mm_all_locks_mutex.
35747906d00cSAndrea Arcangeli 		 *
35757906d00cSAndrea Arcangeli 		 * Operations on ->flags have to be atomic because
35767906d00cSAndrea Arcangeli 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
35777906d00cSAndrea Arcangeli 		 * mm_all_locks_mutex, there may be other cpus
35787906d00cSAndrea Arcangeli 		 * changing other bitflags in parallel to us.
35797906d00cSAndrea Arcangeli 		 */
35807906d00cSAndrea Arcangeli 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
35817906d00cSAndrea Arcangeli 			BUG();
3582da1c55f1SMichel Lespinasse 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
35837906d00cSAndrea Arcangeli 	}
35847906d00cSAndrea Arcangeli }
35857906d00cSAndrea Arcangeli 
35867906d00cSAndrea Arcangeli /*
35877906d00cSAndrea Arcangeli  * This operation locks against the VM for all pte/vma/mm related
35887906d00cSAndrea Arcangeli  * operations that could ever happen on a certain mm. This includes
35897906d00cSAndrea Arcangeli  * vmtruncate, try_to_unmap, and all page faults.
35907906d00cSAndrea Arcangeli  *
3591c1e8d7c6SMichel Lespinasse  * The caller must take the mmap_lock in write mode before calling
35927906d00cSAndrea Arcangeli  * mm_take_all_locks(). The caller isn't allowed to release the
3593c1e8d7c6SMichel Lespinasse  * mmap_lock until mm_drop_all_locks() returns.
35947906d00cSAndrea Arcangeli  *
3595c1e8d7c6SMichel Lespinasse  * mmap_lock in write mode is required in order to block all operations
35967906d00cSAndrea Arcangeli  * that could modify pagetables and free pages without need of
359727ba0644SKirill A. Shutemov  * altering the vma layout. It's also needed in write mode to avoid new
35987906d00cSAndrea Arcangeli  * anon_vmas to be associated with existing vmas.
35997906d00cSAndrea Arcangeli  *
36007906d00cSAndrea Arcangeli  * A single task can't take more than one mm_take_all_locks() in a row
36017906d00cSAndrea Arcangeli  * or it would deadlock.
36027906d00cSAndrea Arcangeli  *
3603bf181b9fSMichel Lespinasse  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
36047906d00cSAndrea Arcangeli  * mapping->flags avoid to take the same lock twice, if more than one
36057906d00cSAndrea Arcangeli  * vma in this mm is backed by the same anon_vma or address_space.
36067906d00cSAndrea Arcangeli  *
360788f306b6SKirill A. Shutemov  * We take locks in following order, accordingly to comment at beginning
360888f306b6SKirill A. Shutemov  * of mm/rmap.c:
360988f306b6SKirill A. Shutemov  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
361088f306b6SKirill A. Shutemov  *     hugetlb mapping);
361188f306b6SKirill A. Shutemov  *   - all i_mmap_rwsem locks;
361288f306b6SKirill A. Shutemov  *   - all anon_vma->rwseml
361388f306b6SKirill A. Shutemov  *
361488f306b6SKirill A. Shutemov  * We can take all locks within these types randomly because the VM code
361588f306b6SKirill A. Shutemov  * doesn't nest them and we protected from parallel mm_take_all_locks() by
361688f306b6SKirill A. Shutemov  * mm_all_locks_mutex.
36177906d00cSAndrea Arcangeli  *
36187906d00cSAndrea Arcangeli  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
36197906d00cSAndrea Arcangeli  * that may have to take thousand of locks.
36207906d00cSAndrea Arcangeli  *
36217906d00cSAndrea Arcangeli  * mm_take_all_locks() can fail if it's interrupted by signals.
36227906d00cSAndrea Arcangeli  */
36237906d00cSAndrea Arcangeli int mm_take_all_locks(struct mm_struct *mm)
36247906d00cSAndrea Arcangeli {
36257906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
36265beb4930SRik van Riel 	struct anon_vma_chain *avc;
36277906d00cSAndrea Arcangeli 
3628325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
36297906d00cSAndrea Arcangeli 
36307906d00cSAndrea Arcangeli 	mutex_lock(&mm_all_locks_mutex);
36317906d00cSAndrea Arcangeli 
36327906d00cSAndrea Arcangeli 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
36337906d00cSAndrea Arcangeli 		if (signal_pending(current))
36347906d00cSAndrea Arcangeli 			goto out_unlock;
363588f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
363688f306b6SKirill A. Shutemov 				is_vm_hugetlb_page(vma))
363788f306b6SKirill A. Shutemov 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
363888f306b6SKirill A. Shutemov 	}
363988f306b6SKirill A. Shutemov 
364088f306b6SKirill A. Shutemov 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
364188f306b6SKirill A. Shutemov 		if (signal_pending(current))
364288f306b6SKirill A. Shutemov 			goto out_unlock;
364388f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
364488f306b6SKirill A. Shutemov 				!is_vm_hugetlb_page(vma))
3645454ed842SPeter Zijlstra 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
36467906d00cSAndrea Arcangeli 	}
36477cd5a02fSPeter Zijlstra 
36487cd5a02fSPeter Zijlstra 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
36497cd5a02fSPeter Zijlstra 		if (signal_pending(current))
36507cd5a02fSPeter Zijlstra 			goto out_unlock;
36517cd5a02fSPeter Zijlstra 		if (vma->anon_vma)
36525beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
36535beb4930SRik van Riel 				vm_lock_anon_vma(mm, avc->anon_vma);
36547cd5a02fSPeter Zijlstra 	}
36557cd5a02fSPeter Zijlstra 
3656584cff54SKautuk Consul 	return 0;
36577906d00cSAndrea Arcangeli 
36587906d00cSAndrea Arcangeli out_unlock:
36597906d00cSAndrea Arcangeli 	mm_drop_all_locks(mm);
3660584cff54SKautuk Consul 	return -EINTR;
36617906d00cSAndrea Arcangeli }
36627906d00cSAndrea Arcangeli 
36637906d00cSAndrea Arcangeli static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
36647906d00cSAndrea Arcangeli {
3665f808c13fSDavidlohr Bueso 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
36667906d00cSAndrea Arcangeli 		/*
36677906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change to 0 from under
36687906d00cSAndrea Arcangeli 		 * us because we hold the mm_all_locks_mutex.
36697906d00cSAndrea Arcangeli 		 *
36707906d00cSAndrea Arcangeli 		 * We must however clear the bitflag before unlocking
3671bf181b9fSMichel Lespinasse 		 * the vma so the users using the anon_vma->rb_root will
36727906d00cSAndrea Arcangeli 		 * never see our bitflag.
36737906d00cSAndrea Arcangeli 		 *
36747906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
36757906d00cSAndrea Arcangeli 		 * can't change from under us until we release the
36765a505085SIngo Molnar 		 * anon_vma->root->rwsem.
36777906d00cSAndrea Arcangeli 		 */
36787906d00cSAndrea Arcangeli 		if (!__test_and_clear_bit(0, (unsigned long *)
3679f808c13fSDavidlohr Bueso 					  &anon_vma->root->rb_root.rb_root.rb_node))
36807906d00cSAndrea Arcangeli 			BUG();
368108b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
36827906d00cSAndrea Arcangeli 	}
36837906d00cSAndrea Arcangeli }
36847906d00cSAndrea Arcangeli 
36857906d00cSAndrea Arcangeli static void vm_unlock_mapping(struct address_space *mapping)
36867906d00cSAndrea Arcangeli {
36877906d00cSAndrea Arcangeli 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
36887906d00cSAndrea Arcangeli 		/*
36897906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
36907906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
36917906d00cSAndrea Arcangeli 		 */
369283cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
36937906d00cSAndrea Arcangeli 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
36947906d00cSAndrea Arcangeli 					&mapping->flags))
36957906d00cSAndrea Arcangeli 			BUG();
36967906d00cSAndrea Arcangeli 	}
36977906d00cSAndrea Arcangeli }
36987906d00cSAndrea Arcangeli 
36997906d00cSAndrea Arcangeli /*
3700c1e8d7c6SMichel Lespinasse  * The mmap_lock cannot be released by the caller until
37017906d00cSAndrea Arcangeli  * mm_drop_all_locks() returns.
37027906d00cSAndrea Arcangeli  */
37037906d00cSAndrea Arcangeli void mm_drop_all_locks(struct mm_struct *mm)
37047906d00cSAndrea Arcangeli {
37057906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
37065beb4930SRik van Riel 	struct anon_vma_chain *avc;
37077906d00cSAndrea Arcangeli 
3708325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
37097906d00cSAndrea Arcangeli 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
37107906d00cSAndrea Arcangeli 
37117906d00cSAndrea Arcangeli 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
37127906d00cSAndrea Arcangeli 		if (vma->anon_vma)
37135beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
37145beb4930SRik van Riel 				vm_unlock_anon_vma(avc->anon_vma);
37157906d00cSAndrea Arcangeli 		if (vma->vm_file && vma->vm_file->f_mapping)
37167906d00cSAndrea Arcangeli 			vm_unlock_mapping(vma->vm_file->f_mapping);
37177906d00cSAndrea Arcangeli 	}
37187906d00cSAndrea Arcangeli 
37197906d00cSAndrea Arcangeli 	mutex_unlock(&mm_all_locks_mutex);
37207906d00cSAndrea Arcangeli }
37218feae131SDavid Howells 
37228feae131SDavid Howells /*
37233edf41d8Sseokhoon.yoon  * initialise the percpu counter for VM
37248feae131SDavid Howells  */
37258feae131SDavid Howells void __init mmap_init(void)
37268feae131SDavid Howells {
372700a62ce9SKOSAKI Motohiro 	int ret;
372800a62ce9SKOSAKI Motohiro 
3729908c7f19STejun Heo 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
373000a62ce9SKOSAKI Motohiro 	VM_BUG_ON(ret);
37318feae131SDavid Howells }
3732c9b1d098SAndrew Shewmaker 
3733c9b1d098SAndrew Shewmaker /*
3734c9b1d098SAndrew Shewmaker  * Initialise sysctl_user_reserve_kbytes.
3735c9b1d098SAndrew Shewmaker  *
3736c9b1d098SAndrew Shewmaker  * This is intended to prevent a user from starting a single memory hogging
3737c9b1d098SAndrew Shewmaker  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3738c9b1d098SAndrew Shewmaker  * mode.
3739c9b1d098SAndrew Shewmaker  *
3740c9b1d098SAndrew Shewmaker  * The default value is min(3% of free memory, 128MB)
3741c9b1d098SAndrew Shewmaker  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3742c9b1d098SAndrew Shewmaker  */
37431640879aSAndrew Shewmaker static int init_user_reserve(void)
3744c9b1d098SAndrew Shewmaker {
3745c9b1d098SAndrew Shewmaker 	unsigned long free_kbytes;
3746c9b1d098SAndrew Shewmaker 
3747c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3748c9b1d098SAndrew Shewmaker 
3749c9b1d098SAndrew Shewmaker 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3750c9b1d098SAndrew Shewmaker 	return 0;
3751c9b1d098SAndrew Shewmaker }
3752a64fb3cdSPaul Gortmaker subsys_initcall(init_user_reserve);
37534eeab4f5SAndrew Shewmaker 
37544eeab4f5SAndrew Shewmaker /*
37554eeab4f5SAndrew Shewmaker  * Initialise sysctl_admin_reserve_kbytes.
37564eeab4f5SAndrew Shewmaker  *
37574eeab4f5SAndrew Shewmaker  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
37584eeab4f5SAndrew Shewmaker  * to log in and kill a memory hogging process.
37594eeab4f5SAndrew Shewmaker  *
37604eeab4f5SAndrew Shewmaker  * Systems with more than 256MB will reserve 8MB, enough to recover
37614eeab4f5SAndrew Shewmaker  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
37624eeab4f5SAndrew Shewmaker  * only reserve 3% of free pages by default.
37634eeab4f5SAndrew Shewmaker  */
37641640879aSAndrew Shewmaker static int init_admin_reserve(void)
37654eeab4f5SAndrew Shewmaker {
37664eeab4f5SAndrew Shewmaker 	unsigned long free_kbytes;
37674eeab4f5SAndrew Shewmaker 
3768c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
37694eeab4f5SAndrew Shewmaker 
37704eeab4f5SAndrew Shewmaker 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
37714eeab4f5SAndrew Shewmaker 	return 0;
37724eeab4f5SAndrew Shewmaker }
3773a64fb3cdSPaul Gortmaker subsys_initcall(init_admin_reserve);
37741640879aSAndrew Shewmaker 
37751640879aSAndrew Shewmaker /*
37761640879aSAndrew Shewmaker  * Reinititalise user and admin reserves if memory is added or removed.
37771640879aSAndrew Shewmaker  *
37781640879aSAndrew Shewmaker  * The default user reserve max is 128MB, and the default max for the
37791640879aSAndrew Shewmaker  * admin reserve is 8MB. These are usually, but not always, enough to
37801640879aSAndrew Shewmaker  * enable recovery from a memory hogging process using login/sshd, a shell,
37811640879aSAndrew Shewmaker  * and tools like top. It may make sense to increase or even disable the
37821640879aSAndrew Shewmaker  * reserve depending on the existence of swap or variations in the recovery
37831640879aSAndrew Shewmaker  * tools. So, the admin may have changed them.
37841640879aSAndrew Shewmaker  *
37851640879aSAndrew Shewmaker  * If memory is added and the reserves have been eliminated or increased above
37861640879aSAndrew Shewmaker  * the default max, then we'll trust the admin.
37871640879aSAndrew Shewmaker  *
37881640879aSAndrew Shewmaker  * If memory is removed and there isn't enough free memory, then we
37891640879aSAndrew Shewmaker  * need to reset the reserves.
37901640879aSAndrew Shewmaker  *
37911640879aSAndrew Shewmaker  * Otherwise keep the reserve set by the admin.
37921640879aSAndrew Shewmaker  */
37931640879aSAndrew Shewmaker static int reserve_mem_notifier(struct notifier_block *nb,
37941640879aSAndrew Shewmaker 			     unsigned long action, void *data)
37951640879aSAndrew Shewmaker {
37961640879aSAndrew Shewmaker 	unsigned long tmp, free_kbytes;
37971640879aSAndrew Shewmaker 
37981640879aSAndrew Shewmaker 	switch (action) {
37991640879aSAndrew Shewmaker 	case MEM_ONLINE:
38001640879aSAndrew Shewmaker 		/* Default max is 128MB. Leave alone if modified by operator. */
38011640879aSAndrew Shewmaker 		tmp = sysctl_user_reserve_kbytes;
38021640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 17))
38031640879aSAndrew Shewmaker 			init_user_reserve();
38041640879aSAndrew Shewmaker 
38051640879aSAndrew Shewmaker 		/* Default max is 8MB.  Leave alone if modified by operator. */
38061640879aSAndrew Shewmaker 		tmp = sysctl_admin_reserve_kbytes;
38071640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 13))
38081640879aSAndrew Shewmaker 			init_admin_reserve();
38091640879aSAndrew Shewmaker 
38101640879aSAndrew Shewmaker 		break;
38111640879aSAndrew Shewmaker 	case MEM_OFFLINE:
3812c41f012aSMichal Hocko 		free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
38131640879aSAndrew Shewmaker 
38141640879aSAndrew Shewmaker 		if (sysctl_user_reserve_kbytes > free_kbytes) {
38151640879aSAndrew Shewmaker 			init_user_reserve();
38161640879aSAndrew Shewmaker 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
38171640879aSAndrew Shewmaker 				sysctl_user_reserve_kbytes);
38181640879aSAndrew Shewmaker 		}
38191640879aSAndrew Shewmaker 
38201640879aSAndrew Shewmaker 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
38211640879aSAndrew Shewmaker 			init_admin_reserve();
38221640879aSAndrew Shewmaker 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
38231640879aSAndrew Shewmaker 				sysctl_admin_reserve_kbytes);
38241640879aSAndrew Shewmaker 		}
38251640879aSAndrew Shewmaker 		break;
38261640879aSAndrew Shewmaker 	default:
38271640879aSAndrew Shewmaker 		break;
38281640879aSAndrew Shewmaker 	}
38291640879aSAndrew Shewmaker 	return NOTIFY_OK;
38301640879aSAndrew Shewmaker }
38311640879aSAndrew Shewmaker 
38321640879aSAndrew Shewmaker static struct notifier_block reserve_mem_nb = {
38331640879aSAndrew Shewmaker 	.notifier_call = reserve_mem_notifier,
38341640879aSAndrew Shewmaker };
38351640879aSAndrew Shewmaker 
38361640879aSAndrew Shewmaker static int __meminit init_reserve_notifier(void)
38371640879aSAndrew Shewmaker {
38381640879aSAndrew Shewmaker 	if (register_hotmemory_notifier(&reserve_mem_nb))
3839b1de0d13SMitchel Humpherys 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
38401640879aSAndrew Shewmaker 
38411640879aSAndrew Shewmaker 	return 0;
38421640879aSAndrew Shewmaker }
3843a64fb3cdSPaul Gortmaker subsys_initcall(init_reserve_notifier);
3844