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