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