xref: /linux/mm/mmap.c (revision 9b593cb20283e68e5e65b09ca10038935297f05b)
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>
16615d6e87SDavidlohr Bueso #include <linux/vmacache.h>
171da177e4SLinus Torvalds #include <linux/shm.h>
181da177e4SLinus Torvalds #include <linux/mman.h>
191da177e4SLinus Torvalds #include <linux/pagemap.h>
201da177e4SLinus Torvalds #include <linux/swap.h>
211da177e4SLinus Torvalds #include <linux/syscalls.h>
22c59ede7bSRandy.Dunlap #include <linux/capability.h>
231da177e4SLinus Torvalds #include <linux/init.h>
241da177e4SLinus Torvalds #include <linux/file.h>
251da177e4SLinus Torvalds #include <linux/fs.h>
261da177e4SLinus Torvalds #include <linux/personality.h>
271da177e4SLinus Torvalds #include <linux/security.h>
281da177e4SLinus Torvalds #include <linux/hugetlb.h>
29c01d5b30SHugh Dickins #include <linux/shmem_fs.h>
301da177e4SLinus Torvalds #include <linux/profile.h>
31b95f1b31SPaul Gortmaker #include <linux/export.h>
321da177e4SLinus Torvalds #include <linux/mount.h>
331da177e4SLinus Torvalds #include <linux/mempolicy.h>
341da177e4SLinus Torvalds #include <linux/rmap.h>
35cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
3682f71ae4SKonstantin Khlebnikov #include <linux/mmdebug.h>
37cdd6c482SIngo Molnar #include <linux/perf_event.h>
38120a795dSAl Viro #include <linux/audit.h>
39b15d00b6SAndrea Arcangeli #include <linux/khugepaged.h>
402b144498SSrikar Dronamraju #include <linux/uprobes.h>
41d3737187SMichel Lespinasse #include <linux/rbtree_augmented.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 
831da177e4SLinus Torvalds /* description of effects of mapping type and prot in current implementation.
841da177e4SLinus Torvalds  * this is due to the limited x86 page protection hardware.  The expected
851da177e4SLinus Torvalds  * behavior is in parens:
861da177e4SLinus Torvalds  *
871da177e4SLinus Torvalds  * map_type	prot
881da177e4SLinus Torvalds  *		PROT_NONE	PROT_READ	PROT_WRITE	PROT_EXEC
891da177e4SLinus Torvalds  * MAP_SHARED	r: (no) no	r: (yes) yes	r: (no) yes	r: (no) yes
901da177e4SLinus Torvalds  *		w: (no) no	w: (no) no	w: (yes) yes	w: (no) no
911da177e4SLinus Torvalds  *		x: (no) no	x: (no) yes	x: (no) yes	x: (yes) yes
921da177e4SLinus Torvalds  *
931da177e4SLinus Torvalds  * MAP_PRIVATE	r: (no) no	r: (yes) yes	r: (no) yes	r: (no) yes
941da177e4SLinus Torvalds  *		w: (no) no	w: (no) no	w: (copy) copy	w: (no) no
951da177e4SLinus Torvalds  *		x: (no) no	x: (no) yes	x: (no) yes	x: (yes) yes
9618107f8aSVladimir Murzin  *
9718107f8aSVladimir Murzin  * On arm64, PROT_EXEC has the following behaviour for both MAP_SHARED and
9818107f8aSVladimir Murzin  * MAP_PRIVATE (with Enhanced PAN supported):
9918107f8aSVladimir Murzin  *								r: (no) no
10018107f8aSVladimir Murzin  *								w: (no) no
10118107f8aSVladimir Murzin  *								x: (yes) yes
1021da177e4SLinus Torvalds  */
103ac34ceafSDaniel Micay pgprot_t protection_map[16] __ro_after_init = {
1041da177e4SLinus Torvalds 	__P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
1051da177e4SLinus Torvalds 	__S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
1061da177e4SLinus Torvalds };
1071da177e4SLinus Torvalds 
108316d097cSDave Hansen #ifndef CONFIG_ARCH_HAS_FILTER_PGPROT
109316d097cSDave Hansen static inline pgprot_t arch_filter_pgprot(pgprot_t prot)
110316d097cSDave Hansen {
111316d097cSDave Hansen 	return prot;
112316d097cSDave Hansen }
113316d097cSDave Hansen #endif
114316d097cSDave Hansen 
115804af2cfSHugh Dickins pgprot_t vm_get_page_prot(unsigned long vm_flags)
116804af2cfSHugh Dickins {
117316d097cSDave Hansen 	pgprot_t ret = __pgprot(pgprot_val(protection_map[vm_flags &
118b845f313SDave Kleikamp 				(VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
119b845f313SDave Kleikamp 			pgprot_val(arch_vm_get_page_prot(vm_flags)));
120316d097cSDave Hansen 
121316d097cSDave Hansen 	return arch_filter_pgprot(ret);
122804af2cfSHugh Dickins }
123804af2cfSHugh Dickins EXPORT_SYMBOL(vm_get_page_prot);
124804af2cfSHugh Dickins 
12564e45507SPeter Feiner static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
12664e45507SPeter Feiner {
12764e45507SPeter Feiner 	return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
12864e45507SPeter Feiner }
12964e45507SPeter Feiner 
13064e45507SPeter Feiner /* Update vma->vm_page_prot to reflect vma->vm_flags. */
13164e45507SPeter Feiner void vma_set_page_prot(struct vm_area_struct *vma)
13264e45507SPeter Feiner {
13364e45507SPeter Feiner 	unsigned long vm_flags = vma->vm_flags;
1346d2329f8SAndrea Arcangeli 	pgprot_t vm_page_prot;
13564e45507SPeter Feiner 
1366d2329f8SAndrea Arcangeli 	vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
1376d2329f8SAndrea Arcangeli 	if (vma_wants_writenotify(vma, vm_page_prot)) {
13864e45507SPeter Feiner 		vm_flags &= ~VM_SHARED;
1396d2329f8SAndrea Arcangeli 		vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
14064e45507SPeter Feiner 	}
141c1e8d7c6SMichel Lespinasse 	/* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
1426d2329f8SAndrea Arcangeli 	WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
14364e45507SPeter Feiner }
14464e45507SPeter Feiner 
1451da177e4SLinus Torvalds /*
146c8c06efaSDavidlohr Bueso  * Requires inode->i_mapping->i_mmap_rwsem
1471da177e4SLinus Torvalds  */
1481da177e4SLinus Torvalds static void __remove_shared_vm_struct(struct vm_area_struct *vma,
1491da177e4SLinus Torvalds 		struct file *file, struct address_space *mapping)
1501da177e4SLinus Torvalds {
1511da177e4SLinus Torvalds 	if (vma->vm_flags & VM_DENYWRITE)
152cb48841fSMiaohe Lin 		allow_write_access(file);
1531da177e4SLinus Torvalds 	if (vma->vm_flags & VM_SHARED)
1544bb5f5d9SDavid Herrmann 		mapping_unmap_writable(mapping);
1551da177e4SLinus Torvalds 
1561da177e4SLinus Torvalds 	flush_dcache_mmap_lock(mapping);
1576b2dbba8SMichel Lespinasse 	vma_interval_tree_remove(vma, &mapping->i_mmap);
1581da177e4SLinus Torvalds 	flush_dcache_mmap_unlock(mapping);
1591da177e4SLinus Torvalds }
1601da177e4SLinus Torvalds 
1611da177e4SLinus Torvalds /*
1626b2dbba8SMichel Lespinasse  * Unlink a file-based vm structure from its interval tree, to hide
163a8fb5618SHugh Dickins  * vma from rmap and vmtruncate before freeing its page tables.
1641da177e4SLinus Torvalds  */
165a8fb5618SHugh Dickins void unlink_file_vma(struct vm_area_struct *vma)
1661da177e4SLinus Torvalds {
1671da177e4SLinus Torvalds 	struct file *file = vma->vm_file;
1681da177e4SLinus Torvalds 
1691da177e4SLinus Torvalds 	if (file) {
1701da177e4SLinus Torvalds 		struct address_space *mapping = file->f_mapping;
17183cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
1721da177e4SLinus Torvalds 		__remove_shared_vm_struct(vma, file, mapping);
17383cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
1741da177e4SLinus Torvalds 	}
175a8fb5618SHugh Dickins }
176a8fb5618SHugh Dickins 
177a8fb5618SHugh Dickins /*
178a8fb5618SHugh Dickins  * Close a vm structure and free it, returning the next.
179a8fb5618SHugh Dickins  */
180a8fb5618SHugh Dickins static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
181a8fb5618SHugh Dickins {
182a8fb5618SHugh Dickins 	struct vm_area_struct *next = vma->vm_next;
183a8fb5618SHugh Dickins 
184a8fb5618SHugh Dickins 	might_sleep();
1851da177e4SLinus Torvalds 	if (vma->vm_ops && vma->vm_ops->close)
1861da177e4SLinus Torvalds 		vma->vm_ops->close(vma);
187e9714acfSKonstantin Khlebnikov 	if (vma->vm_file)
188a8fb5618SHugh Dickins 		fput(vma->vm_file);
189f0be3d32SLee Schermerhorn 	mpol_put(vma_policy(vma));
1903928d4f5SLinus Torvalds 	vm_area_free(vma);
191a8fb5618SHugh Dickins 	return next;
1921da177e4SLinus Torvalds }
1931da177e4SLinus Torvalds 
194bb177a73SMichal Hocko static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long flags,
195bb177a73SMichal Hocko 		struct list_head *uf);
1966a6160a7SHeiko Carstens SYSCALL_DEFINE1(brk, unsigned long, brk)
1971da177e4SLinus Torvalds {
1989bc8039eSYang Shi 	unsigned long newbrk, oldbrk, origbrk;
1991da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
2001be7107fSHugh Dickins 	struct vm_area_struct *next;
201a5b4592cSJiri Kosina 	unsigned long min_brk;
202128557ffSMichel Lespinasse 	bool populate;
2039bc8039eSYang Shi 	bool downgraded = false;
204897ab3e0SMike Rapoport 	LIST_HEAD(uf);
2051da177e4SLinus Torvalds 
206d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
207dc0ef0dfSMichal Hocko 		return -EINTR;
2081da177e4SLinus Torvalds 
2099bc8039eSYang Shi 	origbrk = mm->brk;
2109bc8039eSYang Shi 
211a5b4592cSJiri Kosina #ifdef CONFIG_COMPAT_BRK
2125520e894SJiri Kosina 	/*
2135520e894SJiri Kosina 	 * CONFIG_COMPAT_BRK can still be overridden by setting
2145520e894SJiri Kosina 	 * randomize_va_space to 2, which will still cause mm->start_brk
2155520e894SJiri Kosina 	 * to be arbitrarily shifted
2165520e894SJiri Kosina 	 */
2174471a675SJiri Kosina 	if (current->brk_randomized)
2185520e894SJiri Kosina 		min_brk = mm->start_brk;
2195520e894SJiri Kosina 	else
2205520e894SJiri Kosina 		min_brk = mm->end_data;
221a5b4592cSJiri Kosina #else
222a5b4592cSJiri Kosina 	min_brk = mm->start_brk;
223a5b4592cSJiri Kosina #endif
224a5b4592cSJiri Kosina 	if (brk < min_brk)
2251da177e4SLinus Torvalds 		goto out;
2261e624196SRam Gupta 
2271e624196SRam Gupta 	/*
2281e624196SRam Gupta 	 * Check against rlimit here. If this check is done later after the test
2291e624196SRam Gupta 	 * of oldbrk with newbrk then it can escape the test and let the data
2301e624196SRam Gupta 	 * segment grow beyond its set limit the in case where the limit is
2311e624196SRam Gupta 	 * not page aligned -Ram Gupta
2321e624196SRam Gupta 	 */
2338764b338SCyrill Gorcunov 	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
2348764b338SCyrill Gorcunov 			      mm->end_data, mm->start_data))
2351e624196SRam Gupta 		goto out;
2361e624196SRam Gupta 
2371da177e4SLinus Torvalds 	newbrk = PAGE_ALIGN(brk);
2381da177e4SLinus Torvalds 	oldbrk = PAGE_ALIGN(mm->brk);
2399bc8039eSYang Shi 	if (oldbrk == newbrk) {
2409bc8039eSYang Shi 		mm->brk = brk;
2419bc8039eSYang Shi 		goto success;
2429bc8039eSYang Shi 	}
2431da177e4SLinus Torvalds 
2449bc8039eSYang Shi 	/*
2459bc8039eSYang Shi 	 * Always allow shrinking brk.
246c1e8d7c6SMichel Lespinasse 	 * __do_munmap() may downgrade mmap_lock to read.
2479bc8039eSYang Shi 	 */
2481da177e4SLinus Torvalds 	if (brk <= mm->brk) {
2499bc8039eSYang Shi 		int ret;
2509bc8039eSYang Shi 
2519bc8039eSYang Shi 		/*
252c1e8d7c6SMichel Lespinasse 		 * mm->brk must to be protected by write mmap_lock so update it
253c1e8d7c6SMichel Lespinasse 		 * before downgrading mmap_lock. When __do_munmap() fails,
2549bc8039eSYang Shi 		 * mm->brk will be restored from origbrk.
2559bc8039eSYang Shi 		 */
2569bc8039eSYang Shi 		mm->brk = brk;
2579bc8039eSYang Shi 		ret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);
2589bc8039eSYang Shi 		if (ret < 0) {
2599bc8039eSYang Shi 			mm->brk = origbrk;
2601da177e4SLinus Torvalds 			goto out;
2619bc8039eSYang Shi 		} else if (ret == 1) {
2629bc8039eSYang Shi 			downgraded = true;
2639bc8039eSYang Shi 		}
2649bc8039eSYang Shi 		goto success;
2651da177e4SLinus Torvalds 	}
2661da177e4SLinus Torvalds 
2671da177e4SLinus Torvalds 	/* Check against existing mmap mappings. */
2681be7107fSHugh Dickins 	next = find_vma(mm, oldbrk);
2691be7107fSHugh Dickins 	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
2701da177e4SLinus Torvalds 		goto out;
2711da177e4SLinus Torvalds 
2721da177e4SLinus Torvalds 	/* Ok, looks good - let it rip. */
273bb177a73SMichal Hocko 	if (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)
2741da177e4SLinus Torvalds 		goto out;
2751da177e4SLinus Torvalds 	mm->brk = brk;
2769bc8039eSYang Shi 
2779bc8039eSYang Shi success:
278128557ffSMichel Lespinasse 	populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
2799bc8039eSYang Shi 	if (downgraded)
280d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
2819bc8039eSYang Shi 	else
282d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
283897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
284128557ffSMichel Lespinasse 	if (populate)
285128557ffSMichel Lespinasse 		mm_populate(oldbrk, newbrk - oldbrk);
286128557ffSMichel Lespinasse 	return brk;
287128557ffSMichel Lespinasse 
2881da177e4SLinus Torvalds out:
289d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
290b7204006SAdrian Huang 	return origbrk;
2911da177e4SLinus Torvalds }
2921da177e4SLinus Torvalds 
293315cc066SMichel Lespinasse static inline unsigned long vma_compute_gap(struct vm_area_struct *vma)
294d3737187SMichel Lespinasse {
295315cc066SMichel Lespinasse 	unsigned long gap, prev_end;
2961be7107fSHugh Dickins 
2971be7107fSHugh Dickins 	/*
2981be7107fSHugh Dickins 	 * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
2991be7107fSHugh Dickins 	 * allow two stack_guard_gaps between them here, and when choosing
3001be7107fSHugh Dickins 	 * an unmapped area; whereas when expanding we only require one.
3011be7107fSHugh Dickins 	 * That's a little inconsistent, but keeps the code here simpler.
3021be7107fSHugh Dickins 	 */
303315cc066SMichel Lespinasse 	gap = vm_start_gap(vma);
3041be7107fSHugh Dickins 	if (vma->vm_prev) {
3051be7107fSHugh Dickins 		prev_end = vm_end_gap(vma->vm_prev);
306315cc066SMichel Lespinasse 		if (gap > prev_end)
307315cc066SMichel Lespinasse 			gap -= prev_end;
3081be7107fSHugh Dickins 		else
309315cc066SMichel Lespinasse 			gap = 0;
3101be7107fSHugh Dickins 	}
311315cc066SMichel Lespinasse 	return gap;
312315cc066SMichel Lespinasse }
313315cc066SMichel Lespinasse 
314315cc066SMichel Lespinasse #ifdef CONFIG_DEBUG_VM_RB
315315cc066SMichel Lespinasse static unsigned long vma_compute_subtree_gap(struct vm_area_struct *vma)
316315cc066SMichel Lespinasse {
317315cc066SMichel Lespinasse 	unsigned long max = vma_compute_gap(vma), subtree_gap;
318d3737187SMichel Lespinasse 	if (vma->vm_rb.rb_left) {
319d3737187SMichel Lespinasse 		subtree_gap = rb_entry(vma->vm_rb.rb_left,
320d3737187SMichel Lespinasse 				struct vm_area_struct, vm_rb)->rb_subtree_gap;
321d3737187SMichel Lespinasse 		if (subtree_gap > max)
322d3737187SMichel Lespinasse 			max = subtree_gap;
323d3737187SMichel Lespinasse 	}
324d3737187SMichel Lespinasse 	if (vma->vm_rb.rb_right) {
325d3737187SMichel Lespinasse 		subtree_gap = rb_entry(vma->vm_rb.rb_right,
326d3737187SMichel Lespinasse 				struct vm_area_struct, vm_rb)->rb_subtree_gap;
327d3737187SMichel Lespinasse 		if (subtree_gap > max)
328d3737187SMichel Lespinasse 			max = subtree_gap;
329d3737187SMichel Lespinasse 	}
330d3737187SMichel Lespinasse 	return max;
331d3737187SMichel Lespinasse }
332d3737187SMichel Lespinasse 
333acf128d0SAndrea Arcangeli static int browse_rb(struct mm_struct *mm)
3341da177e4SLinus Torvalds {
335acf128d0SAndrea Arcangeli 	struct rb_root *root = &mm->mm_rb;
3365a0768f6SMichel Lespinasse 	int i = 0, j, bug = 0;
3371da177e4SLinus Torvalds 	struct rb_node *nd, *pn = NULL;
3381da177e4SLinus Torvalds 	unsigned long prev = 0, pend = 0;
3391da177e4SLinus Torvalds 
3401da177e4SLinus Torvalds 	for (nd = rb_first(root); nd; nd = rb_next(nd)) {
3411da177e4SLinus Torvalds 		struct vm_area_struct *vma;
3421da177e4SLinus Torvalds 		vma = rb_entry(nd, struct vm_area_struct, vm_rb);
3435a0768f6SMichel Lespinasse 		if (vma->vm_start < prev) {
344ff26f70fSAndrew Morton 			pr_emerg("vm_start %lx < prev %lx\n",
345ff26f70fSAndrew Morton 				  vma->vm_start, prev);
3465a0768f6SMichel Lespinasse 			bug = 1;
3475a0768f6SMichel Lespinasse 		}
3485a0768f6SMichel Lespinasse 		if (vma->vm_start < pend) {
349ff26f70fSAndrew Morton 			pr_emerg("vm_start %lx < pend %lx\n",
350ff26f70fSAndrew Morton 				  vma->vm_start, pend);
3515a0768f6SMichel Lespinasse 			bug = 1;
3525a0768f6SMichel Lespinasse 		}
3535a0768f6SMichel Lespinasse 		if (vma->vm_start > vma->vm_end) {
354ff26f70fSAndrew Morton 			pr_emerg("vm_start %lx > vm_end %lx\n",
355ff26f70fSAndrew Morton 				  vma->vm_start, vma->vm_end);
3565a0768f6SMichel Lespinasse 			bug = 1;
3575a0768f6SMichel Lespinasse 		}
358acf128d0SAndrea Arcangeli 		spin_lock(&mm->page_table_lock);
3595a0768f6SMichel Lespinasse 		if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
3608542bdfcSSasha Levin 			pr_emerg("free gap %lx, correct %lx\n",
3615a0768f6SMichel Lespinasse 			       vma->rb_subtree_gap,
3625a0768f6SMichel Lespinasse 			       vma_compute_subtree_gap(vma));
3635a0768f6SMichel Lespinasse 			bug = 1;
3645a0768f6SMichel Lespinasse 		}
365acf128d0SAndrea Arcangeli 		spin_unlock(&mm->page_table_lock);
3661da177e4SLinus Torvalds 		i++;
3671da177e4SLinus Torvalds 		pn = nd;
368d1af65d1SDavid Miller 		prev = vma->vm_start;
369d1af65d1SDavid Miller 		pend = vma->vm_end;
3701da177e4SLinus Torvalds 	}
3711da177e4SLinus Torvalds 	j = 0;
3725a0768f6SMichel Lespinasse 	for (nd = pn; nd; nd = rb_prev(nd))
3731da177e4SLinus Torvalds 		j++;
3745a0768f6SMichel Lespinasse 	if (i != j) {
3758542bdfcSSasha Levin 		pr_emerg("backwards %d, forwards %d\n", j, i);
3765a0768f6SMichel Lespinasse 		bug = 1;
3771da177e4SLinus Torvalds 	}
3785a0768f6SMichel Lespinasse 	return bug ? -1 : i;
3791da177e4SLinus Torvalds }
3801da177e4SLinus Torvalds 
381d3737187SMichel Lespinasse static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
382d3737187SMichel Lespinasse {
383d3737187SMichel Lespinasse 	struct rb_node *nd;
384d3737187SMichel Lespinasse 
385d3737187SMichel Lespinasse 	for (nd = rb_first(root); nd; nd = rb_next(nd)) {
386d3737187SMichel Lespinasse 		struct vm_area_struct *vma;
387d3737187SMichel Lespinasse 		vma = rb_entry(nd, struct vm_area_struct, vm_rb);
38896dad67fSSasha Levin 		VM_BUG_ON_VMA(vma != ignore &&
38996dad67fSSasha Levin 			vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
39096dad67fSSasha Levin 			vma);
391d3737187SMichel Lespinasse 	}
3921da177e4SLinus Torvalds }
3931da177e4SLinus Torvalds 
394eafd4dc4SRashika Kheria static void validate_mm(struct mm_struct *mm)
3951da177e4SLinus Torvalds {
3961da177e4SLinus Torvalds 	int bug = 0;
3971da177e4SLinus Torvalds 	int i = 0;
3985a0768f6SMichel Lespinasse 	unsigned long highest_address = 0;
399ed8ea815SMichel Lespinasse 	struct vm_area_struct *vma = mm->mmap;
400ff26f70fSAndrew Morton 
401ed8ea815SMichel Lespinasse 	while (vma) {
40212352d3cSKonstantin Khlebnikov 		struct anon_vma *anon_vma = vma->anon_vma;
403ed8ea815SMichel Lespinasse 		struct anon_vma_chain *avc;
404ff26f70fSAndrew Morton 
40512352d3cSKonstantin Khlebnikov 		if (anon_vma) {
40612352d3cSKonstantin Khlebnikov 			anon_vma_lock_read(anon_vma);
407ed8ea815SMichel Lespinasse 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
408ed8ea815SMichel Lespinasse 				anon_vma_interval_tree_verify(avc);
40912352d3cSKonstantin Khlebnikov 			anon_vma_unlock_read(anon_vma);
41012352d3cSKonstantin Khlebnikov 		}
41112352d3cSKonstantin Khlebnikov 
4121be7107fSHugh Dickins 		highest_address = vm_end_gap(vma);
413ed8ea815SMichel Lespinasse 		vma = vma->vm_next;
4141da177e4SLinus Torvalds 		i++;
4151da177e4SLinus Torvalds 	}
4165a0768f6SMichel Lespinasse 	if (i != mm->map_count) {
4178542bdfcSSasha Levin 		pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
4185a0768f6SMichel Lespinasse 		bug = 1;
4195a0768f6SMichel Lespinasse 	}
4205a0768f6SMichel Lespinasse 	if (highest_address != mm->highest_vm_end) {
4218542bdfcSSasha Levin 		pr_emerg("mm->highest_vm_end %lx, found %lx\n",
4225a0768f6SMichel Lespinasse 			  mm->highest_vm_end, highest_address);
4235a0768f6SMichel Lespinasse 		bug = 1;
4245a0768f6SMichel Lespinasse 	}
425acf128d0SAndrea Arcangeli 	i = browse_rb(mm);
4265a0768f6SMichel Lespinasse 	if (i != mm->map_count) {
427ff26f70fSAndrew Morton 		if (i != -1)
4288542bdfcSSasha Levin 			pr_emerg("map_count %d rb %d\n", mm->map_count, i);
4295a0768f6SMichel Lespinasse 		bug = 1;
4305a0768f6SMichel Lespinasse 	}
43196dad67fSSasha Levin 	VM_BUG_ON_MM(bug, mm);
4321da177e4SLinus Torvalds }
4331da177e4SLinus Torvalds #else
434d3737187SMichel Lespinasse #define validate_mm_rb(root, ignore) do { } while (0)
4351da177e4SLinus Torvalds #define validate_mm(mm) do { } while (0)
4361da177e4SLinus Torvalds #endif
4371da177e4SLinus Torvalds 
438315cc066SMichel Lespinasse RB_DECLARE_CALLBACKS_MAX(static, vma_gap_callbacks,
439315cc066SMichel Lespinasse 			 struct vm_area_struct, vm_rb,
440315cc066SMichel Lespinasse 			 unsigned long, rb_subtree_gap, vma_compute_gap)
441d3737187SMichel Lespinasse 
442d3737187SMichel Lespinasse /*
443d3737187SMichel Lespinasse  * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
444d3737187SMichel Lespinasse  * vma->vm_prev->vm_end values changed, without modifying the vma's position
445d3737187SMichel Lespinasse  * in the rbtree.
446d3737187SMichel Lespinasse  */
447d3737187SMichel Lespinasse static void vma_gap_update(struct vm_area_struct *vma)
448d3737187SMichel Lespinasse {
449d3737187SMichel Lespinasse 	/*
450315cc066SMichel Lespinasse 	 * As it turns out, RB_DECLARE_CALLBACKS_MAX() already created
451315cc066SMichel Lespinasse 	 * a callback function that does exactly what we want.
452d3737187SMichel Lespinasse 	 */
453d3737187SMichel Lespinasse 	vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
454d3737187SMichel Lespinasse }
455d3737187SMichel Lespinasse 
456d3737187SMichel Lespinasse static inline void vma_rb_insert(struct vm_area_struct *vma,
457d3737187SMichel Lespinasse 				 struct rb_root *root)
458d3737187SMichel Lespinasse {
459d3737187SMichel Lespinasse 	/* All rb_subtree_gap values must be consistent prior to insertion */
460d3737187SMichel Lespinasse 	validate_mm_rb(root, NULL);
461d3737187SMichel Lespinasse 
462d3737187SMichel Lespinasse 	rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
463d3737187SMichel Lespinasse }
464d3737187SMichel Lespinasse 
4658f26e0b1SAndrea Arcangeli static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
4668f26e0b1SAndrea Arcangeli {
4678f26e0b1SAndrea Arcangeli 	/*
4688f26e0b1SAndrea Arcangeli 	 * Note rb_erase_augmented is a fairly large inline function,
4698f26e0b1SAndrea Arcangeli 	 * so make sure we instantiate it only once with our desired
4708f26e0b1SAndrea Arcangeli 	 * augmented rbtree callbacks.
4718f26e0b1SAndrea Arcangeli 	 */
4728f26e0b1SAndrea Arcangeli 	rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
4738f26e0b1SAndrea Arcangeli }
4748f26e0b1SAndrea Arcangeli 
4758f26e0b1SAndrea Arcangeli static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,
4768f26e0b1SAndrea Arcangeli 						struct rb_root *root,
4778f26e0b1SAndrea Arcangeli 						struct vm_area_struct *ignore)
4788f26e0b1SAndrea Arcangeli {
4798f26e0b1SAndrea Arcangeli 	/*
4808f26e0b1SAndrea Arcangeli 	 * All rb_subtree_gap values must be consistent prior to erase,
4814d1e7243SWei Yang 	 * with the possible exception of
4824d1e7243SWei Yang 	 *
4834d1e7243SWei Yang 	 * a. the "next" vma being erased if next->vm_start was reduced in
4844d1e7243SWei Yang 	 *    __vma_adjust() -> __vma_unlink()
4854d1e7243SWei Yang 	 * b. the vma being erased in detach_vmas_to_be_unmapped() ->
4864d1e7243SWei Yang 	 *    vma_rb_erase()
4878f26e0b1SAndrea Arcangeli 	 */
4888f26e0b1SAndrea Arcangeli 	validate_mm_rb(root, ignore);
4898f26e0b1SAndrea Arcangeli 
4908f26e0b1SAndrea Arcangeli 	__vma_rb_erase(vma, root);
4918f26e0b1SAndrea Arcangeli }
4928f26e0b1SAndrea Arcangeli 
4938f26e0b1SAndrea Arcangeli static __always_inline void vma_rb_erase(struct vm_area_struct *vma,
4948f26e0b1SAndrea Arcangeli 					 struct rb_root *root)
495d3737187SMichel Lespinasse {
4964d1e7243SWei Yang 	vma_rb_erase_ignore(vma, root, vma);
497d3737187SMichel Lespinasse }
498d3737187SMichel Lespinasse 
499bf181b9fSMichel Lespinasse /*
500bf181b9fSMichel Lespinasse  * vma has some anon_vma assigned, and is already inserted on that
501bf181b9fSMichel Lespinasse  * anon_vma's interval trees.
502bf181b9fSMichel Lespinasse  *
503bf181b9fSMichel Lespinasse  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
504bf181b9fSMichel Lespinasse  * vma must be removed from the anon_vma's interval trees using
505bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_pre_update_vma().
506bf181b9fSMichel Lespinasse  *
507bf181b9fSMichel Lespinasse  * After the update, the vma will be reinserted using
508bf181b9fSMichel Lespinasse  * anon_vma_interval_tree_post_update_vma().
509bf181b9fSMichel Lespinasse  *
510c1e8d7c6SMichel Lespinasse  * The entire update must be protected by exclusive mmap_lock and by
511bf181b9fSMichel Lespinasse  * the root anon_vma's mutex.
512bf181b9fSMichel Lespinasse  */
513bf181b9fSMichel Lespinasse static inline void
514bf181b9fSMichel Lespinasse anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
515bf181b9fSMichel Lespinasse {
516bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
517bf181b9fSMichel Lespinasse 
518bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
519bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
520bf181b9fSMichel Lespinasse }
521bf181b9fSMichel Lespinasse 
522bf181b9fSMichel Lespinasse static inline void
523bf181b9fSMichel Lespinasse anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
524bf181b9fSMichel Lespinasse {
525bf181b9fSMichel Lespinasse 	struct anon_vma_chain *avc;
526bf181b9fSMichel Lespinasse 
527bf181b9fSMichel Lespinasse 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
528bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
529bf181b9fSMichel Lespinasse }
530bf181b9fSMichel Lespinasse 
5316597d783SHugh Dickins static int find_vma_links(struct mm_struct *mm, unsigned long addr,
5326597d783SHugh Dickins 		unsigned long end, struct vm_area_struct **pprev,
5336597d783SHugh Dickins 		struct rb_node ***rb_link, struct rb_node **rb_parent)
5341da177e4SLinus Torvalds {
5351da177e4SLinus Torvalds 	struct rb_node **__rb_link, *__rb_parent, *rb_prev;
5361da177e4SLinus Torvalds 
5375b78ed24SLuigi Rizzo 	mmap_assert_locked(mm);
5381da177e4SLinus Torvalds 	__rb_link = &mm->mm_rb.rb_node;
5391da177e4SLinus Torvalds 	rb_prev = __rb_parent = NULL;
5401da177e4SLinus Torvalds 
5411da177e4SLinus Torvalds 	while (*__rb_link) {
5421da177e4SLinus Torvalds 		struct vm_area_struct *vma_tmp;
5431da177e4SLinus Torvalds 
5441da177e4SLinus Torvalds 		__rb_parent = *__rb_link;
5451da177e4SLinus Torvalds 		vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
5461da177e4SLinus Torvalds 
5471da177e4SLinus Torvalds 		if (vma_tmp->vm_end > addr) {
5486597d783SHugh Dickins 			/* Fail if an existing vma overlaps the area */
5496597d783SHugh Dickins 			if (vma_tmp->vm_start < end)
5506597d783SHugh Dickins 				return -ENOMEM;
5511da177e4SLinus Torvalds 			__rb_link = &__rb_parent->rb_left;
5521da177e4SLinus Torvalds 		} else {
5531da177e4SLinus Torvalds 			rb_prev = __rb_parent;
5541da177e4SLinus Torvalds 			__rb_link = &__rb_parent->rb_right;
5551da177e4SLinus Torvalds 		}
5561da177e4SLinus Torvalds 	}
5571da177e4SLinus Torvalds 
5581da177e4SLinus Torvalds 	*pprev = NULL;
5591da177e4SLinus Torvalds 	if (rb_prev)
5601da177e4SLinus Torvalds 		*pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
5611da177e4SLinus Torvalds 	*rb_link = __rb_link;
5621da177e4SLinus Torvalds 	*rb_parent = __rb_parent;
5636597d783SHugh Dickins 	return 0;
5641da177e4SLinus Torvalds }
5651da177e4SLinus Torvalds 
5663903b55aSLiam R. Howlett /*
5673903b55aSLiam R. Howlett  * vma_next() - Get the next VMA.
5683903b55aSLiam R. Howlett  * @mm: The mm_struct.
5693903b55aSLiam R. Howlett  * @vma: The current vma.
5703903b55aSLiam R. Howlett  *
5713903b55aSLiam R. Howlett  * If @vma is NULL, return the first vma in the mm.
5723903b55aSLiam R. Howlett  *
5733903b55aSLiam R. Howlett  * Returns: The next VMA after @vma.
5743903b55aSLiam R. Howlett  */
5753903b55aSLiam R. Howlett static inline struct vm_area_struct *vma_next(struct mm_struct *mm,
5763903b55aSLiam R. Howlett 					 struct vm_area_struct *vma)
5773903b55aSLiam R. Howlett {
5783903b55aSLiam R. Howlett 	if (!vma)
5793903b55aSLiam R. Howlett 		return mm->mmap;
5803903b55aSLiam R. Howlett 
5813903b55aSLiam R. Howlett 	return vma->vm_next;
5823903b55aSLiam R. Howlett }
583fb8090b6SLiam R. Howlett 
584fb8090b6SLiam R. Howlett /*
585fb8090b6SLiam R. Howlett  * munmap_vma_range() - munmap VMAs that overlap a range.
586fb8090b6SLiam R. Howlett  * @mm: The mm struct
587fb8090b6SLiam R. Howlett  * @start: The start of the range.
588fb8090b6SLiam R. Howlett  * @len: The length of the range.
589fb8090b6SLiam R. Howlett  * @pprev: pointer to the pointer that will be set to previous vm_area_struct
590fb8090b6SLiam R. Howlett  * @rb_link: the rb_node
591fb8090b6SLiam R. Howlett  * @rb_parent: the parent rb_node
592fb8090b6SLiam R. Howlett  *
593fb8090b6SLiam R. Howlett  * Find all the vm_area_struct that overlap from @start to
594fb8090b6SLiam R. Howlett  * @end and munmap them.  Set @pprev to the previous vm_area_struct.
595fb8090b6SLiam R. Howlett  *
596fb8090b6SLiam R. Howlett  * Returns: -ENOMEM on munmap failure or 0 on success.
597fb8090b6SLiam R. Howlett  */
598fb8090b6SLiam R. Howlett static inline int
599fb8090b6SLiam R. Howlett munmap_vma_range(struct mm_struct *mm, unsigned long start, unsigned long len,
600fb8090b6SLiam R. Howlett 		 struct vm_area_struct **pprev, struct rb_node ***link,
601fb8090b6SLiam R. Howlett 		 struct rb_node **parent, struct list_head *uf)
602fb8090b6SLiam R. Howlett {
603fb8090b6SLiam R. Howlett 
604fb8090b6SLiam R. Howlett 	while (find_vma_links(mm, start, start + len, pprev, link, parent))
605fb8090b6SLiam R. Howlett 		if (do_munmap(mm, start, len, uf))
606fb8090b6SLiam R. Howlett 			return -ENOMEM;
607fb8090b6SLiam R. Howlett 
608fb8090b6SLiam R. Howlett 	return 0;
609fb8090b6SLiam R. Howlett }
610e8420a8eSCyril Hrubis static unsigned long count_vma_pages_range(struct mm_struct *mm,
611e8420a8eSCyril Hrubis 		unsigned long addr, unsigned long end)
612e8420a8eSCyril Hrubis {
613e8420a8eSCyril Hrubis 	unsigned long nr_pages = 0;
614e8420a8eSCyril Hrubis 	struct vm_area_struct *vma;
615e8420a8eSCyril Hrubis 
616f0953a1bSIngo Molnar 	/* Find first overlapping mapping */
617e8420a8eSCyril Hrubis 	vma = find_vma_intersection(mm, addr, end);
618e8420a8eSCyril Hrubis 	if (!vma)
619e8420a8eSCyril Hrubis 		return 0;
620e8420a8eSCyril Hrubis 
621e8420a8eSCyril Hrubis 	nr_pages = (min(end, vma->vm_end) -
622e8420a8eSCyril Hrubis 		max(addr, vma->vm_start)) >> PAGE_SHIFT;
623e8420a8eSCyril Hrubis 
624e8420a8eSCyril Hrubis 	/* Iterate over the rest of the overlaps */
625e8420a8eSCyril Hrubis 	for (vma = vma->vm_next; vma; vma = vma->vm_next) {
626e8420a8eSCyril Hrubis 		unsigned long overlap_len;
627e8420a8eSCyril Hrubis 
628e8420a8eSCyril Hrubis 		if (vma->vm_start > end)
629e8420a8eSCyril Hrubis 			break;
630e8420a8eSCyril Hrubis 
631e8420a8eSCyril Hrubis 		overlap_len = min(end, vma->vm_end) - vma->vm_start;
632e8420a8eSCyril Hrubis 		nr_pages += overlap_len >> PAGE_SHIFT;
633e8420a8eSCyril Hrubis 	}
634e8420a8eSCyril Hrubis 
635e8420a8eSCyril Hrubis 	return nr_pages;
636e8420a8eSCyril Hrubis }
637e8420a8eSCyril Hrubis 
6381da177e4SLinus Torvalds void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
6391da177e4SLinus Torvalds 		struct rb_node **rb_link, struct rb_node *rb_parent)
6401da177e4SLinus Torvalds {
641d3737187SMichel Lespinasse 	/* Update tracking information for the gap following the new vma. */
642d3737187SMichel Lespinasse 	if (vma->vm_next)
643d3737187SMichel Lespinasse 		vma_gap_update(vma->vm_next);
644d3737187SMichel Lespinasse 	else
6451be7107fSHugh Dickins 		mm->highest_vm_end = vm_end_gap(vma);
646d3737187SMichel Lespinasse 
647d3737187SMichel Lespinasse 	/*
648d3737187SMichel Lespinasse 	 * vma->vm_prev wasn't known when we followed the rbtree to find the
649d3737187SMichel Lespinasse 	 * correct insertion point for that vma. As a result, we could not
650d3737187SMichel Lespinasse 	 * update the vma vm_rb parents rb_subtree_gap values on the way down.
651d3737187SMichel Lespinasse 	 * So, we first insert the vma with a zero rb_subtree_gap value
652d3737187SMichel Lespinasse 	 * (to be consistent with what we did on the way down), and then
653d3737187SMichel Lespinasse 	 * immediately update the gap to the correct value. Finally we
654d3737187SMichel Lespinasse 	 * rebalance the rbtree after all augmented values have been set.
655d3737187SMichel Lespinasse 	 */
6561da177e4SLinus Torvalds 	rb_link_node(&vma->vm_rb, rb_parent, rb_link);
657d3737187SMichel Lespinasse 	vma->rb_subtree_gap = 0;
658d3737187SMichel Lespinasse 	vma_gap_update(vma);
659d3737187SMichel Lespinasse 	vma_rb_insert(vma, &mm->mm_rb);
6601da177e4SLinus Torvalds }
6611da177e4SLinus Torvalds 
662cb8f488cSDenys Vlasenko static void __vma_link_file(struct vm_area_struct *vma)
6631da177e4SLinus Torvalds {
6641da177e4SLinus Torvalds 	struct file *file;
6651da177e4SLinus Torvalds 
6661da177e4SLinus Torvalds 	file = vma->vm_file;
6671da177e4SLinus Torvalds 	if (file) {
6681da177e4SLinus Torvalds 		struct address_space *mapping = file->f_mapping;
6691da177e4SLinus Torvalds 
6701da177e4SLinus Torvalds 		if (vma->vm_flags & VM_DENYWRITE)
67173eb7f9aSMiaohe Lin 			put_write_access(file_inode(file));
6721da177e4SLinus Torvalds 		if (vma->vm_flags & VM_SHARED)
673cf508b58SMiaohe Lin 			mapping_allow_writable(mapping);
6741da177e4SLinus Torvalds 
6751da177e4SLinus Torvalds 		flush_dcache_mmap_lock(mapping);
6766b2dbba8SMichel Lespinasse 		vma_interval_tree_insert(vma, &mapping->i_mmap);
6771da177e4SLinus Torvalds 		flush_dcache_mmap_unlock(mapping);
6781da177e4SLinus Torvalds 	}
6791da177e4SLinus Torvalds }
6801da177e4SLinus Torvalds 
6811da177e4SLinus Torvalds static void
6821da177e4SLinus Torvalds __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
6831da177e4SLinus Torvalds 	struct vm_area_struct *prev, struct rb_node **rb_link,
6841da177e4SLinus Torvalds 	struct rb_node *rb_parent)
6851da177e4SLinus Torvalds {
686aba6dfb7SWei Yang 	__vma_link_list(mm, vma, prev);
6871da177e4SLinus Torvalds 	__vma_link_rb(mm, vma, rb_link, rb_parent);
6881da177e4SLinus Torvalds }
6891da177e4SLinus Torvalds 
6901da177e4SLinus Torvalds static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
6911da177e4SLinus Torvalds 			struct vm_area_struct *prev, struct rb_node **rb_link,
6921da177e4SLinus Torvalds 			struct rb_node *rb_parent)
6931da177e4SLinus Torvalds {
6941da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
6951da177e4SLinus Torvalds 
69664ac4940SHuang Shijie 	if (vma->vm_file) {
6971da177e4SLinus Torvalds 		mapping = vma->vm_file->f_mapping;
69883cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
69964ac4940SHuang Shijie 	}
7001da177e4SLinus Torvalds 
7011da177e4SLinus Torvalds 	__vma_link(mm, vma, prev, rb_link, rb_parent);
7021da177e4SLinus Torvalds 	__vma_link_file(vma);
7031da177e4SLinus Torvalds 
7041da177e4SLinus Torvalds 	if (mapping)
70583cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
7061da177e4SLinus Torvalds 
7071da177e4SLinus Torvalds 	mm->map_count++;
7081da177e4SLinus Torvalds 	validate_mm(mm);
7091da177e4SLinus Torvalds }
7101da177e4SLinus Torvalds 
7111da177e4SLinus Torvalds /*
71288f6b4c3SKautuk Consul  * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
7136b2dbba8SMichel Lespinasse  * mm's list and rbtree.  It has already been inserted into the interval tree.
7141da177e4SLinus Torvalds  */
71548aae425SZhenwenXu static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
7161da177e4SLinus Torvalds {
7176597d783SHugh Dickins 	struct vm_area_struct *prev;
7181da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
7191da177e4SLinus Torvalds 
7206597d783SHugh Dickins 	if (find_vma_links(mm, vma->vm_start, vma->vm_end,
7216597d783SHugh Dickins 			   &prev, &rb_link, &rb_parent))
7226597d783SHugh Dickins 		BUG();
7231da177e4SLinus Torvalds 	__vma_link(mm, vma, prev, rb_link, rb_parent);
7241da177e4SLinus Torvalds 	mm->map_count++;
7251da177e4SLinus Torvalds }
7261da177e4SLinus Torvalds 
7277c61f917SWei Yang static __always_inline void __vma_unlink(struct mm_struct *mm,
728e86f15eeSAndrea Arcangeli 						struct vm_area_struct *vma,
7298f26e0b1SAndrea Arcangeli 						struct vm_area_struct *ignore)
7301da177e4SLinus Torvalds {
7318f26e0b1SAndrea Arcangeli 	vma_rb_erase_ignore(vma, &mm->mm_rb, ignore);
7321b9fc5b2SWei Yang 	__vma_unlink_list(mm, vma);
733615d6e87SDavidlohr Bueso 	/* Kill the cache */
734615d6e87SDavidlohr Bueso 	vmacache_invalidate(mm);
7351da177e4SLinus Torvalds }
7361da177e4SLinus Torvalds 
7371da177e4SLinus Torvalds /*
7381da177e4SLinus Torvalds  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
7391da177e4SLinus Torvalds  * is already present in an i_mmap tree without adjusting the tree.
7401da177e4SLinus Torvalds  * The following helper function should be used when such adjustments
7411da177e4SLinus Torvalds  * are necessary.  The "insert" vma (if any) is to be inserted
7421da177e4SLinus Torvalds  * before we drop the necessary locks.
7431da177e4SLinus Torvalds  */
744e86f15eeSAndrea Arcangeli int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
745e86f15eeSAndrea Arcangeli 	unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
746e86f15eeSAndrea Arcangeli 	struct vm_area_struct *expand)
7471da177e4SLinus Torvalds {
7481da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
749e86f15eeSAndrea Arcangeli 	struct vm_area_struct *next = vma->vm_next, *orig_vma = vma;
7501da177e4SLinus Torvalds 	struct address_space *mapping = NULL;
751f808c13fSDavidlohr Bueso 	struct rb_root_cached *root = NULL;
752012f1800SRik van Riel 	struct anon_vma *anon_vma = NULL;
7531da177e4SLinus Torvalds 	struct file *file = vma->vm_file;
754d3737187SMichel Lespinasse 	bool start_changed = false, end_changed = false;
7551da177e4SLinus Torvalds 	long adjust_next = 0;
7561da177e4SLinus Torvalds 	int remove_next = 0;
7571da177e4SLinus Torvalds 
7581da177e4SLinus Torvalds 	if (next && !insert) {
759734537c9SKirill A. Shutemov 		struct vm_area_struct *exporter = NULL, *importer = NULL;
760287d97acSLinus Torvalds 
7611da177e4SLinus Torvalds 		if (end >= next->vm_end) {
7621da177e4SLinus Torvalds 			/*
7631da177e4SLinus Torvalds 			 * vma expands, overlapping all the next, and
7641da177e4SLinus Torvalds 			 * perhaps the one after too (mprotect case 6).
76586d12e47SAndrea Arcangeli 			 * The only other cases that gets here are
766e86f15eeSAndrea Arcangeli 			 * case 1, case 7 and case 8.
767e86f15eeSAndrea Arcangeli 			 */
768e86f15eeSAndrea Arcangeli 			if (next == expand) {
769e86f15eeSAndrea Arcangeli 				/*
770e86f15eeSAndrea Arcangeli 				 * The only case where we don't expand "vma"
771e86f15eeSAndrea Arcangeli 				 * and we expand "next" instead is case 8.
772e86f15eeSAndrea Arcangeli 				 */
773e86f15eeSAndrea Arcangeli 				VM_WARN_ON(end != next->vm_end);
774e86f15eeSAndrea Arcangeli 				/*
775e86f15eeSAndrea Arcangeli 				 * remove_next == 3 means we're
776e86f15eeSAndrea Arcangeli 				 * removing "vma" and that to do so we
777e86f15eeSAndrea Arcangeli 				 * swapped "vma" and "next".
778e86f15eeSAndrea Arcangeli 				 */
779e86f15eeSAndrea Arcangeli 				remove_next = 3;
780e86f15eeSAndrea Arcangeli 				VM_WARN_ON(file != next->vm_file);
781e86f15eeSAndrea Arcangeli 				swap(vma, next);
782e86f15eeSAndrea Arcangeli 			} else {
783e86f15eeSAndrea Arcangeli 				VM_WARN_ON(expand != vma);
784e86f15eeSAndrea Arcangeli 				/*
785e86f15eeSAndrea Arcangeli 				 * case 1, 6, 7, remove_next == 2 is case 6,
786e86f15eeSAndrea Arcangeli 				 * remove_next == 1 is case 1 or 7.
7871da177e4SLinus Torvalds 				 */
788734537c9SKirill A. Shutemov 				remove_next = 1 + (end > next->vm_end);
789e86f15eeSAndrea Arcangeli 				VM_WARN_ON(remove_next == 2 &&
790e86f15eeSAndrea Arcangeli 					   end != next->vm_next->vm_end);
791e86f15eeSAndrea Arcangeli 				/* trim end to next, for case 6 first pass */
7921da177e4SLinus Torvalds 				end = next->vm_end;
793e86f15eeSAndrea Arcangeli 			}
794e86f15eeSAndrea Arcangeli 
795287d97acSLinus Torvalds 			exporter = next;
7961da177e4SLinus Torvalds 			importer = vma;
797734537c9SKirill A. Shutemov 
798734537c9SKirill A. Shutemov 			/*
799734537c9SKirill A. Shutemov 			 * If next doesn't have anon_vma, import from vma after
800734537c9SKirill A. Shutemov 			 * next, if the vma overlaps with it.
801734537c9SKirill A. Shutemov 			 */
80297a42cd4SAndrea Arcangeli 			if (remove_next == 2 && !next->anon_vma)
803734537c9SKirill A. Shutemov 				exporter = next->vm_next;
804734537c9SKirill A. Shutemov 
8051da177e4SLinus Torvalds 		} else if (end > next->vm_start) {
8061da177e4SLinus Torvalds 			/*
8071da177e4SLinus Torvalds 			 * vma expands, overlapping part of the next:
8081da177e4SLinus Torvalds 			 * mprotect case 5 shifting the boundary up.
8091da177e4SLinus Torvalds 			 */
810f9d86a60SWei Yang 			adjust_next = (end - next->vm_start);
811287d97acSLinus Torvalds 			exporter = next;
8121da177e4SLinus Torvalds 			importer = vma;
813e86f15eeSAndrea Arcangeli 			VM_WARN_ON(expand != importer);
8141da177e4SLinus Torvalds 		} else if (end < vma->vm_end) {
8151da177e4SLinus Torvalds 			/*
8161da177e4SLinus Torvalds 			 * vma shrinks, and !insert tells it's not
8171da177e4SLinus Torvalds 			 * split_vma inserting another: so it must be
8181da177e4SLinus Torvalds 			 * mprotect case 4 shifting the boundary down.
8191da177e4SLinus Torvalds 			 */
820f9d86a60SWei Yang 			adjust_next = -(vma->vm_end - end);
821287d97acSLinus Torvalds 			exporter = vma;
8221da177e4SLinus Torvalds 			importer = next;
823e86f15eeSAndrea Arcangeli 			VM_WARN_ON(expand != importer);
8241da177e4SLinus Torvalds 		}
8251da177e4SLinus Torvalds 
8265beb4930SRik van Riel 		/*
8275beb4930SRik van Riel 		 * Easily overlooked: when mprotect shifts the boundary,
8285beb4930SRik van Riel 		 * make sure the expanding vma has anon_vma set if the
8295beb4930SRik van Riel 		 * shrinking vma had, to cover any anon pages imported.
8305beb4930SRik van Riel 		 */
831287d97acSLinus Torvalds 		if (exporter && exporter->anon_vma && !importer->anon_vma) {
832c4ea95d7SDaniel Forrest 			int error;
833c4ea95d7SDaniel Forrest 
834287d97acSLinus Torvalds 			importer->anon_vma = exporter->anon_vma;
835b800c91aSKonstantin Khlebnikov 			error = anon_vma_clone(importer, exporter);
8363fe89b3eSLeon Yu 			if (error)
837b800c91aSKonstantin Khlebnikov 				return error;
838b800c91aSKonstantin Khlebnikov 		}
8395beb4930SRik van Riel 	}
840734537c9SKirill A. Shutemov again:
841e86f15eeSAndrea Arcangeli 	vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
84237f9f559SKirill A. Shutemov 
8431da177e4SLinus Torvalds 	if (file) {
8441da177e4SLinus Torvalds 		mapping = file->f_mapping;
8451da177e4SLinus Torvalds 		root = &mapping->i_mmap;
846cbc91f71SSrikar Dronamraju 		uprobe_munmap(vma, vma->vm_start, vma->vm_end);
847682968e0SSrikar Dronamraju 
848682968e0SSrikar Dronamraju 		if (adjust_next)
84927ba0644SKirill A. Shutemov 			uprobe_munmap(next, next->vm_start, next->vm_end);
850682968e0SSrikar Dronamraju 
85183cde9e8SDavidlohr Bueso 		i_mmap_lock_write(mapping);
8521da177e4SLinus Torvalds 		if (insert) {
8531da177e4SLinus Torvalds 			/*
8546b2dbba8SMichel Lespinasse 			 * Put into interval tree now, so instantiated pages
8551da177e4SLinus Torvalds 			 * are visible to arm/parisc __flush_dcache_page
8561da177e4SLinus Torvalds 			 * throughout; but we cannot insert into address
8571da177e4SLinus Torvalds 			 * space until vma start or end is updated.
8581da177e4SLinus Torvalds 			 */
8591da177e4SLinus Torvalds 			__vma_link_file(insert);
8601da177e4SLinus Torvalds 		}
8611da177e4SLinus Torvalds 	}
8621da177e4SLinus Torvalds 
863012f1800SRik van Riel 	anon_vma = vma->anon_vma;
864bf181b9fSMichel Lespinasse 	if (!anon_vma && adjust_next)
865bf181b9fSMichel Lespinasse 		anon_vma = next->anon_vma;
866bf181b9fSMichel Lespinasse 	if (anon_vma) {
867e86f15eeSAndrea Arcangeli 		VM_WARN_ON(adjust_next && next->anon_vma &&
868e86f15eeSAndrea Arcangeli 			   anon_vma != next->anon_vma);
8694fc3f1d6SIngo Molnar 		anon_vma_lock_write(anon_vma);
870bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_pre_update_vma(vma);
871bf181b9fSMichel Lespinasse 		if (adjust_next)
872bf181b9fSMichel Lespinasse 			anon_vma_interval_tree_pre_update_vma(next);
873bf181b9fSMichel Lespinasse 	}
874012f1800SRik van Riel 
8750fc48a6eSWei Yang 	if (file) {
8761da177e4SLinus Torvalds 		flush_dcache_mmap_lock(mapping);
8776b2dbba8SMichel Lespinasse 		vma_interval_tree_remove(vma, root);
8781da177e4SLinus Torvalds 		if (adjust_next)
8796b2dbba8SMichel Lespinasse 			vma_interval_tree_remove(next, root);
8801da177e4SLinus Torvalds 	}
8811da177e4SLinus Torvalds 
882d3737187SMichel Lespinasse 	if (start != vma->vm_start) {
8831da177e4SLinus Torvalds 		vma->vm_start = start;
884d3737187SMichel Lespinasse 		start_changed = true;
885d3737187SMichel Lespinasse 	}
886d3737187SMichel Lespinasse 	if (end != vma->vm_end) {
8871da177e4SLinus Torvalds 		vma->vm_end = end;
888d3737187SMichel Lespinasse 		end_changed = true;
889d3737187SMichel Lespinasse 	}
8901da177e4SLinus Torvalds 	vma->vm_pgoff = pgoff;
8911da177e4SLinus Torvalds 	if (adjust_next) {
892f9d86a60SWei Yang 		next->vm_start += adjust_next;
893f9d86a60SWei Yang 		next->vm_pgoff += adjust_next >> PAGE_SHIFT;
8941da177e4SLinus Torvalds 	}
8951da177e4SLinus Torvalds 
8960fc48a6eSWei Yang 	if (file) {
8971da177e4SLinus Torvalds 		if (adjust_next)
8986b2dbba8SMichel Lespinasse 			vma_interval_tree_insert(next, root);
8996b2dbba8SMichel Lespinasse 		vma_interval_tree_insert(vma, root);
9001da177e4SLinus Torvalds 		flush_dcache_mmap_unlock(mapping);
9011da177e4SLinus Torvalds 	}
9021da177e4SLinus Torvalds 
9031da177e4SLinus Torvalds 	if (remove_next) {
9041da177e4SLinus Torvalds 		/*
9051da177e4SLinus Torvalds 		 * vma_merge has merged next into vma, and needs
9061da177e4SLinus Torvalds 		 * us to remove next before dropping the locks.
9071da177e4SLinus Torvalds 		 */
908e86f15eeSAndrea Arcangeli 		if (remove_next != 3)
9097c61f917SWei Yang 			__vma_unlink(mm, next, next);
910e86f15eeSAndrea Arcangeli 		else
9118f26e0b1SAndrea Arcangeli 			/*
9128f26e0b1SAndrea Arcangeli 			 * vma is not before next if they've been
9138f26e0b1SAndrea Arcangeli 			 * swapped.
9148f26e0b1SAndrea Arcangeli 			 *
9158f26e0b1SAndrea Arcangeli 			 * pre-swap() next->vm_start was reduced so
9168f26e0b1SAndrea Arcangeli 			 * tell validate_mm_rb to ignore pre-swap()
9178f26e0b1SAndrea Arcangeli 			 * "next" (which is stored in post-swap()
9188f26e0b1SAndrea Arcangeli 			 * "vma").
9198f26e0b1SAndrea Arcangeli 			 */
9207c61f917SWei Yang 			__vma_unlink(mm, next, vma);
9211da177e4SLinus Torvalds 		if (file)
9221da177e4SLinus Torvalds 			__remove_shared_vm_struct(next, file, mapping);
9231da177e4SLinus Torvalds 	} else if (insert) {
9241da177e4SLinus Torvalds 		/*
9251da177e4SLinus Torvalds 		 * split_vma has split insert from vma, and needs
9261da177e4SLinus Torvalds 		 * us to insert it before dropping the locks
9271da177e4SLinus Torvalds 		 * (it may either follow vma or precede it).
9281da177e4SLinus Torvalds 		 */
9291da177e4SLinus Torvalds 		__insert_vm_struct(mm, insert);
930d3737187SMichel Lespinasse 	} else {
931d3737187SMichel Lespinasse 		if (start_changed)
932d3737187SMichel Lespinasse 			vma_gap_update(vma);
933d3737187SMichel Lespinasse 		if (end_changed) {
934d3737187SMichel Lespinasse 			if (!next)
9351be7107fSHugh Dickins 				mm->highest_vm_end = vm_end_gap(vma);
936d3737187SMichel Lespinasse 			else if (!adjust_next)
937d3737187SMichel Lespinasse 				vma_gap_update(next);
938d3737187SMichel Lespinasse 		}
9391da177e4SLinus Torvalds 	}
9401da177e4SLinus Torvalds 
941bf181b9fSMichel Lespinasse 	if (anon_vma) {
942bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_post_update_vma(vma);
943bf181b9fSMichel Lespinasse 		if (adjust_next)
944bf181b9fSMichel Lespinasse 			anon_vma_interval_tree_post_update_vma(next);
94508b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
946bf181b9fSMichel Lespinasse 	}
9471da177e4SLinus Torvalds 
9480fc48a6eSWei Yang 	if (file) {
949808fbdbeSWei Yang 		i_mmap_unlock_write(mapping);
9507b2d81d4SIngo Molnar 		uprobe_mmap(vma);
9512b144498SSrikar Dronamraju 
9522b144498SSrikar Dronamraju 		if (adjust_next)
9537b2d81d4SIngo Molnar 			uprobe_mmap(next);
9542b144498SSrikar Dronamraju 	}
9552b144498SSrikar Dronamraju 
9561da177e4SLinus Torvalds 	if (remove_next) {
957925d1c40SMatt Helsley 		if (file) {
958cbc91f71SSrikar Dronamraju 			uprobe_munmap(next, next->vm_start, next->vm_end);
9591da177e4SLinus Torvalds 			fput(file);
960925d1c40SMatt Helsley 		}
9615beb4930SRik van Riel 		if (next->anon_vma)
9625beb4930SRik van Riel 			anon_vma_merge(vma, next);
9631da177e4SLinus Torvalds 		mm->map_count--;
9643964acd0SOleg Nesterov 		mpol_put(vma_policy(next));
9653928d4f5SLinus Torvalds 		vm_area_free(next);
9661da177e4SLinus Torvalds 		/*
9671da177e4SLinus Torvalds 		 * In mprotect's case 6 (see comments on vma_merge),
9681da177e4SLinus Torvalds 		 * we must remove another next too. It would clutter
9691da177e4SLinus Torvalds 		 * up the code too much to do both in one go.
9701da177e4SLinus Torvalds 		 */
971e86f15eeSAndrea Arcangeli 		if (remove_next != 3) {
972e86f15eeSAndrea Arcangeli 			/*
973e86f15eeSAndrea Arcangeli 			 * If "next" was removed and vma->vm_end was
974e86f15eeSAndrea Arcangeli 			 * expanded (up) over it, in turn
975e86f15eeSAndrea Arcangeli 			 * "next->vm_prev->vm_end" changed and the
976e86f15eeSAndrea Arcangeli 			 * "vma->vm_next" gap must be updated.
977e86f15eeSAndrea Arcangeli 			 */
9781da177e4SLinus Torvalds 			next = vma->vm_next;
979e86f15eeSAndrea Arcangeli 		} else {
980e86f15eeSAndrea Arcangeli 			/*
981e86f15eeSAndrea Arcangeli 			 * For the scope of the comment "next" and
982e86f15eeSAndrea Arcangeli 			 * "vma" considered pre-swap(): if "vma" was
983e86f15eeSAndrea Arcangeli 			 * removed, next->vm_start was expanded (down)
984e86f15eeSAndrea Arcangeli 			 * over it and the "next" gap must be updated.
985e86f15eeSAndrea Arcangeli 			 * Because of the swap() the post-swap() "vma"
986e86f15eeSAndrea Arcangeli 			 * actually points to pre-swap() "next"
987e86f15eeSAndrea Arcangeli 			 * (post-swap() "next" as opposed is now a
988e86f15eeSAndrea Arcangeli 			 * dangling pointer).
989e86f15eeSAndrea Arcangeli 			 */
990e86f15eeSAndrea Arcangeli 			next = vma;
991e86f15eeSAndrea Arcangeli 		}
992734537c9SKirill A. Shutemov 		if (remove_next == 2) {
993734537c9SKirill A. Shutemov 			remove_next = 1;
994734537c9SKirill A. Shutemov 			end = next->vm_end;
9951da177e4SLinus Torvalds 			goto again;
996734537c9SKirill A. Shutemov 		}
997d3737187SMichel Lespinasse 		else if (next)
998d3737187SMichel Lespinasse 			vma_gap_update(next);
999fb8c41e9SAndrea Arcangeli 		else {
1000fb8c41e9SAndrea Arcangeli 			/*
1001fb8c41e9SAndrea Arcangeli 			 * If remove_next == 2 we obviously can't
1002fb8c41e9SAndrea Arcangeli 			 * reach this path.
1003fb8c41e9SAndrea Arcangeli 			 *
1004fb8c41e9SAndrea Arcangeli 			 * If remove_next == 3 we can't reach this
1005fb8c41e9SAndrea Arcangeli 			 * path because pre-swap() next is always not
1006fb8c41e9SAndrea Arcangeli 			 * NULL. pre-swap() "next" is not being
1007fb8c41e9SAndrea Arcangeli 			 * removed and its next->vm_end is not altered
1008fb8c41e9SAndrea Arcangeli 			 * (and furthermore "end" already matches
1009fb8c41e9SAndrea Arcangeli 			 * next->vm_end in remove_next == 3).
1010fb8c41e9SAndrea Arcangeli 			 *
1011fb8c41e9SAndrea Arcangeli 			 * We reach this only in the remove_next == 1
1012fb8c41e9SAndrea Arcangeli 			 * case if the "next" vma that was removed was
1013fb8c41e9SAndrea Arcangeli 			 * the highest vma of the mm. However in such
1014fb8c41e9SAndrea Arcangeli 			 * case next->vm_end == "end" and the extended
1015fb8c41e9SAndrea Arcangeli 			 * "vma" has vma->vm_end == next->vm_end so
1016fb8c41e9SAndrea Arcangeli 			 * mm->highest_vm_end doesn't need any update
1017fb8c41e9SAndrea Arcangeli 			 * in remove_next == 1 case.
1018fb8c41e9SAndrea Arcangeli 			 */
10191be7107fSHugh Dickins 			VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
1020fb8c41e9SAndrea Arcangeli 		}
10211da177e4SLinus Torvalds 	}
10222b144498SSrikar Dronamraju 	if (insert && file)
10237b2d81d4SIngo Molnar 		uprobe_mmap(insert);
10241da177e4SLinus Torvalds 
10251da177e4SLinus Torvalds 	validate_mm(mm);
10265beb4930SRik van Riel 
10275beb4930SRik van Riel 	return 0;
10281da177e4SLinus Torvalds }
10291da177e4SLinus Torvalds 
10301da177e4SLinus Torvalds /*
10311da177e4SLinus Torvalds  * If the vma has a ->close operation then the driver probably needs to release
10321da177e4SLinus Torvalds  * per-vma resources, so we don't attempt to merge those.
10331da177e4SLinus Torvalds  */
10341da177e4SLinus Torvalds static inline int is_mergeable_vma(struct vm_area_struct *vma,
103519a809afSAndrea Arcangeli 				struct file *file, unsigned long vm_flags,
103619a809afSAndrea Arcangeli 				struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
10371da177e4SLinus Torvalds {
103834228d47SCyrill Gorcunov 	/*
103934228d47SCyrill Gorcunov 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
104034228d47SCyrill Gorcunov 	 * match the flags but dirty bit -- the caller should mark
104134228d47SCyrill Gorcunov 	 * merged VMA as dirty. If dirty bit won't be excluded from
10428bb4e7a2SWei Yang 	 * comparison, we increase pressure on the memory system forcing
104334228d47SCyrill Gorcunov 	 * the kernel to generate new VMAs when old one could be
104434228d47SCyrill Gorcunov 	 * extended instead.
104534228d47SCyrill Gorcunov 	 */
104634228d47SCyrill Gorcunov 	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
10471da177e4SLinus Torvalds 		return 0;
10481da177e4SLinus Torvalds 	if (vma->vm_file != file)
10491da177e4SLinus Torvalds 		return 0;
10501da177e4SLinus Torvalds 	if (vma->vm_ops && vma->vm_ops->close)
10511da177e4SLinus Torvalds 		return 0;
105219a809afSAndrea Arcangeli 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
105319a809afSAndrea Arcangeli 		return 0;
10541da177e4SLinus Torvalds 	return 1;
10551da177e4SLinus Torvalds }
10561da177e4SLinus Torvalds 
10571da177e4SLinus Torvalds static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
1058965f55deSShaohua Li 					struct anon_vma *anon_vma2,
1059965f55deSShaohua Li 					struct vm_area_struct *vma)
10601da177e4SLinus Torvalds {
1061965f55deSShaohua Li 	/*
1062965f55deSShaohua Li 	 * The list_is_singular() test is to avoid merging VMA cloned from
1063965f55deSShaohua Li 	 * parents. This can improve scalability caused by anon_vma lock.
1064965f55deSShaohua Li 	 */
1065965f55deSShaohua Li 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
1066965f55deSShaohua Li 		list_is_singular(&vma->anon_vma_chain)))
1067965f55deSShaohua Li 		return 1;
1068965f55deSShaohua Li 	return anon_vma1 == anon_vma2;
10691da177e4SLinus Torvalds }
10701da177e4SLinus Torvalds 
10711da177e4SLinus Torvalds /*
10721da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
10731da177e4SLinus Torvalds  * in front of (at a lower virtual address and file offset than) the vma.
10741da177e4SLinus Torvalds  *
10751da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
10761da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
10771da177e4SLinus Torvalds  *
10781da177e4SLinus Torvalds  * We don't check here for the merged mmap wrapping around the end of pagecache
107945e55300SPeter Collingbourne  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
10801da177e4SLinus Torvalds  * wrap, nor mmaps which cover the final page at index -1UL.
10811da177e4SLinus Torvalds  */
10821da177e4SLinus Torvalds static int
10831da177e4SLinus Torvalds can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
108419a809afSAndrea Arcangeli 		     struct anon_vma *anon_vma, struct file *file,
108519a809afSAndrea Arcangeli 		     pgoff_t vm_pgoff,
108619a809afSAndrea Arcangeli 		     struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
10871da177e4SLinus Torvalds {
108819a809afSAndrea Arcangeli 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
1089965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
10901da177e4SLinus Torvalds 		if (vma->vm_pgoff == vm_pgoff)
10911da177e4SLinus Torvalds 			return 1;
10921da177e4SLinus Torvalds 	}
10931da177e4SLinus Torvalds 	return 0;
10941da177e4SLinus Torvalds }
10951da177e4SLinus Torvalds 
10961da177e4SLinus Torvalds /*
10971da177e4SLinus Torvalds  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
10981da177e4SLinus Torvalds  * beyond (at a higher virtual address and file offset than) the vma.
10991da177e4SLinus Torvalds  *
11001da177e4SLinus Torvalds  * We cannot merge two vmas if they have differently assigned (non-NULL)
11011da177e4SLinus Torvalds  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
11021da177e4SLinus Torvalds  */
11031da177e4SLinus Torvalds static int
11041da177e4SLinus Torvalds can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
110519a809afSAndrea Arcangeli 		    struct anon_vma *anon_vma, struct file *file,
110619a809afSAndrea Arcangeli 		    pgoff_t vm_pgoff,
110719a809afSAndrea Arcangeli 		    struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
11081da177e4SLinus Torvalds {
110919a809afSAndrea Arcangeli 	if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx) &&
1110965f55deSShaohua Li 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
11111da177e4SLinus Torvalds 		pgoff_t vm_pglen;
1112d6e93217SLibin 		vm_pglen = vma_pages(vma);
11131da177e4SLinus Torvalds 		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
11141da177e4SLinus Torvalds 			return 1;
11151da177e4SLinus Torvalds 	}
11161da177e4SLinus Torvalds 	return 0;
11171da177e4SLinus Torvalds }
11181da177e4SLinus Torvalds 
11191da177e4SLinus Torvalds /*
11201da177e4SLinus Torvalds  * Given a mapping request (addr,end,vm_flags,file,pgoff), figure out
11211da177e4SLinus Torvalds  * whether that can be merged with its predecessor or its successor.
11221da177e4SLinus Torvalds  * Or both (it neatly fills a hole).
11231da177e4SLinus Torvalds  *
11241da177e4SLinus Torvalds  * In most cases - when called for mmap, brk or mremap - [addr,end) is
11251da177e4SLinus Torvalds  * certain not to be mapped by the time vma_merge is called; but when
11261da177e4SLinus Torvalds  * called for mprotect, it is certain to be already mapped (either at
11271da177e4SLinus Torvalds  * an offset within prev, or at the start of next), and the flags of
11281da177e4SLinus Torvalds  * this area are about to be changed to vm_flags - and the no-change
11291da177e4SLinus Torvalds  * case has already been eliminated.
11301da177e4SLinus Torvalds  *
11311da177e4SLinus Torvalds  * The following mprotect cases have to be considered, where AAAA is
11321da177e4SLinus Torvalds  * the area passed down from mprotect_fixup, never extending beyond one
11331da177e4SLinus Torvalds  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
11341da177e4SLinus Torvalds  *
11355d42ab29SWei Yang  *     AAAA             AAAA                   AAAA
11365d42ab29SWei Yang  *    PPPPPPNNNNNN    PPPPPPNNNNNN       PPPPPPNNNNNN
11375d42ab29SWei Yang  *    cannot merge    might become       might become
11385d42ab29SWei Yang  *                    PPNNNNNNNNNN       PPPPPPPPPPNN
11395d42ab29SWei Yang  *    mmap, brk or    case 4 below       case 5 below
11405d42ab29SWei Yang  *    mremap move:
11415d42ab29SWei Yang  *                        AAAA               AAAA
11425d42ab29SWei Yang  *                    PPPP    NNNN       PPPPNNNNXXXX
11435d42ab29SWei Yang  *                    might become       might become
11445d42ab29SWei Yang  *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
11455d42ab29SWei Yang  *                    PPPPPPPPNNNN 2 or  PPPPPPPPXXXX 7 or
11465d42ab29SWei Yang  *                    PPPPNNNNNNNN 3     PPPPXXXXXXXX 8
11471da177e4SLinus Torvalds  *
11488bb4e7a2SWei Yang  * It is important for case 8 that the vma NNNN overlapping the
1149e86f15eeSAndrea Arcangeli  * region AAAA is never going to extended over XXXX. Instead XXXX must
1150e86f15eeSAndrea Arcangeli  * be extended in region AAAA and NNNN must be removed. This way in
1151e86f15eeSAndrea Arcangeli  * all cases where vma_merge succeeds, the moment vma_adjust drops the
1152e86f15eeSAndrea Arcangeli  * rmap_locks, the properties of the merged vma will be already
1153e86f15eeSAndrea Arcangeli  * correct for the whole merged range. Some of those properties like
1154e86f15eeSAndrea Arcangeli  * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
1155e86f15eeSAndrea Arcangeli  * be correct for the whole merged range immediately after the
1156e86f15eeSAndrea Arcangeli  * rmap_locks are released. Otherwise if XXXX would be removed and
1157e86f15eeSAndrea Arcangeli  * NNNN would be extended over the XXXX range, remove_migration_ptes
1158e86f15eeSAndrea Arcangeli  * or other rmap walkers (if working on addresses beyond the "end"
1159e86f15eeSAndrea Arcangeli  * parameter) may establish ptes with the wrong permissions of NNNN
1160e86f15eeSAndrea Arcangeli  * instead of the right permissions of XXXX.
11611da177e4SLinus Torvalds  */
11621da177e4SLinus Torvalds struct vm_area_struct *vma_merge(struct mm_struct *mm,
11631da177e4SLinus Torvalds 			struct vm_area_struct *prev, unsigned long addr,
11641da177e4SLinus Torvalds 			unsigned long end, unsigned long vm_flags,
11651da177e4SLinus Torvalds 			struct anon_vma *anon_vma, struct file *file,
116619a809afSAndrea Arcangeli 			pgoff_t pgoff, struct mempolicy *policy,
116719a809afSAndrea Arcangeli 			struct vm_userfaultfd_ctx vm_userfaultfd_ctx)
11681da177e4SLinus Torvalds {
11691da177e4SLinus Torvalds 	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
11701da177e4SLinus Torvalds 	struct vm_area_struct *area, *next;
11715beb4930SRik van Riel 	int err;
11721da177e4SLinus Torvalds 
11731da177e4SLinus Torvalds 	/*
11741da177e4SLinus Torvalds 	 * We later require that vma->vm_flags == vm_flags,
11751da177e4SLinus Torvalds 	 * so this tests vma->vm_flags & VM_SPECIAL, too.
11761da177e4SLinus Torvalds 	 */
11771da177e4SLinus Torvalds 	if (vm_flags & VM_SPECIAL)
11781da177e4SLinus Torvalds 		return NULL;
11791da177e4SLinus Torvalds 
11803903b55aSLiam R. Howlett 	next = vma_next(mm, prev);
11811da177e4SLinus Torvalds 	area = next;
1182e86f15eeSAndrea Arcangeli 	if (area && area->vm_end == end)		/* cases 6, 7, 8 */
11831da177e4SLinus Torvalds 		next = next->vm_next;
11841da177e4SLinus Torvalds 
1185e86f15eeSAndrea Arcangeli 	/* verify some invariant that must be enforced by the caller */
1186e86f15eeSAndrea Arcangeli 	VM_WARN_ON(prev && addr <= prev->vm_start);
1187e86f15eeSAndrea Arcangeli 	VM_WARN_ON(area && end > area->vm_end);
1188e86f15eeSAndrea Arcangeli 	VM_WARN_ON(addr >= end);
1189e86f15eeSAndrea Arcangeli 
11901da177e4SLinus Torvalds 	/*
11911da177e4SLinus Torvalds 	 * Can it merge with the predecessor?
11921da177e4SLinus Torvalds 	 */
11931da177e4SLinus Torvalds 	if (prev && prev->vm_end == addr &&
11941da177e4SLinus Torvalds 			mpol_equal(vma_policy(prev), policy) &&
11951da177e4SLinus Torvalds 			can_vma_merge_after(prev, vm_flags,
119619a809afSAndrea Arcangeli 					    anon_vma, file, pgoff,
119719a809afSAndrea Arcangeli 					    vm_userfaultfd_ctx)) {
11981da177e4SLinus Torvalds 		/*
11991da177e4SLinus Torvalds 		 * OK, it can.  Can we now merge in the successor as well?
12001da177e4SLinus Torvalds 		 */
12011da177e4SLinus Torvalds 		if (next && end == next->vm_start &&
12021da177e4SLinus Torvalds 				mpol_equal(policy, vma_policy(next)) &&
12031da177e4SLinus Torvalds 				can_vma_merge_before(next, vm_flags,
120419a809afSAndrea Arcangeli 						     anon_vma, file,
120519a809afSAndrea Arcangeli 						     pgoff+pglen,
120619a809afSAndrea Arcangeli 						     vm_userfaultfd_ctx) &&
12071da177e4SLinus Torvalds 				is_mergeable_anon_vma(prev->anon_vma,
1208965f55deSShaohua Li 						      next->anon_vma, NULL)) {
12091da177e4SLinus Torvalds 							/* cases 1, 6 */
1210e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1211e86f15eeSAndrea Arcangeli 					 next->vm_end, prev->vm_pgoff, NULL,
1212e86f15eeSAndrea Arcangeli 					 prev);
12131da177e4SLinus Torvalds 		} else					/* cases 2, 5, 7 */
1214e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1215e86f15eeSAndrea Arcangeli 					 end, prev->vm_pgoff, NULL, prev);
12165beb4930SRik van Riel 		if (err)
12175beb4930SRik van Riel 			return NULL;
12186d50e60cSDavid Rientjes 		khugepaged_enter_vma_merge(prev, vm_flags);
12191da177e4SLinus Torvalds 		return prev;
12201da177e4SLinus Torvalds 	}
12211da177e4SLinus Torvalds 
12221da177e4SLinus Torvalds 	/*
12231da177e4SLinus Torvalds 	 * Can this new request be merged in front of next?
12241da177e4SLinus Torvalds 	 */
12251da177e4SLinus Torvalds 	if (next && end == next->vm_start &&
12261da177e4SLinus Torvalds 			mpol_equal(policy, vma_policy(next)) &&
12271da177e4SLinus Torvalds 			can_vma_merge_before(next, vm_flags,
122819a809afSAndrea Arcangeli 					     anon_vma, file, pgoff+pglen,
122919a809afSAndrea Arcangeli 					     vm_userfaultfd_ctx)) {
12301da177e4SLinus Torvalds 		if (prev && addr < prev->vm_end)	/* case 4 */
1231e86f15eeSAndrea Arcangeli 			err = __vma_adjust(prev, prev->vm_start,
1232e86f15eeSAndrea Arcangeli 					 addr, prev->vm_pgoff, NULL, next);
1233e86f15eeSAndrea Arcangeli 		else {					/* cases 3, 8 */
1234e86f15eeSAndrea Arcangeli 			err = __vma_adjust(area, addr, next->vm_end,
1235e86f15eeSAndrea Arcangeli 					 next->vm_pgoff - pglen, NULL, next);
1236e86f15eeSAndrea Arcangeli 			/*
1237e86f15eeSAndrea Arcangeli 			 * In case 3 area is already equal to next and
1238e86f15eeSAndrea Arcangeli 			 * this is a noop, but in case 8 "area" has
1239e86f15eeSAndrea Arcangeli 			 * been removed and next was expanded over it.
1240e86f15eeSAndrea Arcangeli 			 */
1241e86f15eeSAndrea Arcangeli 			area = next;
1242e86f15eeSAndrea Arcangeli 		}
12435beb4930SRik van Riel 		if (err)
12445beb4930SRik van Riel 			return NULL;
12456d50e60cSDavid Rientjes 		khugepaged_enter_vma_merge(area, vm_flags);
12461da177e4SLinus Torvalds 		return area;
12471da177e4SLinus Torvalds 	}
12481da177e4SLinus Torvalds 
12491da177e4SLinus Torvalds 	return NULL;
12501da177e4SLinus Torvalds }
12511da177e4SLinus Torvalds 
12521da177e4SLinus Torvalds /*
1253b4f315b4SEthon Paul  * Rough compatibility check to quickly see if it's even worth looking
1254d0e9fe17SLinus Torvalds  * at sharing an anon_vma.
1255d0e9fe17SLinus Torvalds  *
1256d0e9fe17SLinus Torvalds  * They need to have the same vm_file, and the flags can only differ
1257d0e9fe17SLinus Torvalds  * in things that mprotect may change.
1258d0e9fe17SLinus Torvalds  *
1259d0e9fe17SLinus Torvalds  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1260d0e9fe17SLinus Torvalds  * we can merge the two vma's. For example, we refuse to merge a vma if
1261d0e9fe17SLinus Torvalds  * there is a vm_ops->close() function, because that indicates that the
1262d0e9fe17SLinus Torvalds  * driver is doing some kind of reference counting. But that doesn't
1263d0e9fe17SLinus Torvalds  * really matter for the anon_vma sharing case.
1264d0e9fe17SLinus Torvalds  */
1265d0e9fe17SLinus Torvalds static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1266d0e9fe17SLinus Torvalds {
1267d0e9fe17SLinus Torvalds 	return a->vm_end == b->vm_start &&
1268d0e9fe17SLinus Torvalds 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1269d0e9fe17SLinus Torvalds 		a->vm_file == b->vm_file &&
12706cb4d9a2SAnshuman Khandual 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1271d0e9fe17SLinus Torvalds 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1272d0e9fe17SLinus Torvalds }
1273d0e9fe17SLinus Torvalds 
1274d0e9fe17SLinus Torvalds /*
1275d0e9fe17SLinus Torvalds  * Do some basic sanity checking to see if we can re-use the anon_vma
1276d0e9fe17SLinus Torvalds  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1277d0e9fe17SLinus Torvalds  * the same as 'old', the other will be the new one that is trying
1278d0e9fe17SLinus Torvalds  * to share the anon_vma.
1279d0e9fe17SLinus Torvalds  *
1280d0e9fe17SLinus Torvalds  * NOTE! This runs with mm_sem held for reading, so it is possible that
1281d0e9fe17SLinus Torvalds  * the anon_vma of 'old' is concurrently in the process of being set up
1282d0e9fe17SLinus Torvalds  * by another page fault trying to merge _that_. But that's ok: if it
1283d0e9fe17SLinus Torvalds  * is being set up, that automatically means that it will be a singleton
1284d0e9fe17SLinus Torvalds  * acceptable for merging, so we can do all of this optimistically. But
12854db0c3c2SJason Low  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1286d0e9fe17SLinus Torvalds  *
1287d0e9fe17SLinus Torvalds  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1288d0e9fe17SLinus Torvalds  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1289d0e9fe17SLinus Torvalds  * is to return an anon_vma that is "complex" due to having gone through
1290d0e9fe17SLinus Torvalds  * a fork).
1291d0e9fe17SLinus Torvalds  *
1292d0e9fe17SLinus Torvalds  * We also make sure that the two vma's are compatible (adjacent,
1293d0e9fe17SLinus Torvalds  * and with the same memory policies). That's all stable, even with just
1294d0e9fe17SLinus Torvalds  * a read lock on the mm_sem.
1295d0e9fe17SLinus Torvalds  */
1296d0e9fe17SLinus Torvalds static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1297d0e9fe17SLinus Torvalds {
1298d0e9fe17SLinus Torvalds 	if (anon_vma_compatible(a, b)) {
12994db0c3c2SJason Low 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1300d0e9fe17SLinus Torvalds 
1301d0e9fe17SLinus Torvalds 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1302d0e9fe17SLinus Torvalds 			return anon_vma;
1303d0e9fe17SLinus Torvalds 	}
1304d0e9fe17SLinus Torvalds 	return NULL;
1305d0e9fe17SLinus Torvalds }
1306d0e9fe17SLinus Torvalds 
1307d0e9fe17SLinus Torvalds /*
13081da177e4SLinus Torvalds  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
13091da177e4SLinus Torvalds  * neighbouring vmas for a suitable anon_vma, before it goes off
13101da177e4SLinus Torvalds  * to allocate a new anon_vma.  It checks because a repetitive
13111da177e4SLinus Torvalds  * sequence of mprotects and faults may otherwise lead to distinct
13121da177e4SLinus Torvalds  * anon_vmas being allocated, preventing vma merge in subsequent
13131da177e4SLinus Torvalds  * mprotect.
13141da177e4SLinus Torvalds  */
13151da177e4SLinus Torvalds struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
13161da177e4SLinus Torvalds {
1317a67c8caaSMiaohe Lin 	struct anon_vma *anon_vma = NULL;
13181da177e4SLinus Torvalds 
1319a67c8caaSMiaohe Lin 	/* Try next first. */
1320a67c8caaSMiaohe Lin 	if (vma->vm_next) {
1321a67c8caaSMiaohe Lin 		anon_vma = reusable_anon_vma(vma->vm_next, vma, vma->vm_next);
1322d0e9fe17SLinus Torvalds 		if (anon_vma)
1323d0e9fe17SLinus Torvalds 			return anon_vma;
1324a67c8caaSMiaohe Lin 	}
13251da177e4SLinus Torvalds 
1326a67c8caaSMiaohe Lin 	/* Try prev next. */
1327a67c8caaSMiaohe Lin 	if (vma->vm_prev)
1328a67c8caaSMiaohe Lin 		anon_vma = reusable_anon_vma(vma->vm_prev, vma->vm_prev, vma);
1329a67c8caaSMiaohe Lin 
13301da177e4SLinus Torvalds 	/*
1331a67c8caaSMiaohe Lin 	 * We might reach here with anon_vma == NULL if we can't find
1332a67c8caaSMiaohe Lin 	 * any reusable anon_vma.
13331da177e4SLinus Torvalds 	 * There's no absolute need to look only at touching neighbours:
13341da177e4SLinus Torvalds 	 * we could search further afield for "compatible" anon_vmas.
13351da177e4SLinus Torvalds 	 * But it would probably just be a waste of time searching,
13361da177e4SLinus Torvalds 	 * or lead to too many vmas hanging off the same anon_vma.
13371da177e4SLinus Torvalds 	 * We're trying to allow mprotect remerging later on,
13381da177e4SLinus Torvalds 	 * not trying to minimize memory used for anon_vmas.
13391da177e4SLinus Torvalds 	 */
1340a67c8caaSMiaohe Lin 	return anon_vma;
13411da177e4SLinus Torvalds }
13421da177e4SLinus Torvalds 
13431da177e4SLinus Torvalds /*
134440401530SAl Viro  * If a hint addr is less than mmap_min_addr change hint to be as
134540401530SAl Viro  * low as possible but still greater than mmap_min_addr
134640401530SAl Viro  */
134740401530SAl Viro static inline unsigned long round_hint_to_min(unsigned long hint)
134840401530SAl Viro {
134940401530SAl Viro 	hint &= PAGE_MASK;
135040401530SAl Viro 	if (((void *)hint != NULL) &&
135140401530SAl Viro 	    (hint < mmap_min_addr))
135240401530SAl Viro 		return PAGE_ALIGN(mmap_min_addr);
135340401530SAl Viro 	return hint;
135440401530SAl Viro }
135540401530SAl Viro 
13566aeb2542SMike Rapoport int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1357363ee17fSDavidlohr Bueso 		       unsigned long len)
1358363ee17fSDavidlohr Bueso {
1359363ee17fSDavidlohr Bueso 	unsigned long locked, lock_limit;
1360363ee17fSDavidlohr Bueso 
1361363ee17fSDavidlohr Bueso 	/*  mlock MCL_FUTURE? */
1362363ee17fSDavidlohr Bueso 	if (flags & VM_LOCKED) {
1363363ee17fSDavidlohr Bueso 		locked = len >> PAGE_SHIFT;
1364363ee17fSDavidlohr Bueso 		locked += mm->locked_vm;
1365363ee17fSDavidlohr Bueso 		lock_limit = rlimit(RLIMIT_MEMLOCK);
1366363ee17fSDavidlohr Bueso 		lock_limit >>= PAGE_SHIFT;
1367363ee17fSDavidlohr Bueso 		if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1368363ee17fSDavidlohr Bueso 			return -EAGAIN;
1369363ee17fSDavidlohr Bueso 	}
1370363ee17fSDavidlohr Bueso 	return 0;
1371363ee17fSDavidlohr Bueso }
1372363ee17fSDavidlohr Bueso 
1373be83bbf8SLinus Torvalds static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1374be83bbf8SLinus Torvalds {
1375be83bbf8SLinus Torvalds 	if (S_ISREG(inode->i_mode))
1376423913adSLinus Torvalds 		return MAX_LFS_FILESIZE;
1377be83bbf8SLinus Torvalds 
1378be83bbf8SLinus Torvalds 	if (S_ISBLK(inode->i_mode))
1379be83bbf8SLinus Torvalds 		return MAX_LFS_FILESIZE;
1380be83bbf8SLinus Torvalds 
138176f34950SIvan Khoronzhuk 	if (S_ISSOCK(inode->i_mode))
138276f34950SIvan Khoronzhuk 		return MAX_LFS_FILESIZE;
138376f34950SIvan Khoronzhuk 
1384be83bbf8SLinus Torvalds 	/* Special "we do even unsigned file positions" case */
1385be83bbf8SLinus Torvalds 	if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1386be83bbf8SLinus Torvalds 		return 0;
1387be83bbf8SLinus Torvalds 
1388be83bbf8SLinus Torvalds 	/* Yes, random drivers might want more. But I'm tired of buggy drivers */
1389be83bbf8SLinus Torvalds 	return ULONG_MAX;
1390be83bbf8SLinus Torvalds }
1391be83bbf8SLinus Torvalds 
1392be83bbf8SLinus Torvalds static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1393be83bbf8SLinus Torvalds 				unsigned long pgoff, unsigned long len)
1394be83bbf8SLinus Torvalds {
1395be83bbf8SLinus Torvalds 	u64 maxsize = file_mmap_size_max(file, inode);
1396be83bbf8SLinus Torvalds 
1397be83bbf8SLinus Torvalds 	if (maxsize && len > maxsize)
1398be83bbf8SLinus Torvalds 		return false;
1399be83bbf8SLinus Torvalds 	maxsize -= len;
1400be83bbf8SLinus Torvalds 	if (pgoff > maxsize >> PAGE_SHIFT)
1401be83bbf8SLinus Torvalds 		return false;
1402be83bbf8SLinus Torvalds 	return true;
1403be83bbf8SLinus Torvalds }
1404be83bbf8SLinus Torvalds 
140540401530SAl Viro /*
14063e4e28c5SMichel Lespinasse  * The caller must write-lock current->mm->mmap_lock.
14071da177e4SLinus Torvalds  */
14081fcfd8dbSOleg Nesterov unsigned long do_mmap(struct file *file, unsigned long addr,
14091da177e4SLinus Torvalds 			unsigned long len, unsigned long prot,
141045e55300SPeter Collingbourne 			unsigned long flags, unsigned long pgoff,
141145e55300SPeter Collingbourne 			unsigned long *populate, struct list_head *uf)
14121da177e4SLinus Torvalds {
14131da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
141445e55300SPeter Collingbourne 	vm_flags_t vm_flags;
141562b5f7d0SDave Hansen 	int pkey = 0;
14161da177e4SLinus Torvalds 
141741badc15SMichel Lespinasse 	*populate = 0;
1418bebeb3d6SMichel Lespinasse 
1419e37609bbSPiotr Kwapulinski 	if (!len)
1420e37609bbSPiotr Kwapulinski 		return -EINVAL;
1421e37609bbSPiotr Kwapulinski 
14221da177e4SLinus Torvalds 	/*
14231da177e4SLinus Torvalds 	 * Does the application expect PROT_READ to imply PROT_EXEC?
14241da177e4SLinus Torvalds 	 *
14251da177e4SLinus Torvalds 	 * (the exception is when the underlying filesystem is noexec
14261da177e4SLinus Torvalds 	 *  mounted, in which case we dont add PROT_EXEC.)
14271da177e4SLinus Torvalds 	 */
14281da177e4SLinus Torvalds 	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
142990f8572bSEric W. Biederman 		if (!(file && path_noexec(&file->f_path)))
14301da177e4SLinus Torvalds 			prot |= PROT_EXEC;
14311da177e4SLinus Torvalds 
1432a4ff8e86SMichal Hocko 	/* force arch specific MAP_FIXED handling in get_unmapped_area */
1433a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE)
1434a4ff8e86SMichal Hocko 		flags |= MAP_FIXED;
1435a4ff8e86SMichal Hocko 
14367cd94146SEric Paris 	if (!(flags & MAP_FIXED))
14377cd94146SEric Paris 		addr = round_hint_to_min(addr);
14387cd94146SEric Paris 
14391da177e4SLinus Torvalds 	/* Careful about overflows.. */
14401da177e4SLinus Torvalds 	len = PAGE_ALIGN(len);
14419206de95SAl Viro 	if (!len)
14421da177e4SLinus Torvalds 		return -ENOMEM;
14431da177e4SLinus Torvalds 
14441da177e4SLinus Torvalds 	/* offset overflow? */
14451da177e4SLinus Torvalds 	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
14461da177e4SLinus Torvalds 		return -EOVERFLOW;
14471da177e4SLinus Torvalds 
14481da177e4SLinus Torvalds 	/* Too many mappings? */
14491da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
14501da177e4SLinus Torvalds 		return -ENOMEM;
14511da177e4SLinus Torvalds 
14521da177e4SLinus Torvalds 	/* Obtain the address to map to. we verify (or select) it and ensure
14531da177e4SLinus Torvalds 	 * that it represents a valid section of the address space.
14541da177e4SLinus Torvalds 	 */
14551da177e4SLinus Torvalds 	addr = get_unmapped_area(file, addr, len, pgoff, flags);
1456ff68dac6SGaowei Pu 	if (IS_ERR_VALUE(addr))
14571da177e4SLinus Torvalds 		return addr;
14581da177e4SLinus Torvalds 
1459a4ff8e86SMichal Hocko 	if (flags & MAP_FIXED_NOREPLACE) {
146035e43c5fSLiam Howlett 		if (find_vma_intersection(mm, addr, addr + len))
1461a4ff8e86SMichal Hocko 			return -EEXIST;
1462a4ff8e86SMichal Hocko 	}
1463a4ff8e86SMichal Hocko 
146462b5f7d0SDave Hansen 	if (prot == PROT_EXEC) {
146562b5f7d0SDave Hansen 		pkey = execute_only_pkey(mm);
146662b5f7d0SDave Hansen 		if (pkey < 0)
146762b5f7d0SDave Hansen 			pkey = 0;
146862b5f7d0SDave Hansen 	}
146962b5f7d0SDave Hansen 
14701da177e4SLinus Torvalds 	/* Do simple checking here so the lower-level routines won't have
14711da177e4SLinus Torvalds 	 * to. we assume access permissions have been handled by the open
14721da177e4SLinus Torvalds 	 * of the memory object, so we don't do any here.
14731da177e4SLinus Torvalds 	 */
147445e55300SPeter Collingbourne 	vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
14751da177e4SLinus Torvalds 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
14761da177e4SLinus Torvalds 
1477cdf7b341SHuang Shijie 	if (flags & MAP_LOCKED)
14781da177e4SLinus Torvalds 		if (!can_do_mlock())
14791da177e4SLinus Torvalds 			return -EPERM;
1480ba470de4SRik van Riel 
1481363ee17fSDavidlohr Bueso 	if (mlock_future_check(mm, vm_flags, len))
14821da177e4SLinus Torvalds 		return -EAGAIN;
14831da177e4SLinus Torvalds 
14841da177e4SLinus Torvalds 	if (file) {
1485077bf22bSOleg Nesterov 		struct inode *inode = file_inode(file);
14861c972597SDan Williams 		unsigned long flags_mask;
14871c972597SDan Williams 
1488be83bbf8SLinus Torvalds 		if (!file_mmap_ok(file, inode, pgoff, len))
1489be83bbf8SLinus Torvalds 			return -EOVERFLOW;
1490be83bbf8SLinus Torvalds 
14911c972597SDan Williams 		flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1492077bf22bSOleg Nesterov 
14931da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
14941da177e4SLinus Torvalds 		case MAP_SHARED:
14951c972597SDan Williams 			/*
14961c972597SDan Williams 			 * Force use of MAP_SHARED_VALIDATE with non-legacy
14971c972597SDan Williams 			 * flags. E.g. MAP_SYNC is dangerous to use with
14981c972597SDan Williams 			 * MAP_SHARED as you don't know which consistency model
14991c972597SDan Williams 			 * you will get. We silently ignore unsupported flags
15001c972597SDan Williams 			 * with MAP_SHARED to preserve backward compatibility.
15011c972597SDan Williams 			 */
15021c972597SDan Williams 			flags &= LEGACY_MAP_MASK;
1503e4a9bc58SJoe Perches 			fallthrough;
15041c972597SDan Williams 		case MAP_SHARED_VALIDATE:
15051c972597SDan Williams 			if (flags & ~flags_mask)
15061c972597SDan Williams 				return -EOPNOTSUPP;
1507dc617f29SDarrick J. Wong 			if (prot & PROT_WRITE) {
1508dc617f29SDarrick J. Wong 				if (!(file->f_mode & FMODE_WRITE))
15091da177e4SLinus Torvalds 					return -EACCES;
1510dc617f29SDarrick J. Wong 				if (IS_SWAPFILE(file->f_mapping->host))
1511dc617f29SDarrick J. Wong 					return -ETXTBSY;
1512dc617f29SDarrick J. Wong 			}
15131da177e4SLinus Torvalds 
15141da177e4SLinus Torvalds 			/*
15151da177e4SLinus Torvalds 			 * Make sure we don't allow writing to an append-only
15161da177e4SLinus Torvalds 			 * file..
15171da177e4SLinus Torvalds 			 */
15181da177e4SLinus Torvalds 			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
15191da177e4SLinus Torvalds 				return -EACCES;
15201da177e4SLinus Torvalds 
15211da177e4SLinus Torvalds 			/*
15221da177e4SLinus Torvalds 			 * Make sure there are no mandatory locks on the file.
15231da177e4SLinus Torvalds 			 */
1524d7a06983SJeff Layton 			if (locks_verify_locked(file))
15251da177e4SLinus Torvalds 				return -EAGAIN;
15261da177e4SLinus Torvalds 
15271da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
15281da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_WRITE))
15291da177e4SLinus Torvalds 				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1530e4a9bc58SJoe Perches 			fallthrough;
15311da177e4SLinus Torvalds 		case MAP_PRIVATE:
15321da177e4SLinus Torvalds 			if (!(file->f_mode & FMODE_READ))
15331da177e4SLinus Torvalds 				return -EACCES;
153490f8572bSEric W. Biederman 			if (path_noexec(&file->f_path)) {
153580c5606cSLinus Torvalds 				if (vm_flags & VM_EXEC)
153680c5606cSLinus Torvalds 					return -EPERM;
153780c5606cSLinus Torvalds 				vm_flags &= ~VM_MAYEXEC;
153880c5606cSLinus Torvalds 			}
153980c5606cSLinus Torvalds 
154072c2d531SAl Viro 			if (!file->f_op->mmap)
154180c5606cSLinus Torvalds 				return -ENODEV;
1542b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1543b2c56e4fSOleg Nesterov 				return -EINVAL;
15441da177e4SLinus Torvalds 			break;
15451da177e4SLinus Torvalds 
15461da177e4SLinus Torvalds 		default:
15471da177e4SLinus Torvalds 			return -EINVAL;
15481da177e4SLinus Torvalds 		}
15491da177e4SLinus Torvalds 	} else {
15501da177e4SLinus Torvalds 		switch (flags & MAP_TYPE) {
15511da177e4SLinus Torvalds 		case MAP_SHARED:
1552b2c56e4fSOleg Nesterov 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1553b2c56e4fSOleg Nesterov 				return -EINVAL;
1554ce363942STejun Heo 			/*
1555ce363942STejun Heo 			 * Ignore pgoff.
1556ce363942STejun Heo 			 */
1557ce363942STejun Heo 			pgoff = 0;
15581da177e4SLinus Torvalds 			vm_flags |= VM_SHARED | VM_MAYSHARE;
15591da177e4SLinus Torvalds 			break;
15601da177e4SLinus Torvalds 		case MAP_PRIVATE:
15611da177e4SLinus Torvalds 			/*
15621da177e4SLinus Torvalds 			 * Set pgoff according to addr for anon_vma.
15631da177e4SLinus Torvalds 			 */
15641da177e4SLinus Torvalds 			pgoff = addr >> PAGE_SHIFT;
15651da177e4SLinus Torvalds 			break;
15661da177e4SLinus Torvalds 		default:
15671da177e4SLinus Torvalds 			return -EINVAL;
15681da177e4SLinus Torvalds 		}
15691da177e4SLinus Torvalds 	}
15701da177e4SLinus Torvalds 
1571c22c0d63SMichel Lespinasse 	/*
1572c22c0d63SMichel Lespinasse 	 * Set 'VM_NORESERVE' if we should not account for the
1573c22c0d63SMichel Lespinasse 	 * memory use of this mapping.
1574c22c0d63SMichel Lespinasse 	 */
1575c22c0d63SMichel Lespinasse 	if (flags & MAP_NORESERVE) {
1576c22c0d63SMichel Lespinasse 		/* We honor MAP_NORESERVE if allowed to overcommit */
1577c22c0d63SMichel Lespinasse 		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1578c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1579c22c0d63SMichel Lespinasse 
1580c22c0d63SMichel Lespinasse 		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
1581c22c0d63SMichel Lespinasse 		if (file && is_file_hugepages(file))
1582c22c0d63SMichel Lespinasse 			vm_flags |= VM_NORESERVE;
1583c22c0d63SMichel Lespinasse 	}
1584c22c0d63SMichel Lespinasse 
1585897ab3e0SMike Rapoport 	addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
158609a9f1d2SMichel Lespinasse 	if (!IS_ERR_VALUE(addr) &&
158709a9f1d2SMichel Lespinasse 	    ((vm_flags & VM_LOCKED) ||
158809a9f1d2SMichel Lespinasse 	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
158941badc15SMichel Lespinasse 		*populate = len;
1590bebeb3d6SMichel Lespinasse 	return addr;
15910165ab44SMiklos Szeredi }
15926be5ceb0SLinus Torvalds 
1593a90f590aSDominik Brodowski unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1594a90f590aSDominik Brodowski 			      unsigned long prot, unsigned long flags,
1595a90f590aSDominik Brodowski 			      unsigned long fd, unsigned long pgoff)
159666f0dc48SHugh Dickins {
159766f0dc48SHugh Dickins 	struct file *file = NULL;
15981e3ee14bSChen Gang 	unsigned long retval;
159966f0dc48SHugh Dickins 
160066f0dc48SHugh Dickins 	if (!(flags & MAP_ANONYMOUS)) {
1601120a795dSAl Viro 		audit_mmap_fd(fd, flags);
160266f0dc48SHugh Dickins 		file = fget(fd);
160366f0dc48SHugh Dickins 		if (!file)
16041e3ee14bSChen Gang 			return -EBADF;
16057bba8f0eSZhen Lei 		if (is_file_hugepages(file)) {
1606af73e4d9SNaoya Horiguchi 			len = ALIGN(len, huge_page_size(hstate_file(file)));
16077bba8f0eSZhen Lei 		} else if (unlikely(flags & MAP_HUGETLB)) {
1608493af578SJörn Engel 			retval = -EINVAL;
1609493af578SJörn Engel 			goto out_fput;
16107bba8f0eSZhen Lei 		}
161166f0dc48SHugh Dickins 	} else if (flags & MAP_HUGETLB) {
1612d7c9e99aSAlexey Gladkov 		struct ucounts *ucounts = NULL;
1613c103a4dcSAndrew Morton 		struct hstate *hs;
1614af73e4d9SNaoya Horiguchi 
161520ac2893SAnshuman Khandual 		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1616091d0d55SLi Zefan 		if (!hs)
1617091d0d55SLi Zefan 			return -EINVAL;
1618091d0d55SLi Zefan 
1619091d0d55SLi Zefan 		len = ALIGN(len, huge_page_size(hs));
162066f0dc48SHugh Dickins 		/*
162166f0dc48SHugh Dickins 		 * VM_NORESERVE is used because the reservations will be
162266f0dc48SHugh Dickins 		 * taken when vm_ops->mmap() is called
162366f0dc48SHugh Dickins 		 * A dummy user value is used because we are not locking
162466f0dc48SHugh Dickins 		 * memory so no accounting is necessary
162566f0dc48SHugh Dickins 		 */
1626af73e4d9SNaoya Horiguchi 		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
162742d7395fSAndi Kleen 				VM_NORESERVE,
1628d7c9e99aSAlexey Gladkov 				&ucounts, HUGETLB_ANONHUGE_INODE,
162942d7395fSAndi Kleen 				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
163066f0dc48SHugh Dickins 		if (IS_ERR(file))
163166f0dc48SHugh Dickins 			return PTR_ERR(file);
163266f0dc48SHugh Dickins 	}
163366f0dc48SHugh Dickins 
16343b8db39fSDavid Hildenbrand 	flags &= ~MAP_DENYWRITE;
163566f0dc48SHugh Dickins 
16369fbeb5abSMichal Hocko 	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1637493af578SJörn Engel out_fput:
163866f0dc48SHugh Dickins 	if (file)
163966f0dc48SHugh Dickins 		fput(file);
164066f0dc48SHugh Dickins 	return retval;
164166f0dc48SHugh Dickins }
164266f0dc48SHugh Dickins 
1643a90f590aSDominik Brodowski SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1644a90f590aSDominik Brodowski 		unsigned long, prot, unsigned long, flags,
1645a90f590aSDominik Brodowski 		unsigned long, fd, unsigned long, pgoff)
1646a90f590aSDominik Brodowski {
1647a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1648a90f590aSDominik Brodowski }
1649a90f590aSDominik Brodowski 
1650a4679373SChristoph Hellwig #ifdef __ARCH_WANT_SYS_OLD_MMAP
1651a4679373SChristoph Hellwig struct mmap_arg_struct {
1652a4679373SChristoph Hellwig 	unsigned long addr;
1653a4679373SChristoph Hellwig 	unsigned long len;
1654a4679373SChristoph Hellwig 	unsigned long prot;
1655a4679373SChristoph Hellwig 	unsigned long flags;
1656a4679373SChristoph Hellwig 	unsigned long fd;
1657a4679373SChristoph Hellwig 	unsigned long offset;
1658a4679373SChristoph Hellwig };
1659a4679373SChristoph Hellwig 
1660a4679373SChristoph Hellwig SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1661a4679373SChristoph Hellwig {
1662a4679373SChristoph Hellwig 	struct mmap_arg_struct a;
1663a4679373SChristoph Hellwig 
1664a4679373SChristoph Hellwig 	if (copy_from_user(&a, arg, sizeof(a)))
1665a4679373SChristoph Hellwig 		return -EFAULT;
1666de1741a1SAlexander Kuleshov 	if (offset_in_page(a.offset))
1667a4679373SChristoph Hellwig 		return -EINVAL;
1668a4679373SChristoph Hellwig 
1669a90f590aSDominik Brodowski 	return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1670a4679373SChristoph Hellwig 			       a.offset >> PAGE_SHIFT);
1671a4679373SChristoph Hellwig }
1672a4679373SChristoph Hellwig #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1673a4679373SChristoph Hellwig 
16744e950f6fSAlexey Dobriyan /*
16758bb4e7a2SWei Yang  * Some shared mappings will want the pages marked read-only
16764e950f6fSAlexey Dobriyan  * to track write events. If so, we'll downgrade vm_page_prot
16774e950f6fSAlexey Dobriyan  * to the private version (using protection_map[] without the
16784e950f6fSAlexey Dobriyan  * VM_SHARED bit).
16794e950f6fSAlexey Dobriyan  */
16806d2329f8SAndrea Arcangeli int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
16814e950f6fSAlexey Dobriyan {
1682ca16d140SKOSAKI Motohiro 	vm_flags_t vm_flags = vma->vm_flags;
16838a04446aSKirill A. Shutemov 	const struct vm_operations_struct *vm_ops = vma->vm_ops;
16844e950f6fSAlexey Dobriyan 
16854e950f6fSAlexey Dobriyan 	/* If it was private or non-writable, the write bit is already clear */
16864e950f6fSAlexey Dobriyan 	if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
16874e950f6fSAlexey Dobriyan 		return 0;
16884e950f6fSAlexey Dobriyan 
16894e950f6fSAlexey Dobriyan 	/* The backer wishes to know when pages are first written to? */
16908a04446aSKirill A. Shutemov 	if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
16914e950f6fSAlexey Dobriyan 		return 1;
16924e950f6fSAlexey Dobriyan 
169364e45507SPeter Feiner 	/* The open routine did something to the protections that pgprot_modify
169464e45507SPeter Feiner 	 * won't preserve? */
16956d2329f8SAndrea Arcangeli 	if (pgprot_val(vm_page_prot) !=
16966d2329f8SAndrea Arcangeli 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
16974e950f6fSAlexey Dobriyan 		return 0;
16984e950f6fSAlexey Dobriyan 
169964e45507SPeter Feiner 	/* Do we need to track softdirty? */
170064e45507SPeter Feiner 	if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
170164e45507SPeter Feiner 		return 1;
170264e45507SPeter Feiner 
17034e950f6fSAlexey Dobriyan 	/* Specialty mapping? */
17044b6e1e37SKonstantin Khlebnikov 	if (vm_flags & VM_PFNMAP)
17054e950f6fSAlexey Dobriyan 		return 0;
17064e950f6fSAlexey Dobriyan 
17074e950f6fSAlexey Dobriyan 	/* Can the mapping track the dirty pages? */
17084e950f6fSAlexey Dobriyan 	return vma->vm_file && vma->vm_file->f_mapping &&
1709f56753acSChristoph Hellwig 		mapping_can_writeback(vma->vm_file->f_mapping);
17104e950f6fSAlexey Dobriyan }
17114e950f6fSAlexey Dobriyan 
1712fc8744adSLinus Torvalds /*
1713fc8744adSLinus Torvalds  * We account for memory if it's a private writeable mapping,
17145a6fe125SMel Gorman  * not hugepages and VM_NORESERVE wasn't set.
1715fc8744adSLinus Torvalds  */
1716ca16d140SKOSAKI Motohiro static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1717fc8744adSLinus Torvalds {
17185a6fe125SMel Gorman 	/*
17195a6fe125SMel Gorman 	 * hugetlb has its own accounting separate from the core VM
17205a6fe125SMel Gorman 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
17215a6fe125SMel Gorman 	 */
17225a6fe125SMel Gorman 	if (file && is_file_hugepages(file))
17235a6fe125SMel Gorman 		return 0;
17245a6fe125SMel Gorman 
1725fc8744adSLinus Torvalds 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1726fc8744adSLinus Torvalds }
1727fc8744adSLinus Torvalds 
17280165ab44SMiklos Szeredi unsigned long mmap_region(struct file *file, unsigned long addr,
1729897ab3e0SMike Rapoport 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
1730897ab3e0SMike Rapoport 		struct list_head *uf)
17310165ab44SMiklos Szeredi {
17320165ab44SMiklos Szeredi 	struct mm_struct *mm = current->mm;
1733d70cec89SMiaohe Lin 	struct vm_area_struct *vma, *prev, *merge;
17340165ab44SMiklos Szeredi 	int error;
17350165ab44SMiklos Szeredi 	struct rb_node **rb_link, *rb_parent;
17360165ab44SMiklos Szeredi 	unsigned long charged = 0;
17370165ab44SMiklos Szeredi 
1738e8420a8eSCyril Hrubis 	/* Check against address space limit. */
173984638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
1740e8420a8eSCyril Hrubis 		unsigned long nr_pages;
1741e8420a8eSCyril Hrubis 
1742e8420a8eSCyril Hrubis 		/*
1743e8420a8eSCyril Hrubis 		 * MAP_FIXED may remove pages of mappings that intersects with
1744e8420a8eSCyril Hrubis 		 * requested mapping. Account for the pages it would unmap.
1745e8420a8eSCyril Hrubis 		 */
1746e8420a8eSCyril Hrubis 		nr_pages = count_vma_pages_range(mm, addr, addr + len);
1747e8420a8eSCyril Hrubis 
174884638335SKonstantin Khlebnikov 		if (!may_expand_vm(mm, vm_flags,
174984638335SKonstantin Khlebnikov 					(len >> PAGE_SHIFT) - nr_pages))
1750e8420a8eSCyril Hrubis 			return -ENOMEM;
1751e8420a8eSCyril Hrubis 	}
1752e8420a8eSCyril Hrubis 
1753fb8090b6SLiam R. Howlett 	/* Clear old maps, set up prev, rb_link, rb_parent, and uf */
1754fb8090b6SLiam R. Howlett 	if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
17551da177e4SLinus Torvalds 		return -ENOMEM;
1756fc8744adSLinus Torvalds 	/*
17571da177e4SLinus Torvalds 	 * Private writable mapping: check memory availability
17581da177e4SLinus Torvalds 	 */
17595a6fe125SMel Gorman 	if (accountable_mapping(file, vm_flags)) {
17601da177e4SLinus Torvalds 		charged = len >> PAGE_SHIFT;
1761191c5424SAl Viro 		if (security_vm_enough_memory_mm(mm, charged))
17621da177e4SLinus Torvalds 			return -ENOMEM;
17631da177e4SLinus Torvalds 		vm_flags |= VM_ACCOUNT;
17641da177e4SLinus Torvalds 	}
17651da177e4SLinus Torvalds 
17661da177e4SLinus Torvalds 	/*
1767de33c8dbSLinus Torvalds 	 * Can we just expand an old mapping?
17681da177e4SLinus Torvalds 	 */
176919a809afSAndrea Arcangeli 	vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
177019a809afSAndrea Arcangeli 			NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX);
1771ba470de4SRik van Riel 	if (vma)
17721da177e4SLinus Torvalds 		goto out;
17731da177e4SLinus Torvalds 
17741da177e4SLinus Torvalds 	/*
17751da177e4SLinus Torvalds 	 * Determine the object being mapped and call the appropriate
17761da177e4SLinus Torvalds 	 * specific mapper. the address has already been validated, but
17771da177e4SLinus Torvalds 	 * not unmapped, but the maps are removed from the list.
17781da177e4SLinus Torvalds 	 */
1779490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
17801da177e4SLinus Torvalds 	if (!vma) {
17811da177e4SLinus Torvalds 		error = -ENOMEM;
17821da177e4SLinus Torvalds 		goto unacct_error;
17831da177e4SLinus Torvalds 	}
17841da177e4SLinus Torvalds 
17851da177e4SLinus Torvalds 	vma->vm_start = addr;
17861da177e4SLinus Torvalds 	vma->vm_end = addr + len;
17871da177e4SLinus Torvalds 	vma->vm_flags = vm_flags;
17883ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(vm_flags);
17891da177e4SLinus Torvalds 	vma->vm_pgoff = pgoff;
17901da177e4SLinus Torvalds 
17911da177e4SLinus Torvalds 	if (file) {
17921da177e4SLinus Torvalds 		if (vm_flags & VM_DENYWRITE) {
17931da177e4SLinus Torvalds 			error = deny_write_access(file);
17941da177e4SLinus Torvalds 			if (error)
17951da177e4SLinus Torvalds 				goto free_vma;
17961da177e4SLinus Torvalds 		}
17974bb5f5d9SDavid Herrmann 		if (vm_flags & VM_SHARED) {
17984bb5f5d9SDavid Herrmann 			error = mapping_map_writable(file->f_mapping);
17994bb5f5d9SDavid Herrmann 			if (error)
18004bb5f5d9SDavid Herrmann 				goto allow_write_and_free_vma;
18014bb5f5d9SDavid Herrmann 		}
18024bb5f5d9SDavid Herrmann 
18034bb5f5d9SDavid Herrmann 		/* ->mmap() can change vma->vm_file, but must guarantee that
18044bb5f5d9SDavid Herrmann 		 * vma_link() below can deny write-access if VM_DENYWRITE is set
18054bb5f5d9SDavid Herrmann 		 * and map writably if VM_SHARED is set. This usually means the
18064bb5f5d9SDavid Herrmann 		 * new file must not have been exposed to user-space, yet.
18074bb5f5d9SDavid Herrmann 		 */
1808cb0942b8SAl Viro 		vma->vm_file = get_file(file);
1809f74ac015SMiklos Szeredi 		error = call_mmap(file, vma);
18101da177e4SLinus Torvalds 		if (error)
18111da177e4SLinus Torvalds 			goto unmap_and_free_vma;
18121da177e4SLinus Torvalds 
1813309d08d9SLiu Zixian 		/* Can addr have changed??
1814309d08d9SLiu Zixian 		 *
1815309d08d9SLiu Zixian 		 * Answer: Yes, several device drivers can do it in their
1816309d08d9SLiu Zixian 		 *         f_op->mmap method. -DaveM
1817309d08d9SLiu Zixian 		 * Bug: If addr is changed, prev, rb_link, rb_parent should
1818309d08d9SLiu Zixian 		 *      be updated for vma_link()
1819309d08d9SLiu Zixian 		 */
1820309d08d9SLiu Zixian 		WARN_ON_ONCE(addr != vma->vm_start);
1821309d08d9SLiu Zixian 
1822309d08d9SLiu Zixian 		addr = vma->vm_start;
1823309d08d9SLiu Zixian 
1824d70cec89SMiaohe Lin 		/* If vm_flags changed after call_mmap(), we should try merge vma again
1825d70cec89SMiaohe Lin 		 * as we may succeed this time.
1826d70cec89SMiaohe Lin 		 */
1827d70cec89SMiaohe Lin 		if (unlikely(vm_flags != vma->vm_flags && prev)) {
1828d70cec89SMiaohe Lin 			merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
1829d70cec89SMiaohe Lin 				NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX);
1830d70cec89SMiaohe Lin 			if (merge) {
1831bc4fe4cdSMiaohe Lin 				/* ->mmap() can change vma->vm_file and fput the original file. So
1832bc4fe4cdSMiaohe Lin 				 * fput the vma->vm_file here or we would add an extra fput for file
1833bc4fe4cdSMiaohe Lin 				 * and cause general protection fault ultimately.
1834bc4fe4cdSMiaohe Lin 				 */
1835bc4fe4cdSMiaohe Lin 				fput(vma->vm_file);
1836d70cec89SMiaohe Lin 				vm_area_free(vma);
1837d70cec89SMiaohe Lin 				vma = merge;
1838309d08d9SLiu Zixian 				/* Update vm_flags to pick up the change. */
1839d70cec89SMiaohe Lin 				vm_flags = vma->vm_flags;
1840d70cec89SMiaohe Lin 				goto unmap_writable;
1841d70cec89SMiaohe Lin 			}
1842d70cec89SMiaohe Lin 		}
1843d70cec89SMiaohe Lin 
18441da177e4SLinus Torvalds 		vm_flags = vma->vm_flags;
1845f8dbf0a7SHuang Shijie 	} else if (vm_flags & VM_SHARED) {
1846f8dbf0a7SHuang Shijie 		error = shmem_zero_setup(vma);
1847f8dbf0a7SHuang Shijie 		if (error)
1848f8dbf0a7SHuang Shijie 			goto free_vma;
1849bfd40eafSKirill A. Shutemov 	} else {
1850bfd40eafSKirill A. Shutemov 		vma_set_anonymous(vma);
1851f8dbf0a7SHuang Shijie 	}
18521da177e4SLinus Torvalds 
1853c462ac28SCatalin Marinas 	/* Allow architectures to sanity-check the vm_flags */
1854c462ac28SCatalin Marinas 	if (!arch_validate_flags(vma->vm_flags)) {
1855c462ac28SCatalin Marinas 		error = -EINVAL;
1856c462ac28SCatalin Marinas 		if (file)
1857c462ac28SCatalin Marinas 			goto unmap_and_free_vma;
1858c462ac28SCatalin Marinas 		else
1859c462ac28SCatalin Marinas 			goto free_vma;
1860c462ac28SCatalin Marinas 	}
1861c462ac28SCatalin Marinas 
18624d3d5b41SOleg Nesterov 	vma_link(mm, vma, prev, rb_link, rb_parent);
18634d3d5b41SOleg Nesterov 	/* Once vma denies write, undo our temporary denial count */
18644bb5f5d9SDavid Herrmann 	if (file) {
1865d70cec89SMiaohe Lin unmap_writable:
18664bb5f5d9SDavid Herrmann 		if (vm_flags & VM_SHARED)
18674bb5f5d9SDavid Herrmann 			mapping_unmap_writable(file->f_mapping);
1868e8686772SOleg Nesterov 		if (vm_flags & VM_DENYWRITE)
1869e8686772SOleg Nesterov 			allow_write_access(file);
18704bb5f5d9SDavid Herrmann 	}
1871e8686772SOleg Nesterov 	file = vma->vm_file;
18721da177e4SLinus Torvalds out:
1873cdd6c482SIngo Molnar 	perf_event_mmap(vma);
18740a4a9391SPeter Zijlstra 
187584638335SKonstantin Khlebnikov 	vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
18761da177e4SLinus Torvalds 	if (vm_flags & VM_LOCKED) {
1877e1fb4a08SDave Jiang 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
1878e1fb4a08SDave Jiang 					is_vm_hugetlb_page(vma) ||
1879e1fb4a08SDave Jiang 					vma == get_gate_vma(current->mm))
1880de60f5f1SEric B Munson 			vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1881e1fb4a08SDave Jiang 		else
1882e1fb4a08SDave Jiang 			mm->locked_vm += (len >> PAGE_SHIFT);
1883bebeb3d6SMichel Lespinasse 	}
18842b144498SSrikar Dronamraju 
1885c7a3a88cSOleg Nesterov 	if (file)
1886c7a3a88cSOleg Nesterov 		uprobe_mmap(vma);
18872b144498SSrikar Dronamraju 
1888d9104d1cSCyrill Gorcunov 	/*
1889d9104d1cSCyrill Gorcunov 	 * New (or expanded) vma always get soft dirty status.
1890d9104d1cSCyrill Gorcunov 	 * Otherwise user-space soft-dirty page tracker won't
1891d9104d1cSCyrill Gorcunov 	 * be able to distinguish situation when vma area unmapped,
1892d9104d1cSCyrill Gorcunov 	 * then new mapped in-place (which must be aimed as
1893d9104d1cSCyrill Gorcunov 	 * a completely new data area).
1894d9104d1cSCyrill Gorcunov 	 */
1895d9104d1cSCyrill Gorcunov 	vma->vm_flags |= VM_SOFTDIRTY;
1896d9104d1cSCyrill Gorcunov 
189764e45507SPeter Feiner 	vma_set_page_prot(vma);
189864e45507SPeter Feiner 
18991da177e4SLinus Torvalds 	return addr;
19001da177e4SLinus Torvalds 
19011da177e4SLinus Torvalds unmap_and_free_vma:
19021527f926SChristian König 	fput(vma->vm_file);
19031da177e4SLinus Torvalds 	vma->vm_file = NULL;
19041da177e4SLinus Torvalds 
19051da177e4SLinus Torvalds 	/* Undo any partial mapping done by a device driver. */
1906e0da382cSHugh Dickins 	unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1907e0da382cSHugh Dickins 	charged = 0;
19084bb5f5d9SDavid Herrmann 	if (vm_flags & VM_SHARED)
19094bb5f5d9SDavid Herrmann 		mapping_unmap_writable(file->f_mapping);
19104bb5f5d9SDavid Herrmann allow_write_and_free_vma:
19114bb5f5d9SDavid Herrmann 	if (vm_flags & VM_DENYWRITE)
19124bb5f5d9SDavid Herrmann 		allow_write_access(file);
19131da177e4SLinus Torvalds free_vma:
19143928d4f5SLinus Torvalds 	vm_area_free(vma);
19151da177e4SLinus Torvalds unacct_error:
19161da177e4SLinus Torvalds 	if (charged)
19171da177e4SLinus Torvalds 		vm_unacct_memory(charged);
19181da177e4SLinus Torvalds 	return error;
19191da177e4SLinus Torvalds }
19201da177e4SLinus Torvalds 
1921baceaf1cSJaewon Kim static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1922db4fbfb9SMichel Lespinasse {
1923db4fbfb9SMichel Lespinasse 	/*
1924db4fbfb9SMichel Lespinasse 	 * We implement the search by looking for an rbtree node that
1925db4fbfb9SMichel Lespinasse 	 * immediately follows a suitable gap. That is,
1926db4fbfb9SMichel Lespinasse 	 * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1927db4fbfb9SMichel Lespinasse 	 * - gap_end   = vma->vm_start        >= info->low_limit  + length;
1928db4fbfb9SMichel Lespinasse 	 * - gap_end - gap_start >= length
1929db4fbfb9SMichel Lespinasse 	 */
1930db4fbfb9SMichel Lespinasse 
1931db4fbfb9SMichel Lespinasse 	struct mm_struct *mm = current->mm;
1932db4fbfb9SMichel Lespinasse 	struct vm_area_struct *vma;
1933db4fbfb9SMichel Lespinasse 	unsigned long length, low_limit, high_limit, gap_start, gap_end;
1934db4fbfb9SMichel Lespinasse 
1935db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
1936db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
1937db4fbfb9SMichel Lespinasse 	if (length < info->length)
1938db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1939db4fbfb9SMichel Lespinasse 
1940db4fbfb9SMichel Lespinasse 	/* Adjust search limits by the desired length */
1941db4fbfb9SMichel Lespinasse 	if (info->high_limit < length)
1942db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1943db4fbfb9SMichel Lespinasse 	high_limit = info->high_limit - length;
1944db4fbfb9SMichel Lespinasse 
1945db4fbfb9SMichel Lespinasse 	if (info->low_limit > high_limit)
1946db4fbfb9SMichel Lespinasse 		return -ENOMEM;
1947db4fbfb9SMichel Lespinasse 	low_limit = info->low_limit + length;
1948db4fbfb9SMichel Lespinasse 
1949db4fbfb9SMichel Lespinasse 	/* Check if rbtree root looks promising */
1950db4fbfb9SMichel Lespinasse 	if (RB_EMPTY_ROOT(&mm->mm_rb))
1951db4fbfb9SMichel Lespinasse 		goto check_highest;
1952db4fbfb9SMichel Lespinasse 	vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1953db4fbfb9SMichel Lespinasse 	if (vma->rb_subtree_gap < length)
1954db4fbfb9SMichel Lespinasse 		goto check_highest;
1955db4fbfb9SMichel Lespinasse 
1956db4fbfb9SMichel Lespinasse 	while (true) {
1957db4fbfb9SMichel Lespinasse 		/* Visit left subtree if it looks promising */
19581be7107fSHugh Dickins 		gap_end = vm_start_gap(vma);
1959db4fbfb9SMichel Lespinasse 		if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1960db4fbfb9SMichel Lespinasse 			struct vm_area_struct *left =
1961db4fbfb9SMichel Lespinasse 				rb_entry(vma->vm_rb.rb_left,
1962db4fbfb9SMichel Lespinasse 					 struct vm_area_struct, vm_rb);
1963db4fbfb9SMichel Lespinasse 			if (left->rb_subtree_gap >= length) {
1964db4fbfb9SMichel Lespinasse 				vma = left;
1965db4fbfb9SMichel Lespinasse 				continue;
1966db4fbfb9SMichel Lespinasse 			}
1967db4fbfb9SMichel Lespinasse 		}
1968db4fbfb9SMichel Lespinasse 
19691be7107fSHugh Dickins 		gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
1970db4fbfb9SMichel Lespinasse check_current:
1971db4fbfb9SMichel Lespinasse 		/* Check if current node has a suitable gap */
1972db4fbfb9SMichel Lespinasse 		if (gap_start > high_limit)
1973db4fbfb9SMichel Lespinasse 			return -ENOMEM;
1974f4cb767dSHugh Dickins 		if (gap_end >= low_limit &&
1975f4cb767dSHugh Dickins 		    gap_end > gap_start && gap_end - gap_start >= length)
1976db4fbfb9SMichel Lespinasse 			goto found;
1977db4fbfb9SMichel Lespinasse 
1978db4fbfb9SMichel Lespinasse 		/* Visit right subtree if it looks promising */
1979db4fbfb9SMichel Lespinasse 		if (vma->vm_rb.rb_right) {
1980db4fbfb9SMichel Lespinasse 			struct vm_area_struct *right =
1981db4fbfb9SMichel Lespinasse 				rb_entry(vma->vm_rb.rb_right,
1982db4fbfb9SMichel Lespinasse 					 struct vm_area_struct, vm_rb);
1983db4fbfb9SMichel Lespinasse 			if (right->rb_subtree_gap >= length) {
1984db4fbfb9SMichel Lespinasse 				vma = right;
1985db4fbfb9SMichel Lespinasse 				continue;
1986db4fbfb9SMichel Lespinasse 			}
1987db4fbfb9SMichel Lespinasse 		}
1988db4fbfb9SMichel Lespinasse 
1989db4fbfb9SMichel Lespinasse 		/* Go back up the rbtree to find next candidate node */
1990db4fbfb9SMichel Lespinasse 		while (true) {
1991db4fbfb9SMichel Lespinasse 			struct rb_node *prev = &vma->vm_rb;
1992db4fbfb9SMichel Lespinasse 			if (!rb_parent(prev))
1993db4fbfb9SMichel Lespinasse 				goto check_highest;
1994db4fbfb9SMichel Lespinasse 			vma = rb_entry(rb_parent(prev),
1995db4fbfb9SMichel Lespinasse 				       struct vm_area_struct, vm_rb);
1996db4fbfb9SMichel Lespinasse 			if (prev == vma->vm_rb.rb_left) {
19971be7107fSHugh Dickins 				gap_start = vm_end_gap(vma->vm_prev);
19981be7107fSHugh Dickins 				gap_end = vm_start_gap(vma);
1999db4fbfb9SMichel Lespinasse 				goto check_current;
2000db4fbfb9SMichel Lespinasse 			}
2001db4fbfb9SMichel Lespinasse 		}
2002db4fbfb9SMichel Lespinasse 	}
2003db4fbfb9SMichel Lespinasse 
2004db4fbfb9SMichel Lespinasse check_highest:
2005db4fbfb9SMichel Lespinasse 	/* Check highest gap, which does not precede any rbtree node */
2006db4fbfb9SMichel Lespinasse 	gap_start = mm->highest_vm_end;
2007db4fbfb9SMichel Lespinasse 	gap_end = ULONG_MAX;  /* Only for VM_BUG_ON below */
2008db4fbfb9SMichel Lespinasse 	if (gap_start > high_limit)
2009db4fbfb9SMichel Lespinasse 		return -ENOMEM;
2010db4fbfb9SMichel Lespinasse 
2011db4fbfb9SMichel Lespinasse found:
2012db4fbfb9SMichel Lespinasse 	/* We found a suitable gap. Clip it with the original low_limit. */
2013db4fbfb9SMichel Lespinasse 	if (gap_start < info->low_limit)
2014db4fbfb9SMichel Lespinasse 		gap_start = info->low_limit;
2015db4fbfb9SMichel Lespinasse 
2016db4fbfb9SMichel Lespinasse 	/* Adjust gap address to the desired alignment */
2017db4fbfb9SMichel Lespinasse 	gap_start += (info->align_offset - gap_start) & info->align_mask;
2018db4fbfb9SMichel Lespinasse 
2019db4fbfb9SMichel Lespinasse 	VM_BUG_ON(gap_start + info->length > info->high_limit);
2020db4fbfb9SMichel Lespinasse 	VM_BUG_ON(gap_start + info->length > gap_end);
2021db4fbfb9SMichel Lespinasse 	return gap_start;
2022db4fbfb9SMichel Lespinasse }
2023db4fbfb9SMichel Lespinasse 
2024baceaf1cSJaewon Kim static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
2025db4fbfb9SMichel Lespinasse {
2026db4fbfb9SMichel Lespinasse 	struct mm_struct *mm = current->mm;
2027db4fbfb9SMichel Lespinasse 	struct vm_area_struct *vma;
2028db4fbfb9SMichel Lespinasse 	unsigned long length, low_limit, high_limit, gap_start, gap_end;
2029db4fbfb9SMichel Lespinasse 
2030db4fbfb9SMichel Lespinasse 	/* Adjust search length to account for worst case alignment overhead */
2031db4fbfb9SMichel Lespinasse 	length = info->length + info->align_mask;
2032db4fbfb9SMichel Lespinasse 	if (length < info->length)
2033db4fbfb9SMichel Lespinasse 		return -ENOMEM;
2034db4fbfb9SMichel Lespinasse 
2035db4fbfb9SMichel Lespinasse 	/*
2036db4fbfb9SMichel Lespinasse 	 * Adjust search limits by the desired length.
2037db4fbfb9SMichel Lespinasse 	 * See implementation comment at top of unmapped_area().
2038db4fbfb9SMichel Lespinasse 	 */
2039db4fbfb9SMichel Lespinasse 	gap_end = info->high_limit;
2040db4fbfb9SMichel Lespinasse 	if (gap_end < length)
2041db4fbfb9SMichel Lespinasse 		return -ENOMEM;
2042db4fbfb9SMichel Lespinasse 	high_limit = gap_end - length;
2043db4fbfb9SMichel Lespinasse 
2044db4fbfb9SMichel Lespinasse 	if (info->low_limit > high_limit)
2045db4fbfb9SMichel Lespinasse 		return -ENOMEM;
2046db4fbfb9SMichel Lespinasse 	low_limit = info->low_limit + length;
2047db4fbfb9SMichel Lespinasse 
2048db4fbfb9SMichel Lespinasse 	/* Check highest gap, which does not precede any rbtree node */
2049db4fbfb9SMichel Lespinasse 	gap_start = mm->highest_vm_end;
2050db4fbfb9SMichel Lespinasse 	if (gap_start <= high_limit)
2051db4fbfb9SMichel Lespinasse 		goto found_highest;
2052db4fbfb9SMichel Lespinasse 
2053db4fbfb9SMichel Lespinasse 	/* Check if rbtree root looks promising */
2054db4fbfb9SMichel Lespinasse 	if (RB_EMPTY_ROOT(&mm->mm_rb))
2055db4fbfb9SMichel Lespinasse 		return -ENOMEM;
2056db4fbfb9SMichel Lespinasse 	vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
2057db4fbfb9SMichel Lespinasse 	if (vma->rb_subtree_gap < length)
2058db4fbfb9SMichel Lespinasse 		return -ENOMEM;
2059db4fbfb9SMichel Lespinasse 
2060db4fbfb9SMichel Lespinasse 	while (true) {
2061db4fbfb9SMichel Lespinasse 		/* Visit right subtree if it looks promising */
20621be7107fSHugh Dickins 		gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
2063db4fbfb9SMichel Lespinasse 		if (gap_start <= high_limit && vma->vm_rb.rb_right) {
2064db4fbfb9SMichel Lespinasse 			struct vm_area_struct *right =
2065db4fbfb9SMichel Lespinasse 				rb_entry(vma->vm_rb.rb_right,
2066db4fbfb9SMichel Lespinasse 					 struct vm_area_struct, vm_rb);
2067db4fbfb9SMichel Lespinasse 			if (right->rb_subtree_gap >= length) {
2068db4fbfb9SMichel Lespinasse 				vma = right;
2069db4fbfb9SMichel Lespinasse 				continue;
2070db4fbfb9SMichel Lespinasse 			}
2071db4fbfb9SMichel Lespinasse 		}
2072db4fbfb9SMichel Lespinasse 
2073db4fbfb9SMichel Lespinasse check_current:
2074db4fbfb9SMichel Lespinasse 		/* Check if current node has a suitable gap */
20751be7107fSHugh Dickins 		gap_end = vm_start_gap(vma);
2076db4fbfb9SMichel Lespinasse 		if (gap_end < low_limit)
2077db4fbfb9SMichel Lespinasse 			return -ENOMEM;
2078f4cb767dSHugh Dickins 		if (gap_start <= high_limit &&
2079f4cb767dSHugh Dickins 		    gap_end > gap_start && gap_end - gap_start >= length)
2080db4fbfb9SMichel Lespinasse 			goto found;
2081db4fbfb9SMichel Lespinasse 
2082db4fbfb9SMichel Lespinasse 		/* Visit left subtree if it looks promising */
2083db4fbfb9SMichel Lespinasse 		if (vma->vm_rb.rb_left) {
2084db4fbfb9SMichel Lespinasse 			struct vm_area_struct *left =
2085db4fbfb9SMichel Lespinasse 				rb_entry(vma->vm_rb.rb_left,
2086db4fbfb9SMichel Lespinasse 					 struct vm_area_struct, vm_rb);
2087db4fbfb9SMichel Lespinasse 			if (left->rb_subtree_gap >= length) {
2088db4fbfb9SMichel Lespinasse 				vma = left;
2089db4fbfb9SMichel Lespinasse 				continue;
2090db4fbfb9SMichel Lespinasse 			}
2091db4fbfb9SMichel Lespinasse 		}
2092db4fbfb9SMichel Lespinasse 
2093db4fbfb9SMichel Lespinasse 		/* Go back up the rbtree to find next candidate node */
2094db4fbfb9SMichel Lespinasse 		while (true) {
2095db4fbfb9SMichel Lespinasse 			struct rb_node *prev = &vma->vm_rb;
2096db4fbfb9SMichel Lespinasse 			if (!rb_parent(prev))
2097db4fbfb9SMichel Lespinasse 				return -ENOMEM;
2098db4fbfb9SMichel Lespinasse 			vma = rb_entry(rb_parent(prev),
2099db4fbfb9SMichel Lespinasse 				       struct vm_area_struct, vm_rb);
2100db4fbfb9SMichel Lespinasse 			if (prev == vma->vm_rb.rb_right) {
2101db4fbfb9SMichel Lespinasse 				gap_start = vma->vm_prev ?
21021be7107fSHugh Dickins 					vm_end_gap(vma->vm_prev) : 0;
2103db4fbfb9SMichel Lespinasse 				goto check_current;
2104db4fbfb9SMichel Lespinasse 			}
2105db4fbfb9SMichel Lespinasse 		}
2106db4fbfb9SMichel Lespinasse 	}
2107db4fbfb9SMichel Lespinasse 
2108db4fbfb9SMichel Lespinasse found:
2109db4fbfb9SMichel Lespinasse 	/* We found a suitable gap. Clip it with the original high_limit. */
2110db4fbfb9SMichel Lespinasse 	if (gap_end > info->high_limit)
2111db4fbfb9SMichel Lespinasse 		gap_end = info->high_limit;
2112db4fbfb9SMichel Lespinasse 
2113db4fbfb9SMichel Lespinasse found_highest:
2114db4fbfb9SMichel Lespinasse 	/* Compute highest gap address at the desired alignment */
2115db4fbfb9SMichel Lespinasse 	gap_end -= info->length;
2116db4fbfb9SMichel Lespinasse 	gap_end -= (gap_end - info->align_offset) & info->align_mask;
2117db4fbfb9SMichel Lespinasse 
2118db4fbfb9SMichel Lespinasse 	VM_BUG_ON(gap_end < info->low_limit);
2119db4fbfb9SMichel Lespinasse 	VM_BUG_ON(gap_end < gap_start);
2120db4fbfb9SMichel Lespinasse 	return gap_end;
2121db4fbfb9SMichel Lespinasse }
2122db4fbfb9SMichel Lespinasse 
2123baceaf1cSJaewon Kim /*
2124baceaf1cSJaewon Kim  * Search for an unmapped address range.
2125baceaf1cSJaewon Kim  *
2126baceaf1cSJaewon Kim  * We are looking for a range that:
2127baceaf1cSJaewon Kim  * - does not intersect with any VMA;
2128baceaf1cSJaewon Kim  * - is contained within the [low_limit, high_limit) interval;
2129baceaf1cSJaewon Kim  * - is at least the desired size.
2130baceaf1cSJaewon Kim  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
2131baceaf1cSJaewon Kim  */
2132baceaf1cSJaewon Kim unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
2133baceaf1cSJaewon Kim {
2134df529cabSJaewon Kim 	unsigned long addr;
2135df529cabSJaewon Kim 
2136baceaf1cSJaewon Kim 	if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
2137df529cabSJaewon Kim 		addr = unmapped_area_topdown(info);
2138baceaf1cSJaewon Kim 	else
2139df529cabSJaewon Kim 		addr = unmapped_area(info);
2140df529cabSJaewon Kim 
2141df529cabSJaewon Kim 	trace_vm_unmapped_area(addr, info);
2142df529cabSJaewon Kim 	return addr;
2143baceaf1cSJaewon Kim }
2144f6795053SSteve Capper 
2145f6795053SSteve Capper #ifndef arch_get_mmap_end
2146f6795053SSteve Capper #define arch_get_mmap_end(addr)	(TASK_SIZE)
2147f6795053SSteve Capper #endif
2148f6795053SSteve Capper 
2149f6795053SSteve Capper #ifndef arch_get_mmap_base
2150f6795053SSteve Capper #define arch_get_mmap_base(addr, base) (base)
2151f6795053SSteve Capper #endif
2152f6795053SSteve Capper 
21531da177e4SLinus Torvalds /* Get an address range which is currently unmapped.
21541da177e4SLinus Torvalds  * For shmat() with addr=0.
21551da177e4SLinus Torvalds  *
21561da177e4SLinus Torvalds  * Ugly calling convention alert:
21571da177e4SLinus Torvalds  * Return value with the low bits set means error value,
21581da177e4SLinus Torvalds  * ie
21591da177e4SLinus Torvalds  *	if (ret & ~PAGE_MASK)
21601da177e4SLinus Torvalds  *		error = ret;
21611da177e4SLinus Torvalds  *
21621da177e4SLinus Torvalds  * This function "knows" that -ENOMEM has the bits set.
21631da177e4SLinus Torvalds  */
21641da177e4SLinus Torvalds #ifndef HAVE_ARCH_UNMAPPED_AREA
21651da177e4SLinus Torvalds unsigned long
21661da177e4SLinus Torvalds arch_get_unmapped_area(struct file *filp, unsigned long addr,
21671da177e4SLinus Torvalds 		unsigned long len, unsigned long pgoff, unsigned long flags)
21681da177e4SLinus Torvalds {
21691da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
21701be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
2171db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
2172f6795053SSteve Capper 	const unsigned long mmap_end = arch_get_mmap_end(addr);
21731da177e4SLinus Torvalds 
2174f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
21751da177e4SLinus Torvalds 		return -ENOMEM;
21761da177e4SLinus Torvalds 
217706abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
217806abdfb4SBenjamin Herrenschmidt 		return addr;
217906abdfb4SBenjamin Herrenschmidt 
21801da177e4SLinus Torvalds 	if (addr) {
21811da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
21821be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
2183f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
21841be7107fSHugh Dickins 		    (!vma || addr + len <= vm_start_gap(vma)) &&
21851be7107fSHugh Dickins 		    (!prev || addr >= vm_end_gap(prev)))
21861da177e4SLinus Torvalds 			return addr;
21871da177e4SLinus Torvalds 	}
21881da177e4SLinus Torvalds 
2189db4fbfb9SMichel Lespinasse 	info.flags = 0;
2190db4fbfb9SMichel Lespinasse 	info.length = len;
21914e99b021SHeiko Carstens 	info.low_limit = mm->mmap_base;
2192f6795053SSteve Capper 	info.high_limit = mmap_end;
2193db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
219409ef5283SJaewon Kim 	info.align_offset = 0;
2195db4fbfb9SMichel Lespinasse 	return vm_unmapped_area(&info);
21961da177e4SLinus Torvalds }
21971da177e4SLinus Torvalds #endif
21981da177e4SLinus Torvalds 
21991da177e4SLinus Torvalds /*
22001da177e4SLinus Torvalds  * This mmap-allocator allocates new areas top-down from below the
22011da177e4SLinus Torvalds  * stack's low limit (the base):
22021da177e4SLinus Torvalds  */
22031da177e4SLinus Torvalds #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
22041da177e4SLinus Torvalds unsigned long
220543cca0b1SYang Fan arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
220643cca0b1SYang Fan 			  unsigned long len, unsigned long pgoff,
220743cca0b1SYang Fan 			  unsigned long flags)
22081da177e4SLinus Torvalds {
22091be7107fSHugh Dickins 	struct vm_area_struct *vma, *prev;
22101da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
2211db4fbfb9SMichel Lespinasse 	struct vm_unmapped_area_info info;
2212f6795053SSteve Capper 	const unsigned long mmap_end = arch_get_mmap_end(addr);
22131da177e4SLinus Torvalds 
22141da177e4SLinus Torvalds 	/* requested length too big for entire address space */
2215f6795053SSteve Capper 	if (len > mmap_end - mmap_min_addr)
22161da177e4SLinus Torvalds 		return -ENOMEM;
22171da177e4SLinus Torvalds 
221806abdfb4SBenjamin Herrenschmidt 	if (flags & MAP_FIXED)
221906abdfb4SBenjamin Herrenschmidt 		return addr;
222006abdfb4SBenjamin Herrenschmidt 
22211da177e4SLinus Torvalds 	/* requesting a specific address */
22221da177e4SLinus Torvalds 	if (addr) {
22231da177e4SLinus Torvalds 		addr = PAGE_ALIGN(addr);
22241be7107fSHugh Dickins 		vma = find_vma_prev(mm, addr, &prev);
2225f6795053SSteve Capper 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
22261be7107fSHugh Dickins 				(!vma || addr + len <= vm_start_gap(vma)) &&
22271be7107fSHugh Dickins 				(!prev || addr >= vm_end_gap(prev)))
22281da177e4SLinus Torvalds 			return addr;
22291da177e4SLinus Torvalds 	}
22301da177e4SLinus Torvalds 
2231db4fbfb9SMichel Lespinasse 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2232db4fbfb9SMichel Lespinasse 	info.length = len;
22332afc745fSAkira Takeuchi 	info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2234f6795053SSteve Capper 	info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
2235db4fbfb9SMichel Lespinasse 	info.align_mask = 0;
223609ef5283SJaewon Kim 	info.align_offset = 0;
2237db4fbfb9SMichel Lespinasse 	addr = vm_unmapped_area(&info);
2238b716ad95SXiao Guangrong 
22391da177e4SLinus Torvalds 	/*
22401da177e4SLinus Torvalds 	 * A failed mmap() very likely causes application failure,
22411da177e4SLinus Torvalds 	 * so fall back to the bottom-up function here. This scenario
22421da177e4SLinus Torvalds 	 * can happen with large stack limits and large mmap()
22431da177e4SLinus Torvalds 	 * allocations.
22441da177e4SLinus Torvalds 	 */
2245de1741a1SAlexander Kuleshov 	if (offset_in_page(addr)) {
2246db4fbfb9SMichel Lespinasse 		VM_BUG_ON(addr != -ENOMEM);
2247db4fbfb9SMichel Lespinasse 		info.flags = 0;
2248db4fbfb9SMichel Lespinasse 		info.low_limit = TASK_UNMAPPED_BASE;
2249f6795053SSteve Capper 		info.high_limit = mmap_end;
2250db4fbfb9SMichel Lespinasse 		addr = vm_unmapped_area(&info);
2251db4fbfb9SMichel Lespinasse 	}
22521da177e4SLinus Torvalds 
22531da177e4SLinus Torvalds 	return addr;
22541da177e4SLinus Torvalds }
22551da177e4SLinus Torvalds #endif
22561da177e4SLinus Torvalds 
22571da177e4SLinus Torvalds unsigned long
22581da177e4SLinus Torvalds get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
22591da177e4SLinus Torvalds 		unsigned long pgoff, unsigned long flags)
22601da177e4SLinus Torvalds {
226106abdfb4SBenjamin Herrenschmidt 	unsigned long (*get_area)(struct file *, unsigned long,
226206abdfb4SBenjamin Herrenschmidt 				  unsigned long, unsigned long, unsigned long);
226307ab67c8SLinus Torvalds 
22649206de95SAl Viro 	unsigned long error = arch_mmap_check(addr, len, flags);
22659206de95SAl Viro 	if (error)
22669206de95SAl Viro 		return error;
22679206de95SAl Viro 
22689206de95SAl Viro 	/* Careful about overflows.. */
22699206de95SAl Viro 	if (len > TASK_SIZE)
22709206de95SAl Viro 		return -ENOMEM;
22719206de95SAl Viro 
227207ab67c8SLinus Torvalds 	get_area = current->mm->get_unmapped_area;
2273c01d5b30SHugh Dickins 	if (file) {
2274c01d5b30SHugh Dickins 		if (file->f_op->get_unmapped_area)
227507ab67c8SLinus Torvalds 			get_area = file->f_op->get_unmapped_area;
2276c01d5b30SHugh Dickins 	} else if (flags & MAP_SHARED) {
2277c01d5b30SHugh Dickins 		/*
2278c01d5b30SHugh Dickins 		 * mmap_region() will call shmem_zero_setup() to create a file,
2279c01d5b30SHugh Dickins 		 * so use shmem's get_unmapped_area in case it can be huge.
228045e55300SPeter Collingbourne 		 * do_mmap() will clear pgoff, so match alignment.
2281c01d5b30SHugh Dickins 		 */
2282c01d5b30SHugh Dickins 		pgoff = 0;
2283c01d5b30SHugh Dickins 		get_area = shmem_get_unmapped_area;
2284c01d5b30SHugh Dickins 	}
2285c01d5b30SHugh Dickins 
228607ab67c8SLinus Torvalds 	addr = get_area(file, addr, len, pgoff, flags);
228707ab67c8SLinus Torvalds 	if (IS_ERR_VALUE(addr))
228807ab67c8SLinus Torvalds 		return addr;
228907ab67c8SLinus Torvalds 
22901da177e4SLinus Torvalds 	if (addr > TASK_SIZE - len)
22911da177e4SLinus Torvalds 		return -ENOMEM;
2292de1741a1SAlexander Kuleshov 	if (offset_in_page(addr))
22931da177e4SLinus Torvalds 		return -EINVAL;
229406abdfb4SBenjamin Herrenschmidt 
22959ac4ed4bSAl Viro 	error = security_mmap_addr(addr);
22969ac4ed4bSAl Viro 	return error ? error : addr;
22971da177e4SLinus Torvalds }
22981da177e4SLinus Torvalds 
22991da177e4SLinus Torvalds EXPORT_SYMBOL(get_unmapped_area);
23001da177e4SLinus Torvalds 
23011da177e4SLinus Torvalds /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
23021da177e4SLinus Torvalds struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
23031da177e4SLinus Torvalds {
2304615d6e87SDavidlohr Bueso 	struct rb_node *rb_node;
2305615d6e87SDavidlohr Bueso 	struct vm_area_struct *vma;
23061da177e4SLinus Torvalds 
23075b78ed24SLuigi Rizzo 	mmap_assert_locked(mm);
23081da177e4SLinus Torvalds 	/* Check the cache first. */
2309615d6e87SDavidlohr Bueso 	vma = vmacache_find(mm, addr);
2310615d6e87SDavidlohr Bueso 	if (likely(vma))
2311615d6e87SDavidlohr Bueso 		return vma;
23121da177e4SLinus Torvalds 
23131da177e4SLinus Torvalds 	rb_node = mm->mm_rb.rb_node;
23141da177e4SLinus Torvalds 
23151da177e4SLinus Torvalds 	while (rb_node) {
2316615d6e87SDavidlohr Bueso 		struct vm_area_struct *tmp;
23171da177e4SLinus Torvalds 
2318615d6e87SDavidlohr Bueso 		tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
23191da177e4SLinus Torvalds 
2320615d6e87SDavidlohr Bueso 		if (tmp->vm_end > addr) {
2321615d6e87SDavidlohr Bueso 			vma = tmp;
2322615d6e87SDavidlohr Bueso 			if (tmp->vm_start <= addr)
23231da177e4SLinus Torvalds 				break;
23241da177e4SLinus Torvalds 			rb_node = rb_node->rb_left;
23251da177e4SLinus Torvalds 		} else
23261da177e4SLinus Torvalds 			rb_node = rb_node->rb_right;
23271da177e4SLinus Torvalds 	}
2328615d6e87SDavidlohr Bueso 
23291da177e4SLinus Torvalds 	if (vma)
2330615d6e87SDavidlohr Bueso 		vmacache_update(addr, vma);
23311da177e4SLinus Torvalds 	return vma;
23321da177e4SLinus Torvalds }
23331da177e4SLinus Torvalds 
23341da177e4SLinus Torvalds EXPORT_SYMBOL(find_vma);
23351da177e4SLinus Torvalds 
23366bd4837dSKOSAKI Motohiro /*
23376bd4837dSKOSAKI Motohiro  * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
23386bd4837dSKOSAKI Motohiro  */
23391da177e4SLinus Torvalds struct vm_area_struct *
23401da177e4SLinus Torvalds find_vma_prev(struct mm_struct *mm, unsigned long addr,
23411da177e4SLinus Torvalds 			struct vm_area_struct **pprev)
23421da177e4SLinus Torvalds {
23436bd4837dSKOSAKI Motohiro 	struct vm_area_struct *vma;
23441da177e4SLinus Torvalds 
23456bd4837dSKOSAKI Motohiro 	vma = find_vma(mm, addr);
234683cd904dSMikulas Patocka 	if (vma) {
234783cd904dSMikulas Patocka 		*pprev = vma->vm_prev;
234883cd904dSMikulas Patocka 	} else {
234973848a97SWei Yang 		struct rb_node *rb_node = rb_last(&mm->mm_rb);
235073848a97SWei Yang 
235173848a97SWei Yang 		*pprev = rb_node ? rb_entry(rb_node, struct vm_area_struct, vm_rb) : NULL;
235283cd904dSMikulas Patocka 	}
23536bd4837dSKOSAKI Motohiro 	return vma;
23541da177e4SLinus Torvalds }
23551da177e4SLinus Torvalds 
23561da177e4SLinus Torvalds /*
23571da177e4SLinus Torvalds  * Verify that the stack growth is acceptable and
23581da177e4SLinus Torvalds  * update accounting. This is shared with both the
23591da177e4SLinus Torvalds  * grow-up and grow-down cases.
23601da177e4SLinus Torvalds  */
23611be7107fSHugh Dickins static int acct_stack_growth(struct vm_area_struct *vma,
23621be7107fSHugh Dickins 			     unsigned long size, unsigned long grow)
23631da177e4SLinus Torvalds {
23641da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
23651be7107fSHugh Dickins 	unsigned long new_start;
23661da177e4SLinus Torvalds 
23671da177e4SLinus Torvalds 	/* address space limit tests */
236884638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, vma->vm_flags, grow))
23691da177e4SLinus Torvalds 		return -ENOMEM;
23701da177e4SLinus Torvalds 
23711da177e4SLinus Torvalds 	/* Stack limit test */
237224c79d8eSKrzysztof Opasiak 	if (size > rlimit(RLIMIT_STACK))
23731da177e4SLinus Torvalds 		return -ENOMEM;
23741da177e4SLinus Torvalds 
23751da177e4SLinus Torvalds 	/* mlock limit tests */
23761da177e4SLinus Torvalds 	if (vma->vm_flags & VM_LOCKED) {
23771da177e4SLinus Torvalds 		unsigned long locked;
23781da177e4SLinus Torvalds 		unsigned long limit;
23791da177e4SLinus Torvalds 		locked = mm->locked_vm + grow;
238024c79d8eSKrzysztof Opasiak 		limit = rlimit(RLIMIT_MEMLOCK);
238159e99e5bSJiri Slaby 		limit >>= PAGE_SHIFT;
23821da177e4SLinus Torvalds 		if (locked > limit && !capable(CAP_IPC_LOCK))
23831da177e4SLinus Torvalds 			return -ENOMEM;
23841da177e4SLinus Torvalds 	}
23851da177e4SLinus Torvalds 
23860d59a01bSAdam Litke 	/* Check to ensure the stack will not grow into a hugetlb-only region */
23870d59a01bSAdam Litke 	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
23880d59a01bSAdam Litke 			vma->vm_end - size;
23890d59a01bSAdam Litke 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
23900d59a01bSAdam Litke 		return -EFAULT;
23910d59a01bSAdam Litke 
23921da177e4SLinus Torvalds 	/*
23931da177e4SLinus Torvalds 	 * Overcommit..  This must be the final test, as it will
23941da177e4SLinus Torvalds 	 * update security statistics.
23951da177e4SLinus Torvalds 	 */
239605fa199dSHugh Dickins 	if (security_vm_enough_memory_mm(mm, grow))
23971da177e4SLinus Torvalds 		return -ENOMEM;
23981da177e4SLinus Torvalds 
23991da177e4SLinus Torvalds 	return 0;
24001da177e4SLinus Torvalds }
24011da177e4SLinus Torvalds 
240246dea3d0SHugh Dickins #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
24031da177e4SLinus Torvalds /*
240446dea3d0SHugh Dickins  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
240546dea3d0SHugh Dickins  * vma is the last one with address > vma->vm_end.  Have to extend vma.
24061da177e4SLinus Torvalds  */
240746dea3d0SHugh Dickins int expand_upwards(struct vm_area_struct *vma, unsigned long address)
24081da177e4SLinus Torvalds {
240909357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
24101be7107fSHugh Dickins 	struct vm_area_struct *next;
24111be7107fSHugh Dickins 	unsigned long gap_addr;
241212352d3cSKonstantin Khlebnikov 	int error = 0;
24131da177e4SLinus Torvalds 
24141da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSUP))
24151da177e4SLinus Torvalds 		return -EFAULT;
24161da177e4SLinus Torvalds 
2417bd726c90SHelge Deller 	/* Guard against exceeding limits of the address space. */
24181be7107fSHugh Dickins 	address &= PAGE_MASK;
241937511fb5SHelge Deller 	if (address >= (TASK_SIZE & PAGE_MASK))
242012352d3cSKonstantin Khlebnikov 		return -ENOMEM;
2421bd726c90SHelge Deller 	address += PAGE_SIZE;
242212352d3cSKonstantin Khlebnikov 
24231be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
24241be7107fSHugh Dickins 	gap_addr = address + stack_guard_gap;
2425bd726c90SHelge Deller 
2426bd726c90SHelge Deller 	/* Guard against overflow */
2427bd726c90SHelge Deller 	if (gap_addr < address || gap_addr > TASK_SIZE)
2428bd726c90SHelge Deller 		gap_addr = TASK_SIZE;
2429bd726c90SHelge Deller 
24301be7107fSHugh Dickins 	next = vma->vm_next;
24313122e80eSAnshuman Khandual 	if (next && next->vm_start < gap_addr && vma_is_accessible(next)) {
24321be7107fSHugh Dickins 		if (!(next->vm_flags & VM_GROWSUP))
24331be7107fSHugh Dickins 			return -ENOMEM;
24341be7107fSHugh Dickins 		/* Check that both stack segments have the same anon_vma? */
24351be7107fSHugh Dickins 	}
24361be7107fSHugh Dickins 
243712352d3cSKonstantin Khlebnikov 	/* We must make sure the anon_vma is allocated. */
24381da177e4SLinus Torvalds 	if (unlikely(anon_vma_prepare(vma)))
24391da177e4SLinus Torvalds 		return -ENOMEM;
24401da177e4SLinus Torvalds 
24411da177e4SLinus Torvalds 	/*
24421da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2443c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
24441da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
24451da177e4SLinus Torvalds 	 */
244612352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
24471da177e4SLinus Torvalds 
24481da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
24491da177e4SLinus Torvalds 	if (address > vma->vm_end) {
24501da177e4SLinus Torvalds 		unsigned long size, grow;
24511da177e4SLinus Torvalds 
24521da177e4SLinus Torvalds 		size = address - vma->vm_start;
24531da177e4SLinus Torvalds 		grow = (address - vma->vm_end) >> PAGE_SHIFT;
24541da177e4SLinus Torvalds 
245542c36f63SHugh Dickins 		error = -ENOMEM;
245642c36f63SHugh Dickins 		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
24571da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
24583af9e859SEric B Munson 			if (!error) {
24594128997bSMichel Lespinasse 				/*
24604128997bSMichel Lespinasse 				 * vma_gap_update() doesn't support concurrent
2461c1e8d7c6SMichel Lespinasse 				 * updates, but we only hold a shared mmap_lock
24624128997bSMichel Lespinasse 				 * lock here, so we need to protect against
24634128997bSMichel Lespinasse 				 * concurrent vma expansions.
246412352d3cSKonstantin Khlebnikov 				 * anon_vma_lock_write() doesn't help here, as
24654128997bSMichel Lespinasse 				 * we don't guarantee that all growable vmas
24664128997bSMichel Lespinasse 				 * in a mm share the same root anon vma.
24674128997bSMichel Lespinasse 				 * So, we reuse mm->page_table_lock to guard
24684128997bSMichel Lespinasse 				 * against concurrent vma expansions.
24694128997bSMichel Lespinasse 				 */
247009357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
247187e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
247209357814SOleg Nesterov 					mm->locked_vm += grow;
247384638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2474bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
24751da177e4SLinus Torvalds 				vma->vm_end = address;
2476bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
2477d3737187SMichel Lespinasse 				if (vma->vm_next)
2478d3737187SMichel Lespinasse 					vma_gap_update(vma->vm_next);
2479d3737187SMichel Lespinasse 				else
24801be7107fSHugh Dickins 					mm->highest_vm_end = vm_end_gap(vma);
248109357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
24824128997bSMichel Lespinasse 
24833af9e859SEric B Munson 				perf_event_mmap(vma);
24843af9e859SEric B Munson 			}
24851da177e4SLinus Torvalds 		}
248642c36f63SHugh Dickins 	}
248712352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
24886d50e60cSDavid Rientjes 	khugepaged_enter_vma_merge(vma, vma->vm_flags);
248909357814SOleg Nesterov 	validate_mm(mm);
24901da177e4SLinus Torvalds 	return error;
24911da177e4SLinus Torvalds }
249246dea3d0SHugh Dickins #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
249346dea3d0SHugh Dickins 
24941da177e4SLinus Torvalds /*
24951da177e4SLinus Torvalds  * vma is the first one with address < vma->vm_start.  Have to extend vma.
24961da177e4SLinus Torvalds  */
2497d05f3169SMichal Hocko int expand_downwards(struct vm_area_struct *vma,
2498b6a2fea3SOllie Wild 				   unsigned long address)
24991da177e4SLinus Torvalds {
250009357814SOleg Nesterov 	struct mm_struct *mm = vma->vm_mm;
25011be7107fSHugh Dickins 	struct vm_area_struct *prev;
25020a1d5299SJann Horn 	int error = 0;
25031da177e4SLinus Torvalds 
25048869477aSEric Paris 	address &= PAGE_MASK;
25050a1d5299SJann Horn 	if (address < mmap_min_addr)
25060a1d5299SJann Horn 		return -EPERM;
25078869477aSEric Paris 
25081be7107fSHugh Dickins 	/* Enforce stack_guard_gap */
25091be7107fSHugh Dickins 	prev = vma->vm_prev;
25101be7107fSHugh Dickins 	/* Check that both stack segments have the same anon_vma? */
251132e4e6d5SOleg Nesterov 	if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
25123122e80eSAnshuman Khandual 			vma_is_accessible(prev)) {
251332e4e6d5SOleg Nesterov 		if (address - prev->vm_end < stack_guard_gap)
251432e4e6d5SOleg Nesterov 			return -ENOMEM;
25151be7107fSHugh Dickins 	}
25161be7107fSHugh Dickins 
251712352d3cSKonstantin Khlebnikov 	/* We must make sure the anon_vma is allocated. */
251812352d3cSKonstantin Khlebnikov 	if (unlikely(anon_vma_prepare(vma)))
251912352d3cSKonstantin Khlebnikov 		return -ENOMEM;
25201da177e4SLinus Torvalds 
25211da177e4SLinus Torvalds 	/*
25221da177e4SLinus Torvalds 	 * vma->vm_start/vm_end cannot change under us because the caller
2523c1e8d7c6SMichel Lespinasse 	 * is required to hold the mmap_lock in read mode.  We need the
25241da177e4SLinus Torvalds 	 * anon_vma lock to serialize against concurrent expand_stacks.
25251da177e4SLinus Torvalds 	 */
252612352d3cSKonstantin Khlebnikov 	anon_vma_lock_write(vma->anon_vma);
25271da177e4SLinus Torvalds 
25281da177e4SLinus Torvalds 	/* Somebody else might have raced and expanded it already */
25291da177e4SLinus Torvalds 	if (address < vma->vm_start) {
25301da177e4SLinus Torvalds 		unsigned long size, grow;
25311da177e4SLinus Torvalds 
25321da177e4SLinus Torvalds 		size = vma->vm_end - address;
25331da177e4SLinus Torvalds 		grow = (vma->vm_start - address) >> PAGE_SHIFT;
25341da177e4SLinus Torvalds 
2535a626ca6aSLinus Torvalds 		error = -ENOMEM;
2536a626ca6aSLinus Torvalds 		if (grow <= vma->vm_pgoff) {
25371da177e4SLinus Torvalds 			error = acct_stack_growth(vma, size, grow);
25381da177e4SLinus Torvalds 			if (!error) {
25394128997bSMichel Lespinasse 				/*
25404128997bSMichel Lespinasse 				 * vma_gap_update() doesn't support concurrent
2541c1e8d7c6SMichel Lespinasse 				 * updates, but we only hold a shared mmap_lock
25424128997bSMichel Lespinasse 				 * lock here, so we need to protect against
25434128997bSMichel Lespinasse 				 * concurrent vma expansions.
254412352d3cSKonstantin Khlebnikov 				 * anon_vma_lock_write() doesn't help here, as
25454128997bSMichel Lespinasse 				 * we don't guarantee that all growable vmas
25464128997bSMichel Lespinasse 				 * in a mm share the same root anon vma.
25474128997bSMichel Lespinasse 				 * So, we reuse mm->page_table_lock to guard
25484128997bSMichel Lespinasse 				 * against concurrent vma expansions.
25494128997bSMichel Lespinasse 				 */
255009357814SOleg Nesterov 				spin_lock(&mm->page_table_lock);
255187e8827bSOleg Nesterov 				if (vma->vm_flags & VM_LOCKED)
255209357814SOleg Nesterov 					mm->locked_vm += grow;
255384638335SKonstantin Khlebnikov 				vm_stat_account(mm, vma->vm_flags, grow);
2554bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_pre_update_vma(vma);
25551da177e4SLinus Torvalds 				vma->vm_start = address;
25561da177e4SLinus Torvalds 				vma->vm_pgoff -= grow;
2557bf181b9fSMichel Lespinasse 				anon_vma_interval_tree_post_update_vma(vma);
2558d3737187SMichel Lespinasse 				vma_gap_update(vma);
255909357814SOleg Nesterov 				spin_unlock(&mm->page_table_lock);
25604128997bSMichel Lespinasse 
25613af9e859SEric B Munson 				perf_event_mmap(vma);
25621da177e4SLinus Torvalds 			}
25631da177e4SLinus Torvalds 		}
2564a626ca6aSLinus Torvalds 	}
256512352d3cSKonstantin Khlebnikov 	anon_vma_unlock_write(vma->anon_vma);
25666d50e60cSDavid Rientjes 	khugepaged_enter_vma_merge(vma, vma->vm_flags);
256709357814SOleg Nesterov 	validate_mm(mm);
25681da177e4SLinus Torvalds 	return error;
25691da177e4SLinus Torvalds }
25701da177e4SLinus Torvalds 
25711be7107fSHugh Dickins /* enforced gap between the expanding stack and other mappings. */
25721be7107fSHugh Dickins unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
25731be7107fSHugh Dickins 
25741be7107fSHugh Dickins static int __init cmdline_parse_stack_guard_gap(char *p)
25751be7107fSHugh Dickins {
25761be7107fSHugh Dickins 	unsigned long val;
25771be7107fSHugh Dickins 	char *endptr;
25781be7107fSHugh Dickins 
25791be7107fSHugh Dickins 	val = simple_strtoul(p, &endptr, 10);
25801be7107fSHugh Dickins 	if (!*endptr)
25811be7107fSHugh Dickins 		stack_guard_gap = val << PAGE_SHIFT;
25821be7107fSHugh Dickins 
25831be7107fSHugh Dickins 	return 0;
25841be7107fSHugh Dickins }
25851be7107fSHugh Dickins __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
25861be7107fSHugh Dickins 
2587b6a2fea3SOllie Wild #ifdef CONFIG_STACK_GROWSUP
2588b6a2fea3SOllie Wild int expand_stack(struct vm_area_struct *vma, unsigned long address)
2589b6a2fea3SOllie Wild {
2590b6a2fea3SOllie Wild 	return expand_upwards(vma, address);
2591b6a2fea3SOllie Wild }
2592b6a2fea3SOllie Wild 
2593b6a2fea3SOllie Wild struct vm_area_struct *
2594b6a2fea3SOllie Wild find_extend_vma(struct mm_struct *mm, unsigned long addr)
2595b6a2fea3SOllie Wild {
2596b6a2fea3SOllie Wild 	struct vm_area_struct *vma, *prev;
2597b6a2fea3SOllie Wild 
2598b6a2fea3SOllie Wild 	addr &= PAGE_MASK;
2599b6a2fea3SOllie Wild 	vma = find_vma_prev(mm, addr, &prev);
2600b6a2fea3SOllie Wild 	if (vma && (vma->vm_start <= addr))
2601b6a2fea3SOllie Wild 		return vma;
260204f5866eSAndrea Arcangeli 	/* don't alter vm_end if the coredump is running */
26034d45e75aSJann Horn 	if (!prev || expand_stack(prev, addr))
2604b6a2fea3SOllie Wild 		return NULL;
2605cea10a19SMichel Lespinasse 	if (prev->vm_flags & VM_LOCKED)
2606fc05f566SKirill A. Shutemov 		populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2607b6a2fea3SOllie Wild 	return prev;
2608b6a2fea3SOllie Wild }
2609b6a2fea3SOllie Wild #else
2610b6a2fea3SOllie Wild int expand_stack(struct vm_area_struct *vma, unsigned long address)
2611b6a2fea3SOllie Wild {
2612b6a2fea3SOllie Wild 	return expand_downwards(vma, address);
2613b6a2fea3SOllie Wild }
2614b6a2fea3SOllie Wild 
26151da177e4SLinus Torvalds struct vm_area_struct *
26161da177e4SLinus Torvalds find_extend_vma(struct mm_struct *mm, unsigned long addr)
26171da177e4SLinus Torvalds {
26181da177e4SLinus Torvalds 	struct vm_area_struct *vma;
26191da177e4SLinus Torvalds 	unsigned long start;
26201da177e4SLinus Torvalds 
26211da177e4SLinus Torvalds 	addr &= PAGE_MASK;
26221da177e4SLinus Torvalds 	vma = find_vma(mm, addr);
26231da177e4SLinus Torvalds 	if (!vma)
26241da177e4SLinus Torvalds 		return NULL;
26251da177e4SLinus Torvalds 	if (vma->vm_start <= addr)
26261da177e4SLinus Torvalds 		return vma;
26271da177e4SLinus Torvalds 	if (!(vma->vm_flags & VM_GROWSDOWN))
26281da177e4SLinus Torvalds 		return NULL;
26291da177e4SLinus Torvalds 	start = vma->vm_start;
26301da177e4SLinus Torvalds 	if (expand_stack(vma, addr))
26311da177e4SLinus Torvalds 		return NULL;
2632cea10a19SMichel Lespinasse 	if (vma->vm_flags & VM_LOCKED)
2633fc05f566SKirill A. Shutemov 		populate_vma_page_range(vma, addr, start, NULL);
26341da177e4SLinus Torvalds 	return vma;
26351da177e4SLinus Torvalds }
26361da177e4SLinus Torvalds #endif
26371da177e4SLinus Torvalds 
2638e1d6d01aSJesse Barnes EXPORT_SYMBOL_GPL(find_extend_vma);
2639e1d6d01aSJesse Barnes 
26402c0b3814SHugh Dickins /*
26412c0b3814SHugh Dickins  * Ok - we have the memory areas we should free on the vma list,
26422c0b3814SHugh Dickins  * so release them, and do the vma updates.
26431da177e4SLinus Torvalds  *
26442c0b3814SHugh Dickins  * Called with the mm semaphore held.
26451da177e4SLinus Torvalds  */
26462c0b3814SHugh Dickins static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
26471da177e4SLinus Torvalds {
26484f74d2c8SLinus Torvalds 	unsigned long nr_accounted = 0;
26494f74d2c8SLinus Torvalds 
2650365e9c87SHugh Dickins 	/* Update high watermark before we lower total_vm */
2651365e9c87SHugh Dickins 	update_hiwater_vm(mm);
26522c0b3814SHugh Dickins 	do {
2653ab50b8edSHugh Dickins 		long nrpages = vma_pages(vma);
26541da177e4SLinus Torvalds 
26554f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
26564f74d2c8SLinus Torvalds 			nr_accounted += nrpages;
265784638335SKonstantin Khlebnikov 		vm_stat_account(mm, vma->vm_flags, -nrpages);
2658a8fb5618SHugh Dickins 		vma = remove_vma(vma);
2659146425a3SHugh Dickins 	} while (vma);
26604f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
26611da177e4SLinus Torvalds 	validate_mm(mm);
26621da177e4SLinus Torvalds }
26631da177e4SLinus Torvalds 
26641da177e4SLinus Torvalds /*
26651da177e4SLinus Torvalds  * Get rid of page table information in the indicated region.
26661da177e4SLinus Torvalds  *
2667f10df686SPaolo 'Blaisorblade' Giarrusso  * Called with the mm semaphore held.
26681da177e4SLinus Torvalds  */
26691da177e4SLinus Torvalds static void unmap_region(struct mm_struct *mm,
2670e0da382cSHugh Dickins 		struct vm_area_struct *vma, struct vm_area_struct *prev,
2671e0da382cSHugh Dickins 		unsigned long start, unsigned long end)
26721da177e4SLinus Torvalds {
26733903b55aSLiam R. Howlett 	struct vm_area_struct *next = vma_next(mm, prev);
2674d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
26751da177e4SLinus Torvalds 
26761da177e4SLinus Torvalds 	lru_add_drain();
2677a72afd87SWill Deacon 	tlb_gather_mmu(&tlb, mm);
2678365e9c87SHugh Dickins 	update_hiwater_rss(mm);
26794f74d2c8SLinus Torvalds 	unmap_vmas(&tlb, vma, start, end);
2680d16dfc55SPeter Zijlstra 	free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
26816ee8630eSHugh Dickins 				 next ? next->vm_start : USER_PGTABLES_CEILING);
2682ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
26831da177e4SLinus Torvalds }
26841da177e4SLinus Torvalds 
26851da177e4SLinus Torvalds /*
26861da177e4SLinus Torvalds  * Create a list of vma's touched by the unmap, removing them from the mm's
26871da177e4SLinus Torvalds  * vma list as we go..
26881da177e4SLinus Torvalds  */
2689246c320aSKirill A. Shutemov static bool
26901da177e4SLinus Torvalds detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
26911da177e4SLinus Torvalds 	struct vm_area_struct *prev, unsigned long end)
26921da177e4SLinus Torvalds {
26931da177e4SLinus Torvalds 	struct vm_area_struct **insertion_point;
26941da177e4SLinus Torvalds 	struct vm_area_struct *tail_vma = NULL;
26951da177e4SLinus Torvalds 
26961da177e4SLinus Torvalds 	insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2697297c5eeeSLinus Torvalds 	vma->vm_prev = NULL;
26981da177e4SLinus Torvalds 	do {
2699d3737187SMichel Lespinasse 		vma_rb_erase(vma, &mm->mm_rb);
27001da177e4SLinus Torvalds 		mm->map_count--;
27011da177e4SLinus Torvalds 		tail_vma = vma;
27021da177e4SLinus Torvalds 		vma = vma->vm_next;
27031da177e4SLinus Torvalds 	} while (vma && vma->vm_start < end);
27041da177e4SLinus Torvalds 	*insertion_point = vma;
2705d3737187SMichel Lespinasse 	if (vma) {
2706297c5eeeSLinus Torvalds 		vma->vm_prev = prev;
2707d3737187SMichel Lespinasse 		vma_gap_update(vma);
2708d3737187SMichel Lespinasse 	} else
27091be7107fSHugh Dickins 		mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
27101da177e4SLinus Torvalds 	tail_vma->vm_next = NULL;
2711615d6e87SDavidlohr Bueso 
2712615d6e87SDavidlohr Bueso 	/* Kill the cache */
2713615d6e87SDavidlohr Bueso 	vmacache_invalidate(mm);
2714246c320aSKirill A. Shutemov 
2715246c320aSKirill A. Shutemov 	/*
2716246c320aSKirill A. Shutemov 	 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2717246c320aSKirill A. Shutemov 	 * VM_GROWSUP VMA. Such VMAs can change their size under
2718246c320aSKirill A. Shutemov 	 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2719246c320aSKirill A. Shutemov 	 */
2720246c320aSKirill A. Shutemov 	if (vma && (vma->vm_flags & VM_GROWSDOWN))
2721246c320aSKirill A. Shutemov 		return false;
2722246c320aSKirill A. Shutemov 	if (prev && (prev->vm_flags & VM_GROWSUP))
2723246c320aSKirill A. Shutemov 		return false;
2724246c320aSKirill A. Shutemov 	return true;
27251da177e4SLinus Torvalds }
27261da177e4SLinus Torvalds 
27271da177e4SLinus Torvalds /*
2728def5efe0SDavid Rientjes  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2729def5efe0SDavid Rientjes  * has already been checked or doesn't make sense to fail.
27301da177e4SLinus Torvalds  */
2731def5efe0SDavid Rientjes int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
27321da177e4SLinus Torvalds 		unsigned long addr, int new_below)
27331da177e4SLinus Torvalds {
27341da177e4SLinus Torvalds 	struct vm_area_struct *new;
2735e3975891SChen Gang 	int err;
27361da177e4SLinus Torvalds 
2737dd3b614fSDmitry Safonov 	if (vma->vm_ops && vma->vm_ops->may_split) {
2738dd3b614fSDmitry Safonov 		err = vma->vm_ops->may_split(vma, addr);
273931383c68SDan Williams 		if (err)
274031383c68SDan Williams 			return err;
274131383c68SDan Williams 	}
27421da177e4SLinus Torvalds 
27433928d4f5SLinus Torvalds 	new = vm_area_dup(vma);
27441da177e4SLinus Torvalds 	if (!new)
2745e3975891SChen Gang 		return -ENOMEM;
27461da177e4SLinus Torvalds 
27471da177e4SLinus Torvalds 	if (new_below)
27481da177e4SLinus Torvalds 		new->vm_end = addr;
27491da177e4SLinus Torvalds 	else {
27501da177e4SLinus Torvalds 		new->vm_start = addr;
27511da177e4SLinus Torvalds 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
27521da177e4SLinus Torvalds 	}
27531da177e4SLinus Torvalds 
2754ef0855d3SOleg Nesterov 	err = vma_dup_policy(vma, new);
2755ef0855d3SOleg Nesterov 	if (err)
27565beb4930SRik van Riel 		goto out_free_vma;
27571da177e4SLinus Torvalds 
2758c4ea95d7SDaniel Forrest 	err = anon_vma_clone(new, vma);
2759c4ea95d7SDaniel Forrest 	if (err)
27605beb4930SRik van Riel 		goto out_free_mpol;
27615beb4930SRik van Riel 
2762e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
27631da177e4SLinus Torvalds 		get_file(new->vm_file);
27641da177e4SLinus Torvalds 
27651da177e4SLinus Torvalds 	if (new->vm_ops && new->vm_ops->open)
27661da177e4SLinus Torvalds 		new->vm_ops->open(new);
27671da177e4SLinus Torvalds 
27681da177e4SLinus Torvalds 	if (new_below)
27695beb4930SRik van Riel 		err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
27701da177e4SLinus Torvalds 			((addr - new->vm_start) >> PAGE_SHIFT), new);
27711da177e4SLinus Torvalds 	else
27725beb4930SRik van Riel 		err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
27731da177e4SLinus Torvalds 
27745beb4930SRik van Riel 	/* Success. */
27755beb4930SRik van Riel 	if (!err)
27761da177e4SLinus Torvalds 		return 0;
27775beb4930SRik van Riel 
27785beb4930SRik van Riel 	/* Clean everything up if vma_adjust failed. */
277958927533SRik van Riel 	if (new->vm_ops && new->vm_ops->close)
27805beb4930SRik van Riel 		new->vm_ops->close(new);
2781e9714acfSKonstantin Khlebnikov 	if (new->vm_file)
27825beb4930SRik van Riel 		fput(new->vm_file);
27832aeadc30SAndrea Arcangeli 	unlink_anon_vmas(new);
27845beb4930SRik van Riel  out_free_mpol:
2785ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new));
27865beb4930SRik van Riel  out_free_vma:
27873928d4f5SLinus Torvalds 	vm_area_free(new);
27885beb4930SRik van Riel 	return err;
27891da177e4SLinus Torvalds }
27901da177e4SLinus Torvalds 
2791659ace58SKOSAKI Motohiro /*
2792659ace58SKOSAKI Motohiro  * Split a vma into two pieces at address 'addr', a new vma is allocated
2793659ace58SKOSAKI Motohiro  * either for the first part or the tail.
2794659ace58SKOSAKI Motohiro  */
2795659ace58SKOSAKI Motohiro int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2796659ace58SKOSAKI Motohiro 	      unsigned long addr, int new_below)
2797659ace58SKOSAKI Motohiro {
2798659ace58SKOSAKI Motohiro 	if (mm->map_count >= sysctl_max_map_count)
2799659ace58SKOSAKI Motohiro 		return -ENOMEM;
2800659ace58SKOSAKI Motohiro 
2801659ace58SKOSAKI Motohiro 	return __split_vma(mm, vma, addr, new_below);
2802659ace58SKOSAKI Motohiro }
2803659ace58SKOSAKI Motohiro 
280496d99023SLiam Howlett static inline void
280596d99023SLiam Howlett unlock_range(struct vm_area_struct *start, unsigned long limit)
280696d99023SLiam Howlett {
280796d99023SLiam Howlett 	struct mm_struct *mm = start->vm_mm;
280896d99023SLiam Howlett 	struct vm_area_struct *tmp = start;
280996d99023SLiam Howlett 
281096d99023SLiam Howlett 	while (tmp && tmp->vm_start < limit) {
281196d99023SLiam Howlett 		if (tmp->vm_flags & VM_LOCKED) {
281296d99023SLiam Howlett 			mm->locked_vm -= vma_pages(tmp);
281396d99023SLiam Howlett 			munlock_vma_pages_all(tmp);
281496d99023SLiam Howlett 		}
281596d99023SLiam Howlett 
281696d99023SLiam Howlett 		tmp = tmp->vm_next;
281796d99023SLiam Howlett 	}
281896d99023SLiam Howlett }
281996d99023SLiam Howlett 
28201da177e4SLinus Torvalds /* Munmap is split into 2 main parts -- this part which finds
28211da177e4SLinus Torvalds  * what needs doing, and the areas themselves, which do the
28221da177e4SLinus Torvalds  * work.  This now handles partial unmappings.
28231da177e4SLinus Torvalds  * Jeremy Fitzhardinge <jeremy@goop.org>
28241da177e4SLinus Torvalds  */
282585a06835SYang Shi int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2826dd2283f2SYang Shi 		struct list_head *uf, bool downgrade)
28271da177e4SLinus Torvalds {
28281da177e4SLinus Torvalds 	unsigned long end;
2829146425a3SHugh Dickins 	struct vm_area_struct *vma, *prev, *last;
28301da177e4SLinus Torvalds 
2831de1741a1SAlexander Kuleshov 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
28321da177e4SLinus Torvalds 		return -EINVAL;
28331da177e4SLinus Torvalds 
2834cc71aba3Svishnu.ps 	len = PAGE_ALIGN(len);
28355a28fc94SDave Hansen 	end = start + len;
2836cc71aba3Svishnu.ps 	if (len == 0)
28371da177e4SLinus Torvalds 		return -EINVAL;
28381da177e4SLinus Torvalds 
28395a28fc94SDave Hansen 	/*
28405a28fc94SDave Hansen 	 * arch_unmap() might do unmaps itself.  It must be called
28415a28fc94SDave Hansen 	 * and finish any rbtree manipulation before this code
28425a28fc94SDave Hansen 	 * runs and also starts to manipulate the rbtree.
28435a28fc94SDave Hansen 	 */
28445a28fc94SDave Hansen 	arch_unmap(mm, start, end);
28455a28fc94SDave Hansen 
284678d9cf60SGonzalo Matias Juarez Tello 	/* Find the first overlapping VMA where start < vma->vm_end */
284778d9cf60SGonzalo Matias Juarez Tello 	vma = find_vma_intersection(mm, start, end);
2848146425a3SHugh Dickins 	if (!vma)
28491da177e4SLinus Torvalds 		return 0;
28509be34c9dSLinus Torvalds 	prev = vma->vm_prev;
28511da177e4SLinus Torvalds 
28521da177e4SLinus Torvalds 	/*
28531da177e4SLinus Torvalds 	 * If we need to split any vma, do it now to save pain later.
28541da177e4SLinus Torvalds 	 *
28551da177e4SLinus Torvalds 	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
28561da177e4SLinus Torvalds 	 * unmapped vm_area_struct will remain in use: so lower split_vma
28571da177e4SLinus Torvalds 	 * places tmp vma above, and higher split_vma places tmp vma below.
28581da177e4SLinus Torvalds 	 */
2859146425a3SHugh Dickins 	if (start > vma->vm_start) {
2860659ace58SKOSAKI Motohiro 		int error;
2861659ace58SKOSAKI Motohiro 
2862659ace58SKOSAKI Motohiro 		/*
2863659ace58SKOSAKI Motohiro 		 * Make sure that map_count on return from munmap() will
2864659ace58SKOSAKI Motohiro 		 * not exceed its limit; but let map_count go just above
2865659ace58SKOSAKI Motohiro 		 * its limit temporarily, to help free resources as expected.
2866659ace58SKOSAKI Motohiro 		 */
2867659ace58SKOSAKI Motohiro 		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2868659ace58SKOSAKI Motohiro 			return -ENOMEM;
2869659ace58SKOSAKI Motohiro 
2870659ace58SKOSAKI Motohiro 		error = __split_vma(mm, vma, start, 0);
28711da177e4SLinus Torvalds 		if (error)
28721da177e4SLinus Torvalds 			return error;
2873146425a3SHugh Dickins 		prev = vma;
28741da177e4SLinus Torvalds 	}
28751da177e4SLinus Torvalds 
28761da177e4SLinus Torvalds 	/* Does it split the last one? */
28771da177e4SLinus Torvalds 	last = find_vma(mm, end);
28781da177e4SLinus Torvalds 	if (last && end > last->vm_start) {
2879659ace58SKOSAKI Motohiro 		int error = __split_vma(mm, last, end, 1);
28801da177e4SLinus Torvalds 		if (error)
28811da177e4SLinus Torvalds 			return error;
28821da177e4SLinus Torvalds 	}
28833903b55aSLiam R. Howlett 	vma = vma_next(mm, prev);
28841da177e4SLinus Torvalds 
28852376dd7cSAndrea Arcangeli 	if (unlikely(uf)) {
28862376dd7cSAndrea Arcangeli 		/*
28872376dd7cSAndrea Arcangeli 		 * If userfaultfd_unmap_prep returns an error the vmas
2888f0953a1bSIngo Molnar 		 * will remain split, but userland will get a
28892376dd7cSAndrea Arcangeli 		 * highly unexpected error anyway. This is no
28902376dd7cSAndrea Arcangeli 		 * different than the case where the first of the two
28912376dd7cSAndrea Arcangeli 		 * __split_vma fails, but we don't undo the first
28922376dd7cSAndrea Arcangeli 		 * split, despite we could. This is unlikely enough
28932376dd7cSAndrea Arcangeli 		 * failure that it's not worth optimizing it for.
28942376dd7cSAndrea Arcangeli 		 */
28952376dd7cSAndrea Arcangeli 		int error = userfaultfd_unmap_prep(vma, start, end, uf);
28962376dd7cSAndrea Arcangeli 		if (error)
28972376dd7cSAndrea Arcangeli 			return error;
28982376dd7cSAndrea Arcangeli 	}
28992376dd7cSAndrea Arcangeli 
29001da177e4SLinus Torvalds 	/*
2901ba470de4SRik van Riel 	 * unlock any mlock()ed ranges before detaching vmas
2902ba470de4SRik van Riel 	 */
290396d99023SLiam Howlett 	if (mm->locked_vm)
290496d99023SLiam Howlett 		unlock_range(vma, end);
2905ba470de4SRik van Riel 
2906dd2283f2SYang Shi 	/* Detach vmas from rbtree */
2907246c320aSKirill A. Shutemov 	if (!detach_vmas_to_be_unmapped(mm, vma, prev, end))
2908246c320aSKirill A. Shutemov 		downgrade = false;
29091da177e4SLinus Torvalds 
2910dd2283f2SYang Shi 	if (downgrade)
2911d8ed45c5SMichel Lespinasse 		mmap_write_downgrade(mm);
2912dd2283f2SYang Shi 
2913dd2283f2SYang Shi 	unmap_region(mm, vma, prev, start, end);
2914dd2283f2SYang Shi 
29151da177e4SLinus Torvalds 	/* Fix up all other VM information */
29162c0b3814SHugh Dickins 	remove_vma_list(mm, vma);
29171da177e4SLinus Torvalds 
2918dd2283f2SYang Shi 	return downgrade ? 1 : 0;
29191da177e4SLinus Torvalds }
29201da177e4SLinus Torvalds 
2921dd2283f2SYang Shi int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2922dd2283f2SYang Shi 	      struct list_head *uf)
2923dd2283f2SYang Shi {
2924dd2283f2SYang Shi 	return __do_munmap(mm, start, len, uf, false);
2925dd2283f2SYang Shi }
2926dd2283f2SYang Shi 
2927dd2283f2SYang Shi static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2928a46ef99dSLinus Torvalds {
2929a46ef99dSLinus Torvalds 	int ret;
2930bfce281cSAl Viro 	struct mm_struct *mm = current->mm;
2931897ab3e0SMike Rapoport 	LIST_HEAD(uf);
2932a46ef99dSLinus Torvalds 
2933d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2934ae798783SMichal Hocko 		return -EINTR;
2935ae798783SMichal Hocko 
2936dd2283f2SYang Shi 	ret = __do_munmap(mm, start, len, &uf, downgrade);
2937dd2283f2SYang Shi 	/*
2938c1e8d7c6SMichel Lespinasse 	 * Returning 1 indicates mmap_lock is downgraded.
2939dd2283f2SYang Shi 	 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2940dd2283f2SYang Shi 	 * it to 0 before return.
2941dd2283f2SYang Shi 	 */
2942dd2283f2SYang Shi 	if (ret == 1) {
2943d8ed45c5SMichel Lespinasse 		mmap_read_unlock(mm);
2944dd2283f2SYang Shi 		ret = 0;
2945dd2283f2SYang Shi 	} else
2946d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
2947dd2283f2SYang Shi 
2948897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
2949a46ef99dSLinus Torvalds 	return ret;
2950a46ef99dSLinus Torvalds }
2951dd2283f2SYang Shi 
2952dd2283f2SYang Shi int vm_munmap(unsigned long start, size_t len)
2953dd2283f2SYang Shi {
2954dd2283f2SYang Shi 	return __vm_munmap(start, len, false);
2955dd2283f2SYang Shi }
2956a46ef99dSLinus Torvalds EXPORT_SYMBOL(vm_munmap);
2957a46ef99dSLinus Torvalds 
29586a6160a7SHeiko Carstens SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
29591da177e4SLinus Torvalds {
2960ce18d171SCatalin Marinas 	addr = untagged_addr(addr);
29611da177e4SLinus Torvalds 	profile_munmap(addr);
2962dd2283f2SYang Shi 	return __vm_munmap(addr, len, true);
29631da177e4SLinus Torvalds }
29641da177e4SLinus Torvalds 
2965c8d78c18SKirill A. Shutemov 
2966c8d78c18SKirill A. Shutemov /*
2967c8d78c18SKirill A. Shutemov  * Emulation of deprecated remap_file_pages() syscall.
2968c8d78c18SKirill A. Shutemov  */
2969c8d78c18SKirill A. Shutemov SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2970c8d78c18SKirill A. Shutemov 		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2971c8d78c18SKirill A. Shutemov {
2972c8d78c18SKirill A. Shutemov 
2973c8d78c18SKirill A. Shutemov 	struct mm_struct *mm = current->mm;
2974c8d78c18SKirill A. Shutemov 	struct vm_area_struct *vma;
2975c8d78c18SKirill A. Shutemov 	unsigned long populate = 0;
2976c8d78c18SKirill A. Shutemov 	unsigned long ret = -EINVAL;
2977c8d78c18SKirill A. Shutemov 	struct file *file;
2978c8d78c18SKirill A. Shutemov 
2979ad56b738SMike Rapoport 	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/vm/remap_file_pages.rst.\n",
2980c8d78c18SKirill A. Shutemov 		     current->comm, current->pid);
2981c8d78c18SKirill A. Shutemov 
2982c8d78c18SKirill A. Shutemov 	if (prot)
2983c8d78c18SKirill A. Shutemov 		return ret;
2984c8d78c18SKirill A. Shutemov 	start = start & PAGE_MASK;
2985c8d78c18SKirill A. Shutemov 	size = size & PAGE_MASK;
2986c8d78c18SKirill A. Shutemov 
2987c8d78c18SKirill A. Shutemov 	if (start + size <= start)
2988c8d78c18SKirill A. Shutemov 		return ret;
2989c8d78c18SKirill A. Shutemov 
2990c8d78c18SKirill A. Shutemov 	/* Does pgoff wrap? */
2991c8d78c18SKirill A. Shutemov 	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2992c8d78c18SKirill A. Shutemov 		return ret;
2993c8d78c18SKirill A. Shutemov 
2994d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
2995dc0ef0dfSMichal Hocko 		return -EINTR;
2996dc0ef0dfSMichal Hocko 
2997*9b593cb2SLiam R. Howlett 	vma = vma_lookup(mm, start);
2998c8d78c18SKirill A. Shutemov 
2999c8d78c18SKirill A. Shutemov 	if (!vma || !(vma->vm_flags & VM_SHARED))
3000c8d78c18SKirill A. Shutemov 		goto out;
3001c8d78c18SKirill A. Shutemov 
300248f7df32SKirill A. Shutemov 	if (start + size > vma->vm_end) {
300348f7df32SKirill A. Shutemov 		struct vm_area_struct *next;
300448f7df32SKirill A. Shutemov 
300548f7df32SKirill A. Shutemov 		for (next = vma->vm_next; next; next = next->vm_next) {
300648f7df32SKirill A. Shutemov 			/* hole between vmas ? */
300748f7df32SKirill A. Shutemov 			if (next->vm_start != next->vm_prev->vm_end)
300848f7df32SKirill A. Shutemov 				goto out;
300948f7df32SKirill A. Shutemov 
301048f7df32SKirill A. Shutemov 			if (next->vm_file != vma->vm_file)
301148f7df32SKirill A. Shutemov 				goto out;
301248f7df32SKirill A. Shutemov 
301348f7df32SKirill A. Shutemov 			if (next->vm_flags != vma->vm_flags)
301448f7df32SKirill A. Shutemov 				goto out;
301548f7df32SKirill A. Shutemov 
301648f7df32SKirill A. Shutemov 			if (start + size <= next->vm_end)
301748f7df32SKirill A. Shutemov 				break;
301848f7df32SKirill A. Shutemov 		}
301948f7df32SKirill A. Shutemov 
302048f7df32SKirill A. Shutemov 		if (!next)
3021c8d78c18SKirill A. Shutemov 			goto out;
3022c8d78c18SKirill A. Shutemov 	}
3023c8d78c18SKirill A. Shutemov 
3024c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
3025c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
3026c8d78c18SKirill A. Shutemov 	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
3027c8d78c18SKirill A. Shutemov 
3028c8d78c18SKirill A. Shutemov 	flags &= MAP_NONBLOCK;
3029c8d78c18SKirill A. Shutemov 	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
3030fce000b1SLiam Howlett 	if (vma->vm_flags & VM_LOCKED)
3031c8d78c18SKirill A. Shutemov 		flags |= MAP_LOCKED;
303248f7df32SKirill A. Shutemov 
3033c8d78c18SKirill A. Shutemov 	file = get_file(vma->vm_file);
303445e55300SPeter Collingbourne 	ret = do_mmap(vma->vm_file, start, size,
3035897ab3e0SMike Rapoport 			prot, flags, pgoff, &populate, NULL);
3036c8d78c18SKirill A. Shutemov 	fput(file);
3037c8d78c18SKirill A. Shutemov out:
3038d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
3039c8d78c18SKirill A. Shutemov 	if (populate)
3040c8d78c18SKirill A. Shutemov 		mm_populate(ret, populate);
3041c8d78c18SKirill A. Shutemov 	if (!IS_ERR_VALUE(ret))
3042c8d78c18SKirill A. Shutemov 		ret = 0;
3043c8d78c18SKirill A. Shutemov 	return ret;
3044c8d78c18SKirill A. Shutemov }
3045c8d78c18SKirill A. Shutemov 
30461da177e4SLinus Torvalds /*
30471da177e4SLinus Torvalds  *  this is really a simplified "do_mmap".  it only handles
30481da177e4SLinus Torvalds  *  anonymous maps.  eventually we may be able to do some
30491da177e4SLinus Torvalds  *  brk-specific accounting here.
30501da177e4SLinus Torvalds  */
3051bb177a73SMichal Hocko static int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)
30521da177e4SLinus Torvalds {
30531da177e4SLinus Torvalds 	struct mm_struct *mm = current->mm;
30541da177e4SLinus Torvalds 	struct vm_area_struct *vma, *prev;
30551da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
30561da177e4SLinus Torvalds 	pgoff_t pgoff = addr >> PAGE_SHIFT;
30573a459756SKirill Korotaev 	int error;
3058ff68dac6SGaowei Pu 	unsigned long mapped_addr;
30591da177e4SLinus Torvalds 
306016e72e9bSDenys Vlasenko 	/* Until we need other flags, refuse anything except VM_EXEC. */
306116e72e9bSDenys Vlasenko 	if ((flags & (~VM_EXEC)) != 0)
306216e72e9bSDenys Vlasenko 		return -EINVAL;
306316e72e9bSDenys Vlasenko 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
30643a459756SKirill Korotaev 
3065ff68dac6SGaowei Pu 	mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
3066ff68dac6SGaowei Pu 	if (IS_ERR_VALUE(mapped_addr))
3067ff68dac6SGaowei Pu 		return mapped_addr;
30683a459756SKirill Korotaev 
3069363ee17fSDavidlohr Bueso 	error = mlock_future_check(mm, mm->def_flags, len);
3070363ee17fSDavidlohr Bueso 	if (error)
3071363ee17fSDavidlohr Bueso 		return error;
30721da177e4SLinus Torvalds 
3073fb8090b6SLiam R. Howlett 	/* Clear old maps, set up prev, rb_link, rb_parent, and uf */
3074fb8090b6SLiam R. Howlett 	if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
30751da177e4SLinus Torvalds 		return -ENOMEM;
30761da177e4SLinus Torvalds 
30771da177e4SLinus Torvalds 	/* Check against address space limits *after* clearing old maps... */
307884638335SKonstantin Khlebnikov 	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
30791da177e4SLinus Torvalds 		return -ENOMEM;
30801da177e4SLinus Torvalds 
30811da177e4SLinus Torvalds 	if (mm->map_count > sysctl_max_map_count)
30821da177e4SLinus Torvalds 		return -ENOMEM;
30831da177e4SLinus Torvalds 
3084191c5424SAl Viro 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
30851da177e4SLinus Torvalds 		return -ENOMEM;
30861da177e4SLinus Torvalds 
30871da177e4SLinus Torvalds 	/* Can we just expand an old private anonymous mapping? */
3088ba470de4SRik van Riel 	vma = vma_merge(mm, prev, addr, addr + len, flags,
308919a809afSAndrea Arcangeli 			NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX);
3090ba470de4SRik van Riel 	if (vma)
30911da177e4SLinus Torvalds 		goto out;
30921da177e4SLinus Torvalds 
30931da177e4SLinus Torvalds 	/*
30941da177e4SLinus Torvalds 	 * create a vma struct for an anonymous mapping
30951da177e4SLinus Torvalds 	 */
3096490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
30971da177e4SLinus Torvalds 	if (!vma) {
30981da177e4SLinus Torvalds 		vm_unacct_memory(len >> PAGE_SHIFT);
30991da177e4SLinus Torvalds 		return -ENOMEM;
31001da177e4SLinus Torvalds 	}
31011da177e4SLinus Torvalds 
3102bfd40eafSKirill A. Shutemov 	vma_set_anonymous(vma);
31031da177e4SLinus Torvalds 	vma->vm_start = addr;
31041da177e4SLinus Torvalds 	vma->vm_end = addr + len;
31051da177e4SLinus Torvalds 	vma->vm_pgoff = pgoff;
31061da177e4SLinus Torvalds 	vma->vm_flags = flags;
31073ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(flags);
31081da177e4SLinus Torvalds 	vma_link(mm, vma, prev, rb_link, rb_parent);
31091da177e4SLinus Torvalds out:
31103af9e859SEric B Munson 	perf_event_mmap(vma);
31111da177e4SLinus Torvalds 	mm->total_vm += len >> PAGE_SHIFT;
311284638335SKonstantin Khlebnikov 	mm->data_vm += len >> PAGE_SHIFT;
3113128557ffSMichel Lespinasse 	if (flags & VM_LOCKED)
3114ba470de4SRik van Riel 		mm->locked_vm += (len >> PAGE_SHIFT);
3115d9104d1cSCyrill Gorcunov 	vma->vm_flags |= VM_SOFTDIRTY;
31165d22fc25SLinus Torvalds 	return 0;
31171da177e4SLinus Torvalds }
31181da177e4SLinus Torvalds 
3119bb177a73SMichal Hocko int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3120e4eb1ff6SLinus Torvalds {
3121e4eb1ff6SLinus Torvalds 	struct mm_struct *mm = current->mm;
3122bb177a73SMichal Hocko 	unsigned long len;
31235d22fc25SLinus Torvalds 	int ret;
3124128557ffSMichel Lespinasse 	bool populate;
3125897ab3e0SMike Rapoport 	LIST_HEAD(uf);
3126e4eb1ff6SLinus Torvalds 
3127bb177a73SMichal Hocko 	len = PAGE_ALIGN(request);
3128bb177a73SMichal Hocko 	if (len < request)
3129bb177a73SMichal Hocko 		return -ENOMEM;
3130bb177a73SMichal Hocko 	if (!len)
3131bb177a73SMichal Hocko 		return 0;
3132bb177a73SMichal Hocko 
3133d8ed45c5SMichel Lespinasse 	if (mmap_write_lock_killable(mm))
31342d6c9282SMichal Hocko 		return -EINTR;
31352d6c9282SMichal Hocko 
3136897ab3e0SMike Rapoport 	ret = do_brk_flags(addr, len, flags, &uf);
3137128557ffSMichel Lespinasse 	populate = ((mm->def_flags & VM_LOCKED) != 0);
3138d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
3139897ab3e0SMike Rapoport 	userfaultfd_unmap_complete(mm, &uf);
31405d22fc25SLinus Torvalds 	if (populate && !ret)
3141128557ffSMichel Lespinasse 		mm_populate(addr, len);
3142e4eb1ff6SLinus Torvalds 	return ret;
3143e4eb1ff6SLinus Torvalds }
314416e72e9bSDenys Vlasenko EXPORT_SYMBOL(vm_brk_flags);
314516e72e9bSDenys Vlasenko 
314616e72e9bSDenys Vlasenko int vm_brk(unsigned long addr, unsigned long len)
314716e72e9bSDenys Vlasenko {
314816e72e9bSDenys Vlasenko 	return vm_brk_flags(addr, len, 0);
314916e72e9bSDenys Vlasenko }
3150e4eb1ff6SLinus Torvalds EXPORT_SYMBOL(vm_brk);
31511da177e4SLinus Torvalds 
31521da177e4SLinus Torvalds /* Release all mmaps. */
31531da177e4SLinus Torvalds void exit_mmap(struct mm_struct *mm)
31541da177e4SLinus Torvalds {
3155d16dfc55SPeter Zijlstra 	struct mmu_gather tlb;
3156ba470de4SRik van Riel 	struct vm_area_struct *vma;
31571da177e4SLinus Torvalds 	unsigned long nr_accounted = 0;
31581da177e4SLinus Torvalds 
3159d6dd61c8SJeremy Fitzhardinge 	/* mm's last user has gone, and its about to be pulled down */
3160cddb8a5cSAndrea Arcangeli 	mmu_notifier_release(mm);
3161d6dd61c8SJeremy Fitzhardinge 
316227ae357fSDavid Rientjes 	if (unlikely(mm_is_oom_victim(mm))) {
316327ae357fSDavid Rientjes 		/*
316427ae357fSDavid Rientjes 		 * Manually reap the mm to free as much memory as possible.
316527ae357fSDavid Rientjes 		 * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3166c1e8d7c6SMichel Lespinasse 		 * this mm from further consideration.  Taking mm->mmap_lock for
316727ae357fSDavid Rientjes 		 * write after setting MMF_OOM_SKIP will guarantee that the oom
3168c1e8d7c6SMichel Lespinasse 		 * reaper will not run on this mm again after mmap_lock is
316927ae357fSDavid Rientjes 		 * dropped.
317027ae357fSDavid Rientjes 		 *
3171c1e8d7c6SMichel Lespinasse 		 * Nothing can be holding mm->mmap_lock here and the above call
317227ae357fSDavid Rientjes 		 * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
317327ae357fSDavid Rientjes 		 * __oom_reap_task_mm() will not block.
317427ae357fSDavid Rientjes 		 *
317527ae357fSDavid Rientjes 		 * This needs to be done before calling munlock_vma_pages_all(),
317627ae357fSDavid Rientjes 		 * which clears VM_LOCKED, otherwise the oom reaper cannot
317727ae357fSDavid Rientjes 		 * reliably test it.
317827ae357fSDavid Rientjes 		 */
317993065ac7SMichal Hocko 		(void)__oom_reap_task_mm(mm);
318027ae357fSDavid Rientjes 
318127ae357fSDavid Rientjes 		set_bit(MMF_OOM_SKIP, &mm->flags);
3182d8ed45c5SMichel Lespinasse 		mmap_write_lock(mm);
3183d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
318427ae357fSDavid Rientjes 	}
318527ae357fSDavid Rientjes 
318696d99023SLiam Howlett 	if (mm->locked_vm)
318796d99023SLiam Howlett 		unlock_range(mm->mmap, ULONG_MAX);
31889480c53eSJeremy Fitzhardinge 
31899480c53eSJeremy Fitzhardinge 	arch_exit_mmap(mm);
31909480c53eSJeremy Fitzhardinge 
3191ba470de4SRik van Riel 	vma = mm->mmap;
31929480c53eSJeremy Fitzhardinge 	if (!vma)	/* Can happen if dup_mmap() received an OOM */
31939480c53eSJeremy Fitzhardinge 		return;
31949480c53eSJeremy Fitzhardinge 
31951da177e4SLinus Torvalds 	lru_add_drain();
31961da177e4SLinus Torvalds 	flush_cache_mm(mm);
3197d8b45053SWill Deacon 	tlb_gather_mmu_fullmm(&tlb, mm);
3198901608d9SOleg Nesterov 	/* update_hiwater_rss(mm) here? but nobody should be looking */
3199e0da382cSHugh Dickins 	/* Use -1 here to ensure all VMAs in the mm are unmapped */
32004f74d2c8SLinus Torvalds 	unmap_vmas(&tlb, vma, 0, -1);
32016ee8630eSHugh Dickins 	free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3202ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
32031da177e4SLinus Torvalds 
32041da177e4SLinus Torvalds 	/*
32058f4f8c16SHugh Dickins 	 * Walk the list again, actually closing and freeing it,
32068f4f8c16SHugh Dickins 	 * with preemption enabled, without holding any MM locks.
32071da177e4SLinus Torvalds 	 */
32084f74d2c8SLinus Torvalds 	while (vma) {
32094f74d2c8SLinus Torvalds 		if (vma->vm_flags & VM_ACCOUNT)
32104f74d2c8SLinus Torvalds 			nr_accounted += vma_pages(vma);
3211a8fb5618SHugh Dickins 		vma = remove_vma(vma);
32120a3b3c25SPaul E. McKenney 		cond_resched();
32134f74d2c8SLinus Torvalds 	}
32144f74d2c8SLinus Torvalds 	vm_unacct_memory(nr_accounted);
32151da177e4SLinus Torvalds }
32161da177e4SLinus Torvalds 
32171da177e4SLinus Torvalds /* Insert vm structure into process list sorted by address
32181da177e4SLinus Torvalds  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3219c8c06efaSDavidlohr Bueso  * then i_mmap_rwsem is taken here.
32201da177e4SLinus Torvalds  */
32211da177e4SLinus Torvalds int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
32221da177e4SLinus Torvalds {
32236597d783SHugh Dickins 	struct vm_area_struct *prev;
32241da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
32251da177e4SLinus Torvalds 
3226c9d13f5fSChen Gang 	if (find_vma_links(mm, vma->vm_start, vma->vm_end,
3227c9d13f5fSChen Gang 			   &prev, &rb_link, &rb_parent))
3228c9d13f5fSChen Gang 		return -ENOMEM;
3229c9d13f5fSChen Gang 	if ((vma->vm_flags & VM_ACCOUNT) &&
3230c9d13f5fSChen Gang 	     security_vm_enough_memory_mm(mm, vma_pages(vma)))
3231c9d13f5fSChen Gang 		return -ENOMEM;
3232c9d13f5fSChen Gang 
32331da177e4SLinus Torvalds 	/*
32341da177e4SLinus Torvalds 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
32351da177e4SLinus Torvalds 	 * until its first write fault, when page's anon_vma and index
32361da177e4SLinus Torvalds 	 * are set.  But now set the vm_pgoff it will almost certainly
32371da177e4SLinus Torvalds 	 * end up with (unless mremap moves it elsewhere before that
32381da177e4SLinus Torvalds 	 * first wfault), so /proc/pid/maps tells a consistent story.
32391da177e4SLinus Torvalds 	 *
32401da177e4SLinus Torvalds 	 * By setting it to reflect the virtual start address of the
32411da177e4SLinus Torvalds 	 * vma, merges and splits can happen in a seamless way, just
32421da177e4SLinus Torvalds 	 * using the existing file pgoff checks and manipulations.
32438332326eSLiao Pingfang 	 * Similarly in do_mmap and in do_brk_flags.
32441da177e4SLinus Torvalds 	 */
32458a9cc3b5SOleg Nesterov 	if (vma_is_anonymous(vma)) {
32461da177e4SLinus Torvalds 		BUG_ON(vma->anon_vma);
32471da177e4SLinus Torvalds 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
32481da177e4SLinus Torvalds 	}
32492b144498SSrikar Dronamraju 
32501da177e4SLinus Torvalds 	vma_link(mm, vma, prev, rb_link, rb_parent);
32511da177e4SLinus Torvalds 	return 0;
32521da177e4SLinus Torvalds }
32531da177e4SLinus Torvalds 
32541da177e4SLinus Torvalds /*
32551da177e4SLinus Torvalds  * Copy the vma structure to a new location in the same mm,
32561da177e4SLinus Torvalds  * prior to moving page table entries, to effect an mremap move.
32571da177e4SLinus Torvalds  */
32581da177e4SLinus Torvalds struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
325938a76013SMichel Lespinasse 	unsigned long addr, unsigned long len, pgoff_t pgoff,
326038a76013SMichel Lespinasse 	bool *need_rmap_locks)
32611da177e4SLinus Torvalds {
32621da177e4SLinus Torvalds 	struct vm_area_struct *vma = *vmap;
32631da177e4SLinus Torvalds 	unsigned long vma_start = vma->vm_start;
32641da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
32651da177e4SLinus Torvalds 	struct vm_area_struct *new_vma, *prev;
32661da177e4SLinus Torvalds 	struct rb_node **rb_link, *rb_parent;
3267948f017bSAndrea Arcangeli 	bool faulted_in_anon_vma = true;
32681da177e4SLinus Torvalds 
32691da177e4SLinus Torvalds 	/*
32701da177e4SLinus Torvalds 	 * If anonymous vma has not yet been faulted, update new pgoff
32711da177e4SLinus Torvalds 	 * to match new location, to increase its chance of merging.
32721da177e4SLinus Torvalds 	 */
3273ce75799bSOleg Nesterov 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
32741da177e4SLinus Torvalds 		pgoff = addr >> PAGE_SHIFT;
3275948f017bSAndrea Arcangeli 		faulted_in_anon_vma = false;
3276948f017bSAndrea Arcangeli 	}
32771da177e4SLinus Torvalds 
32786597d783SHugh Dickins 	if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
32796597d783SHugh Dickins 		return NULL;	/* should never get here */
32801da177e4SLinus Torvalds 	new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
328119a809afSAndrea Arcangeli 			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
328219a809afSAndrea Arcangeli 			    vma->vm_userfaultfd_ctx);
32831da177e4SLinus Torvalds 	if (new_vma) {
32841da177e4SLinus Torvalds 		/*
32851da177e4SLinus Torvalds 		 * Source vma may have been merged into new_vma
32861da177e4SLinus Torvalds 		 */
3287948f017bSAndrea Arcangeli 		if (unlikely(vma_start >= new_vma->vm_start &&
3288948f017bSAndrea Arcangeli 			     vma_start < new_vma->vm_end)) {
3289948f017bSAndrea Arcangeli 			/*
3290948f017bSAndrea Arcangeli 			 * The only way we can get a vma_merge with
3291948f017bSAndrea Arcangeli 			 * self during an mremap is if the vma hasn't
3292948f017bSAndrea Arcangeli 			 * been faulted in yet and we were allowed to
3293948f017bSAndrea Arcangeli 			 * reset the dst vma->vm_pgoff to the
3294948f017bSAndrea Arcangeli 			 * destination address of the mremap to allow
3295948f017bSAndrea Arcangeli 			 * the merge to happen. mremap must change the
3296948f017bSAndrea Arcangeli 			 * vm_pgoff linearity between src and dst vmas
3297948f017bSAndrea Arcangeli 			 * (in turn preventing a vma_merge) to be
3298948f017bSAndrea Arcangeli 			 * safe. It is only safe to keep the vm_pgoff
3299948f017bSAndrea Arcangeli 			 * linear if there are no pages mapped yet.
3300948f017bSAndrea Arcangeli 			 */
330181d1b09cSSasha Levin 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
330238a76013SMichel Lespinasse 			*vmap = vma = new_vma;
3303108d6642SMichel Lespinasse 		}
330438a76013SMichel Lespinasse 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
33051da177e4SLinus Torvalds 	} else {
33063928d4f5SLinus Torvalds 		new_vma = vm_area_dup(vma);
3307e3975891SChen Gang 		if (!new_vma)
3308e3975891SChen Gang 			goto out;
33091da177e4SLinus Torvalds 		new_vma->vm_start = addr;
33101da177e4SLinus Torvalds 		new_vma->vm_end = addr + len;
33111da177e4SLinus Torvalds 		new_vma->vm_pgoff = pgoff;
3312ef0855d3SOleg Nesterov 		if (vma_dup_policy(vma, new_vma))
3313523d4e20SMichel Lespinasse 			goto out_free_vma;
3314523d4e20SMichel Lespinasse 		if (anon_vma_clone(new_vma, vma))
3315523d4e20SMichel Lespinasse 			goto out_free_mempol;
3316e9714acfSKonstantin Khlebnikov 		if (new_vma->vm_file)
33171da177e4SLinus Torvalds 			get_file(new_vma->vm_file);
33181da177e4SLinus Torvalds 		if (new_vma->vm_ops && new_vma->vm_ops->open)
33191da177e4SLinus Torvalds 			new_vma->vm_ops->open(new_vma);
33201da177e4SLinus Torvalds 		vma_link(mm, new_vma, prev, rb_link, rb_parent);
332138a76013SMichel Lespinasse 		*need_rmap_locks = false;
33221da177e4SLinus Torvalds 	}
33231da177e4SLinus Torvalds 	return new_vma;
33245beb4930SRik van Riel 
33255beb4930SRik van Riel out_free_mempol:
3326ef0855d3SOleg Nesterov 	mpol_put(vma_policy(new_vma));
33275beb4930SRik van Riel out_free_vma:
33283928d4f5SLinus Torvalds 	vm_area_free(new_vma);
3329e3975891SChen Gang out:
33305beb4930SRik van Riel 	return NULL;
33311da177e4SLinus Torvalds }
3332119f657cSakpm@osdl.org 
3333119f657cSakpm@osdl.org /*
3334119f657cSakpm@osdl.org  * Return true if the calling process may expand its vm space by the passed
3335119f657cSakpm@osdl.org  * number of pages
3336119f657cSakpm@osdl.org  */
333784638335SKonstantin Khlebnikov bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3338119f657cSakpm@osdl.org {
333984638335SKonstantin Khlebnikov 	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
334084638335SKonstantin Khlebnikov 		return false;
3341119f657cSakpm@osdl.org 
3342d977d56cSKonstantin Khlebnikov 	if (is_data_mapping(flags) &&
3343d977d56cSKonstantin Khlebnikov 	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3344f4fcd558SKonstantin Khlebnikov 		/* Workaround for Valgrind */
3345f4fcd558SKonstantin Khlebnikov 		if (rlimit(RLIMIT_DATA) == 0 &&
3346f4fcd558SKonstantin Khlebnikov 		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3347f4fcd558SKonstantin Khlebnikov 			return true;
334857a7702bSDavid Woodhouse 
334957a7702bSDavid Woodhouse 		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3350d977d56cSKonstantin Khlebnikov 			     current->comm, current->pid,
3351d977d56cSKonstantin Khlebnikov 			     (mm->data_vm + npages) << PAGE_SHIFT,
335257a7702bSDavid Woodhouse 			     rlimit(RLIMIT_DATA),
335357a7702bSDavid Woodhouse 			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
335457a7702bSDavid Woodhouse 
335557a7702bSDavid Woodhouse 		if (!ignore_rlimit_data)
3356d977d56cSKonstantin Khlebnikov 			return false;
3357d977d56cSKonstantin Khlebnikov 	}
3358119f657cSakpm@osdl.org 
335984638335SKonstantin Khlebnikov 	return true;
336084638335SKonstantin Khlebnikov }
336184638335SKonstantin Khlebnikov 
336284638335SKonstantin Khlebnikov void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
336384638335SKonstantin Khlebnikov {
336484638335SKonstantin Khlebnikov 	mm->total_vm += npages;
336584638335SKonstantin Khlebnikov 
3366d977d56cSKonstantin Khlebnikov 	if (is_exec_mapping(flags))
336784638335SKonstantin Khlebnikov 		mm->exec_vm += npages;
3368d977d56cSKonstantin Khlebnikov 	else if (is_stack_mapping(flags))
336984638335SKonstantin Khlebnikov 		mm->stack_vm += npages;
3370d977d56cSKonstantin Khlebnikov 	else if (is_data_mapping(flags))
337184638335SKonstantin Khlebnikov 		mm->data_vm += npages;
3372119f657cSakpm@osdl.org }
3373fa5dc22fSRoland McGrath 
3374b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3375a62c34bdSAndy Lutomirski 
3376a62c34bdSAndy Lutomirski /*
3377a62c34bdSAndy Lutomirski  * Having a close hook prevents vma merging regardless of flags.
3378a62c34bdSAndy Lutomirski  */
3379a62c34bdSAndy Lutomirski static void special_mapping_close(struct vm_area_struct *vma)
3380a62c34bdSAndy Lutomirski {
3381a62c34bdSAndy Lutomirski }
3382a62c34bdSAndy Lutomirski 
3383a62c34bdSAndy Lutomirski static const char *special_mapping_name(struct vm_area_struct *vma)
3384a62c34bdSAndy Lutomirski {
3385a62c34bdSAndy Lutomirski 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3386a62c34bdSAndy Lutomirski }
3387a62c34bdSAndy Lutomirski 
338814d07113SBrian Geffon static int special_mapping_mremap(struct vm_area_struct *new_vma)
3389b059a453SDmitry Safonov {
3390b059a453SDmitry Safonov 	struct vm_special_mapping *sm = new_vma->vm_private_data;
3391b059a453SDmitry Safonov 
3392280e87e9SDmitry Safonov 	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3393280e87e9SDmitry Safonov 		return -EFAULT;
3394280e87e9SDmitry Safonov 
3395b059a453SDmitry Safonov 	if (sm->mremap)
3396b059a453SDmitry Safonov 		return sm->mremap(sm, new_vma);
3397280e87e9SDmitry Safonov 
3398b059a453SDmitry Safonov 	return 0;
3399b059a453SDmitry Safonov }
3400b059a453SDmitry Safonov 
3401871402e0SDmitry Safonov static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3402871402e0SDmitry Safonov {
3403871402e0SDmitry Safonov 	/*
3404871402e0SDmitry Safonov 	 * Forbid splitting special mappings - kernel has expectations over
3405871402e0SDmitry Safonov 	 * the number of pages in mapping. Together with VM_DONTEXPAND
3406871402e0SDmitry Safonov 	 * the size of vma should stay the same over the special mapping's
3407871402e0SDmitry Safonov 	 * lifetime.
3408871402e0SDmitry Safonov 	 */
3409871402e0SDmitry Safonov 	return -EINVAL;
3410871402e0SDmitry Safonov }
3411871402e0SDmitry Safonov 
3412a62c34bdSAndy Lutomirski static const struct vm_operations_struct special_mapping_vmops = {
3413a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3414a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3415b059a453SDmitry Safonov 	.mremap = special_mapping_mremap,
3416a62c34bdSAndy Lutomirski 	.name = special_mapping_name,
3417af34ebebSDmitry Safonov 	/* vDSO code relies that VVAR can't be accessed remotely */
3418af34ebebSDmitry Safonov 	.access = NULL,
3419871402e0SDmitry Safonov 	.may_split = special_mapping_split,
3420a62c34bdSAndy Lutomirski };
3421a62c34bdSAndy Lutomirski 
3422a62c34bdSAndy Lutomirski static const struct vm_operations_struct legacy_special_mapping_vmops = {
3423a62c34bdSAndy Lutomirski 	.close = special_mapping_close,
3424a62c34bdSAndy Lutomirski 	.fault = special_mapping_fault,
3425a62c34bdSAndy Lutomirski };
3426fa5dc22fSRoland McGrath 
3427b3ec9f33SSouptick Joarder static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3428fa5dc22fSRoland McGrath {
342911bac800SDave Jiang 	struct vm_area_struct *vma = vmf->vma;
3430b1d0e4f5SNick Piggin 	pgoff_t pgoff;
3431fa5dc22fSRoland McGrath 	struct page **pages;
3432fa5dc22fSRoland McGrath 
3433f872f540SAndy Lutomirski 	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3434a62c34bdSAndy Lutomirski 		pages = vma->vm_private_data;
3435f872f540SAndy Lutomirski 	} else {
3436f872f540SAndy Lutomirski 		struct vm_special_mapping *sm = vma->vm_private_data;
3437f872f540SAndy Lutomirski 
3438f872f540SAndy Lutomirski 		if (sm->fault)
343911bac800SDave Jiang 			return sm->fault(sm, vmf->vma, vmf);
3440f872f540SAndy Lutomirski 
3441f872f540SAndy Lutomirski 		pages = sm->pages;
3442f872f540SAndy Lutomirski 	}
3443a62c34bdSAndy Lutomirski 
34448a9cc3b5SOleg Nesterov 	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3445b1d0e4f5SNick Piggin 		pgoff--;
3446fa5dc22fSRoland McGrath 
3447fa5dc22fSRoland McGrath 	if (*pages) {
3448fa5dc22fSRoland McGrath 		struct page *page = *pages;
3449fa5dc22fSRoland McGrath 		get_page(page);
3450b1d0e4f5SNick Piggin 		vmf->page = page;
3451b1d0e4f5SNick Piggin 		return 0;
3452fa5dc22fSRoland McGrath 	}
3453fa5dc22fSRoland McGrath 
3454b1d0e4f5SNick Piggin 	return VM_FAULT_SIGBUS;
3455fa5dc22fSRoland McGrath }
3456fa5dc22fSRoland McGrath 
3457a62c34bdSAndy Lutomirski static struct vm_area_struct *__install_special_mapping(
3458a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3459fa5dc22fSRoland McGrath 	unsigned long addr, unsigned long len,
346027f28b97SChen Gang 	unsigned long vm_flags, void *priv,
346127f28b97SChen Gang 	const struct vm_operations_struct *ops)
3462fa5dc22fSRoland McGrath {
3463462e635eSTavis Ormandy 	int ret;
3464fa5dc22fSRoland McGrath 	struct vm_area_struct *vma;
3465fa5dc22fSRoland McGrath 
3466490fc053SLinus Torvalds 	vma = vm_area_alloc(mm);
3467fa5dc22fSRoland McGrath 	if (unlikely(vma == NULL))
34683935ed6aSStefani Seibold 		return ERR_PTR(-ENOMEM);
3469fa5dc22fSRoland McGrath 
3470fa5dc22fSRoland McGrath 	vma->vm_start = addr;
3471fa5dc22fSRoland McGrath 	vma->vm_end = addr + len;
3472fa5dc22fSRoland McGrath 
3473d9104d1cSCyrill Gorcunov 	vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
34743ed75eb8SColy Li 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3475fa5dc22fSRoland McGrath 
3476a62c34bdSAndy Lutomirski 	vma->vm_ops = ops;
3477a62c34bdSAndy Lutomirski 	vma->vm_private_data = priv;
3478fa5dc22fSRoland McGrath 
3479462e635eSTavis Ormandy 	ret = insert_vm_struct(mm, vma);
3480462e635eSTavis Ormandy 	if (ret)
3481462e635eSTavis Ormandy 		goto out;
3482fa5dc22fSRoland McGrath 
348384638335SKonstantin Khlebnikov 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3484fa5dc22fSRoland McGrath 
3485cdd6c482SIngo Molnar 	perf_event_mmap(vma);
3486089dd79dSPeter Zijlstra 
34873935ed6aSStefani Seibold 	return vma;
3488462e635eSTavis Ormandy 
3489462e635eSTavis Ormandy out:
34903928d4f5SLinus Torvalds 	vm_area_free(vma);
34913935ed6aSStefani Seibold 	return ERR_PTR(ret);
34923935ed6aSStefani Seibold }
34933935ed6aSStefani Seibold 
34942eefd878SDmitry Safonov bool vma_is_special_mapping(const struct vm_area_struct *vma,
34952eefd878SDmitry Safonov 	const struct vm_special_mapping *sm)
34962eefd878SDmitry Safonov {
34972eefd878SDmitry Safonov 	return vma->vm_private_data == sm &&
34982eefd878SDmitry Safonov 		(vma->vm_ops == &special_mapping_vmops ||
34992eefd878SDmitry Safonov 		 vma->vm_ops == &legacy_special_mapping_vmops);
35002eefd878SDmitry Safonov }
35012eefd878SDmitry Safonov 
3502a62c34bdSAndy Lutomirski /*
3503c1e8d7c6SMichel Lespinasse  * Called with mm->mmap_lock held for writing.
3504a62c34bdSAndy Lutomirski  * Insert a new vma covering the given region, with the given flags.
3505a62c34bdSAndy Lutomirski  * Its pages are supplied by the given array of struct page *.
3506a62c34bdSAndy Lutomirski  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3507a62c34bdSAndy Lutomirski  * The region past the last page supplied will always produce SIGBUS.
3508a62c34bdSAndy Lutomirski  * The array pointer and the pages it points to are assumed to stay alive
3509a62c34bdSAndy Lutomirski  * for as long as this mapping might exist.
3510a62c34bdSAndy Lutomirski  */
3511a62c34bdSAndy Lutomirski struct vm_area_struct *_install_special_mapping(
3512a62c34bdSAndy Lutomirski 	struct mm_struct *mm,
3513a62c34bdSAndy Lutomirski 	unsigned long addr, unsigned long len,
3514a62c34bdSAndy Lutomirski 	unsigned long vm_flags, const struct vm_special_mapping *spec)
3515a62c34bdSAndy Lutomirski {
351627f28b97SChen Gang 	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
351727f28b97SChen Gang 					&special_mapping_vmops);
3518a62c34bdSAndy Lutomirski }
3519a62c34bdSAndy Lutomirski 
35203935ed6aSStefani Seibold int install_special_mapping(struct mm_struct *mm,
35213935ed6aSStefani Seibold 			    unsigned long addr, unsigned long len,
35223935ed6aSStefani Seibold 			    unsigned long vm_flags, struct page **pages)
35233935ed6aSStefani Seibold {
3524a62c34bdSAndy Lutomirski 	struct vm_area_struct *vma = __install_special_mapping(
352527f28b97SChen Gang 		mm, addr, len, vm_flags, (void *)pages,
352627f28b97SChen Gang 		&legacy_special_mapping_vmops);
35273935ed6aSStefani Seibold 
352814bd5b45SDuan Jiong 	return PTR_ERR_OR_ZERO(vma);
3529fa5dc22fSRoland McGrath }
35307906d00cSAndrea Arcangeli 
35317906d00cSAndrea Arcangeli static DEFINE_MUTEX(mm_all_locks_mutex);
35327906d00cSAndrea Arcangeli 
3533454ed842SPeter Zijlstra static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
35347906d00cSAndrea Arcangeli {
3535f808c13fSDavidlohr Bueso 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
35367906d00cSAndrea Arcangeli 		/*
35377906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change from under us
35387906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
35397906d00cSAndrea Arcangeli 		 */
3540da1c55f1SMichel Lespinasse 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
35417906d00cSAndrea Arcangeli 		/*
35427906d00cSAndrea Arcangeli 		 * We can safely modify head.next after taking the
35435a505085SIngo Molnar 		 * anon_vma->root->rwsem. If some other vma in this mm shares
35447906d00cSAndrea Arcangeli 		 * the same anon_vma we won't take it again.
35457906d00cSAndrea Arcangeli 		 *
35467906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
35477906d00cSAndrea Arcangeli 		 * can't change from under us thanks to the
35485a505085SIngo Molnar 		 * anon_vma->root->rwsem.
35497906d00cSAndrea Arcangeli 		 */
35507906d00cSAndrea Arcangeli 		if (__test_and_set_bit(0, (unsigned long *)
3551f808c13fSDavidlohr Bueso 				       &anon_vma->root->rb_root.rb_root.rb_node))
35527906d00cSAndrea Arcangeli 			BUG();
35537906d00cSAndrea Arcangeli 	}
35547906d00cSAndrea Arcangeli }
35557906d00cSAndrea Arcangeli 
3556454ed842SPeter Zijlstra static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
35577906d00cSAndrea Arcangeli {
35587906d00cSAndrea Arcangeli 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
35597906d00cSAndrea Arcangeli 		/*
35607906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change from under us because
35617906d00cSAndrea Arcangeli 		 * we hold the mm_all_locks_mutex.
35627906d00cSAndrea Arcangeli 		 *
35637906d00cSAndrea Arcangeli 		 * Operations on ->flags have to be atomic because
35647906d00cSAndrea Arcangeli 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
35657906d00cSAndrea Arcangeli 		 * mm_all_locks_mutex, there may be other cpus
35667906d00cSAndrea Arcangeli 		 * changing other bitflags in parallel to us.
35677906d00cSAndrea Arcangeli 		 */
35687906d00cSAndrea Arcangeli 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
35697906d00cSAndrea Arcangeli 			BUG();
3570da1c55f1SMichel Lespinasse 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
35717906d00cSAndrea Arcangeli 	}
35727906d00cSAndrea Arcangeli }
35737906d00cSAndrea Arcangeli 
35747906d00cSAndrea Arcangeli /*
35757906d00cSAndrea Arcangeli  * This operation locks against the VM for all pte/vma/mm related
35767906d00cSAndrea Arcangeli  * operations that could ever happen on a certain mm. This includes
35777906d00cSAndrea Arcangeli  * vmtruncate, try_to_unmap, and all page faults.
35787906d00cSAndrea Arcangeli  *
3579c1e8d7c6SMichel Lespinasse  * The caller must take the mmap_lock in write mode before calling
35807906d00cSAndrea Arcangeli  * mm_take_all_locks(). The caller isn't allowed to release the
3581c1e8d7c6SMichel Lespinasse  * mmap_lock until mm_drop_all_locks() returns.
35827906d00cSAndrea Arcangeli  *
3583c1e8d7c6SMichel Lespinasse  * mmap_lock in write mode is required in order to block all operations
35847906d00cSAndrea Arcangeli  * that could modify pagetables and free pages without need of
358527ba0644SKirill A. Shutemov  * altering the vma layout. It's also needed in write mode to avoid new
35867906d00cSAndrea Arcangeli  * anon_vmas to be associated with existing vmas.
35877906d00cSAndrea Arcangeli  *
35887906d00cSAndrea Arcangeli  * A single task can't take more than one mm_take_all_locks() in a row
35897906d00cSAndrea Arcangeli  * or it would deadlock.
35907906d00cSAndrea Arcangeli  *
3591bf181b9fSMichel Lespinasse  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
35927906d00cSAndrea Arcangeli  * mapping->flags avoid to take the same lock twice, if more than one
35937906d00cSAndrea Arcangeli  * vma in this mm is backed by the same anon_vma or address_space.
35947906d00cSAndrea Arcangeli  *
359588f306b6SKirill A. Shutemov  * We take locks in following order, accordingly to comment at beginning
359688f306b6SKirill A. Shutemov  * of mm/rmap.c:
359788f306b6SKirill A. Shutemov  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
359888f306b6SKirill A. Shutemov  *     hugetlb mapping);
359988f306b6SKirill A. Shutemov  *   - all i_mmap_rwsem locks;
360088f306b6SKirill A. Shutemov  *   - all anon_vma->rwseml
360188f306b6SKirill A. Shutemov  *
360288f306b6SKirill A. Shutemov  * We can take all locks within these types randomly because the VM code
360388f306b6SKirill A. Shutemov  * doesn't nest them and we protected from parallel mm_take_all_locks() by
360488f306b6SKirill A. Shutemov  * mm_all_locks_mutex.
36057906d00cSAndrea Arcangeli  *
36067906d00cSAndrea Arcangeli  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
36077906d00cSAndrea Arcangeli  * that may have to take thousand of locks.
36087906d00cSAndrea Arcangeli  *
36097906d00cSAndrea Arcangeli  * mm_take_all_locks() can fail if it's interrupted by signals.
36107906d00cSAndrea Arcangeli  */
36117906d00cSAndrea Arcangeli int mm_take_all_locks(struct mm_struct *mm)
36127906d00cSAndrea Arcangeli {
36137906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
36145beb4930SRik van Riel 	struct anon_vma_chain *avc;
36157906d00cSAndrea Arcangeli 
3616d8ed45c5SMichel Lespinasse 	BUG_ON(mmap_read_trylock(mm));
36177906d00cSAndrea Arcangeli 
36187906d00cSAndrea Arcangeli 	mutex_lock(&mm_all_locks_mutex);
36197906d00cSAndrea Arcangeli 
36207906d00cSAndrea Arcangeli 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
36217906d00cSAndrea Arcangeli 		if (signal_pending(current))
36227906d00cSAndrea Arcangeli 			goto out_unlock;
362388f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
362488f306b6SKirill A. Shutemov 				is_vm_hugetlb_page(vma))
362588f306b6SKirill A. Shutemov 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
362688f306b6SKirill A. Shutemov 	}
362788f306b6SKirill A. Shutemov 
362888f306b6SKirill A. Shutemov 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
362988f306b6SKirill A. Shutemov 		if (signal_pending(current))
363088f306b6SKirill A. Shutemov 			goto out_unlock;
363188f306b6SKirill A. Shutemov 		if (vma->vm_file && vma->vm_file->f_mapping &&
363288f306b6SKirill A. Shutemov 				!is_vm_hugetlb_page(vma))
3633454ed842SPeter Zijlstra 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
36347906d00cSAndrea Arcangeli 	}
36357cd5a02fSPeter Zijlstra 
36367cd5a02fSPeter Zijlstra 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
36377cd5a02fSPeter Zijlstra 		if (signal_pending(current))
36387cd5a02fSPeter Zijlstra 			goto out_unlock;
36397cd5a02fSPeter Zijlstra 		if (vma->anon_vma)
36405beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
36415beb4930SRik van Riel 				vm_lock_anon_vma(mm, avc->anon_vma);
36427cd5a02fSPeter Zijlstra 	}
36437cd5a02fSPeter Zijlstra 
3644584cff54SKautuk Consul 	return 0;
36457906d00cSAndrea Arcangeli 
36467906d00cSAndrea Arcangeli out_unlock:
36477906d00cSAndrea Arcangeli 	mm_drop_all_locks(mm);
3648584cff54SKautuk Consul 	return -EINTR;
36497906d00cSAndrea Arcangeli }
36507906d00cSAndrea Arcangeli 
36517906d00cSAndrea Arcangeli static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
36527906d00cSAndrea Arcangeli {
3653f808c13fSDavidlohr Bueso 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
36547906d00cSAndrea Arcangeli 		/*
36557906d00cSAndrea Arcangeli 		 * The LSB of head.next can't change to 0 from under
36567906d00cSAndrea Arcangeli 		 * us because we hold the mm_all_locks_mutex.
36577906d00cSAndrea Arcangeli 		 *
36587906d00cSAndrea Arcangeli 		 * We must however clear the bitflag before unlocking
3659bf181b9fSMichel Lespinasse 		 * the vma so the users using the anon_vma->rb_root will
36607906d00cSAndrea Arcangeli 		 * never see our bitflag.
36617906d00cSAndrea Arcangeli 		 *
36627906d00cSAndrea Arcangeli 		 * No need of atomic instructions here, head.next
36637906d00cSAndrea Arcangeli 		 * can't change from under us until we release the
36645a505085SIngo Molnar 		 * anon_vma->root->rwsem.
36657906d00cSAndrea Arcangeli 		 */
36667906d00cSAndrea Arcangeli 		if (!__test_and_clear_bit(0, (unsigned long *)
3667f808c13fSDavidlohr Bueso 					  &anon_vma->root->rb_root.rb_root.rb_node))
36687906d00cSAndrea Arcangeli 			BUG();
366908b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
36707906d00cSAndrea Arcangeli 	}
36717906d00cSAndrea Arcangeli }
36727906d00cSAndrea Arcangeli 
36737906d00cSAndrea Arcangeli static void vm_unlock_mapping(struct address_space *mapping)
36747906d00cSAndrea Arcangeli {
36757906d00cSAndrea Arcangeli 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
36767906d00cSAndrea Arcangeli 		/*
36777906d00cSAndrea Arcangeli 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
36787906d00cSAndrea Arcangeli 		 * because we hold the mm_all_locks_mutex.
36797906d00cSAndrea Arcangeli 		 */
368083cde9e8SDavidlohr Bueso 		i_mmap_unlock_write(mapping);
36817906d00cSAndrea Arcangeli 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
36827906d00cSAndrea Arcangeli 					&mapping->flags))
36837906d00cSAndrea Arcangeli 			BUG();
36847906d00cSAndrea Arcangeli 	}
36857906d00cSAndrea Arcangeli }
36867906d00cSAndrea Arcangeli 
36877906d00cSAndrea Arcangeli /*
3688c1e8d7c6SMichel Lespinasse  * The mmap_lock cannot be released by the caller until
36897906d00cSAndrea Arcangeli  * mm_drop_all_locks() returns.
36907906d00cSAndrea Arcangeli  */
36917906d00cSAndrea Arcangeli void mm_drop_all_locks(struct mm_struct *mm)
36927906d00cSAndrea Arcangeli {
36937906d00cSAndrea Arcangeli 	struct vm_area_struct *vma;
36945beb4930SRik van Riel 	struct anon_vma_chain *avc;
36957906d00cSAndrea Arcangeli 
3696d8ed45c5SMichel Lespinasse 	BUG_ON(mmap_read_trylock(mm));
36977906d00cSAndrea Arcangeli 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
36987906d00cSAndrea Arcangeli 
36997906d00cSAndrea Arcangeli 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
37007906d00cSAndrea Arcangeli 		if (vma->anon_vma)
37015beb4930SRik van Riel 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
37025beb4930SRik van Riel 				vm_unlock_anon_vma(avc->anon_vma);
37037906d00cSAndrea Arcangeli 		if (vma->vm_file && vma->vm_file->f_mapping)
37047906d00cSAndrea Arcangeli 			vm_unlock_mapping(vma->vm_file->f_mapping);
37057906d00cSAndrea Arcangeli 	}
37067906d00cSAndrea Arcangeli 
37077906d00cSAndrea Arcangeli 	mutex_unlock(&mm_all_locks_mutex);
37087906d00cSAndrea Arcangeli }
37098feae131SDavid Howells 
37108feae131SDavid Howells /*
37113edf41d8Sseokhoon.yoon  * initialise the percpu counter for VM
37128feae131SDavid Howells  */
37138feae131SDavid Howells void __init mmap_init(void)
37148feae131SDavid Howells {
371500a62ce9SKOSAKI Motohiro 	int ret;
371600a62ce9SKOSAKI Motohiro 
3717908c7f19STejun Heo 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
371800a62ce9SKOSAKI Motohiro 	VM_BUG_ON(ret);
37198feae131SDavid Howells }
3720c9b1d098SAndrew Shewmaker 
3721c9b1d098SAndrew Shewmaker /*
3722c9b1d098SAndrew Shewmaker  * Initialise sysctl_user_reserve_kbytes.
3723c9b1d098SAndrew Shewmaker  *
3724c9b1d098SAndrew Shewmaker  * This is intended to prevent a user from starting a single memory hogging
3725c9b1d098SAndrew Shewmaker  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3726c9b1d098SAndrew Shewmaker  * mode.
3727c9b1d098SAndrew Shewmaker  *
3728c9b1d098SAndrew Shewmaker  * The default value is min(3% of free memory, 128MB)
3729c9b1d098SAndrew Shewmaker  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3730c9b1d098SAndrew Shewmaker  */
37311640879aSAndrew Shewmaker static int init_user_reserve(void)
3732c9b1d098SAndrew Shewmaker {
3733c9b1d098SAndrew Shewmaker 	unsigned long free_kbytes;
3734c9b1d098SAndrew Shewmaker 
3735c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3736c9b1d098SAndrew Shewmaker 
3737c9b1d098SAndrew Shewmaker 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3738c9b1d098SAndrew Shewmaker 	return 0;
3739c9b1d098SAndrew Shewmaker }
3740a64fb3cdSPaul Gortmaker subsys_initcall(init_user_reserve);
37414eeab4f5SAndrew Shewmaker 
37424eeab4f5SAndrew Shewmaker /*
37434eeab4f5SAndrew Shewmaker  * Initialise sysctl_admin_reserve_kbytes.
37444eeab4f5SAndrew Shewmaker  *
37454eeab4f5SAndrew Shewmaker  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
37464eeab4f5SAndrew Shewmaker  * to log in and kill a memory hogging process.
37474eeab4f5SAndrew Shewmaker  *
37484eeab4f5SAndrew Shewmaker  * Systems with more than 256MB will reserve 8MB, enough to recover
37494eeab4f5SAndrew Shewmaker  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
37504eeab4f5SAndrew Shewmaker  * only reserve 3% of free pages by default.
37514eeab4f5SAndrew Shewmaker  */
37521640879aSAndrew Shewmaker static int init_admin_reserve(void)
37534eeab4f5SAndrew Shewmaker {
37544eeab4f5SAndrew Shewmaker 	unsigned long free_kbytes;
37554eeab4f5SAndrew Shewmaker 
3756c41f012aSMichal Hocko 	free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
37574eeab4f5SAndrew Shewmaker 
37584eeab4f5SAndrew Shewmaker 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
37594eeab4f5SAndrew Shewmaker 	return 0;
37604eeab4f5SAndrew Shewmaker }
3761a64fb3cdSPaul Gortmaker subsys_initcall(init_admin_reserve);
37621640879aSAndrew Shewmaker 
37631640879aSAndrew Shewmaker /*
37641640879aSAndrew Shewmaker  * Reinititalise user and admin reserves if memory is added or removed.
37651640879aSAndrew Shewmaker  *
37661640879aSAndrew Shewmaker  * The default user reserve max is 128MB, and the default max for the
37671640879aSAndrew Shewmaker  * admin reserve is 8MB. These are usually, but not always, enough to
37681640879aSAndrew Shewmaker  * enable recovery from a memory hogging process using login/sshd, a shell,
37691640879aSAndrew Shewmaker  * and tools like top. It may make sense to increase or even disable the
37701640879aSAndrew Shewmaker  * reserve depending on the existence of swap or variations in the recovery
37711640879aSAndrew Shewmaker  * tools. So, the admin may have changed them.
37721640879aSAndrew Shewmaker  *
37731640879aSAndrew Shewmaker  * If memory is added and the reserves have been eliminated or increased above
37741640879aSAndrew Shewmaker  * the default max, then we'll trust the admin.
37751640879aSAndrew Shewmaker  *
37761640879aSAndrew Shewmaker  * If memory is removed and there isn't enough free memory, then we
37771640879aSAndrew Shewmaker  * need to reset the reserves.
37781640879aSAndrew Shewmaker  *
37791640879aSAndrew Shewmaker  * Otherwise keep the reserve set by the admin.
37801640879aSAndrew Shewmaker  */
37811640879aSAndrew Shewmaker static int reserve_mem_notifier(struct notifier_block *nb,
37821640879aSAndrew Shewmaker 			     unsigned long action, void *data)
37831640879aSAndrew Shewmaker {
37841640879aSAndrew Shewmaker 	unsigned long tmp, free_kbytes;
37851640879aSAndrew Shewmaker 
37861640879aSAndrew Shewmaker 	switch (action) {
37871640879aSAndrew Shewmaker 	case MEM_ONLINE:
37881640879aSAndrew Shewmaker 		/* Default max is 128MB. Leave alone if modified by operator. */
37891640879aSAndrew Shewmaker 		tmp = sysctl_user_reserve_kbytes;
37901640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 17))
37911640879aSAndrew Shewmaker 			init_user_reserve();
37921640879aSAndrew Shewmaker 
37931640879aSAndrew Shewmaker 		/* Default max is 8MB.  Leave alone if modified by operator. */
37941640879aSAndrew Shewmaker 		tmp = sysctl_admin_reserve_kbytes;
37951640879aSAndrew Shewmaker 		if (0 < tmp && tmp < (1UL << 13))
37961640879aSAndrew Shewmaker 			init_admin_reserve();
37971640879aSAndrew Shewmaker 
37981640879aSAndrew Shewmaker 		break;
37991640879aSAndrew Shewmaker 	case MEM_OFFLINE:
3800c41f012aSMichal Hocko 		free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
38011640879aSAndrew Shewmaker 
38021640879aSAndrew Shewmaker 		if (sysctl_user_reserve_kbytes > free_kbytes) {
38031640879aSAndrew Shewmaker 			init_user_reserve();
38041640879aSAndrew Shewmaker 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
38051640879aSAndrew Shewmaker 				sysctl_user_reserve_kbytes);
38061640879aSAndrew Shewmaker 		}
38071640879aSAndrew Shewmaker 
38081640879aSAndrew Shewmaker 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
38091640879aSAndrew Shewmaker 			init_admin_reserve();
38101640879aSAndrew Shewmaker 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
38111640879aSAndrew Shewmaker 				sysctl_admin_reserve_kbytes);
38121640879aSAndrew Shewmaker 		}
38131640879aSAndrew Shewmaker 		break;
38141640879aSAndrew Shewmaker 	default:
38151640879aSAndrew Shewmaker 		break;
38161640879aSAndrew Shewmaker 	}
38171640879aSAndrew Shewmaker 	return NOTIFY_OK;
38181640879aSAndrew Shewmaker }
38191640879aSAndrew Shewmaker 
38201640879aSAndrew Shewmaker static struct notifier_block reserve_mem_nb = {
38211640879aSAndrew Shewmaker 	.notifier_call = reserve_mem_notifier,
38221640879aSAndrew Shewmaker };
38231640879aSAndrew Shewmaker 
38241640879aSAndrew Shewmaker static int __meminit init_reserve_notifier(void)
38251640879aSAndrew Shewmaker {
38261640879aSAndrew Shewmaker 	if (register_hotmemory_notifier(&reserve_mem_nb))
3827b1de0d13SMitchel Humpherys 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
38281640879aSAndrew Shewmaker 
38291640879aSAndrew Shewmaker 	return 0;
38301640879aSAndrew Shewmaker }
3831a64fb3cdSPaul Gortmaker subsys_initcall(init_reserve_notifier);
3832