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