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