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