• 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 	vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
2426 
2427 	if (new_below) {
2428 		vma->vm_start = addr;
2429 		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
2430 	} else {
2431 		vma->vm_end = addr;
2432 	}
2433 
2434 	/* vma_complete stores the new vma */
2435 	vma_complete(&vp, vmi, vma->vm_mm);
2436 
2437 	/* Success. */
2438 	if (new_below)
2439 		vma_next(vmi);
2440 	return 0;
2441 
2442 out_free_mpol:
2443 	mpol_put(vma_policy(new));
2444 out_free_vmi:
2445 	vma_iter_free(vmi);
2446 out_free_vma:
2447 	vm_area_free(new);
2448 	return err;
2449 }
2450 
2451 /*
2452  * Split a vma into two pieces at address 'addr', a new vma is allocated
2453  * either for the first part or the tail.
2454  */
split_vma(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long addr,int new_below)2455 int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
2456 	      unsigned long addr, int new_below)
2457 {
2458 	if (vma->vm_mm->map_count >= sysctl_max_map_count)
2459 		return -ENOMEM;
2460 
2461 	return __split_vma(vmi, vma, addr, new_below);
2462 }
2463 
2464 /*
2465  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
2466  * @vmi: The vma iterator
2467  * @vma: The starting vm_area_struct
2468  * @mm: The mm_struct
2469  * @start: The aligned start address to munmap.
2470  * @end: The aligned end address to munmap.
2471  * @uf: The userfaultfd list_head
2472  * @unlock: Set to true to drop the mmap_lock.  unlocking only happens on
2473  * success.
2474  *
2475  * Return: 0 on success and drops the lock if so directed, error and leaves the
2476  * lock held otherwise.
2477  */
2478 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)2479 do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
2480 		    struct mm_struct *mm, unsigned long start,
2481 		    unsigned long end, struct list_head *uf, bool unlock)
2482 {
2483 	struct vm_area_struct *prev, *next = NULL;
2484 	struct maple_tree mt_detach;
2485 	int count = 0;
2486 	int error = -ENOMEM;
2487 	unsigned long locked_vm = 0;
2488 	MA_STATE(mas_detach, &mt_detach, 0, 0);
2489 	mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
2490 	mt_on_stack(mt_detach);
2491 
2492 	/*
2493 	 * If we need to split any vma, do it now to save pain later.
2494 	 *
2495 	 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2496 	 * unmapped vm_area_struct will remain in use: so lower split_vma
2497 	 * places tmp vma above, and higher split_vma places tmp vma below.
2498 	 */
2499 
2500 	/* Does it split the first one? */
2501 	if (start > vma->vm_start) {
2502 
2503 		/*
2504 		 * Make sure that map_count on return from munmap() will
2505 		 * not exceed its limit; but let map_count go just above
2506 		 * its limit temporarily, to help free resources as expected.
2507 		 */
2508 		if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2509 			goto map_count_exceeded;
2510 
2511 		error = __split_vma(vmi, vma, start, 1);
2512 		if (error)
2513 			goto start_split_failed;
2514 	}
2515 
2516 	/*
2517 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
2518 	 * it is always overwritten.
2519 	 */
2520 	next = vma;
2521 	do {
2522 		/* Does it split the end? */
2523 		if (next->vm_end > end) {
2524 			error = __split_vma(vmi, next, end, 0);
2525 			if (error)
2526 				goto end_split_failed;
2527 		}
2528 		vma_start_write(next);
2529 		mas_set(&mas_detach, count);
2530 		error = mas_store_gfp(&mas_detach, next, GFP_KERNEL);
2531 		if (error)
2532 			goto munmap_gather_failed;
2533 		vma_mark_detached(next, true);
2534 		if (next->vm_flags & VM_LOCKED)
2535 			locked_vm += vma_pages(next);
2536 
2537 		count++;
2538 		if (unlikely(uf)) {
2539 			/*
2540 			 * If userfaultfd_unmap_prep returns an error the vmas
2541 			 * will remain split, but userland will get a
2542 			 * highly unexpected error anyway. This is no
2543 			 * different than the case where the first of the two
2544 			 * __split_vma fails, but we don't undo the first
2545 			 * split, despite we could. This is unlikely enough
2546 			 * failure that it's not worth optimizing it for.
2547 			 */
2548 			error = userfaultfd_unmap_prep(next, start, end, uf);
2549 
2550 			if (error)
2551 				goto userfaultfd_error;
2552 		}
2553 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
2554 		BUG_ON(next->vm_start < start);
2555 		BUG_ON(next->vm_start > end);
2556 #endif
2557 	} for_each_vma_range(*vmi, next, end);
2558 
2559 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2560 	/* Make sure no VMAs are about to be lost. */
2561 	{
2562 		MA_STATE(test, &mt_detach, 0, 0);
2563 		struct vm_area_struct *vma_mas, *vma_test;
2564 		int test_count = 0;
2565 
2566 		vma_iter_set(vmi, start);
2567 		rcu_read_lock();
2568 		vma_test = mas_find(&test, count - 1);
2569 		for_each_vma_range(*vmi, vma_mas, end) {
2570 			BUG_ON(vma_mas != vma_test);
2571 			test_count++;
2572 			vma_test = mas_next(&test, count - 1);
2573 		}
2574 		rcu_read_unlock();
2575 		BUG_ON(count != test_count);
2576 	}
2577 #endif
2578 
2579 	while (vma_iter_addr(vmi) > start)
2580 		vma_iter_prev_range(vmi);
2581 
2582 	error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
2583 	if (error)
2584 		goto clear_tree_failed;
2585 
2586 	/* Point of no return */
2587 	mm->locked_vm -= locked_vm;
2588 	mm->map_count -= count;
2589 	if (unlock)
2590 		mmap_write_downgrade(mm);
2591 
2592 	prev = vma_iter_prev_range(vmi);
2593 	next = vma_next(vmi);
2594 	if (next)
2595 		vma_iter_prev_range(vmi);
2596 
2597 	/*
2598 	 * We can free page tables without write-locking mmap_lock because VMAs
2599 	 * were isolated before we downgraded mmap_lock.
2600 	 */
2601 	mas_set(&mas_detach, 1);
2602 	unmap_region(mm, &mas_detach, vma, prev, next, start, end, count,
2603 		     !unlock);
2604 	/* Statistics and freeing VMAs */
2605 	mas_set(&mas_detach, 0);
2606 	remove_mt(mm, &mas_detach);
2607 	validate_mm(mm);
2608 	if (unlock)
2609 		mmap_read_unlock(mm);
2610 
2611 	__mt_destroy(&mt_detach);
2612 	return 0;
2613 
2614 clear_tree_failed:
2615 userfaultfd_error:
2616 munmap_gather_failed:
2617 end_split_failed:
2618 	mas_set(&mas_detach, 0);
2619 	mas_for_each(&mas_detach, next, end)
2620 		vma_mark_detached(next, false);
2621 
2622 	__mt_destroy(&mt_detach);
2623 start_split_failed:
2624 map_count_exceeded:
2625 	validate_mm(mm);
2626 	return error;
2627 }
2628 
2629 /*
2630  * do_vmi_munmap() - munmap a given range.
2631  * @vmi: The vma iterator
2632  * @mm: The mm_struct
2633  * @start: The start address to munmap
2634  * @len: The length of the range to munmap
2635  * @uf: The userfaultfd list_head
2636  * @unlock: set to true if the user wants to drop the mmap_lock on success
2637  *
2638  * This function takes a @mas that is either pointing to the previous VMA or set
2639  * to MA_START and sets it up to remove the mapping(s).  The @len will be
2640  * aligned and any arch_unmap work will be preformed.
2641  *
2642  * Return: 0 on success and drops the lock if so directed, error and leaves the
2643  * lock held otherwise.
2644  */
do_vmi_munmap(struct vma_iterator * vmi,struct mm_struct * mm,unsigned long start,size_t len,struct list_head * uf,bool unlock)2645 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
2646 		  unsigned long start, size_t len, struct list_head *uf,
2647 		  bool unlock)
2648 {
2649 	unsigned long end;
2650 	struct vm_area_struct *vma;
2651 
2652 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2653 		return -EINVAL;
2654 
2655 	end = start + PAGE_ALIGN(len);
2656 	if (end == start)
2657 		return -EINVAL;
2658 
2659 	int errno = 0;
2660 	CALL_HCK_LITE_HOOK(delete_jit_memory_lhck, current, start, len, &errno);
2661 	if (errno)
2662 		return errno;
2663 
2664 	 /* arch_unmap() might do unmaps itself.  */
2665 	arch_unmap(mm, start, end);
2666 
2667 	/* Find the first overlapping VMA */
2668 	vma = vma_find(vmi, end);
2669 	if (!vma) {
2670 		if (unlock)
2671 			mmap_write_unlock(mm);
2672 		return 0;
2673 	}
2674 
2675 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
2676 }
2677 
2678 /* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
2679  * @mm: The mm_struct
2680  * @start: The start address to munmap
2681  * @len: The length to be munmapped.
2682  * @uf: The userfaultfd list_head
2683  *
2684  * Return: 0 on success, error otherwise.
2685  */
do_munmap(struct mm_struct * mm,unsigned long start,size_t len,struct list_head * uf)2686 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2687 	      struct list_head *uf)
2688 {
2689 	VMA_ITERATOR(vmi, mm, start);
2690 
2691 	return do_vmi_munmap(&vmi, mm, start, len, uf, false);
2692 }
2693 
__mmap_region(struct file * file,unsigned long addr,unsigned long len,vm_flags_t vm_flags,unsigned long pgoff,struct list_head * uf)2694 static unsigned long __mmap_region(struct file *file, unsigned long addr,
2695 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2696 		struct list_head *uf)
2697 {
2698 	struct mm_struct *mm = current->mm;
2699 	struct vm_area_struct *vma = NULL;
2700 	struct vm_area_struct *next, *prev, *merge;
2701 	pgoff_t pglen = PHYS_PFN(len);
2702 	unsigned long charged = 0;
2703 	unsigned long end = addr + len;
2704 	unsigned long merge_start = addr, merge_end = end;
2705 	pgoff_t vm_pgoff;
2706 	int error;
2707 	VMA_ITERATOR(vmi, mm, addr);
2708 
2709 	/* Check against address space limit. */
2710 	if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2711 		unsigned long nr_pages;
2712 
2713 		/*
2714 		 * MAP_FIXED may remove pages of mappings that intersects with
2715 		 * requested mapping. Account for the pages it would unmap.
2716 		 */
2717 		nr_pages = count_vma_pages_range(mm, addr, end);
2718 
2719 		if (!may_expand_vm(mm, vm_flags,
2720 					(len >> PAGE_SHIFT) - nr_pages))
2721 			return -ENOMEM;
2722 	}
2723 
2724 	/* Unmap any existing mapping in the area */
2725 	if (do_vmi_munmap(&vmi, mm, addr, len, uf, false))
2726 		return -ENOMEM;
2727 
2728 	/*
2729 	 * Private writable mapping: check memory availability
2730 	 */
2731 	if (accountable_mapping(file, vm_flags)) {
2732 		charged = len >> PAGE_SHIFT;
2733 		if (security_vm_enough_memory_mm(mm, charged))
2734 			return -ENOMEM;
2735 		vm_flags |= VM_ACCOUNT;
2736 	}
2737 
2738 	next = vma_next(&vmi);
2739 	prev = vma_prev(&vmi);
2740 	if (vm_flags & VM_SPECIAL) {
2741 		if (prev)
2742 			vma_iter_next_range(&vmi);
2743 		goto cannot_expand;
2744 	}
2745 
2746 	/* Attempt to expand an old mapping */
2747 	/* Check next */
2748 	if (next && next->vm_start == end && !vma_policy(next) &&
2749 	    can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2750 				 NULL_VM_UFFD_CTX, NULL)) {
2751 		merge_end = next->vm_end;
2752 		vma = next;
2753 		vm_pgoff = next->vm_pgoff - pglen;
2754 	}
2755 
2756 	/* Check prev */
2757 	if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2758 	    (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2759 				       pgoff, vma->vm_userfaultfd_ctx, NULL) :
2760 		   can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2761 				       NULL_VM_UFFD_CTX, NULL))) {
2762 		merge_start = prev->vm_start;
2763 		vma = prev;
2764 		vm_pgoff = prev->vm_pgoff;
2765 	} else if (prev) {
2766 		vma_iter_next_range(&vmi);
2767 	}
2768 
2769 	/* Actually expand, if possible */
2770 	if (vma &&
2771 	    !vma_expand(&vmi, vma, merge_start, merge_end, vm_pgoff, next)) {
2772 		khugepaged_enter_vma(vma, vm_flags);
2773 		goto expanded;
2774 	}
2775 
2776 	if (vma == prev)
2777 		vma_iter_set(&vmi, addr);
2778 cannot_expand:
2779 
2780 	/*
2781 	 * Determine the object being mapped and call the appropriate
2782 	 * specific mapper. the address has already been validated, but
2783 	 * not unmapped, but the maps are removed from the list.
2784 	 */
2785 	vma = vm_area_alloc(mm);
2786 	if (!vma) {
2787 		error = -ENOMEM;
2788 		goto unacct_error;
2789 	}
2790 
2791 	vma_iter_config(&vmi, addr, end);
2792 	vma->vm_start = addr;
2793 	vma->vm_end = end;
2794 	vm_flags_init(vma, vm_flags);
2795 	vma->vm_page_prot = vm_get_page_prot(vm_flags);
2796 	vma->vm_pgoff = pgoff;
2797 
2798 	if (vma_iter_prealloc(&vmi, vma)) {
2799 		error = -ENOMEM;
2800 		goto free_vma;
2801 	}
2802 
2803 	if (file) {
2804 		vma->vm_file = get_file(file);
2805 		error = mmap_file(file, vma);
2806 		if (error)
2807 			goto unmap_and_free_file_vma;
2808 
2809 		/* Drivers cannot alter the address of the VMA. */
2810 		WARN_ON_ONCE(addr != vma->vm_start);
2811 		/*
2812 		 * Drivers should not permit writability when previously it was
2813 		 * disallowed.
2814 		 */
2815 		VM_WARN_ON_ONCE(vm_flags != vma->vm_flags &&
2816 				!(vm_flags & VM_MAYWRITE) &&
2817 				(vma->vm_flags & VM_MAYWRITE));
2818 
2819 		vma_iter_config(&vmi, addr, end);
2820 		/*
2821 		 * If vm_flags changed after mmap_file(), we should try merge
2822 		 * vma again as we may succeed this time.
2823 		 */
2824 		if (unlikely(vm_flags != vma->vm_flags && prev)) {
2825 			merge = vma_merge(&vmi, mm, prev, vma->vm_start,
2826 				    vma->vm_end, vma->vm_flags, NULL,
2827 				    vma->vm_file, vma->vm_pgoff, NULL,
2828 				    NULL_VM_UFFD_CTX, NULL);
2829 
2830 			if (merge) {
2831 				/*
2832 				 * ->mmap() can change vma->vm_file and fput
2833 				 * the original file. So fput the vma->vm_file
2834 				 * here or we would add an extra fput for file
2835 				 * and cause general protection fault
2836 				 * ultimately.
2837 				 */
2838 				fput(vma->vm_file);
2839 				vm_area_free(vma);
2840 				vma = merge;
2841 				/* Update vm_flags to pick up the change. */
2842 				vm_flags = vma->vm_flags;
2843 				goto file_expanded;
2844 			}
2845 		}
2846 
2847 		vm_flags = vma->vm_flags;
2848 	} else if (vm_flags & VM_SHARED) {
2849 		error = shmem_zero_setup(vma);
2850 		if (error)
2851 			goto free_iter_vma;
2852 	} else {
2853 		vma_set_anonymous(vma);
2854 	}
2855 
2856 #ifdef CONFIG_SPARC64
2857 	/* TODO: Fix SPARC ADI! */
2858 	WARN_ON_ONCE(!arch_validate_flags(vm_flags));
2859 #endif
2860 
2861 	/* Lock the VMA since it is modified after insertion into VMA tree */
2862 	vma_start_write(vma);
2863 	vma_iter_store(&vmi, vma);
2864 	mm->map_count++;
2865 	if (vma->vm_file) {
2866 		i_mmap_lock_write(vma->vm_file->f_mapping);
2867 		if (vma->vm_flags & VM_SHARED)
2868 			mapping_allow_writable(vma->vm_file->f_mapping);
2869 
2870 		flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2871 		vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2872 		flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2873 		i_mmap_unlock_write(vma->vm_file->f_mapping);
2874 	}
2875 
2876 	/*
2877 	 * vma_merge() calls khugepaged_enter_vma() either, the below
2878 	 * call covers the non-merge case.
2879 	 */
2880 	khugepaged_enter_vma(vma, vma->vm_flags);
2881 
2882 file_expanded:
2883 	file = vma->vm_file;
2884 	ksm_add_vma(vma);
2885 expanded:
2886 	perf_event_mmap(vma);
2887 
2888 	vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2889 	if (vm_flags & VM_LOCKED) {
2890 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2891 					is_vm_hugetlb_page(vma) ||
2892 					vma == get_gate_vma(current->mm))
2893 			vm_flags_clear(vma, VM_LOCKED_MASK);
2894 		else
2895 			mm->locked_vm += (len >> PAGE_SHIFT);
2896 	}
2897 
2898 	if (file)
2899 		uprobe_mmap(vma);
2900 
2901 	/*
2902 	 * New (or expanded) vma always get soft dirty status.
2903 	 * Otherwise user-space soft-dirty page tracker won't
2904 	 * be able to distinguish situation when vma area unmapped,
2905 	 * then new mapped in-place (which must be aimed as
2906 	 * a completely new data area).
2907 	 */
2908 	vm_flags_set(vma, VM_SOFTDIRTY);
2909 
2910 	vma_set_page_prot(vma);
2911 
2912 	return addr;
2913 
2914 unmap_and_free_file_vma:
2915 	fput(vma->vm_file);
2916 	vma->vm_file = NULL;
2917 
2918 	vma_iter_set(&vmi, vma->vm_end);
2919 	/* Undo any partial mapping done by a device driver. */
2920 	unmap_region(mm, &vmi.mas, vma, prev, next, vma->vm_start,
2921 		     vma->vm_end, vma->vm_end, true);
2922 free_iter_vma:
2923 	vma_iter_free(&vmi);
2924 free_vma:
2925 	vm_area_free(vma);
2926 unacct_error:
2927 	if (charged)
2928 		vm_unacct_memory(charged);
2929 	return error;
2930 }
2931 
mmap_region(struct file * file,unsigned long addr,unsigned long len,vm_flags_t vm_flags,unsigned long pgoff,struct list_head * uf)2932 unsigned long mmap_region(struct file *file, unsigned long addr,
2933 			  unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2934 			  struct list_head *uf)
2935 {
2936 	unsigned long ret;
2937 	bool writable_file_mapping = false;
2938 
2939 	/* Check to see if MDWE is applicable. */
2940 	if (map_deny_write_exec(vm_flags, vm_flags))
2941 		return -EACCES;
2942 
2943 	/* Allow architectures to sanity-check the vm_flags. */
2944 	if (!arch_validate_flags(vm_flags))
2945 		return -EINVAL;
2946 
2947 	/* Map writable and ensure this isn't a sealed memfd. */
2948 	if (file && (vm_flags & VM_SHARED)) {
2949 		int error = mapping_map_writable(file->f_mapping);
2950 
2951 		if (error)
2952 			return error;
2953 		writable_file_mapping = true;
2954 	}
2955 
2956 	ret = __mmap_region(file, addr, len, vm_flags, pgoff, uf);
2957 
2958 	/* Clear our write mapping regardless of error. */
2959 	if (writable_file_mapping)
2960 		mapping_unmap_writable(file->f_mapping);
2961 
2962 	validate_mm(current->mm);
2963 	return ret;
2964 }
2965 
__vm_munmap(unsigned long start,size_t len,bool unlock)2966 static int __vm_munmap(unsigned long start, size_t len, bool unlock)
2967 {
2968 	int ret;
2969 	struct mm_struct *mm = current->mm;
2970 	LIST_HEAD(uf);
2971 	VMA_ITERATOR(vmi, mm, start);
2972 
2973 	if (mmap_write_lock_killable(mm))
2974 		return -EINTR;
2975 
2976 	ret = do_vmi_munmap(&vmi, mm, start, len, &uf, unlock);
2977 	if (ret || !unlock)
2978 		mmap_write_unlock(mm);
2979 
2980 	userfaultfd_unmap_complete(mm, &uf);
2981 	return ret;
2982 }
2983 
vm_munmap(unsigned long start,size_t len)2984 int vm_munmap(unsigned long start, size_t len)
2985 {
2986 	return __vm_munmap(start, len, false);
2987 }
2988 EXPORT_SYMBOL(vm_munmap);
2989 
SYSCALL_DEFINE2(munmap,unsigned long,addr,size_t,len)2990 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2991 {
2992 	addr = untagged_addr(addr);
2993 	return __vm_munmap(addr, len, true);
2994 }
2995 
2996 
2997 /*
2998  * Emulation of deprecated remap_file_pages() syscall.
2999  */
SYSCALL_DEFINE5(remap_file_pages,unsigned long,start,unsigned long,size,unsigned long,prot,unsigned long,pgoff,unsigned long,flags)3000 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
3001 		unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
3002 {
3003 
3004 	struct mm_struct *mm = current->mm;
3005 	struct vm_area_struct *vma;
3006 	unsigned long populate = 0;
3007 	unsigned long ret = -EINVAL;
3008 	struct file *file;
3009 	vm_flags_t vm_flags;
3010 
3011 	pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
3012 		     current->comm, current->pid);
3013 
3014 	if (prot)
3015 		return ret;
3016 	start = start & PAGE_MASK;
3017 	size = size & PAGE_MASK;
3018 
3019 	if (start + size <= start)
3020 		return ret;
3021 
3022 	/* Does pgoff wrap? */
3023 	if (pgoff + (size >> PAGE_SHIFT) < pgoff)
3024 		return ret;
3025 
3026 	if (mmap_read_lock_killable(mm))
3027 		return -EINTR;
3028 
3029 	/*
3030 	 * Look up VMA under read lock first so we can perform the security
3031 	 * without holding locks (which can be problematic). We reacquire a
3032 	 * write lock later and check nothing changed underneath us.
3033 	 */
3034 	vma = vma_lookup(mm, start);
3035 
3036 	if (!vma || !(vma->vm_flags & VM_SHARED)) {
3037 		mmap_read_unlock(mm);
3038 		return -EINVAL;
3039 	}
3040 
3041 	prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
3042 	prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
3043 	prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
3044 
3045 	flags &= MAP_NONBLOCK;
3046 	flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
3047 	if (vma->vm_flags & VM_LOCKED)
3048 		flags |= MAP_LOCKED;
3049 
3050 	/* Save vm_flags used to calculate prot and flags, and recheck later. */
3051 	vm_flags = vma->vm_flags;
3052 	file = get_file(vma->vm_file);
3053 
3054 	mmap_read_unlock(mm);
3055 
3056 	/* Call outside mmap_lock to be consistent with other callers. */
3057 	ret = security_mmap_file(file, prot, flags);
3058 	if (ret) {
3059 		fput(file);
3060 		return ret;
3061 	}
3062 
3063 	ret = -EINVAL;
3064 
3065 	/* OK security check passed, take write lock + let it rip. */
3066 	if (mmap_write_lock_killable(mm)) {
3067 		fput(file);
3068 		return -EINTR;
3069 	}
3070 
3071 	vma = vma_lookup(mm, start);
3072 
3073 	if (!vma)
3074 		goto out;
3075 
3076 	/* Make sure things didn't change under us. */
3077 	if (vma->vm_flags != vm_flags)
3078 		goto out;
3079 	if (vma->vm_file != file)
3080 		goto out;
3081 
3082 	if (start + size > vma->vm_end) {
3083 		VMA_ITERATOR(vmi, mm, vma->vm_end);
3084 		struct vm_area_struct *next, *prev = vma;
3085 
3086 		for_each_vma_range(vmi, next, start + size) {
3087 			/* hole between vmas ? */
3088 			if (next->vm_start != prev->vm_end)
3089 				goto out;
3090 
3091 			if (next->vm_file != vma->vm_file)
3092 				goto out;
3093 
3094 			if (next->vm_flags != vma->vm_flags)
3095 				goto out;
3096 
3097 			if (start + size <= next->vm_end)
3098 				break;
3099 
3100 			prev = next;
3101 		}
3102 
3103 		if (!next)
3104 			goto out;
3105 	}
3106 
3107 	ret = do_mmap(vma->vm_file, start, size,
3108 			prot, flags, 0, pgoff, &populate, NULL);
3109 out:
3110 	mmap_write_unlock(mm);
3111 	fput(file);
3112 	if (populate)
3113 		mm_populate(ret, populate);
3114 	if (!IS_ERR_VALUE(ret))
3115 		ret = 0;
3116 	return ret;
3117 }
3118 
3119 /*
3120  * do_vma_munmap() - Unmap a full or partial vma.
3121  * @vmi: The vma iterator pointing at the vma
3122  * @vma: The first vma to be munmapped
3123  * @start: the start of the address to unmap
3124  * @end: The end of the address to unmap
3125  * @uf: The userfaultfd list_head
3126  * @unlock: Drop the lock on success
3127  *
3128  * unmaps a VMA mapping when the vma iterator is already in position.
3129  * Does not handle alignment.
3130  *
3131  * Return: 0 on success drops the lock of so directed, error on failure and will
3132  * still hold the lock.
3133  */
do_vma_munmap(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long start,unsigned long end,struct list_head * uf,bool unlock)3134 int do_vma_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
3135 		unsigned long start, unsigned long end, struct list_head *uf,
3136 		bool unlock)
3137 {
3138 	struct mm_struct *mm = vma->vm_mm;
3139 
3140 	arch_unmap(mm, start, end);
3141 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
3142 }
3143 
3144 /*
3145  * do_brk_flags() - Increase the brk vma if the flags match.
3146  * @vmi: The vma iterator
3147  * @addr: The start address
3148  * @len: The length of the increase
3149  * @vma: The vma,
3150  * @flags: The VMA Flags
3151  *
3152  * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
3153  * do not match then create a new anonymous VMA.  Eventually we may be able to
3154  * do some brk-specific accounting here.
3155  */
do_brk_flags(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long addr,unsigned long len,unsigned long flags)3156 static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
3157 		unsigned long addr, unsigned long len, unsigned long flags)
3158 {
3159 	struct mm_struct *mm = current->mm;
3160 	struct vma_prepare vp;
3161 
3162 	/*
3163 	 * Check against address space limits by the changed size
3164 	 * Note: This happens *after* clearing old mappings in some code paths.
3165 	 */
3166 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
3167 	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
3168 		return -ENOMEM;
3169 
3170 	if (mm->map_count > sysctl_max_map_count)
3171 		return -ENOMEM;
3172 
3173 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3174 		return -ENOMEM;
3175 
3176 	/*
3177 	 * Expand the existing vma if possible; Note that singular lists do not
3178 	 * occur after forking, so the expand will only happen on new VMAs.
3179 	 */
3180 	if (vma && vma->vm_end == addr && !vma_policy(vma) &&
3181 	    can_vma_merge_after(vma, flags, NULL, NULL,
3182 				addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
3183 		vma_iter_config(vmi, vma->vm_start, addr + len);
3184 		if (vma_iter_prealloc(vmi, vma))
3185 			goto unacct_fail;
3186 
3187 		vma_start_write(vma);
3188 
3189 		init_vma_prep(&vp, vma);
3190 		vma_prepare(&vp);
3191 		vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
3192 		vma->vm_end = addr + len;
3193 		vm_flags_set(vma, VM_SOFTDIRTY);
3194 		vma_iter_store(vmi, vma);
3195 
3196 		vma_complete(&vp, vmi, mm);
3197 		khugepaged_enter_vma(vma, flags);
3198 		goto out;
3199 	}
3200 
3201 	if (vma)
3202 		vma_iter_next_range(vmi);
3203 	/* create a vma struct for an anonymous mapping */
3204 	vma = vm_area_alloc(mm);
3205 	if (!vma)
3206 		goto unacct_fail;
3207 
3208 	vma_set_anonymous(vma);
3209 	vma->vm_start = addr;
3210 	vma->vm_end = addr + len;
3211 	vma->vm_pgoff = addr >> PAGE_SHIFT;
3212 	vm_flags_init(vma, flags);
3213 	vma->vm_page_prot = vm_get_page_prot(flags);
3214 	vma_start_write(vma);
3215 	if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
3216 		goto mas_store_fail;
3217 
3218 	mm->map_count++;
3219 	validate_mm(mm);
3220 	ksm_add_vma(vma);
3221 out:
3222 	perf_event_mmap(vma);
3223 	mm->total_vm += len >> PAGE_SHIFT;
3224 	mm->data_vm += len >> PAGE_SHIFT;
3225 	if (flags & VM_LOCKED)
3226 		mm->locked_vm += (len >> PAGE_SHIFT);
3227 	vm_flags_set(vma, VM_SOFTDIRTY);
3228 	return 0;
3229 
3230 mas_store_fail:
3231 	vm_area_free(vma);
3232 unacct_fail:
3233 	vm_unacct_memory(len >> PAGE_SHIFT);
3234 	return -ENOMEM;
3235 }
3236 
vm_brk_flags(unsigned long addr,unsigned long request,unsigned long flags)3237 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3238 {
3239 	struct mm_struct *mm = current->mm;
3240 	struct vm_area_struct *vma = NULL;
3241 	unsigned long len;
3242 	int ret;
3243 	bool populate;
3244 	LIST_HEAD(uf);
3245 	VMA_ITERATOR(vmi, mm, addr);
3246 
3247 	len = PAGE_ALIGN(request);
3248 	if (len < request)
3249 		return -ENOMEM;
3250 	if (!len)
3251 		return 0;
3252 
3253 	/* Until we need other flags, refuse anything except VM_EXEC. */
3254 	if ((flags & (~VM_EXEC)) != 0)
3255 		return -EINVAL;
3256 
3257 	if (mmap_write_lock_killable(mm))
3258 		return -EINTR;
3259 
3260 	ret = check_brk_limits(addr, len);
3261 	if (ret)
3262 		goto limits_failed;
3263 
3264 	ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
3265 	if (ret)
3266 		goto munmap_failed;
3267 
3268 	vma = vma_prev(&vmi);
3269 	ret = do_brk_flags(&vmi, vma, addr, len, flags);
3270 	populate = ((mm->def_flags & VM_LOCKED) != 0);
3271 	mmap_write_unlock(mm);
3272 	userfaultfd_unmap_complete(mm, &uf);
3273 	if (populate && !ret)
3274 		mm_populate(addr, len);
3275 	return ret;
3276 
3277 munmap_failed:
3278 limits_failed:
3279 	mmap_write_unlock(mm);
3280 	return ret;
3281 }
3282 EXPORT_SYMBOL(vm_brk_flags);
3283 
vm_brk(unsigned long addr,unsigned long len)3284 int vm_brk(unsigned long addr, unsigned long len)
3285 {
3286 	return vm_brk_flags(addr, len, 0);
3287 }
3288 EXPORT_SYMBOL(vm_brk);
3289 
3290 /* Release all mmaps. */
exit_mmap(struct mm_struct * mm)3291 void exit_mmap(struct mm_struct *mm)
3292 {
3293 	struct mmu_gather tlb;
3294 	struct vm_area_struct *vma;
3295 	unsigned long nr_accounted = 0;
3296 	MA_STATE(mas, &mm->mm_mt, 0, 0);
3297 	int count = 0;
3298 
3299 	/* mm's last user has gone, and its about to be pulled down */
3300 	mmu_notifier_release(mm);
3301 
3302 	mmap_read_lock(mm);
3303 	arch_exit_mmap(mm);
3304 
3305 	vma = mas_find(&mas, ULONG_MAX);
3306 	if (!vma) {
3307 		/* Can happen if dup_mmap() received an OOM */
3308 		mmap_read_unlock(mm);
3309 		return;
3310 	}
3311 
3312 	lru_add_drain();
3313 	flush_cache_mm(mm);
3314 	tlb_gather_mmu_fullmm(&tlb, mm);
3315 	/* update_hiwater_rss(mm) here? but nobody should be looking */
3316 	/* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
3317 	unmap_vmas(&tlb, &mas, vma, 0, ULONG_MAX, ULONG_MAX, false);
3318 	mmap_read_unlock(mm);
3319 
3320 	/*
3321 	 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
3322 	 * because the memory has been already freed.
3323 	 */
3324 	set_bit(MMF_OOM_SKIP, &mm->flags);
3325 	mmap_write_lock(mm);
3326 	mt_clear_in_rcu(&mm->mm_mt);
3327 	mas_set(&mas, vma->vm_end);
3328 	free_pgtables(&tlb, &mas, vma, FIRST_USER_ADDRESS,
3329 		      USER_PGTABLES_CEILING, true);
3330 	tlb_finish_mmu(&tlb);
3331 
3332 	/*
3333 	 * Walk the list again, actually closing and freeing it, with preemption
3334 	 * enabled, without holding any MM locks besides the unreachable
3335 	 * mmap_write_lock.
3336 	 */
3337 	mas_set(&mas, vma->vm_end);
3338 	do {
3339 		if (vma->vm_flags & VM_ACCOUNT)
3340 			nr_accounted += vma_pages(vma);
3341 		remove_vma(vma, true);
3342 		count++;
3343 		cond_resched();
3344 	} while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);
3345 
3346 	BUG_ON(count != mm->map_count);
3347 
3348 	trace_exit_mmap(mm);
3349 	__mt_destroy(&mm->mm_mt);
3350 	mmap_write_unlock(mm);
3351 	vm_unacct_memory(nr_accounted);
3352 }
3353 
3354 /* Insert vm structure into process list sorted by address
3355  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3356  * then i_mmap_rwsem is taken here.
3357  */
insert_vm_struct(struct mm_struct * mm,struct vm_area_struct * vma)3358 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3359 {
3360 	unsigned long charged = vma_pages(vma);
3361 
3362 
3363 	if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3364 		return -ENOMEM;
3365 
3366 	if ((vma->vm_flags & VM_ACCOUNT) &&
3367 	     security_vm_enough_memory_mm(mm, charged))
3368 		return -ENOMEM;
3369 
3370 	/*
3371 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
3372 	 * until its first write fault, when page's anon_vma and index
3373 	 * are set.  But now set the vm_pgoff it will almost certainly
3374 	 * end up with (unless mremap moves it elsewhere before that
3375 	 * first wfault), so /proc/pid/maps tells a consistent story.
3376 	 *
3377 	 * By setting it to reflect the virtual start address of the
3378 	 * vma, merges and splits can happen in a seamless way, just
3379 	 * using the existing file pgoff checks and manipulations.
3380 	 * Similarly in do_mmap and in do_brk_flags.
3381 	 */
3382 	if (vma_is_anonymous(vma)) {
3383 		BUG_ON(vma->anon_vma);
3384 		vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3385 	}
3386 
3387 	if (vma_link(mm, vma)) {
3388 		vm_unacct_memory(charged);
3389 		return -ENOMEM;
3390 	}
3391 
3392 	return 0;
3393 }
3394 
3395 /*
3396  * Copy the vma structure to a new location in the same mm,
3397  * prior to moving page table entries, to effect an mremap move.
3398  */
copy_vma(struct vm_area_struct ** vmap,unsigned long addr,unsigned long len,pgoff_t pgoff,bool * need_rmap_locks)3399 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3400 	unsigned long addr, unsigned long len, pgoff_t pgoff,
3401 	bool *need_rmap_locks)
3402 {
3403 	struct vm_area_struct *vma = *vmap;
3404 	unsigned long vma_start = vma->vm_start;
3405 	struct mm_struct *mm = vma->vm_mm;
3406 	struct vm_area_struct *new_vma, *prev;
3407 	bool faulted_in_anon_vma = true;
3408 	VMA_ITERATOR(vmi, mm, addr);
3409 
3410 	/*
3411 	 * If anonymous vma has not yet been faulted, update new pgoff
3412 	 * to match new location, to increase its chance of merging.
3413 	 */
3414 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3415 		pgoff = addr >> PAGE_SHIFT;
3416 		faulted_in_anon_vma = false;
3417 	}
3418 
3419 	new_vma = find_vma_prev(mm, addr, &prev);
3420 	if (new_vma && new_vma->vm_start < addr + len)
3421 		return NULL;	/* should never get here */
3422 
3423 	new_vma = vma_merge(&vmi, mm, prev, addr, addr + len, vma->vm_flags,
3424 			    vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3425 			    vma->vm_userfaultfd_ctx, anon_vma_name(vma));
3426 	if (new_vma) {
3427 		/*
3428 		 * Source vma may have been merged into new_vma
3429 		 */
3430 		if (unlikely(vma_start >= new_vma->vm_start &&
3431 			     vma_start < new_vma->vm_end)) {
3432 			/*
3433 			 * The only way we can get a vma_merge with
3434 			 * self during an mremap is if the vma hasn't
3435 			 * been faulted in yet and we were allowed to
3436 			 * reset the dst vma->vm_pgoff to the
3437 			 * destination address of the mremap to allow
3438 			 * the merge to happen. mremap must change the
3439 			 * vm_pgoff linearity between src and dst vmas
3440 			 * (in turn preventing a vma_merge) to be
3441 			 * safe. It is only safe to keep the vm_pgoff
3442 			 * linear if there are no pages mapped yet.
3443 			 */
3444 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3445 			*vmap = vma = new_vma;
3446 		}
3447 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3448 	} else {
3449 		new_vma = vm_area_dup(vma);
3450 		if (!new_vma)
3451 			goto out;
3452 		new_vma->vm_start = addr;
3453 		new_vma->vm_end = addr + len;
3454 		new_vma->vm_pgoff = pgoff;
3455 		if (vma_dup_policy(vma, new_vma))
3456 			goto out_free_vma;
3457 		if (anon_vma_clone(new_vma, vma))
3458 			goto out_free_mempol;
3459 		if (new_vma->vm_file)
3460 			get_file(new_vma->vm_file);
3461 		if (new_vma->vm_ops && new_vma->vm_ops->open)
3462 			new_vma->vm_ops->open(new_vma);
3463 		if (vma_link(mm, new_vma))
3464 			goto out_vma_link;
3465 		*need_rmap_locks = false;
3466 	}
3467 	return new_vma;
3468 
3469 out_vma_link:
3470 	vma_close(new_vma);
3471 
3472 	if (new_vma->vm_file)
3473 		fput(new_vma->vm_file);
3474 
3475 	unlink_anon_vmas(new_vma);
3476 out_free_mempol:
3477 	mpol_put(vma_policy(new_vma));
3478 out_free_vma:
3479 	vm_area_free(new_vma);
3480 out:
3481 	return NULL;
3482 }
3483 
3484 /*
3485  * Return true if the calling process may expand its vm space by the passed
3486  * number of pages
3487  */
may_expand_vm(struct mm_struct * mm,vm_flags_t flags,unsigned long npages)3488 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3489 {
3490 	if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3491 		return false;
3492 
3493 	if (is_data_mapping(flags) &&
3494 	    mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3495 		/* Workaround for Valgrind */
3496 		if (rlimit(RLIMIT_DATA) == 0 &&
3497 		    mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3498 			return true;
3499 
3500 		pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3501 			     current->comm, current->pid,
3502 			     (mm->data_vm + npages) << PAGE_SHIFT,
3503 			     rlimit(RLIMIT_DATA),
3504 			     ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3505 
3506 		if (!ignore_rlimit_data)
3507 			return false;
3508 	}
3509 
3510 	return true;
3511 }
3512 
vm_stat_account(struct mm_struct * mm,vm_flags_t flags,long npages)3513 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3514 {
3515 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3516 
3517 	if (is_exec_mapping(flags))
3518 		mm->exec_vm += npages;
3519 	else if (is_stack_mapping(flags))
3520 		mm->stack_vm += npages;
3521 	else if (is_data_mapping(flags))
3522 		mm->data_vm += npages;
3523 }
3524 
3525 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3526 
3527 /*
3528  * Having a close hook prevents vma merging regardless of flags.
3529  */
special_mapping_close(struct vm_area_struct * vma)3530 static void special_mapping_close(struct vm_area_struct *vma)
3531 {
3532 }
3533 
special_mapping_name(struct vm_area_struct * vma)3534 static const char *special_mapping_name(struct vm_area_struct *vma)
3535 {
3536 	return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3537 }
3538 
special_mapping_mremap(struct vm_area_struct * new_vma)3539 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3540 {
3541 	struct vm_special_mapping *sm = new_vma->vm_private_data;
3542 
3543 	if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3544 		return -EFAULT;
3545 
3546 	if (sm->mremap)
3547 		return sm->mremap(sm, new_vma);
3548 
3549 	return 0;
3550 }
3551 
special_mapping_split(struct vm_area_struct * vma,unsigned long addr)3552 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3553 {
3554 	/*
3555 	 * Forbid splitting special mappings - kernel has expectations over
3556 	 * the number of pages in mapping. Together with VM_DONTEXPAND
3557 	 * the size of vma should stay the same over the special mapping's
3558 	 * lifetime.
3559 	 */
3560 	return -EINVAL;
3561 }
3562 
3563 static const struct vm_operations_struct special_mapping_vmops = {
3564 	.close = special_mapping_close,
3565 	.fault = special_mapping_fault,
3566 	.mremap = special_mapping_mremap,
3567 	.name = special_mapping_name,
3568 	/* vDSO code relies that VVAR can't be accessed remotely */
3569 	.access = NULL,
3570 	.may_split = special_mapping_split,
3571 };
3572 
3573 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3574 	.close = special_mapping_close,
3575 	.fault = special_mapping_fault,
3576 };
3577 
special_mapping_fault(struct vm_fault * vmf)3578 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3579 {
3580 	struct vm_area_struct *vma = vmf->vma;
3581 	pgoff_t pgoff;
3582 	struct page **pages;
3583 
3584 	if (vma->vm_ops == &legacy_special_mapping_vmops) {
3585 		pages = vma->vm_private_data;
3586 	} else {
3587 		struct vm_special_mapping *sm = vma->vm_private_data;
3588 
3589 		if (sm->fault)
3590 			return sm->fault(sm, vmf->vma, vmf);
3591 
3592 		pages = sm->pages;
3593 	}
3594 
3595 	for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3596 		pgoff--;
3597 
3598 	if (*pages) {
3599 		struct page *page = *pages;
3600 		get_page(page);
3601 		vmf->page = page;
3602 		return 0;
3603 	}
3604 
3605 	return VM_FAULT_SIGBUS;
3606 }
3607 
__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)3608 static struct vm_area_struct *__install_special_mapping(
3609 	struct mm_struct *mm,
3610 	unsigned long addr, unsigned long len,
3611 	unsigned long vm_flags, void *priv,
3612 	const struct vm_operations_struct *ops)
3613 {
3614 	int ret;
3615 	struct vm_area_struct *vma;
3616 
3617 	vma = vm_area_alloc(mm);
3618 	if (unlikely(vma == NULL))
3619 		return ERR_PTR(-ENOMEM);
3620 
3621 	vma->vm_start = addr;
3622 	vma->vm_end = addr + len;
3623 
3624 	vm_flags_init(vma, (vm_flags | mm->def_flags |
3625 		      VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
3626 	vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3627 
3628 	vma->vm_ops = ops;
3629 	vma->vm_private_data = priv;
3630 
3631 	ret = insert_vm_struct(mm, vma);
3632 	if (ret)
3633 		goto out;
3634 
3635 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3636 
3637 	perf_event_mmap(vma);
3638 
3639 	return vma;
3640 
3641 out:
3642 	vm_area_free(vma);
3643 	return ERR_PTR(ret);
3644 }
3645 
vma_is_special_mapping(const struct vm_area_struct * vma,const struct vm_special_mapping * sm)3646 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3647 	const struct vm_special_mapping *sm)
3648 {
3649 	return vma->vm_private_data == sm &&
3650 		(vma->vm_ops == &special_mapping_vmops ||
3651 		 vma->vm_ops == &legacy_special_mapping_vmops);
3652 }
3653 
3654 /*
3655  * Called with mm->mmap_lock held for writing.
3656  * Insert a new vma covering the given region, with the given flags.
3657  * Its pages are supplied by the given array of struct page *.
3658  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3659  * The region past the last page supplied will always produce SIGBUS.
3660  * The array pointer and the pages it points to are assumed to stay alive
3661  * for as long as this mapping might exist.
3662  */
_install_special_mapping(struct mm_struct * mm,unsigned long addr,unsigned long len,unsigned long vm_flags,const struct vm_special_mapping * spec)3663 struct vm_area_struct *_install_special_mapping(
3664 	struct mm_struct *mm,
3665 	unsigned long addr, unsigned long len,
3666 	unsigned long vm_flags, const struct vm_special_mapping *spec)
3667 {
3668 	return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3669 					&special_mapping_vmops);
3670 }
3671 
install_special_mapping(struct mm_struct * mm,unsigned long addr,unsigned long len,unsigned long vm_flags,struct page ** pages)3672 int install_special_mapping(struct mm_struct *mm,
3673 			    unsigned long addr, unsigned long len,
3674 			    unsigned long vm_flags, struct page **pages)
3675 {
3676 	struct vm_area_struct *vma = __install_special_mapping(
3677 		mm, addr, len, vm_flags, (void *)pages,
3678 		&legacy_special_mapping_vmops);
3679 
3680 	return PTR_ERR_OR_ZERO(vma);
3681 }
3682 
3683 static DEFINE_MUTEX(mm_all_locks_mutex);
3684 
vm_lock_anon_vma(struct mm_struct * mm,struct anon_vma * anon_vma)3685 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3686 {
3687 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3688 		/*
3689 		 * The LSB of head.next can't change from under us
3690 		 * because we hold the mm_all_locks_mutex.
3691 		 */
3692 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3693 		/*
3694 		 * We can safely modify head.next after taking the
3695 		 * anon_vma->root->rwsem. If some other vma in this mm shares
3696 		 * the same anon_vma we won't take it again.
3697 		 *
3698 		 * No need of atomic instructions here, head.next
3699 		 * can't change from under us thanks to the
3700 		 * anon_vma->root->rwsem.
3701 		 */
3702 		if (__test_and_set_bit(0, (unsigned long *)
3703 				       &anon_vma->root->rb_root.rb_root.rb_node))
3704 			BUG();
3705 	}
3706 }
3707 
vm_lock_mapping(struct mm_struct * mm,struct address_space * mapping)3708 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3709 {
3710 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3711 		/*
3712 		 * AS_MM_ALL_LOCKS can't change from under us because
3713 		 * we hold the mm_all_locks_mutex.
3714 		 *
3715 		 * Operations on ->flags have to be atomic because
3716 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
3717 		 * mm_all_locks_mutex, there may be other cpus
3718 		 * changing other bitflags in parallel to us.
3719 		 */
3720 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3721 			BUG();
3722 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3723 	}
3724 }
3725 
3726 /*
3727  * This operation locks against the VM for all pte/vma/mm related
3728  * operations that could ever happen on a certain mm. This includes
3729  * vmtruncate, try_to_unmap, and all page faults.
3730  *
3731  * The caller must take the mmap_lock in write mode before calling
3732  * mm_take_all_locks(). The caller isn't allowed to release the
3733  * mmap_lock until mm_drop_all_locks() returns.
3734  *
3735  * mmap_lock in write mode is required in order to block all operations
3736  * that could modify pagetables and free pages without need of
3737  * altering the vma layout. It's also needed in write mode to avoid new
3738  * anon_vmas to be associated with existing vmas.
3739  *
3740  * A single task can't take more than one mm_take_all_locks() in a row
3741  * or it would deadlock.
3742  *
3743  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3744  * mapping->flags avoid to take the same lock twice, if more than one
3745  * vma in this mm is backed by the same anon_vma or address_space.
3746  *
3747  * We take locks in following order, accordingly to comment at beginning
3748  * of mm/rmap.c:
3749  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3750  *     hugetlb mapping);
3751  *   - all vmas marked locked
3752  *   - all i_mmap_rwsem locks;
3753  *   - all anon_vma->rwseml
3754  *
3755  * We can take all locks within these types randomly because the VM code
3756  * doesn't nest them and we protected from parallel mm_take_all_locks() by
3757  * mm_all_locks_mutex.
3758  *
3759  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3760  * that may have to take thousand of locks.
3761  *
3762  * mm_take_all_locks() can fail if it's interrupted by signals.
3763  */
mm_take_all_locks(struct mm_struct * mm)3764 int mm_take_all_locks(struct mm_struct *mm)
3765 {
3766 	struct vm_area_struct *vma;
3767 	struct anon_vma_chain *avc;
3768 	MA_STATE(mas, &mm->mm_mt, 0, 0);
3769 
3770 	mmap_assert_write_locked(mm);
3771 
3772 	mutex_lock(&mm_all_locks_mutex);
3773 
3774 	/*
3775 	 * vma_start_write() does not have a complement in mm_drop_all_locks()
3776 	 * because vma_start_write() is always asymmetrical; it marks a VMA as
3777 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
3778 	 * is reached.
3779 	 */
3780 	mas_for_each(&mas, vma, ULONG_MAX) {
3781 		if (signal_pending(current))
3782 			goto out_unlock;
3783 		vma_start_write(vma);
3784 	}
3785 
3786 	mas_set(&mas, 0);
3787 	mas_for_each(&mas, vma, ULONG_MAX) {
3788 		if (signal_pending(current))
3789 			goto out_unlock;
3790 		if (vma->vm_file && vma->vm_file->f_mapping &&
3791 				is_vm_hugetlb_page(vma))
3792 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
3793 	}
3794 
3795 	mas_set(&mas, 0);
3796 	mas_for_each(&mas, vma, ULONG_MAX) {
3797 		if (signal_pending(current))
3798 			goto out_unlock;
3799 		if (vma->vm_file && vma->vm_file->f_mapping &&
3800 				!is_vm_hugetlb_page(vma))
3801 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
3802 	}
3803 
3804 	mas_set(&mas, 0);
3805 	mas_for_each(&mas, vma, ULONG_MAX) {
3806 		if (signal_pending(current))
3807 			goto out_unlock;
3808 		if (vma->anon_vma)
3809 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3810 				vm_lock_anon_vma(mm, avc->anon_vma);
3811 	}
3812 
3813 	return 0;
3814 
3815 out_unlock:
3816 	mm_drop_all_locks(mm);
3817 	return -EINTR;
3818 }
3819 
vm_unlock_anon_vma(struct anon_vma * anon_vma)3820 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3821 {
3822 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3823 		/*
3824 		 * The LSB of head.next can't change to 0 from under
3825 		 * us because we hold the mm_all_locks_mutex.
3826 		 *
3827 		 * We must however clear the bitflag before unlocking
3828 		 * the vma so the users using the anon_vma->rb_root will
3829 		 * never see our bitflag.
3830 		 *
3831 		 * No need of atomic instructions here, head.next
3832 		 * can't change from under us until we release the
3833 		 * anon_vma->root->rwsem.
3834 		 */
3835 		if (!__test_and_clear_bit(0, (unsigned long *)
3836 					  &anon_vma->root->rb_root.rb_root.rb_node))
3837 			BUG();
3838 		anon_vma_unlock_write(anon_vma);
3839 	}
3840 }
3841 
vm_unlock_mapping(struct address_space * mapping)3842 static void vm_unlock_mapping(struct address_space *mapping)
3843 {
3844 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3845 		/*
3846 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
3847 		 * because we hold the mm_all_locks_mutex.
3848 		 */
3849 		i_mmap_unlock_write(mapping);
3850 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3851 					&mapping->flags))
3852 			BUG();
3853 	}
3854 }
3855 
3856 /*
3857  * The mmap_lock cannot be released by the caller until
3858  * mm_drop_all_locks() returns.
3859  */
mm_drop_all_locks(struct mm_struct * mm)3860 void mm_drop_all_locks(struct mm_struct *mm)
3861 {
3862 	struct vm_area_struct *vma;
3863 	struct anon_vma_chain *avc;
3864 	MA_STATE(mas, &mm->mm_mt, 0, 0);
3865 
3866 	mmap_assert_write_locked(mm);
3867 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3868 
3869 	mas_for_each(&mas, vma, ULONG_MAX) {
3870 		if (vma->anon_vma)
3871 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3872 				vm_unlock_anon_vma(avc->anon_vma);
3873 		if (vma->vm_file && vma->vm_file->f_mapping)
3874 			vm_unlock_mapping(vma->vm_file->f_mapping);
3875 	}
3876 
3877 	mutex_unlock(&mm_all_locks_mutex);
3878 }
3879 
3880 /*
3881  * initialise the percpu counter for VM
3882  */
mmap_init(void)3883 void __init mmap_init(void)
3884 {
3885 	int ret;
3886 
3887 	ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3888 	VM_BUG_ON(ret);
3889 }
3890 
3891 /*
3892  * Initialise sysctl_user_reserve_kbytes.
3893  *
3894  * This is intended to prevent a user from starting a single memory hogging
3895  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3896  * mode.
3897  *
3898  * The default value is min(3% of free memory, 128MB)
3899  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3900  */
init_user_reserve(void)3901 static int init_user_reserve(void)
3902 {
3903 	unsigned long free_kbytes;
3904 
3905 	free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
3906 
3907 	sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3908 	return 0;
3909 }
3910 subsys_initcall(init_user_reserve);
3911 
3912 /*
3913  * Initialise sysctl_admin_reserve_kbytes.
3914  *
3915  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3916  * to log in and kill a memory hogging process.
3917  *
3918  * Systems with more than 256MB will reserve 8MB, enough to recover
3919  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3920  * only reserve 3% of free pages by default.
3921  */
init_admin_reserve(void)3922 static int init_admin_reserve(void)
3923 {
3924 	unsigned long free_kbytes;
3925 
3926 	free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
3927 
3928 	sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3929 	return 0;
3930 }
3931 subsys_initcall(init_admin_reserve);
3932 
3933 /*
3934  * Reinititalise user and admin reserves if memory is added or removed.
3935  *
3936  * The default user reserve max is 128MB, and the default max for the
3937  * admin reserve is 8MB. These are usually, but not always, enough to
3938  * enable recovery from a memory hogging process using login/sshd, a shell,
3939  * and tools like top. It may make sense to increase or even disable the
3940  * reserve depending on the existence of swap or variations in the recovery
3941  * tools. So, the admin may have changed them.
3942  *
3943  * If memory is added and the reserves have been eliminated or increased above
3944  * the default max, then we'll trust the admin.
3945  *
3946  * If memory is removed and there isn't enough free memory, then we
3947  * need to reset the reserves.
3948  *
3949  * Otherwise keep the reserve set by the admin.
3950  */
reserve_mem_notifier(struct notifier_block * nb,unsigned long action,void * data)3951 static int reserve_mem_notifier(struct notifier_block *nb,
3952 			     unsigned long action, void *data)
3953 {
3954 	unsigned long tmp, free_kbytes;
3955 
3956 	switch (action) {
3957 	case MEM_ONLINE:
3958 		/* Default max is 128MB. Leave alone if modified by operator. */
3959 		tmp = sysctl_user_reserve_kbytes;
3960 		if (0 < tmp && tmp < (1UL << 17))
3961 			init_user_reserve();
3962 
3963 		/* Default max is 8MB.  Leave alone if modified by operator. */
3964 		tmp = sysctl_admin_reserve_kbytes;
3965 		if (0 < tmp && tmp < (1UL << 13))
3966 			init_admin_reserve();
3967 
3968 		break;
3969 	case MEM_OFFLINE:
3970 		free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
3971 
3972 		if (sysctl_user_reserve_kbytes > free_kbytes) {
3973 			init_user_reserve();
3974 			pr_info("vm.user_reserve_kbytes reset to %lu\n",
3975 				sysctl_user_reserve_kbytes);
3976 		}
3977 
3978 		if (sysctl_admin_reserve_kbytes > free_kbytes) {
3979 			init_admin_reserve();
3980 			pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3981 				sysctl_admin_reserve_kbytes);
3982 		}
3983 		break;
3984 	default:
3985 		break;
3986 	}
3987 	return NOTIFY_OK;
3988 }
3989 
init_reserve_notifier(void)3990 static int __meminit init_reserve_notifier(void)
3991 {
3992 	if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
3993 		pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3994 
3995 	return 0;
3996 }
3997 subsys_initcall(init_reserve_notifier);
3998