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