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