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