xref: /linux/mm/vma.c (revision 0c3beacf681ec897e0b36685a9b49d01f5cb2dfb)
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 struct mmap_state {
11 	struct mm_struct *mm;
12 	struct vma_iterator *vmi;
13 
14 	unsigned long addr;
15 	unsigned long end;
16 	pgoff_t pgoff;
17 	unsigned long pglen;
18 	unsigned long flags;
19 	struct file *file;
20 
21 	unsigned long charged;
22 	bool retry_merge;
23 
24 	struct vm_area_struct *prev;
25 	struct vm_area_struct *next;
26 
27 	/* Unmapping state. */
28 	struct vma_munmap_struct vms;
29 	struct ma_state mas_detach;
30 	struct maple_tree mt_detach;
31 };
32 
33 #define MMAP_STATE(name, mm_, vmi_, addr_, len_, pgoff_, flags_, file_) \
34 	struct mmap_state name = {					\
35 		.mm = mm_,						\
36 		.vmi = vmi_,						\
37 		.addr = addr_,						\
38 		.end = (addr_) + len,					\
39 		.pgoff = pgoff_,					\
40 		.pglen = PHYS_PFN(len_),				\
41 		.flags = flags_,					\
42 		.file = file_,						\
43 	}
44 
45 #define VMG_MMAP_STATE(name, map_, vma_)				\
46 	struct vma_merge_struct name = {				\
47 		.mm = (map_)->mm,					\
48 		.vmi = (map_)->vmi,					\
49 		.start = (map_)->addr,					\
50 		.end = (map_)->end,					\
51 		.flags = (map_)->flags,					\
52 		.pgoff = (map_)->pgoff,					\
53 		.file = (map_)->file,					\
54 		.prev = (map_)->prev,					\
55 		.vma = vma_,						\
56 		.next = (vma_) ? NULL : (map_)->next,			\
57 		.state = VMA_MERGE_START,				\
58 		.merge_flags = VMG_FLAG_DEFAULT,			\
59 	}
60 
61 static inline bool is_mergeable_vma(struct vma_merge_struct *vmg, bool merge_next)
62 {
63 	struct vm_area_struct *vma = merge_next ? vmg->next : vmg->prev;
64 
65 	if (!mpol_equal(vmg->policy, vma_policy(vma)))
66 		return false;
67 	/*
68 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
69 	 * match the flags but dirty bit -- the caller should mark
70 	 * merged VMA as dirty. If dirty bit won't be excluded from
71 	 * comparison, we increase pressure on the memory system forcing
72 	 * the kernel to generate new VMAs when old one could be
73 	 * extended instead.
74 	 */
75 	if ((vma->vm_flags ^ vmg->flags) & ~VM_SOFTDIRTY)
76 		return false;
77 	if (vma->vm_file != vmg->file)
78 		return false;
79 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vmg->uffd_ctx))
80 		return false;
81 	if (!anon_vma_name_eq(anon_vma_name(vma), vmg->anon_name))
82 		return false;
83 	return true;
84 }
85 
86 static inline bool is_mergeable_anon_vma(struct anon_vma *anon_vma1,
87 		 struct anon_vma *anon_vma2, struct vm_area_struct *vma)
88 {
89 	/*
90 	 * The list_is_singular() test is to avoid merging VMA cloned from
91 	 * parents. This can improve scalability caused by anon_vma lock.
92 	 */
93 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
94 		list_is_singular(&vma->anon_vma_chain)))
95 		return true;
96 	return anon_vma1 == anon_vma2;
97 }
98 
99 /* Are the anon_vma's belonging to each VMA compatible with one another? */
100 static inline bool are_anon_vmas_compatible(struct vm_area_struct *vma1,
101 					    struct vm_area_struct *vma2)
102 {
103 	return is_mergeable_anon_vma(vma1->anon_vma, vma2->anon_vma, NULL);
104 }
105 
106 /*
107  * init_multi_vma_prep() - Initializer for struct vma_prepare
108  * @vp: The vma_prepare struct
109  * @vma: The vma that will be altered once locked
110  * @next: The next vma if it is to be adjusted
111  * @remove: The first vma to be removed
112  * @remove2: The second vma to be removed
113  */
114 static void init_multi_vma_prep(struct vma_prepare *vp,
115 				struct vm_area_struct *vma,
116 				struct vm_area_struct *next,
117 				struct vm_area_struct *remove,
118 				struct vm_area_struct *remove2)
119 {
120 	memset(vp, 0, sizeof(struct vma_prepare));
121 	vp->vma = vma;
122 	vp->anon_vma = vma->anon_vma;
123 	vp->remove = remove;
124 	vp->remove2 = remove2;
125 	vp->adj_next = next;
126 	if (!vp->anon_vma && next)
127 		vp->anon_vma = next->anon_vma;
128 
129 	vp->file = vma->vm_file;
130 	if (vp->file)
131 		vp->mapping = vma->vm_file->f_mapping;
132 
133 }
134 
135 /*
136  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
137  * in front of (at a lower virtual address and file offset than) the vma.
138  *
139  * We cannot merge two vmas if they have differently assigned (non-NULL)
140  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
141  *
142  * We don't check here for the merged mmap wrapping around the end of pagecache
143  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
144  * wrap, nor mmaps which cover the final page at index -1UL.
145  *
146  * We assume the vma may be removed as part of the merge.
147  */
148 static bool can_vma_merge_before(struct vma_merge_struct *vmg)
149 {
150 	pgoff_t pglen = PHYS_PFN(vmg->end - vmg->start);
151 
152 	if (is_mergeable_vma(vmg, /* merge_next = */ true) &&
153 	    is_mergeable_anon_vma(vmg->anon_vma, vmg->next->anon_vma, vmg->next)) {
154 		if (vmg->next->vm_pgoff == vmg->pgoff + pglen)
155 			return true;
156 	}
157 
158 	return false;
159 }
160 
161 /*
162  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
163  * beyond (at a higher virtual address and file offset than) the vma.
164  *
165  * We cannot merge two vmas if they have differently assigned (non-NULL)
166  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
167  *
168  * We assume that vma is not removed as part of the merge.
169  */
170 static bool can_vma_merge_after(struct vma_merge_struct *vmg)
171 {
172 	if (is_mergeable_vma(vmg, /* merge_next = */ false) &&
173 	    is_mergeable_anon_vma(vmg->anon_vma, vmg->prev->anon_vma, vmg->prev)) {
174 		if (vmg->prev->vm_pgoff + vma_pages(vmg->prev) == vmg->pgoff)
175 			return true;
176 	}
177 	return false;
178 }
179 
180 static void __vma_link_file(struct vm_area_struct *vma,
181 			    struct address_space *mapping)
182 {
183 	if (vma_is_shared_maywrite(vma))
184 		mapping_allow_writable(mapping);
185 
186 	flush_dcache_mmap_lock(mapping);
187 	vma_interval_tree_insert(vma, &mapping->i_mmap);
188 	flush_dcache_mmap_unlock(mapping);
189 }
190 
191 /*
192  * Requires inode->i_mapping->i_mmap_rwsem
193  */
194 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
195 				      struct address_space *mapping)
196 {
197 	if (vma_is_shared_maywrite(vma))
198 		mapping_unmap_writable(mapping);
199 
200 	flush_dcache_mmap_lock(mapping);
201 	vma_interval_tree_remove(vma, &mapping->i_mmap);
202 	flush_dcache_mmap_unlock(mapping);
203 }
204 
205 /*
206  * vma_prepare() - Helper function for handling locking VMAs prior to altering
207  * @vp: The initialized vma_prepare struct
208  */
209 static void vma_prepare(struct vma_prepare *vp)
210 {
211 	if (vp->file) {
212 		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
213 
214 		if (vp->adj_next)
215 			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
216 				      vp->adj_next->vm_end);
217 
218 		i_mmap_lock_write(vp->mapping);
219 		if (vp->insert && vp->insert->vm_file) {
220 			/*
221 			 * Put into interval tree now, so instantiated pages
222 			 * are visible to arm/parisc __flush_dcache_page
223 			 * throughout; but we cannot insert into address
224 			 * space until vma start or end is updated.
225 			 */
226 			__vma_link_file(vp->insert,
227 					vp->insert->vm_file->f_mapping);
228 		}
229 	}
230 
231 	if (vp->anon_vma) {
232 		anon_vma_lock_write(vp->anon_vma);
233 		anon_vma_interval_tree_pre_update_vma(vp->vma);
234 		if (vp->adj_next)
235 			anon_vma_interval_tree_pre_update_vma(vp->adj_next);
236 	}
237 
238 	if (vp->file) {
239 		flush_dcache_mmap_lock(vp->mapping);
240 		vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
241 		if (vp->adj_next)
242 			vma_interval_tree_remove(vp->adj_next,
243 						 &vp->mapping->i_mmap);
244 	}
245 
246 }
247 
248 /*
249  * vma_complete- Helper function for handling the unlocking after altering VMAs,
250  * or for inserting a VMA.
251  *
252  * @vp: The vma_prepare struct
253  * @vmi: The vma iterator
254  * @mm: The mm_struct
255  */
256 static void vma_complete(struct vma_prepare *vp, struct vma_iterator *vmi,
257 			 struct mm_struct *mm)
258 {
259 	if (vp->file) {
260 		if (vp->adj_next)
261 			vma_interval_tree_insert(vp->adj_next,
262 						 &vp->mapping->i_mmap);
263 		vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
264 		flush_dcache_mmap_unlock(vp->mapping);
265 	}
266 
267 	if (vp->remove && vp->file) {
268 		__remove_shared_vm_struct(vp->remove, vp->mapping);
269 		if (vp->remove2)
270 			__remove_shared_vm_struct(vp->remove2, vp->mapping);
271 	} else if (vp->insert) {
272 		/*
273 		 * split_vma has split insert from vma, and needs
274 		 * us to insert it before dropping the locks
275 		 * (it may either follow vma or precede it).
276 		 */
277 		vma_iter_store(vmi, vp->insert);
278 		mm->map_count++;
279 	}
280 
281 	if (vp->anon_vma) {
282 		anon_vma_interval_tree_post_update_vma(vp->vma);
283 		if (vp->adj_next)
284 			anon_vma_interval_tree_post_update_vma(vp->adj_next);
285 		anon_vma_unlock_write(vp->anon_vma);
286 	}
287 
288 	if (vp->file) {
289 		i_mmap_unlock_write(vp->mapping);
290 		uprobe_mmap(vp->vma);
291 
292 		if (vp->adj_next)
293 			uprobe_mmap(vp->adj_next);
294 	}
295 
296 	if (vp->remove) {
297 again:
298 		vma_mark_detached(vp->remove, true);
299 		if (vp->file) {
300 			uprobe_munmap(vp->remove, vp->remove->vm_start,
301 				      vp->remove->vm_end);
302 			fput(vp->file);
303 		}
304 		if (vp->remove->anon_vma)
305 			anon_vma_merge(vp->vma, vp->remove);
306 		mm->map_count--;
307 		mpol_put(vma_policy(vp->remove));
308 		if (!vp->remove2)
309 			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
310 		vm_area_free(vp->remove);
311 
312 		/*
313 		 * In mprotect's case 6 (see comments on vma_merge),
314 		 * we are removing both mid and next vmas
315 		 */
316 		if (vp->remove2) {
317 			vp->remove = vp->remove2;
318 			vp->remove2 = NULL;
319 			goto again;
320 		}
321 	}
322 	if (vp->insert && vp->file)
323 		uprobe_mmap(vp->insert);
324 }
325 
326 /*
327  * init_vma_prep() - Initializer wrapper for vma_prepare struct
328  * @vp: The vma_prepare struct
329  * @vma: The vma that will be altered once locked
330  */
331 static void init_vma_prep(struct vma_prepare *vp, struct vm_area_struct *vma)
332 {
333 	init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
334 }
335 
336 /*
337  * Can the proposed VMA be merged with the left (previous) VMA taking into
338  * account the start position of the proposed range.
339  */
340 static bool can_vma_merge_left(struct vma_merge_struct *vmg)
341 
342 {
343 	return vmg->prev && vmg->prev->vm_end == vmg->start &&
344 		can_vma_merge_after(vmg);
345 }
346 
347 /*
348  * Can the proposed VMA be merged with the right (next) VMA taking into
349  * account the end position of the proposed range.
350  *
351  * In addition, if we can merge with the left VMA, ensure that left and right
352  * anon_vma's are also compatible.
353  */
354 static bool can_vma_merge_right(struct vma_merge_struct *vmg,
355 				bool can_merge_left)
356 {
357 	if (!vmg->next || vmg->end != vmg->next->vm_start ||
358 	    !can_vma_merge_before(vmg))
359 		return false;
360 
361 	if (!can_merge_left)
362 		return true;
363 
364 	/*
365 	 * If we can merge with prev (left) and next (right), indicating that
366 	 * each VMA's anon_vma is compatible with the proposed anon_vma, this
367 	 * does not mean prev and next are compatible with EACH OTHER.
368 	 *
369 	 * We therefore check this in addition to mergeability to either side.
370 	 */
371 	return are_anon_vmas_compatible(vmg->prev, vmg->next);
372 }
373 
374 /*
375  * Close a vm structure and free it.
376  */
377 void remove_vma(struct vm_area_struct *vma, bool unreachable)
378 {
379 	might_sleep();
380 	vma_close(vma);
381 	if (vma->vm_file)
382 		fput(vma->vm_file);
383 	mpol_put(vma_policy(vma));
384 	if (unreachable)
385 		__vm_area_free(vma);
386 	else
387 		vm_area_free(vma);
388 }
389 
390 /*
391  * Get rid of page table information in the indicated region.
392  *
393  * Called with the mm semaphore held.
394  */
395 void unmap_region(struct ma_state *mas, struct vm_area_struct *vma,
396 		struct vm_area_struct *prev, struct vm_area_struct *next)
397 {
398 	struct mm_struct *mm = vma->vm_mm;
399 	struct mmu_gather tlb;
400 
401 	lru_add_drain();
402 	tlb_gather_mmu(&tlb, mm);
403 	update_hiwater_rss(mm);
404 	unmap_vmas(&tlb, mas, vma, vma->vm_start, vma->vm_end, vma->vm_end,
405 		   /* mm_wr_locked = */ true);
406 	mas_set(mas, vma->vm_end);
407 	free_pgtables(&tlb, mas, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
408 		      next ? next->vm_start : USER_PGTABLES_CEILING,
409 		      /* mm_wr_locked = */ true);
410 	tlb_finish_mmu(&tlb);
411 }
412 
413 /*
414  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
415  * has already been checked or doesn't make sense to fail.
416  * VMA Iterator will point to the original VMA.
417  */
418 static int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
419 		       unsigned long addr, int new_below)
420 {
421 	struct vma_prepare vp;
422 	struct vm_area_struct *new;
423 	int err;
424 
425 	WARN_ON(vma->vm_start >= addr);
426 	WARN_ON(vma->vm_end <= addr);
427 
428 	if (vma->vm_ops && vma->vm_ops->may_split) {
429 		err = vma->vm_ops->may_split(vma, addr);
430 		if (err)
431 			return err;
432 	}
433 
434 	new = vm_area_dup(vma);
435 	if (!new)
436 		return -ENOMEM;
437 
438 	if (new_below) {
439 		new->vm_end = addr;
440 	} else {
441 		new->vm_start = addr;
442 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
443 	}
444 
445 	err = -ENOMEM;
446 	vma_iter_config(vmi, new->vm_start, new->vm_end);
447 	if (vma_iter_prealloc(vmi, new))
448 		goto out_free_vma;
449 
450 	err = vma_dup_policy(vma, new);
451 	if (err)
452 		goto out_free_vmi;
453 
454 	err = anon_vma_clone(new, vma);
455 	if (err)
456 		goto out_free_mpol;
457 
458 	if (new->vm_file)
459 		get_file(new->vm_file);
460 
461 	if (new->vm_ops && new->vm_ops->open)
462 		new->vm_ops->open(new);
463 
464 	vma_start_write(vma);
465 	vma_start_write(new);
466 
467 	init_vma_prep(&vp, vma);
468 	vp.insert = new;
469 	vma_prepare(&vp);
470 	vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
471 
472 	if (new_below) {
473 		vma->vm_start = addr;
474 		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
475 	} else {
476 		vma->vm_end = addr;
477 	}
478 
479 	/* vma_complete stores the new vma */
480 	vma_complete(&vp, vmi, vma->vm_mm);
481 	validate_mm(vma->vm_mm);
482 
483 	/* Success. */
484 	if (new_below)
485 		vma_next(vmi);
486 	else
487 		vma_prev(vmi);
488 
489 	return 0;
490 
491 out_free_mpol:
492 	mpol_put(vma_policy(new));
493 out_free_vmi:
494 	vma_iter_free(vmi);
495 out_free_vma:
496 	vm_area_free(new);
497 	return err;
498 }
499 
500 /*
501  * Split a vma into two pieces at address 'addr', a new vma is allocated
502  * either for the first part or the tail.
503  */
504 static int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
505 		     unsigned long addr, int new_below)
506 {
507 	if (vma->vm_mm->map_count >= sysctl_max_map_count)
508 		return -ENOMEM;
509 
510 	return __split_vma(vmi, vma, addr, new_below);
511 }
512 
513 /*
514  * vma has some anon_vma assigned, and is already inserted on that
515  * anon_vma's interval trees.
516  *
517  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
518  * vma must be removed from the anon_vma's interval trees using
519  * anon_vma_interval_tree_pre_update_vma().
520  *
521  * After the update, the vma will be reinserted using
522  * anon_vma_interval_tree_post_update_vma().
523  *
524  * The entire update must be protected by exclusive mmap_lock and by
525  * the root anon_vma's mutex.
526  */
527 void
528 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
529 {
530 	struct anon_vma_chain *avc;
531 
532 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
533 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
534 }
535 
536 void
537 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
538 {
539 	struct anon_vma_chain *avc;
540 
541 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
542 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
543 }
544 
545 /*
546  * dup_anon_vma() - Helper function to duplicate anon_vma
547  * @dst: The destination VMA
548  * @src: The source VMA
549  * @dup: Pointer to the destination VMA when successful.
550  *
551  * Returns: 0 on success.
552  */
553 static int dup_anon_vma(struct vm_area_struct *dst,
554 			struct vm_area_struct *src, struct vm_area_struct **dup)
555 {
556 	/*
557 	 * Easily overlooked: when mprotect shifts the boundary, make sure the
558 	 * expanding vma has anon_vma set if the shrinking vma had, to cover any
559 	 * anon pages imported.
560 	 */
561 	if (src->anon_vma && !dst->anon_vma) {
562 		int ret;
563 
564 		vma_assert_write_locked(dst);
565 		dst->anon_vma = src->anon_vma;
566 		ret = anon_vma_clone(dst, src);
567 		if (ret)
568 			return ret;
569 
570 		*dup = dst;
571 	}
572 
573 	return 0;
574 }
575 
576 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
577 void validate_mm(struct mm_struct *mm)
578 {
579 	int bug = 0;
580 	int i = 0;
581 	struct vm_area_struct *vma;
582 	VMA_ITERATOR(vmi, mm, 0);
583 
584 	mt_validate(&mm->mm_mt);
585 	for_each_vma(vmi, vma) {
586 #ifdef CONFIG_DEBUG_VM_RB
587 		struct anon_vma *anon_vma = vma->anon_vma;
588 		struct anon_vma_chain *avc;
589 #endif
590 		unsigned long vmi_start, vmi_end;
591 		bool warn = 0;
592 
593 		vmi_start = vma_iter_addr(&vmi);
594 		vmi_end = vma_iter_end(&vmi);
595 		if (VM_WARN_ON_ONCE_MM(vma->vm_end != vmi_end, mm))
596 			warn = 1;
597 
598 		if (VM_WARN_ON_ONCE_MM(vma->vm_start != vmi_start, mm))
599 			warn = 1;
600 
601 		if (warn) {
602 			pr_emerg("issue in %s\n", current->comm);
603 			dump_stack();
604 			dump_vma(vma);
605 			pr_emerg("tree range: %px start %lx end %lx\n", vma,
606 				 vmi_start, vmi_end - 1);
607 			vma_iter_dump_tree(&vmi);
608 		}
609 
610 #ifdef CONFIG_DEBUG_VM_RB
611 		if (anon_vma) {
612 			anon_vma_lock_read(anon_vma);
613 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
614 				anon_vma_interval_tree_verify(avc);
615 			anon_vma_unlock_read(anon_vma);
616 		}
617 #endif
618 		i++;
619 	}
620 	if (i != mm->map_count) {
621 		pr_emerg("map_count %d vma iterator %d\n", mm->map_count, i);
622 		bug = 1;
623 	}
624 	VM_BUG_ON_MM(bug, mm);
625 }
626 #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
627 
628 /* Actually perform the VMA merge operation. */
629 static int commit_merge(struct vma_merge_struct *vmg,
630 			struct vm_area_struct *adjust,
631 			struct vm_area_struct *remove,
632 			struct vm_area_struct *remove2,
633 			long adj_start,
634 			bool expanded)
635 {
636 	struct vma_prepare vp;
637 
638 	init_multi_vma_prep(&vp, vmg->vma, adjust, remove, remove2);
639 
640 	VM_WARN_ON(vp.anon_vma && adjust && adjust->anon_vma &&
641 		   vp.anon_vma != adjust->anon_vma);
642 
643 	if (expanded) {
644 		/* Note: vma iterator must be pointing to 'start'. */
645 		vma_iter_config(vmg->vmi, vmg->start, vmg->end);
646 	} else {
647 		vma_iter_config(vmg->vmi, adjust->vm_start + adj_start,
648 				adjust->vm_end);
649 	}
650 
651 	if (vma_iter_prealloc(vmg->vmi, vmg->vma))
652 		return -ENOMEM;
653 
654 	vma_prepare(&vp);
655 	vma_adjust_trans_huge(vmg->vma, vmg->start, vmg->end, adj_start);
656 	vma_set_range(vmg->vma, vmg->start, vmg->end, vmg->pgoff);
657 
658 	if (expanded)
659 		vma_iter_store(vmg->vmi, vmg->vma);
660 
661 	if (adj_start) {
662 		adjust->vm_start += adj_start;
663 		adjust->vm_pgoff += PHYS_PFN(adj_start);
664 		if (adj_start < 0) {
665 			WARN_ON(expanded);
666 			vma_iter_store(vmg->vmi, adjust);
667 		}
668 	}
669 
670 	vma_complete(&vp, vmg->vmi, vmg->vma->vm_mm);
671 
672 	return 0;
673 }
674 
675 /* We can only remove VMAs when merging if they do not have a close hook. */
676 static bool can_merge_remove_vma(struct vm_area_struct *vma)
677 {
678 	return !vma->vm_ops || !vma->vm_ops->close;
679 }
680 
681 /*
682  * vma_merge_existing_range - Attempt to merge VMAs based on a VMA having its
683  * attributes modified.
684  *
685  * @vmg: Describes the modifications being made to a VMA and associated
686  *       metadata.
687  *
688  * When the attributes of a range within a VMA change, then it might be possible
689  * for immediately adjacent VMAs to be merged into that VMA due to having
690  * identical properties.
691  *
692  * This function checks for the existence of any such mergeable VMAs and updates
693  * the maple tree describing the @vmg->vma->vm_mm address space to account for
694  * this, as well as any VMAs shrunk/expanded/deleted as a result of this merge.
695  *
696  * As part of this operation, if a merge occurs, the @vmg object will have its
697  * vma, start, end, and pgoff fields modified to execute the merge. Subsequent
698  * calls to this function should reset these fields.
699  *
700  * Returns: The merged VMA if merge succeeds, or NULL otherwise.
701  *
702  * ASSUMPTIONS:
703  * - The caller must assign the VMA to be modifed to @vmg->vma.
704  * - The caller must have set @vmg->prev to the previous VMA, if there is one.
705  * - The caller must not set @vmg->next, as we determine this.
706  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
707  * - vmi must be positioned within [@vmg->vma->vm_start, @vmg->vma->vm_end).
708  */
709 static struct vm_area_struct *vma_merge_existing_range(struct vma_merge_struct *vmg)
710 {
711 	struct vm_area_struct *vma = vmg->vma;
712 	struct vm_area_struct *prev = vmg->prev;
713 	struct vm_area_struct *next, *res;
714 	struct vm_area_struct *anon_dup = NULL;
715 	struct vm_area_struct *adjust = NULL;
716 	unsigned long start = vmg->start;
717 	unsigned long end = vmg->end;
718 	bool left_side = vma && start == vma->vm_start;
719 	bool right_side = vma && end == vma->vm_end;
720 	int err = 0;
721 	long adj_start = 0;
722 	bool merge_will_delete_vma, merge_will_delete_next;
723 	bool merge_left, merge_right, merge_both;
724 	bool expanded;
725 
726 	mmap_assert_write_locked(vmg->mm);
727 	VM_WARN_ON(!vma); /* We are modifying a VMA, so caller must specify. */
728 	VM_WARN_ON(vmg->next); /* We set this. */
729 	VM_WARN_ON(prev && start <= prev->vm_start);
730 	VM_WARN_ON(start >= end);
731 	/*
732 	 * If vma == prev, then we are offset into a VMA. Otherwise, if we are
733 	 * not, we must span a portion of the VMA.
734 	 */
735 	VM_WARN_ON(vma && ((vma != prev && vmg->start != vma->vm_start) ||
736 			   vmg->end > vma->vm_end));
737 	/* The vmi must be positioned within vmg->vma. */
738 	VM_WARN_ON(vma && !(vma_iter_addr(vmg->vmi) >= vma->vm_start &&
739 			    vma_iter_addr(vmg->vmi) < vma->vm_end));
740 
741 	vmg->state = VMA_MERGE_NOMERGE;
742 
743 	/*
744 	 * If a special mapping or if the range being modified is neither at the
745 	 * furthermost left or right side of the VMA, then we have no chance of
746 	 * merging and should abort.
747 	 */
748 	if (vmg->flags & VM_SPECIAL || (!left_side && !right_side))
749 		return NULL;
750 
751 	if (left_side)
752 		merge_left = can_vma_merge_left(vmg);
753 	else
754 		merge_left = false;
755 
756 	if (right_side) {
757 		next = vmg->next = vma_iter_next_range(vmg->vmi);
758 		vma_iter_prev_range(vmg->vmi);
759 
760 		merge_right = can_vma_merge_right(vmg, merge_left);
761 	} else {
762 		merge_right = false;
763 		next = NULL;
764 	}
765 
766 	if (merge_left)		/* If merging prev, position iterator there. */
767 		vma_prev(vmg->vmi);
768 	else if (!merge_right)	/* If we have nothing to merge, abort. */
769 		return NULL;
770 
771 	merge_both = merge_left && merge_right;
772 	/* If we span the entire VMA, a merge implies it will be deleted. */
773 	merge_will_delete_vma = left_side && right_side;
774 
775 	/*
776 	 * If we need to remove vma in its entirety but are unable to do so,
777 	 * we have no sensible recourse but to abort the merge.
778 	 */
779 	if (merge_will_delete_vma && !can_merge_remove_vma(vma))
780 		return NULL;
781 
782 	/*
783 	 * If we merge both VMAs, then next is also deleted. This implies
784 	 * merge_will_delete_vma also.
785 	 */
786 	merge_will_delete_next = merge_both;
787 
788 	/*
789 	 * If we cannot delete next, then we can reduce the operation to merging
790 	 * prev and vma (thereby deleting vma).
791 	 */
792 	if (merge_will_delete_next && !can_merge_remove_vma(next)) {
793 		merge_will_delete_next = false;
794 		merge_right = false;
795 		merge_both = false;
796 	}
797 
798 	/* No matter what happens, we will be adjusting vma. */
799 	vma_start_write(vma);
800 
801 	if (merge_left)
802 		vma_start_write(prev);
803 
804 	if (merge_right)
805 		vma_start_write(next);
806 
807 	if (merge_both) {
808 		/*
809 		 *         |<----->|
810 		 * |-------*********-------|
811 		 *   prev     vma     next
812 		 *  extend   delete  delete
813 		 */
814 
815 		vmg->vma = prev;
816 		vmg->start = prev->vm_start;
817 		vmg->end = next->vm_end;
818 		vmg->pgoff = prev->vm_pgoff;
819 
820 		/*
821 		 * We already ensured anon_vma compatibility above, so now it's
822 		 * simply a case of, if prev has no anon_vma object, which of
823 		 * next or vma contains the anon_vma we must duplicate.
824 		 */
825 		err = dup_anon_vma(prev, next->anon_vma ? next : vma, &anon_dup);
826 	} else if (merge_left) {
827 		/*
828 		 *         |<----->| OR
829 		 *         |<--------->|
830 		 * |-------*************
831 		 *   prev       vma
832 		 *  extend shrink/delete
833 		 */
834 
835 		vmg->vma = prev;
836 		vmg->start = prev->vm_start;
837 		vmg->pgoff = prev->vm_pgoff;
838 
839 		if (!merge_will_delete_vma) {
840 			adjust = vma;
841 			adj_start = vmg->end - vma->vm_start;
842 		}
843 
844 		err = dup_anon_vma(prev, vma, &anon_dup);
845 	} else { /* merge_right */
846 		/*
847 		 *     |<----->| OR
848 		 * |<--------->|
849 		 * *************-------|
850 		 *      vma       next
851 		 * shrink/delete extend
852 		 */
853 
854 		pgoff_t pglen = PHYS_PFN(vmg->end - vmg->start);
855 
856 		VM_WARN_ON(!merge_right);
857 		/* If we are offset into a VMA, then prev must be vma. */
858 		VM_WARN_ON(vmg->start > vma->vm_start && prev && vma != prev);
859 
860 		if (merge_will_delete_vma) {
861 			vmg->vma = next;
862 			vmg->end = next->vm_end;
863 			vmg->pgoff = next->vm_pgoff - pglen;
864 		} else {
865 			/*
866 			 * We shrink vma and expand next.
867 			 *
868 			 * IMPORTANT: This is the ONLY case where the final
869 			 * merged VMA is NOT vmg->vma, but rather vmg->next.
870 			 */
871 
872 			vmg->start = vma->vm_start;
873 			vmg->end = start;
874 			vmg->pgoff = vma->vm_pgoff;
875 
876 			adjust = next;
877 			adj_start = -(vma->vm_end - start);
878 		}
879 
880 		err = dup_anon_vma(next, vma, &anon_dup);
881 	}
882 
883 	if (err)
884 		goto abort;
885 
886 	/*
887 	 * In nearly all cases, we expand vmg->vma. There is one exception -
888 	 * merge_right where we partially span the VMA. In this case we shrink
889 	 * the end of vmg->vma and adjust the start of vmg->next accordingly.
890 	 */
891 	expanded = !merge_right || merge_will_delete_vma;
892 
893 	if (commit_merge(vmg, adjust,
894 			 merge_will_delete_vma ? vma : NULL,
895 			 merge_will_delete_next ? next : NULL,
896 			 adj_start, expanded)) {
897 		if (anon_dup)
898 			unlink_anon_vmas(anon_dup);
899 
900 		vmg->state = VMA_MERGE_ERROR_NOMEM;
901 		return NULL;
902 	}
903 
904 	res = merge_left ? prev : next;
905 	khugepaged_enter_vma(res, vmg->flags);
906 
907 	vmg->state = VMA_MERGE_SUCCESS;
908 	return res;
909 
910 abort:
911 	vma_iter_set(vmg->vmi, start);
912 	vma_iter_load(vmg->vmi);
913 	vmg->state = VMA_MERGE_ERROR_NOMEM;
914 	return NULL;
915 }
916 
917 /*
918  * vma_merge_new_range - Attempt to merge a new VMA into address space
919  *
920  * @vmg: Describes the VMA we are adding, in the range @vmg->start to @vmg->end
921  *       (exclusive), which we try to merge with any adjacent VMAs if possible.
922  *
923  * We are about to add a VMA to the address space starting at @vmg->start and
924  * ending at @vmg->end. There are three different possible scenarios:
925  *
926  * 1. There is a VMA with identical properties immediately adjacent to the
927  *    proposed new VMA [@vmg->start, @vmg->end) either before or after it -
928  *    EXPAND that VMA:
929  *
930  * Proposed:       |-----|  or  |-----|
931  * Existing:  |----|                  |----|
932  *
933  * 2. There are VMAs with identical properties immediately adjacent to the
934  *    proposed new VMA [@vmg->start, @vmg->end) both before AND after it -
935  *    EXPAND the former and REMOVE the latter:
936  *
937  * Proposed:       |-----|
938  * Existing:  |----|     |----|
939  *
940  * 3. There are no VMAs immediately adjacent to the proposed new VMA or those
941  *    VMAs do not have identical attributes - NO MERGE POSSIBLE.
942  *
943  * In instances where we can merge, this function returns the expanded VMA which
944  * will have its range adjusted accordingly and the underlying maple tree also
945  * adjusted.
946  *
947  * Returns: In instances where no merge was possible, NULL. Otherwise, a pointer
948  *          to the VMA we expanded.
949  *
950  * This function adjusts @vmg to provide @vmg->next if not already specified,
951  * and adjusts [@vmg->start, @vmg->end) to span the expanded range.
952  *
953  * ASSUMPTIONS:
954  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
955  * - The caller must have determined that [@vmg->start, @vmg->end) is empty,
956      other than VMAs that will be unmapped should the operation succeed.
957  * - The caller must have specified the previous vma in @vmg->prev.
958  * - The caller must have specified the next vma in @vmg->next.
959  * - The caller must have positioned the vmi at or before the gap.
960  */
961 struct vm_area_struct *vma_merge_new_range(struct vma_merge_struct *vmg)
962 {
963 	struct vm_area_struct *prev = vmg->prev;
964 	struct vm_area_struct *next = vmg->next;
965 	unsigned long end = vmg->end;
966 	bool can_merge_left, can_merge_right;
967 	bool just_expand = vmg->merge_flags & VMG_FLAG_JUST_EXPAND;
968 
969 	mmap_assert_write_locked(vmg->mm);
970 	VM_WARN_ON(vmg->vma);
971 	/* vmi must point at or before the gap. */
972 	VM_WARN_ON(vma_iter_addr(vmg->vmi) > end);
973 
974 	vmg->state = VMA_MERGE_NOMERGE;
975 
976 	/* Special VMAs are unmergeable, also if no prev/next. */
977 	if ((vmg->flags & VM_SPECIAL) || (!prev && !next))
978 		return NULL;
979 
980 	can_merge_left = can_vma_merge_left(vmg);
981 	can_merge_right = !just_expand && can_vma_merge_right(vmg, can_merge_left);
982 
983 	/* If we can merge with the next VMA, adjust vmg accordingly. */
984 	if (can_merge_right) {
985 		vmg->end = next->vm_end;
986 		vmg->vma = next;
987 	}
988 
989 	/* If we can merge with the previous VMA, adjust vmg accordingly. */
990 	if (can_merge_left) {
991 		vmg->start = prev->vm_start;
992 		vmg->vma = prev;
993 		vmg->pgoff = prev->vm_pgoff;
994 
995 		/*
996 		 * If this merge would result in removal of the next VMA but we
997 		 * are not permitted to do so, reduce the operation to merging
998 		 * prev and vma.
999 		 */
1000 		if (can_merge_right && !can_merge_remove_vma(next))
1001 			vmg->end = end;
1002 
1003 		/* In expand-only case we are already positioned at prev. */
1004 		if (!just_expand) {
1005 			/* Equivalent to going to the previous range. */
1006 			vma_prev(vmg->vmi);
1007 		}
1008 	}
1009 
1010 	/*
1011 	 * Now try to expand adjacent VMA(s). This takes care of removing the
1012 	 * following VMA if we have VMAs on both sides.
1013 	 */
1014 	if (vmg->vma && !vma_expand(vmg)) {
1015 		khugepaged_enter_vma(vmg->vma, vmg->flags);
1016 		vmg->state = VMA_MERGE_SUCCESS;
1017 		return vmg->vma;
1018 	}
1019 
1020 	return NULL;
1021 }
1022 
1023 /*
1024  * vma_expand - Expand an existing VMA
1025  *
1026  * @vmg: Describes a VMA expansion operation.
1027  *
1028  * Expand @vma to vmg->start and vmg->end.  Can expand off the start and end.
1029  * Will expand over vmg->next if it's different from vmg->vma and vmg->end ==
1030  * vmg->next->vm_end.  Checking if the vmg->vma can expand and merge with
1031  * vmg->next needs to be handled by the caller.
1032  *
1033  * Returns: 0 on success.
1034  *
1035  * ASSUMPTIONS:
1036  * - The caller must hold a WRITE lock on vmg->vma->mm->mmap_lock.
1037  * - The caller must have set @vmg->vma and @vmg->next.
1038  */
1039 int vma_expand(struct vma_merge_struct *vmg)
1040 {
1041 	struct vm_area_struct *anon_dup = NULL;
1042 	bool remove_next = false;
1043 	struct vm_area_struct *vma = vmg->vma;
1044 	struct vm_area_struct *next = vmg->next;
1045 
1046 	mmap_assert_write_locked(vmg->mm);
1047 
1048 	vma_start_write(vma);
1049 	if (next && (vma != next) && (vmg->end == next->vm_end)) {
1050 		int ret;
1051 
1052 		remove_next = true;
1053 		/* This should already have been checked by this point. */
1054 		VM_WARN_ON(!can_merge_remove_vma(next));
1055 		vma_start_write(next);
1056 		ret = dup_anon_vma(vma, next, &anon_dup);
1057 		if (ret)
1058 			return ret;
1059 	}
1060 
1061 	/* Not merging but overwriting any part of next is not handled. */
1062 	VM_WARN_ON(next && !remove_next &&
1063 		  next != vma && vmg->end > next->vm_start);
1064 	/* Only handles expanding */
1065 	VM_WARN_ON(vma->vm_start < vmg->start || vma->vm_end > vmg->end);
1066 
1067 	if (commit_merge(vmg, NULL, remove_next ? next : NULL, NULL, 0, true))
1068 		goto nomem;
1069 
1070 	return 0;
1071 
1072 nomem:
1073 	vmg->state = VMA_MERGE_ERROR_NOMEM;
1074 	if (anon_dup)
1075 		unlink_anon_vmas(anon_dup);
1076 	return -ENOMEM;
1077 }
1078 
1079 /*
1080  * vma_shrink() - Reduce an existing VMAs memory area
1081  * @vmi: The vma iterator
1082  * @vma: The VMA to modify
1083  * @start: The new start
1084  * @end: The new end
1085  *
1086  * Returns: 0 on success, -ENOMEM otherwise
1087  */
1088 int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
1089 	       unsigned long start, unsigned long end, pgoff_t pgoff)
1090 {
1091 	struct vma_prepare vp;
1092 
1093 	WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
1094 
1095 	if (vma->vm_start < start)
1096 		vma_iter_config(vmi, vma->vm_start, start);
1097 	else
1098 		vma_iter_config(vmi, end, vma->vm_end);
1099 
1100 	if (vma_iter_prealloc(vmi, NULL))
1101 		return -ENOMEM;
1102 
1103 	vma_start_write(vma);
1104 
1105 	init_vma_prep(&vp, vma);
1106 	vma_prepare(&vp);
1107 	vma_adjust_trans_huge(vma, start, end, 0);
1108 
1109 	vma_iter_clear(vmi);
1110 	vma_set_range(vma, start, end, pgoff);
1111 	vma_complete(&vp, vmi, vma->vm_mm);
1112 	validate_mm(vma->vm_mm);
1113 	return 0;
1114 }
1115 
1116 static inline void vms_clear_ptes(struct vma_munmap_struct *vms,
1117 		    struct ma_state *mas_detach, bool mm_wr_locked)
1118 {
1119 	struct mmu_gather tlb;
1120 
1121 	if (!vms->clear_ptes) /* Nothing to do */
1122 		return;
1123 
1124 	/*
1125 	 * We can free page tables without write-locking mmap_lock because VMAs
1126 	 * were isolated before we downgraded mmap_lock.
1127 	 */
1128 	mas_set(mas_detach, 1);
1129 	lru_add_drain();
1130 	tlb_gather_mmu(&tlb, vms->vma->vm_mm);
1131 	update_hiwater_rss(vms->vma->vm_mm);
1132 	unmap_vmas(&tlb, mas_detach, vms->vma, vms->start, vms->end,
1133 		   vms->vma_count, mm_wr_locked);
1134 
1135 	mas_set(mas_detach, 1);
1136 	/* start and end may be different if there is no prev or next vma. */
1137 	free_pgtables(&tlb, mas_detach, vms->vma, vms->unmap_start,
1138 		      vms->unmap_end, mm_wr_locked);
1139 	tlb_finish_mmu(&tlb);
1140 	vms->clear_ptes = false;
1141 }
1142 
1143 static void vms_clean_up_area(struct vma_munmap_struct *vms,
1144 		struct ma_state *mas_detach)
1145 {
1146 	struct vm_area_struct *vma;
1147 
1148 	if (!vms->nr_pages)
1149 		return;
1150 
1151 	vms_clear_ptes(vms, mas_detach, true);
1152 	mas_set(mas_detach, 0);
1153 	mas_for_each(mas_detach, vma, ULONG_MAX)
1154 		vma_close(vma);
1155 }
1156 
1157 /*
1158  * vms_complete_munmap_vmas() - Finish the munmap() operation
1159  * @vms: The vma munmap struct
1160  * @mas_detach: The maple state of the detached vmas
1161  *
1162  * This updates the mm_struct, unmaps the region, frees the resources
1163  * used for the munmap() and may downgrade the lock - if requested.  Everything
1164  * needed to be done once the vma maple tree is updated.
1165  */
1166 static void vms_complete_munmap_vmas(struct vma_munmap_struct *vms,
1167 		struct ma_state *mas_detach)
1168 {
1169 	struct vm_area_struct *vma;
1170 	struct mm_struct *mm;
1171 
1172 	mm = current->mm;
1173 	mm->map_count -= vms->vma_count;
1174 	mm->locked_vm -= vms->locked_vm;
1175 	if (vms->unlock)
1176 		mmap_write_downgrade(mm);
1177 
1178 	if (!vms->nr_pages)
1179 		return;
1180 
1181 	vms_clear_ptes(vms, mas_detach, !vms->unlock);
1182 	/* Update high watermark before we lower total_vm */
1183 	update_hiwater_vm(mm);
1184 	/* Stat accounting */
1185 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm) - vms->nr_pages);
1186 	/* Paranoid bookkeeping */
1187 	VM_WARN_ON(vms->exec_vm > mm->exec_vm);
1188 	VM_WARN_ON(vms->stack_vm > mm->stack_vm);
1189 	VM_WARN_ON(vms->data_vm > mm->data_vm);
1190 	mm->exec_vm -= vms->exec_vm;
1191 	mm->stack_vm -= vms->stack_vm;
1192 	mm->data_vm -= vms->data_vm;
1193 
1194 	/* Remove and clean up vmas */
1195 	mas_set(mas_detach, 0);
1196 	mas_for_each(mas_detach, vma, ULONG_MAX)
1197 		remove_vma(vma, /* unreachable = */ false);
1198 
1199 	vm_unacct_memory(vms->nr_accounted);
1200 	validate_mm(mm);
1201 	if (vms->unlock)
1202 		mmap_read_unlock(mm);
1203 
1204 	__mt_destroy(mas_detach->tree);
1205 }
1206 
1207 /*
1208  * reattach_vmas() - Undo any munmap work and free resources
1209  * @mas_detach: The maple state with the detached maple tree
1210  *
1211  * Reattach any detached vmas and free up the maple tree used to track the vmas.
1212  */
1213 static void reattach_vmas(struct ma_state *mas_detach)
1214 {
1215 	struct vm_area_struct *vma;
1216 
1217 	mas_set(mas_detach, 0);
1218 	mas_for_each(mas_detach, vma, ULONG_MAX)
1219 		vma_mark_detached(vma, false);
1220 
1221 	__mt_destroy(mas_detach->tree);
1222 }
1223 
1224 /*
1225  * vms_gather_munmap_vmas() - Put all VMAs within a range into a maple tree
1226  * for removal at a later date.  Handles splitting first and last if necessary
1227  * and marking the vmas as isolated.
1228  *
1229  * @vms: The vma munmap struct
1230  * @mas_detach: The maple state tracking the detached tree
1231  *
1232  * Return: 0 on success, error otherwise
1233  */
1234 static int vms_gather_munmap_vmas(struct vma_munmap_struct *vms,
1235 		struct ma_state *mas_detach)
1236 {
1237 	struct vm_area_struct *next = NULL;
1238 	int error;
1239 
1240 	/*
1241 	 * If we need to split any vma, do it now to save pain later.
1242 	 * Does it split the first one?
1243 	 */
1244 	if (vms->start > vms->vma->vm_start) {
1245 
1246 		/*
1247 		 * Make sure that map_count on return from munmap() will
1248 		 * not exceed its limit; but let map_count go just above
1249 		 * its limit temporarily, to help free resources as expected.
1250 		 */
1251 		if (vms->end < vms->vma->vm_end &&
1252 		    vms->vma->vm_mm->map_count >= sysctl_max_map_count) {
1253 			error = -ENOMEM;
1254 			goto map_count_exceeded;
1255 		}
1256 
1257 		/* Don't bother splitting the VMA if we can't unmap it anyway */
1258 		if (!can_modify_vma(vms->vma)) {
1259 			error = -EPERM;
1260 			goto start_split_failed;
1261 		}
1262 
1263 		error = __split_vma(vms->vmi, vms->vma, vms->start, 1);
1264 		if (error)
1265 			goto start_split_failed;
1266 	}
1267 	vms->prev = vma_prev(vms->vmi);
1268 	if (vms->prev)
1269 		vms->unmap_start = vms->prev->vm_end;
1270 
1271 	/*
1272 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
1273 	 * it is always overwritten.
1274 	 */
1275 	for_each_vma_range(*(vms->vmi), next, vms->end) {
1276 		long nrpages;
1277 
1278 		if (!can_modify_vma(next)) {
1279 			error = -EPERM;
1280 			goto modify_vma_failed;
1281 		}
1282 		/* Does it split the end? */
1283 		if (next->vm_end > vms->end) {
1284 			error = __split_vma(vms->vmi, next, vms->end, 0);
1285 			if (error)
1286 				goto end_split_failed;
1287 		}
1288 		vma_start_write(next);
1289 		mas_set(mas_detach, vms->vma_count++);
1290 		error = mas_store_gfp(mas_detach, next, GFP_KERNEL);
1291 		if (error)
1292 			goto munmap_gather_failed;
1293 
1294 		vma_mark_detached(next, true);
1295 		nrpages = vma_pages(next);
1296 
1297 		vms->nr_pages += nrpages;
1298 		if (next->vm_flags & VM_LOCKED)
1299 			vms->locked_vm += nrpages;
1300 
1301 		if (next->vm_flags & VM_ACCOUNT)
1302 			vms->nr_accounted += nrpages;
1303 
1304 		if (is_exec_mapping(next->vm_flags))
1305 			vms->exec_vm += nrpages;
1306 		else if (is_stack_mapping(next->vm_flags))
1307 			vms->stack_vm += nrpages;
1308 		else if (is_data_mapping(next->vm_flags))
1309 			vms->data_vm += nrpages;
1310 
1311 		if (vms->uf) {
1312 			/*
1313 			 * If userfaultfd_unmap_prep returns an error the vmas
1314 			 * will remain split, but userland will get a
1315 			 * highly unexpected error anyway. This is no
1316 			 * different than the case where the first of the two
1317 			 * __split_vma fails, but we don't undo the first
1318 			 * split, despite we could. This is unlikely enough
1319 			 * failure that it's not worth optimizing it for.
1320 			 */
1321 			error = userfaultfd_unmap_prep(next, vms->start,
1322 						       vms->end, vms->uf);
1323 			if (error)
1324 				goto userfaultfd_error;
1325 		}
1326 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
1327 		BUG_ON(next->vm_start < vms->start);
1328 		BUG_ON(next->vm_start > vms->end);
1329 #endif
1330 	}
1331 
1332 	vms->next = vma_next(vms->vmi);
1333 	if (vms->next)
1334 		vms->unmap_end = vms->next->vm_start;
1335 
1336 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
1337 	/* Make sure no VMAs are about to be lost. */
1338 	{
1339 		MA_STATE(test, mas_detach->tree, 0, 0);
1340 		struct vm_area_struct *vma_mas, *vma_test;
1341 		int test_count = 0;
1342 
1343 		vma_iter_set(vms->vmi, vms->start);
1344 		rcu_read_lock();
1345 		vma_test = mas_find(&test, vms->vma_count - 1);
1346 		for_each_vma_range(*(vms->vmi), vma_mas, vms->end) {
1347 			BUG_ON(vma_mas != vma_test);
1348 			test_count++;
1349 			vma_test = mas_next(&test, vms->vma_count - 1);
1350 		}
1351 		rcu_read_unlock();
1352 		BUG_ON(vms->vma_count != test_count);
1353 	}
1354 #endif
1355 
1356 	while (vma_iter_addr(vms->vmi) > vms->start)
1357 		vma_iter_prev_range(vms->vmi);
1358 
1359 	vms->clear_ptes = true;
1360 	return 0;
1361 
1362 userfaultfd_error:
1363 munmap_gather_failed:
1364 end_split_failed:
1365 modify_vma_failed:
1366 	reattach_vmas(mas_detach);
1367 start_split_failed:
1368 map_count_exceeded:
1369 	return error;
1370 }
1371 
1372 /*
1373  * init_vma_munmap() - Initializer wrapper for vma_munmap_struct
1374  * @vms: The vma munmap struct
1375  * @vmi: The vma iterator
1376  * @vma: The first vm_area_struct to munmap
1377  * @start: The aligned start address to munmap
1378  * @end: The aligned end address to munmap
1379  * @uf: The userfaultfd list_head
1380  * @unlock: Unlock after the operation.  Only unlocked on success
1381  */
1382 static void init_vma_munmap(struct vma_munmap_struct *vms,
1383 		struct vma_iterator *vmi, struct vm_area_struct *vma,
1384 		unsigned long start, unsigned long end, struct list_head *uf,
1385 		bool unlock)
1386 {
1387 	vms->vmi = vmi;
1388 	vms->vma = vma;
1389 	if (vma) {
1390 		vms->start = start;
1391 		vms->end = end;
1392 	} else {
1393 		vms->start = vms->end = 0;
1394 	}
1395 	vms->unlock = unlock;
1396 	vms->uf = uf;
1397 	vms->vma_count = 0;
1398 	vms->nr_pages = vms->locked_vm = vms->nr_accounted = 0;
1399 	vms->exec_vm = vms->stack_vm = vms->data_vm = 0;
1400 	vms->unmap_start = FIRST_USER_ADDRESS;
1401 	vms->unmap_end = USER_PGTABLES_CEILING;
1402 	vms->clear_ptes = false;
1403 }
1404 
1405 /*
1406  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
1407  * @vmi: The vma iterator
1408  * @vma: The starting vm_area_struct
1409  * @mm: The mm_struct
1410  * @start: The aligned start address to munmap.
1411  * @end: The aligned end address to munmap.
1412  * @uf: The userfaultfd list_head
1413  * @unlock: Set to true to drop the mmap_lock.  unlocking only happens on
1414  * success.
1415  *
1416  * Return: 0 on success and drops the lock if so directed, error and leaves the
1417  * lock held otherwise.
1418  */
1419 int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
1420 		struct mm_struct *mm, unsigned long start, unsigned long end,
1421 		struct list_head *uf, bool unlock)
1422 {
1423 	struct maple_tree mt_detach;
1424 	MA_STATE(mas_detach, &mt_detach, 0, 0);
1425 	mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
1426 	mt_on_stack(mt_detach);
1427 	struct vma_munmap_struct vms;
1428 	int error;
1429 
1430 	init_vma_munmap(&vms, vmi, vma, start, end, uf, unlock);
1431 	error = vms_gather_munmap_vmas(&vms, &mas_detach);
1432 	if (error)
1433 		goto gather_failed;
1434 
1435 	error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
1436 	if (error)
1437 		goto clear_tree_failed;
1438 
1439 	/* Point of no return */
1440 	vms_complete_munmap_vmas(&vms, &mas_detach);
1441 	return 0;
1442 
1443 clear_tree_failed:
1444 	reattach_vmas(&mas_detach);
1445 gather_failed:
1446 	validate_mm(mm);
1447 	return error;
1448 }
1449 
1450 /*
1451  * do_vmi_munmap() - munmap a given range.
1452  * @vmi: The vma iterator
1453  * @mm: The mm_struct
1454  * @start: The start address to munmap
1455  * @len: The length of the range to munmap
1456  * @uf: The userfaultfd list_head
1457  * @unlock: set to true if the user wants to drop the mmap_lock on success
1458  *
1459  * This function takes a @mas that is either pointing to the previous VMA or set
1460  * to MA_START and sets it up to remove the mapping(s).  The @len will be
1461  * aligned.
1462  *
1463  * Return: 0 on success and drops the lock if so directed, error and leaves the
1464  * lock held otherwise.
1465  */
1466 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
1467 		  unsigned long start, size_t len, struct list_head *uf,
1468 		  bool unlock)
1469 {
1470 	unsigned long end;
1471 	struct vm_area_struct *vma;
1472 
1473 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
1474 		return -EINVAL;
1475 
1476 	end = start + PAGE_ALIGN(len);
1477 	if (end == start)
1478 		return -EINVAL;
1479 
1480 	/* Find the first overlapping VMA */
1481 	vma = vma_find(vmi, end);
1482 	if (!vma) {
1483 		if (unlock)
1484 			mmap_write_unlock(mm);
1485 		return 0;
1486 	}
1487 
1488 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
1489 }
1490 
1491 /*
1492  * We are about to modify one or multiple of a VMA's flags, policy, userfaultfd
1493  * context and anonymous VMA name within the range [start, end).
1494  *
1495  * As a result, we might be able to merge the newly modified VMA range with an
1496  * adjacent VMA with identical properties.
1497  *
1498  * If no merge is possible and the range does not span the entirety of the VMA,
1499  * we then need to split the VMA to accommodate the change.
1500  *
1501  * The function returns either the merged VMA, the original VMA if a split was
1502  * required instead, or an error if the split failed.
1503  */
1504 static struct vm_area_struct *vma_modify(struct vma_merge_struct *vmg)
1505 {
1506 	struct vm_area_struct *vma = vmg->vma;
1507 	struct vm_area_struct *merged;
1508 
1509 	/* First, try to merge. */
1510 	merged = vma_merge_existing_range(vmg);
1511 	if (merged)
1512 		return merged;
1513 
1514 	/* Split any preceding portion of the VMA. */
1515 	if (vma->vm_start < vmg->start) {
1516 		int err = split_vma(vmg->vmi, vma, vmg->start, 1);
1517 
1518 		if (err)
1519 			return ERR_PTR(err);
1520 	}
1521 
1522 	/* Split any trailing portion of the VMA. */
1523 	if (vma->vm_end > vmg->end) {
1524 		int err = split_vma(vmg->vmi, vma, vmg->end, 0);
1525 
1526 		if (err)
1527 			return ERR_PTR(err);
1528 	}
1529 
1530 	return vma;
1531 }
1532 
1533 struct vm_area_struct *vma_modify_flags(
1534 	struct vma_iterator *vmi, struct vm_area_struct *prev,
1535 	struct vm_area_struct *vma, unsigned long start, unsigned long end,
1536 	unsigned long new_flags)
1537 {
1538 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1539 
1540 	vmg.flags = new_flags;
1541 
1542 	return vma_modify(&vmg);
1543 }
1544 
1545 struct vm_area_struct
1546 *vma_modify_flags_name(struct vma_iterator *vmi,
1547 		       struct vm_area_struct *prev,
1548 		       struct vm_area_struct *vma,
1549 		       unsigned long start,
1550 		       unsigned long end,
1551 		       unsigned long new_flags,
1552 		       struct anon_vma_name *new_name)
1553 {
1554 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1555 
1556 	vmg.flags = new_flags;
1557 	vmg.anon_name = new_name;
1558 
1559 	return vma_modify(&vmg);
1560 }
1561 
1562 struct vm_area_struct
1563 *vma_modify_policy(struct vma_iterator *vmi,
1564 		   struct vm_area_struct *prev,
1565 		   struct vm_area_struct *vma,
1566 		   unsigned long start, unsigned long end,
1567 		   struct mempolicy *new_pol)
1568 {
1569 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1570 
1571 	vmg.policy = new_pol;
1572 
1573 	return vma_modify(&vmg);
1574 }
1575 
1576 struct vm_area_struct
1577 *vma_modify_flags_uffd(struct vma_iterator *vmi,
1578 		       struct vm_area_struct *prev,
1579 		       struct vm_area_struct *vma,
1580 		       unsigned long start, unsigned long end,
1581 		       unsigned long new_flags,
1582 		       struct vm_userfaultfd_ctx new_ctx)
1583 {
1584 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1585 
1586 	vmg.flags = new_flags;
1587 	vmg.uffd_ctx = new_ctx;
1588 
1589 	return vma_modify(&vmg);
1590 }
1591 
1592 /*
1593  * Expand vma by delta bytes, potentially merging with an immediately adjacent
1594  * VMA with identical properties.
1595  */
1596 struct vm_area_struct *vma_merge_extend(struct vma_iterator *vmi,
1597 					struct vm_area_struct *vma,
1598 					unsigned long delta)
1599 {
1600 	VMG_VMA_STATE(vmg, vmi, vma, vma, vma->vm_end, vma->vm_end + delta);
1601 
1602 	vmg.next = vma_iter_next_rewind(vmi, NULL);
1603 	vmg.vma = NULL; /* We use the VMA to populate VMG fields only. */
1604 
1605 	return vma_merge_new_range(&vmg);
1606 }
1607 
1608 void unlink_file_vma_batch_init(struct unlink_vma_file_batch *vb)
1609 {
1610 	vb->count = 0;
1611 }
1612 
1613 static void unlink_file_vma_batch_process(struct unlink_vma_file_batch *vb)
1614 {
1615 	struct address_space *mapping;
1616 	int i;
1617 
1618 	mapping = vb->vmas[0]->vm_file->f_mapping;
1619 	i_mmap_lock_write(mapping);
1620 	for (i = 0; i < vb->count; i++) {
1621 		VM_WARN_ON_ONCE(vb->vmas[i]->vm_file->f_mapping != mapping);
1622 		__remove_shared_vm_struct(vb->vmas[i], mapping);
1623 	}
1624 	i_mmap_unlock_write(mapping);
1625 
1626 	unlink_file_vma_batch_init(vb);
1627 }
1628 
1629 void unlink_file_vma_batch_add(struct unlink_vma_file_batch *vb,
1630 			       struct vm_area_struct *vma)
1631 {
1632 	if (vma->vm_file == NULL)
1633 		return;
1634 
1635 	if ((vb->count > 0 && vb->vmas[0]->vm_file != vma->vm_file) ||
1636 	    vb->count == ARRAY_SIZE(vb->vmas))
1637 		unlink_file_vma_batch_process(vb);
1638 
1639 	vb->vmas[vb->count] = vma;
1640 	vb->count++;
1641 }
1642 
1643 void unlink_file_vma_batch_final(struct unlink_vma_file_batch *vb)
1644 {
1645 	if (vb->count > 0)
1646 		unlink_file_vma_batch_process(vb);
1647 }
1648 
1649 /*
1650  * Unlink a file-based vm structure from its interval tree, to hide
1651  * vma from rmap and vmtruncate before freeing its page tables.
1652  */
1653 void unlink_file_vma(struct vm_area_struct *vma)
1654 {
1655 	struct file *file = vma->vm_file;
1656 
1657 	if (file) {
1658 		struct address_space *mapping = file->f_mapping;
1659 
1660 		i_mmap_lock_write(mapping);
1661 		__remove_shared_vm_struct(vma, mapping);
1662 		i_mmap_unlock_write(mapping);
1663 	}
1664 }
1665 
1666 void vma_link_file(struct vm_area_struct *vma)
1667 {
1668 	struct file *file = vma->vm_file;
1669 	struct address_space *mapping;
1670 
1671 	if (file) {
1672 		mapping = file->f_mapping;
1673 		i_mmap_lock_write(mapping);
1674 		__vma_link_file(vma, mapping);
1675 		i_mmap_unlock_write(mapping);
1676 	}
1677 }
1678 
1679 int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
1680 {
1681 	VMA_ITERATOR(vmi, mm, 0);
1682 
1683 	vma_iter_config(&vmi, vma->vm_start, vma->vm_end);
1684 	if (vma_iter_prealloc(&vmi, vma))
1685 		return -ENOMEM;
1686 
1687 	vma_start_write(vma);
1688 	vma_iter_store(&vmi, vma);
1689 	vma_link_file(vma);
1690 	mm->map_count++;
1691 	validate_mm(mm);
1692 	return 0;
1693 }
1694 
1695 /*
1696  * Copy the vma structure to a new location in the same mm,
1697  * prior to moving page table entries, to effect an mremap move.
1698  */
1699 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
1700 	unsigned long addr, unsigned long len, pgoff_t pgoff,
1701 	bool *need_rmap_locks)
1702 {
1703 	struct vm_area_struct *vma = *vmap;
1704 	unsigned long vma_start = vma->vm_start;
1705 	struct mm_struct *mm = vma->vm_mm;
1706 	struct vm_area_struct *new_vma;
1707 	bool faulted_in_anon_vma = true;
1708 	VMA_ITERATOR(vmi, mm, addr);
1709 	VMG_VMA_STATE(vmg, &vmi, NULL, vma, addr, addr + len);
1710 
1711 	/*
1712 	 * If anonymous vma has not yet been faulted, update new pgoff
1713 	 * to match new location, to increase its chance of merging.
1714 	 */
1715 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
1716 		pgoff = addr >> PAGE_SHIFT;
1717 		faulted_in_anon_vma = false;
1718 	}
1719 
1720 	new_vma = find_vma_prev(mm, addr, &vmg.prev);
1721 	if (new_vma && new_vma->vm_start < addr + len)
1722 		return NULL;	/* should never get here */
1723 
1724 	vmg.vma = NULL; /* New VMA range. */
1725 	vmg.pgoff = pgoff;
1726 	vmg.next = vma_iter_next_rewind(&vmi, NULL);
1727 	new_vma = vma_merge_new_range(&vmg);
1728 
1729 	if (new_vma) {
1730 		/*
1731 		 * Source vma may have been merged into new_vma
1732 		 */
1733 		if (unlikely(vma_start >= new_vma->vm_start &&
1734 			     vma_start < new_vma->vm_end)) {
1735 			/*
1736 			 * The only way we can get a vma_merge with
1737 			 * self during an mremap is if the vma hasn't
1738 			 * been faulted in yet and we were allowed to
1739 			 * reset the dst vma->vm_pgoff to the
1740 			 * destination address of the mremap to allow
1741 			 * the merge to happen. mremap must change the
1742 			 * vm_pgoff linearity between src and dst vmas
1743 			 * (in turn preventing a vma_merge) to be
1744 			 * safe. It is only safe to keep the vm_pgoff
1745 			 * linear if there are no pages mapped yet.
1746 			 */
1747 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
1748 			*vmap = vma = new_vma;
1749 		}
1750 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
1751 	} else {
1752 		new_vma = vm_area_dup(vma);
1753 		if (!new_vma)
1754 			goto out;
1755 		vma_set_range(new_vma, addr, addr + len, pgoff);
1756 		if (vma_dup_policy(vma, new_vma))
1757 			goto out_free_vma;
1758 		if (anon_vma_clone(new_vma, vma))
1759 			goto out_free_mempol;
1760 		if (new_vma->vm_file)
1761 			get_file(new_vma->vm_file);
1762 		if (new_vma->vm_ops && new_vma->vm_ops->open)
1763 			new_vma->vm_ops->open(new_vma);
1764 		if (vma_link(mm, new_vma))
1765 			goto out_vma_link;
1766 		*need_rmap_locks = false;
1767 	}
1768 	return new_vma;
1769 
1770 out_vma_link:
1771 	vma_close(new_vma);
1772 
1773 	if (new_vma->vm_file)
1774 		fput(new_vma->vm_file);
1775 
1776 	unlink_anon_vmas(new_vma);
1777 out_free_mempol:
1778 	mpol_put(vma_policy(new_vma));
1779 out_free_vma:
1780 	vm_area_free(new_vma);
1781 out:
1782 	return NULL;
1783 }
1784 
1785 /*
1786  * Rough compatibility check to quickly see if it's even worth looking
1787  * at sharing an anon_vma.
1788  *
1789  * They need to have the same vm_file, and the flags can only differ
1790  * in things that mprotect may change.
1791  *
1792  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1793  * we can merge the two vma's. For example, we refuse to merge a vma if
1794  * there is a vm_ops->close() function, because that indicates that the
1795  * driver is doing some kind of reference counting. But that doesn't
1796  * really matter for the anon_vma sharing case.
1797  */
1798 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1799 {
1800 	return a->vm_end == b->vm_start &&
1801 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1802 		a->vm_file == b->vm_file &&
1803 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1804 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1805 }
1806 
1807 /*
1808  * Do some basic sanity checking to see if we can re-use the anon_vma
1809  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1810  * the same as 'old', the other will be the new one that is trying
1811  * to share the anon_vma.
1812  *
1813  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1814  * the anon_vma of 'old' is concurrently in the process of being set up
1815  * by another page fault trying to merge _that_. But that's ok: if it
1816  * is being set up, that automatically means that it will be a singleton
1817  * acceptable for merging, so we can do all of this optimistically. But
1818  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1819  *
1820  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1821  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1822  * is to return an anon_vma that is "complex" due to having gone through
1823  * a fork).
1824  *
1825  * We also make sure that the two vma's are compatible (adjacent,
1826  * and with the same memory policies). That's all stable, even with just
1827  * a read lock on the mmap_lock.
1828  */
1829 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old,
1830 					  struct vm_area_struct *a,
1831 					  struct vm_area_struct *b)
1832 {
1833 	if (anon_vma_compatible(a, b)) {
1834 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1835 
1836 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1837 			return anon_vma;
1838 	}
1839 	return NULL;
1840 }
1841 
1842 /*
1843  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1844  * neighbouring vmas for a suitable anon_vma, before it goes off
1845  * to allocate a new anon_vma.  It checks because a repetitive
1846  * sequence of mprotects and faults may otherwise lead to distinct
1847  * anon_vmas being allocated, preventing vma merge in subsequent
1848  * mprotect.
1849  */
1850 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1851 {
1852 	struct anon_vma *anon_vma = NULL;
1853 	struct vm_area_struct *prev, *next;
1854 	VMA_ITERATOR(vmi, vma->vm_mm, vma->vm_end);
1855 
1856 	/* Try next first. */
1857 	next = vma_iter_load(&vmi);
1858 	if (next) {
1859 		anon_vma = reusable_anon_vma(next, vma, next);
1860 		if (anon_vma)
1861 			return anon_vma;
1862 	}
1863 
1864 	prev = vma_prev(&vmi);
1865 	VM_BUG_ON_VMA(prev != vma, vma);
1866 	prev = vma_prev(&vmi);
1867 	/* Try prev next. */
1868 	if (prev)
1869 		anon_vma = reusable_anon_vma(prev, prev, vma);
1870 
1871 	/*
1872 	 * We might reach here with anon_vma == NULL if we can't find
1873 	 * any reusable anon_vma.
1874 	 * There's no absolute need to look only at touching neighbours:
1875 	 * we could search further afield for "compatible" anon_vmas.
1876 	 * But it would probably just be a waste of time searching,
1877 	 * or lead to too many vmas hanging off the same anon_vma.
1878 	 * We're trying to allow mprotect remerging later on,
1879 	 * not trying to minimize memory used for anon_vmas.
1880 	 */
1881 	return anon_vma;
1882 }
1883 
1884 static bool vm_ops_needs_writenotify(const struct vm_operations_struct *vm_ops)
1885 {
1886 	return vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite);
1887 }
1888 
1889 static bool vma_is_shared_writable(struct vm_area_struct *vma)
1890 {
1891 	return (vma->vm_flags & (VM_WRITE | VM_SHARED)) ==
1892 		(VM_WRITE | VM_SHARED);
1893 }
1894 
1895 static bool vma_fs_can_writeback(struct vm_area_struct *vma)
1896 {
1897 	/* No managed pages to writeback. */
1898 	if (vma->vm_flags & VM_PFNMAP)
1899 		return false;
1900 
1901 	return vma->vm_file && vma->vm_file->f_mapping &&
1902 		mapping_can_writeback(vma->vm_file->f_mapping);
1903 }
1904 
1905 /*
1906  * Does this VMA require the underlying folios to have their dirty state
1907  * tracked?
1908  */
1909 bool vma_needs_dirty_tracking(struct vm_area_struct *vma)
1910 {
1911 	/* Only shared, writable VMAs require dirty tracking. */
1912 	if (!vma_is_shared_writable(vma))
1913 		return false;
1914 
1915 	/* Does the filesystem need to be notified? */
1916 	if (vm_ops_needs_writenotify(vma->vm_ops))
1917 		return true;
1918 
1919 	/*
1920 	 * Even if the filesystem doesn't indicate a need for writenotify, if it
1921 	 * can writeback, dirty tracking is still required.
1922 	 */
1923 	return vma_fs_can_writeback(vma);
1924 }
1925 
1926 /*
1927  * Some shared mappings will want the pages marked read-only
1928  * to track write events. If so, we'll downgrade vm_page_prot
1929  * to the private version (using protection_map[] without the
1930  * VM_SHARED bit).
1931  */
1932 bool vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1933 {
1934 	/* If it was private or non-writable, the write bit is already clear */
1935 	if (!vma_is_shared_writable(vma))
1936 		return false;
1937 
1938 	/* The backer wishes to know when pages are first written to? */
1939 	if (vm_ops_needs_writenotify(vma->vm_ops))
1940 		return true;
1941 
1942 	/* The open routine did something to the protections that pgprot_modify
1943 	 * won't preserve? */
1944 	if (pgprot_val(vm_page_prot) !=
1945 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vma->vm_flags)))
1946 		return false;
1947 
1948 	/*
1949 	 * Do we need to track softdirty? hugetlb does not support softdirty
1950 	 * tracking yet.
1951 	 */
1952 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1953 		return true;
1954 
1955 	/* Do we need write faults for uffd-wp tracking? */
1956 	if (userfaultfd_wp(vma))
1957 		return true;
1958 
1959 	/* Can the mapping track the dirty pages? */
1960 	return vma_fs_can_writeback(vma);
1961 }
1962 
1963 static DEFINE_MUTEX(mm_all_locks_mutex);
1964 
1965 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
1966 {
1967 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
1968 		/*
1969 		 * The LSB of head.next can't change from under us
1970 		 * because we hold the mm_all_locks_mutex.
1971 		 */
1972 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
1973 		/*
1974 		 * We can safely modify head.next after taking the
1975 		 * anon_vma->root->rwsem. If some other vma in this mm shares
1976 		 * the same anon_vma we won't take it again.
1977 		 *
1978 		 * No need of atomic instructions here, head.next
1979 		 * can't change from under us thanks to the
1980 		 * anon_vma->root->rwsem.
1981 		 */
1982 		if (__test_and_set_bit(0, (unsigned long *)
1983 				       &anon_vma->root->rb_root.rb_root.rb_node))
1984 			BUG();
1985 	}
1986 }
1987 
1988 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
1989 {
1990 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
1991 		/*
1992 		 * AS_MM_ALL_LOCKS can't change from under us because
1993 		 * we hold the mm_all_locks_mutex.
1994 		 *
1995 		 * Operations on ->flags have to be atomic because
1996 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
1997 		 * mm_all_locks_mutex, there may be other cpus
1998 		 * changing other bitflags in parallel to us.
1999 		 */
2000 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
2001 			BUG();
2002 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
2003 	}
2004 }
2005 
2006 /*
2007  * This operation locks against the VM for all pte/vma/mm related
2008  * operations that could ever happen on a certain mm. This includes
2009  * vmtruncate, try_to_unmap, and all page faults.
2010  *
2011  * The caller must take the mmap_lock in write mode before calling
2012  * mm_take_all_locks(). The caller isn't allowed to release the
2013  * mmap_lock until mm_drop_all_locks() returns.
2014  *
2015  * mmap_lock in write mode is required in order to block all operations
2016  * that could modify pagetables and free pages without need of
2017  * altering the vma layout. It's also needed in write mode to avoid new
2018  * anon_vmas to be associated with existing vmas.
2019  *
2020  * A single task can't take more than one mm_take_all_locks() in a row
2021  * or it would deadlock.
2022  *
2023  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
2024  * mapping->flags avoid to take the same lock twice, if more than one
2025  * vma in this mm is backed by the same anon_vma or address_space.
2026  *
2027  * We take locks in following order, accordingly to comment at beginning
2028  * of mm/rmap.c:
2029  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
2030  *     hugetlb mapping);
2031  *   - all vmas marked locked
2032  *   - all i_mmap_rwsem locks;
2033  *   - all anon_vma->rwseml
2034  *
2035  * We can take all locks within these types randomly because the VM code
2036  * doesn't nest them and we protected from parallel mm_take_all_locks() by
2037  * mm_all_locks_mutex.
2038  *
2039  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
2040  * that may have to take thousand of locks.
2041  *
2042  * mm_take_all_locks() can fail if it's interrupted by signals.
2043  */
2044 int mm_take_all_locks(struct mm_struct *mm)
2045 {
2046 	struct vm_area_struct *vma;
2047 	struct anon_vma_chain *avc;
2048 	VMA_ITERATOR(vmi, mm, 0);
2049 
2050 	mmap_assert_write_locked(mm);
2051 
2052 	mutex_lock(&mm_all_locks_mutex);
2053 
2054 	/*
2055 	 * vma_start_write() does not have a complement in mm_drop_all_locks()
2056 	 * because vma_start_write() is always asymmetrical; it marks a VMA as
2057 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
2058 	 * is reached.
2059 	 */
2060 	for_each_vma(vmi, vma) {
2061 		if (signal_pending(current))
2062 			goto out_unlock;
2063 		vma_start_write(vma);
2064 	}
2065 
2066 	vma_iter_init(&vmi, mm, 0);
2067 	for_each_vma(vmi, vma) {
2068 		if (signal_pending(current))
2069 			goto out_unlock;
2070 		if (vma->vm_file && vma->vm_file->f_mapping &&
2071 				is_vm_hugetlb_page(vma))
2072 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
2073 	}
2074 
2075 	vma_iter_init(&vmi, mm, 0);
2076 	for_each_vma(vmi, vma) {
2077 		if (signal_pending(current))
2078 			goto out_unlock;
2079 		if (vma->vm_file && vma->vm_file->f_mapping &&
2080 				!is_vm_hugetlb_page(vma))
2081 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
2082 	}
2083 
2084 	vma_iter_init(&vmi, mm, 0);
2085 	for_each_vma(vmi, vma) {
2086 		if (signal_pending(current))
2087 			goto out_unlock;
2088 		if (vma->anon_vma)
2089 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2090 				vm_lock_anon_vma(mm, avc->anon_vma);
2091 	}
2092 
2093 	return 0;
2094 
2095 out_unlock:
2096 	mm_drop_all_locks(mm);
2097 	return -EINTR;
2098 }
2099 
2100 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
2101 {
2102 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
2103 		/*
2104 		 * The LSB of head.next can't change to 0 from under
2105 		 * us because we hold the mm_all_locks_mutex.
2106 		 *
2107 		 * We must however clear the bitflag before unlocking
2108 		 * the vma so the users using the anon_vma->rb_root will
2109 		 * never see our bitflag.
2110 		 *
2111 		 * No need of atomic instructions here, head.next
2112 		 * can't change from under us until we release the
2113 		 * anon_vma->root->rwsem.
2114 		 */
2115 		if (!__test_and_clear_bit(0, (unsigned long *)
2116 					  &anon_vma->root->rb_root.rb_root.rb_node))
2117 			BUG();
2118 		anon_vma_unlock_write(anon_vma);
2119 	}
2120 }
2121 
2122 static void vm_unlock_mapping(struct address_space *mapping)
2123 {
2124 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2125 		/*
2126 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
2127 		 * because we hold the mm_all_locks_mutex.
2128 		 */
2129 		i_mmap_unlock_write(mapping);
2130 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
2131 					&mapping->flags))
2132 			BUG();
2133 	}
2134 }
2135 
2136 /*
2137  * The mmap_lock cannot be released by the caller until
2138  * mm_drop_all_locks() returns.
2139  */
2140 void mm_drop_all_locks(struct mm_struct *mm)
2141 {
2142 	struct vm_area_struct *vma;
2143 	struct anon_vma_chain *avc;
2144 	VMA_ITERATOR(vmi, mm, 0);
2145 
2146 	mmap_assert_write_locked(mm);
2147 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
2148 
2149 	for_each_vma(vmi, vma) {
2150 		if (vma->anon_vma)
2151 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2152 				vm_unlock_anon_vma(avc->anon_vma);
2153 		if (vma->vm_file && vma->vm_file->f_mapping)
2154 			vm_unlock_mapping(vma->vm_file->f_mapping);
2155 	}
2156 
2157 	mutex_unlock(&mm_all_locks_mutex);
2158 }
2159 
2160 /*
2161  * We account for memory if it's a private writeable mapping,
2162  * not hugepages and VM_NORESERVE wasn't set.
2163  */
2164 static bool accountable_mapping(struct file *file, vm_flags_t vm_flags)
2165 {
2166 	/*
2167 	 * hugetlb has its own accounting separate from the core VM
2168 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
2169 	 */
2170 	if (file && is_file_hugepages(file))
2171 		return false;
2172 
2173 	return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
2174 }
2175 
2176 /*
2177  * vms_abort_munmap_vmas() - Undo as much as possible from an aborted munmap()
2178  * operation.
2179  * @vms: The vma unmap structure
2180  * @mas_detach: The maple state with the detached maple tree
2181  *
2182  * Reattach any detached vmas, free up the maple tree used to track the vmas.
2183  * If that's not possible because the ptes are cleared (and vm_ops->closed() may
2184  * have been called), then a NULL is written over the vmas and the vmas are
2185  * removed (munmap() completed).
2186  */
2187 static void vms_abort_munmap_vmas(struct vma_munmap_struct *vms,
2188 		struct ma_state *mas_detach)
2189 {
2190 	struct ma_state *mas = &vms->vmi->mas;
2191 
2192 	if (!vms->nr_pages)
2193 		return;
2194 
2195 	if (vms->clear_ptes)
2196 		return reattach_vmas(mas_detach);
2197 
2198 	/*
2199 	 * Aborting cannot just call the vm_ops open() because they are often
2200 	 * not symmetrical and state data has been lost.  Resort to the old
2201 	 * failure method of leaving a gap where the MAP_FIXED mapping failed.
2202 	 */
2203 	mas_set_range(mas, vms->start, vms->end - 1);
2204 	mas_store_gfp(mas, NULL, GFP_KERNEL|__GFP_NOFAIL);
2205 	/* Clean up the insertion of the unfortunate gap */
2206 	vms_complete_munmap_vmas(vms, mas_detach);
2207 }
2208 
2209 /*
2210  * __mmap_prepare() - Prepare to gather any overlapping VMAs that need to be
2211  * unmapped once the map operation is completed, check limits, account mapping
2212  * and clean up any pre-existing VMAs.
2213  *
2214  * @map: Mapping state.
2215  * @uf:  Userfaultfd context list.
2216  *
2217  * Returns: 0 on success, error code otherwise.
2218  */
2219 static int __mmap_prepare(struct mmap_state *map, struct list_head *uf)
2220 {
2221 	int error;
2222 	struct vma_iterator *vmi = map->vmi;
2223 	struct vma_munmap_struct *vms = &map->vms;
2224 
2225 	/* Find the first overlapping VMA and initialise unmap state. */
2226 	vms->vma = vma_find(vmi, map->end);
2227 	init_vma_munmap(vms, vmi, vms->vma, map->addr, map->end, uf,
2228 			/* unlock = */ false);
2229 
2230 	/* OK, we have overlapping VMAs - prepare to unmap them. */
2231 	if (vms->vma) {
2232 		mt_init_flags(&map->mt_detach,
2233 			      vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
2234 		mt_on_stack(map->mt_detach);
2235 		mas_init(&map->mas_detach, &map->mt_detach, /* addr = */ 0);
2236 		/* Prepare to unmap any existing mapping in the area */
2237 		error = vms_gather_munmap_vmas(vms, &map->mas_detach);
2238 		if (error) {
2239 			/* On error VMAs will already have been reattached. */
2240 			vms->nr_pages = 0;
2241 			return error;
2242 		}
2243 
2244 		map->next = vms->next;
2245 		map->prev = vms->prev;
2246 	} else {
2247 		map->next = vma_iter_next_rewind(vmi, &map->prev);
2248 	}
2249 
2250 	/* Check against address space limit. */
2251 	if (!may_expand_vm(map->mm, map->flags, map->pglen - vms->nr_pages))
2252 		return -ENOMEM;
2253 
2254 	/* Private writable mapping: check memory availability. */
2255 	if (accountable_mapping(map->file, map->flags)) {
2256 		map->charged = map->pglen;
2257 		map->charged -= vms->nr_accounted;
2258 		if (map->charged) {
2259 			error = security_vm_enough_memory_mm(map->mm, map->charged);
2260 			if (error)
2261 				return error;
2262 		}
2263 
2264 		vms->nr_accounted = 0;
2265 		map->flags |= VM_ACCOUNT;
2266 	}
2267 
2268 	/*
2269 	 * Clear PTEs while the vma is still in the tree so that rmap
2270 	 * cannot race with the freeing later in the truncate scenario.
2271 	 * This is also needed for mmap_file(), which is why vm_ops
2272 	 * close function is called.
2273 	 */
2274 	vms_clean_up_area(vms, &map->mas_detach);
2275 
2276 	return 0;
2277 }
2278 
2279 
2280 static int __mmap_new_file_vma(struct mmap_state *map,
2281 			       struct vm_area_struct *vma)
2282 {
2283 	struct vma_iterator *vmi = map->vmi;
2284 	int error;
2285 
2286 	vma->vm_file = get_file(map->file);
2287 	error = mmap_file(vma->vm_file, vma);
2288 	if (error) {
2289 		fput(vma->vm_file);
2290 		vma->vm_file = NULL;
2291 
2292 		vma_iter_set(vmi, vma->vm_end);
2293 		/* Undo any partial mapping done by a device driver. */
2294 		unmap_region(&vmi->mas, vma, map->prev, map->next);
2295 
2296 		return error;
2297 	}
2298 
2299 	/* Drivers cannot alter the address of the VMA. */
2300 	WARN_ON_ONCE(map->addr != vma->vm_start);
2301 	/*
2302 	 * Drivers should not permit writability when previously it was
2303 	 * disallowed.
2304 	 */
2305 	VM_WARN_ON_ONCE(map->flags != vma->vm_flags &&
2306 			!(map->flags & VM_MAYWRITE) &&
2307 			(vma->vm_flags & VM_MAYWRITE));
2308 
2309 	/* If the flags change (and are mergeable), let's retry later. */
2310 	map->retry_merge = vma->vm_flags != map->flags && !(vma->vm_flags & VM_SPECIAL);
2311 	map->flags = vma->vm_flags;
2312 
2313 	return 0;
2314 }
2315 
2316 /*
2317  * __mmap_new_vma() - Allocate a new VMA for the region, as merging was not
2318  * possible.
2319  *
2320  * @map:  Mapping state.
2321  * @vmap: Output pointer for the new VMA.
2322  *
2323  * Returns: Zero on success, or an error.
2324  */
2325 static int __mmap_new_vma(struct mmap_state *map, struct vm_area_struct **vmap)
2326 {
2327 	struct vma_iterator *vmi = map->vmi;
2328 	int error = 0;
2329 	struct vm_area_struct *vma;
2330 
2331 	/*
2332 	 * Determine the object being mapped and call the appropriate
2333 	 * specific mapper. the address has already been validated, but
2334 	 * not unmapped, but the maps are removed from the list.
2335 	 */
2336 	vma = vm_area_alloc(map->mm);
2337 	if (!vma)
2338 		return -ENOMEM;
2339 
2340 	vma_iter_config(vmi, map->addr, map->end);
2341 	vma_set_range(vma, map->addr, map->end, map->pgoff);
2342 	vm_flags_init(vma, map->flags);
2343 	vma->vm_page_prot = vm_get_page_prot(map->flags);
2344 
2345 	if (vma_iter_prealloc(vmi, vma)) {
2346 		error = -ENOMEM;
2347 		goto free_vma;
2348 	}
2349 
2350 	if (map->file)
2351 		error = __mmap_new_file_vma(map, vma);
2352 	else if (map->flags & VM_SHARED)
2353 		error = shmem_zero_setup(vma);
2354 	else
2355 		vma_set_anonymous(vma);
2356 
2357 	if (error)
2358 		goto free_iter_vma;
2359 
2360 #ifdef CONFIG_SPARC64
2361 	/* TODO: Fix SPARC ADI! */
2362 	WARN_ON_ONCE(!arch_validate_flags(map->flags));
2363 #endif
2364 
2365 	/* Lock the VMA since it is modified after insertion into VMA tree */
2366 	vma_start_write(vma);
2367 	vma_iter_store(vmi, vma);
2368 	map->mm->map_count++;
2369 	vma_link_file(vma);
2370 
2371 	/*
2372 	 * vma_merge_new_range() calls khugepaged_enter_vma() too, the below
2373 	 * call covers the non-merge case.
2374 	 */
2375 	khugepaged_enter_vma(vma, map->flags);
2376 	ksm_add_vma(vma);
2377 	*vmap = vma;
2378 	return 0;
2379 
2380 free_iter_vma:
2381 	vma_iter_free(vmi);
2382 free_vma:
2383 	vm_area_free(vma);
2384 	return error;
2385 }
2386 
2387 /*
2388  * __mmap_complete() - Unmap any VMAs we overlap, account memory mapping
2389  *                     statistics, handle locking and finalise the VMA.
2390  *
2391  * @map: Mapping state.
2392  * @vma: Merged or newly allocated VMA for the mmap()'d region.
2393  */
2394 static void __mmap_complete(struct mmap_state *map, struct vm_area_struct *vma)
2395 {
2396 	struct mm_struct *mm = map->mm;
2397 	unsigned long vm_flags = vma->vm_flags;
2398 
2399 	perf_event_mmap(vma);
2400 
2401 	/* Unmap any existing mapping in the area. */
2402 	vms_complete_munmap_vmas(&map->vms, &map->mas_detach);
2403 
2404 	vm_stat_account(mm, vma->vm_flags, map->pglen);
2405 	if (vm_flags & VM_LOCKED) {
2406 		if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2407 					is_vm_hugetlb_page(vma) ||
2408 					vma == get_gate_vma(mm))
2409 			vm_flags_clear(vma, VM_LOCKED_MASK);
2410 		else
2411 			mm->locked_vm += map->pglen;
2412 	}
2413 
2414 	if (vma->vm_file)
2415 		uprobe_mmap(vma);
2416 
2417 	/*
2418 	 * New (or expanded) vma always get soft dirty status.
2419 	 * Otherwise user-space soft-dirty page tracker won't
2420 	 * be able to distinguish situation when vma area unmapped,
2421 	 * then new mapped in-place (which must be aimed as
2422 	 * a completely new data area).
2423 	 */
2424 	vm_flags_set(vma, VM_SOFTDIRTY);
2425 
2426 	vma_set_page_prot(vma);
2427 }
2428 
2429 unsigned long __mmap_region(struct file *file, unsigned long addr,
2430 		unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2431 		struct list_head *uf)
2432 {
2433 	struct mm_struct *mm = current->mm;
2434 	struct vm_area_struct *vma = NULL;
2435 	int error;
2436 	VMA_ITERATOR(vmi, mm, addr);
2437 	MMAP_STATE(map, mm, &vmi, addr, len, pgoff, vm_flags, file);
2438 
2439 	error = __mmap_prepare(&map, uf);
2440 	if (error)
2441 		goto abort_munmap;
2442 
2443 	/* Attempt to merge with adjacent VMAs... */
2444 	if (map.prev || map.next) {
2445 		VMG_MMAP_STATE(vmg, &map, /* vma = */ NULL);
2446 
2447 		vma = vma_merge_new_range(&vmg);
2448 	}
2449 
2450 	/* ...but if we can't, allocate a new VMA. */
2451 	if (!vma) {
2452 		error = __mmap_new_vma(&map, &vma);
2453 		if (error)
2454 			goto unacct_error;
2455 	}
2456 
2457 	/* If flags changed, we might be able to merge, so try again. */
2458 	if (map.retry_merge) {
2459 		VMG_MMAP_STATE(vmg, &map, vma);
2460 
2461 		vma_iter_config(map.vmi, map.addr, map.end);
2462 		vma_merge_existing_range(&vmg);
2463 	}
2464 
2465 	__mmap_complete(&map, vma);
2466 
2467 	return addr;
2468 
2469 	/* Accounting was done by __mmap_prepare(). */
2470 unacct_error:
2471 	if (map.charged)
2472 		vm_unacct_memory(map.charged);
2473 abort_munmap:
2474 	vms_abort_munmap_vmas(&map.vms, &map.mas_detach);
2475 	return error;
2476 }
2477