xref: /linux/mm/mmap.c (revision 2e7ce7d354f2fae4c9becb8af799cbedf4f71665)
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>
17615d6e87SDavidlohr Bueso #include <linux/vmacache.h>
181da177e4SLinus Torvalds #include <linux/shm.h>
191da177e4SLinus Torvalds #include <linux/mman.h>
201da177e4SLinus Torvalds #include <linux/pagemap.h>
211da177e4SLinus Torvalds #include <linux/swap.h>
221da177e4SLinus Torvalds #include <linux/syscalls.h>
23c59ede7bSRandy.Dunlap #include <linux/capability.h>
241da177e4SLinus Torvalds #include <linux/init.h>
251da177e4SLinus Torvalds #include <linux/file.h>
261da177e4SLinus Torvalds #include <linux/fs.h>
271da177e4SLinus Torvalds #include <linux/personality.h>
281da177e4SLinus Torvalds #include <linux/security.h>
291da177e4SLinus Torvalds #include <linux/hugetlb.h>
30c01d5b30SHugh Dickins #include <linux/shmem_fs.h>
311da177e4SLinus Torvalds #include <linux/profile.h>
32b95f1b31SPaul Gortmaker #include <linux/export.h>
331da177e4SLinus Torvalds #include <linux/mount.h>
341da177e4SLinus Torvalds #include <linux/mempolicy.h>
351da177e4SLinus Torvalds #include <linux/rmap.h>
36cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
3782f71ae4SKonstantin Khlebnikov #include <linux/mmdebug.h>
38cdd6c482SIngo Molnar #include <linux/perf_event.h>
39120a795dSAl Viro #include <linux/audit.h>
40b15d00b6SAndrea Arcangeli #include <linux/khugepaged.h>
412b144498SSrikar Dronamraju #include <linux/uprobes.h>
421640879aSAndrew Shewmaker #include <linux/notifier.h>
431640879aSAndrew Shewmaker #include <linux/memory.h>
44b1de0d13SMitchel Humpherys #include <linux/printk.h>
4519a809afSAndrea Arcangeli #include <linux/userfaultfd_k.h>
46d977d56cSKonstantin Khlebnikov #include <linux/moduleparam.h>
4762b5f7d0SDave Hansen #include <linux/pkeys.h>
4821292580SAndrea Arcangeli #include <linux/oom.h>
4904f5866eSAndrea Arcangeli #include <linux/sched/mm.h>
501da177e4SLinus Torvalds 
517c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
521da177e4SLinus Torvalds #include <asm/cacheflush.h>
531da177e4SLinus Torvalds #include <asm/tlb.h>
54d6dd61c8SJeremy Fitzhardinge #include <asm/mmu_context.h>
551da177e4SLinus Torvalds 
56df529cabSJaewon Kim #define CREATE_TRACE_POINTS
57df529cabSJaewon Kim #include <trace/events/mmap.h>
58df529cabSJaewon Kim 
5942b77728SJan Beulich #include "internal.h"
6042b77728SJan Beulich 
613a459756SKirill Korotaev #ifndef arch_mmap_check
623a459756SKirill Korotaev #define arch_mmap_check(addr, len, flags)	(0)
633a459756SKirill Korotaev #endif
643a459756SKirill Korotaev 
65d07e2259SDaniel Cashman #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
66d07e2259SDaniel Cashman const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
67d07e2259SDaniel Cashman const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
68d07e2259SDaniel Cashman int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
69d07e2259SDaniel Cashman #endif
70d07e2259SDaniel Cashman #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
71d07e2259SDaniel Cashman const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
72d07e2259SDaniel Cashman const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
73d07e2259SDaniel Cashman int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
74d07e2259SDaniel Cashman #endif
75d07e2259SDaniel Cashman 
76f4fcd558SKonstantin Khlebnikov static bool ignore_rlimit_data;
77d977d56cSKonstantin Khlebnikov core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
78d07e2259SDaniel Cashman 
79e0da382cSHugh Dickins static void unmap_region(struct mm_struct *mm,
80e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
81e0da382cSHugh Dickins 		unsigned long start, unsigned long end);
82e0da382cSHugh Dickins 
8364e45507SPeter Feiner static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
8464e45507SPeter Feiner {
8564e45507SPeter Feiner 	return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
8664e45507SPeter Feiner }
8764e45507SPeter Feiner 
8864e45507SPeter Feiner /* Update vma->vm_page_prot to reflect vma->vm_flags. */
8964e45507SPeter Feiner void vma_set_page_prot(struct vm_area_struct *vma)
9064e45507SPeter Feiner {
9164e45507SPeter Feiner 	unsigned long vm_flags = vma->vm_flags;
926d2329f8SAndrea Arcangeli 	pgprot_t vm_page_prot;
9364e45507SPeter Feiner 
946d2329f8SAndrea Arcangeli 	vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
956d2329f8SAndrea Arcangeli 	if (vma_wants_writenotify(vma, vm_page_prot)) {
9664e45507SPeter Feiner 		vm_flags &= ~VM_SHARED;
976d2329f8SAndrea Arcangeli 		vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
9864e45507SPeter Feiner 	}
99c1e8d7c6SMichel Lespinasse 	/* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
1006d2329f8SAndrea Arcangeli 	WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
10164e45507SPeter Feiner }
10264e45507SPeter Feiner 
1031da177e4SLinus Torvalds /*
104c8c06efaSDavidlohr Bueso  * Requires inode->i_mapping->i_mmap_rwsem
1051da177e4SLinus Torvalds  */
1061da177e4SLinus Torvalds static void __remove_shared_vm_struct(struct vm_area_struct *vma,
1071da177e4SLinus Torvalds 		struct file *file, struct address_space *mapping)
1081da177e4SLinus Torvalds {
1091da177e4SLinus Torvalds 	if (vma->vm_flags & VM_SHARED)
1104bb5f5d9SDavid Herrmann 		mapping_unmap_writable(mapping);
1111da177e4SLinus Torvalds 
1121da177e4SLinus Torvalds 	flush_dcache_mmap_lock(mapping);
1136b2dbba8SMichel Lespinasse 	vma_interval_tree_remove(vma, &mapping->i_mmap);
1141da177e4SLinus Torvalds 	flush_dcache_mmap_unlock(mapping);
1151da177e4SLinus Torvalds }
1161da177e4SLinus Torvalds 
1171da177e4SLinus Torvalds /*
1186b2dbba8SMichel Lespinasse  * Unlink a file-based vm structure from its interval tree, to hide
119a8fb5618SHugh Dickins  * vma from rmap and vmtruncate before freeing its page tables.
1201da177e4SLinus Torvalds  */
121a8fb5618SHugh Dickins void unlink_file_vma(struct vm_area_struct *vma)
1221da177e4SLinus Torvalds {
1231da177e4SLinus Torvalds 	struct file *file = vma->vm_file;
1241da177e4SLinus Torvalds 
1251da177e4SLinus Torvalds 	if (file) {
1261da177e4SLinus Torvalds 		struct address_space *mapping = file->f_mapping;
12783cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
1281da177e4SLinus Torvalds 		__remove_shared_vm_struct(vma, file, mapping);
12983cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
1301da177e4SLinus Torvalds 	}
131a8fb5618SHugh Dickins }
132a8fb5618SHugh Dickins 
133a8fb5618SHugh Dickins /*
134a8fb5618SHugh Dickins  * Close a vm structure and free it, returning the next.
135a8fb5618SHugh Dickins  */
136a8fb5618SHugh Dickins static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
137a8fb5618SHugh Dickins {
138a8fb5618SHugh Dickins 	struct vm_area_struct *next = vma->vm_next;
139a8fb5618SHugh Dickins 
140a8fb5618SHugh Dickins 	might_sleep();
1411da177e4SLinus Torvalds 	if (vma->vm_ops && vma->vm_ops->close)
1421da177e4SLinus Torvalds 		vma->vm_ops->close(vma);
143e9714acfSKonstantin Khlebnikov 	if (vma->vm_file)
144a8fb5618SHugh Dickins 		fput(vma->vm_file);
145f0be3d32SLee Schermerhorn 	mpol_put(vma_policy(vma));
1463928d4f5SLinus Torvalds 	vm_area_free(vma);
147a8fb5618SHugh Dickins 	return next;
1481da177e4SLinus Torvalds }
1491da177e4SLinus Torvalds 
150*2e7ce7d3SLiam R. Howlett /*
151*2e7ce7d3SLiam R. Howlett  * check_brk_limits() - Use platform specific check of range & verify mlock
152*2e7ce7d3SLiam R. Howlett  * limits.
153*2e7ce7d3SLiam R. Howlett  * @addr: The address to check
154*2e7ce7d3SLiam R. Howlett  * @len: The size of increase.
155*2e7ce7d3SLiam R. Howlett  *
156*2e7ce7d3SLiam R. Howlett  * Return: 0 on success.
157*2e7ce7d3SLiam R. Howlett  */
158*2e7ce7d3SLiam R. Howlett static int check_brk_limits(unsigned long addr, unsigned long len)
159*2e7ce7d3SLiam R. Howlett {
160*2e7ce7d3SLiam R. Howlett 	unsigned long mapped_addr;
161*2e7ce7d3SLiam R. Howlett 
162*2e7ce7d3SLiam R. Howlett 	mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
163*2e7ce7d3SLiam R. Howlett 	if (IS_ERR_VALUE(mapped_addr))
164*2e7ce7d3SLiam R. Howlett 		return mapped_addr;
165*2e7ce7d3SLiam R. Howlett 
166*2e7ce7d3SLiam R. Howlett 	return mlock_future_check(current->mm, current->mm->def_flags, len);
167*2e7ce7d3SLiam R. Howlett }
168*2e7ce7d3SLiam R. Howlett static int do_brk_munmap(struct ma_state *mas, struct vm_area_struct *vma,
169*2e7ce7d3SLiam R. Howlett 			 unsigned long newbrk, unsigned long oldbrk,
170bb177a73SMichal Hocko 			 struct list_head *uf);
171*2e7ce7d3SLiam R. Howlett static int do_brk_flags(struct ma_state *mas, struct vm_area_struct *brkvma,
172*2e7ce7d3SLiam R. Howlett 			unsigned long addr, unsigned long request,
173*2e7ce7d3SLiam R. Howlett 			unsigned long flags);
1746a6160a7SHeiko Carstens SYSCALL_DEFINE1(brk, unsigned long, brk)
1751da177e4SLinus Torvalds {
1769bc8039eSYang Shi 	unsigned long newbrk, oldbrk, origbrk;
1771da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
178*2e7ce7d3SLiam R. Howlett 	struct vm_area_struct *brkvma, *next = NULL;
179a5b4592cSJiri Kosina 	unsigned long min_brk;
180128557ffSMichel Lespinasse 	bool populate;
1819bc8039eSYang Shi 	bool downgraded = false;
182897ab3e0SMike Rapoport 	LIST_HEAD(uf);
183*2e7ce7d3SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
1841da177e4SLinus Torvalds 
185d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
186dc0ef0dfSMichal Hocko 		return -EINTR;
1871da177e4SLinus Torvalds 
1889bc8039eSYang Shi 	origbrk = mm->brk;
1899bc8039eSYang Shi 
190a5b4592cSJiri Kosina #ifdef CONFIG_COMPAT_BRK
1915520e894SJiri Kosina 	/*
1925520e894SJiri Kosina 	 * CONFIG_COMPAT_BRK can still be overridden by setting
1935520e894SJiri Kosina 	 * randomize_va_space to 2, which will still cause mm->start_brk
1945520e894SJiri Kosina 	 * to be arbitrarily shifted
1955520e894SJiri Kosina 	 */
1964471a675SJiri Kosina 	if (current->brk_randomized)
1975520e894SJiri Kosina 		min_brk = mm->start_brk;
1985520e894SJiri Kosina 	else
1995520e894SJiri Kosina 		min_brk = mm->end_data;
200a5b4592cSJiri Kosina #else
201a5b4592cSJiri Kosina 	min_brk = mm->start_brk;
202a5b4592cSJiri Kosina #endif
203a5b4592cSJiri Kosina 	if (brk < min_brk)
2041da177e4SLinus Torvalds 		goto out;
2051e624196SRam Gupta 
2061e624196SRam Gupta 	/*
2071e624196SRam Gupta 	 * Check against rlimit here. If this check is done later after the test
2081e624196SRam Gupta 	 * of oldbrk with newbrk then it can escape the test and let the data
2091e624196SRam Gupta 	 * segment grow beyond its set limit the in case where the limit is
2101e624196SRam Gupta 	 * not page aligned -Ram Gupta
2111e624196SRam Gupta 	 */
2128764b338SCyrill Gorcunov 	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
2138764b338SCyrill Gorcunov 			      mm->end_data, mm->start_data))
2141e624196SRam Gupta 		goto out;
2151e624196SRam Gupta 
2161da177e4SLinus Torvalds 	newbrk = PAGE_ALIGN(brk);
2171da177e4SLinus Torvalds 	oldbrk = PAGE_ALIGN(mm->brk);
2189bc8039eSYang Shi 	if (oldbrk == newbrk) {
2199bc8039eSYang Shi 		mm->brk = brk;
2209bc8039eSYang Shi 		goto success;
2219bc8039eSYang Shi 	}
2221da177e4SLinus Torvalds 
2239bc8039eSYang Shi 	/*
2249bc8039eSYang Shi 	 * Always allow shrinking brk.
225*2e7ce7d3SLiam R. Howlett 	 * do_brk_munmap() may downgrade mmap_lock to read.
2269bc8039eSYang Shi 	 */
2271da177e4SLinus Torvalds 	if (brk <= mm->brk) {
2289bc8039eSYang Shi 		int ret;
2299bc8039eSYang Shi 
230*2e7ce7d3SLiam R. Howlett 		/* Search one past newbrk */
231*2e7ce7d3SLiam R. Howlett 		mas_set(&mas, newbrk);
232*2e7ce7d3SLiam R. Howlett 		brkvma = mas_find(&mas, oldbrk);
233*2e7ce7d3SLiam R. Howlett 		BUG_ON(brkvma == NULL);
234*2e7ce7d3SLiam R. Howlett 		if (brkvma->vm_start >= oldbrk)
235*2e7ce7d3SLiam R. Howlett 			goto out; /* mapping intersects with an existing non-brk vma. */
2369bc8039eSYang Shi 		/*
237*2e7ce7d3SLiam R. Howlett 		 * mm->brk must be protected by write mmap_lock.
238*2e7ce7d3SLiam R. Howlett 		 * do_brk_munmap() may downgrade the lock,  so update it
239*2e7ce7d3SLiam R. Howlett 		 * before calling do_brk_munmap().
2409bc8039eSYang Shi 		 */
2419bc8039eSYang Shi 		mm->brk = brk;
242*2e7ce7d3SLiam R. Howlett 		mas.last = oldbrk - 1;
243*2e7ce7d3SLiam R. Howlett 		ret = do_brk_munmap(&mas, brkvma, newbrk, oldbrk, &uf);
244*2e7ce7d3SLiam R. Howlett 		if (ret == 1)  {
245*2e7ce7d3SLiam R. Howlett 			downgraded = true;
246*2e7ce7d3SLiam R. Howlett 			goto success;
247*2e7ce7d3SLiam R. Howlett 		} else if (!ret)
248*2e7ce7d3SLiam R. Howlett 			goto success;
249*2e7ce7d3SLiam R. Howlett 
2509bc8039eSYang Shi 		mm->brk = origbrk;
2511da177e4SLinus Torvalds 		goto out;
2521da177e4SLinus Torvalds 	}
2531da177e4SLinus Torvalds 
254*2e7ce7d3SLiam R. Howlett 	if (check_brk_limits(oldbrk, newbrk - oldbrk))
255*2e7ce7d3SLiam R. Howlett 		goto out;
256*2e7ce7d3SLiam R. Howlett 
257*2e7ce7d3SLiam R. Howlett 	/*
258*2e7ce7d3SLiam R. Howlett 	 * Only check if the next VMA is within the stack_guard_gap of the
259*2e7ce7d3SLiam R. Howlett 	 * expansion area
260*2e7ce7d3SLiam R. Howlett 	 */
261*2e7ce7d3SLiam R. Howlett 	mas_set(&mas, oldbrk);
262*2e7ce7d3SLiam R. Howlett 	next = mas_find(&mas, newbrk - 1 + PAGE_SIZE + stack_guard_gap);
2631be7107fSHugh Dickins 	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
2641da177e4SLinus Torvalds 		goto out;
2651da177e4SLinus Torvalds 
266*2e7ce7d3SLiam R. Howlett 	brkvma = mas_prev(&mas, mm->start_brk);
2671da177e4SLinus Torvalds 	/* Ok, looks good - let it rip. */
268*2e7ce7d3SLiam R. Howlett 	if (do_brk_flags(&mas, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
2691da177e4SLinus Torvalds 		goto out;
270*2e7ce7d3SLiam R. Howlett 
2711da177e4SLinus Torvalds 	mm->brk = brk;
2729bc8039eSYang Shi 
2739bc8039eSYang Shi success:
274128557ffSMichel Lespinasse 	populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
2759bc8039eSYang Shi 	if (downgraded)
276d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
2779bc8039eSYang Shi 	else
278d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
279897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
280128557ffSMichel Lespinasse 	if (populate)
281128557ffSMichel Lespinasse 		mm_populate(oldbrk, newbrk - oldbrk);
282128557ffSMichel Lespinasse 	return brk;
283128557ffSMichel Lespinasse 
2841da177e4SLinus Torvalds out:
285d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
286b7204006SAdrian Huang 	return origbrk;
2871da177e4SLinus Torvalds }
2881da177e4SLinus Torvalds 
289d4af56c5SLiam R. Howlett #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
290d4af56c5SLiam R. Howlett extern void mt_validate(struct maple_tree *mt);
291d4af56c5SLiam R. Howlett extern void mt_dump(const struct maple_tree *mt);
2921da177e4SLinus Torvalds 
293d4af56c5SLiam R. Howlett /* Validate the maple tree */
294d4af56c5SLiam R. Howlett static void validate_mm_mt(struct mm_struct *mm)
295d4af56c5SLiam R. Howlett {
296d4af56c5SLiam R. Howlett 	struct maple_tree *mt = &mm->mm_mt;
297d4af56c5SLiam R. Howlett 	struct vm_area_struct *vma_mt, *vma = mm->mmap;
298d4af56c5SLiam R. Howlett 
299d4af56c5SLiam R. Howlett 	MA_STATE(mas, mt, 0, 0);
300d4af56c5SLiam R. Howlett 
301d4af56c5SLiam R. Howlett 	mt_validate(&mm->mm_mt);
302d4af56c5SLiam R. Howlett 	mas_for_each(&mas, vma_mt, ULONG_MAX) {
303d4af56c5SLiam R. Howlett 		if (xa_is_zero(vma_mt))
304d4af56c5SLiam R. Howlett 			continue;
305d4af56c5SLiam R. Howlett 
306d4af56c5SLiam R. Howlett 		if (!vma)
307d4af56c5SLiam R. Howlett 			break;
308d4af56c5SLiam R. Howlett 
309d4af56c5SLiam R. Howlett 		if ((vma != vma_mt) ||
310d4af56c5SLiam R. Howlett 		    (vma->vm_start != vma_mt->vm_start) ||
311d4af56c5SLiam R. Howlett 		    (vma->vm_end != vma_mt->vm_end) ||
312d4af56c5SLiam R. Howlett 		    (vma->vm_start != mas.index) ||
313d4af56c5SLiam R. Howlett 		    (vma->vm_end - 1 != mas.last)) {
314d4af56c5SLiam R. Howlett 			pr_emerg("issue in %s\n", current->comm);
315d4af56c5SLiam R. Howlett 			dump_stack();
316d4af56c5SLiam R. Howlett 			dump_vma(vma_mt);
317524e00b3SLiam R. Howlett 			pr_emerg("and vm_next\n");
318d4af56c5SLiam R. Howlett 			dump_vma(vma->vm_next);
319d4af56c5SLiam R. Howlett 			pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
320d4af56c5SLiam R. Howlett 				 mas.index, mas.last);
321d4af56c5SLiam R. Howlett 			pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
322d4af56c5SLiam R. Howlett 				 vma_mt->vm_start, vma_mt->vm_end);
323524e00b3SLiam R. Howlett 			if (vma->vm_prev) {
324524e00b3SLiam R. Howlett 				pr_emerg("ll prev: %p %lu - %lu\n",
325524e00b3SLiam R. Howlett 					 vma->vm_prev, vma->vm_prev->vm_start,
326524e00b3SLiam R. Howlett 					 vma->vm_prev->vm_end);
327524e00b3SLiam R. Howlett 			}
328524e00b3SLiam R. Howlett 			pr_emerg("ll vma: %p %lu - %lu\n", vma,
329d4af56c5SLiam R. Howlett 				 vma->vm_start, vma->vm_end);
330524e00b3SLiam R. Howlett 			if (vma->vm_next) {
331524e00b3SLiam R. Howlett 				pr_emerg("ll next: %p %lu - %lu\n",
332524e00b3SLiam R. Howlett 					 vma->vm_next, vma->vm_next->vm_start,
333524e00b3SLiam R. Howlett 					 vma->vm_next->vm_end);
334524e00b3SLiam R. Howlett 			}
335d4af56c5SLiam R. Howlett 
336d4af56c5SLiam R. Howlett 			mt_dump(mas.tree);
337d4af56c5SLiam R. Howlett 			if (vma_mt->vm_end != mas.last + 1) {
338d4af56c5SLiam R. Howlett 				pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
339d4af56c5SLiam R. Howlett 						mm, vma_mt->vm_start, vma_mt->vm_end,
340d4af56c5SLiam R. Howlett 						mas.index, mas.last);
341d4af56c5SLiam R. Howlett 				mt_dump(mas.tree);
342d4af56c5SLiam R. Howlett 			}
343d4af56c5SLiam R. Howlett 			VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
344d4af56c5SLiam R. Howlett 			if (vma_mt->vm_start != mas.index) {
345d4af56c5SLiam R. Howlett 				pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
346d4af56c5SLiam R. Howlett 						mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
347d4af56c5SLiam R. Howlett 				mt_dump(mas.tree);
348d4af56c5SLiam R. Howlett 			}
349d4af56c5SLiam R. Howlett 			VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
350d4af56c5SLiam R. Howlett 		}
351d4af56c5SLiam R. Howlett 		VM_BUG_ON(vma != vma_mt);
352d4af56c5SLiam R. Howlett 		vma = vma->vm_next;
353d4af56c5SLiam R. Howlett 
354d4af56c5SLiam R. Howlett 	}
355d4af56c5SLiam R. Howlett 	VM_BUG_ON(vma);
356d4af56c5SLiam R. Howlett }
3571da177e4SLinus Torvalds 
358eafd4dc4SRashika Kheria static void validate_mm(struct mm_struct *mm)
3591da177e4SLinus Torvalds {
3601da177e4SLinus Torvalds 	int bug = 0;
3611da177e4SLinus Torvalds 	int i = 0;
3625a0768f6SMichel Lespinasse 	unsigned long highest_address = 0;
363ed8ea815SMichel Lespinasse 	struct vm_area_struct *vma = mm->mmap;
364ff26f70fSAndrew Morton 
365524e00b3SLiam R. Howlett 	validate_mm_mt(mm);
366524e00b3SLiam R. Howlett 
367ed8ea815SMichel Lespinasse 	while (vma) {
368524e00b3SLiam R. Howlett #ifdef CONFIG_DEBUG_VM_RB
36912352d3cSKonstantin Khlebnikov 		struct anon_vma *anon_vma = vma->anon_vma;
370ed8ea815SMichel Lespinasse 		struct anon_vma_chain *avc;
371ff26f70fSAndrew Morton 
37212352d3cSKonstantin Khlebnikov 		if (anon_vma) {
37312352d3cSKonstantin Khlebnikov 			anon_vma_lock_read(anon_vma);
374ed8ea815SMichel Lespinasse 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
375ed8ea815SMichel Lespinasse 				anon_vma_interval_tree_verify(avc);
37612352d3cSKonstantin Khlebnikov 			anon_vma_unlock_read(anon_vma);
37712352d3cSKonstantin Khlebnikov 		}
378524e00b3SLiam R. Howlett #endif
37912352d3cSKonstantin Khlebnikov 
3801be7107fSHugh Dickins 		highest_address = vm_end_gap(vma);
381ed8ea815SMichel Lespinasse 		vma = vma->vm_next;
3821da177e4SLinus Torvalds 		i++;
3831da177e4SLinus Torvalds 	}
3845a0768f6SMichel Lespinasse 	if (i != mm->map_count) {
3858542bdfcSSasha Levin 		pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
3865a0768f6SMichel Lespinasse 		bug = 1;
3875a0768f6SMichel Lespinasse 	}
3885a0768f6SMichel Lespinasse 	if (highest_address != mm->highest_vm_end) {
3898542bdfcSSasha Levin 		pr_emerg("mm->highest_vm_end %lx, found %lx\n",
3905a0768f6SMichel Lespinasse 			  mm->highest_vm_end, highest_address);
3915a0768f6SMichel Lespinasse 		bug = 1;
3925a0768f6SMichel Lespinasse 	}
39396dad67fSSasha Levin 	VM_BUG_ON_MM(bug, mm);
3941da177e4SLinus Torvalds }
395524e00b3SLiam R. Howlett 
396524e00b3SLiam R. Howlett #else /* !CONFIG_DEBUG_VM_MAPLE_TREE */
397d4af56c5SLiam R. Howlett #define validate_mm_mt(root) do { } while (0)
3981da177e4SLinus Torvalds #define validate_mm(mm) do { } while (0)
399524e00b3SLiam R. Howlett #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
400d3737187SMichel Lespinasse 
401bf181b9fSMichel Lespinasse /*
402bf181b9fSMichel Lespinasse  * vma has some anon_vma assigned, and is already inserted on that
403bf181b9fSMichel Lespinasse  * anon_vma's interval trees.
404bf181b9fSMichel Lespinasse  *
405bf181b9fSMichel Lespinasse  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
406bf181b9fSMichel Lespinasse  * vma must be removed from the anon_vma's interval trees using
407bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_pre_update_vma().
408bf181b9fSMichel Lespinasse  *
409bf181b9fSMichel Lespinasse  * After the update, the vma will be reinserted using
410bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_post_update_vma().
411bf181b9fSMichel Lespinasse  *
412c1e8d7c6SMichel Lespinasse  * The entire update must be protected by exclusive mmap_lock and by
413bf181b9fSMichel Lespinasse  * the root anon_vma's mutex.
414bf181b9fSMichel Lespinasse  */
415bf181b9fSMichel Lespinasse static inline void
416bf181b9fSMichel Lespinasse anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
417bf181b9fSMichel Lespinasse {
418bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
419bf181b9fSMichel Lespinasse 
420bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
421bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
422bf181b9fSMichel Lespinasse }
423bf181b9fSMichel Lespinasse 
424bf181b9fSMichel Lespinasse static inline void
425bf181b9fSMichel Lespinasse anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
426bf181b9fSMichel Lespinasse {
427bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
428bf181b9fSMichel Lespinasse 
429bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
430bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
431bf181b9fSMichel Lespinasse }
432bf181b9fSMichel Lespinasse 
433524e00b3SLiam R. Howlett /*
434524e00b3SLiam R. Howlett  * range_has_overlap() - Check the @start - @end range for overlapping VMAs and
435524e00b3SLiam R. Howlett  * sets up a pointer to the previous VMA
436524e00b3SLiam R. Howlett  * @mm: the mm struct
437524e00b3SLiam R. Howlett  * @start: the start address of the range
438524e00b3SLiam R. Howlett  * @end: the end address of the range
439524e00b3SLiam R. Howlett  * @pprev: the pointer to the pointer of the previous VMA
440524e00b3SLiam R. Howlett  *
441524e00b3SLiam R. Howlett  * Returns: True if there is an overlapping VMA, false otherwise
442524e00b3SLiam R. Howlett  */
443524e00b3SLiam R. Howlett static inline
444524e00b3SLiam R. Howlett bool range_has_overlap(struct mm_struct *mm, unsigned long start,
445524e00b3SLiam R. Howlett 		       unsigned long end, struct vm_area_struct **pprev)
4461da177e4SLinus Torvalds {
447524e00b3SLiam R. Howlett 	struct vm_area_struct *existing;
4481da177e4SLinus Torvalds 
449524e00b3SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, start, start);
450524e00b3SLiam R. Howlett 	existing = mas_find(&mas, end - 1);
451524e00b3SLiam R. Howlett 	*pprev = mas_prev(&mas, 0);
452524e00b3SLiam R. Howlett 	return existing ? true : false;
4531da177e4SLinus Torvalds }
4541da177e4SLinus Torvalds 
4553903b55aSLiam R. Howlett /*
456f39af059SMatthew Wilcox (Oracle)  * __vma_next() - Get the next VMA.
4573903b55aSLiam R. Howlett  * @mm: The mm_struct.
4583903b55aSLiam R. Howlett  * @vma: The current vma.
4593903b55aSLiam R. Howlett  *
4603903b55aSLiam R. Howlett  * If @vma is NULL, return the first vma in the mm.
4613903b55aSLiam R. Howlett  *
4623903b55aSLiam R. Howlett  * Returns: The next VMA after @vma.
4633903b55aSLiam R. Howlett  */
464f39af059SMatthew Wilcox (Oracle) static inline struct vm_area_struct *__vma_next(struct mm_struct *mm,
4653903b55aSLiam R. Howlett 					 struct vm_area_struct *vma)
4663903b55aSLiam R. Howlett {
4673903b55aSLiam R. Howlett 	if (!vma)
4683903b55aSLiam R. Howlett 		return mm->mmap;
4693903b55aSLiam R. Howlett 
4703903b55aSLiam R. Howlett 	return vma->vm_next;
4713903b55aSLiam R. Howlett }
472fb8090b6SLiam R. Howlett 
473fb8090b6SLiam R. Howlett /*
474fb8090b6SLiam R. Howlett  * munmap_vma_range() - munmap VMAs that overlap a range.
475fb8090b6SLiam R. Howlett  * @mm: The mm struct
476fb8090b6SLiam R. Howlett  * @start: The start of the range.
477fb8090b6SLiam R. Howlett  * @len: The length of the range.
478fb8090b6SLiam R. Howlett  * @pprev: pointer to the pointer that will be set to previous vm_area_struct
479fb8090b6SLiam R. Howlett  *
480fb8090b6SLiam R. Howlett  * Find all the vm_area_struct that overlap from @start to
481fb8090b6SLiam R. Howlett  * @end and munmap them.  Set @pprev to the previous vm_area_struct.
482fb8090b6SLiam R. Howlett  *
483fb8090b6SLiam R. Howlett  * Returns: -ENOMEM on munmap failure or 0 on success.
484fb8090b6SLiam R. Howlett  */
485fb8090b6SLiam R. Howlett static inline int
486fb8090b6SLiam R. Howlett munmap_vma_range(struct mm_struct *mm, unsigned long start, unsigned long len,
487524e00b3SLiam R. Howlett 		 struct vm_area_struct **pprev, struct list_head *uf)
488fb8090b6SLiam R. Howlett {
489524e00b3SLiam R. Howlett 	while (range_has_overlap(mm, start, start + len, pprev))
490fb8090b6SLiam R. Howlett 		if (do_munmap(mm, start, len, uf))
491fb8090b6SLiam R. Howlett 			return -ENOMEM;
492fb8090b6SLiam R. Howlett 	return 0;
493fb8090b6SLiam R. Howlett }
4942e3af1dbSMatthew Wilcox (Oracle) 
495e8420a8eSCyril Hrubis static unsigned long count_vma_pages_range(struct mm_struct *mm,
496e8420a8eSCyril Hrubis 		unsigned long addr, unsigned long end)
497e8420a8eSCyril Hrubis {
4982e3af1dbSMatthew Wilcox (Oracle) 	VMA_ITERATOR(vmi, mm, addr);
499e8420a8eSCyril Hrubis 	struct vm_area_struct *vma;
5002e3af1dbSMatthew Wilcox (Oracle) 	unsigned long nr_pages = 0;
501e8420a8eSCyril Hrubis 
5022e3af1dbSMatthew Wilcox (Oracle) 	for_each_vma_range(vmi, vma, end) {
5032e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_start = max(addr, vma->vm_start);
5042e3af1dbSMatthew Wilcox (Oracle) 		unsigned long vm_end = min(end, vma->vm_end);
505e8420a8eSCyril Hrubis 
5062e3af1dbSMatthew Wilcox (Oracle) 		nr_pages += PHYS_PFN(vm_end - vm_start);
507e8420a8eSCyril Hrubis 	}
508e8420a8eSCyril Hrubis 
509e8420a8eSCyril Hrubis 	return nr_pages;
510e8420a8eSCyril Hrubis }
511e8420a8eSCyril Hrubis 
512cb8f488cSDenys Vlasenko static void __vma_link_file(struct vm_area_struct *vma)
5131da177e4SLinus Torvalds {
5141da177e4SLinus Torvalds 	struct file *file;
5151da177e4SLinus Torvalds 
5161da177e4SLinus Torvalds 	file = vma->vm_file;
5171da177e4SLinus Torvalds 	if (file) {
5181da177e4SLinus Torvalds 		struct address_space *mapping = file->f_mapping;
5191da177e4SLinus Torvalds 
5201da177e4SLinus Torvalds 		if (vma->vm_flags & VM_SHARED)
521cf508b58SMiaohe Lin 			mapping_allow_writable(mapping);
5221da177e4SLinus Torvalds 
5231da177e4SLinus Torvalds 		flush_dcache_mmap_lock(mapping);
5246b2dbba8SMichel Lespinasse 		vma_interval_tree_insert(vma, &mapping->i_mmap);
5251da177e4SLinus Torvalds 		flush_dcache_mmap_unlock(mapping);
5261da177e4SLinus Torvalds 	}
5271da177e4SLinus Torvalds }
5281da177e4SLinus Torvalds 
529d4af56c5SLiam R. Howlett /*
530d4af56c5SLiam R. Howlett  * vma_mas_store() - Store a VMA in the maple tree.
531d4af56c5SLiam R. Howlett  * @vma: The vm_area_struct
532d4af56c5SLiam R. Howlett  * @mas: The maple state
533d4af56c5SLiam R. Howlett  *
534d4af56c5SLiam R. Howlett  * Efficient way to store a VMA in the maple tree when the @mas has already
535d4af56c5SLiam R. Howlett  * walked to the correct location.
536d4af56c5SLiam R. Howlett  *
537d4af56c5SLiam R. Howlett  * Note: the end address is inclusive in the maple tree.
538d4af56c5SLiam R. Howlett  */
539d4af56c5SLiam R. Howlett void vma_mas_store(struct vm_area_struct *vma, struct ma_state *mas)
540d4af56c5SLiam R. Howlett {
541d4af56c5SLiam R. Howlett 	trace_vma_store(mas->tree, vma);
542d4af56c5SLiam R. Howlett 	mas_set_range(mas, vma->vm_start, vma->vm_end - 1);
543d4af56c5SLiam R. Howlett 	mas_store_prealloc(mas, vma);
544d4af56c5SLiam R. Howlett }
545d4af56c5SLiam R. Howlett 
546d4af56c5SLiam R. Howlett /*
547d4af56c5SLiam R. Howlett  * vma_mas_remove() - Remove a VMA from the maple tree.
548d4af56c5SLiam R. Howlett  * @vma: The vm_area_struct
549d4af56c5SLiam R. Howlett  * @mas: The maple state
550d4af56c5SLiam R. Howlett  *
551d4af56c5SLiam R. Howlett  * Efficient way to remove a VMA from the maple tree when the @mas has already
552d4af56c5SLiam R. Howlett  * been established and points to the correct location.
553d4af56c5SLiam R. Howlett  * Note: the end address is inclusive in the maple tree.
554d4af56c5SLiam R. Howlett  */
555d4af56c5SLiam R. Howlett void vma_mas_remove(struct vm_area_struct *vma, struct ma_state *mas)
556d4af56c5SLiam R. Howlett {
557d4af56c5SLiam R. Howlett 	trace_vma_mas_szero(mas->tree, vma->vm_start, vma->vm_end - 1);
558d4af56c5SLiam R. Howlett 	mas->index = vma->vm_start;
559d4af56c5SLiam R. Howlett 	mas->last = vma->vm_end - 1;
560d4af56c5SLiam R. Howlett 	mas_store_prealloc(mas, NULL);
561d4af56c5SLiam R. Howlett }
562d4af56c5SLiam R. Howlett 
563d4af56c5SLiam R. Howlett /*
564d4af56c5SLiam R. Howlett  * vma_mas_szero() - Set a given range to zero.  Used when modifying a
565d4af56c5SLiam R. Howlett  * vm_area_struct start or end.
566d4af56c5SLiam R. Howlett  *
567d4af56c5SLiam R. Howlett  * @mm: The struct_mm
568d4af56c5SLiam R. Howlett  * @start: The start address to zero
569d4af56c5SLiam R. Howlett  * @end: The end address to zero.
570d4af56c5SLiam R. Howlett  */
571d4af56c5SLiam R. Howlett static inline void vma_mas_szero(struct ma_state *mas, unsigned long start,
572d4af56c5SLiam R. Howlett 				unsigned long end)
573d4af56c5SLiam R. Howlett {
574d4af56c5SLiam R. Howlett 	trace_vma_mas_szero(mas->tree, start, end - 1);
575d4af56c5SLiam R. Howlett 	mas_set_range(mas, start, end - 1);
576d4af56c5SLiam R. Howlett 	mas_store_prealloc(mas, NULL);
577d4af56c5SLiam R. Howlett }
578d4af56c5SLiam R. Howlett 
579d4af56c5SLiam R. Howlett static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
580524e00b3SLiam R. Howlett 			struct vm_area_struct *prev)
5811da177e4SLinus Torvalds {
582d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
5831da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
5841da177e4SLinus Torvalds 
585d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
586d4af56c5SLiam R. Howlett 		return -ENOMEM;
587d4af56c5SLiam R. Howlett 
58864ac4940SHuang Shijie 	if (vma->vm_file) {
5891da177e4SLinus Torvalds 		mapping = vma->vm_file->f_mapping;
59083cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
59164ac4940SHuang Shijie 	}
5921da177e4SLinus Torvalds 
593d4af56c5SLiam R. Howlett 	vma_mas_store(vma, &mas);
594524e00b3SLiam R. Howlett 	__vma_link_list(mm, vma, prev);
5951da177e4SLinus Torvalds 	__vma_link_file(vma);
5961da177e4SLinus Torvalds 
5971da177e4SLinus Torvalds 	if (mapping)
59883cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
5991da177e4SLinus Torvalds 
6001da177e4SLinus Torvalds 	mm->map_count++;
6011da177e4SLinus Torvalds 	validate_mm(mm);
602d4af56c5SLiam R. Howlett 	return 0;
6031da177e4SLinus Torvalds }
6041da177e4SLinus Torvalds 
6051da177e4SLinus Torvalds /*
60688f6b4c3SKautuk Consul  * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
607524e00b3SLiam R. Howlett  * mm's list and the mm tree.  It has already been inserted into the interval tree.
6081da177e4SLinus Torvalds  */
609d4af56c5SLiam R. Howlett static void __insert_vm_struct(struct mm_struct *mm, struct ma_state *mas,
6103b0e81a1SLiam R. Howlett 		struct vm_area_struct *vma, unsigned long location)
6111da177e4SLinus Torvalds {
6126597d783SHugh Dickins 	struct vm_area_struct *prev;
6131da177e4SLinus Torvalds 
6143b0e81a1SLiam R. Howlett 	mas_set(mas, location);
615524e00b3SLiam R. Howlett 	prev = mas_prev(mas, 0);
616d4af56c5SLiam R. Howlett 	vma_mas_store(vma, mas);
617d4af56c5SLiam R. Howlett 	__vma_link_list(mm, vma, prev);
6181da177e4SLinus Torvalds 	mm->map_count++;
6191da177e4SLinus Torvalds }
6201da177e4SLinus Torvalds 
6211da177e4SLinus Torvalds /*
6221da177e4SLinus Torvalds  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
6231da177e4SLinus Torvalds  * is already present in an i_mmap tree without adjusting the tree.
6241da177e4SLinus Torvalds  * The following helper function should be used when such adjustments
6251da177e4SLinus Torvalds  * are necessary.  The "insert" vma (if any) is to be inserted
6261da177e4SLinus Torvalds  * before we drop the necessary locks.
6271da177e4SLinus Torvalds  */
628e86f15eeSAndrea Arcangeli int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
629e86f15eeSAndrea Arcangeli 	unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
630e86f15eeSAndrea Arcangeli 	struct vm_area_struct *expand)
6311da177e4SLinus Torvalds {
6321da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
633524e00b3SLiam R. Howlett 	struct vm_area_struct *next_next, *next = find_vma(mm, vma->vm_end);
634524e00b3SLiam R. Howlett 	struct vm_area_struct *orig_vma = vma;
6351da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
636f808c13fSDavidlohr Bueso 	struct rb_root_cached *root = NULL;
637012f1800SRik van Riel 	struct anon_vma *anon_vma = NULL;
6381da177e4SLinus Torvalds 	struct file *file = vma->vm_file;
639524e00b3SLiam R. Howlett 	bool vma_changed = false;
6401da177e4SLinus Torvalds 	long adjust_next = 0;
6411da177e4SLinus Torvalds 	int remove_next = 0;
642d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
643734537c9SKirill A. Shutemov 	struct vm_area_struct *exporter = NULL, *importer = NULL;
6443b0e81a1SLiam R. Howlett 	unsigned long ll_prev = vma->vm_start; /* linked list prev. */
645287d97acSLinus Torvalds 
646d4af56c5SLiam R. Howlett 	if (next && !insert) {
6471da177e4SLinus Torvalds 		if (end >= next->vm_end) {
6481da177e4SLinus Torvalds 			/*
6491da177e4SLinus Torvalds 			 * vma expands, overlapping all the next, and
6501da177e4SLinus Torvalds 			 * perhaps the one after too (mprotect case 6).
65186d12e47SAndrea Arcangeli 			 * The only other cases that gets here are
652e86f15eeSAndrea Arcangeli 			 * case 1, case 7 and case 8.
653e86f15eeSAndrea Arcangeli 			 */
654e86f15eeSAndrea Arcangeli 			if (next == expand) {
655e86f15eeSAndrea Arcangeli 				/*
656e86f15eeSAndrea Arcangeli 				 * The only case where we don't expand "vma"
657e86f15eeSAndrea Arcangeli 				 * and we expand "next" instead is case 8.
658e86f15eeSAndrea Arcangeli 				 */
659e86f15eeSAndrea Arcangeli 				VM_WARN_ON(end != next->vm_end);
660e86f15eeSAndrea Arcangeli 				/*
661e86f15eeSAndrea Arcangeli 				 * remove_next == 3 means we're
662e86f15eeSAndrea Arcangeli 				 * removing "vma" and that to do so we
663e86f15eeSAndrea Arcangeli 				 * swapped "vma" and "next".
664e86f15eeSAndrea Arcangeli 				 */
665e86f15eeSAndrea Arcangeli 				remove_next = 3;
666e86f15eeSAndrea Arcangeli 				VM_WARN_ON(file != next->vm_file);
667e86f15eeSAndrea Arcangeli 				swap(vma, next);
668e86f15eeSAndrea Arcangeli 			} else {
669e86f15eeSAndrea Arcangeli 				VM_WARN_ON(expand != vma);
670e86f15eeSAndrea Arcangeli 				/*
671e86f15eeSAndrea Arcangeli 				 * case 1, 6, 7, remove_next == 2 is case 6,
672e86f15eeSAndrea Arcangeli 				 * remove_next == 1 is case 1 or 7.
6731da177e4SLinus Torvalds 				 */
674734537c9SKirill A. Shutemov 				remove_next = 1 + (end > next->vm_end);
675d4af56c5SLiam R. Howlett 				if (remove_next == 2)
676d4af56c5SLiam R. Howlett 					next_next = find_vma(mm, next->vm_end);
677d4af56c5SLiam R. Howlett 
678e86f15eeSAndrea Arcangeli 				VM_WARN_ON(remove_next == 2 &&
679e86f15eeSAndrea Arcangeli 					   end != next->vm_next->vm_end);
680e86f15eeSAndrea Arcangeli 			}
681e86f15eeSAndrea Arcangeli 
682287d97acSLinus Torvalds 			exporter = next;
6831da177e4SLinus Torvalds 			importer = vma;
684734537c9SKirill A. Shutemov 
685734537c9SKirill A. Shutemov 			/*
686734537c9SKirill A. Shutemov 			 * If next doesn't have anon_vma, import from vma after
687734537c9SKirill A. Shutemov 			 * next, if the vma overlaps with it.
688734537c9SKirill A. Shutemov 			 */
68997a42cd4SAndrea Arcangeli 			if (remove_next == 2 && !next->anon_vma)
690734537c9SKirill A. Shutemov 				exporter = next->vm_next;
691734537c9SKirill A. Shutemov 
6921da177e4SLinus Torvalds 		} else if (end > next->vm_start) {
6931da177e4SLinus Torvalds 			/*
6941da177e4SLinus Torvalds 			 * vma expands, overlapping part of the next:
6951da177e4SLinus Torvalds 			 * mprotect case 5 shifting the boundary up.
6961da177e4SLinus Torvalds 			 */
697f9d86a60SWei Yang 			adjust_next = (end - next->vm_start);
698287d97acSLinus Torvalds 			exporter = next;
6991da177e4SLinus Torvalds 			importer = vma;
700e86f15eeSAndrea Arcangeli 			VM_WARN_ON(expand != importer);
7011da177e4SLinus Torvalds 		} else if (end < vma->vm_end) {
7021da177e4SLinus Torvalds 			/*
7031da177e4SLinus Torvalds 			 * vma shrinks, and !insert tells it's not
7041da177e4SLinus Torvalds 			 * split_vma inserting another: so it must be
7051da177e4SLinus Torvalds 			 * mprotect case 4 shifting the boundary down.
7061da177e4SLinus Torvalds 			 */
707f9d86a60SWei Yang 			adjust_next = -(vma->vm_end - end);
708287d97acSLinus Torvalds 			exporter = vma;
7091da177e4SLinus Torvalds 			importer = next;
710e86f15eeSAndrea Arcangeli 			VM_WARN_ON(expand != importer);
7111da177e4SLinus Torvalds 		}
7121da177e4SLinus Torvalds 
7135beb4930SRik van Riel 		/*
7145beb4930SRik van Riel 		 * Easily overlooked: when mprotect shifts the boundary,
7155beb4930SRik van Riel 		 * make sure the expanding vma has anon_vma set if the
7165beb4930SRik van Riel 		 * shrinking vma had, to cover any anon pages imported.
7175beb4930SRik van Riel 		 */
718287d97acSLinus Torvalds 		if (exporter && exporter->anon_vma && !importer->anon_vma) {
719c4ea95d7SDaniel Forrest 			int error;
720c4ea95d7SDaniel Forrest 
721287d97acSLinus Torvalds 			importer->anon_vma = exporter->anon_vma;
722b800c91aSKonstantin Khlebnikov 			error = anon_vma_clone(importer, exporter);
7233fe89b3eSLeon Yu 			if (error)
724b800c91aSKonstantin Khlebnikov 				return error;
725b800c91aSKonstantin Khlebnikov 		}
7265beb4930SRik van Riel 	}
72737f9f559SKirill A. Shutemov 
728d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
729d4af56c5SLiam R. Howlett 		return -ENOMEM;
730d4af56c5SLiam R. Howlett 
731d4af56c5SLiam R. Howlett 	vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
7321da177e4SLinus Torvalds 	if (file) {
7331da177e4SLinus Torvalds 		mapping = file->f_mapping;
7341da177e4SLinus Torvalds 		root = &mapping->i_mmap;
735cbc91f71SSrikar Dronamraju 		uprobe_munmap(vma, vma->vm_start, vma->vm_end);
736682968e0SSrikar Dronamraju 
737682968e0SSrikar Dronamraju 		if (adjust_next)
73827ba0644SKirill A. Shutemov 			uprobe_munmap(next, next->vm_start, next->vm_end);
739682968e0SSrikar Dronamraju 
74083cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
7411da177e4SLinus Torvalds 		if (insert) {
7421da177e4SLinus Torvalds 			/*
7436b2dbba8SMichel Lespinasse 			 * Put into interval tree now, so instantiated pages
7441da177e4SLinus Torvalds 			 * are visible to arm/parisc __flush_dcache_page
7451da177e4SLinus Torvalds 			 * throughout; but we cannot insert into address
7461da177e4SLinus Torvalds 			 * space until vma start or end is updated.
7471da177e4SLinus Torvalds 			 */
7481da177e4SLinus Torvalds 			__vma_link_file(insert);
7491da177e4SLinus Torvalds 		}
7501da177e4SLinus Torvalds 	}
7511da177e4SLinus Torvalds 
752012f1800SRik van Riel 	anon_vma = vma->anon_vma;
753bf181b9fSMichel Lespinasse 	if (!anon_vma && adjust_next)
754bf181b9fSMichel Lespinasse 		anon_vma = next->anon_vma;
755bf181b9fSMichel Lespinasse 	if (anon_vma) {
756e86f15eeSAndrea Arcangeli 		VM_WARN_ON(adjust_next && next->anon_vma &&
757e86f15eeSAndrea Arcangeli 			   anon_vma != next->anon_vma);
7584fc3f1d6SIngo Molnar 		anon_vma_lock_write(anon_vma);
759bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_pre_update_vma(vma);
760bf181b9fSMichel Lespinasse 		if (adjust_next)
761bf181b9fSMichel Lespinasse 			anon_vma_interval_tree_pre_update_vma(next);
762bf181b9fSMichel Lespinasse 	}
763012f1800SRik van Riel 
7640fc48a6eSWei Yang 	if (file) {
7651da177e4SLinus Torvalds 		flush_dcache_mmap_lock(mapping);
7666b2dbba8SMichel Lespinasse 		vma_interval_tree_remove(vma, root);
7671da177e4SLinus Torvalds 		if (adjust_next)
7686b2dbba8SMichel Lespinasse 			vma_interval_tree_remove(next, root);
7691da177e4SLinus Torvalds 	}
7701da177e4SLinus Torvalds 
771d3737187SMichel Lespinasse 	if (start != vma->vm_start) {
7723b0e81a1SLiam R. Howlett 		if ((vma->vm_start < start) &&
7733b0e81a1SLiam R. Howlett 		    (!insert || (insert->vm_end != start))) {
774524e00b3SLiam R. Howlett 			vma_mas_szero(&mas, vma->vm_start, start);
7753b0e81a1SLiam R. Howlett 			VM_WARN_ON(insert && insert->vm_start > vma->vm_start);
7763b0e81a1SLiam R. Howlett 		} else {
777524e00b3SLiam R. Howlett 			vma_changed = true;
7783b0e81a1SLiam R. Howlett 		}
7791da177e4SLinus Torvalds 		vma->vm_start = start;
780d3737187SMichel Lespinasse 	}
781d3737187SMichel Lespinasse 	if (end != vma->vm_end) {
7823b0e81a1SLiam R. Howlett 		if (vma->vm_end > end) {
7833b0e81a1SLiam R. Howlett 			if (!insert || (insert->vm_start != end)) {
784524e00b3SLiam R. Howlett 				vma_mas_szero(&mas, end, vma->vm_end);
7853b0e81a1SLiam R. Howlett 				VM_WARN_ON(insert &&
7863b0e81a1SLiam R. Howlett 					   insert->vm_end < vma->vm_end);
7873b0e81a1SLiam R. Howlett 			} else if (insert->vm_start == end) {
7883b0e81a1SLiam R. Howlett 				ll_prev = vma->vm_end;
7893b0e81a1SLiam R. Howlett 			}
7903b0e81a1SLiam R. Howlett 		} else {
791524e00b3SLiam R. Howlett 			vma_changed = true;
7923b0e81a1SLiam R. Howlett 		}
7931da177e4SLinus Torvalds 		vma->vm_end = end;
794524e00b3SLiam R. Howlett 		if (!next)
795524e00b3SLiam R. Howlett 			mm->highest_vm_end = vm_end_gap(vma);
796d3737187SMichel Lespinasse 	}
797d4af56c5SLiam R. Howlett 
798524e00b3SLiam R. Howlett 	if (vma_changed)
799d4af56c5SLiam R. Howlett 		vma_mas_store(vma, &mas);
800d4af56c5SLiam R. Howlett 
8011da177e4SLinus Torvalds 	vma->vm_pgoff = pgoff;
8021da177e4SLinus Torvalds 	if (adjust_next) {
803f9d86a60SWei Yang 		next->vm_start += adjust_next;
804f9d86a60SWei Yang 		next->vm_pgoff += adjust_next >> PAGE_SHIFT;
805d4af56c5SLiam R. Howlett 		vma_mas_store(next, &mas);
8061da177e4SLinus Torvalds 	}
8071da177e4SLinus Torvalds 
8080fc48a6eSWei Yang 	if (file) {
8091da177e4SLinus Torvalds 		if (adjust_next)
8106b2dbba8SMichel Lespinasse 			vma_interval_tree_insert(next, root);
8116b2dbba8SMichel Lespinasse 		vma_interval_tree_insert(vma, root);
8121da177e4SLinus Torvalds 		flush_dcache_mmap_unlock(mapping);
8131da177e4SLinus Torvalds 	}
8141da177e4SLinus Torvalds 
8151da177e4SLinus Torvalds 	if (remove_next) {
8161da177e4SLinus Torvalds 		/*
8171da177e4SLinus Torvalds 		 * vma_merge has merged next into vma, and needs
8181da177e4SLinus Torvalds 		 * us to remove next before dropping the locks.
819d4af56c5SLiam R. Howlett 		 * Since we have expanded over this vma, the maple tree will
820d4af56c5SLiam R. Howlett 		 * have overwritten by storing the value
8211da177e4SLinus Torvalds 		 */
822524e00b3SLiam R. Howlett 		__vma_unlink_list(mm, next);
823d4af56c5SLiam R. Howlett 		if (remove_next == 2)
824524e00b3SLiam R. Howlett 			__vma_unlink_list(mm, next_next);
825524e00b3SLiam R. Howlett 		/* Kill the cache */
826524e00b3SLiam R. Howlett 		vmacache_invalidate(mm);
827524e00b3SLiam R. Howlett 
828d4af56c5SLiam R. Howlett 		if (file) {
8291da177e4SLinus Torvalds 			__remove_shared_vm_struct(next, file, mapping);
830d4af56c5SLiam R. Howlett 			if (remove_next == 2)
831d4af56c5SLiam R. Howlett 				__remove_shared_vm_struct(next_next, file, mapping);
832d4af56c5SLiam R. Howlett 		}
8331da177e4SLinus Torvalds 	} else if (insert) {
8341da177e4SLinus Torvalds 		/*
8351da177e4SLinus Torvalds 		 * split_vma has split insert from vma, and needs
8361da177e4SLinus Torvalds 		 * us to insert it before dropping the locks
8371da177e4SLinus Torvalds 		 * (it may either follow vma or precede it).
8381da177e4SLinus Torvalds 		 */
8393b0e81a1SLiam R. Howlett 		__insert_vm_struct(mm, &mas, insert, ll_prev);
8401da177e4SLinus Torvalds 	}
8411da177e4SLinus Torvalds 
842bf181b9fSMichel Lespinasse 	if (anon_vma) {
843bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_post_update_vma(vma);
844bf181b9fSMichel Lespinasse 		if (adjust_next)
845bf181b9fSMichel Lespinasse 			anon_vma_interval_tree_post_update_vma(next);
84608b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
847bf181b9fSMichel Lespinasse 	}
8481da177e4SLinus Torvalds 
8490fc48a6eSWei Yang 	if (file) {
850808fbdbeSWei Yang 		i_mmap_unlock_write(mapping);
8517b2d81d4SIngo Molnar 		uprobe_mmap(vma);
8522b144498SSrikar Dronamraju 
8532b144498SSrikar Dronamraju 		if (adjust_next)
8547b2d81d4SIngo Molnar 			uprobe_mmap(next);
8552b144498SSrikar Dronamraju 	}
8562b144498SSrikar Dronamraju 
8571da177e4SLinus Torvalds 	if (remove_next) {
858d4af56c5SLiam R. Howlett again:
859925d1c40SMatt Helsley 		if (file) {
860cbc91f71SSrikar Dronamraju 			uprobe_munmap(next, next->vm_start, next->vm_end);
8611da177e4SLinus Torvalds 			fput(file);
862925d1c40SMatt Helsley 		}
8635beb4930SRik van Riel 		if (next->anon_vma)
8645beb4930SRik van Riel 			anon_vma_merge(vma, next);
8651da177e4SLinus Torvalds 		mm->map_count--;
8663964acd0SOleg Nesterov 		mpol_put(vma_policy(next));
867524e00b3SLiam R. Howlett 		if (remove_next != 2)
868524e00b3SLiam R. Howlett 			BUG_ON(vma->vm_end < next->vm_end);
8693928d4f5SLinus Torvalds 		vm_area_free(next);
870524e00b3SLiam R. Howlett 
8711da177e4SLinus Torvalds 		/*
8721da177e4SLinus Torvalds 		 * In mprotect's case 6 (see comments on vma_merge),
8731da177e4SLinus Torvalds 		 * we must remove another next too. It would clutter
8741da177e4SLinus Torvalds 		 * up the code too much to do both in one go.
8751da177e4SLinus Torvalds 		 */
876e86f15eeSAndrea Arcangeli 		if (remove_next != 3) {
877e86f15eeSAndrea Arcangeli 			/*
878e86f15eeSAndrea Arcangeli 			 * If "next" was removed and vma->vm_end was
879e86f15eeSAndrea Arcangeli 			 * expanded (up) over it, in turn
880e86f15eeSAndrea Arcangeli 			 * "next->vm_prev->vm_end" changed and the
881e86f15eeSAndrea Arcangeli 			 * "vma->vm_next" gap must be updated.
882e86f15eeSAndrea Arcangeli 			 */
883d4af56c5SLiam R. Howlett 			next = next_next;
884e86f15eeSAndrea Arcangeli 		} else {
885e86f15eeSAndrea Arcangeli 			/*
886e86f15eeSAndrea Arcangeli 			 * For the scope of the comment "next" and
887e86f15eeSAndrea Arcangeli 			 * "vma" considered pre-swap(): if "vma" was
888e86f15eeSAndrea Arcangeli 			 * removed, next->vm_start was expanded (down)
889e86f15eeSAndrea Arcangeli 			 * over it and the "next" gap must be updated.
890e86f15eeSAndrea Arcangeli 			 * Because of the swap() the post-swap() "vma"
891e86f15eeSAndrea Arcangeli 			 * actually points to pre-swap() "next"
892e86f15eeSAndrea Arcangeli 			 * (post-swap() "next" as opposed is now a
893e86f15eeSAndrea Arcangeli 			 * dangling pointer).
894e86f15eeSAndrea Arcangeli 			 */
895e86f15eeSAndrea Arcangeli 			next = vma;
896e86f15eeSAndrea Arcangeli 		}
897734537c9SKirill A. Shutemov 		if (remove_next == 2) {
898734537c9SKirill A. Shutemov 			remove_next = 1;
8991da177e4SLinus Torvalds 			goto again;
900524e00b3SLiam R. Howlett 		} else if (!next) {
901fb8c41e9SAndrea Arcangeli 			/*
902fb8c41e9SAndrea Arcangeli 			 * If remove_next == 2 we obviously can't
903fb8c41e9SAndrea Arcangeli 			 * reach this path.
904fb8c41e9SAndrea Arcangeli 			 *
905fb8c41e9SAndrea Arcangeli 			 * If remove_next == 3 we can't reach this
906fb8c41e9SAndrea Arcangeli 			 * path because pre-swap() next is always not
907fb8c41e9SAndrea Arcangeli 			 * NULL. pre-swap() "next" is not being
908fb8c41e9SAndrea Arcangeli 			 * removed and its next->vm_end is not altered
909fb8c41e9SAndrea Arcangeli 			 * (and furthermore "end" already matches
910fb8c41e9SAndrea Arcangeli 			 * next->vm_end in remove_next == 3).
911fb8c41e9SAndrea Arcangeli 			 *
912fb8c41e9SAndrea Arcangeli 			 * We reach this only in the remove_next == 1
913fb8c41e9SAndrea Arcangeli 			 * case if the "next" vma that was removed was
914fb8c41e9SAndrea Arcangeli 			 * the highest vma of the mm. However in such
915fb8c41e9SAndrea Arcangeli 			 * case next->vm_end == "end" and the extended
916fb8c41e9SAndrea Arcangeli 			 * "vma" has vma->vm_end == next->vm_end so
917fb8c41e9SAndrea Arcangeli 			 * mm->highest_vm_end doesn't need any update
918fb8c41e9SAndrea Arcangeli 			 * in remove_next == 1 case.
919fb8c41e9SAndrea Arcangeli 			 */
9201be7107fSHugh Dickins 			VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
921fb8c41e9SAndrea Arcangeli 		}
9221da177e4SLinus Torvalds 	}
9232b144498SSrikar Dronamraju 	if (insert && file)
9247b2d81d4SIngo Molnar 		uprobe_mmap(insert);
9251da177e4SLinus Torvalds 
9263b0e81a1SLiam R. Howlett 	mas_destroy(&mas);
9271da177e4SLinus Torvalds 	validate_mm(mm);
9285beb4930SRik van Riel 	return 0;
9291da177e4SLinus Torvalds }
9301da177e4SLinus Torvalds 
9311da177e4SLinus Torvalds /*
9321da177e4SLinus Torvalds  * If the vma has a ->close operation then the driver probably needs to release
9331da177e4SLinus Torvalds  * per-vma resources, so we don't attempt to merge those.
9341da177e4SLinus Torvalds  */
9351da177e4SLinus Torvalds static inline int is_mergeable_vma(struct vm_area_struct *vma,
93619a809afSAndrea Arcangeli 				struct file *file, unsigned long vm_flags,
9379a10064fSColin Cross 				struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
9385c26f6acSSuren Baghdasaryan 				struct anon_vma_name *anon_name)
9391da177e4SLinus Torvalds {
94034228d47SCyrill Gorcunov 	/*
94134228d47SCyrill Gorcunov 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
94234228d47SCyrill Gorcunov 	 * match the flags but dirty bit -- the caller should mark
94334228d47SCyrill Gorcunov 	 * merged VMA as dirty. If dirty bit won't be excluded from
9448bb4e7a2SWei Yang 	 * comparison, we increase pressure on the memory system forcing
94534228d47SCyrill Gorcunov 	 * the kernel to generate new VMAs when old one could be
94634228d47SCyrill Gorcunov 	 * extended instead.
94734228d47SCyrill Gorcunov 	 */
94834228d47SCyrill Gorcunov 	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
9491da177e4SLinus Torvalds 		return 0;
9501da177e4SLinus Torvalds 	if (vma->vm_file != file)
9511da177e4SLinus Torvalds 		return 0;
9521da177e4SLinus Torvalds 	if (vma->vm_ops && vma->vm_ops->close)
9531da177e4SLinus Torvalds 		return 0;
95419a809afSAndrea Arcangeli 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
95519a809afSAndrea Arcangeli 		return 0;
9565c26f6acSSuren Baghdasaryan 	if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
9579a10064fSColin Cross 		return 0;
9581da177e4SLinus Torvalds 	return 1;
9591da177e4SLinus Torvalds }
9601da177e4SLinus Torvalds 
9611da177e4SLinus Torvalds static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
962965f55deSShaohua Li 					struct anon_vma *anon_vma2,
963965f55deSShaohua Li 					struct vm_area_struct *vma)
9641da177e4SLinus Torvalds {
965965f55deSShaohua Li 	/*
966965f55deSShaohua Li 	 * The list_is_singular() test is to avoid merging VMA cloned from
967965f55deSShaohua Li 	 * parents. This can improve scalability caused by anon_vma lock.
968965f55deSShaohua Li 	 */
969965f55deSShaohua Li 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
970965f55deSShaohua Li 		list_is_singular(&vma->anon_vma_chain)))
971965f55deSShaohua Li 		return 1;
972965f55deSShaohua Li 	return anon_vma1 == anon_vma2;
9731da177e4SLinus Torvalds }
9741da177e4SLinus Torvalds 
9751da177e4SLinus Torvalds /*
9761da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
9771da177e4SLinus Torvalds  * in front of (at a lower virtual address and file offset than) the vma.
9781da177e4SLinus Torvalds  *
9791da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
9801da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
9811da177e4SLinus Torvalds  *
9821da177e4SLinus Torvalds  * We don't check here for the merged mmap wrapping around the end of pagecache
98345e55300SPeter Collingbourne  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
9841da177e4SLinus Torvalds  * wrap, nor mmaps which cover the final page at index -1UL.
9851da177e4SLinus Torvalds  */
9861da177e4SLinus Torvalds static int
9871da177e4SLinus Torvalds can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
98819a809afSAndrea Arcangeli 		     struct anon_vma *anon_vma, struct file *file,
98919a809afSAndrea Arcangeli 		     pgoff_t vm_pgoff,
9909a10064fSColin Cross 		     struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
9915c26f6acSSuren Baghdasaryan 		     struct anon_vma_name *anon_name)
9921da177e4SLinus Torvalds {
9939a10064fSColin Cross 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
994965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
9951da177e4SLinus Torvalds 		if (vma->vm_pgoff == vm_pgoff)
9961da177e4SLinus Torvalds 			return 1;
9971da177e4SLinus Torvalds 	}
9981da177e4SLinus Torvalds 	return 0;
9991da177e4SLinus Torvalds }
10001da177e4SLinus Torvalds 
10011da177e4SLinus Torvalds /*
10021da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
10031da177e4SLinus Torvalds  * beyond (at a higher virtual address and file offset than) the vma.
10041da177e4SLinus Torvalds  *
10051da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
10061da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
10071da177e4SLinus Torvalds  */
10081da177e4SLinus Torvalds static int
10091da177e4SLinus Torvalds can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
101019a809afSAndrea Arcangeli 		    struct anon_vma *anon_vma, struct file *file,
101119a809afSAndrea Arcangeli 		    pgoff_t vm_pgoff,
10129a10064fSColin Cross 		    struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
10135c26f6acSSuren Baghdasaryan 		    struct anon_vma_name *anon_name)
10141da177e4SLinus Torvalds {
10159a10064fSColin Cross 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1016965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
10171da177e4SLinus Torvalds 		pgoff_t vm_pglen;
1018d6e93217SLibin 		vm_pglen = vma_pages(vma);
10191da177e4SLinus Torvalds 		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
10201da177e4SLinus Torvalds 			return 1;
10211da177e4SLinus Torvalds 	}
10221da177e4SLinus Torvalds 	return 0;
10231da177e4SLinus Torvalds }
10241da177e4SLinus Torvalds 
10251da177e4SLinus Torvalds /*
10269a10064fSColin Cross  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
10279a10064fSColin Cross  * figure out whether that can be merged with its predecessor or its
10289a10064fSColin Cross  * successor.  Or both (it neatly fills a hole).
10291da177e4SLinus Torvalds  *
10301da177e4SLinus Torvalds  * In most cases - when called for mmap, brk or mremap - [addr,end) is
10311da177e4SLinus Torvalds  * certain not to be mapped by the time vma_merge is called; but when
10321da177e4SLinus Torvalds  * called for mprotect, it is certain to be already mapped (either at
10331da177e4SLinus Torvalds  * an offset within prev, or at the start of next), and the flags of
10341da177e4SLinus Torvalds  * this area are about to be changed to vm_flags - and the no-change
10351da177e4SLinus Torvalds  * case has already been eliminated.
10361da177e4SLinus Torvalds  *
10371da177e4SLinus Torvalds  * The following mprotect cases have to be considered, where AAAA is
10381da177e4SLinus Torvalds  * the area passed down from mprotect_fixup, never extending beyond one
10391da177e4SLinus Torvalds  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
10401da177e4SLinus Torvalds  *
10415d42ab29SWei Yang  *     AAAA             AAAA                   AAAA
10425d42ab29SWei Yang  *    PPPPPPNNNNNN    PPPPPPNNNNNN       PPPPPPNNNNNN
10435d42ab29SWei Yang  *    cannot merge    might become       might become
10445d42ab29SWei Yang  *                    PPNNNNNNNNNN       PPPPPPPPPPNN
10455d42ab29SWei Yang  *    mmap, brk or    case 4 below       case 5 below
10465d42ab29SWei Yang  *    mremap move:
10475d42ab29SWei Yang  *                        AAAA               AAAA
10485d42ab29SWei Yang  *                    PPPP    NNNN       PPPPNNNNXXXX
10495d42ab29SWei Yang  *                    might become       might become
10505d42ab29SWei Yang  *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
10515d42ab29SWei Yang  *                    PPPPPPPPNNNN 2 or  PPPPPPPPXXXX 7 or
10525d42ab29SWei Yang  *                    PPPPNNNNNNNN 3     PPPPXXXXXXXX 8
10531da177e4SLinus Torvalds  *
10548bb4e7a2SWei Yang  * It is important for case 8 that the vma NNNN overlapping the
1055e86f15eeSAndrea Arcangeli  * region AAAA is never going to extended over XXXX. Instead XXXX must
1056e86f15eeSAndrea Arcangeli  * be extended in region AAAA and NNNN must be removed. This way in
1057e86f15eeSAndrea Arcangeli  * all cases where vma_merge succeeds, the moment vma_adjust drops the
1058e86f15eeSAndrea Arcangeli  * rmap_locks, the properties of the merged vma will be already
1059e86f15eeSAndrea Arcangeli  * correct for the whole merged range. Some of those properties like
1060e86f15eeSAndrea Arcangeli  * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
1061e86f15eeSAndrea Arcangeli  * be correct for the whole merged range immediately after the
1062e86f15eeSAndrea Arcangeli  * rmap_locks are released. Otherwise if XXXX would be removed and
1063e86f15eeSAndrea Arcangeli  * NNNN would be extended over the XXXX range, remove_migration_ptes
1064e86f15eeSAndrea Arcangeli  * or other rmap walkers (if working on addresses beyond the "end"
1065e86f15eeSAndrea Arcangeli  * parameter) may establish ptes with the wrong permissions of NNNN
1066e86f15eeSAndrea Arcangeli  * instead of the right permissions of XXXX.
10671da177e4SLinus Torvalds  */
10681da177e4SLinus Torvalds struct vm_area_struct *vma_merge(struct mm_struct *mm,
10691da177e4SLinus Torvalds 			struct vm_area_struct *prev, unsigned long addr,
10701da177e4SLinus Torvalds 			unsigned long end, unsigned long vm_flags,
10711da177e4SLinus Torvalds 			struct anon_vma *anon_vma, struct file *file,
107219a809afSAndrea Arcangeli 			pgoff_t pgoff, struct mempolicy *policy,
10739a10064fSColin Cross 			struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
10745c26f6acSSuren Baghdasaryan 			struct anon_vma_name *anon_name)
10751da177e4SLinus Torvalds {
10761da177e4SLinus Torvalds 	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
10771da177e4SLinus Torvalds 	struct vm_area_struct *area, *next;
10785beb4930SRik van Riel 	int err;
10791da177e4SLinus Torvalds 
10801da177e4SLinus Torvalds 	/*
10811da177e4SLinus Torvalds 	 * We later require that vma->vm_flags == vm_flags,
10821da177e4SLinus Torvalds 	 * so this tests vma->vm_flags & VM_SPECIAL, too.
10831da177e4SLinus Torvalds 	 */
10841da177e4SLinus Torvalds 	if (vm_flags & VM_SPECIAL)
10851da177e4SLinus Torvalds 		return NULL;
10861da177e4SLinus Torvalds 
1087f39af059SMatthew Wilcox (Oracle) 	next = __vma_next(mm, prev);
10881da177e4SLinus Torvalds 	area = next;
1089e86f15eeSAndrea Arcangeli 	if (area && area->vm_end == end)		/* cases 6, 7, 8 */
10901da177e4SLinus Torvalds 		next = next->vm_next;
10911da177e4SLinus Torvalds 
1092e86f15eeSAndrea Arcangeli 	/* verify some invariant that must be enforced by the caller */
1093e86f15eeSAndrea Arcangeli 	VM_WARN_ON(prev && addr <= prev->vm_start);
1094e86f15eeSAndrea Arcangeli 	VM_WARN_ON(area && end > area->vm_end);
1095e86f15eeSAndrea Arcangeli 	VM_WARN_ON(addr >= end);
1096e86f15eeSAndrea Arcangeli 
10971da177e4SLinus Torvalds 	/*
10981da177e4SLinus Torvalds 	 * Can it merge with the predecessor?
10991da177e4SLinus Torvalds 	 */
11001da177e4SLinus Torvalds 	if (prev && prev->vm_end == addr &&
11011da177e4SLinus Torvalds 			mpol_equal(vma_policy(prev), policy) &&
11021da177e4SLinus Torvalds 			can_vma_merge_after(prev, vm_flags,
110319a809afSAndrea Arcangeli 					    anon_vma, file, pgoff,
11049a10064fSColin Cross 					    vm_userfaultfd_ctx, anon_name)) {
11051da177e4SLinus Torvalds 		/*
11061da177e4SLinus Torvalds 		 * OK, it can.  Can we now merge in the successor as well?
11071da177e4SLinus Torvalds 		 */
11081da177e4SLinus Torvalds 		if (next && end == next->vm_start &&
11091da177e4SLinus Torvalds 				mpol_equal(policy, vma_policy(next)) &&
11101da177e4SLinus Torvalds 				can_vma_merge_before(next, vm_flags,
111119a809afSAndrea Arcangeli 						     anon_vma, file,
111219a809afSAndrea Arcangeli 						     pgoff+pglen,
11139a10064fSColin Cross 						     vm_userfaultfd_ctx, anon_name) &&
11141da177e4SLinus Torvalds 				is_mergeable_anon_vma(prev->anon_vma,
1115965f55deSShaohua Li 						      next->anon_vma, NULL)) {
11161da177e4SLinus Torvalds 							/* cases 1, 6 */
1117e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1118e86f15eeSAndrea Arcangeli 					 next->vm_end, prev->vm_pgoff, NULL,
1119e86f15eeSAndrea Arcangeli 					 prev);
11201da177e4SLinus Torvalds 		} else					/* cases 2, 5, 7 */
1121e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1122e86f15eeSAndrea Arcangeli 					 end, prev->vm_pgoff, NULL, prev);
11235beb4930SRik van Riel 		if (err)
11245beb4930SRik van Riel 			return NULL;
1125c791576cSYang Shi 		khugepaged_enter_vma(prev, vm_flags);
11261da177e4SLinus Torvalds 		return prev;
11271da177e4SLinus Torvalds 	}
11281da177e4SLinus Torvalds 
11291da177e4SLinus Torvalds 	/*
11301da177e4SLinus Torvalds 	 * Can this new request be merged in front of next?
11311da177e4SLinus Torvalds 	 */
11321da177e4SLinus Torvalds 	if (next && end == next->vm_start &&
11331da177e4SLinus Torvalds 			mpol_equal(policy, vma_policy(next)) &&
11341da177e4SLinus Torvalds 			can_vma_merge_before(next, vm_flags,
113519a809afSAndrea Arcangeli 					     anon_vma, file, pgoff+pglen,
11369a10064fSColin Cross 					     vm_userfaultfd_ctx, anon_name)) {
11371da177e4SLinus Torvalds 		if (prev && addr < prev->vm_end)	/* case 4 */
1138e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1139e86f15eeSAndrea Arcangeli 					 addr, prev->vm_pgoff, NULL, next);
1140e86f15eeSAndrea Arcangeli 		else {					/* cases 3, 8 */
1141e86f15eeSAndrea Arcangeli 			err = __vma_adjust(area, addr, next->vm_end,
1142e86f15eeSAndrea Arcangeli 					 next->vm_pgoff - pglen, NULL, next);
1143e86f15eeSAndrea Arcangeli 			/*
1144e86f15eeSAndrea Arcangeli 			 * In case 3 area is already equal to next and
1145e86f15eeSAndrea Arcangeli 			 * this is a noop, but in case 8 "area" has
1146e86f15eeSAndrea Arcangeli 			 * been removed and next was expanded over it.
1147e86f15eeSAndrea Arcangeli 			 */
1148e86f15eeSAndrea Arcangeli 			area = next;
1149e86f15eeSAndrea Arcangeli 		}
11505beb4930SRik van Riel 		if (err)
11515beb4930SRik van Riel 			return NULL;
1152c791576cSYang Shi 		khugepaged_enter_vma(area, vm_flags);
11531da177e4SLinus Torvalds 		return area;
11541da177e4SLinus Torvalds 	}
11551da177e4SLinus Torvalds 
11561da177e4SLinus Torvalds 	return NULL;
11571da177e4SLinus Torvalds }
11581da177e4SLinus Torvalds 
11591da177e4SLinus Torvalds /*
1160b4f315b4SEthon Paul  * Rough compatibility check to quickly see if it's even worth looking
1161d0e9fe17SLinus Torvalds  * at sharing an anon_vma.
1162d0e9fe17SLinus Torvalds  *
1163d0e9fe17SLinus Torvalds  * They need to have the same vm_file, and the flags can only differ
1164d0e9fe17SLinus Torvalds  * in things that mprotect may change.
1165d0e9fe17SLinus Torvalds  *
1166d0e9fe17SLinus Torvalds  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1167d0e9fe17SLinus Torvalds  * we can merge the two vma's. For example, we refuse to merge a vma if
1168d0e9fe17SLinus Torvalds  * there is a vm_ops->close() function, because that indicates that the
1169d0e9fe17SLinus Torvalds  * driver is doing some kind of reference counting. But that doesn't
1170d0e9fe17SLinus Torvalds  * really matter for the anon_vma sharing case.
1171d0e9fe17SLinus Torvalds  */
1172d0e9fe17SLinus Torvalds static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1173d0e9fe17SLinus Torvalds {
1174d0e9fe17SLinus Torvalds 	return a->vm_end == b->vm_start &&
1175d0e9fe17SLinus Torvalds 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1176d0e9fe17SLinus Torvalds 		a->vm_file == b->vm_file &&
11776cb4d9a2SAnshuman Khandual 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1178d0e9fe17SLinus Torvalds 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1179d0e9fe17SLinus Torvalds }
1180d0e9fe17SLinus Torvalds 
1181d0e9fe17SLinus Torvalds /*
1182d0e9fe17SLinus Torvalds  * Do some basic sanity checking to see if we can re-use the anon_vma
1183d0e9fe17SLinus Torvalds  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1184d0e9fe17SLinus Torvalds  * the same as 'old', the other will be the new one that is trying
1185d0e9fe17SLinus Torvalds  * to share the anon_vma.
1186d0e9fe17SLinus Torvalds  *
11875b449489SFlorian Rommel  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1188d0e9fe17SLinus Torvalds  * the anon_vma of 'old' is concurrently in the process of being set up
1189d0e9fe17SLinus Torvalds  * by another page fault trying to merge _that_. But that's ok: if it
1190d0e9fe17SLinus Torvalds  * is being set up, that automatically means that it will be a singleton
1191d0e9fe17SLinus Torvalds  * acceptable for merging, so we can do all of this optimistically. But
11924db0c3c2SJason Low  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1193d0e9fe17SLinus Torvalds  *
1194d0e9fe17SLinus Torvalds  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1195d0e9fe17SLinus Torvalds  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1196d0e9fe17SLinus Torvalds  * is to return an anon_vma that is "complex" due to having gone through
1197d0e9fe17SLinus Torvalds  * a fork).
1198d0e9fe17SLinus Torvalds  *
1199d0e9fe17SLinus Torvalds  * We also make sure that the two vma's are compatible (adjacent,
1200d0e9fe17SLinus Torvalds  * and with the same memory policies). That's all stable, even with just
12015b449489SFlorian Rommel  * a read lock on the mmap_lock.
1202d0e9fe17SLinus Torvalds  */
1203d0e9fe17SLinus Torvalds static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1204d0e9fe17SLinus Torvalds {
1205d0e9fe17SLinus Torvalds 	if (anon_vma_compatible(a, b)) {
12064db0c3c2SJason Low 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1207d0e9fe17SLinus Torvalds 
1208d0e9fe17SLinus Torvalds 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1209d0e9fe17SLinus Torvalds 			return anon_vma;
1210d0e9fe17SLinus Torvalds 	}
1211d0e9fe17SLinus Torvalds 	return NULL;
1212d0e9fe17SLinus Torvalds }
1213d0e9fe17SLinus Torvalds 
1214d0e9fe17SLinus Torvalds /*
12151da177e4SLinus Torvalds  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
12161da177e4SLinus Torvalds  * neighbouring vmas for a suitable anon_vma, before it goes off
12171da177e4SLinus Torvalds  * to allocate a new anon_vma.  It checks because a repetitive
12181da177e4SLinus Torvalds  * sequence of mprotects and faults may otherwise lead to distinct
12191da177e4SLinus Torvalds  * anon_vmas being allocated, preventing vma merge in subsequent
12201da177e4SLinus Torvalds  * mprotect.
12211da177e4SLinus Torvalds  */
12221da177e4SLinus Torvalds struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
12231da177e4SLinus Torvalds {
1224a67c8caaSMiaohe Lin 	struct anon_vma *anon_vma = NULL;
12251da177e4SLinus Torvalds 
1226a67c8caaSMiaohe Lin 	/* Try next first. */
1227a67c8caaSMiaohe Lin 	if (vma->vm_next) {
1228a67c8caaSMiaohe Lin 		anon_vma = reusable_anon_vma(vma->vm_next, vma, vma->vm_next);
1229d0e9fe17SLinus Torvalds 		if (anon_vma)
1230d0e9fe17SLinus Torvalds 			return anon_vma;
1231a67c8caaSMiaohe Lin 	}
12321da177e4SLinus Torvalds 
1233a67c8caaSMiaohe Lin 	/* Try prev next. */
1234a67c8caaSMiaohe Lin 	if (vma->vm_prev)
1235a67c8caaSMiaohe Lin 		anon_vma = reusable_anon_vma(vma->vm_prev, vma->vm_prev, vma);
1236a67c8caaSMiaohe Lin 
12371da177e4SLinus Torvalds 	/*
1238a67c8caaSMiaohe Lin 	 * We might reach here with anon_vma == NULL if we can't find
1239a67c8caaSMiaohe Lin 	 * any reusable anon_vma.
12401da177e4SLinus Torvalds 	 * There's no absolute need to look only at touching neighbours:
12411da177e4SLinus Torvalds 	 * we could search further afield for "compatible" anon_vmas.
12421da177e4SLinus Torvalds 	 * But it would probably just be a waste of time searching,
12431da177e4SLinus Torvalds 	 * or lead to too many vmas hanging off the same anon_vma.
12441da177e4SLinus Torvalds 	 * We're trying to allow mprotect remerging later on,
12451da177e4SLinus Torvalds 	 * not trying to minimize memory used for anon_vmas.
12461da177e4SLinus Torvalds 	 */
1247a67c8caaSMiaohe Lin 	return anon_vma;
12481da177e4SLinus Torvalds }
12491da177e4SLinus Torvalds 
12501da177e4SLinus Torvalds /*
125140401530SAl Viro  * If a hint addr is less than mmap_min_addr change hint to be as
125240401530SAl Viro  * low as possible but still greater than mmap_min_addr
125340401530SAl Viro  */
125440401530SAl Viro static inline unsigned long round_hint_to_min(unsigned long hint)
125540401530SAl Viro {
125640401530SAl Viro 	hint &= PAGE_MASK;
125740401530SAl Viro 	if (((void *)hint != NULL) &&
125840401530SAl Viro 	    (hint < mmap_min_addr))
125940401530SAl Viro 		return PAGE_ALIGN(mmap_min_addr);
126040401530SAl Viro 	return hint;
126140401530SAl Viro }
126240401530SAl Viro 
12636aeb2542SMike Rapoport int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1264363ee17fSDavidlohr Bueso 		       unsigned long len)
1265363ee17fSDavidlohr Bueso {
1266363ee17fSDavidlohr Bueso 	unsigned long locked, lock_limit;
1267363ee17fSDavidlohr Bueso 
1268363ee17fSDavidlohr Bueso 	/*  mlock MCL_FUTURE? */
1269363ee17fSDavidlohr Bueso 	if (flags & VM_LOCKED) {
1270363ee17fSDavidlohr Bueso 		locked = len >> PAGE_SHIFT;
1271363ee17fSDavidlohr Bueso 		locked += mm->locked_vm;
1272363ee17fSDavidlohr Bueso 		lock_limit = rlimit(RLIMIT_MEMLOCK);
1273363ee17fSDavidlohr Bueso 		lock_limit >>= PAGE_SHIFT;
1274363ee17fSDavidlohr Bueso 		if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1275363ee17fSDavidlohr Bueso 			return -EAGAIN;
1276363ee17fSDavidlohr Bueso 	}
1277363ee17fSDavidlohr Bueso 	return 0;
1278363ee17fSDavidlohr Bueso }
1279363ee17fSDavidlohr Bueso 
1280be83bbf8SLinus Torvalds static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1281be83bbf8SLinus Torvalds {
1282be83bbf8SLinus Torvalds 	if (S_ISREG(inode->i_mode))
1283423913adSLinus Torvalds 		return MAX_LFS_FILESIZE;
1284be83bbf8SLinus Torvalds 
1285be83bbf8SLinus Torvalds 	if (S_ISBLK(inode->i_mode))
1286be83bbf8SLinus Torvalds 		return MAX_LFS_FILESIZE;
1287be83bbf8SLinus Torvalds 
128876f34950SIvan Khoronzhuk 	if (S_ISSOCK(inode->i_mode))
128976f34950SIvan Khoronzhuk 		return MAX_LFS_FILESIZE;
129076f34950SIvan Khoronzhuk 
1291be83bbf8SLinus Torvalds 	/* Special "we do even unsigned file positions" case */
1292be83bbf8SLinus Torvalds 	if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1293be83bbf8SLinus Torvalds 		return 0;
1294be83bbf8SLinus Torvalds 
1295be83bbf8SLinus Torvalds 	/* Yes, random drivers might want more. But I'm tired of buggy drivers */
1296be83bbf8SLinus Torvalds 	return ULONG_MAX;
1297be83bbf8SLinus Torvalds }
1298be83bbf8SLinus Torvalds 
1299be83bbf8SLinus Torvalds static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1300be83bbf8SLinus Torvalds 				unsigned long pgoff, unsigned long len)
1301be83bbf8SLinus Torvalds {
1302be83bbf8SLinus Torvalds 	u64 maxsize = file_mmap_size_max(file, inode);
1303be83bbf8SLinus Torvalds 
1304be83bbf8SLinus Torvalds 	if (maxsize && len > maxsize)
1305be83bbf8SLinus Torvalds 		return false;
1306be83bbf8SLinus Torvalds 	maxsize -= len;
1307be83bbf8SLinus Torvalds 	if (pgoff > maxsize >> PAGE_SHIFT)
1308be83bbf8SLinus Torvalds 		return false;
1309be83bbf8SLinus Torvalds 	return true;
1310be83bbf8SLinus Torvalds }
1311be83bbf8SLinus Torvalds 
131240401530SAl Viro /*
13133e4e28c5SMichel Lespinasse  * The caller must write-lock current->mm->mmap_lock.
13141da177e4SLinus Torvalds  */
13151fcfd8dbSOleg Nesterov unsigned long do_mmap(struct file *file, unsigned long addr,
13161da177e4SLinus Torvalds 			unsigned long len, unsigned long prot,
131745e55300SPeter Collingbourne 			unsigned long flags, unsigned long pgoff,
131845e55300SPeter Collingbourne 			unsigned long *populate, struct list_head *uf)
13191da177e4SLinus Torvalds {
13201da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
132145e55300SPeter Collingbourne 	vm_flags_t vm_flags;
132262b5f7d0SDave Hansen 	int pkey = 0;
13231da177e4SLinus Torvalds 
1324524e00b3SLiam R. Howlett 	validate_mm(mm);
132541badc15SMichel Lespinasse 	*populate = 0;
1326bebeb3d6SMichel Lespinasse 
1327e37609bbSPiotr Kwapulinski 	if (!len)
1328e37609bbSPiotr Kwapulinski 		return -EINVAL;
1329e37609bbSPiotr Kwapulinski 
13301da177e4SLinus Torvalds 	/*
13311da177e4SLinus Torvalds 	 * Does the application expect PROT_READ to imply PROT_EXEC?
13321da177e4SLinus Torvalds 	 *
13331da177e4SLinus Torvalds 	 * (the exception is when the underlying filesystem is noexec
13341da177e4SLinus Torvalds 	 *  mounted, in which case we dont add PROT_EXEC.)
13351da177e4SLinus Torvalds 	 */
13361da177e4SLinus Torvalds 	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
133790f8572bSEric W. Biederman 		if (!(file && path_noexec(&file->f_path)))
13381da177e4SLinus Torvalds 			prot |= PROT_EXEC;
13391da177e4SLinus Torvalds 
1340a4ff8e86SMichal Hocko 	/* force arch specific MAP_FIXED handling in get_unmapped_area */
1341a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE)
1342a4ff8e86SMichal Hocko 		flags |= MAP_FIXED;
1343a4ff8e86SMichal Hocko 
13447cd94146SEric Paris 	if (!(flags & MAP_FIXED))
13457cd94146SEric Paris 		addr = round_hint_to_min(addr);
13467cd94146SEric Paris 
13471da177e4SLinus Torvalds 	/* Careful about overflows.. */
13481da177e4SLinus Torvalds 	len = PAGE_ALIGN(len);
13499206de95SAl Viro 	if (!len)
13501da177e4SLinus Torvalds 		return -ENOMEM;
13511da177e4SLinus Torvalds 
13521da177e4SLinus Torvalds 	/* offset overflow? */
13531da177e4SLinus Torvalds 	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
13541da177e4SLinus Torvalds 		return -EOVERFLOW;
13551da177e4SLinus Torvalds 
13561da177e4SLinus Torvalds 	/* Too many mappings? */
13571da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
13581da177e4SLinus Torvalds 		return -ENOMEM;
13591da177e4SLinus Torvalds 
13601da177e4SLinus Torvalds 	/* Obtain the address to map to. we verify (or select) it and ensure
13611da177e4SLinus Torvalds 	 * that it represents a valid section of the address space.
13621da177e4SLinus Torvalds 	 */
13631da177e4SLinus Torvalds 	addr = get_unmapped_area(file, addr, len, pgoff, flags);
1364ff68dac6SGaowei Pu 	if (IS_ERR_VALUE(addr))
13651da177e4SLinus Torvalds 		return addr;
13661da177e4SLinus Torvalds 
1367a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE) {
136835e43c5fSLiam Howlett 		if (find_vma_intersection(mm, addr, addr + len))
1369a4ff8e86SMichal Hocko 			return -EEXIST;
1370a4ff8e86SMichal Hocko 	}
1371a4ff8e86SMichal Hocko 
137262b5f7d0SDave Hansen 	if (prot == PROT_EXEC) {
137362b5f7d0SDave Hansen 		pkey = execute_only_pkey(mm);
137462b5f7d0SDave Hansen 		if (pkey < 0)
137562b5f7d0SDave Hansen 			pkey = 0;
137662b5f7d0SDave Hansen 	}
137762b5f7d0SDave Hansen 
13781da177e4SLinus Torvalds 	/* Do simple checking here so the lower-level routines won't have
13791da177e4SLinus Torvalds 	 * to. we assume access permissions have been handled by the open
13801da177e4SLinus Torvalds 	 * of the memory object, so we don't do any here.
13811da177e4SLinus Torvalds 	 */
138245e55300SPeter Collingbourne 	vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
13831da177e4SLinus Torvalds 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
13841da177e4SLinus Torvalds 
1385cdf7b341SHuang Shijie 	if (flags & MAP_LOCKED)
13861da177e4SLinus Torvalds 		if (!can_do_mlock())
13871da177e4SLinus Torvalds 			return -EPERM;
1388ba470de4SRik van Riel 
1389363ee17fSDavidlohr Bueso 	if (mlock_future_check(mm, vm_flags, len))
13901da177e4SLinus Torvalds 		return -EAGAIN;
13911da177e4SLinus Torvalds 
13921da177e4SLinus Torvalds 	if (file) {
1393077bf22bSOleg Nesterov 		struct inode *inode = file_inode(file);
13941c972597SDan Williams 		unsigned long flags_mask;
13951c972597SDan Williams 
1396be83bbf8SLinus Torvalds 		if (!file_mmap_ok(file, inode, pgoff, len))
1397be83bbf8SLinus Torvalds 			return -EOVERFLOW;
1398be83bbf8SLinus Torvalds 
13991c972597SDan Williams 		flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1400077bf22bSOleg Nesterov 
14011da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
14021da177e4SLinus Torvalds 		case MAP_SHARED:
14031c972597SDan Williams 			/*
14041c972597SDan Williams 			 * Force use of MAP_SHARED_VALIDATE with non-legacy
14051c972597SDan Williams 			 * flags. E.g. MAP_SYNC is dangerous to use with
14061c972597SDan Williams 			 * MAP_SHARED as you don't know which consistency model
14071c972597SDan Williams 			 * you will get. We silently ignore unsupported flags
14081c972597SDan Williams 			 * with MAP_SHARED to preserve backward compatibility.
14091c972597SDan Williams 			 */
14101c972597SDan Williams 			flags &= LEGACY_MAP_MASK;
1411e4a9bc58SJoe Perches 			fallthrough;
14121c972597SDan Williams 		case MAP_SHARED_VALIDATE:
14131c972597SDan Williams 			if (flags & ~flags_mask)
14141c972597SDan Williams 				return -EOPNOTSUPP;
1415dc617f29SDarrick J. Wong 			if (prot & PROT_WRITE) {
1416dc617f29SDarrick J. Wong 				if (!(file->f_mode & FMODE_WRITE))
14171da177e4SLinus Torvalds 					return -EACCES;
1418dc617f29SDarrick J. Wong 				if (IS_SWAPFILE(file->f_mapping->host))
1419dc617f29SDarrick J. Wong 					return -ETXTBSY;
1420dc617f29SDarrick J. Wong 			}
14211da177e4SLinus Torvalds 
14221da177e4SLinus Torvalds 			/*
14231da177e4SLinus Torvalds 			 * Make sure we don't allow writing to an append-only
14241da177e4SLinus Torvalds 			 * file..
14251da177e4SLinus Torvalds 			 */
14261da177e4SLinus Torvalds 			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
14271da177e4SLinus Torvalds 				return -EACCES;
14281da177e4SLinus Torvalds 
14291da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
14301da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_WRITE))
14311da177e4SLinus Torvalds 				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1432e4a9bc58SJoe Perches 			fallthrough;
14331da177e4SLinus Torvalds 		case MAP_PRIVATE:
14341da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_READ))
14351da177e4SLinus Torvalds 				return -EACCES;
143690f8572bSEric W. Biederman 			if (path_noexec(&file->f_path)) {
143780c5606cSLinus Torvalds 				if (vm_flags & VM_EXEC)
143880c5606cSLinus Torvalds 					return -EPERM;
143980c5606cSLinus Torvalds 				vm_flags &= ~VM_MAYEXEC;
144080c5606cSLinus Torvalds 			}
144180c5606cSLinus Torvalds 
144272c2d531SAl Viro 			if (!file->f_op->mmap)
144380c5606cSLinus Torvalds 				return -ENODEV;
1444b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1445b2c56e4fSOleg Nesterov 				return -EINVAL;
14461da177e4SLinus Torvalds 			break;
14471da177e4SLinus Torvalds 
14481da177e4SLinus Torvalds 		default:
14491da177e4SLinus Torvalds 			return -EINVAL;
14501da177e4SLinus Torvalds 		}
14511da177e4SLinus Torvalds 	} else {
14521da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
14531da177e4SLinus Torvalds 		case MAP_SHARED:
1454b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1455b2c56e4fSOleg Nesterov 				return -EINVAL;
1456ce363942STejun Heo 			/*
1457ce363942STejun Heo 			 * Ignore pgoff.
1458ce363942STejun Heo 			 */
1459ce363942STejun Heo 			pgoff = 0;
14601da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
14611da177e4SLinus Torvalds 			break;
14621da177e4SLinus Torvalds 		case MAP_PRIVATE:
14631da177e4SLinus Torvalds 			/*
14641da177e4SLinus Torvalds 			 * Set pgoff according to addr for anon_vma.
14651da177e4SLinus Torvalds 			 */
14661da177e4SLinus Torvalds 			pgoff = addr >> PAGE_SHIFT;
14671da177e4SLinus Torvalds 			break;
14681da177e4SLinus Torvalds 		default:
14691da177e4SLinus Torvalds 			return -EINVAL;
14701da177e4SLinus Torvalds 		}
14711da177e4SLinus Torvalds 	}
14721da177e4SLinus Torvalds 
1473c22c0d63SMichel Lespinasse 	/*
1474c22c0d63SMichel Lespinasse 	 * Set 'VM_NORESERVE' if we should not account for the
1475c22c0d63SMichel Lespinasse 	 * memory use of this mapping.
1476c22c0d63SMichel Lespinasse 	 */
1477c22c0d63SMichel Lespinasse 	if (flags & MAP_NORESERVE) {
1478c22c0d63SMichel Lespinasse 		/* We honor MAP_NORESERVE if allowed to overcommit */
1479c22c0d63SMichel Lespinasse 		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1480c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1481c22c0d63SMichel Lespinasse 
1482c22c0d63SMichel Lespinasse 		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
1483c22c0d63SMichel Lespinasse 		if (file && is_file_hugepages(file))
1484c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1485c22c0d63SMichel Lespinasse 	}
1486c22c0d63SMichel Lespinasse 
1487897ab3e0SMike Rapoport 	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
148809a9f1d2SMichel Lespinasse 	if (!IS_ERR_VALUE(addr) &&
148909a9f1d2SMichel Lespinasse 	    ((vm_flags & VM_LOCKED) ||
149009a9f1d2SMichel Lespinasse 	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
149141badc15SMichel Lespinasse 		*populate = len;
1492bebeb3d6SMichel Lespinasse 	return addr;
14930165ab44SMiklos Szeredi }
14946be5ceb0SLinus Torvalds 
1495a90f590aSDominik Brodowski unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1496a90f590aSDominik Brodowski 			      unsigned long prot, unsigned long flags,
1497a90f590aSDominik Brodowski 			      unsigned long fd, unsigned long pgoff)
149866f0dc48SHugh Dickins {
149966f0dc48SHugh Dickins 	struct file *file = NULL;
15001e3ee14bSChen Gang 	unsigned long retval;
150166f0dc48SHugh Dickins 
150266f0dc48SHugh Dickins 	if (!(flags & MAP_ANONYMOUS)) {
1503120a795dSAl Viro 		audit_mmap_fd(fd, flags);
150466f0dc48SHugh Dickins 		file = fget(fd);
150566f0dc48SHugh Dickins 		if (!file)
15061e3ee14bSChen Gang 			return -EBADF;
15077bba8f0eSZhen Lei 		if (is_file_hugepages(file)) {
1508af73e4d9SNaoya Horiguchi 			len = ALIGN(len, huge_page_size(hstate_file(file)));
15097bba8f0eSZhen Lei 		} else if (unlikely(flags & MAP_HUGETLB)) {
1510493af578SJörn Engel 			retval = -EINVAL;
1511493af578SJörn Engel 			goto out_fput;
15127bba8f0eSZhen Lei 		}
151366f0dc48SHugh Dickins 	} else if (flags & MAP_HUGETLB) {
1514c103a4dcSAndrew Morton 		struct hstate *hs;
1515af73e4d9SNaoya Horiguchi 
151620ac2893SAnshuman Khandual 		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1517091d0d55SLi Zefan 		if (!hs)
1518091d0d55SLi Zefan 			return -EINVAL;
1519091d0d55SLi Zefan 
1520091d0d55SLi Zefan 		len = ALIGN(len, huge_page_size(hs));
152166f0dc48SHugh Dickins 		/*
152266f0dc48SHugh Dickins 		 * VM_NORESERVE is used because the reservations will be
152366f0dc48SHugh Dickins 		 * taken when vm_ops->mmap() is called
152466f0dc48SHugh Dickins 		 */
1525af73e4d9SNaoya Horiguchi 		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
152642d7395fSAndi Kleen 				VM_NORESERVE,
152783c1fd76Szhangyiru 				HUGETLB_ANONHUGE_INODE,
152842d7395fSAndi Kleen 				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
152966f0dc48SHugh Dickins 		if (IS_ERR(file))
153066f0dc48SHugh Dickins 			return PTR_ERR(file);
153166f0dc48SHugh Dickins 	}
153266f0dc48SHugh Dickins 
15339fbeb5abSMichal Hocko 	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1534493af578SJörn Engel out_fput:
153566f0dc48SHugh Dickins 	if (file)
153666f0dc48SHugh Dickins 		fput(file);
153766f0dc48SHugh Dickins 	return retval;
153866f0dc48SHugh Dickins }
153966f0dc48SHugh Dickins 
1540a90f590aSDominik Brodowski SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1541a90f590aSDominik Brodowski 		unsigned long, prot, unsigned long, flags,
1542a90f590aSDominik Brodowski 		unsigned long, fd, unsigned long, pgoff)
1543a90f590aSDominik Brodowski {
1544a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1545a90f590aSDominik Brodowski }
1546a90f590aSDominik Brodowski 
1547a4679373SChristoph Hellwig #ifdef __ARCH_WANT_SYS_OLD_MMAP
1548a4679373SChristoph Hellwig struct mmap_arg_struct {
1549a4679373SChristoph Hellwig 	unsigned long addr;
1550a4679373SChristoph Hellwig 	unsigned long len;
1551a4679373SChristoph Hellwig 	unsigned long prot;
1552a4679373SChristoph Hellwig 	unsigned long flags;
1553a4679373SChristoph Hellwig 	unsigned long fd;
1554a4679373SChristoph Hellwig 	unsigned long offset;
1555a4679373SChristoph Hellwig };
1556a4679373SChristoph Hellwig 
1557a4679373SChristoph Hellwig SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1558a4679373SChristoph Hellwig {
1559a4679373SChristoph Hellwig 	struct mmap_arg_struct a;
1560a4679373SChristoph Hellwig 
1561a4679373SChristoph Hellwig 	if (copy_from_user(&a, arg, sizeof(a)))
1562a4679373SChristoph Hellwig 		return -EFAULT;
1563de1741a1SAlexander Kuleshov 	if (offset_in_page(a.offset))
1564a4679373SChristoph Hellwig 		return -EINVAL;
1565a4679373SChristoph Hellwig 
1566a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1567a4679373SChristoph Hellwig 			       a.offset >> PAGE_SHIFT);
1568a4679373SChristoph Hellwig }
1569a4679373SChristoph Hellwig #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1570a4679373SChristoph Hellwig 
15714e950f6fSAlexey Dobriyan /*
15728bb4e7a2SWei Yang  * Some shared mappings will want the pages marked read-only
15734e950f6fSAlexey Dobriyan  * to track write events. If so, we'll downgrade vm_page_prot
15744e950f6fSAlexey Dobriyan  * to the private version (using protection_map[] without the
15754e950f6fSAlexey Dobriyan  * VM_SHARED bit).
15764e950f6fSAlexey Dobriyan  */
15776d2329f8SAndrea Arcangeli int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
15784e950f6fSAlexey Dobriyan {
1579ca16d140SKOSAKI Motohiro 	vm_flags_t vm_flags = vma->vm_flags;
15808a04446aSKirill A. Shutemov 	const struct vm_operations_struct *vm_ops = vma->vm_ops;
15814e950f6fSAlexey Dobriyan 
15824e950f6fSAlexey Dobriyan 	/* If it was private or non-writable, the write bit is already clear */
15834e950f6fSAlexey Dobriyan 	if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
15844e950f6fSAlexey Dobriyan 		return 0;
15854e950f6fSAlexey Dobriyan 
15864e950f6fSAlexey Dobriyan 	/* The backer wishes to know when pages are first written to? */
15878a04446aSKirill A. Shutemov 	if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
15884e950f6fSAlexey Dobriyan 		return 1;
15894e950f6fSAlexey Dobriyan 
159064e45507SPeter Feiner 	/* The open routine did something to the protections that pgprot_modify
159164e45507SPeter Feiner 	 * won't preserve? */
15926d2329f8SAndrea Arcangeli 	if (pgprot_val(vm_page_prot) !=
15936d2329f8SAndrea Arcangeli 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
15944e950f6fSAlexey Dobriyan 		return 0;
15954e950f6fSAlexey Dobriyan 
1596f96f7a40SDavid Hildenbrand 	/*
1597f96f7a40SDavid Hildenbrand 	 * Do we need to track softdirty? hugetlb does not support softdirty
1598f96f7a40SDavid Hildenbrand 	 * tracking yet.
1599f96f7a40SDavid Hildenbrand 	 */
1600f96f7a40SDavid Hildenbrand 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
160164e45507SPeter Feiner 		return 1;
160264e45507SPeter Feiner 
16034e950f6fSAlexey Dobriyan 	/* Specialty mapping? */
16044b6e1e37SKonstantin Khlebnikov 	if (vm_flags & VM_PFNMAP)
16054e950f6fSAlexey Dobriyan 		return 0;
16064e950f6fSAlexey Dobriyan 
16074e950f6fSAlexey Dobriyan 	/* Can the mapping track the dirty pages? */
16084e950f6fSAlexey Dobriyan 	return vma->vm_file && vma->vm_file->f_mapping &&
1609f56753acSChristoph Hellwig 		mapping_can_writeback(vma->vm_file->f_mapping);
16104e950f6fSAlexey Dobriyan }
16114e950f6fSAlexey Dobriyan 
1612fc8744adSLinus Torvalds /*
1613fc8744adSLinus Torvalds  * We account for memory if it's a private writeable mapping,
16145a6fe125SMel Gorman  * not hugepages and VM_NORESERVE wasn't set.
1615fc8744adSLinus Torvalds  */
1616ca16d140SKOSAKI Motohiro static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1617fc8744adSLinus Torvalds {
16185a6fe125SMel Gorman 	/*
16195a6fe125SMel Gorman 	 * hugetlb has its own accounting separate from the core VM
16205a6fe125SMel Gorman 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
16215a6fe125SMel Gorman 	 */
16225a6fe125SMel Gorman 	if (file && is_file_hugepages(file))
16235a6fe125SMel Gorman 		return 0;
16245a6fe125SMel Gorman 
1625fc8744adSLinus Torvalds 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1626fc8744adSLinus Torvalds }
1627fc8744adSLinus Torvalds 
16280165ab44SMiklos Szeredi unsigned long mmap_region(struct file *file, unsigned long addr,
1629897ab3e0SMike Rapoport 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
1630897ab3e0SMike Rapoport 		struct list_head *uf)
16310165ab44SMiklos Szeredi {
16320165ab44SMiklos Szeredi 	struct mm_struct *mm = current->mm;
1633d70cec89SMiaohe Lin 	struct vm_area_struct *vma, *prev, *merge;
16340165ab44SMiklos Szeredi 	int error;
16350165ab44SMiklos Szeredi 	unsigned long charged = 0;
16360165ab44SMiklos Szeredi 
1637e8420a8eSCyril Hrubis 	/* Check against address space limit. */
163884638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
1639e8420a8eSCyril Hrubis 		unsigned long nr_pages;
1640e8420a8eSCyril Hrubis 
1641e8420a8eSCyril Hrubis 		/*
1642e8420a8eSCyril Hrubis 		 * MAP_FIXED may remove pages of mappings that intersects with
1643e8420a8eSCyril Hrubis 		 * requested mapping. Account for the pages it would unmap.
1644e8420a8eSCyril Hrubis 		 */
1645e8420a8eSCyril Hrubis 		nr_pages = count_vma_pages_range(mm, addr, addr + len);
1646e8420a8eSCyril Hrubis 
164784638335SKonstantin Khlebnikov 		if (!may_expand_vm(mm, vm_flags,
164884638335SKonstantin Khlebnikov 					(len >> PAGE_SHIFT) - nr_pages))
1649e8420a8eSCyril Hrubis 			return -ENOMEM;
1650e8420a8eSCyril Hrubis 	}
1651e8420a8eSCyril Hrubis 
1652524e00b3SLiam R. Howlett 	/* Clear old maps, set up prev and uf */
1653524e00b3SLiam R. Howlett 	if (munmap_vma_range(mm, addr, len, &prev, uf))
16541da177e4SLinus Torvalds 		return -ENOMEM;
1655fc8744adSLinus Torvalds 	/*
16561da177e4SLinus Torvalds 	 * Private writable mapping: check memory availability
16571da177e4SLinus Torvalds 	 */
16585a6fe125SMel Gorman 	if (accountable_mapping(file, vm_flags)) {
16591da177e4SLinus Torvalds 		charged = len >> PAGE_SHIFT;
1660191c5424SAl Viro 		if (security_vm_enough_memory_mm(mm, charged))
16611da177e4SLinus Torvalds 			return -ENOMEM;
16621da177e4SLinus Torvalds 		vm_flags |= VM_ACCOUNT;
16631da177e4SLinus Torvalds 	}
16641da177e4SLinus Torvalds 
16651da177e4SLinus Torvalds 	/*
1666de33c8dbSLinus Torvalds 	 * Can we just expand an old mapping?
16671da177e4SLinus Torvalds 	 */
166819a809afSAndrea Arcangeli 	vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
16699a10064fSColin Cross 			NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1670ba470de4SRik van Riel 	if (vma)
16711da177e4SLinus Torvalds 		goto out;
16721da177e4SLinus Torvalds 
16731da177e4SLinus Torvalds 	/*
16741da177e4SLinus Torvalds 	 * Determine the object being mapped and call the appropriate
16751da177e4SLinus Torvalds 	 * specific mapper. the address has already been validated, but
16761da177e4SLinus Torvalds 	 * not unmapped, but the maps are removed from the list.
16771da177e4SLinus Torvalds 	 */
1678490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
16791da177e4SLinus Torvalds 	if (!vma) {
16801da177e4SLinus Torvalds 		error = -ENOMEM;
16811da177e4SLinus Torvalds 		goto unacct_error;
16821da177e4SLinus Torvalds 	}
16831da177e4SLinus Torvalds 
16841da177e4SLinus Torvalds 	vma->vm_start = addr;
16851da177e4SLinus Torvalds 	vma->vm_end = addr + len;
16861da177e4SLinus Torvalds 	vma->vm_flags = vm_flags;
16873ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(vm_flags);
16881da177e4SLinus Torvalds 	vma->vm_pgoff = pgoff;
16891da177e4SLinus Torvalds 
16901da177e4SLinus Torvalds 	if (file) {
16914bb5f5d9SDavid Herrmann 		if (vm_flags & VM_SHARED) {
16924bb5f5d9SDavid Herrmann 			error = mapping_map_writable(file->f_mapping);
16934bb5f5d9SDavid Herrmann 			if (error)
16948d0920bdSDavid Hildenbrand 				goto free_vma;
16954bb5f5d9SDavid Herrmann 		}
16964bb5f5d9SDavid Herrmann 
1697cb0942b8SAl Viro 		vma->vm_file = get_file(file);
1698f74ac015SMiklos Szeredi 		error = call_mmap(file, vma);
16991da177e4SLinus Torvalds 		if (error)
17001da177e4SLinus Torvalds 			goto unmap_and_free_vma;
17011da177e4SLinus Torvalds 
1702309d08d9SLiu Zixian 		/* Can addr have changed??
1703309d08d9SLiu Zixian 		 *
1704309d08d9SLiu Zixian 		 * Answer: Yes, several device drivers can do it in their
1705309d08d9SLiu Zixian 		 *         f_op->mmap method. -DaveM
1706309d08d9SLiu Zixian 		 * Bug: If addr is changed, prev, rb_link, rb_parent should
1707309d08d9SLiu Zixian 		 *      be updated for vma_link()
1708309d08d9SLiu Zixian 		 */
1709309d08d9SLiu Zixian 		WARN_ON_ONCE(addr != vma->vm_start);
1710309d08d9SLiu Zixian 
1711309d08d9SLiu Zixian 		addr = vma->vm_start;
1712309d08d9SLiu Zixian 
1713d70cec89SMiaohe Lin 		/* If vm_flags changed after call_mmap(), we should try merge vma again
1714d70cec89SMiaohe Lin 		 * as we may succeed this time.
1715d70cec89SMiaohe Lin 		 */
1716d70cec89SMiaohe Lin 		if (unlikely(vm_flags != vma->vm_flags && prev)) {
1717d70cec89SMiaohe Lin 			merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
17189a10064fSColin Cross 				NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1719d70cec89SMiaohe Lin 			if (merge) {
1720bc4fe4cdSMiaohe Lin 				/* ->mmap() can change vma->vm_file and fput the original file. So
1721bc4fe4cdSMiaohe Lin 				 * fput the vma->vm_file here or we would add an extra fput for file
1722bc4fe4cdSMiaohe Lin 				 * and cause general protection fault ultimately.
1723bc4fe4cdSMiaohe Lin 				 */
1724bc4fe4cdSMiaohe Lin 				fput(vma->vm_file);
1725d70cec89SMiaohe Lin 				vm_area_free(vma);
1726d70cec89SMiaohe Lin 				vma = merge;
1727309d08d9SLiu Zixian 				/* Update vm_flags to pick up the change. */
1728d70cec89SMiaohe Lin 				vm_flags = vma->vm_flags;
1729d70cec89SMiaohe Lin 				goto unmap_writable;
1730d70cec89SMiaohe Lin 			}
1731d70cec89SMiaohe Lin 		}
1732d70cec89SMiaohe Lin 
17331da177e4SLinus Torvalds 		vm_flags = vma->vm_flags;
1734f8dbf0a7SHuang Shijie 	} else if (vm_flags & VM_SHARED) {
1735f8dbf0a7SHuang Shijie 		error = shmem_zero_setup(vma);
1736f8dbf0a7SHuang Shijie 		if (error)
1737f8dbf0a7SHuang Shijie 			goto free_vma;
1738bfd40eafSKirill A. Shutemov 	} else {
1739bfd40eafSKirill A. Shutemov 		vma_set_anonymous(vma);
1740f8dbf0a7SHuang Shijie 	}
17411da177e4SLinus Torvalds 
1742c462ac28SCatalin Marinas 	/* Allow architectures to sanity-check the vm_flags */
1743c462ac28SCatalin Marinas 	if (!arch_validate_flags(vma->vm_flags)) {
1744c462ac28SCatalin Marinas 		error = -EINVAL;
1745c462ac28SCatalin Marinas 		if (file)
1746c462ac28SCatalin Marinas 			goto unmap_and_free_vma;
1747c462ac28SCatalin Marinas 		else
1748c462ac28SCatalin Marinas 			goto free_vma;
1749c462ac28SCatalin Marinas 	}
1750c462ac28SCatalin Marinas 
1751524e00b3SLiam R. Howlett 	if (vma_link(mm, vma, prev)) {
1752d4af56c5SLiam R. Howlett 		error = -ENOMEM;
1753d4af56c5SLiam R. Howlett 		if (file)
1754d4af56c5SLiam R. Howlett 			goto unmap_and_free_vma;
1755d4af56c5SLiam R. Howlett 		else
1756d4af56c5SLiam R. Howlett 			goto free_vma;
1757d4af56c5SLiam R. Howlett 	}
1758613bec09SYang Shi 
1759613bec09SYang Shi 	/*
1760613bec09SYang Shi 	 * vma_merge() calls khugepaged_enter_vma() either, the below
1761613bec09SYang Shi 	 * call covers the non-merge case.
1762613bec09SYang Shi 	 */
1763613bec09SYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
1764613bec09SYang Shi 
17654d3d5b41SOleg Nesterov 	/* Once vma denies write, undo our temporary denial count */
1766d70cec89SMiaohe Lin unmap_writable:
17678d0920bdSDavid Hildenbrand 	if (file && vm_flags & VM_SHARED)
17684bb5f5d9SDavid Herrmann 		mapping_unmap_writable(file->f_mapping);
1769e8686772SOleg Nesterov 	file = vma->vm_file;
17701da177e4SLinus Torvalds out:
1771cdd6c482SIngo Molnar 	perf_event_mmap(vma);
17720a4a9391SPeter Zijlstra 
177384638335SKonstantin Khlebnikov 	vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
17741da177e4SLinus Torvalds 	if (vm_flags & VM_LOCKED) {
1775e1fb4a08SDave Jiang 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
1776e1fb4a08SDave Jiang 					is_vm_hugetlb_page(vma) ||
1777e1fb4a08SDave Jiang 					vma == get_gate_vma(current->mm))
1778de60f5f1SEric B Munson 			vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1779e1fb4a08SDave Jiang 		else
1780e1fb4a08SDave Jiang 			mm->locked_vm += (len >> PAGE_SHIFT);
1781bebeb3d6SMichel Lespinasse 	}
17822b144498SSrikar Dronamraju 
1783c7a3a88cSOleg Nesterov 	if (file)
1784c7a3a88cSOleg Nesterov 		uprobe_mmap(vma);
17852b144498SSrikar Dronamraju 
1786d9104d1cSCyrill Gorcunov 	/*
1787d9104d1cSCyrill Gorcunov 	 * New (or expanded) vma always get soft dirty status.
1788d9104d1cSCyrill Gorcunov 	 * Otherwise user-space soft-dirty page tracker won't
1789d9104d1cSCyrill Gorcunov 	 * be able to distinguish situation when vma area unmapped,
1790d9104d1cSCyrill Gorcunov 	 * then new mapped in-place (which must be aimed as
1791d9104d1cSCyrill Gorcunov 	 * a completely new data area).
1792d9104d1cSCyrill Gorcunov 	 */
1793d9104d1cSCyrill Gorcunov 	vma->vm_flags |= VM_SOFTDIRTY;
1794d9104d1cSCyrill Gorcunov 
179564e45507SPeter Feiner 	vma_set_page_prot(vma);
179664e45507SPeter Feiner 
17971da177e4SLinus Torvalds 	return addr;
17981da177e4SLinus Torvalds 
17991da177e4SLinus Torvalds unmap_and_free_vma:
18001527f926SChristian König 	fput(vma->vm_file);
18011da177e4SLinus Torvalds 	vma->vm_file = NULL;
18021da177e4SLinus Torvalds 
18031da177e4SLinus Torvalds 	/* Undo any partial mapping done by a device driver. */
1804e0da382cSHugh Dickins 	unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
18054bb5f5d9SDavid Herrmann 	if (vm_flags & VM_SHARED)
18064bb5f5d9SDavid Herrmann 		mapping_unmap_writable(file->f_mapping);
18071da177e4SLinus Torvalds free_vma:
18083928d4f5SLinus Torvalds 	vm_area_free(vma);
18091da177e4SLinus Torvalds unacct_error:
18101da177e4SLinus Torvalds 	if (charged)
18111da177e4SLinus Torvalds 		vm_unacct_memory(charged);
18121da177e4SLinus Torvalds 	return error;
18131da177e4SLinus Torvalds }
18141da177e4SLinus Torvalds 
18153499a131SLiam R. Howlett /**
18163499a131SLiam R. Howlett  * unmapped_area() - Find an area between the low_limit and the high_limit with
18173499a131SLiam R. Howlett  * the correct alignment and offset, all from @info. Note: current->mm is used
18183499a131SLiam R. Howlett  * for the search.
18193499a131SLiam R. Howlett  *
18203499a131SLiam R. Howlett  * @info: The unmapped area information including the range (low_limit -
18213499a131SLiam R. Howlett  * hight_limit), the alignment offset and mask.
18223499a131SLiam R. Howlett  *
18233499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
18243499a131SLiam R. Howlett  */
1825baceaf1cSJaewon Kim static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1826db4fbfb9SMichel Lespinasse {
18273499a131SLiam R. Howlett 	unsigned long length, gap;
1828db4fbfb9SMichel Lespinasse 
18293499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1830db4fbfb9SMichel Lespinasse 
1831db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1832db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1833db4fbfb9SMichel Lespinasse 	if (length < info->length)
1834db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1835db4fbfb9SMichel Lespinasse 
18363499a131SLiam R. Howlett 	if (mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
18373499a131SLiam R. Howlett 				  length))
18383499a131SLiam R. Howlett 		return -ENOMEM;
18393499a131SLiam R. Howlett 
1840d4af56c5SLiam R. Howlett 	gap = mas.index;
1841d4af56c5SLiam R. Howlett 	gap += (info->align_offset - gap) & info->align_mask;
18423499a131SLiam R. Howlett 	return gap;
1843db4fbfb9SMichel Lespinasse }
1844db4fbfb9SMichel Lespinasse 
18453499a131SLiam R. Howlett /**
18463499a131SLiam R. Howlett  * unmapped_area_topdown() - Find an area between the low_limit and the
18473499a131SLiam R. Howlett  * high_limit with * the correct alignment and offset at the highest available
18483499a131SLiam R. Howlett  * address, all from @info. Note: current->mm is used for the search.
18493499a131SLiam R. Howlett  *
18503499a131SLiam R. Howlett  * @info: The unmapped area information including the range (low_limit -
18513499a131SLiam R. Howlett  * hight_limit), the alignment offset and mask.
18523499a131SLiam R. Howlett  *
18533499a131SLiam R. Howlett  * Return: A memory address or -ENOMEM.
18543499a131SLiam R. Howlett  */
1855baceaf1cSJaewon Kim static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1856db4fbfb9SMichel Lespinasse {
18573499a131SLiam R. Howlett 	unsigned long length, gap;
1858d4af56c5SLiam R. Howlett 
18593499a131SLiam R. Howlett 	MA_STATE(mas, &current->mm->mm_mt, 0, 0);
1860db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1861db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1862db4fbfb9SMichel Lespinasse 	if (length < info->length)
1863db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1864db4fbfb9SMichel Lespinasse 
18653499a131SLiam R. Howlett 	if (mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
18663499a131SLiam R. Howlett 				length))
18673499a131SLiam R. Howlett 		return -ENOMEM;
18683499a131SLiam R. Howlett 
1869d4af56c5SLiam R. Howlett 	gap = mas.last + 1 - info->length;
1870d4af56c5SLiam R. Howlett 	gap -= (gap - info->align_offset) & info->align_mask;
18713499a131SLiam R. Howlett 	return gap;
1872db4fbfb9SMichel Lespinasse }
1873db4fbfb9SMichel Lespinasse 
1874baceaf1cSJaewon Kim /*
1875baceaf1cSJaewon Kim  * Search for an unmapped address range.
1876baceaf1cSJaewon Kim  *
1877baceaf1cSJaewon Kim  * We are looking for a range that:
1878baceaf1cSJaewon Kim  * - does not intersect with any VMA;
1879baceaf1cSJaewon Kim  * - is contained within the [low_limit, high_limit) interval;
1880baceaf1cSJaewon Kim  * - is at least the desired size.
1881baceaf1cSJaewon Kim  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
1882baceaf1cSJaewon Kim  */
1883baceaf1cSJaewon Kim unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
1884baceaf1cSJaewon Kim {
1885df529cabSJaewon Kim 	unsigned long addr;
1886df529cabSJaewon Kim 
1887baceaf1cSJaewon Kim 	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
1888df529cabSJaewon Kim 		addr = unmapped_area_topdown(info);
1889baceaf1cSJaewon Kim 	else
1890df529cabSJaewon Kim 		addr = unmapped_area(info);
1891df529cabSJaewon Kim 
1892df529cabSJaewon Kim 	trace_vm_unmapped_area(addr, info);
1893df529cabSJaewon Kim 	return addr;
1894baceaf1cSJaewon Kim }
1895f6795053SSteve Capper 
18961da177e4SLinus Torvalds /* Get an address range which is currently unmapped.
18971da177e4SLinus Torvalds  * For shmat() with addr=0.
18981da177e4SLinus Torvalds  *
18991da177e4SLinus Torvalds  * Ugly calling convention alert:
19001da177e4SLinus Torvalds  * Return value with the low bits set means error value,
19011da177e4SLinus Torvalds  * ie
19021da177e4SLinus Torvalds  *	if (ret & ~PAGE_MASK)
19031da177e4SLinus Torvalds  *		error = ret;
19041da177e4SLinus Torvalds  *
19051da177e4SLinus Torvalds  * This function "knows" that -ENOMEM has the bits set.
19061da177e4SLinus Torvalds  */
19071da177e4SLinus Torvalds unsigned long
19084b439e25SChristophe Leroy generic_get_unmapped_area(struct file *filp, unsigned long addr,
19094b439e25SChristophe Leroy 			  unsigned long len, unsigned long pgoff,
19104b439e25SChristophe Leroy 			  unsigned long flags)
19111da177e4SLinus Torvalds {
19121da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
19131be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
1914db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
19152cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
19161da177e4SLinus Torvalds 
1917f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
19181da177e4SLinus Torvalds 		return -ENOMEM;
19191da177e4SLinus Torvalds 
192006abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
192106abdfb4SBenjamin Herrenschmidt 		return addr;
192206abdfb4SBenjamin Herrenschmidt 
19231da177e4SLinus Torvalds 	if (addr) {
19241da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
19251be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1926f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
19271be7107fSHugh Dickins 		    (!vma || addr + len <= vm_start_gap(vma)) &&
19281be7107fSHugh Dickins 		    (!prev || addr >= vm_end_gap(prev)))
19291da177e4SLinus Torvalds 			return addr;
19301da177e4SLinus Torvalds 	}
19311da177e4SLinus Torvalds 
1932db4fbfb9SMichel Lespinasse 	info.flags = 0;
1933db4fbfb9SMichel Lespinasse 	info.length = len;
19344e99b021SHeiko Carstens 	info.low_limit = mm->mmap_base;
1935f6795053SSteve Capper 	info.high_limit = mmap_end;
1936db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
193709ef5283SJaewon Kim 	info.align_offset = 0;
1938db4fbfb9SMichel Lespinasse 	return vm_unmapped_area(&info);
19391da177e4SLinus Torvalds }
19404b439e25SChristophe Leroy 
19414b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA
19424b439e25SChristophe Leroy unsigned long
19434b439e25SChristophe Leroy arch_get_unmapped_area(struct file *filp, unsigned long addr,
19444b439e25SChristophe Leroy 		       unsigned long len, unsigned long pgoff,
19454b439e25SChristophe Leroy 		       unsigned long flags)
19464b439e25SChristophe Leroy {
19474b439e25SChristophe Leroy 	return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
19484b439e25SChristophe Leroy }
19491da177e4SLinus Torvalds #endif
19501da177e4SLinus Torvalds 
19511da177e4SLinus Torvalds /*
19521da177e4SLinus Torvalds  * This mmap-allocator allocates new areas top-down from below the
19531da177e4SLinus Torvalds  * stack's low limit (the base):
19541da177e4SLinus Torvalds  */
19551da177e4SLinus Torvalds unsigned long
19564b439e25SChristophe Leroy generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
195743cca0b1SYang Fan 				  unsigned long len, unsigned long pgoff,
195843cca0b1SYang Fan 				  unsigned long flags)
19591da177e4SLinus Torvalds {
19601be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
19611da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
1962db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
19632cb4de08SChristophe Leroy 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
19641da177e4SLinus Torvalds 
19651da177e4SLinus Torvalds 	/* requested length too big for entire address space */
1966f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
19671da177e4SLinus Torvalds 		return -ENOMEM;
19681da177e4SLinus Torvalds 
196906abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
197006abdfb4SBenjamin Herrenschmidt 		return addr;
197106abdfb4SBenjamin Herrenschmidt 
19721da177e4SLinus Torvalds 	/* requesting a specific address */
19731da177e4SLinus Torvalds 	if (addr) {
19741da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
19751be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
1976f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
19771be7107fSHugh Dickins 				(!vma || addr + len <= vm_start_gap(vma)) &&
19781be7107fSHugh Dickins 				(!prev || addr >= vm_end_gap(prev)))
19791da177e4SLinus Torvalds 			return addr;
19801da177e4SLinus Torvalds 	}
19811da177e4SLinus Torvalds 
1982db4fbfb9SMichel Lespinasse 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
1983db4fbfb9SMichel Lespinasse 	info.length = len;
19842afc745fSAkira Takeuchi 	info.low_limit = max(PAGE_SIZE, mmap_min_addr);
1985f6795053SSteve Capper 	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
1986db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
198709ef5283SJaewon Kim 	info.align_offset = 0;
1988db4fbfb9SMichel Lespinasse 	addr = vm_unmapped_area(&info);
1989b716ad95SXiao Guangrong 
19901da177e4SLinus Torvalds 	/*
19911da177e4SLinus Torvalds 	 * A failed mmap() very likely causes application failure,
19921da177e4SLinus Torvalds 	 * so fall back to the bottom-up function here. This scenario
19931da177e4SLinus Torvalds 	 * can happen with large stack limits and large mmap()
19941da177e4SLinus Torvalds 	 * allocations.
19951da177e4SLinus Torvalds 	 */
1996de1741a1SAlexander Kuleshov 	if (offset_in_page(addr)) {
1997db4fbfb9SMichel Lespinasse 		VM_BUG_ON(addr != -ENOMEM);
1998db4fbfb9SMichel Lespinasse 		info.flags = 0;
1999db4fbfb9SMichel Lespinasse 		info.low_limit = TASK_UNMAPPED_BASE;
2000f6795053SSteve Capper 		info.high_limit = mmap_end;
2001db4fbfb9SMichel Lespinasse 		addr = vm_unmapped_area(&info);
2002db4fbfb9SMichel Lespinasse 	}
20031da177e4SLinus Torvalds 
20041da177e4SLinus Torvalds 	return addr;
20051da177e4SLinus Torvalds }
20064b439e25SChristophe Leroy 
20074b439e25SChristophe Leroy #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
20084b439e25SChristophe Leroy unsigned long
20094b439e25SChristophe Leroy arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
20104b439e25SChristophe Leroy 			       unsigned long len, unsigned long pgoff,
20114b439e25SChristophe Leroy 			       unsigned long flags)
20124b439e25SChristophe Leroy {
20134b439e25SChristophe Leroy 	return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
20144b439e25SChristophe Leroy }
20151da177e4SLinus Torvalds #endif
20161da177e4SLinus Torvalds 
20171da177e4SLinus Torvalds unsigned long
20181da177e4SLinus Torvalds get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
20191da177e4SLinus Torvalds 		unsigned long pgoff, unsigned long flags)
20201da177e4SLinus Torvalds {
202106abdfb4SBenjamin Herrenschmidt 	unsigned long (*get_area)(struct file *, unsigned long,
202206abdfb4SBenjamin Herrenschmidt 				  unsigned long, unsigned long, unsigned long);
202307ab67c8SLinus Torvalds 
20249206de95SAl Viro 	unsigned long error = arch_mmap_check(addr, len, flags);
20259206de95SAl Viro 	if (error)
20269206de95SAl Viro 		return error;
20279206de95SAl Viro 
20289206de95SAl Viro 	/* Careful about overflows.. */
20299206de95SAl Viro 	if (len > TASK_SIZE)
20309206de95SAl Viro 		return -ENOMEM;
20319206de95SAl Viro 
203207ab67c8SLinus Torvalds 	get_area = current->mm->get_unmapped_area;
2033c01d5b30SHugh Dickins 	if (file) {
2034c01d5b30SHugh Dickins 		if (file->f_op->get_unmapped_area)
203507ab67c8SLinus Torvalds 			get_area = file->f_op->get_unmapped_area;
2036c01d5b30SHugh Dickins 	} else if (flags & MAP_SHARED) {
2037c01d5b30SHugh Dickins 		/*
2038c01d5b30SHugh Dickins 		 * mmap_region() will call shmem_zero_setup() to create a file,
2039c01d5b30SHugh Dickins 		 * so use shmem's get_unmapped_area in case it can be huge.
204045e55300SPeter Collingbourne 		 * do_mmap() will clear pgoff, so match alignment.
2041c01d5b30SHugh Dickins 		 */
2042c01d5b30SHugh Dickins 		pgoff = 0;
2043c01d5b30SHugh Dickins 		get_area = shmem_get_unmapped_area;
2044f35b5d7dSRik van Riel 	} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
2045f35b5d7dSRik van Riel 		/* Ensures that larger anonymous mappings are THP aligned. */
2046f35b5d7dSRik van Riel 		get_area = thp_get_unmapped_area;
2047c01d5b30SHugh Dickins 	}
2048c01d5b30SHugh Dickins 
204907ab67c8SLinus Torvalds 	addr = get_area(file, addr, len, pgoff, flags);
205007ab67c8SLinus Torvalds 	if (IS_ERR_VALUE(addr))
205107ab67c8SLinus Torvalds 		return addr;
205207ab67c8SLinus Torvalds 
20531da177e4SLinus Torvalds 	if (addr > TASK_SIZE - len)
20541da177e4SLinus Torvalds 		return -ENOMEM;
2055de1741a1SAlexander Kuleshov 	if (offset_in_page(addr))
20561da177e4SLinus Torvalds 		return -EINVAL;
205706abdfb4SBenjamin Herrenschmidt 
20589ac4ed4bSAl Viro 	error = security_mmap_addr(addr);
20599ac4ed4bSAl Viro 	return error ? error : addr;
20601da177e4SLinus Torvalds }
20611da177e4SLinus Torvalds 
20621da177e4SLinus Torvalds EXPORT_SYMBOL(get_unmapped_area);
20631da177e4SLinus Torvalds 
2064be8432e7SLiam R. Howlett /**
2065be8432e7SLiam R. Howlett  * find_vma() - Find the VMA for a given address, or the next VMA.
2066be8432e7SLiam R. Howlett  * @mm: The mm_struct to check
2067be8432e7SLiam R. Howlett  * @addr: The address
2068be8432e7SLiam R. Howlett  *
2069be8432e7SLiam R. Howlett  * Returns: The VMA associated with addr, or the next VMA.
2070be8432e7SLiam R. Howlett  * May return %NULL in the case of no VMA at addr or above.
2071be8432e7SLiam R. Howlett  */
20721da177e4SLinus Torvalds struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
20731da177e4SLinus Torvalds {
2074615d6e87SDavidlohr Bueso 	struct vm_area_struct *vma;
2075be8432e7SLiam R. Howlett 	unsigned long index = addr;
20761da177e4SLinus Torvalds 
20775b78ed24SLuigi Rizzo 	mmap_assert_locked(mm);
20781da177e4SLinus Torvalds 	/* Check the cache first. */
2079615d6e87SDavidlohr Bueso 	vma = vmacache_find(mm, addr);
2080615d6e87SDavidlohr Bueso 	if (likely(vma))
2081615d6e87SDavidlohr Bueso 		return vma;
20821da177e4SLinus Torvalds 
2083be8432e7SLiam R. Howlett 	vma = mt_find(&mm->mm_mt, &index, ULONG_MAX);
20841da177e4SLinus Torvalds 	if (vma)
2085615d6e87SDavidlohr Bueso 		vmacache_update(addr, vma);
20861da177e4SLinus Torvalds 	return vma;
20871da177e4SLinus Torvalds }
20881da177e4SLinus Torvalds EXPORT_SYMBOL(find_vma);
20891da177e4SLinus Torvalds 
20907fdbd37dSLiam R. Howlett /**
20917fdbd37dSLiam R. Howlett  * find_vma_prev() - Find the VMA for a given address, or the next vma and
20927fdbd37dSLiam R. Howlett  * set %pprev to the previous VMA, if any.
20937fdbd37dSLiam R. Howlett  * @mm: The mm_struct to check
20947fdbd37dSLiam R. Howlett  * @addr: The address
20957fdbd37dSLiam R. Howlett  * @pprev: The pointer to set to the previous VMA
20967fdbd37dSLiam R. Howlett  *
20977fdbd37dSLiam R. Howlett  * Note that RCU lock is missing here since the external mmap_lock() is used
20987fdbd37dSLiam R. Howlett  * instead.
20997fdbd37dSLiam R. Howlett  *
21007fdbd37dSLiam R. Howlett  * Returns: The VMA associated with @addr, or the next vma.
21017fdbd37dSLiam R. Howlett  * May return %NULL in the case of no vma at addr or above.
21026bd4837dSKOSAKI Motohiro  */
21031da177e4SLinus Torvalds struct vm_area_struct *
21041da177e4SLinus Torvalds find_vma_prev(struct mm_struct *mm, unsigned long addr,
21051da177e4SLinus Torvalds 			struct vm_area_struct **pprev)
21061da177e4SLinus Torvalds {
21076bd4837dSKOSAKI Motohiro 	struct vm_area_struct *vma;
21087fdbd37dSLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, addr, addr);
21091da177e4SLinus Torvalds 
21107fdbd37dSLiam R. Howlett 	vma = mas_walk(&mas);
21117fdbd37dSLiam R. Howlett 	*pprev = mas_prev(&mas, 0);
21127fdbd37dSLiam R. Howlett 	if (!vma)
21137fdbd37dSLiam R. Howlett 		vma = mas_next(&mas, ULONG_MAX);
21146bd4837dSKOSAKI Motohiro 	return vma;
21151da177e4SLinus Torvalds }
21161da177e4SLinus Torvalds 
21171da177e4SLinus Torvalds /*
21181da177e4SLinus Torvalds  * Verify that the stack growth is acceptable and
21191da177e4SLinus Torvalds  * update accounting. This is shared with both the
21201da177e4SLinus Torvalds  * grow-up and grow-down cases.
21211da177e4SLinus Torvalds  */
21221be7107fSHugh Dickins static int acct_stack_growth(struct vm_area_struct *vma,
21231be7107fSHugh Dickins 			     unsigned long size, unsigned long grow)
21241da177e4SLinus Torvalds {
21251da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
21261be7107fSHugh Dickins 	unsigned long new_start;
21271da177e4SLinus Torvalds 
21281da177e4SLinus Torvalds 	/* address space limit tests */
212984638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vma->vm_flags, grow))
21301da177e4SLinus Torvalds 		return -ENOMEM;
21311da177e4SLinus Torvalds 
21321da177e4SLinus Torvalds 	/* Stack limit test */
213324c79d8eSKrzysztof Opasiak 	if (size > rlimit(RLIMIT_STACK))
21341da177e4SLinus Torvalds 		return -ENOMEM;
21351da177e4SLinus Torvalds 
21361da177e4SLinus Torvalds 	/* mlock limit tests */
2137c5d8a364SMiaohe Lin 	if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
21381da177e4SLinus Torvalds 		return -ENOMEM;
21391da177e4SLinus Torvalds 
21400d59a01bSAdam Litke 	/* Check to ensure the stack will not grow into a hugetlb-only region */
21410d59a01bSAdam Litke 	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
21420d59a01bSAdam Litke 			vma->vm_end - size;
21430d59a01bSAdam Litke 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
21440d59a01bSAdam Litke 		return -EFAULT;
21450d59a01bSAdam Litke 
21461da177e4SLinus Torvalds 	/*
21471da177e4SLinus Torvalds 	 * Overcommit..  This must be the final test, as it will
21481da177e4SLinus Torvalds 	 * update security statistics.
21491da177e4SLinus Torvalds 	 */
215005fa199dSHugh Dickins 	if (security_vm_enough_memory_mm(mm, grow))
21511da177e4SLinus Torvalds 		return -ENOMEM;
21521da177e4SLinus Torvalds 
21531da177e4SLinus Torvalds 	return 0;
21541da177e4SLinus Torvalds }
21551da177e4SLinus Torvalds 
215646dea3d0SHugh Dickins #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
21571da177e4SLinus Torvalds /*
215846dea3d0SHugh Dickins  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
215946dea3d0SHugh Dickins  * vma is the last one with address > vma->vm_end.  Have to extend vma.
21601da177e4SLinus Torvalds  */
216146dea3d0SHugh Dickins int expand_upwards(struct vm_area_struct *vma, unsigned long address)
21621da177e4SLinus Torvalds {
216309357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
21641be7107fSHugh Dickins 	struct vm_area_struct *next;
21651be7107fSHugh Dickins 	unsigned long gap_addr;
216612352d3cSKonstantin Khlebnikov 	int error = 0;
2167d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
21681da177e4SLinus Torvalds 
21691da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSUP))
21701da177e4SLinus Torvalds 		return -EFAULT;
21711da177e4SLinus Torvalds 
2172bd726c90SHelge Deller 	/* Guard against exceeding limits of the address space. */
21731be7107fSHugh Dickins 	address &= PAGE_MASK;
217437511fb5SHelge Deller 	if (address >= (TASK_SIZE & PAGE_MASK))
217512352d3cSKonstantin Khlebnikov 		return -ENOMEM;
2176bd726c90SHelge Deller 	address += PAGE_SIZE;
217712352d3cSKonstantin Khlebnikov 
21781be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
21791be7107fSHugh Dickins 	gap_addr = address + stack_guard_gap;
2180bd726c90SHelge Deller 
2181bd726c90SHelge Deller 	/* Guard against overflow */
2182bd726c90SHelge Deller 	if (gap_addr < address || gap_addr > TASK_SIZE)
2183bd726c90SHelge Deller 		gap_addr = TASK_SIZE;
2184bd726c90SHelge Deller 
21851be7107fSHugh Dickins 	next = vma->vm_next;
21863122e80eSAnshuman Khandual 	if (next && next->vm_start < gap_addr && vma_is_accessible(next)) {
21871be7107fSHugh Dickins 		if (!(next->vm_flags & VM_GROWSUP))
21881be7107fSHugh Dickins 			return -ENOMEM;
21891be7107fSHugh Dickins 		/* Check that both stack segments have the same anon_vma? */
21901be7107fSHugh Dickins 	}
21911be7107fSHugh Dickins 
2192d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
21931da177e4SLinus Torvalds 		return -ENOMEM;
21941da177e4SLinus Torvalds 
2195d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
2196d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
2197d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
2198d4af56c5SLiam R. Howlett 		return -ENOMEM;
2199d4af56c5SLiam R. Howlett 	}
2200d4af56c5SLiam R. Howlett 
22011da177e4SLinus Torvalds 	/*
22021da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2203c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
22041da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
22051da177e4SLinus Torvalds 	 */
220612352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
22071da177e4SLinus Torvalds 
22081da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
22091da177e4SLinus Torvalds 	if (address > vma->vm_end) {
22101da177e4SLinus Torvalds 		unsigned long size, grow;
22111da177e4SLinus Torvalds 
22121da177e4SLinus Torvalds 		size = address - vma->vm_start;
22131da177e4SLinus Torvalds 		grow = (address - vma->vm_end) >> PAGE_SHIFT;
22141da177e4SLinus Torvalds 
221542c36f63SHugh Dickins 		error = -ENOMEM;
221642c36f63SHugh Dickins 		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
22171da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
22183af9e859SEric B Munson 			if (!error) {
22194128997bSMichel Lespinasse 				/*
2220524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
2221524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
2222524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
2223524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
2224524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
2225524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
2226524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
22274128997bSMichel Lespinasse 				 */
222809357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
222987e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
223009357814SOleg Nesterov 					mm->locked_vm += grow;
223184638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2232bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
22331da177e4SLinus Torvalds 				vma->vm_end = address;
2234d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2235d4af56c5SLiam R. Howlett 				vma_mas_store(vma, &mas);
2236bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
2237524e00b3SLiam R. Howlett 				if (!vma->vm_next)
22381be7107fSHugh Dickins 					mm->highest_vm_end = vm_end_gap(vma);
223909357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
22404128997bSMichel Lespinasse 
22413af9e859SEric B Munson 				perf_event_mmap(vma);
22423af9e859SEric B Munson 			}
22431da177e4SLinus Torvalds 		}
224442c36f63SHugh Dickins 	}
224512352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2246c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2247d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
22481da177e4SLinus Torvalds 	return error;
22491da177e4SLinus Torvalds }
225046dea3d0SHugh Dickins #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
225146dea3d0SHugh Dickins 
22521da177e4SLinus Torvalds /*
22531da177e4SLinus Torvalds  * vma is the first one with address < vma->vm_start.  Have to extend vma.
22541da177e4SLinus Torvalds  */
2255524e00b3SLiam R. Howlett int expand_downwards(struct vm_area_struct *vma, unsigned long address)
22561da177e4SLinus Torvalds {
225709357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
22581be7107fSHugh Dickins 	struct vm_area_struct *prev;
22590a1d5299SJann Horn 	int error = 0;
2260d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
22611da177e4SLinus Torvalds 
22628869477aSEric Paris 	address &= PAGE_MASK;
22630a1d5299SJann Horn 	if (address < mmap_min_addr)
22640a1d5299SJann Horn 		return -EPERM;
22658869477aSEric Paris 
22661be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
22671be7107fSHugh Dickins 	prev = vma->vm_prev;
22681be7107fSHugh Dickins 	/* Check that both stack segments have the same anon_vma? */
226932e4e6d5SOleg Nesterov 	if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
22703122e80eSAnshuman Khandual 			vma_is_accessible(prev)) {
227132e4e6d5SOleg Nesterov 		if (address - prev->vm_end < stack_guard_gap)
227232e4e6d5SOleg Nesterov 			return -ENOMEM;
22731be7107fSHugh Dickins 	}
22741be7107fSHugh Dickins 
2275d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
227612352d3cSKonstantin Khlebnikov 		return -ENOMEM;
22771da177e4SLinus Torvalds 
2278d4af56c5SLiam R. Howlett 	/* We must make sure the anon_vma is allocated. */
2279d4af56c5SLiam R. Howlett 	if (unlikely(anon_vma_prepare(vma))) {
2280d4af56c5SLiam R. Howlett 		mas_destroy(&mas);
2281d4af56c5SLiam R. Howlett 		return -ENOMEM;
2282d4af56c5SLiam R. Howlett 	}
2283d4af56c5SLiam R. Howlett 
22841da177e4SLinus Torvalds 	/*
22851da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2286c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
22871da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
22881da177e4SLinus Torvalds 	 */
228912352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
22901da177e4SLinus Torvalds 
22911da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
22921da177e4SLinus Torvalds 	if (address < vma->vm_start) {
22931da177e4SLinus Torvalds 		unsigned long size, grow;
22941da177e4SLinus Torvalds 
22951da177e4SLinus Torvalds 		size = vma->vm_end - address;
22961da177e4SLinus Torvalds 		grow = (vma->vm_start - address) >> PAGE_SHIFT;
22971da177e4SLinus Torvalds 
2298a626ca6aSLinus Torvalds 		error = -ENOMEM;
2299a626ca6aSLinus Torvalds 		if (grow <= vma->vm_pgoff) {
23001da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
23011da177e4SLinus Torvalds 			if (!error) {
23024128997bSMichel Lespinasse 				/*
2303524e00b3SLiam R. Howlett 				 * We only hold a shared mmap_lock lock here, so
2304524e00b3SLiam R. Howlett 				 * we need to protect against concurrent vma
2305524e00b3SLiam R. Howlett 				 * expansions.  anon_vma_lock_write() doesn't
2306524e00b3SLiam R. Howlett 				 * help here, as we don't guarantee that all
2307524e00b3SLiam R. Howlett 				 * growable vmas in a mm share the same root
2308524e00b3SLiam R. Howlett 				 * anon vma.  So, we reuse mm->page_table_lock
2309524e00b3SLiam R. Howlett 				 * to guard against concurrent vma expansions.
23104128997bSMichel Lespinasse 				 */
231109357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
231287e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
231309357814SOleg Nesterov 					mm->locked_vm += grow;
231484638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2315bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
23161da177e4SLinus Torvalds 				vma->vm_start = address;
23171da177e4SLinus Torvalds 				vma->vm_pgoff -= grow;
2318d4af56c5SLiam R. Howlett 				/* Overwrite old entry in mtree. */
2319d4af56c5SLiam R. Howlett 				vma_mas_store(vma, &mas);
2320bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
232109357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
23224128997bSMichel Lespinasse 
23233af9e859SEric B Munson 				perf_event_mmap(vma);
23241da177e4SLinus Torvalds 			}
23251da177e4SLinus Torvalds 		}
2326a626ca6aSLinus Torvalds 	}
232712352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
2328c791576cSYang Shi 	khugepaged_enter_vma(vma, vma->vm_flags);
2329d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
23301da177e4SLinus Torvalds 	return error;
23311da177e4SLinus Torvalds }
23321da177e4SLinus Torvalds 
23331be7107fSHugh Dickins /* enforced gap between the expanding stack and other mappings. */
23341be7107fSHugh Dickins unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
23351be7107fSHugh Dickins 
23361be7107fSHugh Dickins static int __init cmdline_parse_stack_guard_gap(char *p)
23371be7107fSHugh Dickins {
23381be7107fSHugh Dickins 	unsigned long val;
23391be7107fSHugh Dickins 	char *endptr;
23401be7107fSHugh Dickins 
23411be7107fSHugh Dickins 	val = simple_strtoul(p, &endptr, 10);
23421be7107fSHugh Dickins 	if (!*endptr)
23431be7107fSHugh Dickins 		stack_guard_gap = val << PAGE_SHIFT;
23441be7107fSHugh Dickins 
2345e6d09493SRandy Dunlap 	return 1;
23461be7107fSHugh Dickins }
23471be7107fSHugh Dickins __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
23481be7107fSHugh Dickins 
2349b6a2fea3SOllie Wild #ifdef CONFIG_STACK_GROWSUP
2350b6a2fea3SOllie Wild int expand_stack(struct vm_area_struct *vma, unsigned long address)
2351b6a2fea3SOllie Wild {
2352b6a2fea3SOllie Wild 	return expand_upwards(vma, address);
2353b6a2fea3SOllie Wild }
2354b6a2fea3SOllie Wild 
2355b6a2fea3SOllie Wild struct vm_area_struct *
2356b6a2fea3SOllie Wild find_extend_vma(struct mm_struct *mm, unsigned long addr)
2357b6a2fea3SOllie Wild {
2358b6a2fea3SOllie Wild 	struct vm_area_struct *vma, *prev;
2359b6a2fea3SOllie Wild 
2360b6a2fea3SOllie Wild 	addr &= PAGE_MASK;
2361b6a2fea3SOllie Wild 	vma = find_vma_prev(mm, addr, &prev);
2362b6a2fea3SOllie Wild 	if (vma && (vma->vm_start <= addr))
2363b6a2fea3SOllie Wild 		return vma;
23644d45e75aSJann Horn 	if (!prev || expand_stack(prev, addr))
2365b6a2fea3SOllie Wild 		return NULL;
2366cea10a19SMichel Lespinasse 	if (prev->vm_flags & VM_LOCKED)
2367fc05f566SKirill A. Shutemov 		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2368b6a2fea3SOllie Wild 	return prev;
2369b6a2fea3SOllie Wild }
2370b6a2fea3SOllie Wild #else
2371b6a2fea3SOllie Wild int expand_stack(struct vm_area_struct *vma, unsigned long address)
2372b6a2fea3SOllie Wild {
2373b6a2fea3SOllie Wild 	return expand_downwards(vma, address);
2374b6a2fea3SOllie Wild }
2375b6a2fea3SOllie Wild 
23761da177e4SLinus Torvalds struct vm_area_struct *
23771da177e4SLinus Torvalds find_extend_vma(struct mm_struct *mm, unsigned long addr)
23781da177e4SLinus Torvalds {
23791da177e4SLinus Torvalds 	struct vm_area_struct *vma;
23801da177e4SLinus Torvalds 	unsigned long start;
23811da177e4SLinus Torvalds 
23821da177e4SLinus Torvalds 	addr &= PAGE_MASK;
23831da177e4SLinus Torvalds 	vma = find_vma(mm, addr);
23841da177e4SLinus Torvalds 	if (!vma)
23851da177e4SLinus Torvalds 		return NULL;
23861da177e4SLinus Torvalds 	if (vma->vm_start <= addr)
23871da177e4SLinus Torvalds 		return vma;
23881da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSDOWN))
23891da177e4SLinus Torvalds 		return NULL;
23901da177e4SLinus Torvalds 	start = vma->vm_start;
23911da177e4SLinus Torvalds 	if (expand_stack(vma, addr))
23921da177e4SLinus Torvalds 		return NULL;
2393cea10a19SMichel Lespinasse 	if (vma->vm_flags & VM_LOCKED)
2394fc05f566SKirill A. Shutemov 		populate_vma_page_range(vma, addr, start, NULL);
23951da177e4SLinus Torvalds 	return vma;
23961da177e4SLinus Torvalds }
23971da177e4SLinus Torvalds #endif
23981da177e4SLinus Torvalds 
2399e1d6d01aSJesse Barnes EXPORT_SYMBOL_GPL(find_extend_vma);
2400e1d6d01aSJesse Barnes 
24012c0b3814SHugh Dickins /*
24022c0b3814SHugh Dickins  * Ok - we have the memory areas we should free on the vma list,
24032c0b3814SHugh Dickins  * so release them, and do the vma updates.
24041da177e4SLinus Torvalds  *
24052c0b3814SHugh Dickins  * Called with the mm semaphore held.
24061da177e4SLinus Torvalds  */
24072c0b3814SHugh Dickins static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
24081da177e4SLinus Torvalds {
24094f74d2c8SLinus Torvalds 	unsigned long nr_accounted = 0;
24104f74d2c8SLinus Torvalds 
2411365e9c87SHugh Dickins 	/* Update high watermark before we lower total_vm */
2412365e9c87SHugh Dickins 	update_hiwater_vm(mm);
24132c0b3814SHugh Dickins 	do {
2414ab50b8edSHugh Dickins 		long nrpages = vma_pages(vma);
24151da177e4SLinus Torvalds 
24164f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
24174f74d2c8SLinus Torvalds 			nr_accounted += nrpages;
241884638335SKonstantin Khlebnikov 		vm_stat_account(mm, vma->vm_flags, -nrpages);
2419a8fb5618SHugh Dickins 		vma = remove_vma(vma);
2420146425a3SHugh Dickins 	} while (vma);
24214f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
24221da177e4SLinus Torvalds 	validate_mm(mm);
24231da177e4SLinus Torvalds }
24241da177e4SLinus Torvalds 
24251da177e4SLinus Torvalds /*
24261da177e4SLinus Torvalds  * Get rid of page table information in the indicated region.
24271da177e4SLinus Torvalds  *
2428f10df686SPaolo 'Blaisorblade' Giarrusso  * Called with the mm semaphore held.
24291da177e4SLinus Torvalds  */
24301da177e4SLinus Torvalds static void unmap_region(struct mm_struct *mm,
2431e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
2432e0da382cSHugh Dickins 		unsigned long start, unsigned long end)
24331da177e4SLinus Torvalds {
2434f39af059SMatthew Wilcox (Oracle) 	struct vm_area_struct *next = __vma_next(mm, prev);
2435d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
24361da177e4SLinus Torvalds 
24371da177e4SLinus Torvalds 	lru_add_drain();
2438a72afd87SWill Deacon 	tlb_gather_mmu(&tlb, mm);
2439365e9c87SHugh Dickins 	update_hiwater_rss(mm);
24404f74d2c8SLinus Torvalds 	unmap_vmas(&tlb, vma, start, end);
2441d16dfc55SPeter Zijlstra 	free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
24426ee8630eSHugh Dickins 				 next ? next->vm_start : USER_PGTABLES_CEILING);
2443ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
24441da177e4SLinus Torvalds }
24451da177e4SLinus Torvalds 
24461da177e4SLinus Torvalds /*
24471da177e4SLinus Torvalds  * Create a list of vma's touched by the unmap, removing them from the mm's
24481da177e4SLinus Torvalds  * vma list as we go..
24491da177e4SLinus Torvalds  */
2450246c320aSKirill A. Shutemov static bool
2451d4af56c5SLiam R. Howlett detach_vmas_to_be_unmapped(struct mm_struct *mm, struct ma_state *mas,
2452d4af56c5SLiam R. Howlett 	struct vm_area_struct *vma, struct vm_area_struct *prev,
2453d4af56c5SLiam R. Howlett 	unsigned long end)
24541da177e4SLinus Torvalds {
24551da177e4SLinus Torvalds 	struct vm_area_struct **insertion_point;
24561da177e4SLinus Torvalds 	struct vm_area_struct *tail_vma = NULL;
24571da177e4SLinus Torvalds 
24581da177e4SLinus Torvalds 	insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2459297c5eeeSLinus Torvalds 	vma->vm_prev = NULL;
2460524e00b3SLiam R. Howlett 	vma_mas_szero(mas, vma->vm_start, end);
24611da177e4SLinus Torvalds 	do {
2462a213e5cfSHugh Dickins 		if (vma->vm_flags & VM_LOCKED)
2463a213e5cfSHugh Dickins 			mm->locked_vm -= vma_pages(vma);
24641da177e4SLinus Torvalds 		mm->map_count--;
24651da177e4SLinus Torvalds 		tail_vma = vma;
24661da177e4SLinus Torvalds 		vma = vma->vm_next;
24671da177e4SLinus Torvalds 	} while (vma && vma->vm_start < end);
24681da177e4SLinus Torvalds 	*insertion_point = vma;
2469524e00b3SLiam R. Howlett 	if (vma)
2470297c5eeeSLinus Torvalds 		vma->vm_prev = prev;
2471524e00b3SLiam R. Howlett 	else
24721be7107fSHugh Dickins 		mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
24731da177e4SLinus Torvalds 	tail_vma->vm_next = NULL;
2474615d6e87SDavidlohr Bueso 
2475615d6e87SDavidlohr Bueso 	/* Kill the cache */
2476615d6e87SDavidlohr Bueso 	vmacache_invalidate(mm);
2477246c320aSKirill A. Shutemov 
2478246c320aSKirill A. Shutemov 	/*
2479246c320aSKirill A. Shutemov 	 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2480246c320aSKirill A. Shutemov 	 * VM_GROWSUP VMA. Such VMAs can change their size under
2481246c320aSKirill A. Shutemov 	 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2482246c320aSKirill A. Shutemov 	 */
2483246c320aSKirill A. Shutemov 	if (vma && (vma->vm_flags & VM_GROWSDOWN))
2484246c320aSKirill A. Shutemov 		return false;
2485246c320aSKirill A. Shutemov 	if (prev && (prev->vm_flags & VM_GROWSUP))
2486246c320aSKirill A. Shutemov 		return false;
2487246c320aSKirill A. Shutemov 	return true;
24881da177e4SLinus Torvalds }
24891da177e4SLinus Torvalds 
24901da177e4SLinus Torvalds /*
2491def5efe0SDavid Rientjes  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2492def5efe0SDavid Rientjes  * has already been checked or doesn't make sense to fail.
24931da177e4SLinus Torvalds  */
2494def5efe0SDavid Rientjes int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
24951da177e4SLinus Torvalds 		unsigned long addr, int new_below)
24961da177e4SLinus Torvalds {
24971da177e4SLinus Torvalds 	struct vm_area_struct *new;
2498e3975891SChen Gang 	int err;
2499d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
25001da177e4SLinus Torvalds 
2501dd3b614fSDmitry Safonov 	if (vma->vm_ops && vma->vm_ops->may_split) {
2502dd3b614fSDmitry Safonov 		err = vma->vm_ops->may_split(vma, addr);
250331383c68SDan Williams 		if (err)
250431383c68SDan Williams 			return err;
250531383c68SDan Williams 	}
25061da177e4SLinus Torvalds 
25073928d4f5SLinus Torvalds 	new = vm_area_dup(vma);
25081da177e4SLinus Torvalds 	if (!new)
2509e3975891SChen Gang 		return -ENOMEM;
25101da177e4SLinus Torvalds 
25111da177e4SLinus Torvalds 	if (new_below)
25121da177e4SLinus Torvalds 		new->vm_end = addr;
25131da177e4SLinus Torvalds 	else {
25141da177e4SLinus Torvalds 		new->vm_start = addr;
25151da177e4SLinus Torvalds 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
25161da177e4SLinus Torvalds 	}
25171da177e4SLinus Torvalds 
2518ef0855d3SOleg Nesterov 	err = vma_dup_policy(vma, new);
2519ef0855d3SOleg Nesterov 	if (err)
25205beb4930SRik van Riel 		goto out_free_vma;
25211da177e4SLinus Torvalds 
2522c4ea95d7SDaniel Forrest 	err = anon_vma_clone(new, vma);
2523c4ea95d7SDaniel Forrest 	if (err)
25245beb4930SRik van Riel 		goto out_free_mpol;
25255beb4930SRik van Riel 
2526e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
25271da177e4SLinus Torvalds 		get_file(new->vm_file);
25281da177e4SLinus Torvalds 
25291da177e4SLinus Torvalds 	if (new->vm_ops && new->vm_ops->open)
25301da177e4SLinus Torvalds 		new->vm_ops->open(new);
25311da177e4SLinus Torvalds 
25321da177e4SLinus Torvalds 	if (new_below)
25335beb4930SRik van Riel 		err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
25341da177e4SLinus Torvalds 			((addr - new->vm_start) >> PAGE_SHIFT), new);
25351da177e4SLinus Torvalds 	else
25365beb4930SRik van Riel 		err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
25371da177e4SLinus Torvalds 
25385beb4930SRik van Riel 	/* Success. */
25395beb4930SRik van Riel 	if (!err)
25401da177e4SLinus Torvalds 		return 0;
25415beb4930SRik van Riel 
2542d4af56c5SLiam R. Howlett 	/* Avoid vm accounting in close() operation */
2543d4af56c5SLiam R. Howlett 	new->vm_start = new->vm_end;
2544d4af56c5SLiam R. Howlett 	new->vm_pgoff = 0;
25455beb4930SRik van Riel 	/* Clean everything up if vma_adjust failed. */
254658927533SRik van Riel 	if (new->vm_ops && new->vm_ops->close)
25475beb4930SRik van Riel 		new->vm_ops->close(new);
2548e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
25495beb4930SRik van Riel 		fput(new->vm_file);
25502aeadc30SAndrea Arcangeli 	unlink_anon_vmas(new);
25515beb4930SRik van Riel  out_free_mpol:
2552ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new));
25535beb4930SRik van Riel  out_free_vma:
25543928d4f5SLinus Torvalds 	vm_area_free(new);
2555d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
25565beb4930SRik van Riel 	return err;
25571da177e4SLinus Torvalds }
25581da177e4SLinus Torvalds 
2559659ace58SKOSAKI Motohiro /*
2560659ace58SKOSAKI Motohiro  * Split a vma into two pieces at address 'addr', a new vma is allocated
2561659ace58SKOSAKI Motohiro  * either for the first part or the tail.
2562659ace58SKOSAKI Motohiro  */
2563659ace58SKOSAKI Motohiro int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2564659ace58SKOSAKI Motohiro 	      unsigned long addr, int new_below)
2565659ace58SKOSAKI Motohiro {
2566659ace58SKOSAKI Motohiro 	if (mm->map_count >= sysctl_max_map_count)
2567659ace58SKOSAKI Motohiro 		return -ENOMEM;
2568659ace58SKOSAKI Motohiro 
2569659ace58SKOSAKI Motohiro 	return __split_vma(mm, vma, addr, new_below);
2570659ace58SKOSAKI Motohiro }
2571659ace58SKOSAKI Motohiro 
25721da177e4SLinus Torvalds /* Munmap is split into 2 main parts -- this part which finds
25731da177e4SLinus Torvalds  * what needs doing, and the areas themselves, which do the
25741da177e4SLinus Torvalds  * work.  This now handles partial unmappings.
25751da177e4SLinus Torvalds  * Jeremy Fitzhardinge <jeremy@goop.org>
25761da177e4SLinus Torvalds  */
257785a06835SYang Shi int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2578dd2283f2SYang Shi 		struct list_head *uf, bool downgrade)
25791da177e4SLinus Torvalds {
25801da177e4SLinus Torvalds 	unsigned long end;
2581146425a3SHugh Dickins 	struct vm_area_struct *vma, *prev, *last;
2582d4af56c5SLiam R. Howlett 	int error = -ENOMEM;
2583d4af56c5SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
25841da177e4SLinus Torvalds 
2585de1741a1SAlexander Kuleshov 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
25861da177e4SLinus Torvalds 		return -EINVAL;
25871da177e4SLinus Torvalds 
2588cc71aba3Svishnu.ps 	len = PAGE_ALIGN(len);
25895a28fc94SDave Hansen 	end = start + len;
2590cc71aba3Svishnu.ps 	if (len == 0)
25911da177e4SLinus Torvalds 		return -EINVAL;
25921da177e4SLinus Torvalds 
2593524e00b3SLiam R. Howlett 	 /* arch_unmap() might do unmaps itself.  */
25945a28fc94SDave Hansen 	arch_unmap(mm, start, end);
25955a28fc94SDave Hansen 
259678d9cf60SGonzalo Matias Juarez Tello 	/* Find the first overlapping VMA where start < vma->vm_end */
259778d9cf60SGonzalo Matias Juarez Tello 	vma = find_vma_intersection(mm, start, end);
2598146425a3SHugh Dickins 	if (!vma)
25991da177e4SLinus Torvalds 		return 0;
2600d4af56c5SLiam R. Howlett 
2601d4af56c5SLiam R. Howlett 	if (mas_preallocate(&mas, vma, GFP_KERNEL))
2602d4af56c5SLiam R. Howlett 		return -ENOMEM;
26039be34c9dSLinus Torvalds 	prev = vma->vm_prev;
2604524e00b3SLiam R. Howlett 	/* we have start < vma->vm_end  */
2605524e00b3SLiam R. Howlett 
2606524e00b3SLiam R. Howlett 	/* if it doesn't overlap, we have nothing.. */
2607524e00b3SLiam R. Howlett 	if (vma->vm_start >= end)
2608524e00b3SLiam R. Howlett 		return 0;
26091da177e4SLinus Torvalds 
26101da177e4SLinus Torvalds 	/*
26111da177e4SLinus Torvalds 	 * If we need to split any vma, do it now to save pain later.
26121da177e4SLinus Torvalds 	 *
26131da177e4SLinus Torvalds 	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
26141da177e4SLinus Torvalds 	 * unmapped vm_area_struct will remain in use: so lower split_vma
26151da177e4SLinus Torvalds 	 * places tmp vma above, and higher split_vma places tmp vma below.
26161da177e4SLinus Torvalds 	 */
2617146425a3SHugh Dickins 	if (start > vma->vm_start) {
2618659ace58SKOSAKI Motohiro 
2619659ace58SKOSAKI Motohiro 		/*
2620659ace58SKOSAKI Motohiro 		 * Make sure that map_count on return from munmap() will
2621659ace58SKOSAKI Motohiro 		 * not exceed its limit; but let map_count go just above
2622659ace58SKOSAKI Motohiro 		 * its limit temporarily, to help free resources as expected.
2623659ace58SKOSAKI Motohiro 		 */
2624659ace58SKOSAKI Motohiro 		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2625d4af56c5SLiam R. Howlett 			goto map_count_exceeded;
2626659ace58SKOSAKI Motohiro 
2627659ace58SKOSAKI Motohiro 		error = __split_vma(mm, vma, start, 0);
26281da177e4SLinus Torvalds 		if (error)
2629d4af56c5SLiam R. Howlett 			goto split_failed;
2630146425a3SHugh Dickins 		prev = vma;
26311da177e4SLinus Torvalds 	}
26321da177e4SLinus Torvalds 
26331da177e4SLinus Torvalds 	/* Does it split the last one? */
26341da177e4SLinus Torvalds 	last = find_vma(mm, end);
26351da177e4SLinus Torvalds 	if (last && end > last->vm_start) {
2636d4af56c5SLiam R. Howlett 		error = __split_vma(mm, last, end, 1);
26371da177e4SLinus Torvalds 		if (error)
2638d4af56c5SLiam R. Howlett 			goto split_failed;
26391da177e4SLinus Torvalds 	}
2640f39af059SMatthew Wilcox (Oracle) 	vma = __vma_next(mm, prev);
26411da177e4SLinus Torvalds 
26422376dd7cSAndrea Arcangeli 	if (unlikely(uf)) {
26432376dd7cSAndrea Arcangeli 		/*
26442376dd7cSAndrea Arcangeli 		 * If userfaultfd_unmap_prep returns an error the vmas
2645f0953a1bSIngo Molnar 		 * will remain split, but userland will get a
26462376dd7cSAndrea Arcangeli 		 * highly unexpected error anyway. This is no
26472376dd7cSAndrea Arcangeli 		 * different than the case where the first of the two
26482376dd7cSAndrea Arcangeli 		 * __split_vma fails, but we don't undo the first
26492376dd7cSAndrea Arcangeli 		 * split, despite we could. This is unlikely enough
26502376dd7cSAndrea Arcangeli 		 * failure that it's not worth optimizing it for.
26512376dd7cSAndrea Arcangeli 		 */
2652d4af56c5SLiam R. Howlett 		error = userfaultfd_unmap_prep(vma, start, end, uf);
26532376dd7cSAndrea Arcangeli 		if (error)
2654d4af56c5SLiam R. Howlett 			goto userfaultfd_error;
26552376dd7cSAndrea Arcangeli 	}
26562376dd7cSAndrea Arcangeli 
2657dd2283f2SYang Shi 	/* Detach vmas from rbtree */
2658d4af56c5SLiam R. Howlett 	if (!detach_vmas_to_be_unmapped(mm, &mas, vma, prev, end))
2659246c320aSKirill A. Shutemov 		downgrade = false;
26601da177e4SLinus Torvalds 
2661dd2283f2SYang Shi 	if (downgrade)
2662d8ed45c5SMichel Lespinasse 		mmap_write_downgrade(mm);
2663dd2283f2SYang Shi 
2664dd2283f2SYang Shi 	unmap_region(mm, vma, prev, start, end);
2665dd2283f2SYang Shi 
26661da177e4SLinus Torvalds 	/* Fix up all other VM information */
26672c0b3814SHugh Dickins 	remove_vma_list(mm, vma);
26681da177e4SLinus Torvalds 
2669524e00b3SLiam R. Howlett 
2670524e00b3SLiam R. Howlett 	validate_mm(mm);
2671dd2283f2SYang Shi 	return downgrade ? 1 : 0;
2672d4af56c5SLiam R. Howlett 
2673d4af56c5SLiam R. Howlett map_count_exceeded:
2674d4af56c5SLiam R. Howlett split_failed:
2675d4af56c5SLiam R. Howlett userfaultfd_error:
2676d4af56c5SLiam R. Howlett 	mas_destroy(&mas);
2677d4af56c5SLiam R. Howlett 	return error;
26781da177e4SLinus Torvalds }
26791da177e4SLinus Torvalds 
2680dd2283f2SYang Shi int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2681dd2283f2SYang Shi 	      struct list_head *uf)
2682dd2283f2SYang Shi {
2683dd2283f2SYang Shi 	return __do_munmap(mm, start, len, uf, false);
2684dd2283f2SYang Shi }
2685dd2283f2SYang Shi 
2686dd2283f2SYang Shi static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2687a46ef99dSLinus Torvalds {
2688a46ef99dSLinus Torvalds 	int ret;
2689bfce281cSAl Viro 	struct mm_struct *mm = current->mm;
2690897ab3e0SMike Rapoport 	LIST_HEAD(uf);
2691a46ef99dSLinus Torvalds 
2692d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2693ae798783SMichal Hocko 		return -EINTR;
2694ae798783SMichal Hocko 
2695dd2283f2SYang Shi 	ret = __do_munmap(mm, start, len, &uf, downgrade);
2696dd2283f2SYang Shi 	/*
2697c1e8d7c6SMichel Lespinasse 	 * Returning 1 indicates mmap_lock is downgraded.
2698dd2283f2SYang Shi 	 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2699dd2283f2SYang Shi 	 * it to 0 before return.
2700dd2283f2SYang Shi 	 */
2701dd2283f2SYang Shi 	if (ret == 1) {
2702d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
2703dd2283f2SYang Shi 		ret = 0;
2704dd2283f2SYang Shi 	} else
2705d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
2706dd2283f2SYang Shi 
2707897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
2708a46ef99dSLinus Torvalds 	return ret;
2709a46ef99dSLinus Torvalds }
2710dd2283f2SYang Shi 
2711dd2283f2SYang Shi int vm_munmap(unsigned long start, size_t len)
2712dd2283f2SYang Shi {
2713dd2283f2SYang Shi 	return __vm_munmap(start, len, false);
2714dd2283f2SYang Shi }
2715a46ef99dSLinus Torvalds EXPORT_SYMBOL(vm_munmap);
2716a46ef99dSLinus Torvalds 
27176a6160a7SHeiko Carstens SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
27181da177e4SLinus Torvalds {
2719ce18d171SCatalin Marinas 	addr = untagged_addr(addr);
2720dd2283f2SYang Shi 	return __vm_munmap(addr, len, true);
27211da177e4SLinus Torvalds }
27221da177e4SLinus Torvalds 
2723c8d78c18SKirill A. Shutemov 
2724c8d78c18SKirill A. Shutemov /*
2725c8d78c18SKirill A. Shutemov  * Emulation of deprecated remap_file_pages() syscall.
2726c8d78c18SKirill A. Shutemov  */
2727c8d78c18SKirill A. Shutemov SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2728c8d78c18SKirill A. Shutemov 		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2729c8d78c18SKirill A. Shutemov {
2730c8d78c18SKirill A. Shutemov 
2731c8d78c18SKirill A. Shutemov 	struct mm_struct *mm = current->mm;
2732c8d78c18SKirill A. Shutemov 	struct vm_area_struct *vma;
2733c8d78c18SKirill A. Shutemov 	unsigned long populate = 0;
2734c8d78c18SKirill A. Shutemov 	unsigned long ret = -EINVAL;
2735c8d78c18SKirill A. Shutemov 	struct file *file;
2736c8d78c18SKirill A. Shutemov 
2737ee65728eSMike Rapoport 	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2738c8d78c18SKirill A. Shutemov 		     current->comm, current->pid);
2739c8d78c18SKirill A. Shutemov 
2740c8d78c18SKirill A. Shutemov 	if (prot)
2741c8d78c18SKirill A. Shutemov 		return ret;
2742c8d78c18SKirill A. Shutemov 	start = start & PAGE_MASK;
2743c8d78c18SKirill A. Shutemov 	size = size & PAGE_MASK;
2744c8d78c18SKirill A. Shutemov 
2745c8d78c18SKirill A. Shutemov 	if (start + size <= start)
2746c8d78c18SKirill A. Shutemov 		return ret;
2747c8d78c18SKirill A. Shutemov 
2748c8d78c18SKirill A. Shutemov 	/* Does pgoff wrap? */
2749c8d78c18SKirill A. Shutemov 	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2750c8d78c18SKirill A. Shutemov 		return ret;
2751c8d78c18SKirill A. Shutemov 
2752d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2753dc0ef0dfSMichal Hocko 		return -EINTR;
2754dc0ef0dfSMichal Hocko 
27559b593cb2SLiam R. Howlett 	vma = vma_lookup(mm, start);
2756c8d78c18SKirill A. Shutemov 
2757c8d78c18SKirill A. Shutemov 	if (!vma || !(vma->vm_flags & VM_SHARED))
2758c8d78c18SKirill A. Shutemov 		goto out;
2759c8d78c18SKirill A. Shutemov 
276048f7df32SKirill A. Shutemov 	if (start + size > vma->vm_end) {
276148f7df32SKirill A. Shutemov 		struct vm_area_struct *next;
276248f7df32SKirill A. Shutemov 
276348f7df32SKirill A. Shutemov 		for (next = vma->vm_next; next; next = next->vm_next) {
276448f7df32SKirill A. Shutemov 			/* hole between vmas ? */
276548f7df32SKirill A. Shutemov 			if (next->vm_start != next->vm_prev->vm_end)
276648f7df32SKirill A. Shutemov 				goto out;
276748f7df32SKirill A. Shutemov 
276848f7df32SKirill A. Shutemov 			if (next->vm_file != vma->vm_file)
276948f7df32SKirill A. Shutemov 				goto out;
277048f7df32SKirill A. Shutemov 
277148f7df32SKirill A. Shutemov 			if (next->vm_flags != vma->vm_flags)
277248f7df32SKirill A. Shutemov 				goto out;
277348f7df32SKirill A. Shutemov 
277448f7df32SKirill A. Shutemov 			if (start + size <= next->vm_end)
277548f7df32SKirill A. Shutemov 				break;
277648f7df32SKirill A. Shutemov 		}
277748f7df32SKirill A. Shutemov 
277848f7df32SKirill A. Shutemov 		if (!next)
2779c8d78c18SKirill A. Shutemov 			goto out;
2780c8d78c18SKirill A. Shutemov 	}
2781c8d78c18SKirill A. Shutemov 
2782c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2783c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2784c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2785c8d78c18SKirill A. Shutemov 
2786c8d78c18SKirill A. Shutemov 	flags &= MAP_NONBLOCK;
2787c8d78c18SKirill A. Shutemov 	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2788fce000b1SLiam Howlett 	if (vma->vm_flags & VM_LOCKED)
2789c8d78c18SKirill A. Shutemov 		flags |= MAP_LOCKED;
279048f7df32SKirill A. Shutemov 
2791c8d78c18SKirill A. Shutemov 	file = get_file(vma->vm_file);
279245e55300SPeter Collingbourne 	ret = do_mmap(vma->vm_file, start, size,
2793897ab3e0SMike Rapoport 			prot, flags, pgoff, &populate, NULL);
2794c8d78c18SKirill A. Shutemov 	fput(file);
2795c8d78c18SKirill A. Shutemov out:
2796d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
2797c8d78c18SKirill A. Shutemov 	if (populate)
2798c8d78c18SKirill A. Shutemov 		mm_populate(ret, populate);
2799c8d78c18SKirill A. Shutemov 	if (!IS_ERR_VALUE(ret))
2800c8d78c18SKirill A. Shutemov 		ret = 0;
2801c8d78c18SKirill A. Shutemov 	return ret;
2802c8d78c18SKirill A. Shutemov }
2803c8d78c18SKirill A. Shutemov 
28041da177e4SLinus Torvalds /*
2805*2e7ce7d3SLiam R. Howlett  * brk_munmap() - Unmap a parital vma.
2806*2e7ce7d3SLiam R. Howlett  * @mas: The maple tree state.
2807*2e7ce7d3SLiam R. Howlett  * @vma: The vma to be modified
2808*2e7ce7d3SLiam R. Howlett  * @newbrk: the start of the address to unmap
2809*2e7ce7d3SLiam R. Howlett  * @oldbrk: The end of the address to unmap
2810*2e7ce7d3SLiam R. Howlett  * @uf: The userfaultfd list_head
2811*2e7ce7d3SLiam R. Howlett  *
2812*2e7ce7d3SLiam R. Howlett  * Returns: 1 on success.
2813*2e7ce7d3SLiam R. Howlett  * unmaps a partial VMA mapping.  Does not handle alignment, downgrades lock if
2814*2e7ce7d3SLiam R. Howlett  * possible.
28151da177e4SLinus Torvalds  */
2816*2e7ce7d3SLiam R. Howlett static int do_brk_munmap(struct ma_state *mas, struct vm_area_struct *vma,
2817*2e7ce7d3SLiam R. Howlett 			 unsigned long newbrk, unsigned long oldbrk,
2818*2e7ce7d3SLiam R. Howlett 			 struct list_head *uf)
2819*2e7ce7d3SLiam R. Howlett {
2820*2e7ce7d3SLiam R. Howlett 	struct mm_struct *mm = vma->vm_mm;
2821*2e7ce7d3SLiam R. Howlett 	int ret;
2822*2e7ce7d3SLiam R. Howlett 
2823*2e7ce7d3SLiam R. Howlett 	arch_unmap(mm, newbrk, oldbrk);
2824*2e7ce7d3SLiam R. Howlett 	ret = __do_munmap(mm, newbrk, oldbrk - newbrk, uf, true);
2825*2e7ce7d3SLiam R. Howlett 	validate_mm_mt(mm);
2826*2e7ce7d3SLiam R. Howlett 	return ret;
2827*2e7ce7d3SLiam R. Howlett }
2828*2e7ce7d3SLiam R. Howlett 
2829*2e7ce7d3SLiam R. Howlett /*
2830*2e7ce7d3SLiam R. Howlett  * do_brk_flags() - Increase the brk vma if the flags match.
2831*2e7ce7d3SLiam R. Howlett  * @mas: The maple tree state.
2832*2e7ce7d3SLiam R. Howlett  * @addr: The start address
2833*2e7ce7d3SLiam R. Howlett  * @len: The length of the increase
2834*2e7ce7d3SLiam R. Howlett  * @vma: The vma,
2835*2e7ce7d3SLiam R. Howlett  * @flags: The VMA Flags
2836*2e7ce7d3SLiam R. Howlett  *
2837*2e7ce7d3SLiam R. Howlett  * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
2838*2e7ce7d3SLiam R. Howlett  * do not match then create a new anonymous VMA.  Eventually we may be able to
2839*2e7ce7d3SLiam R. Howlett  * do some brk-specific accounting here.
2840*2e7ce7d3SLiam R. Howlett  */
2841*2e7ce7d3SLiam R. Howlett static int do_brk_flags(struct ma_state *mas, struct vm_area_struct *vma,
2842*2e7ce7d3SLiam R. Howlett 			unsigned long addr, unsigned long len,
2843*2e7ce7d3SLiam R. Howlett 			unsigned long flags)
28441da177e4SLinus Torvalds {
28451da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
2846*2e7ce7d3SLiam R. Howlett 	struct vm_area_struct *prev = NULL;
2847*2e7ce7d3SLiam R. Howlett 
2848d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
2849*2e7ce7d3SLiam R. Howlett 	/*
2850*2e7ce7d3SLiam R. Howlett 	 * Check against address space limits by the changed size
2851*2e7ce7d3SLiam R. Howlett 	 * Note: This happens *after* clearing old mappings in some code paths.
2852*2e7ce7d3SLiam R. Howlett 	 */
285316e72e9bSDenys Vlasenko 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
285484638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
28551da177e4SLinus Torvalds 		return -ENOMEM;
28561da177e4SLinus Torvalds 
28571da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
28581da177e4SLinus Torvalds 		return -ENOMEM;
28591da177e4SLinus Torvalds 
2860191c5424SAl Viro 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
28611da177e4SLinus Torvalds 		return -ENOMEM;
28621da177e4SLinus Torvalds 
28631da177e4SLinus Torvalds 	/*
2864*2e7ce7d3SLiam R. Howlett 	 * Expand the existing vma if possible; Note that singular lists do not
2865*2e7ce7d3SLiam R. Howlett 	 * occur after forking, so the expand will only happen on new VMAs.
28661da177e4SLinus Torvalds 	 */
2867*2e7ce7d3SLiam R. Howlett 	if (vma &&
2868*2e7ce7d3SLiam R. Howlett 	    (!vma->anon_vma || list_is_singular(&vma->anon_vma_chain)) &&
2869*2e7ce7d3SLiam R. Howlett 	    ((vma->vm_flags & ~VM_SOFTDIRTY) == flags)) {
2870*2e7ce7d3SLiam R. Howlett 		mas->index = vma->vm_start;
2871*2e7ce7d3SLiam R. Howlett 		mas->last = addr + len - 1;
2872*2e7ce7d3SLiam R. Howlett 		vma_adjust_trans_huge(vma, addr, addr + len, 0);
2873*2e7ce7d3SLiam R. Howlett 		if (vma->anon_vma) {
2874*2e7ce7d3SLiam R. Howlett 			anon_vma_lock_write(vma->anon_vma);
2875*2e7ce7d3SLiam R. Howlett 			anon_vma_interval_tree_pre_update_vma(vma);
28761da177e4SLinus Torvalds 		}
2877*2e7ce7d3SLiam R. Howlett 		vma->vm_end = addr + len;
2878*2e7ce7d3SLiam R. Howlett 		vma->vm_flags |= VM_SOFTDIRTY;
2879*2e7ce7d3SLiam R. Howlett 		if (mas_store_gfp(mas, vma, GFP_KERNEL))
2880*2e7ce7d3SLiam R. Howlett 			goto mas_expand_failed;
2881*2e7ce7d3SLiam R. Howlett 
2882*2e7ce7d3SLiam R. Howlett 		if (vma->anon_vma) {
2883*2e7ce7d3SLiam R. Howlett 			anon_vma_interval_tree_post_update_vma(vma);
2884*2e7ce7d3SLiam R. Howlett 			anon_vma_unlock_write(vma->anon_vma);
2885*2e7ce7d3SLiam R. Howlett 		}
2886*2e7ce7d3SLiam R. Howlett 		khugepaged_enter_vma(vma, flags);
2887*2e7ce7d3SLiam R. Howlett 		goto out;
2888*2e7ce7d3SLiam R. Howlett 	}
2889*2e7ce7d3SLiam R. Howlett 	prev = vma;
2890*2e7ce7d3SLiam R. Howlett 
2891*2e7ce7d3SLiam R. Howlett 	/* create a vma struct for an anonymous mapping */
2892*2e7ce7d3SLiam R. Howlett 	vma = vm_area_alloc(mm);
2893*2e7ce7d3SLiam R. Howlett 	if (!vma)
2894*2e7ce7d3SLiam R. Howlett 		goto vma_alloc_fail;
28951da177e4SLinus Torvalds 
2896bfd40eafSKirill A. Shutemov 	vma_set_anonymous(vma);
28971da177e4SLinus Torvalds 	vma->vm_start = addr;
28981da177e4SLinus Torvalds 	vma->vm_end = addr + len;
2899*2e7ce7d3SLiam R. Howlett 	vma->vm_pgoff = addr >> PAGE_SHIFT;
29001da177e4SLinus Torvalds 	vma->vm_flags = flags;
29013ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(flags);
2902*2e7ce7d3SLiam R. Howlett 	mas_set_range(mas, vma->vm_start, addr + len - 1);
2903*2e7ce7d3SLiam R. Howlett 	if (mas_store_gfp(mas, vma, GFP_KERNEL))
2904*2e7ce7d3SLiam R. Howlett 		goto mas_store_fail;
2905d4af56c5SLiam R. Howlett 
2906*2e7ce7d3SLiam R. Howlett 	if (!prev)
2907*2e7ce7d3SLiam R. Howlett 		prev = mas_prev(mas, 0);
2908*2e7ce7d3SLiam R. Howlett 
2909*2e7ce7d3SLiam R. Howlett 	__vma_link_list(mm, vma, prev);
2910*2e7ce7d3SLiam R. Howlett 	mm->map_count++;
29111da177e4SLinus Torvalds out:
29123af9e859SEric B Munson 	perf_event_mmap(vma);
29131da177e4SLinus Torvalds 	mm->total_vm += len >> PAGE_SHIFT;
291484638335SKonstantin Khlebnikov 	mm->data_vm += len >> PAGE_SHIFT;
2915128557ffSMichel Lespinasse 	if (flags & VM_LOCKED)
2916ba470de4SRik van Riel 		mm->locked_vm += (len >> PAGE_SHIFT);
2917d9104d1cSCyrill Gorcunov 	vma->vm_flags |= VM_SOFTDIRTY;
2918d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
29195d22fc25SLinus Torvalds 	return 0;
2920d4af56c5SLiam R. Howlett 
2921*2e7ce7d3SLiam R. Howlett mas_store_fail:
2922d4af56c5SLiam R. Howlett 	vm_area_free(vma);
2923*2e7ce7d3SLiam R. Howlett vma_alloc_fail:
2924*2e7ce7d3SLiam R. Howlett 	vm_unacct_memory(len >> PAGE_SHIFT);
2925*2e7ce7d3SLiam R. Howlett 	return -ENOMEM;
2926*2e7ce7d3SLiam R. Howlett 
2927*2e7ce7d3SLiam R. Howlett mas_expand_failed:
2928*2e7ce7d3SLiam R. Howlett 	if (vma->anon_vma) {
2929*2e7ce7d3SLiam R. Howlett 		anon_vma_interval_tree_post_update_vma(vma);
2930*2e7ce7d3SLiam R. Howlett 		anon_vma_unlock_write(vma->anon_vma);
2931*2e7ce7d3SLiam R. Howlett 	}
2932d4af56c5SLiam R. Howlett 	return -ENOMEM;
29331da177e4SLinus Torvalds }
29341da177e4SLinus Torvalds 
2935bb177a73SMichal Hocko int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
2936e4eb1ff6SLinus Torvalds {
2937e4eb1ff6SLinus Torvalds 	struct mm_struct *mm = current->mm;
2938*2e7ce7d3SLiam R. Howlett 	struct vm_area_struct *vma = NULL;
2939bb177a73SMichal Hocko 	unsigned long len;
29405d22fc25SLinus Torvalds 	int ret;
2941128557ffSMichel Lespinasse 	bool populate;
2942897ab3e0SMike Rapoport 	LIST_HEAD(uf);
2943*2e7ce7d3SLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, addr, addr);
2944e4eb1ff6SLinus Torvalds 
2945bb177a73SMichal Hocko 	len = PAGE_ALIGN(request);
2946bb177a73SMichal Hocko 	if (len < request)
2947bb177a73SMichal Hocko 		return -ENOMEM;
2948bb177a73SMichal Hocko 	if (!len)
2949bb177a73SMichal Hocko 		return 0;
2950bb177a73SMichal Hocko 
2951d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
29522d6c9282SMichal Hocko 		return -EINTR;
29532d6c9282SMichal Hocko 
2954*2e7ce7d3SLiam R. Howlett 	/* Until we need other flags, refuse anything except VM_EXEC. */
2955*2e7ce7d3SLiam R. Howlett 	if ((flags & (~VM_EXEC)) != 0)
2956*2e7ce7d3SLiam R. Howlett 		return -EINVAL;
2957*2e7ce7d3SLiam R. Howlett 
2958*2e7ce7d3SLiam R. Howlett 	ret = check_brk_limits(addr, len);
2959*2e7ce7d3SLiam R. Howlett 	if (ret)
2960*2e7ce7d3SLiam R. Howlett 		goto limits_failed;
2961*2e7ce7d3SLiam R. Howlett 
2962*2e7ce7d3SLiam R. Howlett 	if (find_vma_intersection(mm, addr, addr + len))
2963*2e7ce7d3SLiam R. Howlett 		ret = do_munmap(mm, addr, len, &uf);
2964*2e7ce7d3SLiam R. Howlett 
2965*2e7ce7d3SLiam R. Howlett 	if (ret)
2966*2e7ce7d3SLiam R. Howlett 		goto munmap_failed;
2967*2e7ce7d3SLiam R. Howlett 
2968*2e7ce7d3SLiam R. Howlett 	vma = mas_prev(&mas, 0);
2969*2e7ce7d3SLiam R. Howlett 	if (!vma || vma->vm_end != addr || vma_policy(vma) ||
2970*2e7ce7d3SLiam R. Howlett 	    !can_vma_merge_after(vma, flags, NULL, NULL,
2971*2e7ce7d3SLiam R. Howlett 				 addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL))
2972*2e7ce7d3SLiam R. Howlett 		vma = NULL;
2973*2e7ce7d3SLiam R. Howlett 
2974*2e7ce7d3SLiam R. Howlett 	ret = do_brk_flags(&mas, vma, addr, len, flags);
2975128557ffSMichel Lespinasse 	populate = ((mm->def_flags & VM_LOCKED) != 0);
2976d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
2977897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
29785d22fc25SLinus Torvalds 	if (populate && !ret)
2979128557ffSMichel Lespinasse 		mm_populate(addr, len);
2980e4eb1ff6SLinus Torvalds 	return ret;
2981*2e7ce7d3SLiam R. Howlett 
2982*2e7ce7d3SLiam R. Howlett munmap_failed:
2983*2e7ce7d3SLiam R. Howlett limits_failed:
2984*2e7ce7d3SLiam R. Howlett 	mmap_write_unlock(mm);
2985*2e7ce7d3SLiam R. Howlett 	return ret;
2986e4eb1ff6SLinus Torvalds }
298716e72e9bSDenys Vlasenko EXPORT_SYMBOL(vm_brk_flags);
298816e72e9bSDenys Vlasenko 
298916e72e9bSDenys Vlasenko int vm_brk(unsigned long addr, unsigned long len)
299016e72e9bSDenys Vlasenko {
299116e72e9bSDenys Vlasenko 	return vm_brk_flags(addr, len, 0);
299216e72e9bSDenys Vlasenko }
2993e4eb1ff6SLinus Torvalds EXPORT_SYMBOL(vm_brk);
29941da177e4SLinus Torvalds 
29951da177e4SLinus Torvalds /* Release all mmaps. */
29961da177e4SLinus Torvalds void exit_mmap(struct mm_struct *mm)
29971da177e4SLinus Torvalds {
2998d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
2999ba470de4SRik van Riel 	struct vm_area_struct *vma;
30001da177e4SLinus Torvalds 	unsigned long nr_accounted = 0;
30011da177e4SLinus Torvalds 
3002d6dd61c8SJeremy Fitzhardinge 	/* mm's last user has gone, and its about to be pulled down */
3003cddb8a5cSAndrea Arcangeli 	mmu_notifier_release(mm);
3004d6dd61c8SJeremy Fitzhardinge 
300527ae357fSDavid Rientjes 	if (unlikely(mm_is_oom_victim(mm))) {
300627ae357fSDavid Rientjes 		/*
300727ae357fSDavid Rientjes 		 * Manually reap the mm to free as much memory as possible.
300827ae357fSDavid Rientjes 		 * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3009c1e8d7c6SMichel Lespinasse 		 * this mm from further consideration.  Taking mm->mmap_lock for
301027ae357fSDavid Rientjes 		 * write after setting MMF_OOM_SKIP will guarantee that the oom
3011c1e8d7c6SMichel Lespinasse 		 * reaper will not run on this mm again after mmap_lock is
301227ae357fSDavid Rientjes 		 * dropped.
301327ae357fSDavid Rientjes 		 *
3014c1e8d7c6SMichel Lespinasse 		 * Nothing can be holding mm->mmap_lock here and the above call
301527ae357fSDavid Rientjes 		 * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
301627ae357fSDavid Rientjes 		 * __oom_reap_task_mm() will not block.
301727ae357fSDavid Rientjes 		 */
301893065ac7SMichal Hocko 		(void)__oom_reap_task_mm(mm);
301927ae357fSDavid Rientjes 		set_bit(MMF_OOM_SKIP, &mm->flags);
302027ae357fSDavid Rientjes 	}
302127ae357fSDavid Rientjes 
302264591e86SSuren Baghdasaryan 	mmap_write_lock(mm);
30239480c53eSJeremy Fitzhardinge 	arch_exit_mmap(mm);
30249480c53eSJeremy Fitzhardinge 
3025ba470de4SRik van Riel 	vma = mm->mmap;
302664591e86SSuren Baghdasaryan 	if (!vma) {
302764591e86SSuren Baghdasaryan 		/* Can happen if dup_mmap() received an OOM */
302864591e86SSuren Baghdasaryan 		mmap_write_unlock(mm);
30299480c53eSJeremy Fitzhardinge 		return;
303064591e86SSuren Baghdasaryan 	}
30319480c53eSJeremy Fitzhardinge 
30321da177e4SLinus Torvalds 	lru_add_drain();
30331da177e4SLinus Torvalds 	flush_cache_mm(mm);
3034d8b45053SWill Deacon 	tlb_gather_mmu_fullmm(&tlb, mm);
3035901608d9SOleg Nesterov 	/* update_hiwater_rss(mm) here? but nobody should be looking */
3036e0da382cSHugh Dickins 	/* Use -1 here to ensure all VMAs in the mm are unmapped */
30374f74d2c8SLinus Torvalds 	unmap_vmas(&tlb, vma, 0, -1);
30386ee8630eSHugh Dickins 	free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3039ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
30401da177e4SLinus Torvalds 
304164591e86SSuren Baghdasaryan 	/* Walk the list again, actually closing and freeing it. */
30424f74d2c8SLinus Torvalds 	while (vma) {
30434f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
30444f74d2c8SLinus Torvalds 			nr_accounted += vma_pages(vma);
3045a8fb5618SHugh Dickins 		vma = remove_vma(vma);
30460a3b3c25SPaul E. McKenney 		cond_resched();
30474f74d2c8SLinus Torvalds 	}
3048d4af56c5SLiam R. Howlett 
3049d4af56c5SLiam R. Howlett 	trace_exit_mmap(mm);
3050d4af56c5SLiam R. Howlett 	__mt_destroy(&mm->mm_mt);
3051f798a1d4SSuren Baghdasaryan 	mm->mmap = NULL;
305264591e86SSuren Baghdasaryan 	mmap_write_unlock(mm);
30534f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
30541da177e4SLinus Torvalds }
30551da177e4SLinus Torvalds 
30561da177e4SLinus Torvalds /* Insert vm structure into process list sorted by address
30571da177e4SLinus Torvalds  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3058c8c06efaSDavidlohr Bueso  * then i_mmap_rwsem is taken here.
30591da177e4SLinus Torvalds  */
30601da177e4SLinus Torvalds int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
30611da177e4SLinus Torvalds {
30626597d783SHugh Dickins 	struct vm_area_struct *prev;
3063d4af56c5SLiam R. Howlett 	unsigned long charged = vma_pages(vma);
30641da177e4SLinus Torvalds 
3065d4af56c5SLiam R. Howlett 
3066524e00b3SLiam R. Howlett 	if (range_has_overlap(mm, vma->vm_start, vma->vm_end, &prev))
3067c9d13f5fSChen Gang 		return -ENOMEM;
3068d4af56c5SLiam R. Howlett 
3069c9d13f5fSChen Gang 	if ((vma->vm_flags & VM_ACCOUNT) &&
3070d4af56c5SLiam R. Howlett 	     security_vm_enough_memory_mm(mm, charged))
3071c9d13f5fSChen Gang 		return -ENOMEM;
3072c9d13f5fSChen Gang 
30731da177e4SLinus Torvalds 	/*
30741da177e4SLinus Torvalds 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
30751da177e4SLinus Torvalds 	 * until its first write fault, when page's anon_vma and index
30761da177e4SLinus Torvalds 	 * are set.  But now set the vm_pgoff it will almost certainly
30771da177e4SLinus Torvalds 	 * end up with (unless mremap moves it elsewhere before that
30781da177e4SLinus Torvalds 	 * first wfault), so /proc/pid/maps tells a consistent story.
30791da177e4SLinus Torvalds 	 *
30801da177e4SLinus Torvalds 	 * By setting it to reflect the virtual start address of the
30811da177e4SLinus Torvalds 	 * vma, merges and splits can happen in a seamless way, just
30821da177e4SLinus Torvalds 	 * using the existing file pgoff checks and manipulations.
30838332326eSLiao Pingfang 	 * Similarly in do_mmap and in do_brk_flags.
30841da177e4SLinus Torvalds 	 */
30858a9cc3b5SOleg Nesterov 	if (vma_is_anonymous(vma)) {
30861da177e4SLinus Torvalds 		BUG_ON(vma->anon_vma);
30871da177e4SLinus Torvalds 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
30881da177e4SLinus Torvalds 	}
30892b144498SSrikar Dronamraju 
3090524e00b3SLiam R. Howlett 	if (vma_link(mm, vma, prev)) {
3091d4af56c5SLiam R. Howlett 		vm_unacct_memory(charged);
3092d4af56c5SLiam R. Howlett 		return -ENOMEM;
3093d4af56c5SLiam R. Howlett 	}
3094d4af56c5SLiam R. Howlett 
30951da177e4SLinus Torvalds 	return 0;
30961da177e4SLinus Torvalds }
30971da177e4SLinus Torvalds 
30981da177e4SLinus Torvalds /*
30991da177e4SLinus Torvalds  * Copy the vma structure to a new location in the same mm,
31001da177e4SLinus Torvalds  * prior to moving page table entries, to effect an mremap move.
31011da177e4SLinus Torvalds  */
31021da177e4SLinus Torvalds struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
310338a76013SMichel Lespinasse 	unsigned long addr, unsigned long len, pgoff_t pgoff,
310438a76013SMichel Lespinasse 	bool *need_rmap_locks)
31051da177e4SLinus Torvalds {
31061da177e4SLinus Torvalds 	struct vm_area_struct *vma = *vmap;
31071da177e4SLinus Torvalds 	unsigned long vma_start = vma->vm_start;
31081da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
31091da177e4SLinus Torvalds 	struct vm_area_struct *new_vma, *prev;
3110948f017bSAndrea Arcangeli 	bool faulted_in_anon_vma = true;
31111da177e4SLinus Torvalds 
3112d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
31131da177e4SLinus Torvalds 	/*
31141da177e4SLinus Torvalds 	 * If anonymous vma has not yet been faulted, update new pgoff
31151da177e4SLinus Torvalds 	 * to match new location, to increase its chance of merging.
31161da177e4SLinus Torvalds 	 */
3117ce75799bSOleg Nesterov 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
31181da177e4SLinus Torvalds 		pgoff = addr >> PAGE_SHIFT;
3119948f017bSAndrea Arcangeli 		faulted_in_anon_vma = false;
3120948f017bSAndrea Arcangeli 	}
31211da177e4SLinus Torvalds 
3122524e00b3SLiam R. Howlett 	if (range_has_overlap(mm, addr, addr + len, &prev))
31236597d783SHugh Dickins 		return NULL;	/* should never get here */
3124524e00b3SLiam R. Howlett 
31251da177e4SLinus Torvalds 	new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
312619a809afSAndrea Arcangeli 			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
31275c26f6acSSuren Baghdasaryan 			    vma->vm_userfaultfd_ctx, anon_vma_name(vma));
31281da177e4SLinus Torvalds 	if (new_vma) {
31291da177e4SLinus Torvalds 		/*
31301da177e4SLinus Torvalds 		 * Source vma may have been merged into new_vma
31311da177e4SLinus Torvalds 		 */
3132948f017bSAndrea Arcangeli 		if (unlikely(vma_start >= new_vma->vm_start &&
3133948f017bSAndrea Arcangeli 			     vma_start < new_vma->vm_end)) {
3134948f017bSAndrea Arcangeli 			/*
3135948f017bSAndrea Arcangeli 			 * The only way we can get a vma_merge with
3136948f017bSAndrea Arcangeli 			 * self during an mremap is if the vma hasn't
3137948f017bSAndrea Arcangeli 			 * been faulted in yet and we were allowed to
3138948f017bSAndrea Arcangeli 			 * reset the dst vma->vm_pgoff to the
3139948f017bSAndrea Arcangeli 			 * destination address of the mremap to allow
3140948f017bSAndrea Arcangeli 			 * the merge to happen. mremap must change the
3141948f017bSAndrea Arcangeli 			 * vm_pgoff linearity between src and dst vmas
3142948f017bSAndrea Arcangeli 			 * (in turn preventing a vma_merge) to be
3143948f017bSAndrea Arcangeli 			 * safe. It is only safe to keep the vm_pgoff
3144948f017bSAndrea Arcangeli 			 * linear if there are no pages mapped yet.
3145948f017bSAndrea Arcangeli 			 */
314681d1b09cSSasha Levin 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
314738a76013SMichel Lespinasse 			*vmap = vma = new_vma;
3148108d6642SMichel Lespinasse 		}
314938a76013SMichel Lespinasse 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
31501da177e4SLinus Torvalds 	} else {
31513928d4f5SLinus Torvalds 		new_vma = vm_area_dup(vma);
3152e3975891SChen Gang 		if (!new_vma)
3153e3975891SChen Gang 			goto out;
31541da177e4SLinus Torvalds 		new_vma->vm_start = addr;
31551da177e4SLinus Torvalds 		new_vma->vm_end = addr + len;
31561da177e4SLinus Torvalds 		new_vma->vm_pgoff = pgoff;
3157ef0855d3SOleg Nesterov 		if (vma_dup_policy(vma, new_vma))
3158523d4e20SMichel Lespinasse 			goto out_free_vma;
3159523d4e20SMichel Lespinasse 		if (anon_vma_clone(new_vma, vma))
3160523d4e20SMichel Lespinasse 			goto out_free_mempol;
3161e9714acfSKonstantin Khlebnikov 		if (new_vma->vm_file)
31621da177e4SLinus Torvalds 			get_file(new_vma->vm_file);
31631da177e4SLinus Torvalds 		if (new_vma->vm_ops && new_vma->vm_ops->open)
31641da177e4SLinus Torvalds 			new_vma->vm_ops->open(new_vma);
3165524e00b3SLiam R. Howlett 		if (vma_link(mm, new_vma, prev))
3166524e00b3SLiam R. Howlett 			goto out_vma_link;
316738a76013SMichel Lespinasse 		*need_rmap_locks = false;
31681da177e4SLinus Torvalds 	}
3169d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
31701da177e4SLinus Torvalds 	return new_vma;
31715beb4930SRik van Riel 
3172524e00b3SLiam R. Howlett out_vma_link:
3173524e00b3SLiam R. Howlett 	if (new_vma->vm_ops && new_vma->vm_ops->close)
3174524e00b3SLiam R. Howlett 		new_vma->vm_ops->close(new_vma);
31755beb4930SRik van Riel out_free_mempol:
3176ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new_vma));
31775beb4930SRik van Riel out_free_vma:
31783928d4f5SLinus Torvalds 	vm_area_free(new_vma);
3179e3975891SChen Gang out:
3180d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
31815beb4930SRik van Riel 	return NULL;
31821da177e4SLinus Torvalds }
3183119f657cSakpm@osdl.org 
3184119f657cSakpm@osdl.org /*
3185119f657cSakpm@osdl.org  * Return true if the calling process may expand its vm space by the passed
3186119f657cSakpm@osdl.org  * number of pages
3187119f657cSakpm@osdl.org  */
318884638335SKonstantin Khlebnikov bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3189119f657cSakpm@osdl.org {
319084638335SKonstantin Khlebnikov 	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
319184638335SKonstantin Khlebnikov 		return false;
3192119f657cSakpm@osdl.org 
3193d977d56cSKonstantin Khlebnikov 	if (is_data_mapping(flags) &&
3194d977d56cSKonstantin Khlebnikov 	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3195f4fcd558SKonstantin Khlebnikov 		/* Workaround for Valgrind */
3196f4fcd558SKonstantin Khlebnikov 		if (rlimit(RLIMIT_DATA) == 0 &&
3197f4fcd558SKonstantin Khlebnikov 		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3198f4fcd558SKonstantin Khlebnikov 			return true;
319957a7702bSDavid Woodhouse 
320057a7702bSDavid Woodhouse 		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3201d977d56cSKonstantin Khlebnikov 			     current->comm, current->pid,
3202d977d56cSKonstantin Khlebnikov 			     (mm->data_vm + npages) << PAGE_SHIFT,
320357a7702bSDavid Woodhouse 			     rlimit(RLIMIT_DATA),
320457a7702bSDavid Woodhouse 			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
320557a7702bSDavid Woodhouse 
320657a7702bSDavid Woodhouse 		if (!ignore_rlimit_data)
3207d977d56cSKonstantin Khlebnikov 			return false;
3208d977d56cSKonstantin Khlebnikov 	}
3209119f657cSakpm@osdl.org 
321084638335SKonstantin Khlebnikov 	return true;
321184638335SKonstantin Khlebnikov }
321284638335SKonstantin Khlebnikov 
321384638335SKonstantin Khlebnikov void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
321484638335SKonstantin Khlebnikov {
32157866076bSPeng Liu 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
321684638335SKonstantin Khlebnikov 
3217d977d56cSKonstantin Khlebnikov 	if (is_exec_mapping(flags))
321884638335SKonstantin Khlebnikov 		mm->exec_vm += npages;
3219d977d56cSKonstantin Khlebnikov 	else if (is_stack_mapping(flags))
322084638335SKonstantin Khlebnikov 		mm->stack_vm += npages;
3221d977d56cSKonstantin Khlebnikov 	else if (is_data_mapping(flags))
322284638335SKonstantin Khlebnikov 		mm->data_vm += npages;
3223119f657cSakpm@osdl.org }
3224fa5dc22fSRoland McGrath 
3225b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3226a62c34bdSAndy Lutomirski 
3227a62c34bdSAndy Lutomirski /*
3228a62c34bdSAndy Lutomirski  * Having a close hook prevents vma merging regardless of flags.
3229a62c34bdSAndy Lutomirski  */
3230a62c34bdSAndy Lutomirski static void special_mapping_close(struct vm_area_struct *vma)
3231a62c34bdSAndy Lutomirski {
3232a62c34bdSAndy Lutomirski }
3233a62c34bdSAndy Lutomirski 
3234a62c34bdSAndy Lutomirski static const char *special_mapping_name(struct vm_area_struct *vma)
3235a62c34bdSAndy Lutomirski {
3236a62c34bdSAndy Lutomirski 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3237a62c34bdSAndy Lutomirski }
3238a62c34bdSAndy Lutomirski 
323914d07113SBrian Geffon static int special_mapping_mremap(struct vm_area_struct *new_vma)
3240b059a453SDmitry Safonov {
3241b059a453SDmitry Safonov 	struct vm_special_mapping *sm = new_vma->vm_private_data;
3242b059a453SDmitry Safonov 
3243280e87e9SDmitry Safonov 	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3244280e87e9SDmitry Safonov 		return -EFAULT;
3245280e87e9SDmitry Safonov 
3246b059a453SDmitry Safonov 	if (sm->mremap)
3247b059a453SDmitry Safonov 		return sm->mremap(sm, new_vma);
3248280e87e9SDmitry Safonov 
3249b059a453SDmitry Safonov 	return 0;
3250b059a453SDmitry Safonov }
3251b059a453SDmitry Safonov 
3252871402e0SDmitry Safonov static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3253871402e0SDmitry Safonov {
3254871402e0SDmitry Safonov 	/*
3255871402e0SDmitry Safonov 	 * Forbid splitting special mappings - kernel has expectations over
3256871402e0SDmitry Safonov 	 * the number of pages in mapping. Together with VM_DONTEXPAND
3257871402e0SDmitry Safonov 	 * the size of vma should stay the same over the special mapping's
3258871402e0SDmitry Safonov 	 * lifetime.
3259871402e0SDmitry Safonov 	 */
3260871402e0SDmitry Safonov 	return -EINVAL;
3261871402e0SDmitry Safonov }
3262871402e0SDmitry Safonov 
3263a62c34bdSAndy Lutomirski static const struct vm_operations_struct special_mapping_vmops = {
3264a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3265a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3266b059a453SDmitry Safonov 	.mremap = special_mapping_mremap,
3267a62c34bdSAndy Lutomirski 	.name = special_mapping_name,
3268af34ebebSDmitry Safonov 	/* vDSO code relies that VVAR can't be accessed remotely */
3269af34ebebSDmitry Safonov 	.access = NULL,
3270871402e0SDmitry Safonov 	.may_split = special_mapping_split,
3271a62c34bdSAndy Lutomirski };
3272a62c34bdSAndy Lutomirski 
3273a62c34bdSAndy Lutomirski static const struct vm_operations_struct legacy_special_mapping_vmops = {
3274a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3275a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3276a62c34bdSAndy Lutomirski };
3277fa5dc22fSRoland McGrath 
3278b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3279fa5dc22fSRoland McGrath {
328011bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
3281b1d0e4f5SNick Piggin 	pgoff_t pgoff;
3282fa5dc22fSRoland McGrath 	struct page **pages;
3283fa5dc22fSRoland McGrath 
3284f872f540SAndy Lutomirski 	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3285a62c34bdSAndy Lutomirski 		pages = vma->vm_private_data;
3286f872f540SAndy Lutomirski 	} else {
3287f872f540SAndy Lutomirski 		struct vm_special_mapping *sm = vma->vm_private_data;
3288f872f540SAndy Lutomirski 
3289f872f540SAndy Lutomirski 		if (sm->fault)
329011bac800SDave Jiang 			return sm->fault(sm, vmf->vma, vmf);
3291f872f540SAndy Lutomirski 
3292f872f540SAndy Lutomirski 		pages = sm->pages;
3293f872f540SAndy Lutomirski 	}
3294a62c34bdSAndy Lutomirski 
32958a9cc3b5SOleg Nesterov 	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3296b1d0e4f5SNick Piggin 		pgoff--;
3297fa5dc22fSRoland McGrath 
3298fa5dc22fSRoland McGrath 	if (*pages) {
3299fa5dc22fSRoland McGrath 		struct page *page = *pages;
3300fa5dc22fSRoland McGrath 		get_page(page);
3301b1d0e4f5SNick Piggin 		vmf->page = page;
3302b1d0e4f5SNick Piggin 		return 0;
3303fa5dc22fSRoland McGrath 	}
3304fa5dc22fSRoland McGrath 
3305b1d0e4f5SNick Piggin 	return VM_FAULT_SIGBUS;
3306fa5dc22fSRoland McGrath }
3307fa5dc22fSRoland McGrath 
3308a62c34bdSAndy Lutomirski static struct vm_area_struct *__install_special_mapping(
3309a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3310fa5dc22fSRoland McGrath 	unsigned long addr, unsigned long len,
331127f28b97SChen Gang 	unsigned long vm_flags, void *priv,
331227f28b97SChen Gang 	const struct vm_operations_struct *ops)
3313fa5dc22fSRoland McGrath {
3314462e635eSTavis Ormandy 	int ret;
3315fa5dc22fSRoland McGrath 	struct vm_area_struct *vma;
3316fa5dc22fSRoland McGrath 
3317d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
3318490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
3319fa5dc22fSRoland McGrath 	if (unlikely(vma == NULL))
33203935ed6aSStefani Seibold 		return ERR_PTR(-ENOMEM);
3321fa5dc22fSRoland McGrath 
3322fa5dc22fSRoland McGrath 	vma->vm_start = addr;
3323fa5dc22fSRoland McGrath 	vma->vm_end = addr + len;
3324fa5dc22fSRoland McGrath 
3325d9104d1cSCyrill Gorcunov 	vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
33261fc09228SHugh Dickins 	vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
33273ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3328fa5dc22fSRoland McGrath 
3329a62c34bdSAndy Lutomirski 	vma->vm_ops = ops;
3330a62c34bdSAndy Lutomirski 	vma->vm_private_data = priv;
3331fa5dc22fSRoland McGrath 
3332462e635eSTavis Ormandy 	ret = insert_vm_struct(mm, vma);
3333462e635eSTavis Ormandy 	if (ret)
3334462e635eSTavis Ormandy 		goto out;
3335fa5dc22fSRoland McGrath 
333684638335SKonstantin Khlebnikov 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3337fa5dc22fSRoland McGrath 
3338cdd6c482SIngo Molnar 	perf_event_mmap(vma);
3339089dd79dSPeter Zijlstra 
3340d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
33413935ed6aSStefani Seibold 	return vma;
3342462e635eSTavis Ormandy 
3343462e635eSTavis Ormandy out:
33443928d4f5SLinus Torvalds 	vm_area_free(vma);
3345d4af56c5SLiam R. Howlett 	validate_mm_mt(mm);
33463935ed6aSStefani Seibold 	return ERR_PTR(ret);
33473935ed6aSStefani Seibold }
33483935ed6aSStefani Seibold 
33492eefd878SDmitry Safonov bool vma_is_special_mapping(const struct vm_area_struct *vma,
33502eefd878SDmitry Safonov 	const struct vm_special_mapping *sm)
33512eefd878SDmitry Safonov {
33522eefd878SDmitry Safonov 	return vma->vm_private_data == sm &&
33532eefd878SDmitry Safonov 		(vma->vm_ops == &special_mapping_vmops ||
33542eefd878SDmitry Safonov 		 vma->vm_ops == &legacy_special_mapping_vmops);
33552eefd878SDmitry Safonov }
33562eefd878SDmitry Safonov 
3357a62c34bdSAndy Lutomirski /*
3358c1e8d7c6SMichel Lespinasse  * Called with mm->mmap_lock held for writing.
3359a62c34bdSAndy Lutomirski  * Insert a new vma covering the given region, with the given flags.
3360a62c34bdSAndy Lutomirski  * Its pages are supplied by the given array of struct page *.
3361a62c34bdSAndy Lutomirski  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3362a62c34bdSAndy Lutomirski  * The region past the last page supplied will always produce SIGBUS.
3363a62c34bdSAndy Lutomirski  * The array pointer and the pages it points to are assumed to stay alive
3364a62c34bdSAndy Lutomirski  * for as long as this mapping might exist.
3365a62c34bdSAndy Lutomirski  */
3366a62c34bdSAndy Lutomirski struct vm_area_struct *_install_special_mapping(
3367a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3368a62c34bdSAndy Lutomirski 	unsigned long addr, unsigned long len,
3369a62c34bdSAndy Lutomirski 	unsigned long vm_flags, const struct vm_special_mapping *spec)
3370a62c34bdSAndy Lutomirski {
337127f28b97SChen Gang 	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
337227f28b97SChen Gang 					&special_mapping_vmops);
3373a62c34bdSAndy Lutomirski }
3374a62c34bdSAndy Lutomirski 
33753935ed6aSStefani Seibold int install_special_mapping(struct mm_struct *mm,
33763935ed6aSStefani Seibold 			    unsigned long addr, unsigned long len,
33773935ed6aSStefani Seibold 			    unsigned long vm_flags, struct page **pages)
33783935ed6aSStefani Seibold {
3379a62c34bdSAndy Lutomirski 	struct vm_area_struct *vma = __install_special_mapping(
338027f28b97SChen Gang 		mm, addr, len, vm_flags, (void *)pages,
338127f28b97SChen Gang 		&legacy_special_mapping_vmops);
33823935ed6aSStefani Seibold 
338314bd5b45SDuan Jiong 	return PTR_ERR_OR_ZERO(vma);
3384fa5dc22fSRoland McGrath }
33857906d00cSAndrea Arcangeli 
33867906d00cSAndrea Arcangeli static DEFINE_MUTEX(mm_all_locks_mutex);
33877906d00cSAndrea Arcangeli 
3388454ed842SPeter Zijlstra static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
33897906d00cSAndrea Arcangeli {
3390f808c13fSDavidlohr Bueso 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
33917906d00cSAndrea Arcangeli 		/*
33927906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change from under us
33937906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
33947906d00cSAndrea Arcangeli 		 */
3395da1c55f1SMichel Lespinasse 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
33967906d00cSAndrea Arcangeli 		/*
33977906d00cSAndrea Arcangeli 		 * We can safely modify head.next after taking the
33985a505085SIngo Molnar 		 * anon_vma->root->rwsem. If some other vma in this mm shares
33997906d00cSAndrea Arcangeli 		 * the same anon_vma we won't take it again.
34007906d00cSAndrea Arcangeli 		 *
34017906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
34027906d00cSAndrea Arcangeli 		 * can't change from under us thanks to the
34035a505085SIngo Molnar 		 * anon_vma->root->rwsem.
34047906d00cSAndrea Arcangeli 		 */
34057906d00cSAndrea Arcangeli 		if (__test_and_set_bit(0, (unsigned long *)
3406f808c13fSDavidlohr Bueso 				       &anon_vma->root->rb_root.rb_root.rb_node))
34077906d00cSAndrea Arcangeli 			BUG();
34087906d00cSAndrea Arcangeli 	}
34097906d00cSAndrea Arcangeli }
34107906d00cSAndrea Arcangeli 
3411454ed842SPeter Zijlstra static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
34127906d00cSAndrea Arcangeli {
34137906d00cSAndrea Arcangeli 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
34147906d00cSAndrea Arcangeli 		/*
34157906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change from under us because
34167906d00cSAndrea Arcangeli 		 * we hold the mm_all_locks_mutex.
34177906d00cSAndrea Arcangeli 		 *
34187906d00cSAndrea Arcangeli 		 * Operations on ->flags have to be atomic because
34197906d00cSAndrea Arcangeli 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
34207906d00cSAndrea Arcangeli 		 * mm_all_locks_mutex, there may be other cpus
34217906d00cSAndrea Arcangeli 		 * changing other bitflags in parallel to us.
34227906d00cSAndrea Arcangeli 		 */
34237906d00cSAndrea Arcangeli 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
34247906d00cSAndrea Arcangeli 			BUG();
3425da1c55f1SMichel Lespinasse 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
34267906d00cSAndrea Arcangeli 	}
34277906d00cSAndrea Arcangeli }
34287906d00cSAndrea Arcangeli 
34297906d00cSAndrea Arcangeli /*
34307906d00cSAndrea Arcangeli  * This operation locks against the VM for all pte/vma/mm related
34317906d00cSAndrea Arcangeli  * operations that could ever happen on a certain mm. This includes
34327906d00cSAndrea Arcangeli  * vmtruncate, try_to_unmap, and all page faults.
34337906d00cSAndrea Arcangeli  *
3434c1e8d7c6SMichel Lespinasse  * The caller must take the mmap_lock in write mode before calling
34357906d00cSAndrea Arcangeli  * mm_take_all_locks(). The caller isn't allowed to release the
3436c1e8d7c6SMichel Lespinasse  * mmap_lock until mm_drop_all_locks() returns.
34377906d00cSAndrea Arcangeli  *
3438c1e8d7c6SMichel Lespinasse  * mmap_lock in write mode is required in order to block all operations
34397906d00cSAndrea Arcangeli  * that could modify pagetables and free pages without need of
344027ba0644SKirill A. Shutemov  * altering the vma layout. It's also needed in write mode to avoid new
34417906d00cSAndrea Arcangeli  * anon_vmas to be associated with existing vmas.
34427906d00cSAndrea Arcangeli  *
34437906d00cSAndrea Arcangeli  * A single task can't take more than one mm_take_all_locks() in a row
34447906d00cSAndrea Arcangeli  * or it would deadlock.
34457906d00cSAndrea Arcangeli  *
3446bf181b9fSMichel Lespinasse  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
34477906d00cSAndrea Arcangeli  * mapping->flags avoid to take the same lock twice, if more than one
34487906d00cSAndrea Arcangeli  * vma in this mm is backed by the same anon_vma or address_space.
34497906d00cSAndrea Arcangeli  *
345088f306b6SKirill A. Shutemov  * We take locks in following order, accordingly to comment at beginning
345188f306b6SKirill A. Shutemov  * of mm/rmap.c:
345288f306b6SKirill A. Shutemov  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
345388f306b6SKirill A. Shutemov  *     hugetlb mapping);
345488f306b6SKirill A. Shutemov  *   - all i_mmap_rwsem locks;
345588f306b6SKirill A. Shutemov  *   - all anon_vma->rwseml
345688f306b6SKirill A. Shutemov  *
345788f306b6SKirill A. Shutemov  * We can take all locks within these types randomly because the VM code
345888f306b6SKirill A. Shutemov  * doesn't nest them and we protected from parallel mm_take_all_locks() by
345988f306b6SKirill A. Shutemov  * mm_all_locks_mutex.
34607906d00cSAndrea Arcangeli  *
34617906d00cSAndrea Arcangeli  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
34627906d00cSAndrea Arcangeli  * that may have to take thousand of locks.
34637906d00cSAndrea Arcangeli  *
34647906d00cSAndrea Arcangeli  * mm_take_all_locks() can fail if it's interrupted by signals.
34657906d00cSAndrea Arcangeli  */
34667906d00cSAndrea Arcangeli int mm_take_all_locks(struct mm_struct *mm)
34677906d00cSAndrea Arcangeli {
34687906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
34695beb4930SRik van Riel 	struct anon_vma_chain *avc;
34707906d00cSAndrea Arcangeli 
3471325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
34727906d00cSAndrea Arcangeli 
34737906d00cSAndrea Arcangeli 	mutex_lock(&mm_all_locks_mutex);
34747906d00cSAndrea Arcangeli 
34757906d00cSAndrea Arcangeli 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
34767906d00cSAndrea Arcangeli 		if (signal_pending(current))
34777906d00cSAndrea Arcangeli 			goto out_unlock;
347888f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
347988f306b6SKirill A. Shutemov 				is_vm_hugetlb_page(vma))
348088f306b6SKirill A. Shutemov 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
348188f306b6SKirill A. Shutemov 	}
348288f306b6SKirill A. Shutemov 
348388f306b6SKirill A. Shutemov 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
348488f306b6SKirill A. Shutemov 		if (signal_pending(current))
348588f306b6SKirill A. Shutemov 			goto out_unlock;
348688f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
348788f306b6SKirill A. Shutemov 				!is_vm_hugetlb_page(vma))
3488454ed842SPeter Zijlstra 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
34897906d00cSAndrea Arcangeli 	}
34907cd5a02fSPeter Zijlstra 
34917cd5a02fSPeter Zijlstra 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
34927cd5a02fSPeter Zijlstra 		if (signal_pending(current))
34937cd5a02fSPeter Zijlstra 			goto out_unlock;
34947cd5a02fSPeter Zijlstra 		if (vma->anon_vma)
34955beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
34965beb4930SRik van Riel 				vm_lock_anon_vma(mm, avc->anon_vma);
34977cd5a02fSPeter Zijlstra 	}
34987cd5a02fSPeter Zijlstra 
3499584cff54SKautuk Consul 	return 0;
35007906d00cSAndrea Arcangeli 
35017906d00cSAndrea Arcangeli out_unlock:
35027906d00cSAndrea Arcangeli 	mm_drop_all_locks(mm);
3503584cff54SKautuk Consul 	return -EINTR;
35047906d00cSAndrea Arcangeli }
35057906d00cSAndrea Arcangeli 
35067906d00cSAndrea Arcangeli static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
35077906d00cSAndrea Arcangeli {
3508f808c13fSDavidlohr Bueso 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
35097906d00cSAndrea Arcangeli 		/*
35107906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change to 0 from under
35117906d00cSAndrea Arcangeli 		 * us because we hold the mm_all_locks_mutex.
35127906d00cSAndrea Arcangeli 		 *
35137906d00cSAndrea Arcangeli 		 * We must however clear the bitflag before unlocking
3514bf181b9fSMichel Lespinasse 		 * the vma so the users using the anon_vma->rb_root will
35157906d00cSAndrea Arcangeli 		 * never see our bitflag.
35167906d00cSAndrea Arcangeli 		 *
35177906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
35187906d00cSAndrea Arcangeli 		 * can't change from under us until we release the
35195a505085SIngo Molnar 		 * anon_vma->root->rwsem.
35207906d00cSAndrea Arcangeli 		 */
35217906d00cSAndrea Arcangeli 		if (!__test_and_clear_bit(0, (unsigned long *)
3522f808c13fSDavidlohr Bueso 					  &anon_vma->root->rb_root.rb_root.rb_node))
35237906d00cSAndrea Arcangeli 			BUG();
352408b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
35257906d00cSAndrea Arcangeli 	}
35267906d00cSAndrea Arcangeli }
35277906d00cSAndrea Arcangeli 
35287906d00cSAndrea Arcangeli static void vm_unlock_mapping(struct address_space *mapping)
35297906d00cSAndrea Arcangeli {
35307906d00cSAndrea Arcangeli 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
35317906d00cSAndrea Arcangeli 		/*
35327906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
35337906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
35347906d00cSAndrea Arcangeli 		 */
353583cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
35367906d00cSAndrea Arcangeli 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
35377906d00cSAndrea Arcangeli 					&mapping->flags))
35387906d00cSAndrea Arcangeli 			BUG();
35397906d00cSAndrea Arcangeli 	}
35407906d00cSAndrea Arcangeli }
35417906d00cSAndrea Arcangeli 
35427906d00cSAndrea Arcangeli /*
3543c1e8d7c6SMichel Lespinasse  * The mmap_lock cannot be released by the caller until
35447906d00cSAndrea Arcangeli  * mm_drop_all_locks() returns.
35457906d00cSAndrea Arcangeli  */
35467906d00cSAndrea Arcangeli void mm_drop_all_locks(struct mm_struct *mm)
35477906d00cSAndrea Arcangeli {
35487906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
35495beb4930SRik van Riel 	struct anon_vma_chain *avc;
35507906d00cSAndrea Arcangeli 
3551325bca1fSRolf Eike Beer 	mmap_assert_write_locked(mm);
35527906d00cSAndrea Arcangeli 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
35537906d00cSAndrea Arcangeli 
35547906d00cSAndrea Arcangeli 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
35557906d00cSAndrea Arcangeli 		if (vma->anon_vma)
35565beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
35575beb4930SRik van Riel 				vm_unlock_anon_vma(avc->anon_vma);
35587906d00cSAndrea Arcangeli 		if (vma->vm_file && vma->vm_file->f_mapping)
35597906d00cSAndrea Arcangeli 			vm_unlock_mapping(vma->vm_file->f_mapping);
35607906d00cSAndrea Arcangeli 	}
35617906d00cSAndrea Arcangeli 
35627906d00cSAndrea Arcangeli 	mutex_unlock(&mm_all_locks_mutex);
35637906d00cSAndrea Arcangeli }
35648feae131SDavid Howells 
35658feae131SDavid Howells /*
35663edf41d8Sseokhoon.yoon  * initialise the percpu counter for VM
35678feae131SDavid Howells  */
35688feae131SDavid Howells void __init mmap_init(void)
35698feae131SDavid Howells {
357000a62ce9SKOSAKI Motohiro 	int ret;
357100a62ce9SKOSAKI Motohiro 
3572908c7f19STejun Heo 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
357300a62ce9SKOSAKI Motohiro 	VM_BUG_ON(ret);
35748feae131SDavid Howells }
3575c9b1d098SAndrew Shewmaker 
3576c9b1d098SAndrew Shewmaker /*
3577c9b1d098SAndrew Shewmaker  * Initialise sysctl_user_reserve_kbytes.
3578c9b1d098SAndrew Shewmaker  *
3579c9b1d098SAndrew Shewmaker  * This is intended to prevent a user from starting a single memory hogging
3580c9b1d098SAndrew Shewmaker  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3581c9b1d098SAndrew Shewmaker  * mode.
3582c9b1d098SAndrew Shewmaker  *
3583c9b1d098SAndrew Shewmaker  * The default value is min(3% of free memory, 128MB)
3584c9b1d098SAndrew Shewmaker  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3585c9b1d098SAndrew Shewmaker  */
35861640879aSAndrew Shewmaker static int init_user_reserve(void)
3587c9b1d098SAndrew Shewmaker {
3588c9b1d098SAndrew Shewmaker 	unsigned long free_kbytes;
3589c9b1d098SAndrew Shewmaker 
3590c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3591c9b1d098SAndrew Shewmaker 
3592c9b1d098SAndrew Shewmaker 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3593c9b1d098SAndrew Shewmaker 	return 0;
3594c9b1d098SAndrew Shewmaker }
3595a64fb3cdSPaul Gortmaker subsys_initcall(init_user_reserve);
35964eeab4f5SAndrew Shewmaker 
35974eeab4f5SAndrew Shewmaker /*
35984eeab4f5SAndrew Shewmaker  * Initialise sysctl_admin_reserve_kbytes.
35994eeab4f5SAndrew Shewmaker  *
36004eeab4f5SAndrew Shewmaker  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
36014eeab4f5SAndrew Shewmaker  * to log in and kill a memory hogging process.
36024eeab4f5SAndrew Shewmaker  *
36034eeab4f5SAndrew Shewmaker  * Systems with more than 256MB will reserve 8MB, enough to recover
36044eeab4f5SAndrew Shewmaker  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
36054eeab4f5SAndrew Shewmaker  * only reserve 3% of free pages by default.
36064eeab4f5SAndrew Shewmaker  */
36071640879aSAndrew Shewmaker static int init_admin_reserve(void)
36084eeab4f5SAndrew Shewmaker {
36094eeab4f5SAndrew Shewmaker 	unsigned long free_kbytes;
36104eeab4f5SAndrew Shewmaker 
3611c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
36124eeab4f5SAndrew Shewmaker 
36134eeab4f5SAndrew Shewmaker 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
36144eeab4f5SAndrew Shewmaker 	return 0;
36154eeab4f5SAndrew Shewmaker }
3616a64fb3cdSPaul Gortmaker subsys_initcall(init_admin_reserve);
36171640879aSAndrew Shewmaker 
36181640879aSAndrew Shewmaker /*
36191640879aSAndrew Shewmaker  * Reinititalise user and admin reserves if memory is added or removed.
36201640879aSAndrew Shewmaker  *
36211640879aSAndrew Shewmaker  * The default user reserve max is 128MB, and the default max for the
36221640879aSAndrew Shewmaker  * admin reserve is 8MB. These are usually, but not always, enough to
36231640879aSAndrew Shewmaker  * enable recovery from a memory hogging process using login/sshd, a shell,
36241640879aSAndrew Shewmaker  * and tools like top. It may make sense to increase or even disable the
36251640879aSAndrew Shewmaker  * reserve depending on the existence of swap or variations in the recovery
36261640879aSAndrew Shewmaker  * tools. So, the admin may have changed them.
36271640879aSAndrew Shewmaker  *
36281640879aSAndrew Shewmaker  * If memory is added and the reserves have been eliminated or increased above
36291640879aSAndrew Shewmaker  * the default max, then we'll trust the admin.
36301640879aSAndrew Shewmaker  *
36311640879aSAndrew Shewmaker  * If memory is removed and there isn't enough free memory, then we
36321640879aSAndrew Shewmaker  * need to reset the reserves.
36331640879aSAndrew Shewmaker  *
36341640879aSAndrew Shewmaker  * Otherwise keep the reserve set by the admin.
36351640879aSAndrew Shewmaker  */
36361640879aSAndrew Shewmaker static int reserve_mem_notifier(struct notifier_block *nb,
36371640879aSAndrew Shewmaker 			     unsigned long action, void *data)
36381640879aSAndrew Shewmaker {
36391640879aSAndrew Shewmaker 	unsigned long tmp, free_kbytes;
36401640879aSAndrew Shewmaker 
36411640879aSAndrew Shewmaker 	switch (action) {
36421640879aSAndrew Shewmaker 	case MEM_ONLINE:
36431640879aSAndrew Shewmaker 		/* Default max is 128MB. Leave alone if modified by operator. */
36441640879aSAndrew Shewmaker 		tmp = sysctl_user_reserve_kbytes;
36451640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 17))
36461640879aSAndrew Shewmaker 			init_user_reserve();
36471640879aSAndrew Shewmaker 
36481640879aSAndrew Shewmaker 		/* Default max is 8MB.  Leave alone if modified by operator. */
36491640879aSAndrew Shewmaker 		tmp = sysctl_admin_reserve_kbytes;
36501640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 13))
36511640879aSAndrew Shewmaker 			init_admin_reserve();
36521640879aSAndrew Shewmaker 
36531640879aSAndrew Shewmaker 		break;
36541640879aSAndrew Shewmaker 	case MEM_OFFLINE:
3655c41f012aSMichal Hocko 		free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
36561640879aSAndrew Shewmaker 
36571640879aSAndrew Shewmaker 		if (sysctl_user_reserve_kbytes > free_kbytes) {
36581640879aSAndrew Shewmaker 			init_user_reserve();
36591640879aSAndrew Shewmaker 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
36601640879aSAndrew Shewmaker 				sysctl_user_reserve_kbytes);
36611640879aSAndrew Shewmaker 		}
36621640879aSAndrew Shewmaker 
36631640879aSAndrew Shewmaker 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
36641640879aSAndrew Shewmaker 			init_admin_reserve();
36651640879aSAndrew Shewmaker 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
36661640879aSAndrew Shewmaker 				sysctl_admin_reserve_kbytes);
36671640879aSAndrew Shewmaker 		}
36681640879aSAndrew Shewmaker 		break;
36691640879aSAndrew Shewmaker 	default:
36701640879aSAndrew Shewmaker 		break;
36711640879aSAndrew Shewmaker 	}
36721640879aSAndrew Shewmaker 	return NOTIFY_OK;
36731640879aSAndrew Shewmaker }
36741640879aSAndrew Shewmaker 
36751640879aSAndrew Shewmaker static struct notifier_block reserve_mem_nb = {
36761640879aSAndrew Shewmaker 	.notifier_call = reserve_mem_notifier,
36771640879aSAndrew Shewmaker };
36781640879aSAndrew Shewmaker 
36791640879aSAndrew Shewmaker static int __meminit init_reserve_notifier(void)
36801640879aSAndrew Shewmaker {
36811640879aSAndrew Shewmaker 	if (register_hotmemory_notifier(&reserve_mem_nb))
3682b1de0d13SMitchel Humpherys 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
36831640879aSAndrew Shewmaker 
36841640879aSAndrew Shewmaker 	return 0;
36851640879aSAndrew Shewmaker }
3686a64fb3cdSPaul Gortmaker subsys_initcall(init_reserve_notifier);
3687