xref: /linux/mm/vma.c (revision b05f8d7e077952d14acb63e3ccdf5f64404b59a4)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 /*
4  * VMA-specific functions.
5  */
6 
7 #include "vma_internal.h"
8 #include "vma.h"
9 
10 struct mmap_state {
11 	struct mm_struct *mm;
12 	struct vma_iterator *vmi;
13 
14 	unsigned long addr;
15 	unsigned long end;
16 	pgoff_t pgoff;
17 	unsigned long pglen;
18 	unsigned long flags;
19 	struct file *file;
20 
21 	unsigned long charged;
22 	bool retry_merge;
23 
24 	struct vm_area_struct *prev;
25 	struct vm_area_struct *next;
26 
27 	/* Unmapping state. */
28 	struct vma_munmap_struct vms;
29 	struct ma_state mas_detach;
30 	struct maple_tree mt_detach;
31 };
32 
33 #define MMAP_STATE(name, mm_, vmi_, addr_, len_, pgoff_, flags_, file_) \
34 	struct mmap_state name = {					\
35 		.mm = mm_,						\
36 		.vmi = vmi_,						\
37 		.addr = addr_,						\
38 		.end = (addr_) + (len_),				\
39 		.pgoff = pgoff_,					\
40 		.pglen = PHYS_PFN(len_),				\
41 		.flags = flags_,					\
42 		.file = file_,						\
43 	}
44 
45 #define VMG_MMAP_STATE(name, map_, vma_)				\
46 	struct vma_merge_struct name = {				\
47 		.mm = (map_)->mm,					\
48 		.vmi = (map_)->vmi,					\
49 		.start = (map_)->addr,					\
50 		.end = (map_)->end,					\
51 		.flags = (map_)->flags,					\
52 		.pgoff = (map_)->pgoff,					\
53 		.file = (map_)->file,					\
54 		.prev = (map_)->prev,					\
55 		.middle = vma_,						\
56 		.next = (vma_) ? NULL : (map_)->next,			\
57 		.state = VMA_MERGE_START,				\
58 	}
59 
60 /*
61  * If, at any point, the VMA had unCoW'd mappings from parents, it will maintain
62  * more than one anon_vma_chain connecting it to more than one anon_vma. A merge
63  * would mean a wider range of folios sharing the root anon_vma lock, and thus
64  * potential lock contention, we do not wish to encourage merging such that this
65  * scales to a problem.
66  */
67 static bool vma_had_uncowed_parents(struct vm_area_struct *vma)
68 {
69 	/*
70 	 * The list_is_singular() test is to avoid merging VMA cloned from
71 	 * parents. This can improve scalability caused by anon_vma lock.
72 	 */
73 	return vma && vma->anon_vma && !list_is_singular(&vma->anon_vma_chain);
74 }
75 
76 static inline bool is_mergeable_vma(struct vma_merge_struct *vmg, bool merge_next)
77 {
78 	struct vm_area_struct *vma = merge_next ? vmg->next : vmg->prev;
79 
80 	if (!mpol_equal(vmg->policy, vma_policy(vma)))
81 		return false;
82 	/*
83 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
84 	 * match the flags but dirty bit -- the caller should mark
85 	 * merged VMA as dirty. If dirty bit won't be excluded from
86 	 * comparison, we increase pressure on the memory system forcing
87 	 * the kernel to generate new VMAs when old one could be
88 	 * extended instead.
89 	 */
90 	if ((vma->vm_flags ^ vmg->flags) & ~VM_SOFTDIRTY)
91 		return false;
92 	if (vma->vm_file != vmg->file)
93 		return false;
94 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vmg->uffd_ctx))
95 		return false;
96 	if (!anon_vma_name_eq(anon_vma_name(vma), vmg->anon_name))
97 		return false;
98 	return true;
99 }
100 
101 static bool is_mergeable_anon_vma(struct vma_merge_struct *vmg, bool merge_next)
102 {
103 	struct vm_area_struct *tgt = merge_next ? vmg->next : vmg->prev;
104 	struct vm_area_struct *src = vmg->middle; /* exisitng merge case. */
105 	struct anon_vma *tgt_anon = tgt->anon_vma;
106 	struct anon_vma *src_anon = vmg->anon_vma;
107 
108 	/*
109 	 * We _can_ have !src, vmg->anon_vma via copy_vma(). In this instance we
110 	 * will remove the existing VMA's anon_vma's so there's no scalability
111 	 * concerns.
112 	 */
113 	VM_WARN_ON(src && src_anon != src->anon_vma);
114 
115 	/* Case 1 - we will dup_anon_vma() from src into tgt. */
116 	if (!tgt_anon && src_anon)
117 		return !vma_had_uncowed_parents(src);
118 	/* Case 2 - we will simply use tgt's anon_vma. */
119 	if (tgt_anon && !src_anon)
120 		return !vma_had_uncowed_parents(tgt);
121 	/* Case 3 - the anon_vma's are already shared. */
122 	return src_anon == tgt_anon;
123 }
124 
125 /*
126  * init_multi_vma_prep() - Initializer for struct vma_prepare
127  * @vp: The vma_prepare struct
128  * @vma: The vma that will be altered once locked
129  * @vmg: The merge state that will be used to determine adjustment and VMA
130  *       removal.
131  */
132 static void init_multi_vma_prep(struct vma_prepare *vp,
133 				struct vm_area_struct *vma,
134 				struct vma_merge_struct *vmg)
135 {
136 	struct vm_area_struct *adjust;
137 	struct vm_area_struct **remove = &vp->remove;
138 
139 	memset(vp, 0, sizeof(struct vma_prepare));
140 	vp->vma = vma;
141 	vp->anon_vma = vma->anon_vma;
142 
143 	if (vmg && vmg->__remove_middle) {
144 		*remove = vmg->middle;
145 		remove = &vp->remove2;
146 	}
147 	if (vmg && vmg->__remove_next)
148 		*remove = vmg->next;
149 
150 	if (vmg && vmg->__adjust_middle_start)
151 		adjust = vmg->middle;
152 	else if (vmg && vmg->__adjust_next_start)
153 		adjust = vmg->next;
154 	else
155 		adjust = NULL;
156 
157 	vp->adj_next = adjust;
158 	if (!vp->anon_vma && adjust)
159 		vp->anon_vma = adjust->anon_vma;
160 
161 	VM_WARN_ON(vp->anon_vma && adjust && adjust->anon_vma &&
162 		   vp->anon_vma != adjust->anon_vma);
163 
164 	vp->file = vma->vm_file;
165 	if (vp->file)
166 		vp->mapping = vma->vm_file->f_mapping;
167 }
168 
169 /*
170  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
171  * in front of (at a lower virtual address and file offset than) the vma.
172  *
173  * We cannot merge two vmas if they have differently assigned (non-NULL)
174  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
175  *
176  * We don't check here for the merged mmap wrapping around the end of pagecache
177  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
178  * wrap, nor mmaps which cover the final page at index -1UL.
179  *
180  * We assume the vma may be removed as part of the merge.
181  */
182 static bool can_vma_merge_before(struct vma_merge_struct *vmg)
183 {
184 	pgoff_t pglen = PHYS_PFN(vmg->end - vmg->start);
185 
186 	if (is_mergeable_vma(vmg, /* merge_next = */ true) &&
187 	    is_mergeable_anon_vma(vmg, /* merge_next = */ true)) {
188 		if (vmg->next->vm_pgoff == vmg->pgoff + pglen)
189 			return true;
190 	}
191 
192 	return false;
193 }
194 
195 /*
196  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
197  * beyond (at a higher virtual address and file offset than) the vma.
198  *
199  * We cannot merge two vmas if they have differently assigned (non-NULL)
200  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
201  *
202  * We assume that vma is not removed as part of the merge.
203  */
204 static bool can_vma_merge_after(struct vma_merge_struct *vmg)
205 {
206 	if (is_mergeable_vma(vmg, /* merge_next = */ false) &&
207 	    is_mergeable_anon_vma(vmg, /* merge_next = */ false)) {
208 		if (vmg->prev->vm_pgoff + vma_pages(vmg->prev) == vmg->pgoff)
209 			return true;
210 	}
211 	return false;
212 }
213 
214 static void __vma_link_file(struct vm_area_struct *vma,
215 			    struct address_space *mapping)
216 {
217 	if (vma_is_shared_maywrite(vma))
218 		mapping_allow_writable(mapping);
219 
220 	flush_dcache_mmap_lock(mapping);
221 	vma_interval_tree_insert(vma, &mapping->i_mmap);
222 	flush_dcache_mmap_unlock(mapping);
223 }
224 
225 /*
226  * Requires inode->i_mapping->i_mmap_rwsem
227  */
228 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
229 				      struct address_space *mapping)
230 {
231 	if (vma_is_shared_maywrite(vma))
232 		mapping_unmap_writable(mapping);
233 
234 	flush_dcache_mmap_lock(mapping);
235 	vma_interval_tree_remove(vma, &mapping->i_mmap);
236 	flush_dcache_mmap_unlock(mapping);
237 }
238 
239 /*
240  * vma has some anon_vma assigned, and is already inserted on that
241  * anon_vma's interval trees.
242  *
243  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
244  * vma must be removed from the anon_vma's interval trees using
245  * anon_vma_interval_tree_pre_update_vma().
246  *
247  * After the update, the vma will be reinserted using
248  * anon_vma_interval_tree_post_update_vma().
249  *
250  * The entire update must be protected by exclusive mmap_lock and by
251  * the root anon_vma's mutex.
252  */
253 static void
254 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
255 {
256 	struct anon_vma_chain *avc;
257 
258 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
259 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
260 }
261 
262 static void
263 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
264 {
265 	struct anon_vma_chain *avc;
266 
267 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
268 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
269 }
270 
271 /*
272  * vma_prepare() - Helper function for handling locking VMAs prior to altering
273  * @vp: The initialized vma_prepare struct
274  */
275 static void vma_prepare(struct vma_prepare *vp)
276 {
277 	if (vp->file) {
278 		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
279 
280 		if (vp->adj_next)
281 			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
282 				      vp->adj_next->vm_end);
283 
284 		i_mmap_lock_write(vp->mapping);
285 		if (vp->insert && vp->insert->vm_file) {
286 			/*
287 			 * Put into interval tree now, so instantiated pages
288 			 * are visible to arm/parisc __flush_dcache_page
289 			 * throughout; but we cannot insert into address
290 			 * space until vma start or end is updated.
291 			 */
292 			__vma_link_file(vp->insert,
293 					vp->insert->vm_file->f_mapping);
294 		}
295 	}
296 
297 	if (vp->anon_vma) {
298 		anon_vma_lock_write(vp->anon_vma);
299 		anon_vma_interval_tree_pre_update_vma(vp->vma);
300 		if (vp->adj_next)
301 			anon_vma_interval_tree_pre_update_vma(vp->adj_next);
302 	}
303 
304 	if (vp->file) {
305 		flush_dcache_mmap_lock(vp->mapping);
306 		vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
307 		if (vp->adj_next)
308 			vma_interval_tree_remove(vp->adj_next,
309 						 &vp->mapping->i_mmap);
310 	}
311 
312 }
313 
314 /*
315  * vma_complete- Helper function for handling the unlocking after altering VMAs,
316  * or for inserting a VMA.
317  *
318  * @vp: The vma_prepare struct
319  * @vmi: The vma iterator
320  * @mm: The mm_struct
321  */
322 static void vma_complete(struct vma_prepare *vp, struct vma_iterator *vmi,
323 			 struct mm_struct *mm)
324 {
325 	if (vp->file) {
326 		if (vp->adj_next)
327 			vma_interval_tree_insert(vp->adj_next,
328 						 &vp->mapping->i_mmap);
329 		vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
330 		flush_dcache_mmap_unlock(vp->mapping);
331 	}
332 
333 	if (vp->remove && vp->file) {
334 		__remove_shared_vm_struct(vp->remove, vp->mapping);
335 		if (vp->remove2)
336 			__remove_shared_vm_struct(vp->remove2, vp->mapping);
337 	} else if (vp->insert) {
338 		/*
339 		 * split_vma has split insert from vma, and needs
340 		 * us to insert it before dropping the locks
341 		 * (it may either follow vma or precede it).
342 		 */
343 		vma_iter_store_new(vmi, vp->insert);
344 		mm->map_count++;
345 	}
346 
347 	if (vp->anon_vma) {
348 		anon_vma_interval_tree_post_update_vma(vp->vma);
349 		if (vp->adj_next)
350 			anon_vma_interval_tree_post_update_vma(vp->adj_next);
351 		anon_vma_unlock_write(vp->anon_vma);
352 	}
353 
354 	if (vp->file) {
355 		i_mmap_unlock_write(vp->mapping);
356 		uprobe_mmap(vp->vma);
357 
358 		if (vp->adj_next)
359 			uprobe_mmap(vp->adj_next);
360 	}
361 
362 	if (vp->remove) {
363 again:
364 		vma_mark_detached(vp->remove);
365 		if (vp->file) {
366 			uprobe_munmap(vp->remove, vp->remove->vm_start,
367 				      vp->remove->vm_end);
368 			fput(vp->file);
369 		}
370 		if (vp->remove->anon_vma)
371 			anon_vma_merge(vp->vma, vp->remove);
372 		mm->map_count--;
373 		mpol_put(vma_policy(vp->remove));
374 		if (!vp->remove2)
375 			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
376 		vm_area_free(vp->remove);
377 
378 		/*
379 		 * In mprotect's case 6 (see comments on vma_merge),
380 		 * we are removing both mid and next vmas
381 		 */
382 		if (vp->remove2) {
383 			vp->remove = vp->remove2;
384 			vp->remove2 = NULL;
385 			goto again;
386 		}
387 	}
388 	if (vp->insert && vp->file)
389 		uprobe_mmap(vp->insert);
390 }
391 
392 /*
393  * init_vma_prep() - Initializer wrapper for vma_prepare struct
394  * @vp: The vma_prepare struct
395  * @vma: The vma that will be altered once locked
396  */
397 static void init_vma_prep(struct vma_prepare *vp, struct vm_area_struct *vma)
398 {
399 	init_multi_vma_prep(vp, vma, NULL);
400 }
401 
402 /*
403  * Can the proposed VMA be merged with the left (previous) VMA taking into
404  * account the start position of the proposed range.
405  */
406 static bool can_vma_merge_left(struct vma_merge_struct *vmg)
407 
408 {
409 	return vmg->prev && vmg->prev->vm_end == vmg->start &&
410 		can_vma_merge_after(vmg);
411 }
412 
413 /*
414  * Can the proposed VMA be merged with the right (next) VMA taking into
415  * account the end position of the proposed range.
416  *
417  * In addition, if we can merge with the left VMA, ensure that left and right
418  * anon_vma's are also compatible.
419  */
420 static bool can_vma_merge_right(struct vma_merge_struct *vmg,
421 				bool can_merge_left)
422 {
423 	struct vm_area_struct *next = vmg->next;
424 	struct vm_area_struct *prev;
425 
426 	if (!next || vmg->end != next->vm_start || !can_vma_merge_before(vmg))
427 		return false;
428 
429 	if (!can_merge_left)
430 		return true;
431 
432 	/*
433 	 * If we can merge with prev (left) and next (right), indicating that
434 	 * each VMA's anon_vma is compatible with the proposed anon_vma, this
435 	 * does not mean prev and next are compatible with EACH OTHER.
436 	 *
437 	 * We therefore check this in addition to mergeability to either side.
438 	 */
439 	prev = vmg->prev;
440 	return !prev->anon_vma || !next->anon_vma ||
441 		prev->anon_vma == next->anon_vma;
442 }
443 
444 /*
445  * Close a vm structure and free it.
446  */
447 void remove_vma(struct vm_area_struct *vma)
448 {
449 	might_sleep();
450 	vma_close(vma);
451 	if (vma->vm_file)
452 		fput(vma->vm_file);
453 	mpol_put(vma_policy(vma));
454 	vm_area_free(vma);
455 }
456 
457 /*
458  * Get rid of page table information in the indicated region.
459  *
460  * Called with the mm semaphore held.
461  */
462 void unmap_region(struct ma_state *mas, struct vm_area_struct *vma,
463 		struct vm_area_struct *prev, struct vm_area_struct *next)
464 {
465 	struct mm_struct *mm = vma->vm_mm;
466 	struct mmu_gather tlb;
467 
468 	tlb_gather_mmu(&tlb, mm);
469 	update_hiwater_rss(mm);
470 	unmap_vmas(&tlb, mas, vma, vma->vm_start, vma->vm_end, vma->vm_end,
471 		   /* mm_wr_locked = */ true);
472 	mas_set(mas, vma->vm_end);
473 	free_pgtables(&tlb, mas, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
474 		      next ? next->vm_start : USER_PGTABLES_CEILING,
475 		      /* mm_wr_locked = */ true);
476 	tlb_finish_mmu(&tlb);
477 }
478 
479 /*
480  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
481  * has already been checked or doesn't make sense to fail.
482  * VMA Iterator will point to the original VMA.
483  */
484 static __must_check int
485 __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
486 	    unsigned long addr, int new_below)
487 {
488 	struct vma_prepare vp;
489 	struct vm_area_struct *new;
490 	int err;
491 
492 	WARN_ON(vma->vm_start >= addr);
493 	WARN_ON(vma->vm_end <= addr);
494 
495 	if (vma->vm_ops && vma->vm_ops->may_split) {
496 		err = vma->vm_ops->may_split(vma, addr);
497 		if (err)
498 			return err;
499 	}
500 
501 	new = vm_area_dup(vma);
502 	if (!new)
503 		return -ENOMEM;
504 
505 	if (new_below) {
506 		new->vm_end = addr;
507 	} else {
508 		new->vm_start = addr;
509 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
510 	}
511 
512 	err = -ENOMEM;
513 	vma_iter_config(vmi, new->vm_start, new->vm_end);
514 	if (vma_iter_prealloc(vmi, new))
515 		goto out_free_vma;
516 
517 	err = vma_dup_policy(vma, new);
518 	if (err)
519 		goto out_free_vmi;
520 
521 	err = anon_vma_clone(new, vma);
522 	if (err)
523 		goto out_free_mpol;
524 
525 	if (new->vm_file)
526 		get_file(new->vm_file);
527 
528 	if (new->vm_ops && new->vm_ops->open)
529 		new->vm_ops->open(new);
530 
531 	vma_start_write(vma);
532 	vma_start_write(new);
533 
534 	init_vma_prep(&vp, vma);
535 	vp.insert = new;
536 	vma_prepare(&vp);
537 	vma_adjust_trans_huge(vma, vma->vm_start, addr, NULL);
538 
539 	if (new_below) {
540 		vma->vm_start = addr;
541 		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
542 	} else {
543 		vma->vm_end = addr;
544 	}
545 
546 	/* vma_complete stores the new vma */
547 	vma_complete(&vp, vmi, vma->vm_mm);
548 	validate_mm(vma->vm_mm);
549 
550 	/* Success. */
551 	if (new_below)
552 		vma_next(vmi);
553 	else
554 		vma_prev(vmi);
555 
556 	return 0;
557 
558 out_free_mpol:
559 	mpol_put(vma_policy(new));
560 out_free_vmi:
561 	vma_iter_free(vmi);
562 out_free_vma:
563 	vm_area_free(new);
564 	return err;
565 }
566 
567 /*
568  * Split a vma into two pieces at address 'addr', a new vma is allocated
569  * either for the first part or the tail.
570  */
571 static int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
572 		     unsigned long addr, int new_below)
573 {
574 	if (vma->vm_mm->map_count >= sysctl_max_map_count)
575 		return -ENOMEM;
576 
577 	return __split_vma(vmi, vma, addr, new_below);
578 }
579 
580 /*
581  * dup_anon_vma() - Helper function to duplicate anon_vma on VMA merge in the
582  * instance that the destination VMA has no anon_vma but the source does.
583  *
584  * @dst: The destination VMA
585  * @src: The source VMA
586  * @dup: Pointer to the destination VMA when successful.
587  *
588  * Returns: 0 on success.
589  */
590 static int dup_anon_vma(struct vm_area_struct *dst,
591 			struct vm_area_struct *src, struct vm_area_struct **dup)
592 {
593 	/*
594 	 * There are three cases to consider for correctly propagating
595 	 * anon_vma's on merge.
596 	 *
597 	 * The first is trivial - neither VMA has anon_vma, we need not do
598 	 * anything.
599 	 *
600 	 * The second where both have anon_vma is also a no-op, as they must
601 	 * then be the same, so there is simply nothing to copy.
602 	 *
603 	 * Here we cover the third - if the destination VMA has no anon_vma,
604 	 * that is it is unfaulted, we need to ensure that the newly merged
605 	 * range is referenced by the anon_vma's of the source.
606 	 */
607 	if (src->anon_vma && !dst->anon_vma) {
608 		int ret;
609 
610 		vma_assert_write_locked(dst);
611 		dst->anon_vma = src->anon_vma;
612 		ret = anon_vma_clone(dst, src);
613 		if (ret)
614 			return ret;
615 
616 		*dup = dst;
617 	}
618 
619 	return 0;
620 }
621 
622 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
623 void validate_mm(struct mm_struct *mm)
624 {
625 	int bug = 0;
626 	int i = 0;
627 	struct vm_area_struct *vma;
628 	VMA_ITERATOR(vmi, mm, 0);
629 
630 	mt_validate(&mm->mm_mt);
631 	for_each_vma(vmi, vma) {
632 #ifdef CONFIG_DEBUG_VM_RB
633 		struct anon_vma *anon_vma = vma->anon_vma;
634 		struct anon_vma_chain *avc;
635 #endif
636 		unsigned long vmi_start, vmi_end;
637 		bool warn = 0;
638 
639 		vmi_start = vma_iter_addr(&vmi);
640 		vmi_end = vma_iter_end(&vmi);
641 		if (VM_WARN_ON_ONCE_MM(vma->vm_end != vmi_end, mm))
642 			warn = 1;
643 
644 		if (VM_WARN_ON_ONCE_MM(vma->vm_start != vmi_start, mm))
645 			warn = 1;
646 
647 		if (warn) {
648 			pr_emerg("issue in %s\n", current->comm);
649 			dump_stack();
650 			dump_vma(vma);
651 			pr_emerg("tree range: %px start %lx end %lx\n", vma,
652 				 vmi_start, vmi_end - 1);
653 			vma_iter_dump_tree(&vmi);
654 		}
655 
656 #ifdef CONFIG_DEBUG_VM_RB
657 		if (anon_vma) {
658 			anon_vma_lock_read(anon_vma);
659 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
660 				anon_vma_interval_tree_verify(avc);
661 			anon_vma_unlock_read(anon_vma);
662 		}
663 #endif
664 		/* Check for a infinite loop */
665 		if (++i > mm->map_count + 10) {
666 			i = -1;
667 			break;
668 		}
669 	}
670 	if (i != mm->map_count) {
671 		pr_emerg("map_count %d vma iterator %d\n", mm->map_count, i);
672 		bug = 1;
673 	}
674 	VM_BUG_ON_MM(bug, mm);
675 }
676 #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
677 
678 /*
679  * Based on the vmg flag indicating whether we need to adjust the vm_start field
680  * for the middle or next VMA, we calculate what the range of the newly adjusted
681  * VMA ought to be, and set the VMA's range accordingly.
682  */
683 static void vmg_adjust_set_range(struct vma_merge_struct *vmg)
684 {
685 	struct vm_area_struct *adjust;
686 	pgoff_t pgoff;
687 
688 	if (vmg->__adjust_middle_start) {
689 		adjust = vmg->middle;
690 		pgoff = adjust->vm_pgoff + PHYS_PFN(vmg->end - adjust->vm_start);
691 	} else if (vmg->__adjust_next_start) {
692 		adjust = vmg->next;
693 		pgoff = adjust->vm_pgoff - PHYS_PFN(adjust->vm_start - vmg->end);
694 	} else {
695 		return;
696 	}
697 
698 	vma_set_range(adjust, vmg->end, adjust->vm_end, pgoff);
699 }
700 
701 /*
702  * Actually perform the VMA merge operation.
703  *
704  * IMPORTANT: We guarantee that, should vmg->give_up_on_oom is set, to not
705  * modify any VMAs or cause inconsistent state should an OOM condition arise.
706  *
707  * Returns 0 on success, or an error value on failure.
708  */
709 static int commit_merge(struct vma_merge_struct *vmg)
710 {
711 	struct vm_area_struct *vma;
712 	struct vma_prepare vp;
713 
714 	if (vmg->__adjust_next_start) {
715 		/* We manipulate middle and adjust next, which is the target. */
716 		vma = vmg->middle;
717 		vma_iter_config(vmg->vmi, vmg->end, vmg->next->vm_end);
718 	} else {
719 		vma = vmg->target;
720 		 /* Note: vma iterator must be pointing to 'start'. */
721 		vma_iter_config(vmg->vmi, vmg->start, vmg->end);
722 	}
723 
724 	init_multi_vma_prep(&vp, vma, vmg);
725 
726 	/*
727 	 * If vmg->give_up_on_oom is set, we're safe, because we don't actually
728 	 * manipulate any VMAs until we succeed at preallocation.
729 	 *
730 	 * Past this point, we will not return an error.
731 	 */
732 	if (vma_iter_prealloc(vmg->vmi, vma))
733 		return -ENOMEM;
734 
735 	vma_prepare(&vp);
736 	/*
737 	 * THP pages may need to do additional splits if we increase
738 	 * middle->vm_start.
739 	 */
740 	vma_adjust_trans_huge(vma, vmg->start, vmg->end,
741 			      vmg->__adjust_middle_start ? vmg->middle : NULL);
742 	vma_set_range(vma, vmg->start, vmg->end, vmg->pgoff);
743 	vmg_adjust_set_range(vmg);
744 	vma_iter_store_overwrite(vmg->vmi, vmg->target);
745 
746 	vma_complete(&vp, vmg->vmi, vma->vm_mm);
747 
748 	return 0;
749 }
750 
751 /* We can only remove VMAs when merging if they do not have a close hook. */
752 static bool can_merge_remove_vma(struct vm_area_struct *vma)
753 {
754 	return !vma->vm_ops || !vma->vm_ops->close;
755 }
756 
757 /*
758  * vma_merge_existing_range - Attempt to merge VMAs based on a VMA having its
759  * attributes modified.
760  *
761  * @vmg: Describes the modifications being made to a VMA and associated
762  *       metadata.
763  *
764  * When the attributes of a range within a VMA change, then it might be possible
765  * for immediately adjacent VMAs to be merged into that VMA due to having
766  * identical properties.
767  *
768  * This function checks for the existence of any such mergeable VMAs and updates
769  * the maple tree describing the @vmg->middle->vm_mm address space to account
770  * for this, as well as any VMAs shrunk/expanded/deleted as a result of this
771  * merge.
772  *
773  * As part of this operation, if a merge occurs, the @vmg object will have its
774  * vma, start, end, and pgoff fields modified to execute the merge. Subsequent
775  * calls to this function should reset these fields.
776  *
777  * Returns: The merged VMA if merge succeeds, or NULL otherwise.
778  *
779  * ASSUMPTIONS:
780  * - The caller must assign the VMA to be modifed to @vmg->middle.
781  * - The caller must have set @vmg->prev to the previous VMA, if there is one.
782  * - The caller must not set @vmg->next, as we determine this.
783  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
784  * - vmi must be positioned within [@vmg->middle->vm_start, @vmg->middle->vm_end).
785  */
786 static __must_check struct vm_area_struct *vma_merge_existing_range(
787 		struct vma_merge_struct *vmg)
788 {
789 	struct vm_area_struct *middle = vmg->middle;
790 	struct vm_area_struct *prev = vmg->prev;
791 	struct vm_area_struct *next;
792 	struct vm_area_struct *anon_dup = NULL;
793 	unsigned long start = vmg->start;
794 	unsigned long end = vmg->end;
795 	bool left_side = middle && start == middle->vm_start;
796 	bool right_side = middle && end == middle->vm_end;
797 	int err = 0;
798 	bool merge_left, merge_right, merge_both;
799 
800 	mmap_assert_write_locked(vmg->mm);
801 	VM_WARN_ON_VMG(!middle, vmg); /* We are modifying a VMA, so caller must specify. */
802 	VM_WARN_ON_VMG(vmg->next, vmg); /* We set this. */
803 	VM_WARN_ON_VMG(prev && start <= prev->vm_start, vmg);
804 	VM_WARN_ON_VMG(start >= end, vmg);
805 
806 	/*
807 	 * If middle == prev, then we are offset into a VMA. Otherwise, if we are
808 	 * not, we must span a portion of the VMA.
809 	 */
810 	VM_WARN_ON_VMG(middle &&
811 		       ((middle != prev && vmg->start != middle->vm_start) ||
812 			vmg->end > middle->vm_end), vmg);
813 	/* The vmi must be positioned within vmg->middle. */
814 	VM_WARN_ON_VMG(middle &&
815 		       !(vma_iter_addr(vmg->vmi) >= middle->vm_start &&
816 			 vma_iter_addr(vmg->vmi) < middle->vm_end), vmg);
817 
818 	vmg->state = VMA_MERGE_NOMERGE;
819 
820 	/*
821 	 * If a special mapping or if the range being modified is neither at the
822 	 * furthermost left or right side of the VMA, then we have no chance of
823 	 * merging and should abort.
824 	 */
825 	if (vmg->flags & VM_SPECIAL || (!left_side && !right_side))
826 		return NULL;
827 
828 	if (left_side)
829 		merge_left = can_vma_merge_left(vmg);
830 	else
831 		merge_left = false;
832 
833 	if (right_side) {
834 		next = vmg->next = vma_iter_next_range(vmg->vmi);
835 		vma_iter_prev_range(vmg->vmi);
836 
837 		merge_right = can_vma_merge_right(vmg, merge_left);
838 	} else {
839 		merge_right = false;
840 		next = NULL;
841 	}
842 
843 	if (merge_left)		/* If merging prev, position iterator there. */
844 		vma_prev(vmg->vmi);
845 	else if (!merge_right)	/* If we have nothing to merge, abort. */
846 		return NULL;
847 
848 	merge_both = merge_left && merge_right;
849 	/* If we span the entire VMA, a merge implies it will be deleted. */
850 	vmg->__remove_middle = left_side && right_side;
851 
852 	/*
853 	 * If we need to remove middle in its entirety but are unable to do so,
854 	 * we have no sensible recourse but to abort the merge.
855 	 */
856 	if (vmg->__remove_middle && !can_merge_remove_vma(middle))
857 		return NULL;
858 
859 	/*
860 	 * If we merge both VMAs, then next is also deleted. This implies
861 	 * merge_will_delete_vma also.
862 	 */
863 	vmg->__remove_next = merge_both;
864 
865 	/*
866 	 * If we cannot delete next, then we can reduce the operation to merging
867 	 * prev and middle (thereby deleting middle).
868 	 */
869 	if (vmg->__remove_next && !can_merge_remove_vma(next)) {
870 		vmg->__remove_next = false;
871 		merge_right = false;
872 		merge_both = false;
873 	}
874 
875 	/* No matter what happens, we will be adjusting middle. */
876 	vma_start_write(middle);
877 
878 	if (merge_right) {
879 		vma_start_write(next);
880 		vmg->target = next;
881 	}
882 
883 	if (merge_left) {
884 		vma_start_write(prev);
885 		vmg->target = prev;
886 	}
887 
888 	if (merge_both) {
889 		/*
890 		 * |<-------------------->|
891 		 * |-------********-------|
892 		 *   prev   middle   next
893 		 *  extend  delete  delete
894 		 */
895 
896 		vmg->start = prev->vm_start;
897 		vmg->end = next->vm_end;
898 		vmg->pgoff = prev->vm_pgoff;
899 
900 		/*
901 		 * We already ensured anon_vma compatibility above, so now it's
902 		 * simply a case of, if prev has no anon_vma object, which of
903 		 * next or middle contains the anon_vma we must duplicate.
904 		 */
905 		err = dup_anon_vma(prev, next->anon_vma ? next : middle,
906 				   &anon_dup);
907 	} else if (merge_left) {
908 		/*
909 		 * |<------------>|      OR
910 		 * |<----------------->|
911 		 * |-------*************
912 		 *   prev     middle
913 		 *  extend shrink/delete
914 		 */
915 
916 		vmg->start = prev->vm_start;
917 		vmg->pgoff = prev->vm_pgoff;
918 
919 		if (!vmg->__remove_middle)
920 			vmg->__adjust_middle_start = true;
921 
922 		err = dup_anon_vma(prev, middle, &anon_dup);
923 	} else { /* merge_right */
924 		/*
925 		 *     |<------------->| OR
926 		 * |<----------------->|
927 		 * *************-------|
928 		 *    middle     next
929 		 * shrink/delete extend
930 		 */
931 
932 		pgoff_t pglen = PHYS_PFN(vmg->end - vmg->start);
933 
934 		VM_WARN_ON_VMG(!merge_right, vmg);
935 		/* If we are offset into a VMA, then prev must be middle. */
936 		VM_WARN_ON_VMG(vmg->start > middle->vm_start && prev && middle != prev, vmg);
937 
938 		if (vmg->__remove_middle) {
939 			vmg->end = next->vm_end;
940 			vmg->pgoff = next->vm_pgoff - pglen;
941 		} else {
942 			/* We shrink middle and expand next. */
943 			vmg->__adjust_next_start = true;
944 			vmg->start = middle->vm_start;
945 			vmg->end = start;
946 			vmg->pgoff = middle->vm_pgoff;
947 		}
948 
949 		err = dup_anon_vma(next, middle, &anon_dup);
950 	}
951 
952 	if (err)
953 		goto abort;
954 
955 	err = commit_merge(vmg);
956 	if (err) {
957 		VM_WARN_ON(err != -ENOMEM);
958 
959 		if (anon_dup)
960 			unlink_anon_vmas(anon_dup);
961 
962 		/*
963 		 * We've cleaned up any cloned anon_vma's, no VMAs have been
964 		 * modified, no harm no foul if the user requests that we not
965 		 * report this and just give up, leaving the VMAs unmerged.
966 		 */
967 		if (!vmg->give_up_on_oom)
968 			vmg->state = VMA_MERGE_ERROR_NOMEM;
969 		return NULL;
970 	}
971 
972 	khugepaged_enter_vma(vmg->target, vmg->flags);
973 	vmg->state = VMA_MERGE_SUCCESS;
974 	return vmg->target;
975 
976 abort:
977 	vma_iter_set(vmg->vmi, start);
978 	vma_iter_load(vmg->vmi);
979 
980 	/*
981 	 * This means we have failed to clone anon_vma's correctly, but no
982 	 * actual changes to VMAs have occurred, so no harm no foul - if the
983 	 * user doesn't want this reported and instead just wants to give up on
984 	 * the merge, allow it.
985 	 */
986 	if (!vmg->give_up_on_oom)
987 		vmg->state = VMA_MERGE_ERROR_NOMEM;
988 	return NULL;
989 }
990 
991 /*
992  * vma_merge_new_range - Attempt to merge a new VMA into address space
993  *
994  * @vmg: Describes the VMA we are adding, in the range @vmg->start to @vmg->end
995  *       (exclusive), which we try to merge with any adjacent VMAs if possible.
996  *
997  * We are about to add a VMA to the address space starting at @vmg->start and
998  * ending at @vmg->end. There are three different possible scenarios:
999  *
1000  * 1. There is a VMA with identical properties immediately adjacent to the
1001  *    proposed new VMA [@vmg->start, @vmg->end) either before or after it -
1002  *    EXPAND that VMA:
1003  *
1004  * Proposed:       |-----|  or  |-----|
1005  * Existing:  |----|                  |----|
1006  *
1007  * 2. There are VMAs with identical properties immediately adjacent to the
1008  *    proposed new VMA [@vmg->start, @vmg->end) both before AND after it -
1009  *    EXPAND the former and REMOVE the latter:
1010  *
1011  * Proposed:       |-----|
1012  * Existing:  |----|     |----|
1013  *
1014  * 3. There are no VMAs immediately adjacent to the proposed new VMA or those
1015  *    VMAs do not have identical attributes - NO MERGE POSSIBLE.
1016  *
1017  * In instances where we can merge, this function returns the expanded VMA which
1018  * will have its range adjusted accordingly and the underlying maple tree also
1019  * adjusted.
1020  *
1021  * Returns: In instances where no merge was possible, NULL. Otherwise, a pointer
1022  *          to the VMA we expanded.
1023  *
1024  * This function adjusts @vmg to provide @vmg->next if not already specified,
1025  * and adjusts [@vmg->start, @vmg->end) to span the expanded range.
1026  *
1027  * ASSUMPTIONS:
1028  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
1029  * - The caller must have determined that [@vmg->start, @vmg->end) is empty,
1030      other than VMAs that will be unmapped should the operation succeed.
1031  * - The caller must have specified the previous vma in @vmg->prev.
1032  * - The caller must have specified the next vma in @vmg->next.
1033  * - The caller must have positioned the vmi at or before the gap.
1034  */
1035 struct vm_area_struct *vma_merge_new_range(struct vma_merge_struct *vmg)
1036 {
1037 	struct vm_area_struct *prev = vmg->prev;
1038 	struct vm_area_struct *next = vmg->next;
1039 	unsigned long end = vmg->end;
1040 	bool can_merge_left, can_merge_right;
1041 
1042 	mmap_assert_write_locked(vmg->mm);
1043 	VM_WARN_ON_VMG(vmg->middle, vmg);
1044 	/* vmi must point at or before the gap. */
1045 	VM_WARN_ON_VMG(vma_iter_addr(vmg->vmi) > end, vmg);
1046 
1047 	vmg->state = VMA_MERGE_NOMERGE;
1048 
1049 	/* Special VMAs are unmergeable, also if no prev/next. */
1050 	if ((vmg->flags & VM_SPECIAL) || (!prev && !next))
1051 		return NULL;
1052 
1053 	can_merge_left = can_vma_merge_left(vmg);
1054 	can_merge_right = !vmg->just_expand && can_vma_merge_right(vmg, can_merge_left);
1055 
1056 	/* If we can merge with the next VMA, adjust vmg accordingly. */
1057 	if (can_merge_right) {
1058 		vmg->end = next->vm_end;
1059 		vmg->middle = next;
1060 	}
1061 
1062 	/* If we can merge with the previous VMA, adjust vmg accordingly. */
1063 	if (can_merge_left) {
1064 		vmg->start = prev->vm_start;
1065 		vmg->middle = prev;
1066 		vmg->pgoff = prev->vm_pgoff;
1067 
1068 		/*
1069 		 * If this merge would result in removal of the next VMA but we
1070 		 * are not permitted to do so, reduce the operation to merging
1071 		 * prev and vma.
1072 		 */
1073 		if (can_merge_right && !can_merge_remove_vma(next))
1074 			vmg->end = end;
1075 
1076 		/* In expand-only case we are already positioned at prev. */
1077 		if (!vmg->just_expand) {
1078 			/* Equivalent to going to the previous range. */
1079 			vma_prev(vmg->vmi);
1080 		}
1081 	}
1082 
1083 	/*
1084 	 * Now try to expand adjacent VMA(s). This takes care of removing the
1085 	 * following VMA if we have VMAs on both sides.
1086 	 */
1087 	if (vmg->middle && !vma_expand(vmg)) {
1088 		khugepaged_enter_vma(vmg->middle, vmg->flags);
1089 		vmg->state = VMA_MERGE_SUCCESS;
1090 		return vmg->middle;
1091 	}
1092 
1093 	return NULL;
1094 }
1095 
1096 /*
1097  * vma_expand - Expand an existing VMA
1098  *
1099  * @vmg: Describes a VMA expansion operation.
1100  *
1101  * Expand @vma to vmg->start and vmg->end.  Can expand off the start and end.
1102  * Will expand over vmg->next if it's different from vmg->middle and vmg->end ==
1103  * vmg->next->vm_end.  Checking if the vmg->middle can expand and merge with
1104  * vmg->next needs to be handled by the caller.
1105  *
1106  * Returns: 0 on success.
1107  *
1108  * ASSUMPTIONS:
1109  * - The caller must hold a WRITE lock on vmg->middle->mm->mmap_lock.
1110  * - The caller must have set @vmg->middle and @vmg->next.
1111  */
1112 int vma_expand(struct vma_merge_struct *vmg)
1113 {
1114 	struct vm_area_struct *anon_dup = NULL;
1115 	bool remove_next = false;
1116 	struct vm_area_struct *middle = vmg->middle;
1117 	struct vm_area_struct *next = vmg->next;
1118 
1119 	mmap_assert_write_locked(vmg->mm);
1120 
1121 	vma_start_write(middle);
1122 	if (next && (middle != next) && (vmg->end == next->vm_end)) {
1123 		int ret;
1124 
1125 		remove_next = true;
1126 		/* This should already have been checked by this point. */
1127 		VM_WARN_ON_VMG(!can_merge_remove_vma(next), vmg);
1128 		vma_start_write(next);
1129 		/*
1130 		 * In this case we don't report OOM, so vmg->give_up_on_mm is
1131 		 * safe.
1132 		 */
1133 		ret = dup_anon_vma(middle, next, &anon_dup);
1134 		if (ret)
1135 			return ret;
1136 	}
1137 
1138 	/* Not merging but overwriting any part of next is not handled. */
1139 	VM_WARN_ON_VMG(next && !remove_next &&
1140 		       next != middle && vmg->end > next->vm_start, vmg);
1141 	/* Only handles expanding */
1142 	VM_WARN_ON_VMG(middle->vm_start < vmg->start ||
1143 		       middle->vm_end > vmg->end, vmg);
1144 
1145 	vmg->target = middle;
1146 	if (remove_next)
1147 		vmg->__remove_next = true;
1148 
1149 	if (commit_merge(vmg))
1150 		goto nomem;
1151 
1152 	return 0;
1153 
1154 nomem:
1155 	if (anon_dup)
1156 		unlink_anon_vmas(anon_dup);
1157 	/*
1158 	 * If the user requests that we just give upon OOM, we are safe to do so
1159 	 * here, as commit merge provides this contract to us. Nothing has been
1160 	 * changed - no harm no foul, just don't report it.
1161 	 */
1162 	if (!vmg->give_up_on_oom)
1163 		vmg->state = VMA_MERGE_ERROR_NOMEM;
1164 	return -ENOMEM;
1165 }
1166 
1167 /*
1168  * vma_shrink() - Reduce an existing VMAs memory area
1169  * @vmi: The vma iterator
1170  * @vma: The VMA to modify
1171  * @start: The new start
1172  * @end: The new end
1173  *
1174  * Returns: 0 on success, -ENOMEM otherwise
1175  */
1176 int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
1177 	       unsigned long start, unsigned long end, pgoff_t pgoff)
1178 {
1179 	struct vma_prepare vp;
1180 
1181 	WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
1182 
1183 	if (vma->vm_start < start)
1184 		vma_iter_config(vmi, vma->vm_start, start);
1185 	else
1186 		vma_iter_config(vmi, end, vma->vm_end);
1187 
1188 	if (vma_iter_prealloc(vmi, NULL))
1189 		return -ENOMEM;
1190 
1191 	vma_start_write(vma);
1192 
1193 	init_vma_prep(&vp, vma);
1194 	vma_prepare(&vp);
1195 	vma_adjust_trans_huge(vma, start, end, NULL);
1196 
1197 	vma_iter_clear(vmi);
1198 	vma_set_range(vma, start, end, pgoff);
1199 	vma_complete(&vp, vmi, vma->vm_mm);
1200 	validate_mm(vma->vm_mm);
1201 	return 0;
1202 }
1203 
1204 static inline void vms_clear_ptes(struct vma_munmap_struct *vms,
1205 		    struct ma_state *mas_detach, bool mm_wr_locked)
1206 {
1207 	struct mmu_gather tlb;
1208 
1209 	if (!vms->clear_ptes) /* Nothing to do */
1210 		return;
1211 
1212 	/*
1213 	 * We can free page tables without write-locking mmap_lock because VMAs
1214 	 * were isolated before we downgraded mmap_lock.
1215 	 */
1216 	mas_set(mas_detach, 1);
1217 	tlb_gather_mmu(&tlb, vms->vma->vm_mm);
1218 	update_hiwater_rss(vms->vma->vm_mm);
1219 	unmap_vmas(&tlb, mas_detach, vms->vma, vms->start, vms->end,
1220 		   vms->vma_count, mm_wr_locked);
1221 
1222 	mas_set(mas_detach, 1);
1223 	/* start and end may be different if there is no prev or next vma. */
1224 	free_pgtables(&tlb, mas_detach, vms->vma, vms->unmap_start,
1225 		      vms->unmap_end, mm_wr_locked);
1226 	tlb_finish_mmu(&tlb);
1227 	vms->clear_ptes = false;
1228 }
1229 
1230 static void vms_clean_up_area(struct vma_munmap_struct *vms,
1231 		struct ma_state *mas_detach)
1232 {
1233 	struct vm_area_struct *vma;
1234 
1235 	if (!vms->nr_pages)
1236 		return;
1237 
1238 	vms_clear_ptes(vms, mas_detach, true);
1239 	mas_set(mas_detach, 0);
1240 	mas_for_each(mas_detach, vma, ULONG_MAX)
1241 		vma_close(vma);
1242 }
1243 
1244 /*
1245  * vms_complete_munmap_vmas() - Finish the munmap() operation
1246  * @vms: The vma munmap struct
1247  * @mas_detach: The maple state of the detached vmas
1248  *
1249  * This updates the mm_struct, unmaps the region, frees the resources
1250  * used for the munmap() and may downgrade the lock - if requested.  Everything
1251  * needed to be done once the vma maple tree is updated.
1252  */
1253 static void vms_complete_munmap_vmas(struct vma_munmap_struct *vms,
1254 		struct ma_state *mas_detach)
1255 {
1256 	struct vm_area_struct *vma;
1257 	struct mm_struct *mm;
1258 
1259 	mm = current->mm;
1260 	mm->map_count -= vms->vma_count;
1261 	mm->locked_vm -= vms->locked_vm;
1262 	if (vms->unlock)
1263 		mmap_write_downgrade(mm);
1264 
1265 	if (!vms->nr_pages)
1266 		return;
1267 
1268 	vms_clear_ptes(vms, mas_detach, !vms->unlock);
1269 	/* Update high watermark before we lower total_vm */
1270 	update_hiwater_vm(mm);
1271 	/* Stat accounting */
1272 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm) - vms->nr_pages);
1273 	/* Paranoid bookkeeping */
1274 	VM_WARN_ON(vms->exec_vm > mm->exec_vm);
1275 	VM_WARN_ON(vms->stack_vm > mm->stack_vm);
1276 	VM_WARN_ON(vms->data_vm > mm->data_vm);
1277 	mm->exec_vm -= vms->exec_vm;
1278 	mm->stack_vm -= vms->stack_vm;
1279 	mm->data_vm -= vms->data_vm;
1280 
1281 	/* Remove and clean up vmas */
1282 	mas_set(mas_detach, 0);
1283 	mas_for_each(mas_detach, vma, ULONG_MAX)
1284 		remove_vma(vma);
1285 
1286 	vm_unacct_memory(vms->nr_accounted);
1287 	validate_mm(mm);
1288 	if (vms->unlock)
1289 		mmap_read_unlock(mm);
1290 
1291 	__mt_destroy(mas_detach->tree);
1292 }
1293 
1294 /*
1295  * reattach_vmas() - Undo any munmap work and free resources
1296  * @mas_detach: The maple state with the detached maple tree
1297  *
1298  * Reattach any detached vmas and free up the maple tree used to track the vmas.
1299  */
1300 static void reattach_vmas(struct ma_state *mas_detach)
1301 {
1302 	struct vm_area_struct *vma;
1303 
1304 	mas_set(mas_detach, 0);
1305 	mas_for_each(mas_detach, vma, ULONG_MAX)
1306 		vma_mark_attached(vma);
1307 
1308 	__mt_destroy(mas_detach->tree);
1309 }
1310 
1311 /*
1312  * vms_gather_munmap_vmas() - Put all VMAs within a range into a maple tree
1313  * for removal at a later date.  Handles splitting first and last if necessary
1314  * and marking the vmas as isolated.
1315  *
1316  * @vms: The vma munmap struct
1317  * @mas_detach: The maple state tracking the detached tree
1318  *
1319  * Return: 0 on success, error otherwise
1320  */
1321 static int vms_gather_munmap_vmas(struct vma_munmap_struct *vms,
1322 		struct ma_state *mas_detach)
1323 {
1324 	struct vm_area_struct *next = NULL;
1325 	int error;
1326 
1327 	/*
1328 	 * If we need to split any vma, do it now to save pain later.
1329 	 * Does it split the first one?
1330 	 */
1331 	if (vms->start > vms->vma->vm_start) {
1332 
1333 		/*
1334 		 * Make sure that map_count on return from munmap() will
1335 		 * not exceed its limit; but let map_count go just above
1336 		 * its limit temporarily, to help free resources as expected.
1337 		 */
1338 		if (vms->end < vms->vma->vm_end &&
1339 		    vms->vma->vm_mm->map_count >= sysctl_max_map_count) {
1340 			error = -ENOMEM;
1341 			goto map_count_exceeded;
1342 		}
1343 
1344 		/* Don't bother splitting the VMA if we can't unmap it anyway */
1345 		if (!can_modify_vma(vms->vma)) {
1346 			error = -EPERM;
1347 			goto start_split_failed;
1348 		}
1349 
1350 		error = __split_vma(vms->vmi, vms->vma, vms->start, 1);
1351 		if (error)
1352 			goto start_split_failed;
1353 	}
1354 	vms->prev = vma_prev(vms->vmi);
1355 	if (vms->prev)
1356 		vms->unmap_start = vms->prev->vm_end;
1357 
1358 	/*
1359 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
1360 	 * it is always overwritten.
1361 	 */
1362 	for_each_vma_range(*(vms->vmi), next, vms->end) {
1363 		long nrpages;
1364 
1365 		if (!can_modify_vma(next)) {
1366 			error = -EPERM;
1367 			goto modify_vma_failed;
1368 		}
1369 		/* Does it split the end? */
1370 		if (next->vm_end > vms->end) {
1371 			error = __split_vma(vms->vmi, next, vms->end, 0);
1372 			if (error)
1373 				goto end_split_failed;
1374 		}
1375 		vma_start_write(next);
1376 		mas_set(mas_detach, vms->vma_count++);
1377 		error = mas_store_gfp(mas_detach, next, GFP_KERNEL);
1378 		if (error)
1379 			goto munmap_gather_failed;
1380 
1381 		vma_mark_detached(next);
1382 		nrpages = vma_pages(next);
1383 
1384 		vms->nr_pages += nrpages;
1385 		if (next->vm_flags & VM_LOCKED)
1386 			vms->locked_vm += nrpages;
1387 
1388 		if (next->vm_flags & VM_ACCOUNT)
1389 			vms->nr_accounted += nrpages;
1390 
1391 		if (is_exec_mapping(next->vm_flags))
1392 			vms->exec_vm += nrpages;
1393 		else if (is_stack_mapping(next->vm_flags))
1394 			vms->stack_vm += nrpages;
1395 		else if (is_data_mapping(next->vm_flags))
1396 			vms->data_vm += nrpages;
1397 
1398 		if (vms->uf) {
1399 			/*
1400 			 * If userfaultfd_unmap_prep returns an error the vmas
1401 			 * will remain split, but userland will get a
1402 			 * highly unexpected error anyway. This is no
1403 			 * different than the case where the first of the two
1404 			 * __split_vma fails, but we don't undo the first
1405 			 * split, despite we could. This is unlikely enough
1406 			 * failure that it's not worth optimizing it for.
1407 			 */
1408 			error = userfaultfd_unmap_prep(next, vms->start,
1409 						       vms->end, vms->uf);
1410 			if (error)
1411 				goto userfaultfd_error;
1412 		}
1413 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
1414 		BUG_ON(next->vm_start < vms->start);
1415 		BUG_ON(next->vm_start > vms->end);
1416 #endif
1417 	}
1418 
1419 	vms->next = vma_next(vms->vmi);
1420 	if (vms->next)
1421 		vms->unmap_end = vms->next->vm_start;
1422 
1423 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
1424 	/* Make sure no VMAs are about to be lost. */
1425 	{
1426 		MA_STATE(test, mas_detach->tree, 0, 0);
1427 		struct vm_area_struct *vma_mas, *vma_test;
1428 		int test_count = 0;
1429 
1430 		vma_iter_set(vms->vmi, vms->start);
1431 		rcu_read_lock();
1432 		vma_test = mas_find(&test, vms->vma_count - 1);
1433 		for_each_vma_range(*(vms->vmi), vma_mas, vms->end) {
1434 			BUG_ON(vma_mas != vma_test);
1435 			test_count++;
1436 			vma_test = mas_next(&test, vms->vma_count - 1);
1437 		}
1438 		rcu_read_unlock();
1439 		BUG_ON(vms->vma_count != test_count);
1440 	}
1441 #endif
1442 
1443 	while (vma_iter_addr(vms->vmi) > vms->start)
1444 		vma_iter_prev_range(vms->vmi);
1445 
1446 	vms->clear_ptes = true;
1447 	return 0;
1448 
1449 userfaultfd_error:
1450 munmap_gather_failed:
1451 end_split_failed:
1452 modify_vma_failed:
1453 	reattach_vmas(mas_detach);
1454 start_split_failed:
1455 map_count_exceeded:
1456 	return error;
1457 }
1458 
1459 /*
1460  * init_vma_munmap() - Initializer wrapper for vma_munmap_struct
1461  * @vms: The vma munmap struct
1462  * @vmi: The vma iterator
1463  * @vma: The first vm_area_struct to munmap
1464  * @start: The aligned start address to munmap
1465  * @end: The aligned end address to munmap
1466  * @uf: The userfaultfd list_head
1467  * @unlock: Unlock after the operation.  Only unlocked on success
1468  */
1469 static void init_vma_munmap(struct vma_munmap_struct *vms,
1470 		struct vma_iterator *vmi, struct vm_area_struct *vma,
1471 		unsigned long start, unsigned long end, struct list_head *uf,
1472 		bool unlock)
1473 {
1474 	vms->vmi = vmi;
1475 	vms->vma = vma;
1476 	if (vma) {
1477 		vms->start = start;
1478 		vms->end = end;
1479 	} else {
1480 		vms->start = vms->end = 0;
1481 	}
1482 	vms->unlock = unlock;
1483 	vms->uf = uf;
1484 	vms->vma_count = 0;
1485 	vms->nr_pages = vms->locked_vm = vms->nr_accounted = 0;
1486 	vms->exec_vm = vms->stack_vm = vms->data_vm = 0;
1487 	vms->unmap_start = FIRST_USER_ADDRESS;
1488 	vms->unmap_end = USER_PGTABLES_CEILING;
1489 	vms->clear_ptes = false;
1490 }
1491 
1492 /*
1493  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
1494  * @vmi: The vma iterator
1495  * @vma: The starting vm_area_struct
1496  * @mm: The mm_struct
1497  * @start: The aligned start address to munmap.
1498  * @end: The aligned end address to munmap.
1499  * @uf: The userfaultfd list_head
1500  * @unlock: Set to true to drop the mmap_lock.  unlocking only happens on
1501  * success.
1502  *
1503  * Return: 0 on success and drops the lock if so directed, error and leaves the
1504  * lock held otherwise.
1505  */
1506 int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
1507 		struct mm_struct *mm, unsigned long start, unsigned long end,
1508 		struct list_head *uf, bool unlock)
1509 {
1510 	struct maple_tree mt_detach;
1511 	MA_STATE(mas_detach, &mt_detach, 0, 0);
1512 	mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
1513 	mt_on_stack(mt_detach);
1514 	struct vma_munmap_struct vms;
1515 	int error;
1516 
1517 	init_vma_munmap(&vms, vmi, vma, start, end, uf, unlock);
1518 	error = vms_gather_munmap_vmas(&vms, &mas_detach);
1519 	if (error)
1520 		goto gather_failed;
1521 
1522 	error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
1523 	if (error)
1524 		goto clear_tree_failed;
1525 
1526 	/* Point of no return */
1527 	vms_complete_munmap_vmas(&vms, &mas_detach);
1528 	return 0;
1529 
1530 clear_tree_failed:
1531 	reattach_vmas(&mas_detach);
1532 gather_failed:
1533 	validate_mm(mm);
1534 	return error;
1535 }
1536 
1537 /*
1538  * do_vmi_munmap() - munmap a given range.
1539  * @vmi: The vma iterator
1540  * @mm: The mm_struct
1541  * @start: The start address to munmap
1542  * @len: The length of the range to munmap
1543  * @uf: The userfaultfd list_head
1544  * @unlock: set to true if the user wants to drop the mmap_lock on success
1545  *
1546  * This function takes a @mas that is either pointing to the previous VMA or set
1547  * to MA_START and sets it up to remove the mapping(s).  The @len will be
1548  * aligned.
1549  *
1550  * Return: 0 on success and drops the lock if so directed, error and leaves the
1551  * lock held otherwise.
1552  */
1553 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
1554 		  unsigned long start, size_t len, struct list_head *uf,
1555 		  bool unlock)
1556 {
1557 	unsigned long end;
1558 	struct vm_area_struct *vma;
1559 
1560 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
1561 		return -EINVAL;
1562 
1563 	end = start + PAGE_ALIGN(len);
1564 	if (end == start)
1565 		return -EINVAL;
1566 
1567 	/* Find the first overlapping VMA */
1568 	vma = vma_find(vmi, end);
1569 	if (!vma) {
1570 		if (unlock)
1571 			mmap_write_unlock(mm);
1572 		return 0;
1573 	}
1574 
1575 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
1576 }
1577 
1578 /*
1579  * We are about to modify one or multiple of a VMA's flags, policy, userfaultfd
1580  * context and anonymous VMA name within the range [start, end).
1581  *
1582  * As a result, we might be able to merge the newly modified VMA range with an
1583  * adjacent VMA with identical properties.
1584  *
1585  * If no merge is possible and the range does not span the entirety of the VMA,
1586  * we then need to split the VMA to accommodate the change.
1587  *
1588  * The function returns either the merged VMA, the original VMA if a split was
1589  * required instead, or an error if the split failed.
1590  */
1591 static struct vm_area_struct *vma_modify(struct vma_merge_struct *vmg)
1592 {
1593 	struct vm_area_struct *vma = vmg->middle;
1594 	unsigned long start = vmg->start;
1595 	unsigned long end = vmg->end;
1596 	struct vm_area_struct *merged;
1597 
1598 	/* First, try to merge. */
1599 	merged = vma_merge_existing_range(vmg);
1600 	if (merged)
1601 		return merged;
1602 	if (vmg_nomem(vmg))
1603 		return ERR_PTR(-ENOMEM);
1604 
1605 	/*
1606 	 * Split can fail for reasons other than OOM, so if the user requests
1607 	 * this it's probably a mistake.
1608 	 */
1609 	VM_WARN_ON(vmg->give_up_on_oom &&
1610 		   (vma->vm_start != start || vma->vm_end != end));
1611 
1612 	/* Split any preceding portion of the VMA. */
1613 	if (vma->vm_start < start) {
1614 		int err = split_vma(vmg->vmi, vma, start, 1);
1615 
1616 		if (err)
1617 			return ERR_PTR(err);
1618 	}
1619 
1620 	/* Split any trailing portion of the VMA. */
1621 	if (vma->vm_end > end) {
1622 		int err = split_vma(vmg->vmi, vma, end, 0);
1623 
1624 		if (err)
1625 			return ERR_PTR(err);
1626 	}
1627 
1628 	return vma;
1629 }
1630 
1631 struct vm_area_struct *vma_modify_flags(
1632 	struct vma_iterator *vmi, struct vm_area_struct *prev,
1633 	struct vm_area_struct *vma, unsigned long start, unsigned long end,
1634 	unsigned long new_flags)
1635 {
1636 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1637 
1638 	vmg.flags = new_flags;
1639 
1640 	return vma_modify(&vmg);
1641 }
1642 
1643 struct vm_area_struct
1644 *vma_modify_flags_name(struct vma_iterator *vmi,
1645 		       struct vm_area_struct *prev,
1646 		       struct vm_area_struct *vma,
1647 		       unsigned long start,
1648 		       unsigned long end,
1649 		       unsigned long new_flags,
1650 		       struct anon_vma_name *new_name)
1651 {
1652 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1653 
1654 	vmg.flags = new_flags;
1655 	vmg.anon_name = new_name;
1656 
1657 	return vma_modify(&vmg);
1658 }
1659 
1660 struct vm_area_struct
1661 *vma_modify_policy(struct vma_iterator *vmi,
1662 		   struct vm_area_struct *prev,
1663 		   struct vm_area_struct *vma,
1664 		   unsigned long start, unsigned long end,
1665 		   struct mempolicy *new_pol)
1666 {
1667 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1668 
1669 	vmg.policy = new_pol;
1670 
1671 	return vma_modify(&vmg);
1672 }
1673 
1674 struct vm_area_struct
1675 *vma_modify_flags_uffd(struct vma_iterator *vmi,
1676 		       struct vm_area_struct *prev,
1677 		       struct vm_area_struct *vma,
1678 		       unsigned long start, unsigned long end,
1679 		       unsigned long new_flags,
1680 		       struct vm_userfaultfd_ctx new_ctx,
1681 		       bool give_up_on_oom)
1682 {
1683 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1684 
1685 	vmg.flags = new_flags;
1686 	vmg.uffd_ctx = new_ctx;
1687 	if (give_up_on_oom)
1688 		vmg.give_up_on_oom = true;
1689 
1690 	return vma_modify(&vmg);
1691 }
1692 
1693 /*
1694  * Expand vma by delta bytes, potentially merging with an immediately adjacent
1695  * VMA with identical properties.
1696  */
1697 struct vm_area_struct *vma_merge_extend(struct vma_iterator *vmi,
1698 					struct vm_area_struct *vma,
1699 					unsigned long delta)
1700 {
1701 	VMG_VMA_STATE(vmg, vmi, vma, vma, vma->vm_end, vma->vm_end + delta);
1702 
1703 	vmg.next = vma_iter_next_rewind(vmi, NULL);
1704 	vmg.middle = NULL; /* We use the VMA to populate VMG fields only. */
1705 
1706 	return vma_merge_new_range(&vmg);
1707 }
1708 
1709 void unlink_file_vma_batch_init(struct unlink_vma_file_batch *vb)
1710 {
1711 	vb->count = 0;
1712 }
1713 
1714 static void unlink_file_vma_batch_process(struct unlink_vma_file_batch *vb)
1715 {
1716 	struct address_space *mapping;
1717 	int i;
1718 
1719 	mapping = vb->vmas[0]->vm_file->f_mapping;
1720 	i_mmap_lock_write(mapping);
1721 	for (i = 0; i < vb->count; i++) {
1722 		VM_WARN_ON_ONCE(vb->vmas[i]->vm_file->f_mapping != mapping);
1723 		__remove_shared_vm_struct(vb->vmas[i], mapping);
1724 	}
1725 	i_mmap_unlock_write(mapping);
1726 
1727 	unlink_file_vma_batch_init(vb);
1728 }
1729 
1730 void unlink_file_vma_batch_add(struct unlink_vma_file_batch *vb,
1731 			       struct vm_area_struct *vma)
1732 {
1733 	if (vma->vm_file == NULL)
1734 		return;
1735 
1736 	if ((vb->count > 0 && vb->vmas[0]->vm_file != vma->vm_file) ||
1737 	    vb->count == ARRAY_SIZE(vb->vmas))
1738 		unlink_file_vma_batch_process(vb);
1739 
1740 	vb->vmas[vb->count] = vma;
1741 	vb->count++;
1742 }
1743 
1744 void unlink_file_vma_batch_final(struct unlink_vma_file_batch *vb)
1745 {
1746 	if (vb->count > 0)
1747 		unlink_file_vma_batch_process(vb);
1748 }
1749 
1750 /*
1751  * Unlink a file-based vm structure from its interval tree, to hide
1752  * vma from rmap and vmtruncate before freeing its page tables.
1753  */
1754 void unlink_file_vma(struct vm_area_struct *vma)
1755 {
1756 	struct file *file = vma->vm_file;
1757 
1758 	if (file) {
1759 		struct address_space *mapping = file->f_mapping;
1760 
1761 		i_mmap_lock_write(mapping);
1762 		__remove_shared_vm_struct(vma, mapping);
1763 		i_mmap_unlock_write(mapping);
1764 	}
1765 }
1766 
1767 void vma_link_file(struct vm_area_struct *vma)
1768 {
1769 	struct file *file = vma->vm_file;
1770 	struct address_space *mapping;
1771 
1772 	if (file) {
1773 		mapping = file->f_mapping;
1774 		i_mmap_lock_write(mapping);
1775 		__vma_link_file(vma, mapping);
1776 		i_mmap_unlock_write(mapping);
1777 	}
1778 }
1779 
1780 int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
1781 {
1782 	VMA_ITERATOR(vmi, mm, 0);
1783 
1784 	vma_iter_config(&vmi, vma->vm_start, vma->vm_end);
1785 	if (vma_iter_prealloc(&vmi, vma))
1786 		return -ENOMEM;
1787 
1788 	vma_start_write(vma);
1789 	vma_iter_store_new(&vmi, vma);
1790 	vma_link_file(vma);
1791 	mm->map_count++;
1792 	validate_mm(mm);
1793 	return 0;
1794 }
1795 
1796 /*
1797  * Copy the vma structure to a new location in the same mm,
1798  * prior to moving page table entries, to effect an mremap move.
1799  */
1800 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
1801 	unsigned long addr, unsigned long len, pgoff_t pgoff,
1802 	bool *need_rmap_locks)
1803 {
1804 	struct vm_area_struct *vma = *vmap;
1805 	unsigned long vma_start = vma->vm_start;
1806 	struct mm_struct *mm = vma->vm_mm;
1807 	struct vm_area_struct *new_vma;
1808 	bool faulted_in_anon_vma = true;
1809 	VMA_ITERATOR(vmi, mm, addr);
1810 	VMG_VMA_STATE(vmg, &vmi, NULL, vma, addr, addr + len);
1811 
1812 	/*
1813 	 * If anonymous vma has not yet been faulted, update new pgoff
1814 	 * to match new location, to increase its chance of merging.
1815 	 */
1816 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
1817 		pgoff = addr >> PAGE_SHIFT;
1818 		faulted_in_anon_vma = false;
1819 	}
1820 
1821 	new_vma = find_vma_prev(mm, addr, &vmg.prev);
1822 	if (new_vma && new_vma->vm_start < addr + len)
1823 		return NULL;	/* should never get here */
1824 
1825 	vmg.middle = NULL; /* New VMA range. */
1826 	vmg.pgoff = pgoff;
1827 	vmg.next = vma_iter_next_rewind(&vmi, NULL);
1828 	new_vma = vma_merge_new_range(&vmg);
1829 
1830 	if (new_vma) {
1831 		/*
1832 		 * Source vma may have been merged into new_vma
1833 		 */
1834 		if (unlikely(vma_start >= new_vma->vm_start &&
1835 			     vma_start < new_vma->vm_end)) {
1836 			/*
1837 			 * The only way we can get a vma_merge with
1838 			 * self during an mremap is if the vma hasn't
1839 			 * been faulted in yet and we were allowed to
1840 			 * reset the dst vma->vm_pgoff to the
1841 			 * destination address of the mremap to allow
1842 			 * the merge to happen. mremap must change the
1843 			 * vm_pgoff linearity between src and dst vmas
1844 			 * (in turn preventing a vma_merge) to be
1845 			 * safe. It is only safe to keep the vm_pgoff
1846 			 * linear if there are no pages mapped yet.
1847 			 */
1848 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
1849 			*vmap = vma = new_vma;
1850 		}
1851 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
1852 	} else {
1853 		new_vma = vm_area_dup(vma);
1854 		if (!new_vma)
1855 			goto out;
1856 		vma_set_range(new_vma, addr, addr + len, pgoff);
1857 		if (vma_dup_policy(vma, new_vma))
1858 			goto out_free_vma;
1859 		if (anon_vma_clone(new_vma, vma))
1860 			goto out_free_mempol;
1861 		if (new_vma->vm_file)
1862 			get_file(new_vma->vm_file);
1863 		if (new_vma->vm_ops && new_vma->vm_ops->open)
1864 			new_vma->vm_ops->open(new_vma);
1865 		if (vma_link(mm, new_vma))
1866 			goto out_vma_link;
1867 		*need_rmap_locks = false;
1868 	}
1869 	return new_vma;
1870 
1871 out_vma_link:
1872 	vma_close(new_vma);
1873 
1874 	if (new_vma->vm_file)
1875 		fput(new_vma->vm_file);
1876 
1877 	unlink_anon_vmas(new_vma);
1878 out_free_mempol:
1879 	mpol_put(vma_policy(new_vma));
1880 out_free_vma:
1881 	vm_area_free(new_vma);
1882 out:
1883 	return NULL;
1884 }
1885 
1886 /*
1887  * Rough compatibility check to quickly see if it's even worth looking
1888  * at sharing an anon_vma.
1889  *
1890  * They need to have the same vm_file, and the flags can only differ
1891  * in things that mprotect may change.
1892  *
1893  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1894  * we can merge the two vma's. For example, we refuse to merge a vma if
1895  * there is a vm_ops->close() function, because that indicates that the
1896  * driver is doing some kind of reference counting. But that doesn't
1897  * really matter for the anon_vma sharing case.
1898  */
1899 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1900 {
1901 	return a->vm_end == b->vm_start &&
1902 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1903 		a->vm_file == b->vm_file &&
1904 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1905 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1906 }
1907 
1908 /*
1909  * Do some basic sanity checking to see if we can re-use the anon_vma
1910  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1911  * the same as 'old', the other will be the new one that is trying
1912  * to share the anon_vma.
1913  *
1914  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1915  * the anon_vma of 'old' is concurrently in the process of being set up
1916  * by another page fault trying to merge _that_. But that's ok: if it
1917  * is being set up, that automatically means that it will be a singleton
1918  * acceptable for merging, so we can do all of this optimistically. But
1919  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1920  *
1921  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1922  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1923  * is to return an anon_vma that is "complex" due to having gone through
1924  * a fork).
1925  *
1926  * We also make sure that the two vma's are compatible (adjacent,
1927  * and with the same memory policies). That's all stable, even with just
1928  * a read lock on the mmap_lock.
1929  */
1930 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old,
1931 					  struct vm_area_struct *a,
1932 					  struct vm_area_struct *b)
1933 {
1934 	if (anon_vma_compatible(a, b)) {
1935 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1936 
1937 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1938 			return anon_vma;
1939 	}
1940 	return NULL;
1941 }
1942 
1943 /*
1944  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1945  * neighbouring vmas for a suitable anon_vma, before it goes off
1946  * to allocate a new anon_vma.  It checks because a repetitive
1947  * sequence of mprotects and faults may otherwise lead to distinct
1948  * anon_vmas being allocated, preventing vma merge in subsequent
1949  * mprotect.
1950  */
1951 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1952 {
1953 	struct anon_vma *anon_vma = NULL;
1954 	struct vm_area_struct *prev, *next;
1955 	VMA_ITERATOR(vmi, vma->vm_mm, vma->vm_end);
1956 
1957 	/* Try next first. */
1958 	next = vma_iter_load(&vmi);
1959 	if (next) {
1960 		anon_vma = reusable_anon_vma(next, vma, next);
1961 		if (anon_vma)
1962 			return anon_vma;
1963 	}
1964 
1965 	prev = vma_prev(&vmi);
1966 	VM_BUG_ON_VMA(prev != vma, vma);
1967 	prev = vma_prev(&vmi);
1968 	/* Try prev next. */
1969 	if (prev)
1970 		anon_vma = reusable_anon_vma(prev, prev, vma);
1971 
1972 	/*
1973 	 * We might reach here with anon_vma == NULL if we can't find
1974 	 * any reusable anon_vma.
1975 	 * There's no absolute need to look only at touching neighbours:
1976 	 * we could search further afield for "compatible" anon_vmas.
1977 	 * But it would probably just be a waste of time searching,
1978 	 * or lead to too many vmas hanging off the same anon_vma.
1979 	 * We're trying to allow mprotect remerging later on,
1980 	 * not trying to minimize memory used for anon_vmas.
1981 	 */
1982 	return anon_vma;
1983 }
1984 
1985 static bool vm_ops_needs_writenotify(const struct vm_operations_struct *vm_ops)
1986 {
1987 	return vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite);
1988 }
1989 
1990 static bool vma_is_shared_writable(struct vm_area_struct *vma)
1991 {
1992 	return (vma->vm_flags & (VM_WRITE | VM_SHARED)) ==
1993 		(VM_WRITE | VM_SHARED);
1994 }
1995 
1996 static bool vma_fs_can_writeback(struct vm_area_struct *vma)
1997 {
1998 	/* No managed pages to writeback. */
1999 	if (vma->vm_flags & VM_PFNMAP)
2000 		return false;
2001 
2002 	return vma->vm_file && vma->vm_file->f_mapping &&
2003 		mapping_can_writeback(vma->vm_file->f_mapping);
2004 }
2005 
2006 /*
2007  * Does this VMA require the underlying folios to have their dirty state
2008  * tracked?
2009  */
2010 bool vma_needs_dirty_tracking(struct vm_area_struct *vma)
2011 {
2012 	/* Only shared, writable VMAs require dirty tracking. */
2013 	if (!vma_is_shared_writable(vma))
2014 		return false;
2015 
2016 	/* Does the filesystem need to be notified? */
2017 	if (vm_ops_needs_writenotify(vma->vm_ops))
2018 		return true;
2019 
2020 	/*
2021 	 * Even if the filesystem doesn't indicate a need for writenotify, if it
2022 	 * can writeback, dirty tracking is still required.
2023 	 */
2024 	return vma_fs_can_writeback(vma);
2025 }
2026 
2027 /*
2028  * Some shared mappings will want the pages marked read-only
2029  * to track write events. If so, we'll downgrade vm_page_prot
2030  * to the private version (using protection_map[] without the
2031  * VM_SHARED bit).
2032  */
2033 bool vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
2034 {
2035 	/* If it was private or non-writable, the write bit is already clear */
2036 	if (!vma_is_shared_writable(vma))
2037 		return false;
2038 
2039 	/* The backer wishes to know when pages are first written to? */
2040 	if (vm_ops_needs_writenotify(vma->vm_ops))
2041 		return true;
2042 
2043 	/* The open routine did something to the protections that pgprot_modify
2044 	 * won't preserve? */
2045 	if (pgprot_val(vm_page_prot) !=
2046 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vma->vm_flags)))
2047 		return false;
2048 
2049 	/*
2050 	 * Do we need to track softdirty? hugetlb does not support softdirty
2051 	 * tracking yet.
2052 	 */
2053 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
2054 		return true;
2055 
2056 	/* Do we need write faults for uffd-wp tracking? */
2057 	if (userfaultfd_wp(vma))
2058 		return true;
2059 
2060 	/* Can the mapping track the dirty pages? */
2061 	return vma_fs_can_writeback(vma);
2062 }
2063 
2064 static DEFINE_MUTEX(mm_all_locks_mutex);
2065 
2066 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
2067 {
2068 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
2069 		/*
2070 		 * The LSB of head.next can't change from under us
2071 		 * because we hold the mm_all_locks_mutex.
2072 		 */
2073 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
2074 		/*
2075 		 * We can safely modify head.next after taking the
2076 		 * anon_vma->root->rwsem. If some other vma in this mm shares
2077 		 * the same anon_vma we won't take it again.
2078 		 *
2079 		 * No need of atomic instructions here, head.next
2080 		 * can't change from under us thanks to the
2081 		 * anon_vma->root->rwsem.
2082 		 */
2083 		if (__test_and_set_bit(0, (unsigned long *)
2084 				       &anon_vma->root->rb_root.rb_root.rb_node))
2085 			BUG();
2086 	}
2087 }
2088 
2089 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
2090 {
2091 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2092 		/*
2093 		 * AS_MM_ALL_LOCKS can't change from under us because
2094 		 * we hold the mm_all_locks_mutex.
2095 		 *
2096 		 * Operations on ->flags have to be atomic because
2097 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
2098 		 * mm_all_locks_mutex, there may be other cpus
2099 		 * changing other bitflags in parallel to us.
2100 		 */
2101 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
2102 			BUG();
2103 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
2104 	}
2105 }
2106 
2107 /*
2108  * This operation locks against the VM for all pte/vma/mm related
2109  * operations that could ever happen on a certain mm. This includes
2110  * vmtruncate, try_to_unmap, and all page faults.
2111  *
2112  * The caller must take the mmap_lock in write mode before calling
2113  * mm_take_all_locks(). The caller isn't allowed to release the
2114  * mmap_lock until mm_drop_all_locks() returns.
2115  *
2116  * mmap_lock in write mode is required in order to block all operations
2117  * that could modify pagetables and free pages without need of
2118  * altering the vma layout. It's also needed in write mode to avoid new
2119  * anon_vmas to be associated with existing vmas.
2120  *
2121  * A single task can't take more than one mm_take_all_locks() in a row
2122  * or it would deadlock.
2123  *
2124  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
2125  * mapping->flags avoid to take the same lock twice, if more than one
2126  * vma in this mm is backed by the same anon_vma or address_space.
2127  *
2128  * We take locks in following order, accordingly to comment at beginning
2129  * of mm/rmap.c:
2130  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
2131  *     hugetlb mapping);
2132  *   - all vmas marked locked
2133  *   - all i_mmap_rwsem locks;
2134  *   - all anon_vma->rwseml
2135  *
2136  * We can take all locks within these types randomly because the VM code
2137  * doesn't nest them and we protected from parallel mm_take_all_locks() by
2138  * mm_all_locks_mutex.
2139  *
2140  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
2141  * that may have to take thousand of locks.
2142  *
2143  * mm_take_all_locks() can fail if it's interrupted by signals.
2144  */
2145 int mm_take_all_locks(struct mm_struct *mm)
2146 {
2147 	struct vm_area_struct *vma;
2148 	struct anon_vma_chain *avc;
2149 	VMA_ITERATOR(vmi, mm, 0);
2150 
2151 	mmap_assert_write_locked(mm);
2152 
2153 	mutex_lock(&mm_all_locks_mutex);
2154 
2155 	/*
2156 	 * vma_start_write() does not have a complement in mm_drop_all_locks()
2157 	 * because vma_start_write() is always asymmetrical; it marks a VMA as
2158 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
2159 	 * is reached.
2160 	 */
2161 	for_each_vma(vmi, vma) {
2162 		if (signal_pending(current))
2163 			goto out_unlock;
2164 		vma_start_write(vma);
2165 	}
2166 
2167 	vma_iter_init(&vmi, mm, 0);
2168 	for_each_vma(vmi, vma) {
2169 		if (signal_pending(current))
2170 			goto out_unlock;
2171 		if (vma->vm_file && vma->vm_file->f_mapping &&
2172 				is_vm_hugetlb_page(vma))
2173 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
2174 	}
2175 
2176 	vma_iter_init(&vmi, mm, 0);
2177 	for_each_vma(vmi, vma) {
2178 		if (signal_pending(current))
2179 			goto out_unlock;
2180 		if (vma->vm_file && vma->vm_file->f_mapping &&
2181 				!is_vm_hugetlb_page(vma))
2182 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
2183 	}
2184 
2185 	vma_iter_init(&vmi, mm, 0);
2186 	for_each_vma(vmi, vma) {
2187 		if (signal_pending(current))
2188 			goto out_unlock;
2189 		if (vma->anon_vma)
2190 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2191 				vm_lock_anon_vma(mm, avc->anon_vma);
2192 	}
2193 
2194 	return 0;
2195 
2196 out_unlock:
2197 	mm_drop_all_locks(mm);
2198 	return -EINTR;
2199 }
2200 
2201 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
2202 {
2203 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
2204 		/*
2205 		 * The LSB of head.next can't change to 0 from under
2206 		 * us because we hold the mm_all_locks_mutex.
2207 		 *
2208 		 * We must however clear the bitflag before unlocking
2209 		 * the vma so the users using the anon_vma->rb_root will
2210 		 * never see our bitflag.
2211 		 *
2212 		 * No need of atomic instructions here, head.next
2213 		 * can't change from under us until we release the
2214 		 * anon_vma->root->rwsem.
2215 		 */
2216 		if (!__test_and_clear_bit(0, (unsigned long *)
2217 					  &anon_vma->root->rb_root.rb_root.rb_node))
2218 			BUG();
2219 		anon_vma_unlock_write(anon_vma);
2220 	}
2221 }
2222 
2223 static void vm_unlock_mapping(struct address_space *mapping)
2224 {
2225 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2226 		/*
2227 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
2228 		 * because we hold the mm_all_locks_mutex.
2229 		 */
2230 		i_mmap_unlock_write(mapping);
2231 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
2232 					&mapping->flags))
2233 			BUG();
2234 	}
2235 }
2236 
2237 /*
2238  * The mmap_lock cannot be released by the caller until
2239  * mm_drop_all_locks() returns.
2240  */
2241 void mm_drop_all_locks(struct mm_struct *mm)
2242 {
2243 	struct vm_area_struct *vma;
2244 	struct anon_vma_chain *avc;
2245 	VMA_ITERATOR(vmi, mm, 0);
2246 
2247 	mmap_assert_write_locked(mm);
2248 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
2249 
2250 	for_each_vma(vmi, vma) {
2251 		if (vma->anon_vma)
2252 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2253 				vm_unlock_anon_vma(avc->anon_vma);
2254 		if (vma->vm_file && vma->vm_file->f_mapping)
2255 			vm_unlock_mapping(vma->vm_file->f_mapping);
2256 	}
2257 
2258 	mutex_unlock(&mm_all_locks_mutex);
2259 }
2260 
2261 /*
2262  * We account for memory if it's a private writeable mapping,
2263  * not hugepages and VM_NORESERVE wasn't set.
2264  */
2265 static bool accountable_mapping(struct file *file, vm_flags_t vm_flags)
2266 {
2267 	/*
2268 	 * hugetlb has its own accounting separate from the core VM
2269 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
2270 	 */
2271 	if (file && is_file_hugepages(file))
2272 		return false;
2273 
2274 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
2275 }
2276 
2277 /*
2278  * vms_abort_munmap_vmas() - Undo as much as possible from an aborted munmap()
2279  * operation.
2280  * @vms: The vma unmap structure
2281  * @mas_detach: The maple state with the detached maple tree
2282  *
2283  * Reattach any detached vmas, free up the maple tree used to track the vmas.
2284  * If that's not possible because the ptes are cleared (and vm_ops->closed() may
2285  * have been called), then a NULL is written over the vmas and the vmas are
2286  * removed (munmap() completed).
2287  */
2288 static void vms_abort_munmap_vmas(struct vma_munmap_struct *vms,
2289 		struct ma_state *mas_detach)
2290 {
2291 	struct ma_state *mas = &vms->vmi->mas;
2292 
2293 	if (!vms->nr_pages)
2294 		return;
2295 
2296 	if (vms->clear_ptes)
2297 		return reattach_vmas(mas_detach);
2298 
2299 	/*
2300 	 * Aborting cannot just call the vm_ops open() because they are often
2301 	 * not symmetrical and state data has been lost.  Resort to the old
2302 	 * failure method of leaving a gap where the MAP_FIXED mapping failed.
2303 	 */
2304 	mas_set_range(mas, vms->start, vms->end - 1);
2305 	mas_store_gfp(mas, NULL, GFP_KERNEL|__GFP_NOFAIL);
2306 	/* Clean up the insertion of the unfortunate gap */
2307 	vms_complete_munmap_vmas(vms, mas_detach);
2308 }
2309 
2310 /*
2311  * __mmap_prepare() - Prepare to gather any overlapping VMAs that need to be
2312  * unmapped once the map operation is completed, check limits, account mapping
2313  * and clean up any pre-existing VMAs.
2314  *
2315  * @map: Mapping state.
2316  * @uf:  Userfaultfd context list.
2317  *
2318  * Returns: 0 on success, error code otherwise.
2319  */
2320 static int __mmap_prepare(struct mmap_state *map, struct list_head *uf)
2321 {
2322 	int error;
2323 	struct vma_iterator *vmi = map->vmi;
2324 	struct vma_munmap_struct *vms = &map->vms;
2325 
2326 	/* Find the first overlapping VMA and initialise unmap state. */
2327 	vms->vma = vma_find(vmi, map->end);
2328 	init_vma_munmap(vms, vmi, vms->vma, map->addr, map->end, uf,
2329 			/* unlock = */ false);
2330 
2331 	/* OK, we have overlapping VMAs - prepare to unmap them. */
2332 	if (vms->vma) {
2333 		mt_init_flags(&map->mt_detach,
2334 			      vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
2335 		mt_on_stack(map->mt_detach);
2336 		mas_init(&map->mas_detach, &map->mt_detach, /* addr = */ 0);
2337 		/* Prepare to unmap any existing mapping in the area */
2338 		error = vms_gather_munmap_vmas(vms, &map->mas_detach);
2339 		if (error) {
2340 			/* On error VMAs will already have been reattached. */
2341 			vms->nr_pages = 0;
2342 			return error;
2343 		}
2344 
2345 		map->next = vms->next;
2346 		map->prev = vms->prev;
2347 	} else {
2348 		map->next = vma_iter_next_rewind(vmi, &map->prev);
2349 	}
2350 
2351 	/* Check against address space limit. */
2352 	if (!may_expand_vm(map->mm, map->flags, map->pglen - vms->nr_pages))
2353 		return -ENOMEM;
2354 
2355 	/* Private writable mapping: check memory availability. */
2356 	if (accountable_mapping(map->file, map->flags)) {
2357 		map->charged = map->pglen;
2358 		map->charged -= vms->nr_accounted;
2359 		if (map->charged) {
2360 			error = security_vm_enough_memory_mm(map->mm, map->charged);
2361 			if (error)
2362 				return error;
2363 		}
2364 
2365 		vms->nr_accounted = 0;
2366 		map->flags |= VM_ACCOUNT;
2367 	}
2368 
2369 	/*
2370 	 * Clear PTEs while the vma is still in the tree so that rmap
2371 	 * cannot race with the freeing later in the truncate scenario.
2372 	 * This is also needed for mmap_file(), which is why vm_ops
2373 	 * close function is called.
2374 	 */
2375 	vms_clean_up_area(vms, &map->mas_detach);
2376 
2377 	return 0;
2378 }
2379 
2380 
2381 static int __mmap_new_file_vma(struct mmap_state *map,
2382 			       struct vm_area_struct *vma)
2383 {
2384 	struct vma_iterator *vmi = map->vmi;
2385 	int error;
2386 
2387 	vma->vm_file = get_file(map->file);
2388 	error = mmap_file(vma->vm_file, vma);
2389 	if (error) {
2390 		fput(vma->vm_file);
2391 		vma->vm_file = NULL;
2392 
2393 		vma_iter_set(vmi, vma->vm_end);
2394 		/* Undo any partial mapping done by a device driver. */
2395 		unmap_region(&vmi->mas, vma, map->prev, map->next);
2396 
2397 		return error;
2398 	}
2399 
2400 	/* Drivers cannot alter the address of the VMA. */
2401 	WARN_ON_ONCE(map->addr != vma->vm_start);
2402 	/*
2403 	 * Drivers should not permit writability when previously it was
2404 	 * disallowed.
2405 	 */
2406 	VM_WARN_ON_ONCE(map->flags != vma->vm_flags &&
2407 			!(map->flags & VM_MAYWRITE) &&
2408 			(vma->vm_flags & VM_MAYWRITE));
2409 
2410 	/* If the flags change (and are mergeable), let's retry later. */
2411 	map->retry_merge = vma->vm_flags != map->flags && !(vma->vm_flags & VM_SPECIAL);
2412 	map->flags = vma->vm_flags;
2413 
2414 	return 0;
2415 }
2416 
2417 /*
2418  * __mmap_new_vma() - Allocate a new VMA for the region, as merging was not
2419  * possible.
2420  *
2421  * @map:  Mapping state.
2422  * @vmap: Output pointer for the new VMA.
2423  *
2424  * Returns: Zero on success, or an error.
2425  */
2426 static int __mmap_new_vma(struct mmap_state *map, struct vm_area_struct **vmap)
2427 {
2428 	struct vma_iterator *vmi = map->vmi;
2429 	int error = 0;
2430 	struct vm_area_struct *vma;
2431 
2432 	/*
2433 	 * Determine the object being mapped and call the appropriate
2434 	 * specific mapper. the address has already been validated, but
2435 	 * not unmapped, but the maps are removed from the list.
2436 	 */
2437 	vma = vm_area_alloc(map->mm);
2438 	if (!vma)
2439 		return -ENOMEM;
2440 
2441 	vma_iter_config(vmi, map->addr, map->end);
2442 	vma_set_range(vma, map->addr, map->end, map->pgoff);
2443 	vm_flags_init(vma, map->flags);
2444 	vma->vm_page_prot = vm_get_page_prot(map->flags);
2445 
2446 	if (vma_iter_prealloc(vmi, vma)) {
2447 		error = -ENOMEM;
2448 		goto free_vma;
2449 	}
2450 
2451 	if (map->file)
2452 		error = __mmap_new_file_vma(map, vma);
2453 	else if (map->flags & VM_SHARED)
2454 		error = shmem_zero_setup(vma);
2455 	else
2456 		vma_set_anonymous(vma);
2457 
2458 	if (error)
2459 		goto free_iter_vma;
2460 
2461 #ifdef CONFIG_SPARC64
2462 	/* TODO: Fix SPARC ADI! */
2463 	WARN_ON_ONCE(!arch_validate_flags(map->flags));
2464 #endif
2465 
2466 	/* Lock the VMA since it is modified after insertion into VMA tree */
2467 	vma_start_write(vma);
2468 	vma_iter_store_new(vmi, vma);
2469 	map->mm->map_count++;
2470 	vma_link_file(vma);
2471 
2472 	/*
2473 	 * vma_merge_new_range() calls khugepaged_enter_vma() too, the below
2474 	 * call covers the non-merge case.
2475 	 */
2476 	if (!vma_is_anonymous(vma))
2477 		khugepaged_enter_vma(vma, map->flags);
2478 	ksm_add_vma(vma);
2479 	*vmap = vma;
2480 	return 0;
2481 
2482 free_iter_vma:
2483 	vma_iter_free(vmi);
2484 free_vma:
2485 	vm_area_free(vma);
2486 	return error;
2487 }
2488 
2489 /*
2490  * __mmap_complete() - Unmap any VMAs we overlap, account memory mapping
2491  *                     statistics, handle locking and finalise the VMA.
2492  *
2493  * @map: Mapping state.
2494  * @vma: Merged or newly allocated VMA for the mmap()'d region.
2495  */
2496 static void __mmap_complete(struct mmap_state *map, struct vm_area_struct *vma)
2497 {
2498 	struct mm_struct *mm = map->mm;
2499 	unsigned long vm_flags = vma->vm_flags;
2500 
2501 	perf_event_mmap(vma);
2502 
2503 	/* Unmap any existing mapping in the area. */
2504 	vms_complete_munmap_vmas(&map->vms, &map->mas_detach);
2505 
2506 	vm_stat_account(mm, vma->vm_flags, map->pglen);
2507 	if (vm_flags & VM_LOCKED) {
2508 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2509 					is_vm_hugetlb_page(vma) ||
2510 					vma == get_gate_vma(mm))
2511 			vm_flags_clear(vma, VM_LOCKED_MASK);
2512 		else
2513 			mm->locked_vm += map->pglen;
2514 	}
2515 
2516 	if (vma->vm_file)
2517 		uprobe_mmap(vma);
2518 
2519 	/*
2520 	 * New (or expanded) vma always get soft dirty status.
2521 	 * Otherwise user-space soft-dirty page tracker won't
2522 	 * be able to distinguish situation when vma area unmapped,
2523 	 * then new mapped in-place (which must be aimed as
2524 	 * a completely new data area).
2525 	 */
2526 	vm_flags_set(vma, VM_SOFTDIRTY);
2527 
2528 	vma_set_page_prot(vma);
2529 }
2530 
2531 static unsigned long __mmap_region(struct file *file, unsigned long addr,
2532 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2533 		struct list_head *uf)
2534 {
2535 	struct mm_struct *mm = current->mm;
2536 	struct vm_area_struct *vma = NULL;
2537 	int error;
2538 	VMA_ITERATOR(vmi, mm, addr);
2539 	MMAP_STATE(map, mm, &vmi, addr, len, pgoff, vm_flags, file);
2540 
2541 	error = __mmap_prepare(&map, uf);
2542 	if (error)
2543 		goto abort_munmap;
2544 
2545 	/* Attempt to merge with adjacent VMAs... */
2546 	if (map.prev || map.next) {
2547 		VMG_MMAP_STATE(vmg, &map, /* vma = */ NULL);
2548 
2549 		vma = vma_merge_new_range(&vmg);
2550 	}
2551 
2552 	/* ...but if we can't, allocate a new VMA. */
2553 	if (!vma) {
2554 		error = __mmap_new_vma(&map, &vma);
2555 		if (error)
2556 			goto unacct_error;
2557 	}
2558 
2559 	/* If flags changed, we might be able to merge, so try again. */
2560 	if (map.retry_merge) {
2561 		struct vm_area_struct *merged;
2562 		VMG_MMAP_STATE(vmg, &map, vma);
2563 
2564 		vma_iter_config(map.vmi, map.addr, map.end);
2565 		merged = vma_merge_existing_range(&vmg);
2566 		if (merged)
2567 			vma = merged;
2568 	}
2569 
2570 	__mmap_complete(&map, vma);
2571 
2572 	return addr;
2573 
2574 	/* Accounting was done by __mmap_prepare(). */
2575 unacct_error:
2576 	if (map.charged)
2577 		vm_unacct_memory(map.charged);
2578 abort_munmap:
2579 	vms_abort_munmap_vmas(&map.vms, &map.mas_detach);
2580 	return error;
2581 }
2582 
2583 /**
2584  * mmap_region() - Actually perform the userland mapping of a VMA into
2585  * current->mm with known, aligned and overflow-checked @addr and @len, and
2586  * correctly determined VMA flags @vm_flags and page offset @pgoff.
2587  *
2588  * This is an internal memory management function, and should not be used
2589  * directly.
2590  *
2591  * The caller must write-lock current->mm->mmap_lock.
2592  *
2593  * @file: If a file-backed mapping, a pointer to the struct file describing the
2594  * file to be mapped, otherwise NULL.
2595  * @addr: The page-aligned address at which to perform the mapping.
2596  * @len: The page-aligned, non-zero, length of the mapping.
2597  * @vm_flags: The VMA flags which should be applied to the mapping.
2598  * @pgoff: If @file is specified, the page offset into the file, if not then
2599  * the virtual page offset in memory of the anonymous mapping.
2600  * @uf: Optionally, a pointer to a list head used for tracking userfaultfd unmap
2601  * events.
2602  *
2603  * Returns: Either an error, or the address at which the requested mapping has
2604  * been performed.
2605  */
2606 unsigned long mmap_region(struct file *file, unsigned long addr,
2607 			  unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2608 			  struct list_head *uf)
2609 {
2610 	unsigned long ret;
2611 	bool writable_file_mapping = false;
2612 
2613 	mmap_assert_write_locked(current->mm);
2614 
2615 	/* Check to see if MDWE is applicable. */
2616 	if (map_deny_write_exec(vm_flags, vm_flags))
2617 		return -EACCES;
2618 
2619 	/* Allow architectures to sanity-check the vm_flags. */
2620 	if (!arch_validate_flags(vm_flags))
2621 		return -EINVAL;
2622 
2623 	/* Map writable and ensure this isn't a sealed memfd. */
2624 	if (file && is_shared_maywrite(vm_flags)) {
2625 		int error = mapping_map_writable(file->f_mapping);
2626 
2627 		if (error)
2628 			return error;
2629 		writable_file_mapping = true;
2630 	}
2631 
2632 	ret = __mmap_region(file, addr, len, vm_flags, pgoff, uf);
2633 
2634 	/* Clear our write mapping regardless of error. */
2635 	if (writable_file_mapping)
2636 		mapping_unmap_writable(file->f_mapping);
2637 
2638 	validate_mm(current->mm);
2639 	return ret;
2640 }
2641 
2642 /*
2643  * do_brk_flags() - Increase the brk vma if the flags match.
2644  * @vmi: The vma iterator
2645  * @addr: The start address
2646  * @len: The length of the increase
2647  * @vma: The vma,
2648  * @flags: The VMA Flags
2649  *
2650  * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
2651  * do not match then create a new anonymous VMA.  Eventually we may be able to
2652  * do some brk-specific accounting here.
2653  */
2654 int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
2655 		 unsigned long addr, unsigned long len, unsigned long flags)
2656 {
2657 	struct mm_struct *mm = current->mm;
2658 
2659 	/*
2660 	 * Check against address space limits by the changed size
2661 	 * Note: This happens *after* clearing old mappings in some code paths.
2662 	 */
2663 	flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
2664 	if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
2665 		return -ENOMEM;
2666 
2667 	if (mm->map_count > sysctl_max_map_count)
2668 		return -ENOMEM;
2669 
2670 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
2671 		return -ENOMEM;
2672 
2673 	/*
2674 	 * Expand the existing vma if possible; Note that singular lists do not
2675 	 * occur after forking, so the expand will only happen on new VMAs.
2676 	 */
2677 	if (vma && vma->vm_end == addr) {
2678 		VMG_STATE(vmg, mm, vmi, addr, addr + len, flags, PHYS_PFN(addr));
2679 
2680 		vmg.prev = vma;
2681 		/* vmi is positioned at prev, which this mode expects. */
2682 		vmg.just_expand = true;
2683 
2684 		if (vma_merge_new_range(&vmg))
2685 			goto out;
2686 		else if (vmg_nomem(&vmg))
2687 			goto unacct_fail;
2688 	}
2689 
2690 	if (vma)
2691 		vma_iter_next_range(vmi);
2692 	/* create a vma struct for an anonymous mapping */
2693 	vma = vm_area_alloc(mm);
2694 	if (!vma)
2695 		goto unacct_fail;
2696 
2697 	vma_set_anonymous(vma);
2698 	vma_set_range(vma, addr, addr + len, addr >> PAGE_SHIFT);
2699 	vm_flags_init(vma, flags);
2700 	vma->vm_page_prot = vm_get_page_prot(flags);
2701 	vma_start_write(vma);
2702 	if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
2703 		goto mas_store_fail;
2704 
2705 	mm->map_count++;
2706 	validate_mm(mm);
2707 	ksm_add_vma(vma);
2708 out:
2709 	perf_event_mmap(vma);
2710 	mm->total_vm += len >> PAGE_SHIFT;
2711 	mm->data_vm += len >> PAGE_SHIFT;
2712 	if (flags & VM_LOCKED)
2713 		mm->locked_vm += (len >> PAGE_SHIFT);
2714 	vm_flags_set(vma, VM_SOFTDIRTY);
2715 	return 0;
2716 
2717 mas_store_fail:
2718 	vm_area_free(vma);
2719 unacct_fail:
2720 	vm_unacct_memory(len >> PAGE_SHIFT);
2721 	return -ENOMEM;
2722 }
2723 
2724 /**
2725  * unmapped_area() - Find an area between the low_limit and the high_limit with
2726  * the correct alignment and offset, all from @info. Note: current->mm is used
2727  * for the search.
2728  *
2729  * @info: The unmapped area information including the range [low_limit -
2730  * high_limit), the alignment offset and mask.
2731  *
2732  * Return: A memory address or -ENOMEM.
2733  */
2734 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
2735 {
2736 	unsigned long length, gap;
2737 	unsigned long low_limit, high_limit;
2738 	struct vm_area_struct *tmp;
2739 	VMA_ITERATOR(vmi, current->mm, 0);
2740 
2741 	/* Adjust search length to account for worst case alignment overhead */
2742 	length = info->length + info->align_mask + info->start_gap;
2743 	if (length < info->length)
2744 		return -ENOMEM;
2745 
2746 	low_limit = info->low_limit;
2747 	if (low_limit < mmap_min_addr)
2748 		low_limit = mmap_min_addr;
2749 	high_limit = info->high_limit;
2750 retry:
2751 	if (vma_iter_area_lowest(&vmi, low_limit, high_limit, length))
2752 		return -ENOMEM;
2753 
2754 	/*
2755 	 * Adjust for the gap first so it doesn't interfere with the
2756 	 * later alignment. The first step is the minimum needed to
2757 	 * fulill the start gap, the next steps is the minimum to align
2758 	 * that. It is the minimum needed to fulill both.
2759 	 */
2760 	gap = vma_iter_addr(&vmi) + info->start_gap;
2761 	gap += (info->align_offset - gap) & info->align_mask;
2762 	tmp = vma_next(&vmi);
2763 	if (tmp && (tmp->vm_flags & VM_STARTGAP_FLAGS)) { /* Avoid prev check if possible */
2764 		if (vm_start_gap(tmp) < gap + length - 1) {
2765 			low_limit = tmp->vm_end;
2766 			vma_iter_reset(&vmi);
2767 			goto retry;
2768 		}
2769 	} else {
2770 		tmp = vma_prev(&vmi);
2771 		if (tmp && vm_end_gap(tmp) > gap) {
2772 			low_limit = vm_end_gap(tmp);
2773 			vma_iter_reset(&vmi);
2774 			goto retry;
2775 		}
2776 	}
2777 
2778 	return gap;
2779 }
2780 
2781 /**
2782  * unmapped_area_topdown() - Find an area between the low_limit and the
2783  * high_limit with the correct alignment and offset at the highest available
2784  * address, all from @info. Note: current->mm is used for the search.
2785  *
2786  * @info: The unmapped area information including the range [low_limit -
2787  * high_limit), the alignment offset and mask.
2788  *
2789  * Return: A memory address or -ENOMEM.
2790  */
2791 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
2792 {
2793 	unsigned long length, gap, gap_end;
2794 	unsigned long low_limit, high_limit;
2795 	struct vm_area_struct *tmp;
2796 	VMA_ITERATOR(vmi, current->mm, 0);
2797 
2798 	/* Adjust search length to account for worst case alignment overhead */
2799 	length = info->length + info->align_mask + info->start_gap;
2800 	if (length < info->length)
2801 		return -ENOMEM;
2802 
2803 	low_limit = info->low_limit;
2804 	if (low_limit < mmap_min_addr)
2805 		low_limit = mmap_min_addr;
2806 	high_limit = info->high_limit;
2807 retry:
2808 	if (vma_iter_area_highest(&vmi, low_limit, high_limit, length))
2809 		return -ENOMEM;
2810 
2811 	gap = vma_iter_end(&vmi) - info->length;
2812 	gap -= (gap - info->align_offset) & info->align_mask;
2813 	gap_end = vma_iter_end(&vmi);
2814 	tmp = vma_next(&vmi);
2815 	if (tmp && (tmp->vm_flags & VM_STARTGAP_FLAGS)) { /* Avoid prev check if possible */
2816 		if (vm_start_gap(tmp) < gap_end) {
2817 			high_limit = vm_start_gap(tmp);
2818 			vma_iter_reset(&vmi);
2819 			goto retry;
2820 		}
2821 	} else {
2822 		tmp = vma_prev(&vmi);
2823 		if (tmp && vm_end_gap(tmp) > gap) {
2824 			high_limit = tmp->vm_start;
2825 			vma_iter_reset(&vmi);
2826 			goto retry;
2827 		}
2828 	}
2829 
2830 	return gap;
2831 }
2832 
2833 /*
2834  * Verify that the stack growth is acceptable and
2835  * update accounting. This is shared with both the
2836  * grow-up and grow-down cases.
2837  */
2838 static int acct_stack_growth(struct vm_area_struct *vma,
2839 			     unsigned long size, unsigned long grow)
2840 {
2841 	struct mm_struct *mm = vma->vm_mm;
2842 	unsigned long new_start;
2843 
2844 	/* address space limit tests */
2845 	if (!may_expand_vm(mm, vma->vm_flags, grow))
2846 		return -ENOMEM;
2847 
2848 	/* Stack limit test */
2849 	if (size > rlimit(RLIMIT_STACK))
2850 		return -ENOMEM;
2851 
2852 	/* mlock limit tests */
2853 	if (!mlock_future_ok(mm, vma->vm_flags, grow << PAGE_SHIFT))
2854 		return -ENOMEM;
2855 
2856 	/* Check to ensure the stack will not grow into a hugetlb-only region */
2857 	new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2858 			vma->vm_end - size;
2859 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2860 		return -EFAULT;
2861 
2862 	/*
2863 	 * Overcommit..  This must be the final test, as it will
2864 	 * update security statistics.
2865 	 */
2866 	if (security_vm_enough_memory_mm(mm, grow))
2867 		return -ENOMEM;
2868 
2869 	return 0;
2870 }
2871 
2872 #if defined(CONFIG_STACK_GROWSUP)
2873 /*
2874  * PA-RISC uses this for its stack.
2875  * vma is the last one with address > vma->vm_end.  Have to extend vma.
2876  */
2877 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2878 {
2879 	struct mm_struct *mm = vma->vm_mm;
2880 	struct vm_area_struct *next;
2881 	unsigned long gap_addr;
2882 	int error = 0;
2883 	VMA_ITERATOR(vmi, mm, vma->vm_start);
2884 
2885 	if (!(vma->vm_flags & VM_GROWSUP))
2886 		return -EFAULT;
2887 
2888 	mmap_assert_write_locked(mm);
2889 
2890 	/* Guard against exceeding limits of the address space. */
2891 	address &= PAGE_MASK;
2892 	if (address >= (TASK_SIZE & PAGE_MASK))
2893 		return -ENOMEM;
2894 	address += PAGE_SIZE;
2895 
2896 	/* Enforce stack_guard_gap */
2897 	gap_addr = address + stack_guard_gap;
2898 
2899 	/* Guard against overflow */
2900 	if (gap_addr < address || gap_addr > TASK_SIZE)
2901 		gap_addr = TASK_SIZE;
2902 
2903 	next = find_vma_intersection(mm, vma->vm_end, gap_addr);
2904 	if (next && vma_is_accessible(next)) {
2905 		if (!(next->vm_flags & VM_GROWSUP))
2906 			return -ENOMEM;
2907 		/* Check that both stack segments have the same anon_vma? */
2908 	}
2909 
2910 	if (next)
2911 		vma_iter_prev_range_limit(&vmi, address);
2912 
2913 	vma_iter_config(&vmi, vma->vm_start, address);
2914 	if (vma_iter_prealloc(&vmi, vma))
2915 		return -ENOMEM;
2916 
2917 	/* We must make sure the anon_vma is allocated. */
2918 	if (unlikely(anon_vma_prepare(vma))) {
2919 		vma_iter_free(&vmi);
2920 		return -ENOMEM;
2921 	}
2922 
2923 	/* Lock the VMA before expanding to prevent concurrent page faults */
2924 	vma_start_write(vma);
2925 	/* We update the anon VMA tree. */
2926 	anon_vma_lock_write(vma->anon_vma);
2927 
2928 	/* Somebody else might have raced and expanded it already */
2929 	if (address > vma->vm_end) {
2930 		unsigned long size, grow;
2931 
2932 		size = address - vma->vm_start;
2933 		grow = (address - vma->vm_end) >> PAGE_SHIFT;
2934 
2935 		error = -ENOMEM;
2936 		if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2937 			error = acct_stack_growth(vma, size, grow);
2938 			if (!error) {
2939 				if (vma->vm_flags & VM_LOCKED)
2940 					mm->locked_vm += grow;
2941 				vm_stat_account(mm, vma->vm_flags, grow);
2942 				anon_vma_interval_tree_pre_update_vma(vma);
2943 				vma->vm_end = address;
2944 				/* Overwrite old entry in mtree. */
2945 				vma_iter_store_overwrite(&vmi, vma);
2946 				anon_vma_interval_tree_post_update_vma(vma);
2947 
2948 				perf_event_mmap(vma);
2949 			}
2950 		}
2951 	}
2952 	anon_vma_unlock_write(vma->anon_vma);
2953 	vma_iter_free(&vmi);
2954 	validate_mm(mm);
2955 	return error;
2956 }
2957 #endif /* CONFIG_STACK_GROWSUP */
2958 
2959 /*
2960  * vma is the first one with address < vma->vm_start.  Have to extend vma.
2961  * mmap_lock held for writing.
2962  */
2963 int expand_downwards(struct vm_area_struct *vma, unsigned long address)
2964 {
2965 	struct mm_struct *mm = vma->vm_mm;
2966 	struct vm_area_struct *prev;
2967 	int error = 0;
2968 	VMA_ITERATOR(vmi, mm, vma->vm_start);
2969 
2970 	if (!(vma->vm_flags & VM_GROWSDOWN))
2971 		return -EFAULT;
2972 
2973 	mmap_assert_write_locked(mm);
2974 
2975 	address &= PAGE_MASK;
2976 	if (address < mmap_min_addr || address < FIRST_USER_ADDRESS)
2977 		return -EPERM;
2978 
2979 	/* Enforce stack_guard_gap */
2980 	prev = vma_prev(&vmi);
2981 	/* Check that both stack segments have the same anon_vma? */
2982 	if (prev) {
2983 		if (!(prev->vm_flags & VM_GROWSDOWN) &&
2984 		    vma_is_accessible(prev) &&
2985 		    (address - prev->vm_end < stack_guard_gap))
2986 			return -ENOMEM;
2987 	}
2988 
2989 	if (prev)
2990 		vma_iter_next_range_limit(&vmi, vma->vm_start);
2991 
2992 	vma_iter_config(&vmi, address, vma->vm_end);
2993 	if (vma_iter_prealloc(&vmi, vma))
2994 		return -ENOMEM;
2995 
2996 	/* We must make sure the anon_vma is allocated. */
2997 	if (unlikely(anon_vma_prepare(vma))) {
2998 		vma_iter_free(&vmi);
2999 		return -ENOMEM;
3000 	}
3001 
3002 	/* Lock the VMA before expanding to prevent concurrent page faults */
3003 	vma_start_write(vma);
3004 	/* We update the anon VMA tree. */
3005 	anon_vma_lock_write(vma->anon_vma);
3006 
3007 	/* Somebody else might have raced and expanded it already */
3008 	if (address < vma->vm_start) {
3009 		unsigned long size, grow;
3010 
3011 		size = vma->vm_end - address;
3012 		grow = (vma->vm_start - address) >> PAGE_SHIFT;
3013 
3014 		error = -ENOMEM;
3015 		if (grow <= vma->vm_pgoff) {
3016 			error = acct_stack_growth(vma, size, grow);
3017 			if (!error) {
3018 				if (vma->vm_flags & VM_LOCKED)
3019 					mm->locked_vm += grow;
3020 				vm_stat_account(mm, vma->vm_flags, grow);
3021 				anon_vma_interval_tree_pre_update_vma(vma);
3022 				vma->vm_start = address;
3023 				vma->vm_pgoff -= grow;
3024 				/* Overwrite old entry in mtree. */
3025 				vma_iter_store_overwrite(&vmi, vma);
3026 				anon_vma_interval_tree_post_update_vma(vma);
3027 
3028 				perf_event_mmap(vma);
3029 			}
3030 		}
3031 	}
3032 	anon_vma_unlock_write(vma->anon_vma);
3033 	vma_iter_free(&vmi);
3034 	validate_mm(mm);
3035 	return error;
3036 }
3037 
3038 int __vm_munmap(unsigned long start, size_t len, bool unlock)
3039 {
3040 	int ret;
3041 	struct mm_struct *mm = current->mm;
3042 	LIST_HEAD(uf);
3043 	VMA_ITERATOR(vmi, mm, start);
3044 
3045 	if (mmap_write_lock_killable(mm))
3046 		return -EINTR;
3047 
3048 	ret = do_vmi_munmap(&vmi, mm, start, len, &uf, unlock);
3049 	if (ret || !unlock)
3050 		mmap_write_unlock(mm);
3051 
3052 	userfaultfd_unmap_complete(mm, &uf);
3053 	return ret;
3054 }
3055