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