xref: /linux/mm/vma.c (revision 3e01310d29a700b99067cb0d6ba21284f2389308)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 /*
4  * VMA-specific functions.
5  */
6 
7 #include "vma_internal.h"
8 #include "vma.h"
9 
10 static inline bool is_mergeable_vma(struct vma_merge_struct *vmg, bool merge_next)
11 {
12 	struct vm_area_struct *vma = merge_next ? vmg->next : vmg->prev;
13 	/*
14 	 * If the vma has a ->close operation then the driver probably needs to
15 	 * release per-vma resources, so we don't attempt to merge those if the
16 	 * caller indicates the current vma may be removed as part of the merge,
17 	 * which is the case if we are attempting to merge the next VMA into
18 	 * this one.
19 	 */
20 	bool may_remove_vma = merge_next;
21 
22 	if (!mpol_equal(vmg->policy, vma_policy(vma)))
23 		return false;
24 	/*
25 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
26 	 * match the flags but dirty bit -- the caller should mark
27 	 * merged VMA as dirty. If dirty bit won't be excluded from
28 	 * comparison, we increase pressure on the memory system forcing
29 	 * the kernel to generate new VMAs when old one could be
30 	 * extended instead.
31 	 */
32 	if ((vma->vm_flags ^ vmg->flags) & ~VM_SOFTDIRTY)
33 		return false;
34 	if (vma->vm_file != vmg->file)
35 		return false;
36 	if (may_remove_vma && vma->vm_ops && vma->vm_ops->close)
37 		return false;
38 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vmg->uffd_ctx))
39 		return false;
40 	if (!anon_vma_name_eq(anon_vma_name(vma), vmg->anon_name))
41 		return false;
42 	return true;
43 }
44 
45 static inline bool is_mergeable_anon_vma(struct anon_vma *anon_vma1,
46 		 struct anon_vma *anon_vma2, struct vm_area_struct *vma)
47 {
48 	/*
49 	 * The list_is_singular() test is to avoid merging VMA cloned from
50 	 * parents. This can improve scalability caused by anon_vma lock.
51 	 */
52 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
53 		list_is_singular(&vma->anon_vma_chain)))
54 		return true;
55 	return anon_vma1 == anon_vma2;
56 }
57 
58 /*
59  * init_multi_vma_prep() - Initializer for struct vma_prepare
60  * @vp: The vma_prepare struct
61  * @vma: The vma that will be altered once locked
62  * @next: The next vma if it is to be adjusted
63  * @remove: The first vma to be removed
64  * @remove2: The second vma to be removed
65  */
66 static void init_multi_vma_prep(struct vma_prepare *vp,
67 				struct vm_area_struct *vma,
68 				struct vm_area_struct *next,
69 				struct vm_area_struct *remove,
70 				struct vm_area_struct *remove2)
71 {
72 	memset(vp, 0, sizeof(struct vma_prepare));
73 	vp->vma = vma;
74 	vp->anon_vma = vma->anon_vma;
75 	vp->remove = remove;
76 	vp->remove2 = remove2;
77 	vp->adj_next = next;
78 	if (!vp->anon_vma && next)
79 		vp->anon_vma = next->anon_vma;
80 
81 	vp->file = vma->vm_file;
82 	if (vp->file)
83 		vp->mapping = vma->vm_file->f_mapping;
84 
85 }
86 
87 /*
88  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
89  * in front of (at a lower virtual address and file offset than) the vma.
90  *
91  * We cannot merge two vmas if they have differently assigned (non-NULL)
92  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
93  *
94  * We don't check here for the merged mmap wrapping around the end of pagecache
95  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
96  * wrap, nor mmaps which cover the final page at index -1UL.
97  *
98  * We assume the vma may be removed as part of the merge.
99  */
100 bool
101 can_vma_merge_before(struct vma_merge_struct *vmg)
102 {
103 	pgoff_t pglen = PHYS_PFN(vmg->end - vmg->start);
104 
105 	if (is_mergeable_vma(vmg, /* merge_next = */ true) &&
106 	    is_mergeable_anon_vma(vmg->anon_vma, vmg->next->anon_vma, vmg->next)) {
107 		if (vmg->next->vm_pgoff == vmg->pgoff + pglen)
108 			return true;
109 	}
110 
111 	return false;
112 }
113 
114 /*
115  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
116  * beyond (at a higher virtual address and file offset than) the vma.
117  *
118  * We cannot merge two vmas if they have differently assigned (non-NULL)
119  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
120  *
121  * We assume that vma is not removed as part of the merge.
122  */
123 bool can_vma_merge_after(struct vma_merge_struct *vmg)
124 {
125 	if (is_mergeable_vma(vmg, /* merge_next = */ false) &&
126 	    is_mergeable_anon_vma(vmg->anon_vma, vmg->prev->anon_vma, vmg->prev)) {
127 		if (vmg->prev->vm_pgoff + vma_pages(vmg->prev) == vmg->pgoff)
128 			return true;
129 	}
130 	return false;
131 }
132 
133 /*
134  * Close a vm structure and free it.
135  */
136 void remove_vma(struct vm_area_struct *vma, bool unreachable, bool closed)
137 {
138 	might_sleep();
139 	if (!closed && vma->vm_ops && vma->vm_ops->close)
140 		vma->vm_ops->close(vma);
141 	if (vma->vm_file)
142 		fput(vma->vm_file);
143 	mpol_put(vma_policy(vma));
144 	if (unreachable)
145 		__vm_area_free(vma);
146 	else
147 		vm_area_free(vma);
148 }
149 
150 /*
151  * Get rid of page table information in the indicated region.
152  *
153  * Called with the mm semaphore held.
154  */
155 void unmap_region(struct ma_state *mas, struct vm_area_struct *vma,
156 		struct vm_area_struct *prev, struct vm_area_struct *next)
157 {
158 	struct mm_struct *mm = vma->vm_mm;
159 	struct mmu_gather tlb;
160 
161 	lru_add_drain();
162 	tlb_gather_mmu(&tlb, mm);
163 	update_hiwater_rss(mm);
164 	unmap_vmas(&tlb, mas, vma, vma->vm_start, vma->vm_end, vma->vm_end,
165 		   /* mm_wr_locked = */ true);
166 	mas_set(mas, vma->vm_end);
167 	free_pgtables(&tlb, mas, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
168 		      next ? next->vm_start : USER_PGTABLES_CEILING,
169 		      /* mm_wr_locked = */ true);
170 	tlb_finish_mmu(&tlb);
171 }
172 
173 /*
174  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
175  * has already been checked or doesn't make sense to fail.
176  * VMA Iterator will point to the original VMA.
177  */
178 static int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
179 		       unsigned long addr, int new_below)
180 {
181 	struct vma_prepare vp;
182 	struct vm_area_struct *new;
183 	int err;
184 
185 	WARN_ON(vma->vm_start >= addr);
186 	WARN_ON(vma->vm_end <= addr);
187 
188 	if (vma->vm_ops && vma->vm_ops->may_split) {
189 		err = vma->vm_ops->may_split(vma, addr);
190 		if (err)
191 			return err;
192 	}
193 
194 	new = vm_area_dup(vma);
195 	if (!new)
196 		return -ENOMEM;
197 
198 	if (new_below) {
199 		new->vm_end = addr;
200 	} else {
201 		new->vm_start = addr;
202 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
203 	}
204 
205 	err = -ENOMEM;
206 	vma_iter_config(vmi, new->vm_start, new->vm_end);
207 	if (vma_iter_prealloc(vmi, new))
208 		goto out_free_vma;
209 
210 	err = vma_dup_policy(vma, new);
211 	if (err)
212 		goto out_free_vmi;
213 
214 	err = anon_vma_clone(new, vma);
215 	if (err)
216 		goto out_free_mpol;
217 
218 	if (new->vm_file)
219 		get_file(new->vm_file);
220 
221 	if (new->vm_ops && new->vm_ops->open)
222 		new->vm_ops->open(new);
223 
224 	vma_start_write(vma);
225 	vma_start_write(new);
226 
227 	init_vma_prep(&vp, vma);
228 	vp.insert = new;
229 	vma_prepare(&vp);
230 	vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
231 
232 	if (new_below) {
233 		vma->vm_start = addr;
234 		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
235 	} else {
236 		vma->vm_end = addr;
237 	}
238 
239 	/* vma_complete stores the new vma */
240 	vma_complete(&vp, vmi, vma->vm_mm);
241 	validate_mm(vma->vm_mm);
242 
243 	/* Success. */
244 	if (new_below)
245 		vma_next(vmi);
246 	else
247 		vma_prev(vmi);
248 
249 	return 0;
250 
251 out_free_mpol:
252 	mpol_put(vma_policy(new));
253 out_free_vmi:
254 	vma_iter_free(vmi);
255 out_free_vma:
256 	vm_area_free(new);
257 	return err;
258 }
259 
260 /*
261  * Split a vma into two pieces at address 'addr', a new vma is allocated
262  * either for the first part or the tail.
263  */
264 static int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
265 		     unsigned long addr, int new_below)
266 {
267 	if (vma->vm_mm->map_count >= sysctl_max_map_count)
268 		return -ENOMEM;
269 
270 	return __split_vma(vmi, vma, addr, new_below);
271 }
272 
273 /*
274  * init_vma_prep() - Initializer wrapper for vma_prepare struct
275  * @vp: The vma_prepare struct
276  * @vma: The vma that will be altered once locked
277  */
278 void init_vma_prep(struct vma_prepare *vp,
279 		   struct vm_area_struct *vma)
280 {
281 	init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
282 }
283 
284 /*
285  * Requires inode->i_mapping->i_mmap_rwsem
286  */
287 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
288 				      struct address_space *mapping)
289 {
290 	if (vma_is_shared_maywrite(vma))
291 		mapping_unmap_writable(mapping);
292 
293 	flush_dcache_mmap_lock(mapping);
294 	vma_interval_tree_remove(vma, &mapping->i_mmap);
295 	flush_dcache_mmap_unlock(mapping);
296 }
297 
298 /*
299  * vma has some anon_vma assigned, and is already inserted on that
300  * anon_vma's interval trees.
301  *
302  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
303  * vma must be removed from the anon_vma's interval trees using
304  * anon_vma_interval_tree_pre_update_vma().
305  *
306  * After the update, the vma will be reinserted using
307  * anon_vma_interval_tree_post_update_vma().
308  *
309  * The entire update must be protected by exclusive mmap_lock and by
310  * the root anon_vma's mutex.
311  */
312 void
313 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
314 {
315 	struct anon_vma_chain *avc;
316 
317 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
318 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
319 }
320 
321 void
322 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
323 {
324 	struct anon_vma_chain *avc;
325 
326 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
327 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
328 }
329 
330 static void __vma_link_file(struct vm_area_struct *vma,
331 			    struct address_space *mapping)
332 {
333 	if (vma_is_shared_maywrite(vma))
334 		mapping_allow_writable(mapping);
335 
336 	flush_dcache_mmap_lock(mapping);
337 	vma_interval_tree_insert(vma, &mapping->i_mmap);
338 	flush_dcache_mmap_unlock(mapping);
339 }
340 
341 /*
342  * vma_prepare() - Helper function for handling locking VMAs prior to altering
343  * @vp: The initialized vma_prepare struct
344  */
345 void vma_prepare(struct vma_prepare *vp)
346 {
347 	if (vp->file) {
348 		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
349 
350 		if (vp->adj_next)
351 			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
352 				      vp->adj_next->vm_end);
353 
354 		i_mmap_lock_write(vp->mapping);
355 		if (vp->insert && vp->insert->vm_file) {
356 			/*
357 			 * Put into interval tree now, so instantiated pages
358 			 * are visible to arm/parisc __flush_dcache_page
359 			 * throughout; but we cannot insert into address
360 			 * space until vma start or end is updated.
361 			 */
362 			__vma_link_file(vp->insert,
363 					vp->insert->vm_file->f_mapping);
364 		}
365 	}
366 
367 	if (vp->anon_vma) {
368 		anon_vma_lock_write(vp->anon_vma);
369 		anon_vma_interval_tree_pre_update_vma(vp->vma);
370 		if (vp->adj_next)
371 			anon_vma_interval_tree_pre_update_vma(vp->adj_next);
372 	}
373 
374 	if (vp->file) {
375 		flush_dcache_mmap_lock(vp->mapping);
376 		vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
377 		if (vp->adj_next)
378 			vma_interval_tree_remove(vp->adj_next,
379 						 &vp->mapping->i_mmap);
380 	}
381 
382 }
383 
384 /*
385  * dup_anon_vma() - Helper function to duplicate anon_vma
386  * @dst: The destination VMA
387  * @src: The source VMA
388  * @dup: Pointer to the destination VMA when successful.
389  *
390  * Returns: 0 on success.
391  */
392 static int dup_anon_vma(struct vm_area_struct *dst,
393 			struct vm_area_struct *src, struct vm_area_struct **dup)
394 {
395 	/*
396 	 * Easily overlooked: when mprotect shifts the boundary, make sure the
397 	 * expanding vma has anon_vma set if the shrinking vma had, to cover any
398 	 * anon pages imported.
399 	 */
400 	if (src->anon_vma && !dst->anon_vma) {
401 		int ret;
402 
403 		vma_assert_write_locked(dst);
404 		dst->anon_vma = src->anon_vma;
405 		ret = anon_vma_clone(dst, src);
406 		if (ret)
407 			return ret;
408 
409 		*dup = dst;
410 	}
411 
412 	return 0;
413 }
414 
415 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
416 void validate_mm(struct mm_struct *mm)
417 {
418 	int bug = 0;
419 	int i = 0;
420 	struct vm_area_struct *vma;
421 	VMA_ITERATOR(vmi, mm, 0);
422 
423 	mt_validate(&mm->mm_mt);
424 	for_each_vma(vmi, vma) {
425 #ifdef CONFIG_DEBUG_VM_RB
426 		struct anon_vma *anon_vma = vma->anon_vma;
427 		struct anon_vma_chain *avc;
428 #endif
429 		unsigned long vmi_start, vmi_end;
430 		bool warn = 0;
431 
432 		vmi_start = vma_iter_addr(&vmi);
433 		vmi_end = vma_iter_end(&vmi);
434 		if (VM_WARN_ON_ONCE_MM(vma->vm_end != vmi_end, mm))
435 			warn = 1;
436 
437 		if (VM_WARN_ON_ONCE_MM(vma->vm_start != vmi_start, mm))
438 			warn = 1;
439 
440 		if (warn) {
441 			pr_emerg("issue in %s\n", current->comm);
442 			dump_stack();
443 			dump_vma(vma);
444 			pr_emerg("tree range: %px start %lx end %lx\n", vma,
445 				 vmi_start, vmi_end - 1);
446 			vma_iter_dump_tree(&vmi);
447 		}
448 
449 #ifdef CONFIG_DEBUG_VM_RB
450 		if (anon_vma) {
451 			anon_vma_lock_read(anon_vma);
452 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
453 				anon_vma_interval_tree_verify(avc);
454 			anon_vma_unlock_read(anon_vma);
455 		}
456 #endif
457 		i++;
458 	}
459 	if (i != mm->map_count) {
460 		pr_emerg("map_count %d vma iterator %d\n", mm->map_count, i);
461 		bug = 1;
462 	}
463 	VM_BUG_ON_MM(bug, mm);
464 }
465 #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
466 
467 /*
468  * vma_expand - Expand an existing VMA
469  *
470  * @vmi: The vma iterator
471  * @vma: The vma to expand
472  * @start: The start of the vma
473  * @end: The exclusive end of the vma
474  * @pgoff: The page offset of vma
475  * @next: The current of next vma.
476  *
477  * Expand @vma to @start and @end.  Can expand off the start and end.  Will
478  * expand over @next if it's different from @vma and @end == @next->vm_end.
479  * Checking if the @vma can expand and merge with @next needs to be handled by
480  * the caller.
481  *
482  * Returns: 0 on success
483  */
484 int vma_expand(struct vma_iterator *vmi, struct vm_area_struct *vma,
485 	       unsigned long start, unsigned long end, pgoff_t pgoff,
486 	       struct vm_area_struct *next)
487 {
488 	struct vm_area_struct *anon_dup = NULL;
489 	bool remove_next = false;
490 	struct vma_prepare vp;
491 
492 	vma_start_write(vma);
493 	if (next && (vma != next) && (end == next->vm_end)) {
494 		int ret;
495 
496 		remove_next = true;
497 		vma_start_write(next);
498 		ret = dup_anon_vma(vma, next, &anon_dup);
499 		if (ret)
500 			return ret;
501 	}
502 
503 	init_multi_vma_prep(&vp, vma, NULL, remove_next ? next : NULL, NULL);
504 	/* Not merging but overwriting any part of next is not handled. */
505 	VM_WARN_ON(next && !vp.remove &&
506 		  next != vma && end > next->vm_start);
507 	/* Only handles expanding */
508 	VM_WARN_ON(vma->vm_start < start || vma->vm_end > end);
509 
510 	/* Note: vma iterator must be pointing to 'start' */
511 	vma_iter_config(vmi, start, end);
512 	if (vma_iter_prealloc(vmi, vma))
513 		goto nomem;
514 
515 	vma_prepare(&vp);
516 	vma_adjust_trans_huge(vma, start, end, 0);
517 	vma_set_range(vma, start, end, pgoff);
518 	vma_iter_store(vmi, vma);
519 
520 	vma_complete(&vp, vmi, vma->vm_mm);
521 	return 0;
522 
523 nomem:
524 	if (anon_dup)
525 		unlink_anon_vmas(anon_dup);
526 	return -ENOMEM;
527 }
528 
529 /*
530  * vma_shrink() - Reduce an existing VMAs memory area
531  * @vmi: The vma iterator
532  * @vma: The VMA to modify
533  * @start: The new start
534  * @end: The new end
535  *
536  * Returns: 0 on success, -ENOMEM otherwise
537  */
538 int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
539 	       unsigned long start, unsigned long end, pgoff_t pgoff)
540 {
541 	struct vma_prepare vp;
542 
543 	WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
544 
545 	if (vma->vm_start < start)
546 		vma_iter_config(vmi, vma->vm_start, start);
547 	else
548 		vma_iter_config(vmi, end, vma->vm_end);
549 
550 	if (vma_iter_prealloc(vmi, NULL))
551 		return -ENOMEM;
552 
553 	vma_start_write(vma);
554 
555 	init_vma_prep(&vp, vma);
556 	vma_prepare(&vp);
557 	vma_adjust_trans_huge(vma, start, end, 0);
558 
559 	vma_iter_clear(vmi);
560 	vma_set_range(vma, start, end, pgoff);
561 	vma_complete(&vp, vmi, vma->vm_mm);
562 	validate_mm(vma->vm_mm);
563 	return 0;
564 }
565 
566 /*
567  * vma_complete- Helper function for handling the unlocking after altering VMAs,
568  * or for inserting a VMA.
569  *
570  * @vp: The vma_prepare struct
571  * @vmi: The vma iterator
572  * @mm: The mm_struct
573  */
574 void vma_complete(struct vma_prepare *vp,
575 		  struct vma_iterator *vmi, struct mm_struct *mm)
576 {
577 	if (vp->file) {
578 		if (vp->adj_next)
579 			vma_interval_tree_insert(vp->adj_next,
580 						 &vp->mapping->i_mmap);
581 		vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
582 		flush_dcache_mmap_unlock(vp->mapping);
583 	}
584 
585 	if (vp->remove && vp->file) {
586 		__remove_shared_vm_struct(vp->remove, vp->mapping);
587 		if (vp->remove2)
588 			__remove_shared_vm_struct(vp->remove2, vp->mapping);
589 	} else if (vp->insert) {
590 		/*
591 		 * split_vma has split insert from vma, and needs
592 		 * us to insert it before dropping the locks
593 		 * (it may either follow vma or precede it).
594 		 */
595 		vma_iter_store(vmi, vp->insert);
596 		mm->map_count++;
597 	}
598 
599 	if (vp->anon_vma) {
600 		anon_vma_interval_tree_post_update_vma(vp->vma);
601 		if (vp->adj_next)
602 			anon_vma_interval_tree_post_update_vma(vp->adj_next);
603 		anon_vma_unlock_write(vp->anon_vma);
604 	}
605 
606 	if (vp->file) {
607 		i_mmap_unlock_write(vp->mapping);
608 		uprobe_mmap(vp->vma);
609 
610 		if (vp->adj_next)
611 			uprobe_mmap(vp->adj_next);
612 	}
613 
614 	if (vp->remove) {
615 again:
616 		vma_mark_detached(vp->remove, true);
617 		if (vp->file) {
618 			uprobe_munmap(vp->remove, vp->remove->vm_start,
619 				      vp->remove->vm_end);
620 			fput(vp->file);
621 		}
622 		if (vp->remove->anon_vma)
623 			anon_vma_merge(vp->vma, vp->remove);
624 		mm->map_count--;
625 		mpol_put(vma_policy(vp->remove));
626 		if (!vp->remove2)
627 			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
628 		vm_area_free(vp->remove);
629 
630 		/*
631 		 * In mprotect's case 6 (see comments on vma_merge),
632 		 * we are removing both mid and next vmas
633 		 */
634 		if (vp->remove2) {
635 			vp->remove = vp->remove2;
636 			vp->remove2 = NULL;
637 			goto again;
638 		}
639 	}
640 	if (vp->insert && vp->file)
641 		uprobe_mmap(vp->insert);
642 }
643 
644 static inline void vms_clear_ptes(struct vma_munmap_struct *vms,
645 		    struct ma_state *mas_detach, bool mm_wr_locked)
646 {
647 	struct mmu_gather tlb;
648 
649 	if (!vms->clear_ptes) /* Nothing to do */
650 		return;
651 
652 	/*
653 	 * We can free page tables without write-locking mmap_lock because VMAs
654 	 * were isolated before we downgraded mmap_lock.
655 	 */
656 	mas_set(mas_detach, 1);
657 	lru_add_drain();
658 	tlb_gather_mmu(&tlb, vms->vma->vm_mm);
659 	update_hiwater_rss(vms->vma->vm_mm);
660 	unmap_vmas(&tlb, mas_detach, vms->vma, vms->start, vms->end,
661 		   vms->vma_count, mm_wr_locked);
662 
663 	mas_set(mas_detach, 1);
664 	/* start and end may be different if there is no prev or next vma. */
665 	free_pgtables(&tlb, mas_detach, vms->vma, vms->unmap_start,
666 		      vms->unmap_end, mm_wr_locked);
667 	tlb_finish_mmu(&tlb);
668 	vms->clear_ptes = false;
669 }
670 
671 void vms_clean_up_area(struct vma_munmap_struct *vms,
672 		struct ma_state *mas_detach)
673 {
674 	struct vm_area_struct *vma;
675 
676 	if (!vms->nr_pages)
677 		return;
678 
679 	vms_clear_ptes(vms, mas_detach, true);
680 	mas_set(mas_detach, 0);
681 	mas_for_each(mas_detach, vma, ULONG_MAX)
682 		if (vma->vm_ops && vma->vm_ops->close)
683 			vma->vm_ops->close(vma);
684 	vms->closed_vm_ops = true;
685 }
686 
687 /*
688  * vms_complete_munmap_vmas() - Finish the munmap() operation
689  * @vms: The vma munmap struct
690  * @mas_detach: The maple state of the detached vmas
691  *
692  * This updates the mm_struct, unmaps the region, frees the resources
693  * used for the munmap() and may downgrade the lock - if requested.  Everything
694  * needed to be done once the vma maple tree is updated.
695  */
696 void vms_complete_munmap_vmas(struct vma_munmap_struct *vms,
697 		struct ma_state *mas_detach)
698 {
699 	struct vm_area_struct *vma;
700 	struct mm_struct *mm;
701 
702 	mm = current->mm;
703 	mm->map_count -= vms->vma_count;
704 	mm->locked_vm -= vms->locked_vm;
705 	if (vms->unlock)
706 		mmap_write_downgrade(mm);
707 
708 	if (!vms->nr_pages)
709 		return;
710 
711 	vms_clear_ptes(vms, mas_detach, !vms->unlock);
712 	/* Update high watermark before we lower total_vm */
713 	update_hiwater_vm(mm);
714 	/* Stat accounting */
715 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm) - vms->nr_pages);
716 	/* Paranoid bookkeeping */
717 	VM_WARN_ON(vms->exec_vm > mm->exec_vm);
718 	VM_WARN_ON(vms->stack_vm > mm->stack_vm);
719 	VM_WARN_ON(vms->data_vm > mm->data_vm);
720 	mm->exec_vm -= vms->exec_vm;
721 	mm->stack_vm -= vms->stack_vm;
722 	mm->data_vm -= vms->data_vm;
723 
724 	/* Remove and clean up vmas */
725 	mas_set(mas_detach, 0);
726 	mas_for_each(mas_detach, vma, ULONG_MAX)
727 		remove_vma(vma, /* = */ false, vms->closed_vm_ops);
728 
729 	vm_unacct_memory(vms->nr_accounted);
730 	validate_mm(mm);
731 	if (vms->unlock)
732 		mmap_read_unlock(mm);
733 
734 	__mt_destroy(mas_detach->tree);
735 }
736 
737 /*
738  * vms_gather_munmap_vmas() - Put all VMAs within a range into a maple tree
739  * for removal at a later date.  Handles splitting first and last if necessary
740  * and marking the vmas as isolated.
741  *
742  * @vms: The vma munmap struct
743  * @mas_detach: The maple state tracking the detached tree
744  *
745  * Return: 0 on success, -EPERM on mseal vmas, -ENOMEM otherwise
746  */
747 int vms_gather_munmap_vmas(struct vma_munmap_struct *vms,
748 		struct ma_state *mas_detach)
749 {
750 	struct vm_area_struct *next = NULL;
751 	int error = -ENOMEM;
752 
753 	/*
754 	 * If we need to split any vma, do it now to save pain later.
755 	 * Does it split the first one?
756 	 */
757 	if (vms->start > vms->vma->vm_start) {
758 
759 		/*
760 		 * Make sure that map_count on return from munmap() will
761 		 * not exceed its limit; but let map_count go just above
762 		 * its limit temporarily, to help free resources as expected.
763 		 */
764 		if (vms->end < vms->vma->vm_end &&
765 		    vms->vma->vm_mm->map_count >= sysctl_max_map_count)
766 			goto map_count_exceeded;
767 
768 		/* Don't bother splitting the VMA if we can't unmap it anyway */
769 		if (!can_modify_vma(vms->vma)) {
770 			error = -EPERM;
771 			goto start_split_failed;
772 		}
773 
774 		if (__split_vma(vms->vmi, vms->vma, vms->start, 1))
775 			goto start_split_failed;
776 	}
777 	vms->prev = vma_prev(vms->vmi);
778 	if (vms->prev)
779 		vms->unmap_start = vms->prev->vm_end;
780 
781 	/*
782 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
783 	 * it is always overwritten.
784 	 */
785 	for_each_vma_range(*(vms->vmi), next, vms->end) {
786 		long nrpages;
787 
788 		if (!can_modify_vma(next)) {
789 			error = -EPERM;
790 			goto modify_vma_failed;
791 		}
792 		/* Does it split the end? */
793 		if (next->vm_end > vms->end) {
794 			if (__split_vma(vms->vmi, next, vms->end, 0))
795 				goto end_split_failed;
796 		}
797 		vma_start_write(next);
798 		mas_set(mas_detach, vms->vma_count++);
799 		if (mas_store_gfp(mas_detach, next, GFP_KERNEL))
800 			goto munmap_gather_failed;
801 
802 		vma_mark_detached(next, true);
803 		nrpages = vma_pages(next);
804 
805 		vms->nr_pages += nrpages;
806 		if (next->vm_flags & VM_LOCKED)
807 			vms->locked_vm += nrpages;
808 
809 		if (next->vm_flags & VM_ACCOUNT)
810 			vms->nr_accounted += nrpages;
811 
812 		if (is_exec_mapping(next->vm_flags))
813 			vms->exec_vm += nrpages;
814 		else if (is_stack_mapping(next->vm_flags))
815 			vms->stack_vm += nrpages;
816 		else if (is_data_mapping(next->vm_flags))
817 			vms->data_vm += nrpages;
818 
819 		if (unlikely(vms->uf)) {
820 			/*
821 			 * If userfaultfd_unmap_prep returns an error the vmas
822 			 * will remain split, but userland will get a
823 			 * highly unexpected error anyway. This is no
824 			 * different than the case where the first of the two
825 			 * __split_vma fails, but we don't undo the first
826 			 * split, despite we could. This is unlikely enough
827 			 * failure that it's not worth optimizing it for.
828 			 */
829 			if (userfaultfd_unmap_prep(next, vms->start, vms->end,
830 						   vms->uf))
831 				goto userfaultfd_error;
832 		}
833 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
834 		BUG_ON(next->vm_start < vms->start);
835 		BUG_ON(next->vm_start > vms->end);
836 #endif
837 	}
838 
839 	vms->next = vma_next(vms->vmi);
840 	if (vms->next)
841 		vms->unmap_end = vms->next->vm_start;
842 
843 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
844 	/* Make sure no VMAs are about to be lost. */
845 	{
846 		MA_STATE(test, mas_detach->tree, 0, 0);
847 		struct vm_area_struct *vma_mas, *vma_test;
848 		int test_count = 0;
849 
850 		vma_iter_set(vms->vmi, vms->start);
851 		rcu_read_lock();
852 		vma_test = mas_find(&test, vms->vma_count - 1);
853 		for_each_vma_range(*(vms->vmi), vma_mas, vms->end) {
854 			BUG_ON(vma_mas != vma_test);
855 			test_count++;
856 			vma_test = mas_next(&test, vms->vma_count - 1);
857 		}
858 		rcu_read_unlock();
859 		BUG_ON(vms->vma_count != test_count);
860 	}
861 #endif
862 
863 	while (vma_iter_addr(vms->vmi) > vms->start)
864 		vma_iter_prev_range(vms->vmi);
865 
866 	vms->clear_ptes = true;
867 	return 0;
868 
869 userfaultfd_error:
870 munmap_gather_failed:
871 end_split_failed:
872 modify_vma_failed:
873 	reattach_vmas(mas_detach);
874 start_split_failed:
875 map_count_exceeded:
876 	return error;
877 }
878 
879 /*
880  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
881  * @vmi: The vma iterator
882  * @vma: The starting vm_area_struct
883  * @mm: The mm_struct
884  * @start: The aligned start address to munmap.
885  * @end: The aligned end address to munmap.
886  * @uf: The userfaultfd list_head
887  * @unlock: Set to true to drop the mmap_lock.  unlocking only happens on
888  * success.
889  *
890  * Return: 0 on success and drops the lock if so directed, error and leaves the
891  * lock held otherwise.
892  */
893 int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
894 		struct mm_struct *mm, unsigned long start, unsigned long end,
895 		struct list_head *uf, bool unlock)
896 {
897 	struct maple_tree mt_detach;
898 	MA_STATE(mas_detach, &mt_detach, 0, 0);
899 	mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
900 	mt_on_stack(mt_detach);
901 	struct vma_munmap_struct vms;
902 	int error;
903 
904 	init_vma_munmap(&vms, vmi, vma, start, end, uf, unlock);
905 	error = vms_gather_munmap_vmas(&vms, &mas_detach);
906 	if (error)
907 		goto gather_failed;
908 
909 	error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
910 	if (error)
911 		goto clear_tree_failed;
912 
913 	/* Point of no return */
914 	vms_complete_munmap_vmas(&vms, &mas_detach);
915 	return 0;
916 
917 clear_tree_failed:
918 	reattach_vmas(&mas_detach);
919 gather_failed:
920 	validate_mm(mm);
921 	return error;
922 }
923 
924 /*
925  * do_vmi_munmap() - munmap a given range.
926  * @vmi: The vma iterator
927  * @mm: The mm_struct
928  * @start: The start address to munmap
929  * @len: The length of the range to munmap
930  * @uf: The userfaultfd list_head
931  * @unlock: set to true if the user wants to drop the mmap_lock on success
932  *
933  * This function takes a @mas that is either pointing to the previous VMA or set
934  * to MA_START and sets it up to remove the mapping(s).  The @len will be
935  * aligned.
936  *
937  * Return: 0 on success and drops the lock if so directed, error and leaves the
938  * lock held otherwise.
939  */
940 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
941 		  unsigned long start, size_t len, struct list_head *uf,
942 		  bool unlock)
943 {
944 	unsigned long end;
945 	struct vm_area_struct *vma;
946 
947 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
948 		return -EINVAL;
949 
950 	end = start + PAGE_ALIGN(len);
951 	if (end == start)
952 		return -EINVAL;
953 
954 	/* Find the first overlapping VMA */
955 	vma = vma_find(vmi, end);
956 	if (!vma) {
957 		if (unlock)
958 			mmap_write_unlock(mm);
959 		return 0;
960 	}
961 
962 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
963 }
964 
965 /*
966  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
967  * figure out whether that can be merged with its predecessor or its
968  * successor.  Or both (it neatly fills a hole).
969  *
970  * In most cases - when called for mmap, brk or mremap - [addr,end) is
971  * certain not to be mapped by the time vma_merge is called; but when
972  * called for mprotect, it is certain to be already mapped (either at
973  * an offset within prev, or at the start of next), and the flags of
974  * this area are about to be changed to vm_flags - and the no-change
975  * case has already been eliminated.
976  *
977  * The following mprotect cases have to be considered, where **** is
978  * the area passed down from mprotect_fixup, never extending beyond one
979  * vma, PPPP is the previous vma, CCCC is a concurrent vma that starts
980  * at the same address as **** and is of the same or larger span, and
981  * NNNN the next vma after ****:
982  *
983  *     ****             ****                   ****
984  *    PPPPPPNNNNNN    PPPPPPNNNNNN       PPPPPPCCCCCC
985  *    cannot merge    might become       might become
986  *                    PPNNNNNNNNNN       PPPPPPPPPPCC
987  *    mmap, brk or    case 4 below       case 5 below
988  *    mremap move:
989  *                        ****               ****
990  *                    PPPP    NNNN       PPPPCCCCNNNN
991  *                    might become       might become
992  *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
993  *                    PPPPPPPPNNNN 2 or  PPPPPPPPNNNN 7 or
994  *                    PPPPNNNNNNNN 3     PPPPNNNNNNNN 8
995  *
996  * It is important for case 8 that the vma CCCC overlapping the
997  * region **** is never going to extended over NNNN. Instead NNNN must
998  * be extended in region **** and CCCC must be removed. This way in
999  * all cases where vma_merge succeeds, the moment vma_merge drops the
1000  * rmap_locks, the properties of the merged vma will be already
1001  * correct for the whole merged range. Some of those properties like
1002  * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
1003  * be correct for the whole merged range immediately after the
1004  * rmap_locks are released. Otherwise if NNNN would be removed and
1005  * CCCC would be extended over the NNNN range, remove_migration_ptes
1006  * or other rmap walkers (if working on addresses beyond the "end"
1007  * parameter) may establish ptes with the wrong permissions of CCCC
1008  * instead of the right permissions of NNNN.
1009  *
1010  * In the code below:
1011  * PPPP is represented by *prev
1012  * CCCC is represented by *curr or not represented at all (NULL)
1013  * NNNN is represented by *next or not represented at all (NULL)
1014  * **** is not represented - it will be merged and the vma containing the
1015  *      area is returned, or the function will return NULL
1016  */
1017 static struct vm_area_struct *vma_merge(struct vma_merge_struct *vmg)
1018 {
1019 	struct mm_struct *mm = vmg->mm;
1020 	struct vm_area_struct *prev = vmg->prev;
1021 	struct vm_area_struct *curr, *next, *res;
1022 	struct vm_area_struct *vma, *adjust, *remove, *remove2;
1023 	struct vm_area_struct *anon_dup = NULL;
1024 	struct vma_prepare vp;
1025 	pgoff_t vma_pgoff;
1026 	int err = 0;
1027 	bool merge_prev = false;
1028 	bool merge_next = false;
1029 	bool vma_expanded = false;
1030 	unsigned long addr = vmg->start;
1031 	unsigned long end = vmg->end;
1032 	unsigned long vma_start = addr;
1033 	unsigned long vma_end = end;
1034 	pgoff_t pglen = PHYS_PFN(end - addr);
1035 	long adj_start = 0;
1036 
1037 	/*
1038 	 * We later require that vma->vm_flags == vm_flags,
1039 	 * so this tests vma->vm_flags & VM_SPECIAL, too.
1040 	 */
1041 	if (vmg->flags & VM_SPECIAL)
1042 		return NULL;
1043 
1044 	/* Does the input range span an existing VMA? (cases 5 - 8) */
1045 	curr = find_vma_intersection(mm, prev ? prev->vm_end : 0, end);
1046 
1047 	if (!curr ||			/* cases 1 - 4 */
1048 	    end == curr->vm_end)	/* cases 6 - 8, adjacent VMA */
1049 		next = vmg->next = vma_lookup(mm, end);
1050 	else
1051 		next = vmg->next = NULL;	/* case 5 */
1052 
1053 	if (prev) {
1054 		vma_start = prev->vm_start;
1055 		vma_pgoff = prev->vm_pgoff;
1056 
1057 		/* Can we merge the predecessor? */
1058 		if (addr == prev->vm_end && can_vma_merge_after(vmg)) {
1059 			merge_prev = true;
1060 			vma_prev(vmg->vmi);
1061 		}
1062 	}
1063 
1064 	/* Can we merge the successor? */
1065 	if (next && can_vma_merge_before(vmg)) {
1066 		merge_next = true;
1067 	}
1068 
1069 	/* Verify some invariant that must be enforced by the caller. */
1070 	VM_WARN_ON(prev && addr <= prev->vm_start);
1071 	VM_WARN_ON(curr && (addr != curr->vm_start || end > curr->vm_end));
1072 	VM_WARN_ON(addr >= end);
1073 
1074 	if (!merge_prev && !merge_next)
1075 		return NULL; /* Not mergeable. */
1076 
1077 	if (merge_prev)
1078 		vma_start_write(prev);
1079 
1080 	res = vma = prev;
1081 	remove = remove2 = adjust = NULL;
1082 
1083 	/* Can we merge both the predecessor and the successor? */
1084 	if (merge_prev && merge_next &&
1085 	    is_mergeable_anon_vma(prev->anon_vma, next->anon_vma, NULL)) {
1086 		vma_start_write(next);
1087 		remove = next;				/* case 1 */
1088 		vma_end = next->vm_end;
1089 		err = dup_anon_vma(prev, next, &anon_dup);
1090 		if (curr) {				/* case 6 */
1091 			vma_start_write(curr);
1092 			remove = curr;
1093 			remove2 = next;
1094 			/*
1095 			 * Note that the dup_anon_vma below cannot overwrite err
1096 			 * since the first caller would do nothing unless next
1097 			 * has an anon_vma.
1098 			 */
1099 			if (!next->anon_vma)
1100 				err = dup_anon_vma(prev, curr, &anon_dup);
1101 		}
1102 	} else if (merge_prev) {			/* case 2 */
1103 		if (curr) {
1104 			vma_start_write(curr);
1105 			if (end == curr->vm_end) {	/* case 7 */
1106 				/*
1107 				 * can_vma_merge_after() assumed we would not be
1108 				 * removing prev vma, so it skipped the check
1109 				 * for vm_ops->close, but we are removing curr
1110 				 */
1111 				if (curr->vm_ops && curr->vm_ops->close)
1112 					err = -EINVAL;
1113 				remove = curr;
1114 			} else {			/* case 5 */
1115 				adjust = curr;
1116 				adj_start = (end - curr->vm_start);
1117 			}
1118 			if (!err)
1119 				err = dup_anon_vma(prev, curr, &anon_dup);
1120 		}
1121 	} else { /* merge_next */
1122 		vma_start_write(next);
1123 		res = next;
1124 		if (prev && addr < prev->vm_end) {	/* case 4 */
1125 			vma_start_write(prev);
1126 			vma_end = addr;
1127 			adjust = next;
1128 			adj_start = -(prev->vm_end - addr);
1129 			err = dup_anon_vma(next, prev, &anon_dup);
1130 		} else {
1131 			/*
1132 			 * Note that cases 3 and 8 are the ONLY ones where prev
1133 			 * is permitted to be (but is not necessarily) NULL.
1134 			 */
1135 			vma = next;			/* case 3 */
1136 			vma_start = addr;
1137 			vma_end = next->vm_end;
1138 			vma_pgoff = next->vm_pgoff - pglen;
1139 			if (curr) {			/* case 8 */
1140 				vma_pgoff = curr->vm_pgoff;
1141 				vma_start_write(curr);
1142 				remove = curr;
1143 				err = dup_anon_vma(next, curr, &anon_dup);
1144 			}
1145 		}
1146 	}
1147 
1148 	/* Error in anon_vma clone. */
1149 	if (err)
1150 		goto anon_vma_fail;
1151 
1152 	if (vma_start < vma->vm_start || vma_end > vma->vm_end)
1153 		vma_expanded = true;
1154 
1155 	if (vma_expanded) {
1156 		vma_iter_config(vmg->vmi, vma_start, vma_end);
1157 	} else {
1158 		vma_iter_config(vmg->vmi, adjust->vm_start + adj_start,
1159 				adjust->vm_end);
1160 	}
1161 
1162 	if (vma_iter_prealloc(vmg->vmi, vma))
1163 		goto prealloc_fail;
1164 
1165 	init_multi_vma_prep(&vp, vma, adjust, remove, remove2);
1166 	VM_WARN_ON(vp.anon_vma && adjust && adjust->anon_vma &&
1167 		   vp.anon_vma != adjust->anon_vma);
1168 
1169 	vma_prepare(&vp);
1170 	vma_adjust_trans_huge(vma, vma_start, vma_end, adj_start);
1171 	vma_set_range(vma, vma_start, vma_end, vma_pgoff);
1172 
1173 	if (vma_expanded)
1174 		vma_iter_store(vmg->vmi, vma);
1175 
1176 	if (adj_start) {
1177 		adjust->vm_start += adj_start;
1178 		adjust->vm_pgoff += adj_start >> PAGE_SHIFT;
1179 		if (adj_start < 0) {
1180 			WARN_ON(vma_expanded);
1181 			vma_iter_store(vmg->vmi, next);
1182 		}
1183 	}
1184 
1185 	vma_complete(&vp, vmg->vmi, mm);
1186 	validate_mm(mm);
1187 	khugepaged_enter_vma(res, vmg->flags);
1188 	return res;
1189 
1190 prealloc_fail:
1191 	if (anon_dup)
1192 		unlink_anon_vmas(anon_dup);
1193 
1194 anon_vma_fail:
1195 	vma_iter_set(vmg->vmi, addr);
1196 	vma_iter_load(vmg->vmi);
1197 	return NULL;
1198 }
1199 
1200 /*
1201  * We are about to modify one or multiple of a VMA's flags, policy, userfaultfd
1202  * context and anonymous VMA name within the range [start, end).
1203  *
1204  * As a result, we might be able to merge the newly modified VMA range with an
1205  * adjacent VMA with identical properties.
1206  *
1207  * If no merge is possible and the range does not span the entirety of the VMA,
1208  * we then need to split the VMA to accommodate the change.
1209  *
1210  * The function returns either the merged VMA, the original VMA if a split was
1211  * required instead, or an error if the split failed.
1212  */
1213 static struct vm_area_struct *vma_modify(struct vma_merge_struct *vmg)
1214 {
1215 	struct vm_area_struct *vma = vmg->vma;
1216 	struct vm_area_struct *merged;
1217 
1218 	/* First, try to merge. */
1219 	merged = vma_merge(vmg);
1220 	if (merged)
1221 		return merged;
1222 
1223 	/* Split any preceding portion of the VMA. */
1224 	if (vma->vm_start < vmg->start) {
1225 		int err = split_vma(vmg->vmi, vma, vmg->start, 1);
1226 
1227 		if (err)
1228 			return ERR_PTR(err);
1229 	}
1230 
1231 	/* Split any trailing portion of the VMA. */
1232 	if (vma->vm_end > vmg->end) {
1233 		int err = split_vma(vmg->vmi, vma, vmg->end, 0);
1234 
1235 		if (err)
1236 			return ERR_PTR(err);
1237 	}
1238 
1239 	return vma;
1240 }
1241 
1242 struct vm_area_struct *vma_modify_flags(
1243 	struct vma_iterator *vmi, struct vm_area_struct *prev,
1244 	struct vm_area_struct *vma, unsigned long start, unsigned long end,
1245 	unsigned long new_flags)
1246 {
1247 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1248 
1249 	vmg.flags = new_flags;
1250 
1251 	return vma_modify(&vmg);
1252 }
1253 
1254 struct vm_area_struct
1255 *vma_modify_flags_name(struct vma_iterator *vmi,
1256 		       struct vm_area_struct *prev,
1257 		       struct vm_area_struct *vma,
1258 		       unsigned long start,
1259 		       unsigned long end,
1260 		       unsigned long new_flags,
1261 		       struct anon_vma_name *new_name)
1262 {
1263 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1264 
1265 	vmg.flags = new_flags;
1266 	vmg.anon_name = new_name;
1267 
1268 	return vma_modify(&vmg);
1269 }
1270 
1271 struct vm_area_struct
1272 *vma_modify_policy(struct vma_iterator *vmi,
1273 		   struct vm_area_struct *prev,
1274 		   struct vm_area_struct *vma,
1275 		   unsigned long start, unsigned long end,
1276 		   struct mempolicy *new_pol)
1277 {
1278 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1279 
1280 	vmg.policy = new_pol;
1281 
1282 	return vma_modify(&vmg);
1283 }
1284 
1285 struct vm_area_struct
1286 *vma_modify_flags_uffd(struct vma_iterator *vmi,
1287 		       struct vm_area_struct *prev,
1288 		       struct vm_area_struct *vma,
1289 		       unsigned long start, unsigned long end,
1290 		       unsigned long new_flags,
1291 		       struct vm_userfaultfd_ctx new_ctx)
1292 {
1293 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1294 
1295 	vmg.flags = new_flags;
1296 	vmg.uffd_ctx = new_ctx;
1297 
1298 	return vma_modify(&vmg);
1299 }
1300 
1301 /*
1302  * Attempt to merge a newly mapped VMA with those adjacent to it. The caller
1303  * must ensure that [start, end) does not overlap any existing VMA.
1304  */
1305 struct vm_area_struct
1306 *vma_merge_new_vma(struct vma_iterator *vmi, struct vm_area_struct *prev,
1307 		   struct vm_area_struct *vma, unsigned long start,
1308 		   unsigned long end, pgoff_t pgoff)
1309 {
1310 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1311 
1312 	vmg.pgoff = pgoff;
1313 
1314 	return vma_merge(&vmg);
1315 }
1316 
1317 /*
1318  * Expand vma by delta bytes, potentially merging with an immediately adjacent
1319  * VMA with identical properties.
1320  */
1321 struct vm_area_struct *vma_merge_extend(struct vma_iterator *vmi,
1322 					struct vm_area_struct *vma,
1323 					unsigned long delta)
1324 {
1325 	VMG_VMA_STATE(vmg, vmi, vma, vma, vma->vm_end, vma->vm_end + delta);
1326 
1327 	/* vma is specified as prev, so case 1 or 2 will apply. */
1328 	return vma_merge(&vmg);
1329 }
1330 
1331 void unlink_file_vma_batch_init(struct unlink_vma_file_batch *vb)
1332 {
1333 	vb->count = 0;
1334 }
1335 
1336 static void unlink_file_vma_batch_process(struct unlink_vma_file_batch *vb)
1337 {
1338 	struct address_space *mapping;
1339 	int i;
1340 
1341 	mapping = vb->vmas[0]->vm_file->f_mapping;
1342 	i_mmap_lock_write(mapping);
1343 	for (i = 0; i < vb->count; i++) {
1344 		VM_WARN_ON_ONCE(vb->vmas[i]->vm_file->f_mapping != mapping);
1345 		__remove_shared_vm_struct(vb->vmas[i], mapping);
1346 	}
1347 	i_mmap_unlock_write(mapping);
1348 
1349 	unlink_file_vma_batch_init(vb);
1350 }
1351 
1352 void unlink_file_vma_batch_add(struct unlink_vma_file_batch *vb,
1353 			       struct vm_area_struct *vma)
1354 {
1355 	if (vma->vm_file == NULL)
1356 		return;
1357 
1358 	if ((vb->count > 0 && vb->vmas[0]->vm_file != vma->vm_file) ||
1359 	    vb->count == ARRAY_SIZE(vb->vmas))
1360 		unlink_file_vma_batch_process(vb);
1361 
1362 	vb->vmas[vb->count] = vma;
1363 	vb->count++;
1364 }
1365 
1366 void unlink_file_vma_batch_final(struct unlink_vma_file_batch *vb)
1367 {
1368 	if (vb->count > 0)
1369 		unlink_file_vma_batch_process(vb);
1370 }
1371 
1372 /*
1373  * Unlink a file-based vm structure from its interval tree, to hide
1374  * vma from rmap and vmtruncate before freeing its page tables.
1375  */
1376 void unlink_file_vma(struct vm_area_struct *vma)
1377 {
1378 	struct file *file = vma->vm_file;
1379 
1380 	if (file) {
1381 		struct address_space *mapping = file->f_mapping;
1382 
1383 		i_mmap_lock_write(mapping);
1384 		__remove_shared_vm_struct(vma, mapping);
1385 		i_mmap_unlock_write(mapping);
1386 	}
1387 }
1388 
1389 void vma_link_file(struct vm_area_struct *vma)
1390 {
1391 	struct file *file = vma->vm_file;
1392 	struct address_space *mapping;
1393 
1394 	if (file) {
1395 		mapping = file->f_mapping;
1396 		i_mmap_lock_write(mapping);
1397 		__vma_link_file(vma, mapping);
1398 		i_mmap_unlock_write(mapping);
1399 	}
1400 }
1401 
1402 int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
1403 {
1404 	VMA_ITERATOR(vmi, mm, 0);
1405 
1406 	vma_iter_config(&vmi, vma->vm_start, vma->vm_end);
1407 	if (vma_iter_prealloc(&vmi, vma))
1408 		return -ENOMEM;
1409 
1410 	vma_start_write(vma);
1411 	vma_iter_store(&vmi, vma);
1412 	vma_link_file(vma);
1413 	mm->map_count++;
1414 	validate_mm(mm);
1415 	return 0;
1416 }
1417 
1418 /*
1419  * Copy the vma structure to a new location in the same mm,
1420  * prior to moving page table entries, to effect an mremap move.
1421  */
1422 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
1423 	unsigned long addr, unsigned long len, pgoff_t pgoff,
1424 	bool *need_rmap_locks)
1425 {
1426 	struct vm_area_struct *vma = *vmap;
1427 	unsigned long vma_start = vma->vm_start;
1428 	struct mm_struct *mm = vma->vm_mm;
1429 	struct vm_area_struct *new_vma, *prev;
1430 	bool faulted_in_anon_vma = true;
1431 	VMA_ITERATOR(vmi, mm, addr);
1432 
1433 	/*
1434 	 * If anonymous vma has not yet been faulted, update new pgoff
1435 	 * to match new location, to increase its chance of merging.
1436 	 */
1437 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
1438 		pgoff = addr >> PAGE_SHIFT;
1439 		faulted_in_anon_vma = false;
1440 	}
1441 
1442 	new_vma = find_vma_prev(mm, addr, &prev);
1443 	if (new_vma && new_vma->vm_start < addr + len)
1444 		return NULL;	/* should never get here */
1445 
1446 	new_vma = vma_merge_new_vma(&vmi, prev, vma, addr, addr + len, pgoff);
1447 	if (new_vma) {
1448 		/*
1449 		 * Source vma may have been merged into new_vma
1450 		 */
1451 		if (unlikely(vma_start >= new_vma->vm_start &&
1452 			     vma_start < new_vma->vm_end)) {
1453 			/*
1454 			 * The only way we can get a vma_merge with
1455 			 * self during an mremap is if the vma hasn't
1456 			 * been faulted in yet and we were allowed to
1457 			 * reset the dst vma->vm_pgoff to the
1458 			 * destination address of the mremap to allow
1459 			 * the merge to happen. mremap must change the
1460 			 * vm_pgoff linearity between src and dst vmas
1461 			 * (in turn preventing a vma_merge) to be
1462 			 * safe. It is only safe to keep the vm_pgoff
1463 			 * linear if there are no pages mapped yet.
1464 			 */
1465 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
1466 			*vmap = vma = new_vma;
1467 		}
1468 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
1469 	} else {
1470 		new_vma = vm_area_dup(vma);
1471 		if (!new_vma)
1472 			goto out;
1473 		vma_set_range(new_vma, addr, addr + len, pgoff);
1474 		if (vma_dup_policy(vma, new_vma))
1475 			goto out_free_vma;
1476 		if (anon_vma_clone(new_vma, vma))
1477 			goto out_free_mempol;
1478 		if (new_vma->vm_file)
1479 			get_file(new_vma->vm_file);
1480 		if (new_vma->vm_ops && new_vma->vm_ops->open)
1481 			new_vma->vm_ops->open(new_vma);
1482 		if (vma_link(mm, new_vma))
1483 			goto out_vma_link;
1484 		*need_rmap_locks = false;
1485 	}
1486 	return new_vma;
1487 
1488 out_vma_link:
1489 	if (new_vma->vm_ops && new_vma->vm_ops->close)
1490 		new_vma->vm_ops->close(new_vma);
1491 
1492 	if (new_vma->vm_file)
1493 		fput(new_vma->vm_file);
1494 
1495 	unlink_anon_vmas(new_vma);
1496 out_free_mempol:
1497 	mpol_put(vma_policy(new_vma));
1498 out_free_vma:
1499 	vm_area_free(new_vma);
1500 out:
1501 	return NULL;
1502 }
1503 
1504 /*
1505  * Rough compatibility check to quickly see if it's even worth looking
1506  * at sharing an anon_vma.
1507  *
1508  * They need to have the same vm_file, and the flags can only differ
1509  * in things that mprotect may change.
1510  *
1511  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1512  * we can merge the two vma's. For example, we refuse to merge a vma if
1513  * there is a vm_ops->close() function, because that indicates that the
1514  * driver is doing some kind of reference counting. But that doesn't
1515  * really matter for the anon_vma sharing case.
1516  */
1517 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1518 {
1519 	return a->vm_end == b->vm_start &&
1520 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1521 		a->vm_file == b->vm_file &&
1522 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1523 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1524 }
1525 
1526 /*
1527  * Do some basic sanity checking to see if we can re-use the anon_vma
1528  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1529  * the same as 'old', the other will be the new one that is trying
1530  * to share the anon_vma.
1531  *
1532  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1533  * the anon_vma of 'old' is concurrently in the process of being set up
1534  * by another page fault trying to merge _that_. But that's ok: if it
1535  * is being set up, that automatically means that it will be a singleton
1536  * acceptable for merging, so we can do all of this optimistically. But
1537  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1538  *
1539  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1540  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1541  * is to return an anon_vma that is "complex" due to having gone through
1542  * a fork).
1543  *
1544  * We also make sure that the two vma's are compatible (adjacent,
1545  * and with the same memory policies). That's all stable, even with just
1546  * a read lock on the mmap_lock.
1547  */
1548 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old,
1549 					  struct vm_area_struct *a,
1550 					  struct vm_area_struct *b)
1551 {
1552 	if (anon_vma_compatible(a, b)) {
1553 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1554 
1555 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1556 			return anon_vma;
1557 	}
1558 	return NULL;
1559 }
1560 
1561 /*
1562  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1563  * neighbouring vmas for a suitable anon_vma, before it goes off
1564  * to allocate a new anon_vma.  It checks because a repetitive
1565  * sequence of mprotects and faults may otherwise lead to distinct
1566  * anon_vmas being allocated, preventing vma merge in subsequent
1567  * mprotect.
1568  */
1569 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1570 {
1571 	struct anon_vma *anon_vma = NULL;
1572 	struct vm_area_struct *prev, *next;
1573 	VMA_ITERATOR(vmi, vma->vm_mm, vma->vm_end);
1574 
1575 	/* Try next first. */
1576 	next = vma_iter_load(&vmi);
1577 	if (next) {
1578 		anon_vma = reusable_anon_vma(next, vma, next);
1579 		if (anon_vma)
1580 			return anon_vma;
1581 	}
1582 
1583 	prev = vma_prev(&vmi);
1584 	VM_BUG_ON_VMA(prev != vma, vma);
1585 	prev = vma_prev(&vmi);
1586 	/* Try prev next. */
1587 	if (prev)
1588 		anon_vma = reusable_anon_vma(prev, prev, vma);
1589 
1590 	/*
1591 	 * We might reach here with anon_vma == NULL if we can't find
1592 	 * any reusable anon_vma.
1593 	 * There's no absolute need to look only at touching neighbours:
1594 	 * we could search further afield for "compatible" anon_vmas.
1595 	 * But it would probably just be a waste of time searching,
1596 	 * or lead to too many vmas hanging off the same anon_vma.
1597 	 * We're trying to allow mprotect remerging later on,
1598 	 * not trying to minimize memory used for anon_vmas.
1599 	 */
1600 	return anon_vma;
1601 }
1602 
1603 static bool vm_ops_needs_writenotify(const struct vm_operations_struct *vm_ops)
1604 {
1605 	return vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite);
1606 }
1607 
1608 static bool vma_is_shared_writable(struct vm_area_struct *vma)
1609 {
1610 	return (vma->vm_flags & (VM_WRITE | VM_SHARED)) ==
1611 		(VM_WRITE | VM_SHARED);
1612 }
1613 
1614 static bool vma_fs_can_writeback(struct vm_area_struct *vma)
1615 {
1616 	/* No managed pages to writeback. */
1617 	if (vma->vm_flags & VM_PFNMAP)
1618 		return false;
1619 
1620 	return vma->vm_file && vma->vm_file->f_mapping &&
1621 		mapping_can_writeback(vma->vm_file->f_mapping);
1622 }
1623 
1624 /*
1625  * Does this VMA require the underlying folios to have their dirty state
1626  * tracked?
1627  */
1628 bool vma_needs_dirty_tracking(struct vm_area_struct *vma)
1629 {
1630 	/* Only shared, writable VMAs require dirty tracking. */
1631 	if (!vma_is_shared_writable(vma))
1632 		return false;
1633 
1634 	/* Does the filesystem need to be notified? */
1635 	if (vm_ops_needs_writenotify(vma->vm_ops))
1636 		return true;
1637 
1638 	/*
1639 	 * Even if the filesystem doesn't indicate a need for writenotify, if it
1640 	 * can writeback, dirty tracking is still required.
1641 	 */
1642 	return vma_fs_can_writeback(vma);
1643 }
1644 
1645 /*
1646  * Some shared mappings will want the pages marked read-only
1647  * to track write events. If so, we'll downgrade vm_page_prot
1648  * to the private version (using protection_map[] without the
1649  * VM_SHARED bit).
1650  */
1651 bool vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1652 {
1653 	/* If it was private or non-writable, the write bit is already clear */
1654 	if (!vma_is_shared_writable(vma))
1655 		return false;
1656 
1657 	/* The backer wishes to know when pages are first written to? */
1658 	if (vm_ops_needs_writenotify(vma->vm_ops))
1659 		return true;
1660 
1661 	/* The open routine did something to the protections that pgprot_modify
1662 	 * won't preserve? */
1663 	if (pgprot_val(vm_page_prot) !=
1664 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vma->vm_flags)))
1665 		return false;
1666 
1667 	/*
1668 	 * Do we need to track softdirty? hugetlb does not support softdirty
1669 	 * tracking yet.
1670 	 */
1671 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1672 		return true;
1673 
1674 	/* Do we need write faults for uffd-wp tracking? */
1675 	if (userfaultfd_wp(vma))
1676 		return true;
1677 
1678 	/* Can the mapping track the dirty pages? */
1679 	return vma_fs_can_writeback(vma);
1680 }
1681 
1682 static DEFINE_MUTEX(mm_all_locks_mutex);
1683 
1684 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
1685 {
1686 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
1687 		/*
1688 		 * The LSB of head.next can't change from under us
1689 		 * because we hold the mm_all_locks_mutex.
1690 		 */
1691 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
1692 		/*
1693 		 * We can safely modify head.next after taking the
1694 		 * anon_vma->root->rwsem. If some other vma in this mm shares
1695 		 * the same anon_vma we won't take it again.
1696 		 *
1697 		 * No need of atomic instructions here, head.next
1698 		 * can't change from under us thanks to the
1699 		 * anon_vma->root->rwsem.
1700 		 */
1701 		if (__test_and_set_bit(0, (unsigned long *)
1702 				       &anon_vma->root->rb_root.rb_root.rb_node))
1703 			BUG();
1704 	}
1705 }
1706 
1707 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
1708 {
1709 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
1710 		/*
1711 		 * AS_MM_ALL_LOCKS can't change from under us because
1712 		 * we hold the mm_all_locks_mutex.
1713 		 *
1714 		 * Operations on ->flags have to be atomic because
1715 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
1716 		 * mm_all_locks_mutex, there may be other cpus
1717 		 * changing other bitflags in parallel to us.
1718 		 */
1719 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
1720 			BUG();
1721 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
1722 	}
1723 }
1724 
1725 /*
1726  * This operation locks against the VM for all pte/vma/mm related
1727  * operations that could ever happen on a certain mm. This includes
1728  * vmtruncate, try_to_unmap, and all page faults.
1729  *
1730  * The caller must take the mmap_lock in write mode before calling
1731  * mm_take_all_locks(). The caller isn't allowed to release the
1732  * mmap_lock until mm_drop_all_locks() returns.
1733  *
1734  * mmap_lock in write mode is required in order to block all operations
1735  * that could modify pagetables and free pages without need of
1736  * altering the vma layout. It's also needed in write mode to avoid new
1737  * anon_vmas to be associated with existing vmas.
1738  *
1739  * A single task can't take more than one mm_take_all_locks() in a row
1740  * or it would deadlock.
1741  *
1742  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
1743  * mapping->flags avoid to take the same lock twice, if more than one
1744  * vma in this mm is backed by the same anon_vma or address_space.
1745  *
1746  * We take locks in following order, accordingly to comment at beginning
1747  * of mm/rmap.c:
1748  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
1749  *     hugetlb mapping);
1750  *   - all vmas marked locked
1751  *   - all i_mmap_rwsem locks;
1752  *   - all anon_vma->rwseml
1753  *
1754  * We can take all locks within these types randomly because the VM code
1755  * doesn't nest them and we protected from parallel mm_take_all_locks() by
1756  * mm_all_locks_mutex.
1757  *
1758  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
1759  * that may have to take thousand of locks.
1760  *
1761  * mm_take_all_locks() can fail if it's interrupted by signals.
1762  */
1763 int mm_take_all_locks(struct mm_struct *mm)
1764 {
1765 	struct vm_area_struct *vma;
1766 	struct anon_vma_chain *avc;
1767 	VMA_ITERATOR(vmi, mm, 0);
1768 
1769 	mmap_assert_write_locked(mm);
1770 
1771 	mutex_lock(&mm_all_locks_mutex);
1772 
1773 	/*
1774 	 * vma_start_write() does not have a complement in mm_drop_all_locks()
1775 	 * because vma_start_write() is always asymmetrical; it marks a VMA as
1776 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
1777 	 * is reached.
1778 	 */
1779 	for_each_vma(vmi, vma) {
1780 		if (signal_pending(current))
1781 			goto out_unlock;
1782 		vma_start_write(vma);
1783 	}
1784 
1785 	vma_iter_init(&vmi, mm, 0);
1786 	for_each_vma(vmi, vma) {
1787 		if (signal_pending(current))
1788 			goto out_unlock;
1789 		if (vma->vm_file && vma->vm_file->f_mapping &&
1790 				is_vm_hugetlb_page(vma))
1791 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
1792 	}
1793 
1794 	vma_iter_init(&vmi, mm, 0);
1795 	for_each_vma(vmi, vma) {
1796 		if (signal_pending(current))
1797 			goto out_unlock;
1798 		if (vma->vm_file && vma->vm_file->f_mapping &&
1799 				!is_vm_hugetlb_page(vma))
1800 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
1801 	}
1802 
1803 	vma_iter_init(&vmi, mm, 0);
1804 	for_each_vma(vmi, vma) {
1805 		if (signal_pending(current))
1806 			goto out_unlock;
1807 		if (vma->anon_vma)
1808 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
1809 				vm_lock_anon_vma(mm, avc->anon_vma);
1810 	}
1811 
1812 	return 0;
1813 
1814 out_unlock:
1815 	mm_drop_all_locks(mm);
1816 	return -EINTR;
1817 }
1818 
1819 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
1820 {
1821 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
1822 		/*
1823 		 * The LSB of head.next can't change to 0 from under
1824 		 * us because we hold the mm_all_locks_mutex.
1825 		 *
1826 		 * We must however clear the bitflag before unlocking
1827 		 * the vma so the users using the anon_vma->rb_root will
1828 		 * never see our bitflag.
1829 		 *
1830 		 * No need of atomic instructions here, head.next
1831 		 * can't change from under us until we release the
1832 		 * anon_vma->root->rwsem.
1833 		 */
1834 		if (!__test_and_clear_bit(0, (unsigned long *)
1835 					  &anon_vma->root->rb_root.rb_root.rb_node))
1836 			BUG();
1837 		anon_vma_unlock_write(anon_vma);
1838 	}
1839 }
1840 
1841 static void vm_unlock_mapping(struct address_space *mapping)
1842 {
1843 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
1844 		/*
1845 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
1846 		 * because we hold the mm_all_locks_mutex.
1847 		 */
1848 		i_mmap_unlock_write(mapping);
1849 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
1850 					&mapping->flags))
1851 			BUG();
1852 	}
1853 }
1854 
1855 /*
1856  * The mmap_lock cannot be released by the caller until
1857  * mm_drop_all_locks() returns.
1858  */
1859 void mm_drop_all_locks(struct mm_struct *mm)
1860 {
1861 	struct vm_area_struct *vma;
1862 	struct anon_vma_chain *avc;
1863 	VMA_ITERATOR(vmi, mm, 0);
1864 
1865 	mmap_assert_write_locked(mm);
1866 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
1867 
1868 	for_each_vma(vmi, vma) {
1869 		if (vma->anon_vma)
1870 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
1871 				vm_unlock_anon_vma(avc->anon_vma);
1872 		if (vma->vm_file && vma->vm_file->f_mapping)
1873 			vm_unlock_mapping(vma->vm_file->f_mapping);
1874 	}
1875 
1876 	mutex_unlock(&mm_all_locks_mutex);
1877 }
1878