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