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