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