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