• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * mm/mmap.c
3  *
4  * Written by obz.
5  *
6  * Address space accounting code	<alan@lxorguk.ukuu.org.uk>
7  */
8 
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/kernel.h>
12 #include <linux/slab.h>
13 #include <linux/backing-dev.h>
14 #include <linux/mm.h>
15 #include <linux/vmacache.h>
16 #include <linux/shm.h>
17 #include <linux/mman.h>
18 #include <linux/pagemap.h>
19 #include <linux/swap.h>
20 #include <linux/syscalls.h>
21 #include <linux/capability.h>
22 #include <linux/init.h>
23 #include <linux/file.h>
24 #include <linux/fs.h>
25 #include <linux/personality.h>
26 #include <linux/security.h>
27 #include <linux/hugetlb.h>
28 #include <linux/profile.h>
29 #include <linux/export.h>
30 #include <linux/mount.h>
31 #include <linux/mempolicy.h>
32 #include <linux/rmap.h>
33 #include <linux/mmu_notifier.h>
34 #include <linux/mmdebug.h>
35 #include <linux/perf_event.h>
36 #include <linux/audit.h>
37 #include <linux/khugepaged.h>
38 #include <linux/uprobes.h>
39 #include <linux/rbtree_augmented.h>
40 #include <linux/sched/sysctl.h>
41 #include <linux/notifier.h>
42 #include <linux/memory.h>
43 #include <linux/printk.h>
44 
45 #include <asm/uaccess.h>
46 #include <asm/cacheflush.h>
47 #include <asm/tlb.h>
48 #include <asm/mmu_context.h>
49 
50 #include "internal.h"
51 
52 #ifndef arch_mmap_check
53 #define arch_mmap_check(addr, len, flags)	(0)
54 #endif
55 
56 #ifndef arch_rebalance_pgtables
57 #define arch_rebalance_pgtables(addr, len)		(addr)
58 #endif
59 
60 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
61 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
62 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
63 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
64 #endif
65 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
66 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
67 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
68 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
69 #endif
70 
71 
72 static void unmap_region(struct mm_struct *mm,
73 		struct vm_area_struct *vma, struct vm_area_struct *prev,
74 		unsigned long start, unsigned long end);
75 
76 /* description of effects of mapping type and prot in current implementation.
77  * this is due to the limited x86 page protection hardware.  The expected
78  * behavior is in parens:
79  *
80  * map_type	prot
81  *		PROT_NONE	PROT_READ	PROT_WRITE	PROT_EXEC
82  * MAP_SHARED	r: (no) no	r: (yes) yes	r: (no) yes	r: (no) yes
83  *		w: (no) no	w: (no) no	w: (yes) yes	w: (no) no
84  *		x: (no) no	x: (no) yes	x: (no) yes	x: (yes) yes
85  *
86  * MAP_PRIVATE	r: (no) no	r: (yes) yes	r: (no) yes	r: (no) yes
87  *		w: (no) no	w: (no) no	w: (copy) copy	w: (no) no
88  *		x: (no) no	x: (no) yes	x: (no) yes	x: (yes) yes
89  *
90  */
91 pgprot_t protection_map[16] = {
92 	__P000, __P001, __P010, __P011, __P100, __P101, __P110, __P111,
93 	__S000, __S001, __S010, __S011, __S100, __S101, __S110, __S111
94 };
95 
vm_get_page_prot(unsigned long vm_flags)96 pgprot_t vm_get_page_prot(unsigned long vm_flags)
97 {
98 	return __pgprot(pgprot_val(protection_map[vm_flags &
99 				(VM_READ|VM_WRITE|VM_EXEC|VM_SHARED)]) |
100 			pgprot_val(arch_vm_get_page_prot(vm_flags)));
101 }
102 EXPORT_SYMBOL(vm_get_page_prot);
103 
vm_pgprot_modify(pgprot_t oldprot,unsigned long vm_flags)104 static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
105 {
106 	return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
107 }
108 
109 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
vma_set_page_prot(struct vm_area_struct * vma)110 void vma_set_page_prot(struct vm_area_struct *vma)
111 {
112 	unsigned long vm_flags = vma->vm_flags;
113 
114 	vma->vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
115 	if (vma_wants_writenotify(vma)) {
116 		vm_flags &= ~VM_SHARED;
117 		vma->vm_page_prot = vm_pgprot_modify(vma->vm_page_prot,
118 						     vm_flags);
119 	}
120 }
121 
122 
123 int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;  /* heuristic overcommit */
124 int sysctl_overcommit_ratio __read_mostly = 50;	/* default is 50% */
125 unsigned long sysctl_overcommit_kbytes __read_mostly;
126 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
127 unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
128 unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
129 /*
130  * Make sure vm_committed_as in one cacheline and not cacheline shared with
131  * other variables. It can be updated by several CPUs frequently.
132  */
133 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
134 
135 /*
136  * The global memory commitment made in the system can be a metric
137  * that can be used to drive ballooning decisions when Linux is hosted
138  * as a guest. On Hyper-V, the host implements a policy engine for dynamically
139  * balancing memory across competing virtual machines that are hosted.
140  * Several metrics drive this policy engine including the guest reported
141  * memory commitment.
142  */
vm_memory_committed(void)143 unsigned long vm_memory_committed(void)
144 {
145 	return percpu_counter_read_positive(&vm_committed_as);
146 }
147 EXPORT_SYMBOL_GPL(vm_memory_committed);
148 
149 /*
150  * Check that a process has enough memory to allocate a new virtual
151  * mapping. 0 means there is enough memory for the allocation to
152  * succeed and -ENOMEM implies there is not.
153  *
154  * We currently support three overcommit policies, which are set via the
155  * vm.overcommit_memory sysctl.  See Documentation/vm/overcommit-accounting
156  *
157  * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
158  * Additional code 2002 Jul 20 by Robert Love.
159  *
160  * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
161  *
162  * Note this is a helper function intended to be used by LSMs which
163  * wish to use this logic.
164  */
__vm_enough_memory(struct mm_struct * mm,long pages,int cap_sys_admin)165 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
166 {
167 	long free, allowed, reserve;
168 
169 	VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
170 			-(s64)vm_committed_as_batch * num_online_cpus(),
171 			"memory commitment underflow");
172 
173 	vm_acct_memory(pages);
174 
175 	/*
176 	 * Sometimes we want to use more memory than we have
177 	 */
178 	if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
179 		return 0;
180 
181 	if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
182 		free = global_page_state(NR_FREE_PAGES);
183 		free += global_page_state(NR_FILE_PAGES);
184 
185 		/*
186 		 * shmem pages shouldn't be counted as free in this
187 		 * case, they can't be purged, only swapped out, and
188 		 * that won't affect the overall amount of available
189 		 * memory in the system.
190 		 */
191 		free -= global_page_state(NR_SHMEM);
192 
193 		free += get_nr_swap_pages();
194 
195 		/*
196 		 * Any slabs which are created with the
197 		 * SLAB_RECLAIM_ACCOUNT flag claim to have contents
198 		 * which are reclaimable, under pressure.  The dentry
199 		 * cache and most inode caches should fall into this
200 		 */
201 		free += global_page_state(NR_SLAB_RECLAIMABLE);
202 
203 		/*
204 		 * Leave reserved pages. The pages are not for anonymous pages.
205 		 */
206 		if (free <= totalreserve_pages)
207 			goto error;
208 		else
209 			free -= totalreserve_pages;
210 
211 		/*
212 		 * Reserve some for root
213 		 */
214 		if (!cap_sys_admin)
215 			free -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
216 
217 		if (free > pages)
218 			return 0;
219 
220 		goto error;
221 	}
222 
223 	allowed = vm_commit_limit();
224 	/*
225 	 * Reserve some for root
226 	 */
227 	if (!cap_sys_admin)
228 		allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
229 
230 	/*
231 	 * Don't let a single process grow so big a user can't recover
232 	 */
233 	if (mm) {
234 		reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
235 		allowed -= min_t(long, mm->total_vm / 32, reserve);
236 	}
237 
238 	if (percpu_counter_read_positive(&vm_committed_as) < allowed)
239 		return 0;
240 error:
241 	vm_unacct_memory(pages);
242 
243 	return -ENOMEM;
244 }
245 
246 /*
247  * Requires inode->i_mapping->i_mmap_mutex
248  */
__remove_shared_vm_struct(struct vm_area_struct * vma,struct file * file,struct address_space * mapping)249 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
250 		struct file *file, struct address_space *mapping)
251 {
252 	if (vma->vm_flags & VM_DENYWRITE)
253 		atomic_inc(&file_inode(file)->i_writecount);
254 	if (vma->vm_flags & VM_SHARED)
255 		mapping_unmap_writable(mapping);
256 
257 	flush_dcache_mmap_lock(mapping);
258 	if (unlikely(vma->vm_flags & VM_NONLINEAR))
259 		list_del_init(&vma->shared.nonlinear);
260 	else
261 		vma_interval_tree_remove(vma, &mapping->i_mmap);
262 	flush_dcache_mmap_unlock(mapping);
263 }
264 
265 /*
266  * Unlink a file-based vm structure from its interval tree, to hide
267  * vma from rmap and vmtruncate before freeing its page tables.
268  */
unlink_file_vma(struct vm_area_struct * vma)269 void unlink_file_vma(struct vm_area_struct *vma)
270 {
271 	struct file *file = vma->vm_file;
272 
273 	if (file) {
274 		struct address_space *mapping = file->f_mapping;
275 		mutex_lock(&mapping->i_mmap_mutex);
276 		__remove_shared_vm_struct(vma, file, mapping);
277 		mutex_unlock(&mapping->i_mmap_mutex);
278 	}
279 }
280 
281 /*
282  * Close a vm structure and free it, returning the next.
283  */
remove_vma(struct vm_area_struct * vma)284 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
285 {
286 	struct vm_area_struct *next = vma->vm_next;
287 
288 	might_sleep();
289 	if (vma->vm_ops && vma->vm_ops->close)
290 		vma->vm_ops->close(vma);
291 	if (vma->vm_file)
292 		fput(vma->vm_file);
293 	mpol_put(vma_policy(vma));
294 	kmem_cache_free(vm_area_cachep, vma);
295 	return next;
296 }
297 
298 static unsigned long do_brk(unsigned long addr, unsigned long len);
299 
SYSCALL_DEFINE1(brk,unsigned long,brk)300 SYSCALL_DEFINE1(brk, unsigned long, brk)
301 {
302 	unsigned long retval;
303 	unsigned long newbrk, oldbrk;
304 	struct mm_struct *mm = current->mm;
305 	struct vm_area_struct *next;
306 	unsigned long min_brk;
307 	bool populate;
308 
309 	down_write(&mm->mmap_sem);
310 
311 #ifdef CONFIG_COMPAT_BRK
312 	/*
313 	 * CONFIG_COMPAT_BRK can still be overridden by setting
314 	 * randomize_va_space to 2, which will still cause mm->start_brk
315 	 * to be arbitrarily shifted
316 	 */
317 	if (current->brk_randomized)
318 		min_brk = mm->start_brk;
319 	else
320 		min_brk = mm->end_data;
321 #else
322 	min_brk = mm->start_brk;
323 #endif
324 	if (brk < min_brk)
325 		goto out;
326 
327 	/*
328 	 * Check against rlimit here. If this check is done later after the test
329 	 * of oldbrk with newbrk then it can escape the test and let the data
330 	 * segment grow beyond its set limit the in case where the limit is
331 	 * not page aligned -Ram Gupta
332 	 */
333 	if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
334 			      mm->end_data, mm->start_data))
335 		goto out;
336 
337 	newbrk = PAGE_ALIGN(brk);
338 	oldbrk = PAGE_ALIGN(mm->brk);
339 	if (oldbrk == newbrk)
340 		goto set_brk;
341 
342 	/* Always allow shrinking brk. */
343 	if (brk <= mm->brk) {
344 		if (!do_munmap(mm, newbrk, oldbrk-newbrk))
345 			goto set_brk;
346 		goto out;
347 	}
348 
349 	/* Check against existing mmap mappings. */
350 	next = find_vma(mm, oldbrk);
351 	if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
352 		goto out;
353 
354 	/* Ok, looks good - let it rip. */
355 	if (do_brk(oldbrk, newbrk-oldbrk) != oldbrk)
356 		goto out;
357 
358 set_brk:
359 	mm->brk = brk;
360 	populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
361 	up_write(&mm->mmap_sem);
362 	if (populate)
363 		mm_populate(oldbrk, newbrk - oldbrk);
364 	return brk;
365 
366 out:
367 	retval = mm->brk;
368 	up_write(&mm->mmap_sem);
369 	return retval;
370 }
371 
vma_compute_subtree_gap(struct vm_area_struct * vma)372 static long vma_compute_subtree_gap(struct vm_area_struct *vma)
373 {
374 	unsigned long max, prev_end, subtree_gap;
375 
376 	/*
377 	 * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
378 	 * allow two stack_guard_gaps between them here, and when choosing
379 	 * an unmapped area; whereas when expanding we only require one.
380 	 * That's a little inconsistent, but keeps the code here simpler.
381 	 */
382 	max = vm_start_gap(vma);
383 	if (vma->vm_prev) {
384 		prev_end = vm_end_gap(vma->vm_prev);
385 		if (max > prev_end)
386 			max -= prev_end;
387 		else
388 			max = 0;
389 	}
390 	if (vma->vm_rb.rb_left) {
391 		subtree_gap = rb_entry(vma->vm_rb.rb_left,
392 				struct vm_area_struct, vm_rb)->rb_subtree_gap;
393 		if (subtree_gap > max)
394 			max = subtree_gap;
395 	}
396 	if (vma->vm_rb.rb_right) {
397 		subtree_gap = rb_entry(vma->vm_rb.rb_right,
398 				struct vm_area_struct, vm_rb)->rb_subtree_gap;
399 		if (subtree_gap > max)
400 			max = subtree_gap;
401 	}
402 	return max;
403 }
404 
405 #ifdef CONFIG_DEBUG_VM_RB
browse_rb(struct rb_root * root)406 static int browse_rb(struct rb_root *root)
407 {
408 	int i = 0, j, bug = 0;
409 	struct rb_node *nd, *pn = NULL;
410 	unsigned long prev = 0, pend = 0;
411 
412 	for (nd = rb_first(root); nd; nd = rb_next(nd)) {
413 		struct vm_area_struct *vma;
414 		vma = rb_entry(nd, struct vm_area_struct, vm_rb);
415 		if (vma->vm_start < prev) {
416 			pr_emerg("vm_start %lx < prev %lx\n",
417 				  vma->vm_start, prev);
418 			bug = 1;
419 		}
420 		if (vma->vm_start < pend) {
421 			pr_emerg("vm_start %lx < pend %lx\n",
422 				  vma->vm_start, pend);
423 			bug = 1;
424 		}
425 		if (vma->vm_start > vma->vm_end) {
426 			pr_emerg("vm_start %lx > vm_end %lx\n",
427 				  vma->vm_start, vma->vm_end);
428 			bug = 1;
429 		}
430 		if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
431 			pr_emerg("free gap %lx, correct %lx\n",
432 			       vma->rb_subtree_gap,
433 			       vma_compute_subtree_gap(vma));
434 			bug = 1;
435 		}
436 		i++;
437 		pn = nd;
438 		prev = vma->vm_start;
439 		pend = vma->vm_end;
440 	}
441 	j = 0;
442 	for (nd = pn; nd; nd = rb_prev(nd))
443 		j++;
444 	if (i != j) {
445 		pr_emerg("backwards %d, forwards %d\n", j, i);
446 		bug = 1;
447 	}
448 	return bug ? -1 : i;
449 }
450 
validate_mm_rb(struct rb_root * root,struct vm_area_struct * ignore)451 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
452 {
453 	struct rb_node *nd;
454 
455 	for (nd = rb_first(root); nd; nd = rb_next(nd)) {
456 		struct vm_area_struct *vma;
457 		vma = rb_entry(nd, struct vm_area_struct, vm_rb);
458 		VM_BUG_ON_VMA(vma != ignore &&
459 			vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
460 			vma);
461 	}
462 }
463 
validate_mm(struct mm_struct * mm)464 static void validate_mm(struct mm_struct *mm)
465 {
466 	int bug = 0;
467 	int i = 0;
468 	unsigned long highest_address = 0;
469 	struct vm_area_struct *vma = mm->mmap;
470 
471 	while (vma) {
472 		struct anon_vma *anon_vma = vma->anon_vma;
473 		struct anon_vma_chain *avc;
474 
475 		if (anon_vma) {
476 			anon_vma_lock_read(anon_vma);
477 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
478 				anon_vma_interval_tree_verify(avc);
479 			anon_vma_unlock_read(anon_vma);
480 		}
481 
482 		highest_address = vm_end_gap(vma);
483 		vma = vma->vm_next;
484 		i++;
485 	}
486 	if (i != mm->map_count) {
487 		pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
488 		bug = 1;
489 	}
490 	if (highest_address != mm->highest_vm_end) {
491 		pr_emerg("mm->highest_vm_end %lx, found %lx\n",
492 			  mm->highest_vm_end, highest_address);
493 		bug = 1;
494 	}
495 	i = browse_rb(&mm->mm_rb);
496 	if (i != mm->map_count) {
497 		if (i != -1)
498 			pr_emerg("map_count %d rb %d\n", mm->map_count, i);
499 		bug = 1;
500 	}
501 	VM_BUG_ON_MM(bug, mm);
502 }
503 #else
504 #define validate_mm_rb(root, ignore) do { } while (0)
505 #define validate_mm(mm) do { } while (0)
506 #endif
507 
RB_DECLARE_CALLBACKS(static,vma_gap_callbacks,struct vm_area_struct,vm_rb,unsigned long,rb_subtree_gap,vma_compute_subtree_gap)508 RB_DECLARE_CALLBACKS(static, vma_gap_callbacks, struct vm_area_struct, vm_rb,
509 		     unsigned long, rb_subtree_gap, vma_compute_subtree_gap)
510 
511 /*
512  * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
513  * vma->vm_prev->vm_end values changed, without modifying the vma's position
514  * in the rbtree.
515  */
516 static void vma_gap_update(struct vm_area_struct *vma)
517 {
518 	/*
519 	 * As it turns out, RB_DECLARE_CALLBACKS() already created a callback
520 	 * function that does exacltly what we want.
521 	 */
522 	vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
523 }
524 
vma_rb_insert(struct vm_area_struct * vma,struct rb_root * root)525 static inline void vma_rb_insert(struct vm_area_struct *vma,
526 				 struct rb_root *root)
527 {
528 	/* All rb_subtree_gap values must be consistent prior to insertion */
529 	validate_mm_rb(root, NULL);
530 
531 	rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
532 }
533 
vma_rb_erase(struct vm_area_struct * vma,struct rb_root * root)534 static void vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
535 {
536 	/*
537 	 * All rb_subtree_gap values must be consistent prior to erase,
538 	 * with the possible exception of the vma being erased.
539 	 */
540 	validate_mm_rb(root, vma);
541 
542 	/*
543 	 * Note rb_erase_augmented is a fairly large inline function,
544 	 * so make sure we instantiate it only once with our desired
545 	 * augmented rbtree callbacks.
546 	 */
547 	rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
548 }
549 
550 /*
551  * vma has some anon_vma assigned, and is already inserted on that
552  * anon_vma's interval trees.
553  *
554  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
555  * vma must be removed from the anon_vma's interval trees using
556  * anon_vma_interval_tree_pre_update_vma().
557  *
558  * After the update, the vma will be reinserted using
559  * anon_vma_interval_tree_post_update_vma().
560  *
561  * The entire update must be protected by exclusive mmap_sem and by
562  * the root anon_vma's mutex.
563  */
564 static inline void
anon_vma_interval_tree_pre_update_vma(struct vm_area_struct * vma)565 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
566 {
567 	struct anon_vma_chain *avc;
568 
569 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
570 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
571 }
572 
573 static inline void
anon_vma_interval_tree_post_update_vma(struct vm_area_struct * vma)574 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
575 {
576 	struct anon_vma_chain *avc;
577 
578 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
579 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
580 }
581 
find_vma_links(struct mm_struct * mm,unsigned long addr,unsigned long end,struct vm_area_struct ** pprev,struct rb_node *** rb_link,struct rb_node ** rb_parent)582 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
583 		unsigned long end, struct vm_area_struct **pprev,
584 		struct rb_node ***rb_link, struct rb_node **rb_parent)
585 {
586 	struct rb_node **__rb_link, *__rb_parent, *rb_prev;
587 
588 	__rb_link = &mm->mm_rb.rb_node;
589 	rb_prev = __rb_parent = NULL;
590 
591 	while (*__rb_link) {
592 		struct vm_area_struct *vma_tmp;
593 
594 		__rb_parent = *__rb_link;
595 		vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
596 
597 		if (vma_tmp->vm_end > addr) {
598 			/* Fail if an existing vma overlaps the area */
599 			if (vma_tmp->vm_start < end)
600 				return -ENOMEM;
601 			__rb_link = &__rb_parent->rb_left;
602 		} else {
603 			rb_prev = __rb_parent;
604 			__rb_link = &__rb_parent->rb_right;
605 		}
606 	}
607 
608 	*pprev = NULL;
609 	if (rb_prev)
610 		*pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
611 	*rb_link = __rb_link;
612 	*rb_parent = __rb_parent;
613 	return 0;
614 }
615 
count_vma_pages_range(struct mm_struct * mm,unsigned long addr,unsigned long end)616 static unsigned long count_vma_pages_range(struct mm_struct *mm,
617 		unsigned long addr, unsigned long end)
618 {
619 	unsigned long nr_pages = 0;
620 	struct vm_area_struct *vma;
621 
622 	/* Find first overlaping mapping */
623 	vma = find_vma_intersection(mm, addr, end);
624 	if (!vma)
625 		return 0;
626 
627 	nr_pages = (min(end, vma->vm_end) -
628 		max(addr, vma->vm_start)) >> PAGE_SHIFT;
629 
630 	/* Iterate over the rest of the overlaps */
631 	for (vma = vma->vm_next; vma; vma = vma->vm_next) {
632 		unsigned long overlap_len;
633 
634 		if (vma->vm_start > end)
635 			break;
636 
637 		overlap_len = min(end, vma->vm_end) - vma->vm_start;
638 		nr_pages += overlap_len >> PAGE_SHIFT;
639 	}
640 
641 	return nr_pages;
642 }
643 
__vma_link_rb(struct mm_struct * mm,struct vm_area_struct * vma,struct rb_node ** rb_link,struct rb_node * rb_parent)644 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
645 		struct rb_node **rb_link, struct rb_node *rb_parent)
646 {
647 	/* Update tracking information for the gap following the new vma. */
648 	if (vma->vm_next)
649 		vma_gap_update(vma->vm_next);
650 	else
651 		mm->highest_vm_end = vm_end_gap(vma);
652 
653 	/*
654 	 * vma->vm_prev wasn't known when we followed the rbtree to find the
655 	 * correct insertion point for that vma. As a result, we could not
656 	 * update the vma vm_rb parents rb_subtree_gap values on the way down.
657 	 * So, we first insert the vma with a zero rb_subtree_gap value
658 	 * (to be consistent with what we did on the way down), and then
659 	 * immediately update the gap to the correct value. Finally we
660 	 * rebalance the rbtree after all augmented values have been set.
661 	 */
662 	rb_link_node(&vma->vm_rb, rb_parent, rb_link);
663 	vma->rb_subtree_gap = 0;
664 	vma_gap_update(vma);
665 	vma_rb_insert(vma, &mm->mm_rb);
666 }
667 
__vma_link_file(struct vm_area_struct * vma)668 static void __vma_link_file(struct vm_area_struct *vma)
669 {
670 	struct file *file;
671 
672 	file = vma->vm_file;
673 	if (file) {
674 		struct address_space *mapping = file->f_mapping;
675 
676 		if (vma->vm_flags & VM_DENYWRITE)
677 			atomic_dec(&file_inode(file)->i_writecount);
678 		if (vma->vm_flags & VM_SHARED)
679 			atomic_inc(&mapping->i_mmap_writable);
680 
681 		flush_dcache_mmap_lock(mapping);
682 		if (unlikely(vma->vm_flags & VM_NONLINEAR))
683 			vma_nonlinear_insert(vma, &mapping->i_mmap_nonlinear);
684 		else
685 			vma_interval_tree_insert(vma, &mapping->i_mmap);
686 		flush_dcache_mmap_unlock(mapping);
687 	}
688 }
689 
690 static void
__vma_link(struct mm_struct * mm,struct vm_area_struct * vma,struct vm_area_struct * prev,struct rb_node ** rb_link,struct rb_node * rb_parent)691 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
692 	struct vm_area_struct *prev, struct rb_node **rb_link,
693 	struct rb_node *rb_parent)
694 {
695 	__vma_link_list(mm, vma, prev, rb_parent);
696 	__vma_link_rb(mm, vma, rb_link, rb_parent);
697 }
698 
vma_link(struct mm_struct * mm,struct vm_area_struct * vma,struct vm_area_struct * prev,struct rb_node ** rb_link,struct rb_node * rb_parent)699 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
700 			struct vm_area_struct *prev, struct rb_node **rb_link,
701 			struct rb_node *rb_parent)
702 {
703 	struct address_space *mapping = NULL;
704 
705 	if (vma->vm_file) {
706 		mapping = vma->vm_file->f_mapping;
707 		mutex_lock(&mapping->i_mmap_mutex);
708 	}
709 
710 	__vma_link(mm, vma, prev, rb_link, rb_parent);
711 	__vma_link_file(vma);
712 
713 	if (mapping)
714 		mutex_unlock(&mapping->i_mmap_mutex);
715 
716 	mm->map_count++;
717 	validate_mm(mm);
718 }
719 
720 /*
721  * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
722  * mm's list and rbtree.  It has already been inserted into the interval tree.
723  */
__insert_vm_struct(struct mm_struct * mm,struct vm_area_struct * vma)724 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
725 {
726 	struct vm_area_struct *prev;
727 	struct rb_node **rb_link, *rb_parent;
728 
729 	if (find_vma_links(mm, vma->vm_start, vma->vm_end,
730 			   &prev, &rb_link, &rb_parent))
731 		BUG();
732 	__vma_link(mm, vma, prev, rb_link, rb_parent);
733 	mm->map_count++;
734 }
735 
736 static inline void
__vma_unlink(struct mm_struct * mm,struct vm_area_struct * vma,struct vm_area_struct * prev)737 __vma_unlink(struct mm_struct *mm, struct vm_area_struct *vma,
738 		struct vm_area_struct *prev)
739 {
740 	struct vm_area_struct *next;
741 
742 	vma_rb_erase(vma, &mm->mm_rb);
743 	prev->vm_next = next = vma->vm_next;
744 	if (next)
745 		next->vm_prev = prev;
746 
747 	/* Kill the cache */
748 	vmacache_invalidate(mm);
749 }
750 
751 /*
752  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
753  * is already present in an i_mmap tree without adjusting the tree.
754  * The following helper function should be used when such adjustments
755  * are necessary.  The "insert" vma (if any) is to be inserted
756  * before we drop the necessary locks.
757  */
vma_adjust(struct vm_area_struct * vma,unsigned long start,unsigned long end,pgoff_t pgoff,struct vm_area_struct * insert)758 int vma_adjust(struct vm_area_struct *vma, unsigned long start,
759 	unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert)
760 {
761 	struct mm_struct *mm = vma->vm_mm;
762 	struct vm_area_struct *next = vma->vm_next;
763 	struct vm_area_struct *importer = NULL;
764 	struct address_space *mapping = NULL;
765 	struct rb_root *root = NULL;
766 	struct anon_vma *anon_vma = NULL;
767 	struct file *file = vma->vm_file;
768 	bool start_changed = false, end_changed = false;
769 	long adjust_next = 0;
770 	int remove_next = 0;
771 
772 	if (next && !insert) {
773 		struct vm_area_struct *exporter = NULL;
774 
775 		if (end >= next->vm_end) {
776 			/*
777 			 * vma expands, overlapping all the next, and
778 			 * perhaps the one after too (mprotect case 6).
779 			 */
780 again:			remove_next = 1 + (end > next->vm_end);
781 			end = next->vm_end;
782 			exporter = next;
783 			importer = vma;
784 		} else if (end > next->vm_start) {
785 			/*
786 			 * vma expands, overlapping part of the next:
787 			 * mprotect case 5 shifting the boundary up.
788 			 */
789 			adjust_next = (end - next->vm_start) >> PAGE_SHIFT;
790 			exporter = next;
791 			importer = vma;
792 		} else if (end < vma->vm_end) {
793 			/*
794 			 * vma shrinks, and !insert tells it's not
795 			 * split_vma inserting another: so it must be
796 			 * mprotect case 4 shifting the boundary down.
797 			 */
798 			adjust_next = -((vma->vm_end - end) >> PAGE_SHIFT);
799 			exporter = vma;
800 			importer = next;
801 		}
802 
803 		/*
804 		 * Easily overlooked: when mprotect shifts the boundary,
805 		 * make sure the expanding vma has anon_vma set if the
806 		 * shrinking vma had, to cover any anon pages imported.
807 		 */
808 		if (exporter && exporter->anon_vma && !importer->anon_vma) {
809 			int error;
810 
811 			importer->anon_vma = exporter->anon_vma;
812 			error = anon_vma_clone(importer, exporter);
813 			if (error)
814 				return error;
815 		}
816 	}
817 
818 	if (file) {
819 		mapping = file->f_mapping;
820 		if (!(vma->vm_flags & VM_NONLINEAR)) {
821 			root = &mapping->i_mmap;
822 			uprobe_munmap(vma, vma->vm_start, vma->vm_end);
823 
824 			if (adjust_next)
825 				uprobe_munmap(next, next->vm_start,
826 							next->vm_end);
827 		}
828 
829 		mutex_lock(&mapping->i_mmap_mutex);
830 		if (insert) {
831 			/*
832 			 * Put into interval tree now, so instantiated pages
833 			 * are visible to arm/parisc __flush_dcache_page
834 			 * throughout; but we cannot insert into address
835 			 * space until vma start or end is updated.
836 			 */
837 			__vma_link_file(insert);
838 		}
839 	}
840 
841 	vma_adjust_trans_huge(vma, start, end, adjust_next);
842 
843 	anon_vma = vma->anon_vma;
844 	if (!anon_vma && adjust_next)
845 		anon_vma = next->anon_vma;
846 	if (anon_vma) {
847 		VM_BUG_ON_VMA(adjust_next && next->anon_vma &&
848 			  anon_vma != next->anon_vma, next);
849 		anon_vma_lock_write(anon_vma);
850 		anon_vma_interval_tree_pre_update_vma(vma);
851 		if (adjust_next)
852 			anon_vma_interval_tree_pre_update_vma(next);
853 	}
854 
855 	if (root) {
856 		flush_dcache_mmap_lock(mapping);
857 		vma_interval_tree_remove(vma, root);
858 		if (adjust_next)
859 			vma_interval_tree_remove(next, root);
860 	}
861 
862 	if (start != vma->vm_start) {
863 		vma->vm_start = start;
864 		start_changed = true;
865 	}
866 	if (end != vma->vm_end) {
867 		vma->vm_end = end;
868 		end_changed = true;
869 	}
870 	vma->vm_pgoff = pgoff;
871 	if (adjust_next) {
872 		next->vm_start += adjust_next << PAGE_SHIFT;
873 		next->vm_pgoff += adjust_next;
874 	}
875 
876 	if (root) {
877 		if (adjust_next)
878 			vma_interval_tree_insert(next, root);
879 		vma_interval_tree_insert(vma, root);
880 		flush_dcache_mmap_unlock(mapping);
881 	}
882 
883 	if (remove_next) {
884 		/*
885 		 * vma_merge has merged next into vma, and needs
886 		 * us to remove next before dropping the locks.
887 		 */
888 		__vma_unlink(mm, next, vma);
889 		if (file)
890 			__remove_shared_vm_struct(next, file, mapping);
891 	} else if (insert) {
892 		/*
893 		 * split_vma has split insert from vma, and needs
894 		 * us to insert it before dropping the locks
895 		 * (it may either follow vma or precede it).
896 		 */
897 		__insert_vm_struct(mm, insert);
898 	} else {
899 		if (start_changed)
900 			vma_gap_update(vma);
901 		if (end_changed) {
902 			if (!next)
903 				mm->highest_vm_end = vm_end_gap(vma);
904 			else if (!adjust_next)
905 				vma_gap_update(next);
906 		}
907 	}
908 
909 	if (anon_vma) {
910 		anon_vma_interval_tree_post_update_vma(vma);
911 		if (adjust_next)
912 			anon_vma_interval_tree_post_update_vma(next);
913 		anon_vma_unlock_write(anon_vma);
914 	}
915 	if (mapping)
916 		mutex_unlock(&mapping->i_mmap_mutex);
917 
918 	if (root) {
919 		uprobe_mmap(vma);
920 
921 		if (adjust_next)
922 			uprobe_mmap(next);
923 	}
924 
925 	if (remove_next) {
926 		if (file) {
927 			uprobe_munmap(next, next->vm_start, next->vm_end);
928 			fput(file);
929 		}
930 		if (next->anon_vma)
931 			anon_vma_merge(vma, next);
932 		mm->map_count--;
933 		mpol_put(vma_policy(next));
934 		kmem_cache_free(vm_area_cachep, next);
935 		/*
936 		 * In mprotect's case 6 (see comments on vma_merge),
937 		 * we must remove another next too. It would clutter
938 		 * up the code too much to do both in one go.
939 		 */
940 		next = vma->vm_next;
941 		if (remove_next == 2)
942 			goto again;
943 		else if (next)
944 			vma_gap_update(next);
945 		else
946 			VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
947 	}
948 	if (insert && file)
949 		uprobe_mmap(insert);
950 
951 	validate_mm(mm);
952 
953 	return 0;
954 }
955 
956 /*
957  * If the vma has a ->close operation then the driver probably needs to release
958  * per-vma resources, so we don't attempt to merge those.
959  */
is_mergeable_vma(struct vm_area_struct * vma,struct file * file,unsigned long vm_flags,const char __user * anon_name)960 static inline int is_mergeable_vma(struct vm_area_struct *vma,
961 			struct file *file, unsigned long vm_flags,
962 			const char __user *anon_name)
963 {
964 	/*
965 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
966 	 * match the flags but dirty bit -- the caller should mark
967 	 * merged VMA as dirty. If dirty bit won't be excluded from
968 	 * comparison, we increase pressue on the memory system forcing
969 	 * the kernel to generate new VMAs when old one could be
970 	 * extended instead.
971 	 */
972 	if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
973 		return 0;
974 	if (vma->vm_file != file)
975 		return 0;
976 	if (vma->vm_ops && vma->vm_ops->close)
977 		return 0;
978 	if (vma_get_anon_name(vma) != anon_name)
979 		return 0;
980 	return 1;
981 }
982 
is_mergeable_anon_vma(struct anon_vma * anon_vma1,struct anon_vma * anon_vma2,struct vm_area_struct * vma)983 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
984 					struct anon_vma *anon_vma2,
985 					struct vm_area_struct *vma)
986 {
987 	/*
988 	 * The list_is_singular() test is to avoid merging VMA cloned from
989 	 * parents. This can improve scalability caused by anon_vma lock.
990 	 */
991 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
992 		list_is_singular(&vma->anon_vma_chain)))
993 		return 1;
994 	return anon_vma1 == anon_vma2;
995 }
996 
997 /*
998  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
999  * in front of (at a lower virtual address and file offset than) the vma.
1000  *
1001  * We cannot merge two vmas if they have differently assigned (non-NULL)
1002  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1003  *
1004  * We don't check here for the merged mmap wrapping around the end of pagecache
1005  * indices (16TB on ia32) because do_mmap_pgoff() does not permit mmap's which
1006  * wrap, nor mmaps which cover the final page at index -1UL.
1007  */
1008 static int
can_vma_merge_before(struct vm_area_struct * vma,unsigned long vm_flags,struct anon_vma * anon_vma,struct file * file,pgoff_t vm_pgoff,const char __user * anon_name)1009 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
1010 	struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff,
1011 	const char __user *anon_name)
1012 {
1013 	if (is_mergeable_vma(vma, file, vm_flags, anon_name) &&
1014 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1015 		if (vma->vm_pgoff == vm_pgoff)
1016 			return 1;
1017 	}
1018 	return 0;
1019 }
1020 
1021 /*
1022  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1023  * beyond (at a higher virtual address and file offset than) the vma.
1024  *
1025  * We cannot merge two vmas if they have differently assigned (non-NULL)
1026  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1027  */
1028 static int
can_vma_merge_after(struct vm_area_struct * vma,unsigned long vm_flags,struct anon_vma * anon_vma,struct file * file,pgoff_t vm_pgoff,const char __user * anon_name)1029 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
1030 	struct anon_vma *anon_vma, struct file *file, pgoff_t vm_pgoff,
1031 	const char __user *anon_name)
1032 {
1033 	if (is_mergeable_vma(vma, file, vm_flags, anon_name) &&
1034 	    is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1035 		pgoff_t vm_pglen;
1036 		vm_pglen = vma_pages(vma);
1037 		if (vma->vm_pgoff + vm_pglen == vm_pgoff)
1038 			return 1;
1039 	}
1040 	return 0;
1041 }
1042 
1043 /*
1044  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
1045  * figure out whether that can be merged with its predecessor or its
1046  * successor.  Or both (it neatly fills a hole).
1047  *
1048  * In most cases - when called for mmap, brk or mremap - [addr,end) is
1049  * certain not to be mapped by the time vma_merge is called; but when
1050  * called for mprotect, it is certain to be already mapped (either at
1051  * an offset within prev, or at the start of next), and the flags of
1052  * this area are about to be changed to vm_flags - and the no-change
1053  * case has already been eliminated.
1054  *
1055  * The following mprotect cases have to be considered, where AAAA is
1056  * the area passed down from mprotect_fixup, never extending beyond one
1057  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
1058  *
1059  *     AAAA             AAAA                AAAA          AAAA
1060  *    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPPPNNNNNN    PPPPNNNNXXXX
1061  *    cannot merge    might become    might become    might become
1062  *                    PPNNNNNNNNNN    PPPPPPPPPPNN    PPPPPPPPPPPP 6 or
1063  *    mmap, brk or    case 4 below    case 5 below    PPPPPPPPXXXX 7 or
1064  *    mremap move:                                    PPPPNNNNNNNN 8
1065  *        AAAA
1066  *    PPPP    NNNN    PPPPPPPPPPPP    PPPPPPPPNNNN    PPPPNNNNNNNN
1067  *    might become    case 1 below    case 2 below    case 3 below
1068  *
1069  * Odd one out? Case 8, because it extends NNNN but needs flags of XXXX:
1070  * mprotect_fixup updates vm_flags & vm_page_prot on successful return.
1071  */
vma_merge(struct mm_struct * mm,struct vm_area_struct * prev,unsigned long addr,unsigned long end,unsigned long vm_flags,struct anon_vma * anon_vma,struct file * file,pgoff_t pgoff,struct mempolicy * policy,const char __user * anon_name)1072 struct vm_area_struct *vma_merge(struct mm_struct *mm,
1073 			struct vm_area_struct *prev, unsigned long addr,
1074 			unsigned long end, unsigned long vm_flags,
1075 		    struct anon_vma *anon_vma, struct file *file,
1076 			pgoff_t pgoff, struct mempolicy *policy,
1077 			const char __user *anon_name)
1078 {
1079 	pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
1080 	struct vm_area_struct *area, *next;
1081 	int err;
1082 
1083 	/*
1084 	 * We later require that vma->vm_flags == vm_flags,
1085 	 * so this tests vma->vm_flags & VM_SPECIAL, too.
1086 	 */
1087 	if (vm_flags & VM_SPECIAL)
1088 		return NULL;
1089 
1090 	if (prev)
1091 		next = prev->vm_next;
1092 	else
1093 		next = mm->mmap;
1094 	area = next;
1095 	if (next && next->vm_end == end)		/* cases 6, 7, 8 */
1096 		next = next->vm_next;
1097 
1098 	/*
1099 	 * Can it merge with the predecessor?
1100 	 */
1101 	if (prev && prev->vm_end == addr &&
1102   			mpol_equal(vma_policy(prev), policy) &&
1103 			can_vma_merge_after(prev, vm_flags, anon_vma,
1104 						file, pgoff, anon_name)) {
1105 		/*
1106 		 * OK, it can.  Can we now merge in the successor as well?
1107 		 */
1108 		if (next && end == next->vm_start &&
1109 				mpol_equal(policy, vma_policy(next)) &&
1110 				can_vma_merge_before(next, vm_flags, anon_vma,
1111 						file, pgoff+pglen, anon_name) &&
1112 				is_mergeable_anon_vma(prev->anon_vma,
1113 						      next->anon_vma, NULL)) {
1114 							/* cases 1, 6 */
1115 			err = vma_adjust(prev, prev->vm_start,
1116 				next->vm_end, prev->vm_pgoff, NULL);
1117 		} else					/* cases 2, 5, 7 */
1118 			err = vma_adjust(prev, prev->vm_start,
1119 				end, prev->vm_pgoff, NULL);
1120 		if (err)
1121 			return NULL;
1122 		khugepaged_enter_vma_merge(prev, vm_flags);
1123 		return prev;
1124 	}
1125 
1126 	/*
1127 	 * Can this new request be merged in front of next?
1128 	 */
1129 	if (next && end == next->vm_start &&
1130  			mpol_equal(policy, vma_policy(next)) &&
1131 			can_vma_merge_before(next, vm_flags, anon_vma,
1132 					file, pgoff+pglen, anon_name)) {
1133 		if (prev && addr < prev->vm_end)	/* case 4 */
1134 			err = vma_adjust(prev, prev->vm_start,
1135 				addr, prev->vm_pgoff, NULL);
1136 		else					/* cases 3, 8 */
1137 			err = vma_adjust(area, addr, next->vm_end,
1138 				next->vm_pgoff - pglen, NULL);
1139 		if (err)
1140 			return NULL;
1141 		khugepaged_enter_vma_merge(area, vm_flags);
1142 		return area;
1143 	}
1144 
1145 	return NULL;
1146 }
1147 
1148 /*
1149  * Rough compatbility check to quickly see if it's even worth looking
1150  * at sharing an anon_vma.
1151  *
1152  * They need to have the same vm_file, and the flags can only differ
1153  * in things that mprotect may change.
1154  *
1155  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1156  * we can merge the two vma's. For example, we refuse to merge a vma if
1157  * there is a vm_ops->close() function, because that indicates that the
1158  * driver is doing some kind of reference counting. But that doesn't
1159  * really matter for the anon_vma sharing case.
1160  */
anon_vma_compatible(struct vm_area_struct * a,struct vm_area_struct * b)1161 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1162 {
1163 	return a->vm_end == b->vm_start &&
1164 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1165 		a->vm_file == b->vm_file &&
1166 		!((a->vm_flags ^ b->vm_flags) & ~(VM_READ|VM_WRITE|VM_EXEC|VM_SOFTDIRTY)) &&
1167 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1168 }
1169 
1170 /*
1171  * Do some basic sanity checking to see if we can re-use the anon_vma
1172  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1173  * the same as 'old', the other will be the new one that is trying
1174  * to share the anon_vma.
1175  *
1176  * NOTE! This runs with mm_sem held for reading, so it is possible that
1177  * the anon_vma of 'old' is concurrently in the process of being set up
1178  * by another page fault trying to merge _that_. But that's ok: if it
1179  * is being set up, that automatically means that it will be a singleton
1180  * acceptable for merging, so we can do all of this optimistically. But
1181  * we do that ACCESS_ONCE() to make sure that we never re-load the pointer.
1182  *
1183  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1184  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1185  * is to return an anon_vma that is "complex" due to having gone through
1186  * a fork).
1187  *
1188  * We also make sure that the two vma's are compatible (adjacent,
1189  * and with the same memory policies). That's all stable, even with just
1190  * a read lock on the mm_sem.
1191  */
reusable_anon_vma(struct vm_area_struct * old,struct vm_area_struct * a,struct vm_area_struct * b)1192 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1193 {
1194 	if (anon_vma_compatible(a, b)) {
1195 		struct anon_vma *anon_vma = ACCESS_ONCE(old->anon_vma);
1196 
1197 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1198 			return anon_vma;
1199 	}
1200 	return NULL;
1201 }
1202 
1203 /*
1204  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1205  * neighbouring vmas for a suitable anon_vma, before it goes off
1206  * to allocate a new anon_vma.  It checks because a repetitive
1207  * sequence of mprotects and faults may otherwise lead to distinct
1208  * anon_vmas being allocated, preventing vma merge in subsequent
1209  * mprotect.
1210  */
find_mergeable_anon_vma(struct vm_area_struct * vma)1211 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1212 {
1213 	struct anon_vma *anon_vma;
1214 	struct vm_area_struct *near;
1215 
1216 	near = vma->vm_next;
1217 	if (!near)
1218 		goto try_prev;
1219 
1220 	anon_vma = reusable_anon_vma(near, vma, near);
1221 	if (anon_vma)
1222 		return anon_vma;
1223 try_prev:
1224 	near = vma->vm_prev;
1225 	if (!near)
1226 		goto none;
1227 
1228 	anon_vma = reusable_anon_vma(near, near, vma);
1229 	if (anon_vma)
1230 		return anon_vma;
1231 none:
1232 	/*
1233 	 * There's no absolute need to look only at touching neighbours:
1234 	 * we could search further afield for "compatible" anon_vmas.
1235 	 * But it would probably just be a waste of time searching,
1236 	 * or lead to too many vmas hanging off the same anon_vma.
1237 	 * We're trying to allow mprotect remerging later on,
1238 	 * not trying to minimize memory used for anon_vmas.
1239 	 */
1240 	return NULL;
1241 }
1242 
1243 #ifdef CONFIG_PROC_FS
vm_stat_account(struct mm_struct * mm,unsigned long flags,struct file * file,long pages)1244 void vm_stat_account(struct mm_struct *mm, unsigned long flags,
1245 						struct file *file, long pages)
1246 {
1247 	const unsigned long stack_flags
1248 		= VM_STACK_FLAGS & (VM_GROWSUP|VM_GROWSDOWN);
1249 
1250 	mm->total_vm += pages;
1251 
1252 	if (file) {
1253 		mm->shared_vm += pages;
1254 		if ((flags & (VM_EXEC|VM_WRITE)) == VM_EXEC)
1255 			mm->exec_vm += pages;
1256 	} else if (flags & stack_flags)
1257 		mm->stack_vm += pages;
1258 }
1259 #endif /* CONFIG_PROC_FS */
1260 
1261 /*
1262  * If a hint addr is less than mmap_min_addr change hint to be as
1263  * low as possible but still greater than mmap_min_addr
1264  */
round_hint_to_min(unsigned long hint)1265 static inline unsigned long round_hint_to_min(unsigned long hint)
1266 {
1267 	hint &= PAGE_MASK;
1268 	if (((void *)hint != NULL) &&
1269 	    (hint < mmap_min_addr))
1270 		return PAGE_ALIGN(mmap_min_addr);
1271 	return hint;
1272 }
1273 
mlock_future_check(struct mm_struct * mm,unsigned long flags,unsigned long len)1274 static inline int mlock_future_check(struct mm_struct *mm,
1275 				     unsigned long flags,
1276 				     unsigned long len)
1277 {
1278 	unsigned long locked, lock_limit;
1279 
1280 	/*  mlock MCL_FUTURE? */
1281 	if (flags & VM_LOCKED) {
1282 		locked = len >> PAGE_SHIFT;
1283 		locked += mm->locked_vm;
1284 		lock_limit = rlimit(RLIMIT_MEMLOCK);
1285 		lock_limit >>= PAGE_SHIFT;
1286 		if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1287 			return -EAGAIN;
1288 	}
1289 	return 0;
1290 }
1291 
1292 /*
1293  * The caller must hold down_write(&current->mm->mmap_sem).
1294  */
1295 
do_mmap_pgoff(struct file * file,unsigned long addr,unsigned long len,unsigned long prot,unsigned long flags,unsigned long pgoff,unsigned long * populate)1296 unsigned long do_mmap_pgoff(struct file *file, unsigned long addr,
1297 			unsigned long len, unsigned long prot,
1298 			unsigned long flags, unsigned long pgoff,
1299 			unsigned long *populate)
1300 {
1301 	struct mm_struct *mm = current->mm;
1302 	vm_flags_t vm_flags;
1303 
1304 	*populate = 0;
1305 
1306 	/*
1307 	 * Does the application expect PROT_READ to imply PROT_EXEC?
1308 	 *
1309 	 * (the exception is when the underlying filesystem is noexec
1310 	 *  mounted, in which case we dont add PROT_EXEC.)
1311 	 */
1312 	if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1313 		if (!(file && (file->f_path.mnt->mnt_flags & MNT_NOEXEC)))
1314 			prot |= PROT_EXEC;
1315 
1316 	if (!len)
1317 		return -EINVAL;
1318 
1319 	if (!(flags & MAP_FIXED))
1320 		addr = round_hint_to_min(addr);
1321 
1322 	/* Careful about overflows.. */
1323 	len = PAGE_ALIGN(len);
1324 	if (!len)
1325 		return -ENOMEM;
1326 
1327 	/* offset overflow? */
1328 	if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1329 		return -EOVERFLOW;
1330 
1331 	/* Too many mappings? */
1332 	if (mm->map_count > sysctl_max_map_count)
1333 		return -ENOMEM;
1334 
1335 	/* Obtain the address to map to. we verify (or select) it and ensure
1336 	 * that it represents a valid section of the address space.
1337 	 */
1338 	addr = get_unmapped_area(file, addr, len, pgoff, flags);
1339 	if (addr & ~PAGE_MASK)
1340 		return addr;
1341 
1342 	/* Do simple checking here so the lower-level routines won't have
1343 	 * to. we assume access permissions have been handled by the open
1344 	 * of the memory object, so we don't do any here.
1345 	 */
1346 	vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags) |
1347 			mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1348 
1349 	if (flags & MAP_LOCKED)
1350 		if (!can_do_mlock())
1351 			return -EPERM;
1352 
1353 	if (mlock_future_check(mm, vm_flags, len))
1354 		return -EAGAIN;
1355 
1356 	if (file) {
1357 		struct inode *inode = file_inode(file);
1358 
1359 		switch (flags & MAP_TYPE) {
1360 		case MAP_SHARED:
1361 			if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
1362 				return -EACCES;
1363 
1364 			/*
1365 			 * Make sure we don't allow writing to an append-only
1366 			 * file..
1367 			 */
1368 			if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1369 				return -EACCES;
1370 
1371 			/*
1372 			 * Make sure there are no mandatory locks on the file.
1373 			 */
1374 			if (locks_verify_locked(file))
1375 				return -EAGAIN;
1376 
1377 			vm_flags |= VM_SHARED | VM_MAYSHARE;
1378 			if (!(file->f_mode & FMODE_WRITE))
1379 				vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1380 
1381 			/* fall through */
1382 		case MAP_PRIVATE:
1383 			if (!(file->f_mode & FMODE_READ))
1384 				return -EACCES;
1385 			if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) {
1386 				if (vm_flags & VM_EXEC)
1387 					return -EPERM;
1388 				vm_flags &= ~VM_MAYEXEC;
1389 			}
1390 
1391 			if (!file->f_op->mmap)
1392 				return -ENODEV;
1393 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1394 				return -EINVAL;
1395 			break;
1396 
1397 		default:
1398 			return -EINVAL;
1399 		}
1400 	} else {
1401 		switch (flags & MAP_TYPE) {
1402 		case MAP_SHARED:
1403 			if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1404 				return -EINVAL;
1405 			/*
1406 			 * Ignore pgoff.
1407 			 */
1408 			pgoff = 0;
1409 			vm_flags |= VM_SHARED | VM_MAYSHARE;
1410 			break;
1411 		case MAP_PRIVATE:
1412 			/*
1413 			 * Set pgoff according to addr for anon_vma.
1414 			 */
1415 			pgoff = addr >> PAGE_SHIFT;
1416 			break;
1417 		default:
1418 			return -EINVAL;
1419 		}
1420 	}
1421 
1422 	/*
1423 	 * Set 'VM_NORESERVE' if we should not account for the
1424 	 * memory use of this mapping.
1425 	 */
1426 	if (flags & MAP_NORESERVE) {
1427 		/* We honor MAP_NORESERVE if allowed to overcommit */
1428 		if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1429 			vm_flags |= VM_NORESERVE;
1430 
1431 		/* hugetlb applies strict overcommit unless MAP_NORESERVE */
1432 		if (file && is_file_hugepages(file))
1433 			vm_flags |= VM_NORESERVE;
1434 	}
1435 
1436 	addr = mmap_region(file, addr, len, vm_flags, pgoff);
1437 	if (!IS_ERR_VALUE(addr) &&
1438 	    ((vm_flags & VM_LOCKED) ||
1439 	     (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1440 		*populate = len;
1441 	return addr;
1442 }
1443 
SYSCALL_DEFINE6(mmap_pgoff,unsigned long,addr,unsigned long,len,unsigned long,prot,unsigned long,flags,unsigned long,fd,unsigned long,pgoff)1444 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1445 		unsigned long, prot, unsigned long, flags,
1446 		unsigned long, fd, unsigned long, pgoff)
1447 {
1448 	struct file *file = NULL;
1449 	unsigned long retval = -EBADF;
1450 
1451 	if (!(flags & MAP_ANONYMOUS)) {
1452 		audit_mmap_fd(fd, flags);
1453 		file = fget(fd);
1454 		if (!file)
1455 			goto out;
1456 		if (is_file_hugepages(file))
1457 			len = ALIGN(len, huge_page_size(hstate_file(file)));
1458 		retval = -EINVAL;
1459 		if (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))
1460 			goto out_fput;
1461 	} else if (flags & MAP_HUGETLB) {
1462 		struct user_struct *user = NULL;
1463 		struct hstate *hs;
1464 
1465 		hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & SHM_HUGE_MASK);
1466 		if (!hs)
1467 			return -EINVAL;
1468 
1469 		len = ALIGN(len, huge_page_size(hs));
1470 		/*
1471 		 * VM_NORESERVE is used because the reservations will be
1472 		 * taken when vm_ops->mmap() is called
1473 		 * A dummy user value is used because we are not locking
1474 		 * memory so no accounting is necessary
1475 		 */
1476 		file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1477 				VM_NORESERVE,
1478 				&user, HUGETLB_ANONHUGE_INODE,
1479 				(flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1480 		if (IS_ERR(file))
1481 			return PTR_ERR(file);
1482 	}
1483 
1484 	flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1485 
1486 	retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1487 out_fput:
1488 	if (file)
1489 		fput(file);
1490 out:
1491 	return retval;
1492 }
1493 
1494 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1495 struct mmap_arg_struct {
1496 	unsigned long addr;
1497 	unsigned long len;
1498 	unsigned long prot;
1499 	unsigned long flags;
1500 	unsigned long fd;
1501 	unsigned long offset;
1502 };
1503 
SYSCALL_DEFINE1(old_mmap,struct mmap_arg_struct __user *,arg)1504 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1505 {
1506 	struct mmap_arg_struct a;
1507 
1508 	if (copy_from_user(&a, arg, sizeof(a)))
1509 		return -EFAULT;
1510 	if (a.offset & ~PAGE_MASK)
1511 		return -EINVAL;
1512 
1513 	return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1514 			      a.offset >> PAGE_SHIFT);
1515 }
1516 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1517 
1518 /*
1519  * Some shared mappigns will want the pages marked read-only
1520  * to track write events. If so, we'll downgrade vm_page_prot
1521  * to the private version (using protection_map[] without the
1522  * VM_SHARED bit).
1523  */
vma_wants_writenotify(struct vm_area_struct * vma)1524 int vma_wants_writenotify(struct vm_area_struct *vma)
1525 {
1526 	vm_flags_t vm_flags = vma->vm_flags;
1527 
1528 	/* If it was private or non-writable, the write bit is already clear */
1529 	if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1530 		return 0;
1531 
1532 	/* The backer wishes to know when pages are first written to? */
1533 	if (vma->vm_ops && vma->vm_ops->page_mkwrite)
1534 		return 1;
1535 
1536 	/* The open routine did something to the protections that pgprot_modify
1537 	 * won't preserve? */
1538 	if (pgprot_val(vma->vm_page_prot) !=
1539 	    pgprot_val(vm_pgprot_modify(vma->vm_page_prot, vm_flags)))
1540 		return 0;
1541 
1542 	/* Do we need to track softdirty? */
1543 	if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
1544 		return 1;
1545 
1546 	/* Specialty mapping? */
1547 	if (vm_flags & VM_PFNMAP)
1548 		return 0;
1549 
1550 	/* Can the mapping track the dirty pages? */
1551 	return vma->vm_file && vma->vm_file->f_mapping &&
1552 		mapping_cap_account_dirty(vma->vm_file->f_mapping);
1553 }
1554 
1555 /*
1556  * We account for memory if it's a private writeable mapping,
1557  * not hugepages and VM_NORESERVE wasn't set.
1558  */
accountable_mapping(struct file * file,vm_flags_t vm_flags)1559 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1560 {
1561 	/*
1562 	 * hugetlb has its own accounting separate from the core VM
1563 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
1564 	 */
1565 	if (file && is_file_hugepages(file))
1566 		return 0;
1567 
1568 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1569 }
1570 
mmap_region(struct file * file,unsigned long addr,unsigned long len,vm_flags_t vm_flags,unsigned long pgoff)1571 unsigned long mmap_region(struct file *file, unsigned long addr,
1572 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff)
1573 {
1574 	struct mm_struct *mm = current->mm;
1575 	struct vm_area_struct *vma, *prev;
1576 	int error;
1577 	struct rb_node **rb_link, *rb_parent;
1578 	unsigned long charged = 0;
1579 
1580 	/* Check against address space limit. */
1581 	if (!may_expand_vm(mm, len >> PAGE_SHIFT)) {
1582 		unsigned long nr_pages;
1583 
1584 		/*
1585 		 * MAP_FIXED may remove pages of mappings that intersects with
1586 		 * requested mapping. Account for the pages it would unmap.
1587 		 */
1588 		if (!(vm_flags & MAP_FIXED))
1589 			return -ENOMEM;
1590 
1591 		nr_pages = count_vma_pages_range(mm, addr, addr + len);
1592 
1593 		if (!may_expand_vm(mm, (len >> PAGE_SHIFT) - nr_pages))
1594 			return -ENOMEM;
1595 	}
1596 
1597 	/* Clear old maps */
1598 	error = -ENOMEM;
1599 munmap_back:
1600 	if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent)) {
1601 		if (do_munmap(mm, addr, len))
1602 			return -ENOMEM;
1603 		goto munmap_back;
1604 	}
1605 
1606 	/*
1607 	 * Private writable mapping: check memory availability
1608 	 */
1609 	if (accountable_mapping(file, vm_flags)) {
1610 		charged = len >> PAGE_SHIFT;
1611 		if (security_vm_enough_memory_mm(mm, charged))
1612 			return -ENOMEM;
1613 		vm_flags |= VM_ACCOUNT;
1614 	}
1615 
1616 	/*
1617 	 * Can we just expand an old mapping?
1618 	 */
1619 	vma = vma_merge(mm, prev, addr, addr + len, vm_flags, NULL, file, pgoff,
1620 			NULL, NULL);
1621 	if (vma)
1622 		goto out;
1623 
1624 	/*
1625 	 * Determine the object being mapped and call the appropriate
1626 	 * specific mapper. the address has already been validated, but
1627 	 * not unmapped, but the maps are removed from the list.
1628 	 */
1629 	vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
1630 	if (!vma) {
1631 		error = -ENOMEM;
1632 		goto unacct_error;
1633 	}
1634 
1635 	vma->vm_mm = mm;
1636 	vma->vm_start = addr;
1637 	vma->vm_end = addr + len;
1638 	vma->vm_flags = vm_flags;
1639 	vma->vm_page_prot = vm_get_page_prot(vm_flags);
1640 	vma->vm_pgoff = pgoff;
1641 	INIT_LIST_HEAD(&vma->anon_vma_chain);
1642 
1643 	if (file) {
1644 		if (vm_flags & VM_DENYWRITE) {
1645 			error = deny_write_access(file);
1646 			if (error)
1647 				goto free_vma;
1648 		}
1649 		if (vm_flags & VM_SHARED) {
1650 			error = mapping_map_writable(file->f_mapping);
1651 			if (error)
1652 				goto allow_write_and_free_vma;
1653 		}
1654 
1655 		/* ->mmap() can change vma->vm_file, but must guarantee that
1656 		 * vma_link() below can deny write-access if VM_DENYWRITE is set
1657 		 * and map writably if VM_SHARED is set. This usually means the
1658 		 * new file must not have been exposed to user-space, yet.
1659 		 */
1660 		vma->vm_file = get_file(file);
1661 		error = file->f_op->mmap(file, vma);
1662 		if (error)
1663 			goto unmap_and_free_vma;
1664 
1665 		/* Can addr have changed??
1666 		 *
1667 		 * Answer: Yes, several device drivers can do it in their
1668 		 *         f_op->mmap method. -DaveM
1669 		 * Bug: If addr is changed, prev, rb_link, rb_parent should
1670 		 *      be updated for vma_link()
1671 		 */
1672 		WARN_ON_ONCE(addr != vma->vm_start);
1673 
1674 		addr = vma->vm_start;
1675 		vm_flags = vma->vm_flags;
1676 	} else if (vm_flags & VM_SHARED) {
1677 		error = shmem_zero_setup(vma);
1678 		if (error)
1679 			goto free_vma;
1680 	}
1681 
1682 	vma_link(mm, vma, prev, rb_link, rb_parent);
1683 	/* Once vma denies write, undo our temporary denial count */
1684 	if (file) {
1685 		if (vm_flags & VM_SHARED)
1686 			mapping_unmap_writable(file->f_mapping);
1687 		if (vm_flags & VM_DENYWRITE)
1688 			allow_write_access(file);
1689 	}
1690 	file = vma->vm_file;
1691 out:
1692 	perf_event_mmap(vma);
1693 
1694 	vm_stat_account(mm, vm_flags, file, len >> PAGE_SHIFT);
1695 	if (vm_flags & VM_LOCKED) {
1696 		if (!((vm_flags & VM_SPECIAL) || is_vm_hugetlb_page(vma) ||
1697 					vma == get_gate_vma(current->mm)))
1698 			mm->locked_vm += (len >> PAGE_SHIFT);
1699 		else
1700 			vma->vm_flags &= ~VM_LOCKED;
1701 	}
1702 
1703 	if (file)
1704 		uprobe_mmap(vma);
1705 
1706 	/*
1707 	 * New (or expanded) vma always get soft dirty status.
1708 	 * Otherwise user-space soft-dirty page tracker won't
1709 	 * be able to distinguish situation when vma area unmapped,
1710 	 * then new mapped in-place (which must be aimed as
1711 	 * a completely new data area).
1712 	 */
1713 	vma->vm_flags |= VM_SOFTDIRTY;
1714 
1715 	vma_set_page_prot(vma);
1716 
1717 	return addr;
1718 
1719 unmap_and_free_vma:
1720 	vma->vm_file = NULL;
1721 	fput(file);
1722 
1723 	/* Undo any partial mapping done by a device driver. */
1724 	unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1725 	charged = 0;
1726 	if (vm_flags & VM_SHARED)
1727 		mapping_unmap_writable(file->f_mapping);
1728 allow_write_and_free_vma:
1729 	if (vm_flags & VM_DENYWRITE)
1730 		allow_write_access(file);
1731 free_vma:
1732 	kmem_cache_free(vm_area_cachep, vma);
1733 unacct_error:
1734 	if (charged)
1735 		vm_unacct_memory(charged);
1736 	return error;
1737 }
1738 
unmapped_area(struct vm_unmapped_area_info * info)1739 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1740 {
1741 	/*
1742 	 * We implement the search by looking for an rbtree node that
1743 	 * immediately follows a suitable gap. That is,
1744 	 * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1745 	 * - gap_end   = vma->vm_start        >= info->low_limit  + length;
1746 	 * - gap_end - gap_start >= length
1747 	 */
1748 
1749 	struct mm_struct *mm = current->mm;
1750 	struct vm_area_struct *vma;
1751 	unsigned long length, low_limit, high_limit, gap_start, gap_end;
1752 
1753 	/* Adjust search length to account for worst case alignment overhead */
1754 	length = info->length + info->align_mask;
1755 	if (length < info->length)
1756 		return -ENOMEM;
1757 
1758 	/* Adjust search limits by the desired length */
1759 	if (info->high_limit < length)
1760 		return -ENOMEM;
1761 	high_limit = info->high_limit - length;
1762 
1763 	if (info->low_limit > high_limit)
1764 		return -ENOMEM;
1765 	low_limit = info->low_limit + length;
1766 
1767 	/* Check if rbtree root looks promising */
1768 	if (RB_EMPTY_ROOT(&mm->mm_rb))
1769 		goto check_highest;
1770 	vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1771 	if (vma->rb_subtree_gap < length)
1772 		goto check_highest;
1773 
1774 	while (true) {
1775 		/* Visit left subtree if it looks promising */
1776 		gap_end = vm_start_gap(vma);
1777 		if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1778 			struct vm_area_struct *left =
1779 				rb_entry(vma->vm_rb.rb_left,
1780 					 struct vm_area_struct, vm_rb);
1781 			if (left->rb_subtree_gap >= length) {
1782 				vma = left;
1783 				continue;
1784 			}
1785 		}
1786 
1787 		gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
1788 check_current:
1789 		/* Check if current node has a suitable gap */
1790 		if (gap_start > high_limit)
1791 			return -ENOMEM;
1792 		if (gap_end >= low_limit &&
1793 		    gap_end > gap_start && gap_end - gap_start >= length)
1794 			goto found;
1795 
1796 		/* Visit right subtree if it looks promising */
1797 		if (vma->vm_rb.rb_right) {
1798 			struct vm_area_struct *right =
1799 				rb_entry(vma->vm_rb.rb_right,
1800 					 struct vm_area_struct, vm_rb);
1801 			if (right->rb_subtree_gap >= length) {
1802 				vma = right;
1803 				continue;
1804 			}
1805 		}
1806 
1807 		/* Go back up the rbtree to find next candidate node */
1808 		while (true) {
1809 			struct rb_node *prev = &vma->vm_rb;
1810 			if (!rb_parent(prev))
1811 				goto check_highest;
1812 			vma = rb_entry(rb_parent(prev),
1813 				       struct vm_area_struct, vm_rb);
1814 			if (prev == vma->vm_rb.rb_left) {
1815 				gap_start = vm_end_gap(vma->vm_prev);
1816 				gap_end = vm_start_gap(vma);
1817 				goto check_current;
1818 			}
1819 		}
1820 	}
1821 
1822 check_highest:
1823 	/* Check highest gap, which does not precede any rbtree node */
1824 	gap_start = mm->highest_vm_end;
1825 	gap_end = ULONG_MAX;  /* Only for VM_BUG_ON below */
1826 	if (gap_start > high_limit)
1827 		return -ENOMEM;
1828 
1829 found:
1830 	/* We found a suitable gap. Clip it with the original low_limit. */
1831 	if (gap_start < info->low_limit)
1832 		gap_start = info->low_limit;
1833 
1834 	/* Adjust gap address to the desired alignment */
1835 	gap_start += (info->align_offset - gap_start) & info->align_mask;
1836 
1837 	VM_BUG_ON(gap_start + info->length > info->high_limit);
1838 	VM_BUG_ON(gap_start + info->length > gap_end);
1839 	return gap_start;
1840 }
1841 
unmapped_area_topdown(struct vm_unmapped_area_info * info)1842 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1843 {
1844 	struct mm_struct *mm = current->mm;
1845 	struct vm_area_struct *vma;
1846 	unsigned long length, low_limit, high_limit, gap_start, gap_end;
1847 
1848 	/* Adjust search length to account for worst case alignment overhead */
1849 	length = info->length + info->align_mask;
1850 	if (length < info->length)
1851 		return -ENOMEM;
1852 
1853 	/*
1854 	 * Adjust search limits by the desired length.
1855 	 * See implementation comment at top of unmapped_area().
1856 	 */
1857 	gap_end = info->high_limit;
1858 	if (gap_end < length)
1859 		return -ENOMEM;
1860 	high_limit = gap_end - length;
1861 
1862 	if (info->low_limit > high_limit)
1863 		return -ENOMEM;
1864 	low_limit = info->low_limit + length;
1865 
1866 	/* Check highest gap, which does not precede any rbtree node */
1867 	gap_start = mm->highest_vm_end;
1868 	if (gap_start <= high_limit)
1869 		goto found_highest;
1870 
1871 	/* Check if rbtree root looks promising */
1872 	if (RB_EMPTY_ROOT(&mm->mm_rb))
1873 		return -ENOMEM;
1874 	vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1875 	if (vma->rb_subtree_gap < length)
1876 		return -ENOMEM;
1877 
1878 	while (true) {
1879 		/* Visit right subtree if it looks promising */
1880 		gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
1881 		if (gap_start <= high_limit && vma->vm_rb.rb_right) {
1882 			struct vm_area_struct *right =
1883 				rb_entry(vma->vm_rb.rb_right,
1884 					 struct vm_area_struct, vm_rb);
1885 			if (right->rb_subtree_gap >= length) {
1886 				vma = right;
1887 				continue;
1888 			}
1889 		}
1890 
1891 check_current:
1892 		/* Check if current node has a suitable gap */
1893 		gap_end = vm_start_gap(vma);
1894 		if (gap_end < low_limit)
1895 			return -ENOMEM;
1896 		if (gap_start <= high_limit &&
1897 		    gap_end > gap_start && gap_end - gap_start >= length)
1898 			goto found;
1899 
1900 		/* Visit left subtree if it looks promising */
1901 		if (vma->vm_rb.rb_left) {
1902 			struct vm_area_struct *left =
1903 				rb_entry(vma->vm_rb.rb_left,
1904 					 struct vm_area_struct, vm_rb);
1905 			if (left->rb_subtree_gap >= length) {
1906 				vma = left;
1907 				continue;
1908 			}
1909 		}
1910 
1911 		/* Go back up the rbtree to find next candidate node */
1912 		while (true) {
1913 			struct rb_node *prev = &vma->vm_rb;
1914 			if (!rb_parent(prev))
1915 				return -ENOMEM;
1916 			vma = rb_entry(rb_parent(prev),
1917 				       struct vm_area_struct, vm_rb);
1918 			if (prev == vma->vm_rb.rb_right) {
1919 				gap_start = vma->vm_prev ?
1920 					vm_end_gap(vma->vm_prev) : 0;
1921 				goto check_current;
1922 			}
1923 		}
1924 	}
1925 
1926 found:
1927 	/* We found a suitable gap. Clip it with the original high_limit. */
1928 	if (gap_end > info->high_limit)
1929 		gap_end = info->high_limit;
1930 
1931 found_highest:
1932 	/* Compute highest gap address at the desired alignment */
1933 	gap_end -= info->length;
1934 	gap_end -= (gap_end - info->align_offset) & info->align_mask;
1935 
1936 	VM_BUG_ON(gap_end < info->low_limit);
1937 	VM_BUG_ON(gap_end < gap_start);
1938 	return gap_end;
1939 }
1940 
1941 /* Get an address range which is currently unmapped.
1942  * For shmat() with addr=0.
1943  *
1944  * Ugly calling convention alert:
1945  * Return value with the low bits set means error value,
1946  * ie
1947  *	if (ret & ~PAGE_MASK)
1948  *		error = ret;
1949  *
1950  * This function "knows" that -ENOMEM has the bits set.
1951  */
1952 #ifndef HAVE_ARCH_UNMAPPED_AREA
1953 unsigned long
arch_get_unmapped_area(struct file * filp,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)1954 arch_get_unmapped_area(struct file *filp, unsigned long addr,
1955 		unsigned long len, unsigned long pgoff, unsigned long flags)
1956 {
1957 	struct mm_struct *mm = current->mm;
1958 	struct vm_area_struct *vma, *prev;
1959 	struct vm_unmapped_area_info info;
1960 
1961 	if (len > TASK_SIZE - mmap_min_addr)
1962 		return -ENOMEM;
1963 
1964 	if (flags & MAP_FIXED)
1965 		return addr;
1966 
1967 	if (addr) {
1968 		addr = PAGE_ALIGN(addr);
1969 		vma = find_vma_prev(mm, addr, &prev);
1970 		if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
1971 		    (!vma || addr + len <= vm_start_gap(vma)) &&
1972 		    (!prev || addr >= vm_end_gap(prev)))
1973 			return addr;
1974 	}
1975 
1976 	info.flags = 0;
1977 	info.length = len;
1978 	info.low_limit = mm->mmap_base;
1979 	info.high_limit = TASK_SIZE;
1980 	info.align_mask = 0;
1981 	return vm_unmapped_area(&info);
1982 }
1983 #endif
1984 
1985 /*
1986  * This mmap-allocator allocates new areas top-down from below the
1987  * stack's low limit (the base):
1988  */
1989 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
1990 unsigned long
arch_get_unmapped_area_topdown(struct file * filp,const unsigned long addr0,const unsigned long len,const unsigned long pgoff,const unsigned long flags)1991 arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0,
1992 			  const unsigned long len, const unsigned long pgoff,
1993 			  const unsigned long flags)
1994 {
1995 	struct vm_area_struct *vma, *prev;
1996 	struct mm_struct *mm = current->mm;
1997 	unsigned long addr = addr0;
1998 	struct vm_unmapped_area_info info;
1999 
2000 	/* requested length too big for entire address space */
2001 	if (len > TASK_SIZE - mmap_min_addr)
2002 		return -ENOMEM;
2003 
2004 	if (flags & MAP_FIXED)
2005 		return addr;
2006 
2007 	/* requesting a specific address */
2008 	if (addr) {
2009 		addr = PAGE_ALIGN(addr);
2010 		vma = find_vma_prev(mm, addr, &prev);
2011 		if (TASK_SIZE - len >= addr && addr >= mmap_min_addr &&
2012 				(!vma || addr + len <= vm_start_gap(vma)) &&
2013 				(!prev || addr >= vm_end_gap(prev)))
2014 			return addr;
2015 	}
2016 
2017 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2018 	info.length = len;
2019 	info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2020 	info.high_limit = mm->mmap_base;
2021 	info.align_mask = 0;
2022 	addr = vm_unmapped_area(&info);
2023 
2024 	/*
2025 	 * A failed mmap() very likely causes application failure,
2026 	 * so fall back to the bottom-up function here. This scenario
2027 	 * can happen with large stack limits and large mmap()
2028 	 * allocations.
2029 	 */
2030 	if (addr & ~PAGE_MASK) {
2031 		VM_BUG_ON(addr != -ENOMEM);
2032 		info.flags = 0;
2033 		info.low_limit = TASK_UNMAPPED_BASE;
2034 		info.high_limit = TASK_SIZE;
2035 		addr = vm_unmapped_area(&info);
2036 	}
2037 
2038 	return addr;
2039 }
2040 #endif
2041 
2042 unsigned long
get_unmapped_area(struct file * file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)2043 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
2044 		unsigned long pgoff, unsigned long flags)
2045 {
2046 	unsigned long (*get_area)(struct file *, unsigned long,
2047 				  unsigned long, unsigned long, unsigned long);
2048 
2049 	unsigned long error = arch_mmap_check(addr, len, flags);
2050 	if (error)
2051 		return error;
2052 
2053 	/* Careful about overflows.. */
2054 	if (len > TASK_SIZE)
2055 		return -ENOMEM;
2056 
2057 	get_area = current->mm->get_unmapped_area;
2058 	if (file && file->f_op->get_unmapped_area)
2059 		get_area = file->f_op->get_unmapped_area;
2060 	addr = get_area(file, addr, len, pgoff, flags);
2061 	if (IS_ERR_VALUE(addr))
2062 		return addr;
2063 
2064 	if (addr > TASK_SIZE - len)
2065 		return -ENOMEM;
2066 	if (addr & ~PAGE_MASK)
2067 		return -EINVAL;
2068 
2069 	addr = arch_rebalance_pgtables(addr, len);
2070 	error = security_mmap_addr(addr);
2071 	return error ? error : addr;
2072 }
2073 
2074 EXPORT_SYMBOL(get_unmapped_area);
2075 
2076 /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
find_vma(struct mm_struct * mm,unsigned long addr)2077 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2078 {
2079 	struct rb_node *rb_node;
2080 	struct vm_area_struct *vma;
2081 
2082 	/* Check the cache first. */
2083 	vma = vmacache_find(mm, addr);
2084 	if (likely(vma))
2085 		return vma;
2086 
2087 	rb_node = mm->mm_rb.rb_node;
2088 	vma = NULL;
2089 
2090 	while (rb_node) {
2091 		struct vm_area_struct *tmp;
2092 
2093 		tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2094 
2095 		if (tmp->vm_end > addr) {
2096 			vma = tmp;
2097 			if (tmp->vm_start <= addr)
2098 				break;
2099 			rb_node = rb_node->rb_left;
2100 		} else
2101 			rb_node = rb_node->rb_right;
2102 	}
2103 
2104 	if (vma)
2105 		vmacache_update(addr, vma);
2106 	return vma;
2107 }
2108 
2109 EXPORT_SYMBOL(find_vma);
2110 
2111 /*
2112  * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
2113  */
2114 struct vm_area_struct *
find_vma_prev(struct mm_struct * mm,unsigned long addr,struct vm_area_struct ** pprev)2115 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2116 			struct vm_area_struct **pprev)
2117 {
2118 	struct vm_area_struct *vma;
2119 
2120 	vma = find_vma(mm, addr);
2121 	if (vma) {
2122 		*pprev = vma->vm_prev;
2123 	} else {
2124 		struct rb_node *rb_node = mm->mm_rb.rb_node;
2125 		*pprev = NULL;
2126 		while (rb_node) {
2127 			*pprev = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2128 			rb_node = rb_node->rb_right;
2129 		}
2130 	}
2131 	return vma;
2132 }
2133 
2134 /*
2135  * Verify that the stack growth is acceptable and
2136  * update accounting. This is shared with both the
2137  * grow-up and grow-down cases.
2138  */
acct_stack_growth(struct vm_area_struct * vma,unsigned long size,unsigned long grow)2139 static int acct_stack_growth(struct vm_area_struct *vma,
2140 			     unsigned long size, unsigned long grow)
2141 {
2142 	struct mm_struct *mm = vma->vm_mm;
2143 	struct rlimit *rlim = current->signal->rlim;
2144 	unsigned long new_start;
2145 
2146 	/* address space limit tests */
2147 	if (!may_expand_vm(mm, grow))
2148 		return -ENOMEM;
2149 
2150 	/* Stack limit test */
2151 	if (size > ACCESS_ONCE(rlim[RLIMIT_STACK].rlim_cur))
2152 		return -ENOMEM;
2153 
2154 	/* mlock limit tests */
2155 	if (vma->vm_flags & VM_LOCKED) {
2156 		unsigned long locked;
2157 		unsigned long limit;
2158 		locked = mm->locked_vm + grow;
2159 		limit = ACCESS_ONCE(rlim[RLIMIT_MEMLOCK].rlim_cur);
2160 		limit >>= PAGE_SHIFT;
2161 		if (locked > limit && !capable(CAP_IPC_LOCK))
2162 			return -ENOMEM;
2163 	}
2164 
2165 	/* Check to ensure the stack will not grow into a hugetlb-only region */
2166 	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2167 			vma->vm_end - size;
2168 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2169 		return -EFAULT;
2170 
2171 	/*
2172 	 * Overcommit..  This must be the final test, as it will
2173 	 * update security statistics.
2174 	 */
2175 	if (security_vm_enough_memory_mm(mm, grow))
2176 		return -ENOMEM;
2177 
2178 	/* Ok, everything looks good - let it rip */
2179 	if (vma->vm_flags & VM_LOCKED)
2180 		mm->locked_vm += grow;
2181 	vm_stat_account(mm, vma->vm_flags, vma->vm_file, grow);
2182 	return 0;
2183 }
2184 
2185 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2186 /*
2187  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2188  * vma is the last one with address > vma->vm_end.  Have to extend vma.
2189  */
expand_upwards(struct vm_area_struct * vma,unsigned long address)2190 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2191 {
2192 	struct vm_area_struct *next;
2193 	unsigned long gap_addr;
2194 	int error = 0;
2195 
2196 	if (!(vma->vm_flags & VM_GROWSUP))
2197 		return -EFAULT;
2198 
2199 	/* Guard against exceeding limits of the address space. */
2200 	address &= PAGE_MASK;
2201 	if (address >= (TASK_SIZE & PAGE_MASK))
2202 		return -ENOMEM;
2203 	address += PAGE_SIZE;
2204 
2205 	/* Enforce stack_guard_gap */
2206 	gap_addr = address + stack_guard_gap;
2207 
2208 	/* Guard against overflow */
2209 	if (gap_addr < address || gap_addr > TASK_SIZE)
2210 		gap_addr = TASK_SIZE;
2211 
2212 	next = vma->vm_next;
2213 	if (next && next->vm_start < gap_addr &&
2214 			(next->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
2215 		if (!(next->vm_flags & VM_GROWSUP))
2216 			return -ENOMEM;
2217 		/* Check that both stack segments have the same anon_vma? */
2218 	}
2219 
2220 	/* We must make sure the anon_vma is allocated. */
2221 	if (unlikely(anon_vma_prepare(vma)))
2222 		return -ENOMEM;
2223 
2224 	/*
2225 	 * vma->vm_start/vm_end cannot change under us because the caller
2226 	 * is required to hold the mmap_sem in read mode.  We need the
2227 	 * anon_vma lock to serialize against concurrent expand_stacks.
2228 	 */
2229 	anon_vma_lock_write(vma->anon_vma);
2230 
2231 	/* Somebody else might have raced and expanded it already */
2232 	if (address > vma->vm_end) {
2233 		unsigned long size, grow;
2234 
2235 		size = address - vma->vm_start;
2236 		grow = (address - vma->vm_end) >> PAGE_SHIFT;
2237 
2238 		error = -ENOMEM;
2239 		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2240 			error = acct_stack_growth(vma, size, grow);
2241 			if (!error) {
2242 				/*
2243 				 * vma_gap_update() doesn't support concurrent
2244 				 * updates, but we only hold a shared mmap_sem
2245 				 * lock here, so we need to protect against
2246 				 * concurrent vma expansions.
2247 				 * anon_vma_lock_write() doesn't help here, as
2248 				 * we don't guarantee that all growable vmas
2249 				 * in a mm share the same root anon vma.
2250 				 * So, we reuse mm->page_table_lock to guard
2251 				 * against concurrent vma expansions.
2252 				 */
2253 				spin_lock(&vma->vm_mm->page_table_lock);
2254 				anon_vma_interval_tree_pre_update_vma(vma);
2255 				vma->vm_end = address;
2256 				anon_vma_interval_tree_post_update_vma(vma);
2257 				if (vma->vm_next)
2258 					vma_gap_update(vma->vm_next);
2259 				else
2260 					vma->vm_mm->highest_vm_end = vm_end_gap(vma);
2261 				spin_unlock(&vma->vm_mm->page_table_lock);
2262 
2263 				perf_event_mmap(vma);
2264 			}
2265 		}
2266 	}
2267 	anon_vma_unlock_write(vma->anon_vma);
2268 	khugepaged_enter_vma_merge(vma, vma->vm_flags);
2269 	validate_mm(vma->vm_mm);
2270 	return error;
2271 }
2272 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2273 
2274 /*
2275  * vma is the first one with address < vma->vm_start.  Have to extend vma.
2276  */
expand_downwards(struct vm_area_struct * vma,unsigned long address)2277 int expand_downwards(struct vm_area_struct *vma,
2278 				   unsigned long address)
2279 {
2280 	struct vm_area_struct *prev;
2281 	unsigned long gap_addr;
2282 	int error;
2283 
2284 	address &= PAGE_MASK;
2285 	error = security_mmap_addr(address);
2286 	if (error)
2287 		return error;
2288 
2289 	/* Enforce stack_guard_gap */
2290 	gap_addr = address - stack_guard_gap;
2291 	if (gap_addr > address)
2292 		return -ENOMEM;
2293 	prev = vma->vm_prev;
2294 	if (prev && prev->vm_end > gap_addr &&
2295 			(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
2296 		if (!(prev->vm_flags & VM_GROWSDOWN))
2297 			return -ENOMEM;
2298 		/* Check that both stack segments have the same anon_vma? */
2299 	}
2300 
2301 	/* We must make sure the anon_vma is allocated. */
2302 	if (unlikely(anon_vma_prepare(vma)))
2303 		return -ENOMEM;
2304 
2305 	/*
2306 	 * vma->vm_start/vm_end cannot change under us because the caller
2307 	 * is required to hold the mmap_sem in read mode.  We need the
2308 	 * anon_vma lock to serialize against concurrent expand_stacks.
2309 	 */
2310 	anon_vma_lock_write(vma->anon_vma);
2311 
2312 	/* Somebody else might have raced and expanded it already */
2313 	if (address < vma->vm_start) {
2314 		unsigned long size, grow;
2315 
2316 		size = vma->vm_end - address;
2317 		grow = (vma->vm_start - address) >> PAGE_SHIFT;
2318 
2319 		error = -ENOMEM;
2320 		if (grow <= vma->vm_pgoff) {
2321 			error = acct_stack_growth(vma, size, grow);
2322 			if (!error) {
2323 				/*
2324 				 * vma_gap_update() doesn't support concurrent
2325 				 * updates, but we only hold a shared mmap_sem
2326 				 * lock here, so we need to protect against
2327 				 * concurrent vma expansions.
2328 				 * anon_vma_lock_write() doesn't help here, as
2329 				 * we don't guarantee that all growable vmas
2330 				 * in a mm share the same root anon vma.
2331 				 * So, we reuse mm->page_table_lock to guard
2332 				 * against concurrent vma expansions.
2333 				 */
2334 				spin_lock(&vma->vm_mm->page_table_lock);
2335 				anon_vma_interval_tree_pre_update_vma(vma);
2336 				vma->vm_start = address;
2337 				vma->vm_pgoff -= grow;
2338 				anon_vma_interval_tree_post_update_vma(vma);
2339 				vma_gap_update(vma);
2340 				spin_unlock(&vma->vm_mm->page_table_lock);
2341 
2342 				perf_event_mmap(vma);
2343 			}
2344 		}
2345 	}
2346 	anon_vma_unlock_write(vma->anon_vma);
2347 	khugepaged_enter_vma_merge(vma, vma->vm_flags);
2348 	validate_mm(vma->vm_mm);
2349 	return error;
2350 }
2351 
2352 /* enforced gap between the expanding stack and other mappings. */
2353 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2354 
cmdline_parse_stack_guard_gap(char * p)2355 static int __init cmdline_parse_stack_guard_gap(char *p)
2356 {
2357 	unsigned long val;
2358 	char *endptr;
2359 
2360 	val = simple_strtoul(p, &endptr, 10);
2361 	if (!*endptr)
2362 		stack_guard_gap = val << PAGE_SHIFT;
2363 
2364 	return 0;
2365 }
2366 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2367 
2368 #ifdef CONFIG_STACK_GROWSUP
expand_stack(struct vm_area_struct * vma,unsigned long address)2369 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2370 {
2371 	return expand_upwards(vma, address);
2372 }
2373 
2374 struct vm_area_struct *
find_extend_vma(struct mm_struct * mm,unsigned long addr)2375 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2376 {
2377 	struct vm_area_struct *vma, *prev;
2378 
2379 	addr &= PAGE_MASK;
2380 	vma = find_vma_prev(mm, addr, &prev);
2381 	if (vma && (vma->vm_start <= addr))
2382 		return vma;
2383 	if (!prev || expand_stack(prev, addr))
2384 		return NULL;
2385 	if (prev->vm_flags & VM_LOCKED)
2386 		__mlock_vma_pages_range(prev, addr, prev->vm_end, NULL);
2387 	return prev;
2388 }
2389 #else
expand_stack(struct vm_area_struct * vma,unsigned long address)2390 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2391 {
2392 	return expand_downwards(vma, address);
2393 }
2394 
2395 struct vm_area_struct *
find_extend_vma(struct mm_struct * mm,unsigned long addr)2396 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2397 {
2398 	struct vm_area_struct *vma;
2399 	unsigned long start;
2400 
2401 	addr &= PAGE_MASK;
2402 	vma = find_vma(mm, addr);
2403 	if (!vma)
2404 		return NULL;
2405 	if (vma->vm_start <= addr)
2406 		return vma;
2407 	if (!(vma->vm_flags & VM_GROWSDOWN))
2408 		return NULL;
2409 	start = vma->vm_start;
2410 	if (expand_stack(vma, addr))
2411 		return NULL;
2412 	if (vma->vm_flags & VM_LOCKED)
2413 		__mlock_vma_pages_range(vma, addr, start, NULL);
2414 	return vma;
2415 }
2416 #endif
2417 
2418 /*
2419  * Ok - we have the memory areas we should free on the vma list,
2420  * so release them, and do the vma updates.
2421  *
2422  * Called with the mm semaphore held.
2423  */
remove_vma_list(struct mm_struct * mm,struct vm_area_struct * vma)2424 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2425 {
2426 	unsigned long nr_accounted = 0;
2427 
2428 	/* Update high watermark before we lower total_vm */
2429 	update_hiwater_vm(mm);
2430 	do {
2431 		long nrpages = vma_pages(vma);
2432 
2433 		if (vma->vm_flags & VM_ACCOUNT)
2434 			nr_accounted += nrpages;
2435 		vm_stat_account(mm, vma->vm_flags, vma->vm_file, -nrpages);
2436 		vma = remove_vma(vma);
2437 	} while (vma);
2438 	vm_unacct_memory(nr_accounted);
2439 	validate_mm(mm);
2440 }
2441 
2442 /*
2443  * Get rid of page table information in the indicated region.
2444  *
2445  * Called with the mm semaphore held.
2446  */
unmap_region(struct mm_struct * mm,struct vm_area_struct * vma,struct vm_area_struct * prev,unsigned long start,unsigned long end)2447 static void unmap_region(struct mm_struct *mm,
2448 		struct vm_area_struct *vma, struct vm_area_struct *prev,
2449 		unsigned long start, unsigned long end)
2450 {
2451 	struct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;
2452 	struct mmu_gather tlb;
2453 
2454 	lru_add_drain();
2455 	tlb_gather_mmu(&tlb, mm, start, end);
2456 	update_hiwater_rss(mm);
2457 	unmap_vmas(&tlb, vma, start, end);
2458 	free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2459 				 next ? next->vm_start : USER_PGTABLES_CEILING);
2460 	tlb_finish_mmu(&tlb, start, end);
2461 }
2462 
2463 /*
2464  * Create a list of vma's touched by the unmap, removing them from the mm's
2465  * vma list as we go..
2466  */
2467 static void
detach_vmas_to_be_unmapped(struct mm_struct * mm,struct vm_area_struct * vma,struct vm_area_struct * prev,unsigned long end)2468 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2469 	struct vm_area_struct *prev, unsigned long end)
2470 {
2471 	struct vm_area_struct **insertion_point;
2472 	struct vm_area_struct *tail_vma = NULL;
2473 
2474 	insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2475 	vma->vm_prev = NULL;
2476 	do {
2477 		vma_rb_erase(vma, &mm->mm_rb);
2478 		mm->map_count--;
2479 		tail_vma = vma;
2480 		vma = vma->vm_next;
2481 	} while (vma && vma->vm_start < end);
2482 	*insertion_point = vma;
2483 	if (vma) {
2484 		vma->vm_prev = prev;
2485 		vma_gap_update(vma);
2486 	} else
2487 		mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
2488 	tail_vma->vm_next = NULL;
2489 
2490 	/* Kill the cache */
2491 	vmacache_invalidate(mm);
2492 }
2493 
2494 /*
2495  * __split_vma() bypasses sysctl_max_map_count checking.  We use this on the
2496  * munmap path where it doesn't make sense to fail.
2497  */
__split_vma(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,int new_below)2498 static int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2499 	      unsigned long addr, int new_below)
2500 {
2501 	struct vm_area_struct *new;
2502 	int err = -ENOMEM;
2503 
2504 	if (is_vm_hugetlb_page(vma) && (addr &
2505 					~(huge_page_mask(hstate_vma(vma)))))
2506 		return -EINVAL;
2507 
2508 	new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2509 	if (!new)
2510 		goto out_err;
2511 
2512 	/* most fields are the same, copy all, and then fixup */
2513 	*new = *vma;
2514 
2515 	INIT_LIST_HEAD(&new->anon_vma_chain);
2516 
2517 	if (new_below)
2518 		new->vm_end = addr;
2519 	else {
2520 		new->vm_start = addr;
2521 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2522 	}
2523 
2524 	err = vma_dup_policy(vma, new);
2525 	if (err)
2526 		goto out_free_vma;
2527 
2528 	err = anon_vma_clone(new, vma);
2529 	if (err)
2530 		goto out_free_mpol;
2531 
2532 	if (new->vm_file)
2533 		get_file(new->vm_file);
2534 
2535 	if (new->vm_ops && new->vm_ops->open)
2536 		new->vm_ops->open(new);
2537 
2538 	if (new_below)
2539 		err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2540 			((addr - new->vm_start) >> PAGE_SHIFT), new);
2541 	else
2542 		err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2543 
2544 	/* Success. */
2545 	if (!err)
2546 		return 0;
2547 
2548 	/* Clean everything up if vma_adjust failed. */
2549 	if (new->vm_ops && new->vm_ops->close)
2550 		new->vm_ops->close(new);
2551 	if (new->vm_file)
2552 		fput(new->vm_file);
2553 	unlink_anon_vmas(new);
2554  out_free_mpol:
2555 	mpol_put(vma_policy(new));
2556  out_free_vma:
2557 	kmem_cache_free(vm_area_cachep, new);
2558  out_err:
2559 	return err;
2560 }
2561 
2562 /*
2563  * Split a vma into two pieces at address 'addr', a new vma is allocated
2564  * either for the first part or the tail.
2565  */
split_vma(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,int new_below)2566 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2567 	      unsigned long addr, int new_below)
2568 {
2569 	if (mm->map_count >= sysctl_max_map_count)
2570 		return -ENOMEM;
2571 
2572 	return __split_vma(mm, vma, addr, new_below);
2573 }
2574 
2575 /* Munmap is split into 2 main parts -- this part which finds
2576  * what needs doing, and the areas themselves, which do the
2577  * work.  This now handles partial unmappings.
2578  * Jeremy Fitzhardinge <jeremy@goop.org>
2579  */
do_munmap(struct mm_struct * mm,unsigned long start,size_t len)2580 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
2581 {
2582 	unsigned long end;
2583 	struct vm_area_struct *vma, *prev, *last;
2584 
2585 	if ((start & ~PAGE_MASK) || start > TASK_SIZE || len > TASK_SIZE-start)
2586 		return -EINVAL;
2587 
2588 	len = PAGE_ALIGN(len);
2589 	if (len == 0)
2590 		return -EINVAL;
2591 
2592 	/* Find the first overlapping VMA */
2593 	vma = find_vma(mm, start);
2594 	if (!vma)
2595 		return 0;
2596 	prev = vma->vm_prev;
2597 	/* we have  start < vma->vm_end  */
2598 
2599 	/* if it doesn't overlap, we have nothing.. */
2600 	end = start + len;
2601 	if (vma->vm_start >= end)
2602 		return 0;
2603 
2604 	/*
2605 	 * If we need to split any vma, do it now to save pain later.
2606 	 *
2607 	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2608 	 * unmapped vm_area_struct will remain in use: so lower split_vma
2609 	 * places tmp vma above, and higher split_vma places tmp vma below.
2610 	 */
2611 	if (start > vma->vm_start) {
2612 		int error;
2613 
2614 		/*
2615 		 * Make sure that map_count on return from munmap() will
2616 		 * not exceed its limit; but let map_count go just above
2617 		 * its limit temporarily, to help free resources as expected.
2618 		 */
2619 		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2620 			return -ENOMEM;
2621 
2622 		error = __split_vma(mm, vma, start, 0);
2623 		if (error)
2624 			return error;
2625 		prev = vma;
2626 	}
2627 
2628 	/* Does it split the last one? */
2629 	last = find_vma(mm, end);
2630 	if (last && end > last->vm_start) {
2631 		int error = __split_vma(mm, last, end, 1);
2632 		if (error)
2633 			return error;
2634 	}
2635 	vma = prev ? prev->vm_next : mm->mmap;
2636 
2637 	/*
2638 	 * unlock any mlock()ed ranges before detaching vmas
2639 	 */
2640 	if (mm->locked_vm) {
2641 		struct vm_area_struct *tmp = vma;
2642 		while (tmp && tmp->vm_start < end) {
2643 			if (tmp->vm_flags & VM_LOCKED) {
2644 				mm->locked_vm -= vma_pages(tmp);
2645 				munlock_vma_pages_all(tmp);
2646 			}
2647 			tmp = tmp->vm_next;
2648 		}
2649 	}
2650 
2651 	/*
2652 	 * Remove the vma's, and unmap the actual pages
2653 	 */
2654 	detach_vmas_to_be_unmapped(mm, vma, prev, end);
2655 	unmap_region(mm, vma, prev, start, end);
2656 
2657 	/* Fix up all other VM information */
2658 	remove_vma_list(mm, vma);
2659 
2660 	return 0;
2661 }
2662 EXPORT_SYMBOL(do_munmap);
2663 
vm_munmap(unsigned long start,size_t len)2664 int vm_munmap(unsigned long start, size_t len)
2665 {
2666 	int ret;
2667 	struct mm_struct *mm = current->mm;
2668 
2669 	down_write(&mm->mmap_sem);
2670 	ret = do_munmap(mm, start, len);
2671 	up_write(&mm->mmap_sem);
2672 	return ret;
2673 }
2674 EXPORT_SYMBOL(vm_munmap);
2675 
SYSCALL_DEFINE2(munmap,unsigned long,addr,size_t,len)2676 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2677 {
2678 	profile_munmap(addr);
2679 	return vm_munmap(addr, len);
2680 }
2681 
verify_mm_writelocked(struct mm_struct * mm)2682 static inline void verify_mm_writelocked(struct mm_struct *mm)
2683 {
2684 #ifdef CONFIG_DEBUG_VM
2685 	if (unlikely(down_read_trylock(&mm->mmap_sem))) {
2686 		WARN_ON(1);
2687 		up_read(&mm->mmap_sem);
2688 	}
2689 #endif
2690 }
2691 
2692 /*
2693  *  this is really a simplified "do_mmap".  it only handles
2694  *  anonymous maps.  eventually we may be able to do some
2695  *  brk-specific accounting here.
2696  */
do_brk(unsigned long addr,unsigned long len)2697 static unsigned long do_brk(unsigned long addr, unsigned long len)
2698 {
2699 	struct mm_struct *mm = current->mm;
2700 	struct vm_area_struct *vma, *prev;
2701 	unsigned long flags;
2702 	struct rb_node **rb_link, *rb_parent;
2703 	pgoff_t pgoff = addr >> PAGE_SHIFT;
2704 	int error;
2705 
2706 	len = PAGE_ALIGN(len);
2707 	if (!len)
2708 		return addr;
2709 
2710 	flags = VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2711 
2712 	error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
2713 	if (error & ~PAGE_MASK)
2714 		return error;
2715 
2716 	error = mlock_future_check(mm, mm->def_flags, len);
2717 	if (error)
2718 		return error;
2719 
2720 	/*
2721 	 * mm->mmap_sem is required to protect against another thread
2722 	 * changing the mappings in case we sleep.
2723 	 */
2724 	verify_mm_writelocked(mm);
2725 
2726 	/*
2727 	 * Clear old maps.  this also does some error checking for us
2728 	 */
2729  munmap_back:
2730 	if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent)) {
2731 		if (do_munmap(mm, addr, len))
2732 			return -ENOMEM;
2733 		goto munmap_back;
2734 	}
2735 
2736 	/* Check against address space limits *after* clearing old maps... */
2737 	if (!may_expand_vm(mm, len >> PAGE_SHIFT))
2738 		return -ENOMEM;
2739 
2740 	if (mm->map_count > sysctl_max_map_count)
2741 		return -ENOMEM;
2742 
2743 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
2744 		return -ENOMEM;
2745 
2746 	/* Can we just expand an old private anonymous mapping? */
2747 	vma = vma_merge(mm, prev, addr, addr + len, flags,
2748 					NULL, NULL, pgoff, NULL, NULL);
2749 	if (vma)
2750 		goto out;
2751 
2752 	/*
2753 	 * create a vma struct for an anonymous mapping
2754 	 */
2755 	vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
2756 	if (!vma) {
2757 		vm_unacct_memory(len >> PAGE_SHIFT);
2758 		return -ENOMEM;
2759 	}
2760 
2761 	INIT_LIST_HEAD(&vma->anon_vma_chain);
2762 	vma->vm_mm = mm;
2763 	vma->vm_start = addr;
2764 	vma->vm_end = addr + len;
2765 	vma->vm_pgoff = pgoff;
2766 	vma->vm_flags = flags;
2767 	vma->vm_page_prot = vm_get_page_prot(flags);
2768 	vma_link(mm, vma, prev, rb_link, rb_parent);
2769 out:
2770 	perf_event_mmap(vma);
2771 	mm->total_vm += len >> PAGE_SHIFT;
2772 	if (flags & VM_LOCKED)
2773 		mm->locked_vm += (len >> PAGE_SHIFT);
2774 	vma->vm_flags |= VM_SOFTDIRTY;
2775 	return addr;
2776 }
2777 
vm_brk(unsigned long addr,unsigned long len)2778 unsigned long vm_brk(unsigned long addr, unsigned long len)
2779 {
2780 	struct mm_struct *mm = current->mm;
2781 	unsigned long ret;
2782 	bool populate;
2783 
2784 	down_write(&mm->mmap_sem);
2785 	ret = do_brk(addr, len);
2786 	populate = ((mm->def_flags & VM_LOCKED) != 0);
2787 	up_write(&mm->mmap_sem);
2788 	if (populate)
2789 		mm_populate(addr, len);
2790 	return ret;
2791 }
2792 EXPORT_SYMBOL(vm_brk);
2793 
2794 /* Release all mmaps. */
exit_mmap(struct mm_struct * mm)2795 void exit_mmap(struct mm_struct *mm)
2796 {
2797 	struct mmu_gather tlb;
2798 	struct vm_area_struct *vma;
2799 	unsigned long nr_accounted = 0;
2800 
2801 	/* mm's last user has gone, and its about to be pulled down */
2802 	mmu_notifier_release(mm);
2803 
2804 	if (mm->locked_vm) {
2805 		vma = mm->mmap;
2806 		while (vma) {
2807 			if (vma->vm_flags & VM_LOCKED)
2808 				munlock_vma_pages_all(vma);
2809 			vma = vma->vm_next;
2810 		}
2811 	}
2812 
2813 	arch_exit_mmap(mm);
2814 
2815 	vma = mm->mmap;
2816 	if (!vma)	/* Can happen if dup_mmap() received an OOM */
2817 		return;
2818 
2819 	lru_add_drain();
2820 	flush_cache_mm(mm);
2821 	tlb_gather_mmu(&tlb, mm, 0, -1);
2822 	/* update_hiwater_rss(mm) here? but nobody should be looking */
2823 	/* Use -1 here to ensure all VMAs in the mm are unmapped */
2824 	unmap_vmas(&tlb, vma, 0, -1);
2825 
2826 	free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
2827 	tlb_finish_mmu(&tlb, 0, -1);
2828 
2829 	/*
2830 	 * Walk the list again, actually closing and freeing it,
2831 	 * with preemption enabled, without holding any MM locks.
2832 	 */
2833 	while (vma) {
2834 		if (vma->vm_flags & VM_ACCOUNT)
2835 			nr_accounted += vma_pages(vma);
2836 		vma = remove_vma(vma);
2837 	}
2838 	vm_unacct_memory(nr_accounted);
2839 
2840 	WARN_ON(atomic_long_read(&mm->nr_ptes) >
2841 			(FIRST_USER_ADDRESS+PMD_SIZE-1)>>PMD_SHIFT);
2842 }
2843 
2844 /* Insert vm structure into process list sorted by address
2845  * and into the inode's i_mmap tree.  If vm_file is non-NULL
2846  * then i_mmap_mutex is taken here.
2847  */
insert_vm_struct(struct mm_struct * mm,struct vm_area_struct * vma)2848 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
2849 {
2850 	struct vm_area_struct *prev;
2851 	struct rb_node **rb_link, *rb_parent;
2852 
2853 	/*
2854 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
2855 	 * until its first write fault, when page's anon_vma and index
2856 	 * are set.  But now set the vm_pgoff it will almost certainly
2857 	 * end up with (unless mremap moves it elsewhere before that
2858 	 * first wfault), so /proc/pid/maps tells a consistent story.
2859 	 *
2860 	 * By setting it to reflect the virtual start address of the
2861 	 * vma, merges and splits can happen in a seamless way, just
2862 	 * using the existing file pgoff checks and manipulations.
2863 	 * Similarly in do_mmap_pgoff and in do_brk.
2864 	 */
2865 	if (!vma->vm_file) {
2866 		BUG_ON(vma->anon_vma);
2867 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
2868 	}
2869 	if (find_vma_links(mm, vma->vm_start, vma->vm_end,
2870 			   &prev, &rb_link, &rb_parent))
2871 		return -ENOMEM;
2872 	if ((vma->vm_flags & VM_ACCOUNT) &&
2873 	     security_vm_enough_memory_mm(mm, vma_pages(vma)))
2874 		return -ENOMEM;
2875 
2876 	vma_link(mm, vma, prev, rb_link, rb_parent);
2877 	return 0;
2878 }
2879 
2880 /*
2881  * Copy the vma structure to a new location in the same mm,
2882  * prior to moving page table entries, to effect an mremap move.
2883  */
copy_vma(struct vm_area_struct ** vmap,unsigned long addr,unsigned long len,pgoff_t pgoff,bool * need_rmap_locks)2884 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
2885 	unsigned long addr, unsigned long len, pgoff_t pgoff,
2886 	bool *need_rmap_locks)
2887 {
2888 	struct vm_area_struct *vma = *vmap;
2889 	unsigned long vma_start = vma->vm_start;
2890 	struct mm_struct *mm = vma->vm_mm;
2891 	struct vm_area_struct *new_vma, *prev;
2892 	struct rb_node **rb_link, *rb_parent;
2893 	bool faulted_in_anon_vma = true;
2894 
2895 	/*
2896 	 * If anonymous vma has not yet been faulted, update new pgoff
2897 	 * to match new location, to increase its chance of merging.
2898 	 */
2899 	if (unlikely(!vma->vm_file && !vma->anon_vma)) {
2900 		pgoff = addr >> PAGE_SHIFT;
2901 		faulted_in_anon_vma = false;
2902 	}
2903 
2904 	if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
2905 		return NULL;	/* should never get here */
2906 	new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
2907 			vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
2908 			vma_get_anon_name(vma));
2909 	if (new_vma) {
2910 		/*
2911 		 * Source vma may have been merged into new_vma
2912 		 */
2913 		if (unlikely(vma_start >= new_vma->vm_start &&
2914 			     vma_start < new_vma->vm_end)) {
2915 			/*
2916 			 * The only way we can get a vma_merge with
2917 			 * self during an mremap is if the vma hasn't
2918 			 * been faulted in yet and we were allowed to
2919 			 * reset the dst vma->vm_pgoff to the
2920 			 * destination address of the mremap to allow
2921 			 * the merge to happen. mremap must change the
2922 			 * vm_pgoff linearity between src and dst vmas
2923 			 * (in turn preventing a vma_merge) to be
2924 			 * safe. It is only safe to keep the vm_pgoff
2925 			 * linear if there are no pages mapped yet.
2926 			 */
2927 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
2928 			*vmap = vma = new_vma;
2929 		}
2930 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
2931 	} else {
2932 		new_vma = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
2933 		if (new_vma) {
2934 			*new_vma = *vma;
2935 			new_vma->vm_start = addr;
2936 			new_vma->vm_end = addr + len;
2937 			new_vma->vm_pgoff = pgoff;
2938 			if (vma_dup_policy(vma, new_vma))
2939 				goto out_free_vma;
2940 			INIT_LIST_HEAD(&new_vma->anon_vma_chain);
2941 			if (anon_vma_clone(new_vma, vma))
2942 				goto out_free_mempol;
2943 			if (new_vma->vm_file)
2944 				get_file(new_vma->vm_file);
2945 			if (new_vma->vm_ops && new_vma->vm_ops->open)
2946 				new_vma->vm_ops->open(new_vma);
2947 			vma_link(mm, new_vma, prev, rb_link, rb_parent);
2948 			*need_rmap_locks = false;
2949 		}
2950 	}
2951 	return new_vma;
2952 
2953  out_free_mempol:
2954 	mpol_put(vma_policy(new_vma));
2955  out_free_vma:
2956 	kmem_cache_free(vm_area_cachep, new_vma);
2957 	return NULL;
2958 }
2959 
2960 /*
2961  * Return true if the calling process may expand its vm space by the passed
2962  * number of pages
2963  */
may_expand_vm(struct mm_struct * mm,unsigned long npages)2964 int may_expand_vm(struct mm_struct *mm, unsigned long npages)
2965 {
2966 	unsigned long cur = mm->total_vm;	/* pages */
2967 	unsigned long lim;
2968 
2969 	lim = rlimit(RLIMIT_AS) >> PAGE_SHIFT;
2970 
2971 	if (cur + npages > lim)
2972 		return 0;
2973 	return 1;
2974 }
2975 
2976 static int special_mapping_fault(struct vm_area_struct *vma,
2977 				 struct vm_fault *vmf);
2978 
2979 /*
2980  * Having a close hook prevents vma merging regardless of flags.
2981  */
special_mapping_close(struct vm_area_struct * vma)2982 static void special_mapping_close(struct vm_area_struct *vma)
2983 {
2984 }
2985 
special_mapping_name(struct vm_area_struct * vma)2986 static const char *special_mapping_name(struct vm_area_struct *vma)
2987 {
2988 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
2989 }
2990 
2991 static const struct vm_operations_struct special_mapping_vmops = {
2992 	.close = special_mapping_close,
2993 	.fault = special_mapping_fault,
2994 	.name = special_mapping_name,
2995 };
2996 
2997 static const struct vm_operations_struct legacy_special_mapping_vmops = {
2998 	.close = special_mapping_close,
2999 	.fault = special_mapping_fault,
3000 };
3001 
special_mapping_fault(struct vm_area_struct * vma,struct vm_fault * vmf)3002 static int special_mapping_fault(struct vm_area_struct *vma,
3003 				struct vm_fault *vmf)
3004 {
3005 	pgoff_t pgoff;
3006 	struct page **pages;
3007 
3008 	/*
3009 	 * special mappings have no vm_file, and in that case, the mm
3010 	 * uses vm_pgoff internally. So we have to subtract it from here.
3011 	 * We are allowed to do this because we are the mm; do not copy
3012 	 * this code into drivers!
3013 	 */
3014 	pgoff = vmf->pgoff - vma->vm_pgoff;
3015 
3016 	if (vma->vm_ops == &legacy_special_mapping_vmops)
3017 		pages = vma->vm_private_data;
3018 	else
3019 		pages = ((struct vm_special_mapping *)vma->vm_private_data)->
3020 			pages;
3021 
3022 	for (; pgoff && *pages; ++pages)
3023 		pgoff--;
3024 
3025 	if (*pages) {
3026 		struct page *page = *pages;
3027 		get_page(page);
3028 		vmf->page = page;
3029 		return 0;
3030 	}
3031 
3032 	return VM_FAULT_SIGBUS;
3033 }
3034 
__install_special_mapping(struct mm_struct * mm,unsigned long addr,unsigned long len,unsigned long vm_flags,const struct vm_operations_struct * ops,void * priv)3035 static struct vm_area_struct *__install_special_mapping(
3036 	struct mm_struct *mm,
3037 	unsigned long addr, unsigned long len,
3038 	unsigned long vm_flags, const struct vm_operations_struct *ops,
3039 	void *priv)
3040 {
3041 	int ret;
3042 	struct vm_area_struct *vma;
3043 
3044 	vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
3045 	if (unlikely(vma == NULL))
3046 		return ERR_PTR(-ENOMEM);
3047 
3048 	INIT_LIST_HEAD(&vma->anon_vma_chain);
3049 	vma->vm_mm = mm;
3050 	vma->vm_start = addr;
3051 	vma->vm_end = addr + len;
3052 
3053 	vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3054 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3055 
3056 	vma->vm_ops = ops;
3057 	vma->vm_private_data = priv;
3058 
3059 	ret = insert_vm_struct(mm, vma);
3060 	if (ret)
3061 		goto out;
3062 
3063 	mm->total_vm += len >> PAGE_SHIFT;
3064 
3065 	perf_event_mmap(vma);
3066 
3067 	return vma;
3068 
3069 out:
3070 	kmem_cache_free(vm_area_cachep, vma);
3071 	return ERR_PTR(ret);
3072 }
3073 
3074 /*
3075  * Called with mm->mmap_sem held for writing.
3076  * Insert a new vma covering the given region, with the given flags.
3077  * Its pages are supplied by the given array of struct page *.
3078  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3079  * The region past the last page supplied will always produce SIGBUS.
3080  * The array pointer and the pages it points to are assumed to stay alive
3081  * for as long as this mapping might exist.
3082  */
_install_special_mapping(struct mm_struct * mm,unsigned long addr,unsigned long len,unsigned long vm_flags,const struct vm_special_mapping * spec)3083 struct vm_area_struct *_install_special_mapping(
3084 	struct mm_struct *mm,
3085 	unsigned long addr, unsigned long len,
3086 	unsigned long vm_flags, const struct vm_special_mapping *spec)
3087 {
3088 	return __install_special_mapping(mm, addr, len, vm_flags,
3089 					 &special_mapping_vmops, (void *)spec);
3090 }
3091 
install_special_mapping(struct mm_struct * mm,unsigned long addr,unsigned long len,unsigned long vm_flags,struct page ** pages)3092 int install_special_mapping(struct mm_struct *mm,
3093 			    unsigned long addr, unsigned long len,
3094 			    unsigned long vm_flags, struct page **pages)
3095 {
3096 	struct vm_area_struct *vma = __install_special_mapping(
3097 		mm, addr, len, vm_flags, &legacy_special_mapping_vmops,
3098 		(void *)pages);
3099 
3100 	return PTR_ERR_OR_ZERO(vma);
3101 }
3102 
3103 static DEFINE_MUTEX(mm_all_locks_mutex);
3104 
vm_lock_anon_vma(struct mm_struct * mm,struct anon_vma * anon_vma)3105 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3106 {
3107 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3108 		/*
3109 		 * The LSB of head.next can't change from under us
3110 		 * because we hold the mm_all_locks_mutex.
3111 		 */
3112 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
3113 		/*
3114 		 * We can safely modify head.next after taking the
3115 		 * anon_vma->root->rwsem. If some other vma in this mm shares
3116 		 * the same anon_vma we won't take it again.
3117 		 *
3118 		 * No need of atomic instructions here, head.next
3119 		 * can't change from under us thanks to the
3120 		 * anon_vma->root->rwsem.
3121 		 */
3122 		if (__test_and_set_bit(0, (unsigned long *)
3123 				       &anon_vma->root->rb_root.rb_node))
3124 			BUG();
3125 	}
3126 }
3127 
vm_lock_mapping(struct mm_struct * mm,struct address_space * mapping)3128 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3129 {
3130 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3131 		/*
3132 		 * AS_MM_ALL_LOCKS can't change from under us because
3133 		 * we hold the mm_all_locks_mutex.
3134 		 *
3135 		 * Operations on ->flags have to be atomic because
3136 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
3137 		 * mm_all_locks_mutex, there may be other cpus
3138 		 * changing other bitflags in parallel to us.
3139 		 */
3140 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3141 			BUG();
3142 		mutex_lock_nest_lock(&mapping->i_mmap_mutex, &mm->mmap_sem);
3143 	}
3144 }
3145 
3146 /*
3147  * This operation locks against the VM for all pte/vma/mm related
3148  * operations that could ever happen on a certain mm. This includes
3149  * vmtruncate, try_to_unmap, and all page faults.
3150  *
3151  * The caller must take the mmap_sem in write mode before calling
3152  * mm_take_all_locks(). The caller isn't allowed to release the
3153  * mmap_sem until mm_drop_all_locks() returns.
3154  *
3155  * mmap_sem in write mode is required in order to block all operations
3156  * that could modify pagetables and free pages without need of
3157  * altering the vma layout (for example populate_range() with
3158  * nonlinear vmas). It's also needed in write mode to avoid new
3159  * anon_vmas to be associated with existing vmas.
3160  *
3161  * A single task can't take more than one mm_take_all_locks() in a row
3162  * or it would deadlock.
3163  *
3164  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3165  * mapping->flags avoid to take the same lock twice, if more than one
3166  * vma in this mm is backed by the same anon_vma or address_space.
3167  *
3168  * We can take all the locks in random order because the VM code
3169  * taking i_mmap_mutex or anon_vma->rwsem outside the mmap_sem never
3170  * takes more than one of them in a row. Secondly we're protected
3171  * against a concurrent mm_take_all_locks() by the mm_all_locks_mutex.
3172  *
3173  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3174  * that may have to take thousand of locks.
3175  *
3176  * mm_take_all_locks() can fail if it's interrupted by signals.
3177  */
mm_take_all_locks(struct mm_struct * mm)3178 int mm_take_all_locks(struct mm_struct *mm)
3179 {
3180 	struct vm_area_struct *vma;
3181 	struct anon_vma_chain *avc;
3182 
3183 	BUG_ON(down_read_trylock(&mm->mmap_sem));
3184 
3185 	mutex_lock(&mm_all_locks_mutex);
3186 
3187 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
3188 		if (signal_pending(current))
3189 			goto out_unlock;
3190 		if (vma->vm_file && vma->vm_file->f_mapping)
3191 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
3192 	}
3193 
3194 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
3195 		if (signal_pending(current))
3196 			goto out_unlock;
3197 		if (vma->anon_vma)
3198 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3199 				vm_lock_anon_vma(mm, avc->anon_vma);
3200 	}
3201 
3202 	return 0;
3203 
3204 out_unlock:
3205 	mm_drop_all_locks(mm);
3206 	return -EINTR;
3207 }
3208 
vm_unlock_anon_vma(struct anon_vma * anon_vma)3209 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3210 {
3211 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_node)) {
3212 		/*
3213 		 * The LSB of head.next can't change to 0 from under
3214 		 * us because we hold the mm_all_locks_mutex.
3215 		 *
3216 		 * We must however clear the bitflag before unlocking
3217 		 * the vma so the users using the anon_vma->rb_root will
3218 		 * never see our bitflag.
3219 		 *
3220 		 * No need of atomic instructions here, head.next
3221 		 * can't change from under us until we release the
3222 		 * anon_vma->root->rwsem.
3223 		 */
3224 		if (!__test_and_clear_bit(0, (unsigned long *)
3225 					  &anon_vma->root->rb_root.rb_node))
3226 			BUG();
3227 		anon_vma_unlock_write(anon_vma);
3228 	}
3229 }
3230 
vm_unlock_mapping(struct address_space * mapping)3231 static void vm_unlock_mapping(struct address_space *mapping)
3232 {
3233 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3234 		/*
3235 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
3236 		 * because we hold the mm_all_locks_mutex.
3237 		 */
3238 		mutex_unlock(&mapping->i_mmap_mutex);
3239 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3240 					&mapping->flags))
3241 			BUG();
3242 	}
3243 }
3244 
3245 /*
3246  * The mmap_sem cannot be released by the caller until
3247  * mm_drop_all_locks() returns.
3248  */
mm_drop_all_locks(struct mm_struct * mm)3249 void mm_drop_all_locks(struct mm_struct *mm)
3250 {
3251 	struct vm_area_struct *vma;
3252 	struct anon_vma_chain *avc;
3253 
3254 	BUG_ON(down_read_trylock(&mm->mmap_sem));
3255 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3256 
3257 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
3258 		if (vma->anon_vma)
3259 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3260 				vm_unlock_anon_vma(avc->anon_vma);
3261 		if (vma->vm_file && vma->vm_file->f_mapping)
3262 			vm_unlock_mapping(vma->vm_file->f_mapping);
3263 	}
3264 
3265 	mutex_unlock(&mm_all_locks_mutex);
3266 }
3267 
3268 /*
3269  * initialise the VMA slab
3270  */
mmap_init(void)3271 void __init mmap_init(void)
3272 {
3273 	int ret;
3274 
3275 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3276 	VM_BUG_ON(ret);
3277 }
3278 
3279 /*
3280  * Initialise sysctl_user_reserve_kbytes.
3281  *
3282  * This is intended to prevent a user from starting a single memory hogging
3283  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3284  * mode.
3285  *
3286  * The default value is min(3% of free memory, 128MB)
3287  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3288  */
init_user_reserve(void)3289 static int init_user_reserve(void)
3290 {
3291 	unsigned long free_kbytes;
3292 
3293 	free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3294 
3295 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3296 	return 0;
3297 }
3298 subsys_initcall(init_user_reserve);
3299 
3300 /*
3301  * Initialise sysctl_admin_reserve_kbytes.
3302  *
3303  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3304  * to log in and kill a memory hogging process.
3305  *
3306  * Systems with more than 256MB will reserve 8MB, enough to recover
3307  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3308  * only reserve 3% of free pages by default.
3309  */
init_admin_reserve(void)3310 static int init_admin_reserve(void)
3311 {
3312 	unsigned long free_kbytes;
3313 
3314 	free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3315 
3316 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3317 	return 0;
3318 }
3319 subsys_initcall(init_admin_reserve);
3320 
3321 /*
3322  * Reinititalise user and admin reserves if memory is added or removed.
3323  *
3324  * The default user reserve max is 128MB, and the default max for the
3325  * admin reserve is 8MB. These are usually, but not always, enough to
3326  * enable recovery from a memory hogging process using login/sshd, a shell,
3327  * and tools like top. It may make sense to increase or even disable the
3328  * reserve depending on the existence of swap or variations in the recovery
3329  * tools. So, the admin may have changed them.
3330  *
3331  * If memory is added and the reserves have been eliminated or increased above
3332  * the default max, then we'll trust the admin.
3333  *
3334  * If memory is removed and there isn't enough free memory, then we
3335  * need to reset the reserves.
3336  *
3337  * Otherwise keep the reserve set by the admin.
3338  */
reserve_mem_notifier(struct notifier_block * nb,unsigned long action,void * data)3339 static int reserve_mem_notifier(struct notifier_block *nb,
3340 			     unsigned long action, void *data)
3341 {
3342 	unsigned long tmp, free_kbytes;
3343 
3344 	switch (action) {
3345 	case MEM_ONLINE:
3346 		/* Default max is 128MB. Leave alone if modified by operator. */
3347 		tmp = sysctl_user_reserve_kbytes;
3348 		if (0 < tmp && tmp < (1UL << 17))
3349 			init_user_reserve();
3350 
3351 		/* Default max is 8MB.  Leave alone if modified by operator. */
3352 		tmp = sysctl_admin_reserve_kbytes;
3353 		if (0 < tmp && tmp < (1UL << 13))
3354 			init_admin_reserve();
3355 
3356 		break;
3357 	case MEM_OFFLINE:
3358 		free_kbytes = global_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3359 
3360 		if (sysctl_user_reserve_kbytes > free_kbytes) {
3361 			init_user_reserve();
3362 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
3363 				sysctl_user_reserve_kbytes);
3364 		}
3365 
3366 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
3367 			init_admin_reserve();
3368 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3369 				sysctl_admin_reserve_kbytes);
3370 		}
3371 		break;
3372 	default:
3373 		break;
3374 	}
3375 	return NOTIFY_OK;
3376 }
3377 
3378 static struct notifier_block reserve_mem_nb = {
3379 	.notifier_call = reserve_mem_notifier,
3380 };
3381 
init_reserve_notifier(void)3382 static int __meminit init_reserve_notifier(void)
3383 {
3384 	if (register_hotmemory_notifier(&reserve_mem_nb))
3385 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3386 
3387 	return 0;
3388 }
3389 subsys_initcall(init_reserve_notifier);
3390