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