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