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