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