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