xref: /linux/mm/vma.c (revision d68ce4e71248e1ff5af9654b407541d9260b3ba5)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 /*
4  * VMA-specific functions.
5  */
6 
7 /*
8  * To allow for userland testing we place internal dependencies in
9  * vma_internal.h and external VMA API declarations in vma.h.
10  */
11 #include "vma_internal.h"
12 #include "vma.h"
13 
14 struct mmap_state {
15 	struct mm_struct *mm;
16 	struct vma_iterator *vmi;
17 
18 	unsigned long addr;
19 	unsigned long end;
20 	pgoff_t pgoff;
21 	pgoff_t anon_pgoff;
22 	unsigned long pglen;
23 	union {
24 		vm_flags_t vm_flags;
25 		vma_flags_t vma_flags;
26 	};
27 	struct file *file;	/* mmap()-specified file. */
28 	struct file *vm_file;	/* May be updated by mmap_prepare. */
29 	pgprot_t page_prot;
30 
31 	/* User-defined fields, perhaps updated by .mmap_prepare(). */
32 	const struct vm_operations_struct *vm_ops;
33 	void *vm_private_data;
34 
35 	unsigned long charged;
36 
37 	struct vm_area_struct *prev;
38 	struct vm_area_struct *next;
39 
40 	/* Unmapping state. */
41 	struct vma_munmap_struct vms;
42 	struct ma_state mas_detach;
43 	struct maple_tree mt_detach;
44 
45 	/* Determine if we can check KSM flags early in mmap() logic. */
46 	bool check_ksm_early :1;
47 };
48 
49 #define MMAP_STATE(name, mm_, vmi_, addr_, len_, pgoff_, anon_pgoff_, vma_flags_, file_) \
50 	struct mmap_state name = {					\
51 		.mm = mm_,						\
52 		.vmi = vmi_,						\
53 		.addr = addr_,						\
54 		.end = (addr_) + (len_),				\
55 		.pgoff = pgoff_,					\
56 		.anon_pgoff = anon_pgoff_,				\
57 		.pglen = PHYS_PFN(len_),				\
58 		.vma_flags = vma_flags_,				\
59 		.file = file_,						\
60 		.vm_file = file_,					\
61 		.page_prot = vma_flags_to_page_prot(vma_flags_),	\
62 	}
63 
64 #define VMG_MMAP_STATE(name, map_, vma_)				\
65 	struct vma_merge_struct name = {				\
66 		.mm = (map_)->mm,					\
67 		.vmi = (map_)->vmi,					\
68 		.start = (map_)->addr,					\
69 		.end = (map_)->end,					\
70 		.vma_flags = (map_)->vma_flags,				\
71 		.pgoff = (map_)->pgoff,					\
72 		.anon_pgoff = (map_)->anon_pgoff,			\
73 		.file = (map_)->vm_file,				\
74 		.prev = (map_)->prev,					\
75 		.middle = vma_,						\
76 		.next = (vma_) ? NULL : (map_)->next,			\
77 		.state = VMA_MERGE_START,				\
78 	}
79 
80 static void __vma_set_range(struct vm_area_struct *vma, unsigned long start,
81 			    unsigned long end)
82 {
83 	vma->vm_start = start;
84 	vma->vm_end = end;
85 }
86 
87 static void vma_set_range(struct vm_area_struct *vma, unsigned long start,
88 			  unsigned long end, pgoff_t pgoff, pgoff_t anon_pgoff)
89 {
90 	__vma_set_range(vma, start, end);
91 	vma_set_pgoff(vma, pgoff);
92 	vma_set_anon_pgoff(vma, anon_pgoff);
93 }
94 
95 /* Was this VMA ever forked from a parent, i.e. maybe contains CoW mappings? */
96 static bool vma_is_fork_child(struct vm_area_struct *vma)
97 {
98 	/*
99 	 * The list_is_singular() test is to avoid merging VMA cloned from
100 	 * parents. This can improve scalability caused by the anon rmap root
101 	 * lock.
102 	 */
103 	return vma && vma_has_anon_rmap(vma) &&
104 		!list_is_singular(&vma->anon_vma_chain);
105 }
106 
107 static inline bool is_mergeable_vma(struct vma_merge_struct *vmg, bool merge_next)
108 {
109 	struct vm_area_struct *vma = merge_next ? vmg->next : vmg->prev;
110 	vma_flags_t diff;
111 
112 	if (!mpol_equal(vmg->policy, vma_policy(vma)))
113 		return false;
114 
115 	diff = vma_flags_diff_pair(&vma->flags, &vmg->vma_flags);
116 	vma_flags_clear_mask(&diff, VMA_IGNORE_MERGE_FLAGS);
117 
118 	if (!vma_flags_empty(&diff))
119 		return false;
120 	if (vma->vm_file != vmg->file)
121 		return false;
122 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vmg->uffd_ctx))
123 		return false;
124 	if (!anon_vma_name_eq(anon_vma_name(vma), vmg->anon_name))
125 		return false;
126 	return true;
127 }
128 
129 static bool is_mergeable_anon_vma(struct vma_merge_struct *vmg, bool merge_next)
130 {
131 	struct vm_area_struct *tgt = merge_next ? vmg->next : vmg->prev;
132 	struct vm_area_struct *src = vmg->middle; /* existing merge case. */
133 	struct anon_vma *tgt_anon = tgt->anon_vma;
134 	struct anon_vma *src_anon = vmg->anon_vma;
135 
136 	/*
137 	 * We _can_ have !src, vmg->anon_vma via copy_vma(). In this instance we
138 	 * will remove the existing VMA's anon rmap so there's no scalability
139 	 * concerns.
140 	 */
141 	VM_WARN_ON(src && src_anon != src->anon_vma);
142 
143 	/* Case 1 - we will dup_anon_vma() from src into tgt. */
144 	if (!vma_has_anon_rmap(tgt) && src_anon) {
145 		struct vm_area_struct *copied_from = vmg->copied_from;
146 
147 		if (vma_is_fork_child(src))
148 			return false;
149 		if (vma_is_fork_child(copied_from))
150 			return false;
151 
152 		return true;
153 	}
154 	/* Case 2 - we will simply use tgt's anon rmap. */
155 	if (vma_has_anon_rmap(tgt) && !src_anon)
156 		return !vma_is_fork_child(tgt);
157 	/* Case 3 - src and tgt already share an anon rmap. */
158 	return src_anon == tgt_anon;
159 }
160 
161 /*
162  * init_multi_vma_prep() - Initializer for struct vma_prepare
163  * @vp: The vma_prepare struct
164  * @vma: The vma that will be altered once locked
165  * @vmg: The merge state that will be used to determine adjustment and VMA
166  *       removal.
167  */
168 static void init_multi_vma_prep(struct vma_prepare *vp,
169 				struct vm_area_struct *vma,
170 				struct vma_merge_struct *vmg)
171 {
172 	struct vm_area_struct *adjust;
173 	struct vm_area_struct **remove = &vp->remove;
174 
175 	memset(vp, 0, sizeof(struct vma_prepare));
176 	vp->vma = vma;
177 	vp->anon_vma = vma->anon_vma;
178 
179 	if (vmg && vmg->__remove_middle) {
180 		*remove = vmg->middle;
181 		remove = &vp->remove2;
182 	}
183 	if (vmg && vmg->__remove_next)
184 		*remove = vmg->next;
185 
186 	if (vmg && vmg->__adjust_middle_start)
187 		adjust = vmg->middle;
188 	else if (vmg && vmg->__adjust_next_start)
189 		adjust = vmg->next;
190 	else
191 		adjust = NULL;
192 
193 	vp->adj_next = adjust;
194 	if (!vma_has_anon_rmap(vma) && adjust)
195 		vp->anon_vma = adjust->anon_vma;
196 
197 	VM_WARN_ON(vma_has_anon_rmap(vma) && adjust && vma_has_anon_rmap(adjust) &&
198 		   vp->anon_vma != adjust->anon_vma);
199 
200 	vp->file = vma->vm_file;
201 	if (vp->file)
202 		vp->mapping = vma->vm_file->f_mapping;
203 
204 	if (!vmg)
205 		return;
206 
207 	if (vmg->skip_vma_uprobe)
208 		vp->skip_vma_uprobe = true;
209 	if (vma_start_pgoff(vma) == vmg_start_pgoff(vmg))
210 		vp->file_pgoff_unchanged = true;
211 	if (vma_start_anon_pgoff(vma) == vmg_start_anon_pgoff(vmg))
212 		vp->anon_pgoff_unchanged = true;
213 }
214 
215 /*
216  * Does this merge require that adjacent VMAs must have adjacent anonymous page
217  * offsets in addition to having adjacent vma->vm_pgoff?
218  *
219  * This is only required for MAP_PRIVATE-file backed mappings as the page offset
220  * for pure anonymous VMAs is equal to the anonymous page offset.
221  *
222  * Read-only shared mappings (with VMA_SHARED_BIT cleared) are always unfaulted
223  * so automatically have correct anonymous page offset (as it is always updated
224  * on remap).
225  *
226  * 'Special' mappings in the sense of VDSO, VVAR etc. have !file but would in
227  * any case not be candidates for merge nor be mergeable.
228  */
229 static bool needs_adjacent_anon_pgoff(const struct vma_merge_struct *vmg)
230 {
231 	return vmg->file && vma_flags_is_cow_mapping(&vmg->vma_flags);
232 }
233 
234 /*
235  * Return true if we can merge this (vma_flags,anon_vma,file,vm_pgoff)
236  * in front of (at a lower virtual address and file offset than) the vma.
237  *
238  * We cannot merge two vmas if they have differently assigned anon rmaps,
239  * nor if the same anon rmap is assigned but offsets incompatible.
240  *
241  * We don't check here for the merged mmap wrapping around the end of pagecache
242  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
243  * wrap, nor mmaps which cover the final page at index -1UL.
244  *
245  * We assume the vma may be removed as part of the merge.
246  */
247 static bool can_vma_merge_before(struct vma_merge_struct *vmg)
248 {
249 	if (!is_mergeable_vma(vmg, /* merge_next = */ true))
250 		return false;
251 	if (!is_mergeable_anon_vma(vmg, /* merge_next = */ true))
252 		return false;
253 	if (vmg_end_pgoff(vmg) != vma_start_pgoff(vmg->next))
254 		return false;
255 	if (needs_adjacent_anon_pgoff(vmg) &&
256 	    vmg_end_anon_pgoff(vmg) != vma_start_anon_pgoff(vmg->next))
257 		return false;
258 	return true;
259 }
260 
261 /*
262  * Return true if we can merge this (vma_flags,anon_vma,file,vm_pgoff)
263  * beyond (at a higher virtual address and file offset than) the vma.
264  *
265  * We cannot merge two vmas if they have differently assigned anon rmaps,
266  * nor if the same anon rmap is assigned but offsets incompatible.
267  *
268  * We assume that vma is not removed as part of the merge.
269  */
270 static bool can_vma_merge_after(struct vma_merge_struct *vmg)
271 {
272 	if (!is_mergeable_vma(vmg, /* merge_next = */ false))
273 		return false;
274 	if (!is_mergeable_anon_vma(vmg, /* merge_next = */ false))
275 		return false;
276 	if (vma_end_pgoff(vmg->prev) != vmg_start_pgoff(vmg))
277 		return false;
278 	if (needs_adjacent_anon_pgoff(vmg) &&
279 	    vma_end_anon_pgoff(vmg->prev) != vmg_start_anon_pgoff(vmg))
280 		return false;
281 	return true;
282 }
283 
284 static void __vma_link_file(struct vm_area_struct *vma,
285 			    struct address_space *mapping)
286 {
287 	if (vma_is_shared_maywrite(vma))
288 		mapping_allow_writable(mapping);
289 
290 	flush_dcache_mmap_lock(mapping);
291 	mapping_rmap_tree_insert(vma, mapping);
292 	flush_dcache_mmap_unlock(mapping);
293 }
294 
295 /*
296  * Requires inode->i_mapping->i_mmap_rwsem
297  */
298 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
299 				      struct address_space *mapping)
300 {
301 	if (vma_is_shared_maywrite(vma))
302 		mapping_unmap_writable(mapping);
303 
304 	flush_dcache_mmap_lock(mapping);
305 	mapping_rmap_tree_remove(vma, mapping);
306 	flush_dcache_mmap_unlock(mapping);
307 }
308 
309 /*
310  * vma_prepare() - Helper function for handling locking VMAs prior to altering
311  * @vp: The initialized vma_prepare struct
312  */
313 static void vma_prepare(struct vma_prepare *vp)
314 {
315 	if (vp->file) {
316 		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
317 
318 		if (vp->adj_next)
319 			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
320 				      vp->adj_next->vm_end);
321 
322 		i_mmap_lock_write(vp->mapping);
323 		if (vp->insert && vp->insert->vm_file) {
324 			/*
325 			 * Put into interval tree now, so instantiated pages
326 			 * are visible to arm/parisc __flush_dcache_page
327 			 * throughout; but we cannot insert into address
328 			 * space until vma start or end is updated.
329 			 */
330 			__vma_link_file(vp->insert,
331 					vp->insert->vm_file->f_mapping);
332 		}
333 	}
334 
335 	if (vp->anon_vma) {
336 		anon_vma_lock_write(vp->anon_vma);
337 		anon_rmap_tree_pre_update_vma(vp->vma, vp->anon_pgoff_unchanged);
338 		/* The adjacent VMA's start is moved, so its page offset changes. */
339 		if (vp->adj_next)
340 			anon_rmap_tree_pre_update_vma(vp->adj_next, false);
341 	}
342 
343 	if (vp->file) {
344 		flush_dcache_mmap_lock(vp->mapping);
345 		mapping_rmap_tree_pre_update(vp->vma, vp->mapping,
346 					     vp->file_pgoff_unchanged);
347 		if (vp->adj_next)
348 			mapping_rmap_tree_pre_update(vp->adj_next, vp->mapping,
349 						     false);
350 	}
351 
352 }
353 
354 /*
355  * vma_complete- Helper function for handling the unlocking after altering VMAs,
356  * or for inserting a VMA.
357  *
358  * @vp: The vma_prepare struct
359  * @vmi: The vma iterator
360  * @mm: The mm_struct
361  */
362 static void vma_complete(struct vma_prepare *vp, struct vma_iterator *vmi,
363 			 struct mm_struct *mm)
364 {
365 	if (vp->file) {
366 		if (vp->adj_next)
367 			mapping_rmap_tree_post_update(vp->adj_next, vp->mapping,
368 						      false);
369 		mapping_rmap_tree_post_update(vp->vma, vp->mapping,
370 					      vp->file_pgoff_unchanged);
371 		flush_dcache_mmap_unlock(vp->mapping);
372 	}
373 
374 	if (vp->remove && vp->file) {
375 		__remove_shared_vm_struct(vp->remove, vp->mapping);
376 		if (vp->remove2)
377 			__remove_shared_vm_struct(vp->remove2, vp->mapping);
378 	} else if (vp->insert) {
379 		/*
380 		 * split_vma has split insert from vma, and needs
381 		 * us to insert it before dropping the locks
382 		 * (it may either follow vma or precede it).
383 		 */
384 		vma_iter_store_new(vmi, vp->insert);
385 		mm->map_count++;
386 	}
387 
388 	if (vp->anon_vma) {
389 		anon_rmap_tree_post_update_vma(vp->vma, vp->anon_pgoff_unchanged);
390 		if (vp->adj_next)
391 			anon_rmap_tree_post_update_vma(vp->adj_next, false);
392 		anon_vma_unlock_write(vp->anon_vma);
393 	}
394 
395 	if (vp->file) {
396 		i_mmap_unlock_write(vp->mapping);
397 
398 		if (!vp->skip_vma_uprobe) {
399 			uprobe_mmap(vp->vma);
400 
401 			if (vp->adj_next)
402 				uprobe_mmap(vp->adj_next);
403 		}
404 	}
405 
406 	if (vp->remove) {
407 again:
408 		vma_mark_detached(vp->remove);
409 		if (vp->file) {
410 			uprobe_munmap(vp->remove, vp->remove->vm_start,
411 				      vp->remove->vm_end);
412 			fput(vp->file);
413 		}
414 		if (vma_has_anon_rmap(vp->remove))
415 			unlink_anon_vmas(vp->remove);
416 		mm->map_count--;
417 		mpol_put(vma_policy(vp->remove));
418 		if (!vp->remove2)
419 			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
420 		vm_area_free(vp->remove);
421 
422 		/*
423 		 * In mprotect's case 6 (see comments on vma_merge),
424 		 * we are removing both mid and next vmas
425 		 */
426 		if (vp->remove2) {
427 			vp->remove = vp->remove2;
428 			vp->remove2 = NULL;
429 			goto again;
430 		}
431 	}
432 	if (vp->insert && vp->file)
433 		uprobe_mmap(vp->insert);
434 }
435 
436 /*
437  * init_vma_prep() - Initializer wrapper for vma_prepare struct
438  * @vp: The vma_prepare struct
439  * @vma: The vma that will be altered once locked
440  */
441 static void init_vma_prep(struct vma_prepare *vp, struct vm_area_struct *vma)
442 {
443 	init_multi_vma_prep(vp, vma, NULL);
444 }
445 
446 /*
447  * Can the proposed VMA be merged with the left (previous) VMA taking into
448  * account the start position of the proposed range.
449  */
450 static bool can_vma_merge_left(struct vma_merge_struct *vmg)
451 
452 {
453 	return vmg->prev && vmg->prev->vm_end == vmg->start &&
454 		can_vma_merge_after(vmg);
455 }
456 
457 /*
458  * Can the proposed VMA be merged with the right (next) VMA taking into
459  * account the end position of the proposed range.
460  *
461  * In addition, if we can merge with the left VMA, ensure that left and right
462  * anon rmaps are also compatible.
463  */
464 static bool can_vma_merge_right(struct vma_merge_struct *vmg,
465 				bool can_merge_left)
466 {
467 	struct vm_area_struct *next = vmg->next;
468 	struct vm_area_struct *prev;
469 
470 	if (!next || vmg->end != next->vm_start || !can_vma_merge_before(vmg))
471 		return false;
472 
473 	if (!can_merge_left)
474 		return true;
475 
476 	/*
477 	 * If we can merge with prev (left) and next (right), indicating that
478 	 * each VMA's anon rmap is compatible with the proposed anon rmap, this
479 	 * does not mean prev and next are compatible with EACH OTHER.
480 	 *
481 	 * We therefore check this in addition to mergeability to either side.
482 	 */
483 	prev = vmg->prev;
484 	return !vma_has_anon_rmap(prev) || !vma_has_anon_rmap(next) ||
485 		prev->anon_vma == next->anon_vma;
486 }
487 
488 /*
489  * Close a vm structure and free it.
490  */
491 void remove_vma(struct vm_area_struct *vma)
492 {
493 	might_sleep();
494 	vma_close(vma);
495 	if (vma->vm_file)
496 		fput(vma->vm_file);
497 	mpol_put(vma_policy(vma));
498 	vm_area_free(vma);
499 }
500 
501 /*
502  * Get rid of page table information in the indicated region.
503  *
504  * Called with the mm semaphore held.
505  */
506 void unmap_region(struct unmap_desc *unmap)
507 {
508 	struct mm_struct *mm = unmap->first->vm_mm;
509 	struct mmu_gather tlb;
510 
511 	tlb_gather_mmu(&tlb, mm);
512 	update_hiwater_rss(mm);
513 	unmap_vmas(&tlb, unmap);
514 	mas_set(unmap->mas, unmap->tree_reset);
515 	free_pgtables(&tlb, unmap);
516 	tlb_finish_mmu(&tlb);
517 }
518 
519 static int check_split(struct vm_area_struct *vma, unsigned long addr)
520 {
521 	if (!vma->vm_ops)
522 		return 0;
523 	if (!vma->vm_ops->may_split)
524 		return 0;
525 	return vma->vm_ops->may_split(vma, addr);
526 }
527 
528 /*
529  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
530  * has already been checked or doesn't make sense to fail.
531  * VMA Iterator will point to the original VMA.
532  */
533 static __must_check int
534 __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
535 	    unsigned long addr, int new_below)
536 {
537 	struct vma_prepare vp;
538 	struct vm_area_struct *new;
539 	int err;
540 
541 	WARN_ON(vma->vm_start >= addr);
542 	WARN_ON(vma->vm_end <= addr);
543 
544 	err = check_split(vma, addr);
545 	if (err)
546 		return err;
547 
548 	vma_start_write(vma);
549 	new = vm_area_dup(vma);
550 	if (!new)
551 		return -ENOMEM;
552 
553 	if (new_below) {
554 		new->vm_end = addr;
555 	} else {
556 		new->vm_start = addr;
557 		vma_add_pgoff(new, linear_page_delta(vma, addr));
558 	}
559 
560 	err = -ENOMEM;
561 	vma_iter_config(vmi, new->vm_start, new->vm_end);
562 	if (vma_iter_prealloc(vmi, new))
563 		goto out_free_vma;
564 
565 	err = vma_dup_policy(vma, new);
566 	if (err)
567 		goto out_free_vmi;
568 
569 	err = anon_vma_clone(new, vma, VMA_OP_SPLIT);
570 	if (err)
571 		goto out_free_mpol;
572 
573 	if (new->vm_file)
574 		get_file(new->vm_file);
575 
576 	if (new->vm_ops && new->vm_ops->open)
577 		new->vm_ops->open(new);
578 
579 	vma_start_write(new);
580 
581 	init_vma_prep(&vp, vma);
582 	vp.insert = new;
583 	vp.file_pgoff_unchanged = !new_below;
584 	vp.anon_pgoff_unchanged = !new_below;
585 	vma_prepare(&vp);
586 
587 	/*
588 	 * Get rid of huge pages and shared page tables straddling the split
589 	 * boundary.
590 	 */
591 	vma_adjust_trans_huge(vma, vma->vm_start, addr, NULL);
592 	if (vma_is_hugetlb(vma))
593 		hugetlb_split(vma, addr);
594 
595 	if (new_below) {
596 		vma->vm_start = addr;
597 		vma_add_pgoff(vma, linear_page_delta(new, addr));
598 	} else {
599 		vma->vm_end = addr;
600 	}
601 
602 	/* vma_complete stores the new vma */
603 	vma_complete(&vp, vmi, vma->vm_mm);
604 	validate_mm(vma->vm_mm);
605 
606 	/* Success. */
607 	if (new_below)
608 		vma_next(vmi);
609 	else
610 		vma_prev(vmi);
611 
612 	return 0;
613 
614 out_free_mpol:
615 	mpol_put(vma_policy(new));
616 out_free_vmi:
617 	vma_iter_free(vmi);
618 out_free_vma:
619 	vm_area_free(new);
620 	return err;
621 }
622 
623 /*
624  * Split a vma into two pieces at address 'addr', a new vma is allocated
625  * either for the first part or the tail.
626  */
627 int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
628 	      unsigned long addr, int new_below)
629 {
630 	if (vma->vm_mm->map_count >= get_sysctl_max_map_count())
631 		return -ENOMEM;
632 
633 	return __split_vma(vmi, vma, addr, new_below);
634 }
635 
636 /*
637  * dup_anon_vma() - Helper function to duplicate the anon rmap on VMA merge in
638  * the instance that the destination VMA has no anon rmap but the source does.
639  *
640  * @dst: The destination VMA
641  * @src: The source VMA
642  * @dup: Pointer to the destination VMA when successful.
643  *
644  * Returns: 0 on success.
645  */
646 static int dup_anon_vma(struct vm_area_struct *dst,
647 			struct vm_area_struct *src, struct vm_area_struct **dup)
648 {
649 	/*
650 	 * There are three cases to consider for correctly propagating
651 	 * anon rmaps on merge.
652 	 *
653 	 * The first is trivial - neither VMA has an anon rmap, we need not do
654 	 * anything.
655 	 *
656 	 * The second where both have an anon rmap is also a no-op, as they must
657 	 * then be the same, so there is simply nothing to copy.
658 	 *
659 	 * Here we cover the third - if the destination VMA has no anon rmap,
660 	 * that is it is unfaulted, we need to ensure that the newly merged
661 	 * range is referenced by the anon rmap of the source.
662 	 */
663 	if (vma_has_anon_rmap(src) && !vma_has_anon_rmap(dst)) {
664 		int ret;
665 
666 		vma_assert_write_locked(dst);
667 		dst->anon_vma = src->anon_vma;
668 		ret = anon_vma_clone(dst, src, VMA_OP_MERGE_UNFAULTED);
669 		if (ret)
670 			return ret;
671 
672 		*dup = dst;
673 	}
674 
675 	return 0;
676 }
677 
678 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
679 void validate_mm(struct mm_struct *mm)
680 {
681 	int bug = 0;
682 	int i = 0;
683 	struct vm_area_struct *vma;
684 	VMA_ITERATOR(vmi, mm, 0);
685 
686 	mt_validate(&mm->mm_mt);
687 	for_each_vma(vmi, vma) {
688 #ifdef CONFIG_DEBUG_VM_RB
689 		struct anon_vma *anon_vma = vma->anon_vma;
690 		struct anon_vma_chain *avc;
691 #endif
692 		unsigned long vmi_start, vmi_end;
693 		bool warn = 0;
694 
695 		vmi_start = vma_iter_addr(&vmi);
696 		vmi_end = vma_iter_end(&vmi);
697 		if (VM_WARN_ON_ONCE_MM(vma->vm_end != vmi_end, mm))
698 			warn = 1;
699 
700 		if (VM_WARN_ON_ONCE_MM(vma->vm_start != vmi_start, mm))
701 			warn = 1;
702 
703 		if (warn) {
704 			pr_emerg("issue in %s\n", current->comm);
705 			dump_stack();
706 			dump_vma(vma);
707 			pr_emerg("tree range: %px start %lx end %lx\n", vma,
708 				 vmi_start, vmi_end - 1);
709 			vma_iter_dump_tree(&vmi);
710 		}
711 
712 #ifdef CONFIG_DEBUG_VM_RB
713 		if (vma_has_anon_rmap(vma)) {
714 			anon_vma_lock_read(anon_vma);
715 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
716 				anon_rmap_tree_verify(avc);
717 			anon_vma_unlock_read(anon_vma);
718 		}
719 #endif
720 		/* Check for a infinite loop */
721 		if (++i > mm->map_count + 10) {
722 			i = -1;
723 			break;
724 		}
725 	}
726 	if (i != mm->map_count) {
727 		pr_emerg("map_count %d vma iterator %d\n", mm->map_count, i);
728 		bug = 1;
729 	}
730 	VM_BUG_ON_MM(bug, mm);
731 }
732 #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
733 
734 /*
735  * Based on the vmg flag indicating whether we need to adjust the vm_start field
736  * for the middle or next VMA, we calculate what the range of the newly adjusted
737  * VMA ought to be, and set the VMA's range accordingly.
738  */
739 static void vmg_adjust_set_range(struct vma_merge_struct *vmg)
740 {
741 	if (vmg->__adjust_middle_start) {
742 		/*
743 		 * vmg->start    vmg->end
744 		 * |             |
745 		 * v    merge    v
746 		 * <------------->
747 		 *         delta
748 		 *        <------>
749 		 * |------|----------------|
750 		 * | prev |    middle      |
751 		 * |------|----------------|
752 		 *        ^
753 		 *        |
754 		 *        middle->vm_start
755 		 */
756 		struct vm_area_struct *middle = vmg->middle;
757 		const unsigned long delta = vmg->end - middle->vm_start;
758 
759 		__vma_set_range(middle, vmg->end, middle->vm_end);
760 		vma_add_pgoff(middle, delta >> PAGE_SHIFT);
761 	} else if (vmg->__adjust_next_start) {
762 		/*
763 		 *                Originally:
764 		 *
765 		 *            vmg->start   vmg->end
766 		 *            |            |
767 		 *            v    merge   v
768 		 *            <------------>
769 		 *            .            .
770 		 * merge_existing_range() updates to:
771 		 *            .            .
772 		 * vmg->start vmg->end     .
773 		 * |          |            .
774 		 * v  retain  v            .
775 		 * <---------->            .
776 		 *             delta       .
777 		 *            <----->      .
778 		 * |----------------|------|
779 		 * |    middle      | next |
780 		 * |----------------|------|
781 		 *                  ^
782 		 *                  |
783 		 *                  next->vm_start
784 		 */
785 		struct vm_area_struct *next = vmg->next;
786 		const unsigned long delta = next->vm_start - vmg->end;
787 
788 		__vma_set_range(next, vmg->end, next->vm_end);
789 		vma_sub_pgoff(next, delta >> PAGE_SHIFT);
790 	}
791 }
792 
793 static void propagate_sticky_flags(struct vma_merge_struct *vmg,
794 		const struct vm_area_struct *vma)
795 {
796 	const vma_flags_t sticky =
797 		vma_flags_and_mask(&vma->flags, VMA_STICKY_FLAGS);
798 
799 	/* Write lock prevents concurrent atomic VMA flag updates. */
800 	vma_assert_write_locked(vma);
801 	vma_flags_set_mask(&vmg->vma_flags, sticky);
802 }
803 
804 static void commit_sticky_flags(struct vma_merge_struct *vmg)
805 {
806 	const vma_flags_t sticky =
807 		vma_flags_and_mask(&vmg->vma_flags, VMA_STICKY_FLAGS);
808 	struct vm_area_struct *target = vmg->target;
809 
810 	vma_assert_write_locked(target);
811 	vma_set_flags_mask(target, sticky);
812 }
813 
814 /*
815  * Actually perform the VMA merge operation.
816  *
817  * IMPORTANT: We guarantee that, should vmg->give_up_on_oom is set, to not
818  * modify any VMAs or cause inconsistent state should an OOM condition arise.
819  *
820  * Returns 0 on success, or an error value on failure.
821  */
822 static int commit_merge(struct vma_merge_struct *vmg)
823 {
824 	struct vm_area_struct *vma;
825 	struct vma_prepare vp;
826 
827 	if (vmg->__adjust_next_start) {
828 		/* We manipulate middle and adjust next, which is the target. */
829 		vma = vmg->middle;
830 		vma_iter_config(vmg->vmi, vmg->end, vmg->next->vm_end);
831 	} else {
832 		vma = vmg->target;
833 		 /* Note: vma iterator must be pointing to 'start'. */
834 		vma_iter_config(vmg->vmi, vmg->start, vmg->end);
835 	}
836 
837 	init_multi_vma_prep(&vp, vma, vmg);
838 
839 	/*
840 	 * If vmg->give_up_on_oom is set, we're safe, because we don't actually
841 	 * manipulate any VMAs until we succeed at preallocation.
842 	 *
843 	 * Past this point, we will not return an error.
844 	 */
845 	if (vma_iter_prealloc(vmg->vmi, vma))
846 		return -ENOMEM;
847 
848 	vma_prepare(&vp);
849 	/* Must be made visible before vma_complete() for rmap walkers. */
850 	commit_sticky_flags(vmg);
851 	/*
852 	 * THP pages may need to do additional splits if we increase
853 	 * middle->vm_start.
854 	 */
855 	vma_adjust_trans_huge(vma, vmg->start, vmg->end,
856 			      vmg->__adjust_middle_start ? vmg->middle : NULL);
857 	vma_set_range(vma, vmg->start, vmg->end, vmg_start_pgoff(vmg),
858 		      vmg_start_anon_pgoff(vmg));
859 	vmg_adjust_set_range(vmg);
860 	vma_iter_store_overwrite(vmg->vmi, vmg->target);
861 
862 	vma_complete(&vp, vmg->vmi, vma->vm_mm);
863 
864 	return 0;
865 }
866 
867 /* We can only remove VMAs when merging if they do not have a close hook. */
868 static bool can_merge_remove_vma(struct vm_area_struct *vma)
869 {
870 	return !vma->vm_ops || !vma->vm_ops->close;
871 }
872 
873 /*
874  * vma_merge_existing_range - Attempt to merge VMAs based on a VMA having its
875  * attributes modified.
876  *
877  * @vmg: Describes the modifications being made to a VMA and associated
878  *       metadata.
879  *
880  * When the attributes of a range within a VMA change, then it might be possible
881  * for immediately adjacent VMAs to be merged into that VMA due to having
882  * identical properties.
883  *
884  * This function checks for the existence of any such mergeable VMAs and updates
885  * the maple tree describing the @vmg->middle->vm_mm address space to account
886  * for this, as well as any VMAs shrunk/expanded/deleted as a result of this
887  * merge.
888  *
889  * As part of this operation, if a merge occurs, the @vmg object will have its
890  * vma, start, end, pgoff and vma_flags fields modified to execute the merge.
891  * Subsequent calls to this function should reset these fields.
892  *
893  * Returns: The merged VMA if merge succeeds, or NULL otherwise.
894  *
895  * ASSUMPTIONS:
896  * - The caller must assign the VMA to be modified to @vmg->middle.
897  * - The caller must have set @vmg->prev to the previous VMA, if there is one.
898  * - The caller must not set @vmg->next, as we determine this.
899  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
900  * - vmi must be positioned within [@vmg->middle->vm_start, @vmg->middle->vm_end).
901  */
902 static __must_check struct vm_area_struct *vma_merge_existing_range(
903 		struct vma_merge_struct *vmg)
904 {
905 	struct vm_area_struct *middle = vmg->middle;
906 	struct vm_area_struct *prev = vmg->prev;
907 	struct vm_area_struct *next;
908 	struct vm_area_struct *anon_dup = NULL;
909 	unsigned long start = vmg->start;
910 	unsigned long end = vmg->end;
911 	bool left_side = middle && start == middle->vm_start;
912 	bool right_side = middle && end == middle->vm_end;
913 	int err = 0;
914 	bool merge_left, merge_right, merge_both;
915 
916 	mmap_assert_write_locked(vmg->mm);
917 	VM_WARN_ON_VMG(!middle, vmg); /* We are modifying a VMA, so caller must specify. */
918 	VM_WARN_ON_VMG(vmg->next, vmg); /* We set this. */
919 	VM_WARN_ON_VMG(prev && start <= prev->vm_start, vmg);
920 	VM_WARN_ON_VMG(start >= end, vmg);
921 
922 	/*
923 	 * If middle == prev, then we are offset into a VMA. Otherwise, if we are
924 	 * not, we must span a portion of the VMA.
925 	 */
926 	VM_WARN_ON_VMG(middle &&
927 		       ((middle != prev && vmg->start != middle->vm_start) ||
928 			vmg->end > middle->vm_end), vmg);
929 	/* The vmi must be positioned within vmg->middle. */
930 	VM_WARN_ON_VMG(middle &&
931 		       !(vma_iter_addr(vmg->vmi) >= middle->vm_start &&
932 			 vma_iter_addr(vmg->vmi) < middle->vm_end), vmg);
933 	/* An existing merge can never be used by the mremap() logic. */
934 	VM_WARN_ON_VMG(vmg->copied_from, vmg);
935 
936 	vmg->state = VMA_MERGE_NOMERGE;
937 
938 	if (!vma_flags_can_merge(&vmg->vma_flags))
939 		return NULL;
940 	/*
941 	 * If the range being modified is neither at the furthermost left or
942 	 * right side of the VMA, then we have no chance of merging and should
943 	 * abort.
944 	 */
945 	if (!left_side && !right_side)
946 		return NULL;
947 
948 	if (left_side)
949 		merge_left = can_vma_merge_left(vmg);
950 	else
951 		merge_left = false;
952 
953 	if (right_side) {
954 		next = vmg->next = vma_iter_next_range(vmg->vmi);
955 		vma_iter_prev_range(vmg->vmi);
956 
957 		merge_right = can_vma_merge_right(vmg, merge_left);
958 	} else {
959 		merge_right = false;
960 		next = NULL;
961 	}
962 
963 	if (merge_left)		/* If merging prev, position iterator there. */
964 		vma_prev(vmg->vmi);
965 	else if (!merge_right)	/* If we have nothing to merge, abort. */
966 		return NULL;
967 
968 	merge_both = merge_left && merge_right;
969 	/* If we span the entire VMA, a merge implies it will be deleted. */
970 	vmg->__remove_middle = left_side && right_side;
971 
972 	/*
973 	 * If we need to remove middle in its entirety but are unable to do so,
974 	 * we have no sensible recourse but to abort the merge.
975 	 */
976 	if (vmg->__remove_middle && !can_merge_remove_vma(middle))
977 		return NULL;
978 
979 	/* If middle isn't removed then it's resized, i.e. splits. */
980 	if (!vmg->__remove_middle && check_split(middle, left_side ? end : start))
981 		return NULL;
982 
983 	/*
984 	 * If we merge both VMAs, then next is also deleted. This implies
985 	 * merge_will_delete_vma also.
986 	 */
987 	vmg->__remove_next = merge_both;
988 
989 	/*
990 	 * If we cannot delete next, then we can reduce the operation to merging
991 	 * prev and middle (thereby deleting middle).
992 	 */
993 	if (vmg->__remove_next && !can_merge_remove_vma(next)) {
994 		vmg->__remove_next = false;
995 		merge_right = false;
996 		merge_both = false;
997 	}
998 
999 	/* No matter what happens, we will be adjusting middle. */
1000 	vma_start_write(middle);
1001 	propagate_sticky_flags(vmg, middle);
1002 
1003 	if (merge_right) {
1004 		vma_start_write(next);
1005 		vmg->target = next;
1006 		propagate_sticky_flags(vmg, next);
1007 	}
1008 
1009 	if (merge_left) {
1010 		vma_start_write(prev);
1011 		vmg->target = prev;
1012 		propagate_sticky_flags(vmg, prev);
1013 	}
1014 
1015 	if (merge_both) {
1016 		/*
1017 		 * |<-------------------->|
1018 		 * |-------********-------|
1019 		 *   prev   middle   next
1020 		 *  extend  delete  delete
1021 		 */
1022 		vmg->start = prev->vm_start;
1023 		vmg->end = next->vm_end;
1024 		vmg->pgoff = vma_start_pgoff(prev);
1025 		vmg->anon_pgoff = vma_start_anon_pgoff(prev);
1026 
1027 		/*
1028 		 * We already ensured anon rmap compatibility above, so now it's
1029 		 * simply a case of, if prev has no anon rmap, which of next or
1030 		 * middle contains the anon rmap we must duplicate.
1031 		 */
1032 		err = dup_anon_vma(prev, vma_has_anon_rmap(next) ? next : middle,
1033 				   &anon_dup);
1034 	} else if (merge_left) {
1035 		/*
1036 		 * |<------------>|      OR
1037 		 * |<----------------->|
1038 		 * |-------*************
1039 		 *   prev     middle
1040 		 *  extend shrink/delete
1041 		 */
1042 		vmg->start = prev->vm_start;
1043 		vmg->pgoff = vma_start_pgoff(prev);
1044 		vmg->anon_pgoff = vma_start_anon_pgoff(prev);
1045 
1046 		if (!vmg->__remove_middle)
1047 			vmg->__adjust_middle_start = true;
1048 
1049 		err = dup_anon_vma(prev, middle, &anon_dup);
1050 	} else { /* merge_right */
1051 		/*
1052 		 *     |<------------->| OR
1053 		 * |<----------------->|
1054 		 * *************-------|
1055 		 *    middle     next
1056 		 * shrink/delete extend
1057 		 */
1058 		const pgoff_t pglen = vmg_pages(vmg);
1059 
1060 		VM_WARN_ON_VMG(!merge_right, vmg);
1061 		/* If we are offset into a VMA, then prev must be middle. */
1062 		VM_WARN_ON_VMG(vmg->start > middle->vm_start && prev && middle != prev, vmg);
1063 
1064 		if (vmg->__remove_middle) {
1065 			vmg->end = next->vm_end;
1066 			vmg->pgoff = vma_start_pgoff(next) - pglen;
1067 			vmg->anon_pgoff = vma_start_anon_pgoff(next) - pglen;
1068 		} else {
1069 			/* We shrink middle and expand next. */
1070 			vmg->__adjust_next_start = true;
1071 			vmg->start = middle->vm_start;
1072 			vmg->end = start;
1073 			vmg->pgoff = vma_start_pgoff(middle);
1074 			vmg->anon_pgoff = vma_start_anon_pgoff(middle);
1075 		}
1076 
1077 		err = dup_anon_vma(next, middle, &anon_dup);
1078 	}
1079 
1080 	if (err || commit_merge(vmg))
1081 		goto abort;
1082 
1083 	khugepaged_enter_vma(vmg->target, vmg->vm_flags);
1084 	vmg->state = VMA_MERGE_SUCCESS;
1085 	return vmg->target;
1086 
1087 abort:
1088 	vma_iter_set(vmg->vmi, start);
1089 	vma_iter_load(vmg->vmi);
1090 
1091 	if (anon_dup)
1092 		unlink_anon_vmas(anon_dup);
1093 
1094 	/*
1095 	 * This means we have failed to clone the anon rmap correctly, but no
1096 	 * actual changes to VMAs have occurred, so no harm no foul - if the
1097 	 * user doesn't want this reported and instead just wants to give up on
1098 	 * the merge, allow it.
1099 	 */
1100 	if (!vmg->give_up_on_oom)
1101 		vmg->state = VMA_MERGE_ERROR_NOMEM;
1102 	return NULL;
1103 }
1104 
1105 /*
1106  * vma_merge_new_range - Attempt to merge a new VMA into address space
1107  *
1108  * @vmg: Describes the VMA we are adding, in the range @vmg->start to @vmg->end
1109  *       (exclusive), which we try to merge with any adjacent VMAs if possible.
1110  *
1111  * We are about to add a VMA to the address space starting at @vmg->start and
1112  * ending at @vmg->end. There are three different possible scenarios:
1113  *
1114  * 1. There is a VMA with identical properties immediately adjacent to the
1115  *    proposed new VMA [@vmg->start, @vmg->end) either before or after it -
1116  *    EXPAND that VMA:
1117  *
1118  * Proposed:       |-----|  or  |-----|
1119  * Existing:  |----|                  |----|
1120  *
1121  * 2. There are VMAs with identical properties immediately adjacent to the
1122  *    proposed new VMA [@vmg->start, @vmg->end) both before AND after it -
1123  *    EXPAND the former and REMOVE the latter:
1124  *
1125  * Proposed:       |-----|
1126  * Existing:  |----|     |----|
1127  *
1128  * 3. There are no VMAs immediately adjacent to the proposed new VMA or those
1129  *    VMAs do not have identical attributes - NO MERGE POSSIBLE.
1130  *
1131  * In instances where we can merge, this function returns the expanded VMA which
1132  * will have its range adjusted accordingly and the underlying maple tree also
1133  * adjusted.
1134  *
1135  * Returns: In instances where no merge was possible, NULL. Otherwise, a pointer
1136  *          to the VMA we expanded.
1137  *
1138  * This function adjusts @vmg to provide @vmg->next if not already specified,
1139  * and adjusts [@vmg->start, @vmg->end) to span the expanded range.
1140  *
1141  * ASSUMPTIONS:
1142  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
1143  * - The caller must have determined that [@vmg->start, @vmg->end) is empty,
1144      other than VMAs that will be unmapped should the operation succeed.
1145  * - The caller must have specified the previous vma in @vmg->prev.
1146  * - The caller must have specified the next vma in @vmg->next.
1147  * - The caller must have positioned the vmi at or before the gap.
1148  */
1149 struct vm_area_struct *vma_merge_new_range(struct vma_merge_struct *vmg)
1150 {
1151 	struct vm_area_struct *prev = vmg->prev;
1152 	struct vm_area_struct *next = vmg->next;
1153 	unsigned long end = vmg->end;
1154 	bool can_merge_left, can_merge_right;
1155 	bool move_iter_back = false;
1156 
1157 	mmap_assert_write_locked(vmg->mm);
1158 	VM_WARN_ON_VMG(vmg->middle, vmg);
1159 	VM_WARN_ON_VMG(vmg->target, vmg);
1160 	/* vmi must point at or before the gap. */
1161 	VM_WARN_ON_VMG(vma_iter_addr(vmg->vmi) > end, vmg);
1162 
1163 	vmg->state = VMA_MERGE_NOMERGE;
1164 
1165 	if (!vma_flags_can_merge(&vmg->vma_flags))
1166 		return NULL;
1167 
1168 	/* VMAs with no prev/next are unmergeable. */
1169 	if (!prev && !next)
1170 		return NULL;
1171 
1172 	can_merge_left = can_vma_merge_left(vmg);
1173 	can_merge_right = !vmg->just_expand && can_vma_merge_right(vmg, can_merge_left);
1174 
1175 	/* If we can merge with the next VMA, adjust vmg accordingly. */
1176 	if (can_merge_right) {
1177 		vmg->end = next->vm_end;
1178 		vmg->target = next;
1179 	}
1180 
1181 	/* If we can merge with the previous VMA, adjust vmg accordingly. */
1182 	if (can_merge_left) {
1183 		vmg->start = prev->vm_start;
1184 		vmg->target = prev;
1185 		vmg->pgoff = vma_start_pgoff(prev);
1186 		vmg->anon_pgoff = vma_start_anon_pgoff(prev);
1187 
1188 		/*
1189 		 * If this merge would result in removal of the next VMA but we
1190 		 * are not permitted to do so, reduce the operation to merging
1191 		 * prev and vma.
1192 		 */
1193 		if (can_merge_right && !can_merge_remove_vma(next))
1194 			vmg->end = end;
1195 
1196 		/* In expand-only case we are already positioned at prev. */
1197 		if (!vmg->just_expand)
1198 			move_iter_back = true;
1199 	}
1200 
1201 	if (!can_merge_left && !can_merge_right)
1202 		return NULL;
1203 
1204 	if (move_iter_back)
1205 		vma_prev(vmg->vmi);
1206 
1207 	/*
1208 	 * Now try to expand adjacent VMA(s). This takes care of removing the
1209 	 * following VMA if we have VMAs on both sides.
1210 	 */
1211 	if (vma_expand(vmg)) {
1212 		/* Error occurred, restore iterator. */
1213 		if (move_iter_back)
1214 			vma_iter_next_range(vmg->vmi);
1215 		return NULL;
1216 	}
1217 
1218 	khugepaged_enter_vma(vmg->target, vmg->vm_flags);
1219 	vmg->state = VMA_MERGE_SUCCESS;
1220 	return vmg->target;
1221 }
1222 
1223 /*
1224  * vma_merge_copied_range - Attempt to merge a VMA that is being copied by
1225  * mremap()
1226  *
1227  * @vmg: Describes the VMA we are adding, in the copied-to range @vmg->start to
1228  *       @vmg->end (exclusive), which we try to merge with any adjacent VMAs if
1229  *       possible.
1230  *
1231  * vmg->prev, next, start, end, pgoff should all be relative to the COPIED TO
1232  * range, i.e. the target range for the VMA.
1233  *
1234  * Returns: In instances where no merge was possible, NULL. Otherwise, a pointer
1235  *          to the VMA we expanded.
1236  *
1237  * ASSUMPTIONS: Same as vma_merge_new_range(), except vmg->middle must contain
1238  *              the copied-from VMA.
1239  */
1240 static struct vm_area_struct *vma_merge_copied_range(struct vma_merge_struct *vmg)
1241 {
1242 	/* We must have a copied-from VMA. */
1243 	VM_WARN_ON_VMG(!vmg->middle, vmg);
1244 
1245 	vmg->copied_from = vmg->middle;
1246 	vmg->middle = NULL;
1247 
1248 	/* If not registered for remap, uffd context will be cleared. */
1249 	if (vma_has_uffd_without_event_remap(vmg->copied_from))
1250 		return NULL;
1251 
1252 	return vma_merge_new_range(vmg);
1253 }
1254 
1255 /*
1256  * vma_expand - Expand an existing VMA
1257  *
1258  * @vmg: Describes a VMA expansion operation.
1259  *
1260  * Expand @vma to vmg->start and vmg->end.  Can expand off the start and end.
1261  * Will expand over vmg->next if it's different from vmg->target and vmg->end ==
1262  * vmg->next->vm_end.  Checking if the vmg->target can expand and merge with
1263  * vmg->next needs to be handled by the caller.
1264  *
1265  * Returns: 0 on success.
1266  *
1267  * ASSUMPTIONS:
1268  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
1269  * - The caller must have set @vmg->target and @vmg->next.
1270  */
1271 int vma_expand(struct vma_merge_struct *vmg)
1272 {
1273 	struct vm_area_struct *anon_dup = NULL;
1274 	struct vm_area_struct *target = vmg->target;
1275 	struct vm_area_struct *next = vmg->next;
1276 	bool remove_next = false;
1277 	int ret = 0;
1278 
1279 	mmap_assert_write_locked(vmg->mm);
1280 	vma_start_write(target);
1281 
1282 	if (next && target != next && vmg->end == next->vm_end)
1283 		remove_next = true;
1284 
1285 	/* We must have a target. */
1286 	VM_WARN_ON_VMG(!target, vmg);
1287 	/* This should have already been checked by this point. */
1288 	VM_WARN_ON_VMG(remove_next && !can_merge_remove_vma(next), vmg);
1289 	/* Not merging but overwriting any part of next is not handled. */
1290 	VM_WARN_ON_VMG(next && !remove_next &&
1291 		       next != target && vmg->end > next->vm_start, vmg);
1292 	/* Only handles expanding. */
1293 	VM_WARN_ON_VMG(target->vm_start < vmg->start ||
1294 		       target->vm_end > vmg->end, vmg);
1295 
1296 	propagate_sticky_flags(vmg, target);
1297 
1298 	/*
1299 	 * If we are removing the next VMA or copying from a VMA
1300 	 * (e.g. mremap()'ing), we must propagate anon rmap state.
1301 	 *
1302 	 * Note that, by convention, callers ignore OOM for this case, so
1303 	 * we don't need to account for vmg->give_up_on_mm here.
1304 	 */
1305 	if (remove_next)
1306 		ret = dup_anon_vma(target, next, &anon_dup);
1307 	if (!ret && vmg->copied_from)
1308 		ret = dup_anon_vma(target, vmg->copied_from, &anon_dup);
1309 	if (ret)
1310 		goto nomem;
1311 
1312 	if (remove_next) {
1313 		vma_start_write(next);
1314 		vmg->__remove_next = true;
1315 
1316 		propagate_sticky_flags(vmg, next);
1317 	}
1318 	if (commit_merge(vmg))
1319 		goto nomem;
1320 
1321 	return 0;
1322 
1323 nomem:
1324 	if (anon_dup)
1325 		unlink_anon_vmas(anon_dup);
1326 	/*
1327 	 * If the user requests that we just give upon OOM, we are safe to do so
1328 	 * here, as commit merge provides this contract to us. Nothing has been
1329 	 * changed - no harm no foul, just don't report it.
1330 	 */
1331 	if (!vmg->give_up_on_oom)
1332 		vmg->state = VMA_MERGE_ERROR_NOMEM;
1333 	return -ENOMEM;
1334 }
1335 
1336 /**
1337  * vma_shrink() - Shrink the end of a VMA
1338  * @vmi: The vma iterator
1339  * @vma: The VMA to modify
1340  * @end: The new end
1341  *
1342  * Note that the caller may only shrink the end of the VMA.
1343  *
1344  * Returns: 0 on success, -ENOMEM otherwise
1345  */
1346 int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
1347 	       unsigned long end)
1348 {
1349 	struct vma_prepare vp;
1350 
1351 	VM_WARN_ON_ONCE(end > vma->vm_end);
1352 
1353 	vma_iter_config(vmi, end, vma->vm_end);
1354 	if (vma_iter_prealloc(vmi, NULL))
1355 		return -ENOMEM;
1356 
1357 	vma_start_write(vma);
1358 
1359 	init_vma_prep(&vp, vma);
1360 	vp.file_pgoff_unchanged = true;
1361 	vp.anon_pgoff_unchanged = true;
1362 	vma_prepare(&vp);
1363 	vma_adjust_trans_huge(vma, vma->vm_start, end, NULL);
1364 
1365 	vma_iter_clear(vmi);
1366 	__vma_set_range(vma, vma->vm_start, end);
1367 	vma_complete(&vp, vmi, vma->vm_mm);
1368 	validate_mm(vma->vm_mm);
1369 	return 0;
1370 }
1371 
1372 static inline void vms_clear_ptes(struct vma_munmap_struct *vms,
1373 		    struct ma_state *mas_detach, bool mm_wr_locked)
1374 {
1375 	struct unmap_desc unmap = {
1376 		.mas = mas_detach,
1377 		.first = vms->vma,
1378 		/* start and end may be different if there is no prev or next vma. */
1379 		.pg_start = vms->unmap_start,
1380 		.pg_end = vms->unmap_end,
1381 		.vma_start = vms->start,
1382 		.vma_end = vms->end,
1383 		/*
1384 		 * The tree limits and reset differ from the normal case since it's a
1385 		 * side-tree
1386 		 */
1387 		.tree_reset = 1,
1388 		.tree_end = vms->vma_count,
1389 		/*
1390 		 * We can free page tables without write-locking mmap_lock because VMAs
1391 		 * were isolated before we downgraded mmap_lock.
1392 		 */
1393 		.mm_wr_locked = mm_wr_locked,
1394 	};
1395 
1396 	if (!vms->clear_ptes) /* Nothing to do */
1397 		return;
1398 
1399 	mas_set(mas_detach, 1);
1400 	unmap_region(&unmap);
1401 	vms->clear_ptes = false;
1402 }
1403 
1404 static void vms_clean_up_area(struct vma_munmap_struct *vms,
1405 		struct ma_state *mas_detach)
1406 {
1407 	struct vm_area_struct *vma;
1408 
1409 	if (!vms->nr_pages)
1410 		return;
1411 
1412 	vms_clear_ptes(vms, mas_detach, true);
1413 	mas_set(mas_detach, 0);
1414 	mas_for_each(mas_detach, vma, ULONG_MAX)
1415 		vma_close(vma);
1416 }
1417 
1418 /*
1419  * vms_complete_munmap_vmas() - Finish the munmap() operation
1420  * @vms: The vma munmap struct
1421  * @mas_detach: The maple state of the detached vmas
1422  *
1423  * This updates the mm_struct, unmaps the region, frees the resources
1424  * used for the munmap() and may downgrade the lock - if requested.  Everything
1425  * needed to be done once the vma maple tree is updated.
1426  */
1427 static void vms_complete_munmap_vmas(struct vma_munmap_struct *vms,
1428 		struct ma_state *mas_detach)
1429 {
1430 	struct vm_area_struct *vma;
1431 	struct mm_struct *mm;
1432 
1433 	mm = current->mm;
1434 	mm->map_count -= vms->vma_count;
1435 	mm->locked_vm -= vms->locked_vm;
1436 	if (vms->unlock)
1437 		mmap_write_downgrade(mm);
1438 
1439 	if (!vms->nr_pages)
1440 		return;
1441 
1442 	vms_clear_ptes(vms, mas_detach, !vms->unlock);
1443 	/* Update high watermark before we lower total_vm */
1444 	update_hiwater_vm(mm);
1445 	/* Stat accounting */
1446 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm) - vms->nr_pages);
1447 	/* Paranoid bookkeeping */
1448 	VM_WARN_ON(vms->exec_vm > mm->exec_vm);
1449 	VM_WARN_ON(vms->stack_vm > mm->stack_vm);
1450 	VM_WARN_ON(vms->data_vm > mm->data_vm);
1451 	mm->exec_vm -= vms->exec_vm;
1452 	mm->stack_vm -= vms->stack_vm;
1453 	mm->data_vm -= vms->data_vm;
1454 
1455 	/* Remove and clean up vmas */
1456 	mas_set(mas_detach, 0);
1457 	mas_for_each(mas_detach, vma, ULONG_MAX)
1458 		remove_vma(vma);
1459 
1460 	vm_unacct_memory(vms->nr_accounted);
1461 	validate_mm(mm);
1462 	if (vms->unlock)
1463 		mmap_read_unlock(mm);
1464 
1465 	__mt_destroy(mas_detach->tree);
1466 }
1467 
1468 /*
1469  * reattach_vmas() - Undo any munmap work and free resources
1470  * @mas_detach: The maple state with the detached maple tree
1471  *
1472  * Reattach any detached vmas and free up the maple tree used to track the vmas.
1473  */
1474 static void reattach_vmas(struct ma_state *mas_detach)
1475 {
1476 	struct vm_area_struct *vma;
1477 
1478 	mas_set(mas_detach, 0);
1479 	mas_for_each(mas_detach, vma, ULONG_MAX)
1480 		vma_mark_attached(vma);
1481 
1482 	__mt_destroy(mas_detach->tree);
1483 }
1484 
1485 /*
1486  * vms_gather_munmap_vmas() - Put all VMAs within a range into a maple tree
1487  * for removal at a later date.  Handles splitting first and last if necessary
1488  * and marking the vmas as isolated.
1489  *
1490  * @vms: The vma munmap struct
1491  * @mas_detach: The maple state tracking the detached tree
1492  *
1493  * Return: 0 on success, error otherwise
1494  */
1495 static int vms_gather_munmap_vmas(struct vma_munmap_struct *vms,
1496 		struct ma_state *mas_detach)
1497 {
1498 	struct vm_area_struct *next = NULL;
1499 	int error;
1500 
1501 	/*
1502 	 * If we need to split any vma, do it now to save pain later.
1503 	 * Does it split the first one?
1504 	 */
1505 	if (vms->start > vms->vma->vm_start) {
1506 
1507 		/*
1508 		 * Make sure that map_count on return from munmap() will
1509 		 * not exceed its limit; but let map_count go just above
1510 		 * its limit temporarily, to help free resources as expected.
1511 		 */
1512 		if (vms->end < vms->vma->vm_end &&
1513 		    vms->vma->vm_mm->map_count >= get_sysctl_max_map_count()) {
1514 			error = -ENOMEM;
1515 			goto map_count_exceeded;
1516 		}
1517 
1518 		/* Don't bother splitting the VMA if we can't unmap it anyway */
1519 		if (vma_is_sealed(vms->vma)) {
1520 			error = -EPERM;
1521 			goto start_split_failed;
1522 		}
1523 
1524 		error = __split_vma(vms->vmi, vms->vma, vms->start, 1);
1525 		if (error)
1526 			goto start_split_failed;
1527 	}
1528 	vms->prev = vma_prev(vms->vmi);
1529 	if (vms->prev)
1530 		vms->unmap_start = vms->prev->vm_end;
1531 
1532 	/*
1533 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
1534 	 * it is always overwritten.
1535 	 */
1536 	for_each_vma_range(*(vms->vmi), next, vms->end) {
1537 		long nrpages;
1538 
1539 		if (vma_is_sealed(next)) {
1540 			error = -EPERM;
1541 			goto modify_vma_failed;
1542 		}
1543 		/* Does it split the end? */
1544 		if (next->vm_end > vms->end) {
1545 			error = __split_vma(vms->vmi, next, vms->end, 0);
1546 			if (error)
1547 				goto end_split_failed;
1548 		}
1549 		vma_start_write(next);
1550 		mas_set(mas_detach, vms->vma_count++);
1551 		error = mas_store_gfp(mas_detach, next, GFP_KERNEL);
1552 		if (error)
1553 			goto munmap_gather_failed;
1554 
1555 		vma_mark_detached(next);
1556 		nrpages = vma_pages(next);
1557 
1558 		vms->nr_pages += nrpages;
1559 		if (vma_test(next, VMA_LOCKED_BIT))
1560 			vms->locked_vm += nrpages;
1561 
1562 		if (vma_test(next, VMA_ACCOUNT_BIT))
1563 			vms->nr_accounted += nrpages;
1564 
1565 		if (is_exec_mapping(next->vm_flags))
1566 			vms->exec_vm += nrpages;
1567 		else if (is_stack_mapping(next->vm_flags))
1568 			vms->stack_vm += nrpages;
1569 		else if (is_data_mapping_vma_flags(&next->flags))
1570 			vms->data_vm += nrpages;
1571 
1572 		if (vms->uf) {
1573 			/*
1574 			 * If userfaultfd_unmap_prep returns an error the vmas
1575 			 * will remain split, but userland will get a
1576 			 * highly unexpected error anyway. This is no
1577 			 * different than the case where the first of the two
1578 			 * __split_vma fails, but we don't undo the first
1579 			 * split, despite we could. This is unlikely enough
1580 			 * failure that it's not worth optimizing it for.
1581 			 */
1582 			error = userfaultfd_unmap_prep(next, vms->start,
1583 						       vms->end, vms->uf);
1584 			if (error)
1585 				goto userfaultfd_error;
1586 		}
1587 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
1588 		BUG_ON(next->vm_start < vms->start);
1589 		BUG_ON(next->vm_start > vms->end);
1590 #endif
1591 	}
1592 
1593 	vms->next = vma_next(vms->vmi);
1594 	if (vms->next)
1595 		vms->unmap_end = vms->next->vm_start;
1596 
1597 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
1598 	/* Make sure no VMAs are about to be lost. */
1599 	{
1600 		MA_STATE(test, mas_detach->tree, 0, 0);
1601 		struct vm_area_struct *vma_mas, *vma_test;
1602 		int test_count = 0;
1603 
1604 		vma_iter_set(vms->vmi, vms->start);
1605 		rcu_read_lock();
1606 		vma_test = mas_find(&test, vms->vma_count - 1);
1607 		for_each_vma_range(*(vms->vmi), vma_mas, vms->end) {
1608 			BUG_ON(vma_mas != vma_test);
1609 			test_count++;
1610 			vma_test = mas_next(&test, vms->vma_count - 1);
1611 		}
1612 		rcu_read_unlock();
1613 		BUG_ON(vms->vma_count != test_count);
1614 	}
1615 #endif
1616 
1617 	while (vma_iter_addr(vms->vmi) > vms->start)
1618 		vma_iter_prev_range(vms->vmi);
1619 
1620 	vms->clear_ptes = true;
1621 	return 0;
1622 
1623 userfaultfd_error:
1624 munmap_gather_failed:
1625 end_split_failed:
1626 modify_vma_failed:
1627 	reattach_vmas(mas_detach);
1628 start_split_failed:
1629 map_count_exceeded:
1630 	return error;
1631 }
1632 
1633 /*
1634  * init_vma_munmap() - Initializer wrapper for vma_munmap_struct
1635  * @vms: The vma munmap struct
1636  * @vmi: The vma iterator
1637  * @vma: The first vm_area_struct to munmap
1638  * @start: The aligned start address to munmap
1639  * @end: The aligned end address to munmap
1640  * @uf: The userfaultfd list_head
1641  * @unlock: Unlock after the operation.  Only unlocked on success
1642  */
1643 static void init_vma_munmap(struct vma_munmap_struct *vms,
1644 		struct vma_iterator *vmi, struct vm_area_struct *vma,
1645 		unsigned long start, unsigned long end, struct list_head *uf,
1646 		bool unlock)
1647 {
1648 	vms->vmi = vmi;
1649 	vms->vma = vma;
1650 	if (vma) {
1651 		vms->start = start;
1652 		vms->end = end;
1653 	} else {
1654 		vms->start = vms->end = 0;
1655 	}
1656 	vms->unlock = unlock;
1657 	vms->uf = uf;
1658 	vms->vma_count = 0;
1659 	vms->nr_pages = vms->locked_vm = vms->nr_accounted = 0;
1660 	vms->exec_vm = vms->stack_vm = vms->data_vm = 0;
1661 	vms->unmap_start = FIRST_USER_ADDRESS;
1662 	vms->unmap_end = USER_PGTABLES_CEILING;
1663 	vms->clear_ptes = false;
1664 }
1665 
1666 /*
1667  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
1668  * @vmi: The vma iterator
1669  * @vma: The starting vm_area_struct
1670  * @mm: The mm_struct
1671  * @start: The aligned start address to munmap.
1672  * @end: The aligned end address to munmap.
1673  * @uf: The userfaultfd list_head
1674  * @unlock: Set to true to drop the mmap_lock.  unlocking only happens on
1675  * success.
1676  *
1677  * Return: 0 on success and drops the lock if so directed, error and leaves the
1678  * lock held otherwise.
1679  */
1680 int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
1681 		struct mm_struct *mm, unsigned long start, unsigned long end,
1682 		struct list_head *uf, bool unlock)
1683 {
1684 	struct maple_tree mt_detach;
1685 	MA_STATE(mas_detach, &mt_detach, 0, 0);
1686 	mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
1687 	mt_on_stack(mt_detach);
1688 	struct vma_munmap_struct vms;
1689 	int error;
1690 
1691 	init_vma_munmap(&vms, vmi, vma, start, end, uf, unlock);
1692 	error = vms_gather_munmap_vmas(&vms, &mas_detach);
1693 	if (error)
1694 		goto gather_failed;
1695 
1696 	error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
1697 	if (error)
1698 		goto clear_tree_failed;
1699 
1700 	/* Point of no return */
1701 	vms_complete_munmap_vmas(&vms, &mas_detach);
1702 	return 0;
1703 
1704 clear_tree_failed:
1705 	reattach_vmas(&mas_detach);
1706 gather_failed:
1707 	validate_mm(mm);
1708 	return error;
1709 }
1710 
1711 /*
1712  * do_vmi_munmap() - munmap a given range.
1713  * @vmi: The vma iterator
1714  * @mm: The mm_struct
1715  * @start: The start address to munmap
1716  * @len: The length of the range to munmap
1717  * @uf: The userfaultfd list_head
1718  * @unlock: set to true if the user wants to drop the mmap_lock on success
1719  *
1720  * This function takes a @mas that is either pointing to the previous VMA or set
1721  * to MA_START and sets it up to remove the mapping(s).  The @len will be
1722  * aligned.
1723  *
1724  * Return: 0 on success and drops the lock if so directed, error and leaves the
1725  * lock held otherwise.
1726  */
1727 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
1728 		  unsigned long start, size_t len, struct list_head *uf,
1729 		  bool unlock)
1730 {
1731 	unsigned long end;
1732 	struct vm_area_struct *vma;
1733 
1734 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
1735 		return -EINVAL;
1736 
1737 	end = start + PAGE_ALIGN(len);
1738 	if (end == start)
1739 		return -EINVAL;
1740 
1741 	/* Find the first overlapping VMA */
1742 	vma = vma_find(vmi, end);
1743 	if (!vma) {
1744 		if (unlock)
1745 			mmap_write_unlock(mm);
1746 		return 0;
1747 	}
1748 
1749 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
1750 }
1751 
1752 /*
1753  * We are about to modify one or multiple of a VMA's flags, policy, userfaultfd
1754  * context and anonymous VMA name within the range [start, end).
1755  *
1756  * As a result, we might be able to merge the newly modified VMA range with an
1757  * adjacent VMA with identical properties.
1758  *
1759  * If no merge is possible and the range does not span the entirety of the VMA,
1760  * we then need to split the VMA to accommodate the change.
1761  *
1762  * The function returns either the merged VMA, the original VMA if a split was
1763  * required instead, or an error if the split failed.
1764  */
1765 static struct vm_area_struct *vma_modify(struct vma_merge_struct *vmg)
1766 {
1767 	struct vm_area_struct *vma = vmg->middle;
1768 	unsigned long start = vmg->start;
1769 	unsigned long end = vmg->end;
1770 	struct vm_area_struct *merged;
1771 
1772 	/* First, try to merge. */
1773 	merged = vma_merge_existing_range(vmg);
1774 	if (merged)
1775 		return merged;
1776 	if (vmg_nomem(vmg))
1777 		return ERR_PTR(-ENOMEM);
1778 
1779 	/*
1780 	 * Split can fail for reasons other than OOM, so if the user requests
1781 	 * this it's probably a mistake.
1782 	 */
1783 	VM_WARN_ON(vmg->give_up_on_oom &&
1784 		   (vma->vm_start != start || vma->vm_end != end));
1785 
1786 	/* Split any preceding portion of the VMA. */
1787 	if (vma->vm_start < start) {
1788 		int err = split_vma(vmg->vmi, vma, start, 1);
1789 
1790 		if (err)
1791 			return ERR_PTR(err);
1792 	}
1793 
1794 	/* Split any trailing portion of the VMA. */
1795 	if (vma->vm_end > end) {
1796 		int err = split_vma(vmg->vmi, vma, end, 0);
1797 
1798 		if (err)
1799 			return ERR_PTR(err);
1800 	}
1801 
1802 	return vma;
1803 }
1804 
1805 struct vm_area_struct *vma_modify_flags(struct vma_iterator *vmi,
1806 		struct vm_area_struct *prev, struct vm_area_struct *vma,
1807 		unsigned long start, unsigned long end,
1808 		vma_flags_t *vma_flags_ptr)
1809 {
1810 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1811 	const vma_flags_t vma_flags = *vma_flags_ptr;
1812 	struct vm_area_struct *ret;
1813 
1814 	vmg.vma_flags = vma_flags;
1815 
1816 	ret = vma_modify(&vmg);
1817 	if (IS_ERR(ret))
1818 		return ret;
1819 
1820 	/*
1821 	 * For a merge to succeed, the flags must match those
1822 	 * requested. However, sticky flags may have been retained, so propagate
1823 	 * them to the caller.
1824 	 */
1825 	if (vmg.state == VMA_MERGE_SUCCESS)
1826 		*vma_flags_ptr = ret->flags;
1827 	return ret;
1828 }
1829 
1830 struct vm_area_struct *vma_modify_name(struct vma_iterator *vmi,
1831 		struct vm_area_struct *prev, struct vm_area_struct *vma,
1832 		unsigned long start, unsigned long end,
1833 		struct anon_vma_name *new_name)
1834 {
1835 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1836 
1837 	vmg.anon_name = new_name;
1838 
1839 	return vma_modify(&vmg);
1840 }
1841 
1842 struct vm_area_struct *vma_modify_policy(struct vma_iterator *vmi,
1843 		struct vm_area_struct *prev, struct vm_area_struct *vma,
1844 		unsigned long start, unsigned long end,
1845 		struct mempolicy *new_pol)
1846 {
1847 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1848 
1849 	vmg.policy = new_pol;
1850 
1851 	return vma_modify(&vmg);
1852 }
1853 
1854 struct vm_area_struct *vma_modify_flags_uffd(struct vma_iterator *vmi,
1855 		struct vm_area_struct *prev, struct vm_area_struct *vma,
1856 		unsigned long start, unsigned long end,
1857 		const vma_flags_t *vma_flags, struct vm_userfaultfd_ctx new_ctx,
1858 		bool give_up_on_oom)
1859 {
1860 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1861 
1862 	vmg.vma_flags = *vma_flags;
1863 	vmg.uffd_ctx = new_ctx;
1864 	if (give_up_on_oom)
1865 		vmg.give_up_on_oom = true;
1866 
1867 	return vma_modify(&vmg);
1868 }
1869 
1870 /*
1871  * Expand vma by delta bytes, potentially merging with an immediately adjacent
1872  * VMA with identical properties.
1873  */
1874 struct vm_area_struct *vma_merge_extend(struct vma_iterator *vmi,
1875 					struct vm_area_struct *vma,
1876 					unsigned long delta)
1877 {
1878 	const unsigned long start =
1879 		vma_can_merge(vma) ? vma->vm_end : vma->vm_start;
1880 	VMG_VMA_STATE(vmg, vmi, vma, vma, start, vma->vm_end + delta);
1881 
1882 	vmg.middle = NULL; /* We use the VMA to populate VMG fields only. */
1883 
1884 	if (vma_can_merge(vma)) {
1885 		vmg.next = vma_iter_next_rewind(vmi, NULL);
1886 		return vma_merge_new_range(&vmg);
1887 	}
1888 
1889 	/* Mixed mappings are permitted to be expanded, not merged. */
1890 	VM_WARN_ON_ONCE(vma_is_fixed_mapping(vma));
1891 	VM_WARN_ON_ONCE(!vma_test(vma, VMA_MIXEDMAP_BIT));
1892 	vma_prev(vmi); /* Reposition to start of VMA. */
1893 	vmg.target = vma;
1894 	if (vma_expand(&vmg))
1895 		return NULL;
1896 	return vma;
1897 }
1898 
1899 void unlink_file_vma_batch_init(struct unlink_vma_file_batch *vb)
1900 {
1901 	vb->count = 0;
1902 }
1903 
1904 static void unlink_file_vma_batch_process(struct unlink_vma_file_batch *vb)
1905 {
1906 	struct address_space *mapping;
1907 	int i;
1908 
1909 	mapping = vb->vmas[0]->vm_file->f_mapping;
1910 	i_mmap_lock_write(mapping);
1911 	for (i = 0; i < vb->count; i++) {
1912 		VM_WARN_ON_ONCE(vb->vmas[i]->vm_file->f_mapping != mapping);
1913 		__remove_shared_vm_struct(vb->vmas[i], mapping);
1914 	}
1915 	i_mmap_unlock_write(mapping);
1916 
1917 	unlink_file_vma_batch_init(vb);
1918 }
1919 
1920 void unlink_file_vma_batch_add(struct unlink_vma_file_batch *vb,
1921 			       struct vm_area_struct *vma)
1922 {
1923 	if (vma->vm_file == NULL)
1924 		return;
1925 
1926 	if ((vb->count > 0 && vb->vmas[0]->vm_file != vma->vm_file) ||
1927 	    vb->count == ARRAY_SIZE(vb->vmas))
1928 		unlink_file_vma_batch_process(vb);
1929 
1930 	vb->vmas[vb->count] = vma;
1931 	vb->count++;
1932 }
1933 
1934 void unlink_file_vma_batch_final(struct unlink_vma_file_batch *vb)
1935 {
1936 	if (vb->count > 0)
1937 		unlink_file_vma_batch_process(vb);
1938 }
1939 
1940 static void vma_link_file(struct vm_area_struct *vma, bool hold_rmap_lock)
1941 {
1942 	struct file *file = vma->vm_file;
1943 	struct address_space *mapping;
1944 
1945 	if (file) {
1946 		mapping = file->f_mapping;
1947 		i_mmap_lock_write(mapping);
1948 		__vma_link_file(vma, mapping);
1949 		if (!hold_rmap_lock)
1950 			i_mmap_unlock_write(mapping);
1951 	}
1952 }
1953 
1954 static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
1955 {
1956 	VMA_ITERATOR(vmi, mm, 0);
1957 
1958 	vma_iter_config(&vmi, vma->vm_start, vma->vm_end);
1959 	if (vma_iter_prealloc(&vmi, vma))
1960 		return -ENOMEM;
1961 
1962 	vma_start_write(vma);
1963 	vma_iter_store_new(&vmi, vma);
1964 	vma_link_file(vma, /* hold_rmap_lock= */false);
1965 	mm->map_count++;
1966 	validate_mm(mm);
1967 	return 0;
1968 }
1969 
1970 /*
1971  * Copy the vma structure to a new location in the same mm,
1972  * prior to moving page table entries, to effect an mremap move.
1973  */
1974 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
1975 	unsigned long addr, unsigned long len, pgoff_t pgoff,
1976 	pgoff_t anon_pgoff, bool *need_rmap_locks, bool keep_source)
1977 {
1978 	struct vm_area_struct *vma = *vmap;
1979 	unsigned long old_vma_start = vma->vm_start;
1980 	struct mm_struct *mm = vma->vm_mm;
1981 	struct vm_area_struct *new_vma;
1982 	bool can_self_merge = false;
1983 	VMA_ITERATOR(vmi, mm, addr);
1984 	VMG_VMA_STATE(vmg, &vmi, NULL, vma, addr, addr + len);
1985 
1986 	/*
1987 	 * If a vma has not yet been faulted, update its anonymous pgoff to
1988 	 * match the new location to increase its chance of merging.
1989 	 */
1990 	if (!vma_has_anon_rmap(vma)) {
1991 		anon_pgoff = addr >> PAGE_SHIFT;
1992 
1993 		if (vma_is_anonymous(vma)) {
1994 			pgoff = anon_pgoff;
1995 			can_self_merge = true;
1996 		}
1997 	}
1998 
1999 	/*
2000 	 * If the VMA we are copying might contain a uprobe PTE, ensure
2001 	 * that we do not establish one upon merge. Otherwise, when mremap()
2002 	 * moves page tables, it will orphan the newly created PTE.
2003 	 */
2004 	if (vma->vm_file)
2005 		vmg.skip_vma_uprobe = true;
2006 
2007 	new_vma = find_vma_prev(mm, addr, &vmg.prev);
2008 	if (new_vma && new_vma->vm_start < addr + len)
2009 		return NULL;	/* should never get here */
2010 
2011 	vmg.pgoff = pgoff;
2012 	vmg.anon_pgoff = anon_pgoff;
2013 	vmg.next = vma_iter_next_rewind(&vmi, NULL);
2014 
2015 	/*
2016 	 * If the original VMA is kept (MREMAP_DONTUNMAP), the source and
2017 	 * destination VMA must be treated distinctly.
2018 	 *
2019 	 * A merge violates this, so in this case disallow a self-merge.
2020 	 */
2021 	if (can_self_merge && keep_source) {
2022 		if (vmg.prev == vma)
2023 			vmg.prev = NULL;
2024 		if (vmg.next == vma)
2025 			vmg.next = NULL;
2026 		can_self_merge = false;
2027 	}
2028 
2029 	new_vma = vma_merge_copied_range(&vmg);
2030 
2031 	if (new_vma) {
2032 		/* Self-merged and VMA replaced. */
2033 		if (unlikely(new_vma->vm_start < old_vma_start &&
2034 			     new_vma->vm_end > old_vma_start)) {
2035 			/*
2036 			 * The only way a VMA can both self-merge and be
2037 			 * replaced is if the remap places the new VMA
2038 			 * immediately prior to its old self ('next') and
2039 			 * immediately after another VMA ('prev') causing the
2040 			 * next to be removed and prev to be expanded to cover
2041 			 * the entire range.
2042 			 *
2043 			 * This should only be possible if the anonymous page
2044 			 * offset was updated, i.e. the VMA is unfaulted.
2045 			 */
2046 			VM_WARN_ON_ONCE_VMA(!can_self_merge, new_vma);
2047 			*vmap = vma = new_vma;
2048 		}
2049 		*need_rmap_locks =
2050 			(vma_start_pgoff(new_vma) <= vma_start_pgoff(vma));
2051 	} else {
2052 		new_vma = vm_area_dup(vma);
2053 		if (!new_vma)
2054 			goto out;
2055 		vma_set_range(new_vma, addr, addr + len, pgoff, anon_pgoff);
2056 		if (vma_dup_policy(vma, new_vma))
2057 			goto out_free_vma;
2058 		if (anon_vma_clone(new_vma, vma, VMA_OP_REMAP))
2059 			goto out_free_mempol;
2060 		if (new_vma->vm_file)
2061 			get_file(new_vma->vm_file);
2062 		if (new_vma->vm_ops && new_vma->vm_ops->open)
2063 			new_vma->vm_ops->open(new_vma);
2064 		if (vma_link(mm, new_vma))
2065 			goto out_vma_link;
2066 		*need_rmap_locks = false;
2067 	}
2068 	return new_vma;
2069 
2070 out_vma_link:
2071 	fixup_hugetlb_reservations(new_vma);
2072 	vma_close(new_vma);
2073 
2074 	if (new_vma->vm_file)
2075 		fput(new_vma->vm_file);
2076 
2077 	unlink_anon_vmas(new_vma);
2078 out_free_mempol:
2079 	mpol_put(vma_policy(new_vma));
2080 out_free_vma:
2081 	vm_area_free(new_vma);
2082 out:
2083 	return NULL;
2084 }
2085 
2086 /*
2087  * Rough compatibility check to quickly see if it's even worth looking
2088  * at sharing an anon rmap.
2089  *
2090  * They need to have the same vm_file, and the flags can only differ
2091  * in things that mprotect may change.
2092  *
2093  * NOTE! The fact that we share an anon rmap doesn't _have_ to mean that
2094  * we can merge the two vma's. For example, we refuse to merge a vma if
2095  * there is a vm_ops->close() function, because that indicates that the
2096  * driver is doing some kind of reference counting. But that doesn't
2097  * really matter for the anon rmap sharing case.
2098  */
2099 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
2100 {
2101 	vma_flags_t diff = vma_flags_diff_pair(&a->flags, &b->flags);
2102 
2103 	/* Ignore flags that mprotect() can change. */
2104 	vma_flags_clear_mask(&diff, VMA_ACCESS_FLAGS);
2105 	/* Ignore flags that do not impact merging. */
2106 	vma_flags_clear_mask(&diff, VMA_IGNORE_MERGE_FLAGS);
2107 
2108 	/* Must be adjacent. */
2109 	if (a->vm_end != b->vm_start)
2110 		return false;
2111 	/* Must have matching policy. */
2112 	if (!mpol_equal(vma_policy(a), vma_policy(b)))
2113 		return false;
2114 	/* Must both be anon or map the same file (MAP_PRIVATE case). */
2115 	if (a->vm_file != b->vm_file)
2116 		return false;
2117 	/* Flags must be equivalent modulo mprotect(). */
2118 	if (!vma_flags_empty(&diff))
2119 		return false;
2120 	/* Page offset must align. */
2121 	if (vma_end_pgoff(a) != vma_start_pgoff(b))
2122 		return false;
2123 	/* Only reached from anon path, so either MAP_PRIVATE file or anon. */
2124 	if (vma_end_anon_pgoff(a) != vma_start_anon_pgoff(b))
2125 		return false;
2126 	return true;
2127 }
2128 
2129 /*
2130  * Do some basic sanity checking to see if we can re-use the anon rmap
2131  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
2132  * the same as 'old', the other will be the new one that is trying
2133  * to share the anon rmap.
2134  *
2135  * NOTE! This runs with mmap_lock held for reading, so it is possible that
2136  * the anon rmap of 'old' is concurrently in the process of being set up
2137  * by another page fault trying to merge _that_. But that's ok: if it
2138  * is being set up, that automatically means that it will be a singleton
2139  * acceptable for merging, so we can do all of this optimistically. But
2140  * we do that READ_ONCE() to make sure that we never re-load the pointer.
2141  *
2142  * The READ_ONCE() establishes an address dependency between anon_vma and
2143  * any access to its fields, which pairs with the assignment to
2144  * vma->anon_vma performed with release semantics in __anon_vma_prepare().
2145  *
2146  * This is especially important as anon_vma's are SLAB_TYPESAFE_BY_RCU so
2147  * accessing an uninitialised anon_vma's fields may result in a UAF.
2148  *
2149  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
2150  * matters for the 'stable anon rmap' case (ie the thing we want to avoid
2151  * is to return an anon rmap that is "complex" due to having gone through
2152  * a fork).
2153  *
2154  * We also make sure that the two vma's are compatible (adjacent,
2155  * and with the same memory policies). That's all stable, even with just
2156  * a read lock on the mmap_lock.
2157  */
2158 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old,
2159 					  struct vm_area_struct *a,
2160 					  struct vm_area_struct *b)
2161 {
2162 	if (anon_vma_compatible(a, b)) {
2163 		/* Paired with a memory barrier in __anon_vma_prepare(). */
2164 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
2165 
2166 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
2167 			return anon_vma;
2168 	}
2169 	return NULL;
2170 }
2171 
2172 /*
2173  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
2174  * neighbouring vmas for a suitable anon rmap, before it goes off
2175  * to allocate a new anon rmap.  It checks because a repetitive
2176  * sequence of mprotects and faults may otherwise lead to distinct
2177  * anon rmaps being allocated, preventing vma merge in subsequent
2178  * mprotect.
2179  */
2180 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
2181 {
2182 	struct anon_vma *anon_vma = NULL;
2183 	struct vm_area_struct *prev, *next;
2184 	VMA_ITERATOR(vmi, vma->vm_mm, vma->vm_end);
2185 
2186 	/* Try next first. */
2187 	next = vma_iter_load(&vmi);
2188 	if (next) {
2189 		anon_vma = reusable_anon_vma(next, vma, next);
2190 		if (anon_vma)
2191 			return anon_vma;
2192 	}
2193 
2194 	prev = vma_prev(&vmi);
2195 	VM_BUG_ON_VMA(prev != vma, vma);
2196 	prev = vma_prev(&vmi);
2197 	/* Try prev next. */
2198 	if (prev)
2199 		anon_vma = reusable_anon_vma(prev, prev, vma);
2200 
2201 	/*
2202 	 * We might reach here with anon_vma == NULL if we can't find
2203 	 * any reusable anon rmap.
2204 	 * There's no absolute need to look only at touching neighbours:
2205 	 * we could search further afield for "compatible" anon rmaps.
2206 	 * But it would probably just be a waste of time searching,
2207 	 * or lead to too many vmas hanging off the same anon rmap.
2208 	 * We're trying to allow mprotect remerging later on,
2209 	 * not trying to minimize memory used for anon rmaps.
2210 	 */
2211 	return anon_vma;
2212 }
2213 
2214 static bool vm_ops_needs_writenotify(const struct vm_operations_struct *vm_ops)
2215 {
2216 	return vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite);
2217 }
2218 
2219 static bool vma_is_shared_writable(struct vm_area_struct *vma)
2220 {
2221 	return vma_test_all(vma, VMA_WRITE_BIT, VMA_SHARED_BIT);
2222 }
2223 
2224 static bool vma_fs_can_writeback(struct vm_area_struct *vma)
2225 {
2226 	/* No managed pages to writeback. */
2227 	if (vma_test(vma, VMA_PFNMAP_BIT))
2228 		return false;
2229 
2230 	return vma->vm_file && vma->vm_file->f_mapping &&
2231 		mapping_can_writeback(vma->vm_file->f_mapping);
2232 }
2233 
2234 /*
2235  * Does this VMA require the underlying folios to have their dirty state
2236  * tracked?
2237  */
2238 bool vma_needs_dirty_tracking(struct vm_area_struct *vma)
2239 {
2240 	/* Only shared, writable VMAs require dirty tracking. */
2241 	if (!vma_is_shared_writable(vma))
2242 		return false;
2243 
2244 	/* Does the filesystem need to be notified? */
2245 	if (vm_ops_needs_writenotify(vma->vm_ops))
2246 		return true;
2247 
2248 	/*
2249 	 * Even if the filesystem doesn't indicate a need for writenotify, if it
2250 	 * can writeback, dirty tracking is still required.
2251 	 */
2252 	return vma_fs_can_writeback(vma);
2253 }
2254 
2255 /*
2256  * Some shared mappings will want the pages marked read-only
2257  * to track write events. If so, we'll downgrade vm_page_prot
2258  * to the private version (using protection_map[] without the
2259  * VM_SHARED bit).
2260  */
2261 bool vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
2262 {
2263 	/* If it was private or non-writable, the write bit is already clear */
2264 	if (!vma_is_shared_writable(vma))
2265 		return false;
2266 
2267 	/* The backer wishes to know when pages are first written to? */
2268 	if (vm_ops_needs_writenotify(vma->vm_ops))
2269 		return true;
2270 
2271 	/* The open routine did something to the protections that pgprot_modify
2272 	 * won't preserve? */
2273 	if (pgprot_val(vm_page_prot) !=
2274 	    pgprot_val(vma_pgprot_modify(vm_page_prot, vma->flags)))
2275 		return false;
2276 
2277 	/*
2278 	 * Do we need to track softdirty? hugetlb does not support softdirty
2279 	 * tracking yet.
2280 	 */
2281 	if (vma_soft_dirty_enabled(vma) && !vma_is_hugetlb(vma))
2282 		return true;
2283 
2284 	/* Do we need write faults for uffd-wp tracking? */
2285 	if (userfaultfd_wp(vma))
2286 		return true;
2287 
2288 	/* Can the mapping track the dirty pages? */
2289 	return vma_fs_can_writeback(vma);
2290 }
2291 
2292 static DEFINE_MUTEX(mm_all_locks_mutex);
2293 
2294 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
2295 {
2296 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
2297 		/*
2298 		 * The LSB of head.next can't change from under us
2299 		 * because we hold the mm_all_locks_mutex.
2300 		 */
2301 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
2302 		/*
2303 		 * We can safely modify head.next after taking the
2304 		 * anon_vma->root->rwsem. If some other vma in this mm shares
2305 		 * the same anon rmap we won't take it again.
2306 		 *
2307 		 * No need of atomic instructions here, head.next
2308 		 * can't change from under us thanks to the
2309 		 * anon_vma->root->rwsem.
2310 		 */
2311 		if (__test_and_set_bit(0, (unsigned long *)
2312 				       &anon_vma->root->rb_root.rb_root.rb_node))
2313 			BUG();
2314 	}
2315 }
2316 
2317 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
2318 {
2319 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2320 		/*
2321 		 * AS_MM_ALL_LOCKS can't change from under us because
2322 		 * we hold the mm_all_locks_mutex.
2323 		 *
2324 		 * Operations on ->flags have to be atomic because
2325 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
2326 		 * mm_all_locks_mutex, there may be other cpus
2327 		 * changing other bitflags in parallel to us.
2328 		 */
2329 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
2330 			BUG();
2331 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
2332 	}
2333 }
2334 
2335 /*
2336  * This operation locks against the VM for all pte/vma/mm related
2337  * operations that could ever happen on a certain mm. This includes
2338  * vmtruncate, try_to_unmap, and all page faults.
2339  *
2340  * The caller must take the mmap_lock in write mode before calling
2341  * mm_take_all_locks(). The caller isn't allowed to release the
2342  * mmap_lock until mm_drop_all_locks() returns.
2343  *
2344  * mmap_lock in write mode is required in order to block all operations
2345  * that could modify pagetables and free pages without need of
2346  * altering the vma layout. It's also needed in write mode to avoid new
2347  * anon rmaps being associated with existing vmas.
2348  *
2349  * A single task can't take more than one mm_take_all_locks() in a row
2350  * or it would deadlock.
2351  *
2352  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
2353  * mapping->flags avoid to take the same lock twice, if more than one
2354  * vma in this mm is backed by the same anon rmap or address_space.
2355  *
2356  * We take locks in following order, accordingly to comment at beginning
2357  * of mm/rmap.c:
2358  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
2359  *     hugetlb mapping);
2360  *   - all vmas marked locked
2361  *   - all i_mmap_rwsem locks;
2362  *   - all anon_vma->rwseml
2363  *
2364  * We can take all locks within these types randomly because the VM code
2365  * doesn't nest them and we protected from parallel mm_take_all_locks() by
2366  * mm_all_locks_mutex.
2367  *
2368  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
2369  * that may have to take thousand of locks.
2370  *
2371  * mm_take_all_locks() can fail if it's interrupted by signals.
2372  */
2373 int mm_take_all_locks(struct mm_struct *mm)
2374 {
2375 	struct vm_area_struct *vma;
2376 	struct anon_vma_chain *avc;
2377 	VMA_ITERATOR(vmi, mm, 0);
2378 
2379 	mmap_assert_write_locked(mm);
2380 
2381 	mutex_lock(&mm_all_locks_mutex);
2382 
2383 	/*
2384 	 * vma_start_write() does not have a complement in mm_drop_all_locks()
2385 	 * because vma_start_write() is always asymmetrical; it marks a VMA as
2386 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
2387 	 * is reached.
2388 	 */
2389 	for_each_vma(vmi, vma) {
2390 		if (signal_pending(current))
2391 			goto out_unlock;
2392 		vma_start_write(vma);
2393 	}
2394 
2395 	vma_iter_init(&vmi, mm, 0);
2396 	for_each_vma(vmi, vma) {
2397 		if (signal_pending(current))
2398 			goto out_unlock;
2399 		if (vma->vm_file && vma->vm_file->f_mapping &&
2400 				vma_is_hugetlb(vma))
2401 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
2402 	}
2403 
2404 	vma_iter_init(&vmi, mm, 0);
2405 	for_each_vma(vmi, vma) {
2406 		if (signal_pending(current))
2407 			goto out_unlock;
2408 		if (vma->vm_file && vma->vm_file->f_mapping &&
2409 				!vma_is_hugetlb(vma))
2410 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
2411 	}
2412 
2413 	vma_iter_init(&vmi, mm, 0);
2414 	for_each_vma(vmi, vma) {
2415 		if (signal_pending(current))
2416 			goto out_unlock;
2417 		if (vma_has_anon_rmap(vma))
2418 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2419 				vm_lock_anon_vma(mm, avc->anon_vma);
2420 	}
2421 
2422 	return 0;
2423 
2424 out_unlock:
2425 	mm_drop_all_locks(mm);
2426 	return -EINTR;
2427 }
2428 
2429 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
2430 {
2431 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
2432 		/*
2433 		 * The LSB of head.next can't change to 0 from under
2434 		 * us because we hold the mm_all_locks_mutex.
2435 		 *
2436 		 * We must however clear the bitflag before unlocking
2437 		 * the vma so the users using the anon_vma->rb_root will
2438 		 * never see our bitflag.
2439 		 *
2440 		 * No need of atomic instructions here, head.next
2441 		 * can't change from under us until we release the
2442 		 * anon_vma->root->rwsem.
2443 		 */
2444 		if (!__test_and_clear_bit(0, (unsigned long *)
2445 					  &anon_vma->root->rb_root.rb_root.rb_node))
2446 			BUG();
2447 		anon_vma_unlock_write(anon_vma);
2448 	}
2449 }
2450 
2451 static void vm_unlock_mapping(struct address_space *mapping)
2452 {
2453 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2454 		/*
2455 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
2456 		 * because we hold the mm_all_locks_mutex.
2457 		 */
2458 		i_mmap_unlock_write(mapping);
2459 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
2460 					&mapping->flags))
2461 			BUG();
2462 	}
2463 }
2464 
2465 /*
2466  * The mmap_lock cannot be released by the caller until
2467  * mm_drop_all_locks() returns.
2468  */
2469 void mm_drop_all_locks(struct mm_struct *mm)
2470 {
2471 	struct vm_area_struct *vma;
2472 	struct anon_vma_chain *avc;
2473 	VMA_ITERATOR(vmi, mm, 0);
2474 
2475 	mmap_assert_write_locked(mm);
2476 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
2477 
2478 	for_each_vma(vmi, vma) {
2479 		if (vma_has_anon_rmap(vma))
2480 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2481 				vm_unlock_anon_vma(avc->anon_vma);
2482 		if (vma->vm_file && vma->vm_file->f_mapping)
2483 			vm_unlock_mapping(vma->vm_file->f_mapping);
2484 	}
2485 
2486 	mutex_unlock(&mm_all_locks_mutex);
2487 }
2488 
2489 /*
2490  * We account for memory if it's a private writeable mapping,
2491  * not hugepages and VM_NORESERVE wasn't set.
2492  */
2493 static bool accountable_mapping(struct mmap_state *map)
2494 {
2495 	const struct file *file = map->vm_file;
2496 
2497 	/*
2498 	 * hugetlb has its own accounting separate from the core VM
2499 	 * VM_HUGETLB may not be set yet so we cannot check for that flag.
2500 	 */
2501 	if (file && is_file_hugepages(file))
2502 		return false;
2503 
2504 	return vma_flags_test(&map->vma_flags, VMA_WRITE_BIT) &&
2505 		!vma_flags_test_any(&map->vma_flags, VMA_NORESERVE_BIT,
2506 				    VMA_SHARED_BIT);
2507 }
2508 
2509 /*
2510  * vms_abort_munmap_vmas() - Undo as much as possible from an aborted munmap()
2511  * operation.
2512  * @vms: The vma unmap structure
2513  * @mas_detach: The maple state with the detached maple tree
2514  *
2515  * Reattach any detached vmas, free up the maple tree used to track the vmas.
2516  * If that's not possible because the ptes are cleared (and vm_ops->closed() may
2517  * have been called), then a NULL is written over the vmas and the vmas are
2518  * removed (munmap() completed).
2519  */
2520 static void vms_abort_munmap_vmas(struct vma_munmap_struct *vms,
2521 		struct ma_state *mas_detach)
2522 {
2523 	struct ma_state *mas = &vms->vmi->mas;
2524 
2525 	if (!vms->nr_pages)
2526 		return;
2527 
2528 	if (vms->clear_ptes)
2529 		return reattach_vmas(mas_detach);
2530 
2531 	/*
2532 	 * Aborting cannot just call the vm_ops open() because they are often
2533 	 * not symmetrical and state data has been lost.  Resort to the old
2534 	 * failure method of leaving a gap where the MAP_FIXED mapping failed.
2535 	 */
2536 	mas_set_range(mas, vms->start, vms->end - 1);
2537 	mas_store_gfp(mas, NULL, GFP_KERNEL|__GFP_NOFAIL);
2538 	/* Clean up the insertion of the unfortunate gap */
2539 	vms_complete_munmap_vmas(vms, mas_detach);
2540 }
2541 
2542 static void update_ksm_flags(struct mmap_state *map)
2543 {
2544 	map->vma_flags = ksm_vma_flags(map->mm, map->vm_file, map->vma_flags);
2545 }
2546 
2547 static void set_desc_from_map(struct vm_area_desc *desc,
2548 		const struct mmap_state *map)
2549 {
2550 	desc->start = map->addr;
2551 	desc->end = map->end;
2552 
2553 	desc->pgoff = map->pgoff;
2554 	desc->vm_file = map->vm_file;
2555 	desc->vma_flags = map->vma_flags;
2556 	desc->page_prot = map->page_prot;
2557 }
2558 
2559 /*
2560  * __mmap_setup() - Prepare to gather any overlapping VMAs that need to be
2561  * unmapped once the map operation is completed, check limits, account mapping
2562  * and clean up any pre-existing VMAs.
2563  *
2564  * As a result it sets up the @map and @desc objects.
2565  *
2566  * @map: Mapping state.
2567  * @desc: VMA descriptor
2568  * @uf:  Userfaultfd context list.
2569  *
2570  * Returns: 0 on success, error code otherwise.
2571  */
2572 static int __mmap_setup(struct mmap_state *map, struct vm_area_desc *desc,
2573 			struct list_head *uf)
2574 {
2575 	int error;
2576 	struct vma_iterator *vmi = map->vmi;
2577 	struct vma_munmap_struct *vms = &map->vms;
2578 
2579 	/* Find the first overlapping VMA and initialise unmap state. */
2580 	vms->vma = vma_find(vmi, map->end);
2581 	init_vma_munmap(vms, vmi, vms->vma, map->addr, map->end, uf,
2582 			/* unlock = */ false);
2583 
2584 	/* OK, we have overlapping VMAs - prepare to unmap them. */
2585 	if (vms->vma) {
2586 		mt_init_flags(&map->mt_detach,
2587 			      vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
2588 		mt_on_stack(map->mt_detach);
2589 		mas_init(&map->mas_detach, &map->mt_detach, /* addr = */ 0);
2590 		/* Prepare to unmap any existing mapping in the area */
2591 		error = vms_gather_munmap_vmas(vms, &map->mas_detach);
2592 		if (error) {
2593 			/* On error VMAs will already have been reattached. */
2594 			vms->nr_pages = 0;
2595 			return error;
2596 		}
2597 
2598 		map->next = vms->next;
2599 		map->prev = vms->prev;
2600 	} else {
2601 		map->next = vma_iter_next_rewind(vmi, &map->prev);
2602 	}
2603 
2604 	/* Check against address space limit. */
2605 	if (!may_expand_vm(map->mm, &map->vma_flags, map->pglen - vms->nr_pages))
2606 		return -ENOMEM;
2607 
2608 	/* Private writable mapping: check memory availability. */
2609 	if (accountable_mapping(map)) {
2610 		const unsigned long uncharged = map->pglen - vms->nr_accounted;
2611 
2612 		/* Charge only what's not already charged by mappings we replace. */
2613 		if (uncharged) {
2614 			error = security_vm_enough_memory_mm(map->mm, uncharged);
2615 			if (error)
2616 				return error;
2617 		}
2618 
2619 		/* Our new mapping owns the entire charge now. */
2620 		map->charged = map->pglen;
2621 		vms->nr_accounted = 0;
2622 		vma_flags_set(&map->vma_flags, VMA_ACCOUNT_BIT);
2623 	}
2624 
2625 	/*
2626 	 * Clear PTEs while the vma is still in the tree so that rmap
2627 	 * cannot race with the freeing later in the truncate scenario.
2628 	 * This is also needed for mmap_file(), which is why vm_ops
2629 	 * close function is called.
2630 	 */
2631 	vms_clean_up_area(vms, &map->mas_detach);
2632 
2633 	set_desc_from_map(desc, map);
2634 	return 0;
2635 }
2636 
2637 static bool map_same_file(struct mmap_state *map)
2638 {
2639 	return map->vm_file == map->file;
2640 }
2641 
2642 static int __mmap_new_file_vma(struct mmap_state *map,
2643 			       struct vm_area_struct *vma)
2644 {
2645 	struct vma_iterator *vmi = map->vmi;
2646 	int error;
2647 
2648 	vma->vm_file = map->vm_file;
2649 	if (map_same_file(map))
2650 		get_file(map->vm_file);
2651 
2652 	if (!map->vm_file->f_op->mmap)
2653 		return 0;
2654 
2655 	/*
2656 	 * Driver-specified flags may make the lock flags invalid, so clear
2657 	 * VMA_LOCKED_MASK and reinstate it afterwards if appropriate.
2658 	 */
2659 	vma_clear_flags_mask(vma, VMA_LOCKED_MASK);
2660 	error = mmap_file(vma->vm_file, vma);
2661 	map->vm_file = vma->vm_file;
2662 
2663 	if (error) {
2664 		UNMAP_STATE(unmap, vmi, vma, vma->vm_start, vma->vm_end,
2665 			    map->prev, map->next);
2666 
2667 		if (vma->vm_ops->close) {
2668 			zap_vma(vma);
2669 			/* Safe, because VMA zapped. */
2670 			vma_close(vma);
2671 		}
2672 		if (map_same_file(map))
2673 			fput(map->vm_file);
2674 
2675 		vma->vm_file = NULL;
2676 		vma_iter_set(vmi, vma->vm_end);
2677 		/* Undo any partial mapping done by a device driver. */
2678 		unmap_region(&unmap);
2679 		return error;
2680 	}
2681 
2682 	/*
2683 	 * If the VMA is still eligible for mlock(), reinstate any original
2684 	 * VMA_LOCKED_BIT and/or VMA_LOCKONFAULT_BIT flags.
2685 	 */
2686 	if (vma_supports_mlock(vma)) {
2687 		const vma_flags_t mask = vma_flags_and_mask(&map->vma_flags, VMA_LOCKED_MASK);
2688 
2689 		vma_set_flags_mask(vma, mask);
2690 	}
2691 
2692 	map->vma_flags = vma->flags;
2693 
2694 	return 0;
2695 }
2696 
2697 static void map_set_anon(struct mmap_state *map)
2698 {
2699 	map->vm_file = NULL;
2700 	map->vm_ops = NULL;
2701 	map->pgoff = map->addr >> PAGE_SHIFT;
2702 }
2703 
2704 static bool map_is_private(const struct mmap_state *map)
2705 {
2706 	return !vma_flags_test(&map->vma_flags, VMA_SHARED_BIT);
2707 }
2708 
2709 static bool map_is_anon(const struct mmap_state *map)
2710 {
2711 	return map_is_private(map) && !map->vm_file;
2712 }
2713 
2714 /*
2715  * __mmap_new_vma() - Allocate a new VMA for the region, as merging was not
2716  * possible.
2717  *
2718  * @map:  Mapping state.
2719  * @vmap: Output pointer for the new VMA.
2720  * @action: Any mmap_prepare action that is still to complete.
2721  *
2722  * Returns: Zero on success, or an error.
2723  */
2724 static int __mmap_new_vma(struct mmap_state *map, struct vm_area_struct **vmap,
2725 	struct mmap_action *action)
2726 {
2727 	const bool is_anon = map_is_anon(map);
2728 	struct vma_iterator *vmi = map->vmi;
2729 	int error = 0;
2730 	struct vm_area_struct *vma;
2731 
2732 	/*
2733 	 * Determine the object being mapped and call the appropriate
2734 	 * specific mapper. the address has already been validated, but
2735 	 * not unmapped, but the maps are removed from the list.
2736 	 */
2737 	vma = vm_area_alloc(map->mm);
2738 	if (!vma)
2739 		return -ENOMEM;
2740 
2741 	vma_iter_config(vmi, map->addr, map->end);
2742 
2743 	if (is_anon)
2744 		vma_set_anonymous(vma);
2745 
2746 	vma_set_range(vma, map->addr, map->end, map->pgoff, map->anon_pgoff);
2747 	vma->flags = map->vma_flags;
2748 	vma->vm_page_prot = map->page_prot;
2749 
2750 	if (vma_iter_prealloc(vmi, vma)) {
2751 		error = -ENOMEM;
2752 		goto free_vma;
2753 	}
2754 
2755 	/* Invoke callbacks. */
2756 	if (map->vm_file)
2757 		error = __mmap_new_file_vma(map, vma);
2758 	else if (!is_anon)
2759 		error = shmem_zero_setup(vma);
2760 
2761 	if (error)
2762 		goto free_iter_vma;
2763 
2764 	if (!map->check_ksm_early) {
2765 		update_ksm_flags(map);
2766 		vma->flags = map->vma_flags;
2767 	}
2768 
2769 	/* Lock the VMA since it is modified after insertion into VMA tree */
2770 	vma_start_write(vma);
2771 	vma_iter_store_new(vmi, vma);
2772 	map->mm->map_count++;
2773 	vma_link_file(vma, action->hide_from_rmap_until_complete);
2774 
2775 	/*
2776 	 * vma_merge_new_range() calls khugepaged_enter_vma() too, the below
2777 	 * call covers the non-merge case.
2778 	 */
2779 	if (!vma_is_anonymous(vma))
2780 		khugepaged_enter_vma(vma, map->vm_flags);
2781 	*vmap = vma;
2782 	return 0;
2783 
2784 free_iter_vma:
2785 	vma_iter_free(vmi);
2786 free_vma:
2787 	vm_area_free(vma);
2788 	return error;
2789 }
2790 
2791 /*
2792  * __mmap_complete() - Unmap any VMAs we overlap, account memory mapping
2793  *                     statistics, handle locking and finalise the VMA.
2794  *
2795  * @map: Mapping state.
2796  * @vma: Merged or newly allocated VMA for the mmap()'d region.
2797  */
2798 static void __mmap_complete(struct mmap_state *map, struct vm_area_struct *vma)
2799 {
2800 	struct mm_struct *mm = map->mm;
2801 
2802 	perf_event_mmap(vma);
2803 
2804 	/* Unmap any existing mapping in the area. */
2805 	vms_complete_munmap_vmas(&map->vms, &map->mas_detach);
2806 
2807 	vm_stat_account(mm, vma->vm_flags, map->pglen);
2808 	if (vma_test(vma, VMA_LOCKED_BIT)) {
2809 		if (!vma_supports_mlock(vma))
2810 			vma_clear_flags_mask(vma, VMA_LOCKED_MASK);
2811 		else
2812 			mm->locked_vm += map->pglen;
2813 	}
2814 
2815 	if (vma->vm_file)
2816 		uprobe_mmap(vma);
2817 
2818 	/*
2819 	 * New (or expanded) vma always get soft dirty status.
2820 	 * Otherwise user-space soft-dirty page tracker won't
2821 	 * be able to distinguish situation when vma area unmapped,
2822 	 * then new mapped in-place (which must be aimed as
2823 	 * a completely new data area).
2824 	 */
2825 	if (pgtable_supports_soft_dirty())
2826 		vma_set_flags(vma, VMA_SOFTDIRTY_BIT);
2827 
2828 	vma_set_page_prot(vma);
2829 }
2830 
2831 /* Check to ensure that the VMA flags of a newly mapped VMA are sane. */
2832 static int mmap_validate_vma_flags(const vma_flags_t *flags)
2833 {
2834 #ifdef CONFIG_SPARC64
2835 	const vm_flags_t legacy_flags = vma_flags_to_legacy(*flags);
2836 
2837 	/* TODO: Fix SPARC ADI! */
2838 	if (WARN_ON_ONCE(!arch_validate_flags(legacy_flags)))
2839 		return -EINVAL;
2840 #endif
2841 
2842 	if (vma_flags_is_mm_managed(flags)) {
2843 		/* mm-managed mappings may not set VMA_IO_BIT. */
2844 		if (WARN_ON_ONCE(vma_flags_test(flags, VMA_IO_BIT)))
2845 			return -EINVAL;
2846 	}
2847 
2848 	return 0;
2849 }
2850 
2851 /* Check to ensure a driver hasn't done something crazy. */
2852 static int mmap_validate(unsigned long orig_start, unsigned long orig_end,
2853 			 unsigned long curr_start, unsigned long curr_end,
2854 			 const vma_flags_t *orig_flags,
2855 			 const vma_flags_t *curr_flags)
2856 {
2857 	bool was_maywrite, is_maywrite;
2858 
2859 	/* Drivers cannot alter the range of the VMA. */
2860 	if (WARN_ON_ONCE(orig_start != curr_start || orig_end != curr_end))
2861 		return -EINVAL;
2862 
2863 	was_maywrite = vma_flags_test(orig_flags, VMA_MAYWRITE_BIT);
2864 	is_maywrite = vma_flags_test(curr_flags, VMA_MAYWRITE_BIT);
2865 
2866 	/* A driver may not make a previously unwritable mapping writable. */
2867 	if (WARN_ON_ONCE(!was_maywrite && is_maywrite))
2868 		return -EINVAL;
2869 
2870 	/* mm-managed mappings may not clear VMA_MAYWRITE_BIT. */
2871 	if (vma_flags_is_mm_managed(curr_flags) &&
2872 	    WARN_ON_ONCE(was_maywrite && !is_maywrite))
2873 		return -EINVAL;
2874 
2875 	return mmap_validate_vma_flags(curr_flags);
2876 }
2877 
2878 /**
2879  * mmap_prepare_validate() - Ensure the driver hasn't violated invariants in its
2880  * f_op->mmap_prepare hook.
2881  * @orig_desc: The VMA descriptor prior to the mmap_prepare hook being called.
2882  * @desc: The VMA descriptor after the mmap_prepare hook has been called.
2883  *
2884  * Returns: 0 on success, otherwise an error.
2885  */
2886 int mmap_prepare_validate(const struct vm_area_desc *orig_desc,
2887 			  const struct vm_area_desc *desc)
2888 {
2889 	/*
2890 	 * It is not valid to execute mmap actions for VMAs which can be merged,
2891 	 * as any such merge would leave portions of the mapping incorrectly
2892 	 * unmapped.
2893 	 *
2894 	 * This is checked after mmap_action_prepare(), as it may update the VMA
2895 	 * flags and therefore whether the VMA can be merged.
2896 	 */
2897 	if (vma_flags_can_merge(&desc->vma_flags) &&
2898 	    WARN_ON_ONCE(desc->action.type != MMAP_NOTHING))
2899 		return -EINVAL;
2900 
2901 	return mmap_validate(orig_desc->start, orig_desc->end,
2902 			     desc->start, desc->end,
2903 			     &orig_desc->vma_flags, &desc->vma_flags);
2904 }
2905 
2906 /**
2907  * mmap_hook_validate() - Ensure the driver hasn't violated invariants in
2908  * its f_op->mmap hook.
2909  * @orig_start: The start of the mapping prior to the mmap hook.
2910  * @orig_end: The end of the mapping prior to the mmap hook.
2911  * @orig_flags: The VMA flags set for the VMA prior to the mmap hook.
2912  * @vma: The VMA after the hook has been applied.
2913  *
2914  * Returns: 0 on success, otherwise an error.
2915  */
2916 int mmap_hook_validate(unsigned long orig_start, unsigned long orig_end,
2917 		       const vma_flags_t *orig_flags,
2918 		       const struct vm_area_struct *vma)
2919 {
2920 	const unsigned long start = vma->vm_start;
2921 	const unsigned long end = vma->vm_end;
2922 	const vma_flags_t *flags = &vma->flags;
2923 
2924 	return mmap_validate(orig_start, orig_end, start, end, orig_flags,
2925 			     flags);
2926 }
2927 
2928 static int call_action_prepare(struct mmap_state *map,
2929 			       struct vm_area_desc *desc)
2930 {
2931 	int err;
2932 
2933 	err = mmap_action_prepare(desc);
2934 	if (err)
2935 		return err;
2936 
2937 	return 0;
2938 }
2939 
2940 /*
2941  * Invoke the f_op->mmap_prepare() callback for a file-backed mapping that
2942  * specifies it.
2943  *
2944  * This is called prior to any merge attempt, and updates whitelisted fields
2945  * that are permitted to be updated by the caller.
2946  *
2947  * All but user-defined fields will be pre-populated with original values.
2948  *
2949  * Returns 0 on success, or an error code otherwise.
2950  */
2951 static int call_mmap_prepare(struct mmap_state *map,
2952 		struct vm_area_desc *desc)
2953 {
2954 	const struct vm_area_desc orig_desc = *desc;
2955 	int err;
2956 
2957 	/* Invoke the hook. */
2958 	err = vfs_mmap_prepare(map->vm_file, desc);
2959 	if (err)
2960 		return err;
2961 
2962 	/* Update first so file refcount tracked correctly. */
2963 	if (desc->vm_file != map->vm_file)
2964 		map->vm_file = desc->vm_file;
2965 
2966 	/* It's invalid for mmap_prepare hooks to clear vm_ops. */
2967 	if (!desc->vm_ops)
2968 		return -EINVAL;
2969 
2970 	err = call_action_prepare(map, desc);
2971 	if (err)
2972 		return err;
2973 
2974 	/* Check the caller did nothing crazy. */
2975 	err = mmap_prepare_validate(&orig_desc, desc);
2976 	if (err)
2977 		return err;
2978 
2979 	/* Update fields permitted to be changed. */
2980 	map->pgoff = desc->pgoff;
2981 	map->vma_flags = desc->vma_flags;
2982 	map->page_prot = desc->page_prot;
2983 	/* User-defined fields. */
2984 	map->vm_ops = desc->vm_ops;
2985 	map->vm_private_data = desc->private_data;
2986 
2987 	/*
2988 	 * MAP_PRIVATE-/dev/zero mappings are an ancient way of getting
2989 	 * anonymous mappings. Rather than allowing these mappings to be odd
2990 	 * outliers, simply make them truly anonymous.
2991 	 */
2992 	if (map_is_private(map) && file_is_dev_zero(map->vm_file))
2993 		map_set_anon(map);
2994 
2995 	return 0;
2996 }
2997 
2998 static void set_vma_user_defined_fields(struct vm_area_struct *vma,
2999 		struct mmap_state *map)
3000 {
3001 	vma->vm_ops = map->vm_ops;
3002 	vma->vm_private_data = map->vm_private_data;
3003 }
3004 
3005 /*
3006  * Are we guaranteed no driver can change state such as to preclude KSM merging?
3007  * If so, let's set the KSM mergeable flag early so we don't break VMA merging.
3008  */
3009 static bool can_set_ksm_flags_early(struct mmap_state *map)
3010 {
3011 	struct file *file = map->vm_file;
3012 
3013 	/* Anonymous mappings have no driver which can change them. */
3014 	if (!file)
3015 		return true;
3016 
3017 	/*
3018 	 * If .mmap_prepare() is specified, then the driver will have already
3019 	 * manipulated state prior to updating KSM flags. So no need to worry
3020 	 * about mmap callbacks modifying VMA flags after the KSM flag has been
3021 	 * updated here, which could otherwise affect KSM eligibility.
3022 	 */
3023 	if (file->f_op->mmap_prepare)
3024 		return true;
3025 
3026 	/* shmem is safe. */
3027 	if (shmem_file(file))
3028 		return true;
3029 
3030 	/* Any other .mmap callback is not safe. */
3031 	return false;
3032 }
3033 
3034 static void map_put_vm_file(struct mmap_state *map)
3035 {
3036 	/*
3037 	 * An error occurred or the VMA was merged.
3038 	 *
3039 	 * If the file was changed by the driver (which is required to increment
3040 	 * the replacement file's reference count), drop its reference count.
3041 	 *
3042 	 * On error, the caller always drops the original file regardless.
3043 	 */
3044 	if (map->vm_file && !map_same_file(map))
3045 		fput(map->vm_file);
3046 }
3047 
3048 static unsigned long __mmap_region(struct file *file, unsigned long addr,
3049 		unsigned long len, vma_flags_t vma_flags,
3050 		unsigned long pgoff, struct list_head *uf)
3051 {
3052 	struct mm_struct *mm = current->mm;
3053 	struct vm_area_struct *vma = NULL;
3054 	const bool have_mmap_prepare = file && file->f_op->mmap_prepare;
3055 	VMA_ITERATOR(vmi, mm, addr);
3056 	const pgoff_t anon_pgoff = addr >> PAGE_SHIFT;
3057 	MMAP_STATE(map, mm, &vmi, addr, len, pgoff, anon_pgoff, vma_flags, file);
3058 	struct vm_area_desc desc = {
3059 		.mm = mm,
3060 		.file = file,
3061 		.action = {
3062 			.type = MMAP_NOTHING, /* Default to no further action. */
3063 		},
3064 		.vm_ops = &vma_dummy_vm_ops,
3065 	};
3066 	bool allocated_new = false;
3067 	int error;
3068 
3069 	map.check_ksm_early = can_set_ksm_flags_early(&map);
3070 
3071 	error = __mmap_setup(&map, &desc, uf);
3072 	if (error)
3073 		goto abort_munmap;
3074 	if (have_mmap_prepare)
3075 		error = call_mmap_prepare(&map, &desc);
3076 	if (error)
3077 		goto unacct_error;
3078 
3079 	if (map.check_ksm_early)
3080 		update_ksm_flags(&map);
3081 
3082 	/* Attempt to merge with adjacent VMAs... */
3083 	if (map.prev || map.next) {
3084 		VMG_MMAP_STATE(vmg, &map, /* vma = */ NULL);
3085 
3086 		vma = vma_merge_new_range(&vmg);
3087 	}
3088 
3089 	/* ...but if we can't, allocate a new VMA. */
3090 	if (!vma) {
3091 		error = __mmap_new_vma(&map, &vma, &desc.action);
3092 		if (error)
3093 			goto unacct_error;
3094 		allocated_new = true;
3095 	}
3096 
3097 	if (have_mmap_prepare && !map_is_anon(&map) && allocated_new)
3098 		set_vma_user_defined_fields(vma, &map);
3099 
3100 	__mmap_complete(&map, vma);
3101 
3102 	if (!allocated_new) {
3103 		/* Merged, so need to drop refcount. */
3104 		map_put_vm_file(&map);
3105 	} else if (have_mmap_prepare) {
3106 		error = mmap_action_complete(vma, &desc.action,
3107 					     /*is_compat=*/false);
3108 		if (error)
3109 			return error;
3110 	}
3111 
3112 	return addr;
3113 
3114 	/* Accounting was done by __mmap_setup(). */
3115 unacct_error:
3116 	if (map.charged)
3117 		vm_unacct_memory(map.charged);
3118 abort_munmap:
3119 	map_put_vm_file(&map);
3120 	vms_abort_munmap_vmas(&map.vms, &map.mas_detach);
3121 	return error;
3122 }
3123 
3124 /**
3125  * mmap_region() - Actually perform the userland mapping of a VMA into
3126  * current->mm with known, aligned and overflow-checked @addr and @len, and
3127  * correctly determined VMA flags @vm_flags and page offset @pgoff.
3128  *
3129  * This is an internal memory management function, and should not be used
3130  * directly.
3131  *
3132  * The caller must write-lock current->mm->mmap_lock.
3133  *
3134  * @file: If a file-backed mapping, a pointer to the struct file describing the
3135  * file to be mapped, otherwise NULL.
3136  * @addr: The page-aligned address at which to perform the mapping.
3137  * @len: The page-aligned, non-zero, length of the mapping.
3138  * @vma_flags: The VMA flags which should be applied to the mapping.
3139  * @pgoff: If @file is specified, the page offset into the file, if not then
3140  * the virtual page offset in memory of the anonymous mapping.
3141  * @uf: Optionally, a pointer to a list head used for tracking userfaultfd unmap
3142  * events.
3143  *
3144  * Returns: Either an error, or the address at which the requested mapping has
3145  * been performed.
3146  */
3147 unsigned long mmap_region(struct file *file, unsigned long addr,
3148 			  unsigned long len, vma_flags_t vma_flags,
3149 			  unsigned long pgoff, struct list_head *uf)
3150 {
3151 	unsigned long ret;
3152 	bool writable_file_mapping = false;
3153 
3154 	mmap_assert_write_locked(current->mm);
3155 
3156 	/* Check to see if MDWE is applicable. */
3157 	if (map_deny_write_exec(&vma_flags, &vma_flags))
3158 		return -EACCES;
3159 
3160 	/* Allow architectures to sanity-check the vm_flags. */
3161 	if (!arch_validate_flags(vma_flags_to_legacy(vma_flags)))
3162 		return -EINVAL;
3163 
3164 	/* Map writable and ensure this isn't a sealed memfd. */
3165 	if (file && is_shared_maywrite(&vma_flags)) {
3166 		int error = mapping_map_writable(file->f_mapping);
3167 
3168 		if (error)
3169 			return error;
3170 		writable_file_mapping = true;
3171 	}
3172 
3173 	ret = __mmap_region(file, addr, len, vma_flags, pgoff, uf);
3174 
3175 	/* Clear our write mapping regardless of error. */
3176 	if (writable_file_mapping)
3177 		mapping_unmap_writable(file->f_mapping);
3178 
3179 	validate_mm(current->mm);
3180 	return ret;
3181 }
3182 
3183 /**
3184  * do_brk_flags() - Increase the brk vma if the flags match.
3185  * @vmi: The vma iterator
3186  * @addr: The start address
3187  * @len: The length of the increase
3188  * @vma: The vma,
3189  * @vma_flags: The VMA Flags
3190  *
3191  * Extend the brk VMA from addr to addr + len.  If the VMA is NULL or the flags
3192  * do not match then create a new anonymous VMA.  Eventually we may be able to
3193  * do some brk-specific accounting here.
3194  *
3195  * Returns: %0 on success, or otherwise an error.
3196  */
3197 int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
3198 		 unsigned long addr, unsigned long len, vma_flags_t vma_flags)
3199 {
3200 	struct mm_struct *mm = current->mm;
3201 	const pgoff_t pgoff = addr >> PAGE_SHIFT;
3202 
3203 	/*
3204 	 * Check against address space limits by the changed size
3205 	 * Note: This happens *after* clearing old mappings in some code paths.
3206 	 */
3207 	vma_flags_set_mask(&vma_flags, VMA_DATA_DEFAULT_FLAGS);
3208 	vma_flags_set(&vma_flags, VMA_ACCOUNT_BIT);
3209 	vma_flags_set_mask(&vma_flags, mm->def_vma_flags);
3210 
3211 	vma_flags = ksm_vma_flags(mm, NULL, vma_flags);
3212 	if (!may_expand_vm(mm, &vma_flags, len >> PAGE_SHIFT))
3213 		return -ENOMEM;
3214 
3215 	if (mm->map_count > get_sysctl_max_map_count())
3216 		return -ENOMEM;
3217 
3218 	if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3219 		return -ENOMEM;
3220 
3221 	/*
3222 	 * Expand the existing vma if possible; Note that singular lists do not
3223 	 * occur after forking, so the expand will only happen on new VMAs.
3224 	 */
3225 	if (vma && vma->vm_end == addr) {
3226 		VMG_STATE(vmg, mm, vmi, addr, addr + len, vma_flags, pgoff, pgoff);
3227 
3228 		vmg.prev = vma;
3229 		/* vmi is positioned at prev, which this mode expects. */
3230 		vmg.just_expand = true;
3231 
3232 		if (vma_merge_new_range(&vmg))
3233 			goto out;
3234 		else if (vmg_nomem(&vmg))
3235 			goto unacct_fail;
3236 	}
3237 
3238 	if (vma)
3239 		vma_iter_next_range(vmi);
3240 	/* create a vma struct for an anonymous mapping */
3241 	vma = vm_area_alloc(mm);
3242 	if (!vma)
3243 		goto unacct_fail;
3244 
3245 	vma_set_anonymous(vma);
3246 	vma_set_range(vma, addr, addr + len, pgoff, pgoff);
3247 	vma->flags = vma_flags;
3248 	vma->vm_page_prot = vm_get_page_prot(vma_flags_to_legacy(vma_flags));
3249 	vma_start_write(vma);
3250 	if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
3251 		goto mas_store_fail;
3252 
3253 	mm->map_count++;
3254 	validate_mm(mm);
3255 out:
3256 	perf_event_mmap(vma);
3257 	mm->total_vm += len >> PAGE_SHIFT;
3258 	mm->data_vm += len >> PAGE_SHIFT;
3259 	if (vma_flags_test(&vma_flags, VMA_LOCKED_BIT))
3260 		mm->locked_vm += (len >> PAGE_SHIFT);
3261 	if (pgtable_supports_soft_dirty())
3262 		vma_set_flags(vma, VMA_SOFTDIRTY_BIT);
3263 	return 0;
3264 
3265 mas_store_fail:
3266 	vm_area_free(vma);
3267 unacct_fail:
3268 	vm_unacct_memory(len >> PAGE_SHIFT);
3269 	return -ENOMEM;
3270 }
3271 
3272 /**
3273  * unmapped_area() - Find an area between the low_limit and the high_limit with
3274  * the correct alignment and offset, all from @info. Note: current->mm is used
3275  * for the search.
3276  *
3277  * @info: The unmapped area information including the range [low_limit -
3278  * high_limit), the alignment offset and mask.
3279  *
3280  * Return: A memory address or -ENOMEM.
3281  */
3282 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
3283 {
3284 	unsigned long length, gap;
3285 	unsigned long low_limit, high_limit;
3286 	struct vm_area_struct *tmp;
3287 	VMA_ITERATOR(vmi, current->mm, 0);
3288 
3289 	/* Adjust search length to account for worst case alignment overhead */
3290 	length = info->length + info->align_mask + info->start_gap;
3291 	if (length < info->length)
3292 		return -ENOMEM;
3293 
3294 	low_limit = info->low_limit;
3295 	if (low_limit < mmap_min_addr)
3296 		low_limit = mmap_min_addr;
3297 	high_limit = info->high_limit;
3298 retry:
3299 	if (vma_iter_area_lowest(&vmi, low_limit, high_limit, length))
3300 		return -ENOMEM;
3301 
3302 	/*
3303 	 * Adjust for the gap first so it doesn't interfere with the later
3304 	 * alignment. The first step is the minimum needed to fulfill the start
3305 	 * gap, the next step is the minimum to align that. It is the minimum
3306 	 * needed to fulfill both.
3307 	 */
3308 	gap = vma_iter_addr(&vmi) + info->start_gap;
3309 	gap += (info->align_offset - gap) & info->align_mask;
3310 	tmp = vma_next(&vmi);
3311 	/* Avoid prev check if possible */
3312 	if (tmp && vma_test_any_mask(tmp, VMA_STARTGAP_FLAGS)) {
3313 		if (vm_start_gap(tmp) < gap + length - 1) {
3314 			low_limit = tmp->vm_end;
3315 			vma_iter_reset(&vmi);
3316 			goto retry;
3317 		}
3318 	} else {
3319 		tmp = vma_prev(&vmi);
3320 		if (tmp && vm_end_gap(tmp) > gap) {
3321 			low_limit = vm_end_gap(tmp);
3322 			vma_iter_reset(&vmi);
3323 			goto retry;
3324 		}
3325 	}
3326 
3327 	return gap;
3328 }
3329 
3330 /**
3331  * unmapped_area_topdown() - Find an area between the low_limit and the
3332  * high_limit with the correct alignment and offset at the highest available
3333  * address, all from @info. Note: current->mm is used for the search.
3334  *
3335  * @info: The unmapped area information including the range [low_limit -
3336  * high_limit), the alignment offset and mask.
3337  *
3338  * Return: A memory address or -ENOMEM.
3339  */
3340 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
3341 {
3342 	unsigned long length, gap, gap_end;
3343 	unsigned long low_limit, high_limit;
3344 	struct vm_area_struct *tmp;
3345 	VMA_ITERATOR(vmi, current->mm, 0);
3346 
3347 	/* Adjust search length to account for worst case alignment overhead */
3348 	length = info->length + info->align_mask + info->start_gap;
3349 	if (length < info->length)
3350 		return -ENOMEM;
3351 
3352 	low_limit = info->low_limit;
3353 	if (low_limit < mmap_min_addr)
3354 		low_limit = mmap_min_addr;
3355 	high_limit = info->high_limit;
3356 retry:
3357 	if (vma_iter_area_highest(&vmi, low_limit, high_limit, length))
3358 		return -ENOMEM;
3359 
3360 	gap = vma_iter_end(&vmi) - info->length;
3361 	gap -= (gap - info->align_offset) & info->align_mask;
3362 	gap_end = vma_iter_end(&vmi);
3363 	tmp = vma_next(&vmi);
3364 	 /* Avoid prev check if possible */
3365 	if (tmp && vma_test_any_mask(tmp, VMA_STARTGAP_FLAGS)) {
3366 		if (vm_start_gap(tmp) < gap_end) {
3367 			high_limit = vm_start_gap(tmp);
3368 			vma_iter_reset(&vmi);
3369 			goto retry;
3370 		}
3371 	} else {
3372 		tmp = vma_prev(&vmi);
3373 		if (tmp && vm_end_gap(tmp) > gap) {
3374 			high_limit = tmp->vm_start;
3375 			vma_iter_reset(&vmi);
3376 			goto retry;
3377 		}
3378 	}
3379 
3380 	return gap;
3381 }
3382 
3383 /*
3384  * Verify that the stack growth is acceptable and
3385  * update accounting. This is shared with both the
3386  * grow-up and grow-down cases.
3387  */
3388 static int acct_stack_growth(struct vm_area_struct *vma,
3389 			     unsigned long size, unsigned long grow)
3390 {
3391 	struct mm_struct *mm = vma->vm_mm;
3392 	unsigned long new_start;
3393 
3394 	/* address space limit tests */
3395 	if (!may_expand_vm(mm, &vma->flags, grow))
3396 		return -ENOMEM;
3397 
3398 	/* Stack limit test */
3399 	if (size > rlimit(RLIMIT_STACK))
3400 		return -ENOMEM;
3401 
3402 	/* mlock limit tests */
3403 	if (!mlock_future_ok(mm, vma_test(vma, VMA_LOCKED_BIT),
3404 			     grow << PAGE_SHIFT))
3405 		return -ENOMEM;
3406 
3407 	/* Check to ensure the stack will not grow into a hugetlb-only region */
3408 	new_start = vma->vm_end - size;
3409 #ifdef CONFIG_STACK_GROWSUP
3410 	if (vma_test(vma, VMA_GROWSUP_BIT))
3411 		new_start = vma->vm_start;
3412 #endif
3413 	if (is_hugepage_only_range(vma->vm_mm, new_start, size))
3414 		return -EFAULT;
3415 
3416 	/*
3417 	 * Overcommit..  This must be the final test, as it will
3418 	 * update security statistics.
3419 	 */
3420 	if (vma_test(vma, VMA_ACCOUNT_BIT) &&
3421 	    security_vm_enough_memory_mm(mm, grow))
3422 		return -ENOMEM;
3423 
3424 	return 0;
3425 }
3426 
3427 #ifdef CONFIG_STACK_GROWSUP
3428 /*
3429  * PA-RISC uses this for its stack.
3430  * vma is the last one with address > vma->vm_end.  Have to extend vma.
3431  */
3432 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
3433 {
3434 	struct mm_struct *mm = vma->vm_mm;
3435 	struct vm_area_struct *next;
3436 	unsigned long gap_addr;
3437 	int error = 0;
3438 	VMA_ITERATOR(vmi, mm, vma->vm_start);
3439 
3440 	if (!vma_test(vma, VMA_GROWSUP_BIT))
3441 		return -EFAULT;
3442 
3443 	mmap_assert_write_locked(mm);
3444 
3445 	/* Guard against exceeding limits of the address space. */
3446 	address &= PAGE_MASK;
3447 	if (address >= (TASK_SIZE & PAGE_MASK))
3448 		return -ENOMEM;
3449 	address += PAGE_SIZE;
3450 
3451 	/* Enforce stack_guard_gap */
3452 	gap_addr = address + stack_guard_gap;
3453 
3454 	/* Guard against overflow */
3455 	if (gap_addr < address || gap_addr > TASK_SIZE)
3456 		gap_addr = TASK_SIZE;
3457 
3458 	next = find_vma_intersection(mm, vma->vm_end, gap_addr);
3459 	if (next && vma_is_accessible(next)) {
3460 		if (!vma_test(next, VMA_GROWSUP_BIT))
3461 			return -ENOMEM;
3462 		/* Check that both stack segments have the same anon rmap? */
3463 	}
3464 
3465 	if (next)
3466 		vma_iter_prev_range_limit(&vmi, address);
3467 
3468 	vma_iter_config(&vmi, vma->vm_start, address);
3469 	if (vma_iter_prealloc(&vmi, vma))
3470 		return -ENOMEM;
3471 
3472 	/* We must make sure the anon rmap is allocated. */
3473 	if (unlikely(anon_vma_prepare(vma))) {
3474 		vma_iter_free(&vmi);
3475 		return -ENOMEM;
3476 	}
3477 
3478 	/* Lock the VMA before expanding to prevent concurrent page faults */
3479 	vma_start_write(vma);
3480 	/* We update the anon VMA tree. */
3481 	anon_vma_lock_write(vma->anon_vma);
3482 
3483 	/* Somebody else might have raced and expanded it already */
3484 	if (address > vma->vm_end) {
3485 		const unsigned long size = address - vma->vm_start;
3486 		const unsigned long grow = (address - vma->vm_end) >> PAGE_SHIFT;
3487 		const pgoff_t pgoff = vma_start_pgoff(vma);
3488 
3489 		error = -ENOMEM;
3490 		if (pgoff + (size >> PAGE_SHIFT) >= pgoff) {
3491 			error = acct_stack_growth(vma, size, grow);
3492 			if (!error) {
3493 				if (vma_test(vma, VMA_LOCKED_BIT))
3494 					mm->locked_vm += grow;
3495 				vm_stat_account(mm, vma->vm_flags, grow);
3496 				anon_rmap_tree_pre_update_vma(vma, true);
3497 				vma->vm_end = address;
3498 				/* Overwrite old entry in mtree. */
3499 				vma_iter_store_overwrite(&vmi, vma);
3500 				anon_rmap_tree_post_update_vma(vma, true);
3501 
3502 				perf_event_mmap(vma);
3503 			}
3504 		}
3505 	}
3506 	anon_vma_unlock_write(vma->anon_vma);
3507 	vma_iter_free(&vmi);
3508 	validate_mm(mm);
3509 	return error;
3510 }
3511 #endif /* CONFIG_STACK_GROWSUP */
3512 
3513 /*
3514  * vma is the first one with address < vma->vm_start.  Have to extend vma.
3515  * mmap_lock held for writing.
3516  */
3517 int expand_downwards(struct vm_area_struct *vma, unsigned long address)
3518 {
3519 	struct mm_struct *mm = vma->vm_mm;
3520 	struct vm_area_struct *prev;
3521 	int error = 0;
3522 	VMA_ITERATOR(vmi, mm, vma->vm_start);
3523 
3524 	if (!vma_test(vma, VMA_GROWSDOWN_BIT))
3525 		return -EFAULT;
3526 
3527 	mmap_assert_write_locked(mm);
3528 
3529 	address &= PAGE_MASK;
3530 	if (address < mmap_min_addr || address < FIRST_USER_ADDRESS)
3531 		return -EPERM;
3532 
3533 	/* Enforce stack_guard_gap */
3534 	prev = vma_prev(&vmi);
3535 	/* Check that both stack segments have the same anon rmap? */
3536 	if (prev) {
3537 		if (!vma_test(prev, VMA_GROWSDOWN_BIT) &&
3538 		    vma_is_accessible(prev) &&
3539 		    (address - prev->vm_end < stack_guard_gap))
3540 			return -ENOMEM;
3541 	}
3542 
3543 	if (prev)
3544 		vma_iter_next_range_limit(&vmi, vma->vm_start);
3545 
3546 	vma_iter_config(&vmi, address, vma->vm_end);
3547 	if (vma_iter_prealloc(&vmi, vma))
3548 		return -ENOMEM;
3549 
3550 	/* We must make sure the anon rmap is allocated. */
3551 	if (unlikely(anon_vma_prepare(vma))) {
3552 		vma_iter_free(&vmi);
3553 		return -ENOMEM;
3554 	}
3555 
3556 	/* Lock the VMA before expanding to prevent concurrent page faults */
3557 	vma_start_write(vma);
3558 	/* We update the anon VMA tree. */
3559 	anon_vma_lock_write(vma->anon_vma);
3560 
3561 	/* Somebody else might have raced and expanded it already */
3562 	if (address < vma->vm_start) {
3563 		const unsigned long size = vma->vm_end - address;
3564 		const unsigned long grow = (vma->vm_start - address) >> PAGE_SHIFT;
3565 
3566 		error = -ENOMEM;
3567 		if (grow <= vma_start_pgoff(vma)) {
3568 			error = acct_stack_growth(vma, size, grow);
3569 			if (!error) {
3570 				if (vma_test(vma, VMA_LOCKED_BIT))
3571 					mm->locked_vm += grow;
3572 				vm_stat_account(mm, vma->vm_flags, grow);
3573 				anon_rmap_tree_pre_update_vma(vma, false);
3574 				vma->vm_start = address;
3575 				vma_sub_pgoff(vma, grow);
3576 				/* Overwrite old entry in mtree. */
3577 				vma_iter_store_overwrite(&vmi, vma);
3578 				anon_rmap_tree_post_update_vma(vma, false);
3579 
3580 				perf_event_mmap(vma);
3581 			}
3582 		}
3583 	}
3584 	anon_vma_unlock_write(vma->anon_vma);
3585 	vma_iter_free(&vmi);
3586 	validate_mm(mm);
3587 	return error;
3588 }
3589 
3590 int __vm_munmap(unsigned long start, size_t len, bool unlock)
3591 {
3592 	int ret;
3593 	struct mm_struct *mm = current->mm;
3594 	LIST_HEAD(uf);
3595 	VMA_ITERATOR(vmi, mm, start);
3596 
3597 	if (mmap_write_lock_killable(mm))
3598 		return -EINTR;
3599 
3600 	ret = do_vmi_munmap(&vmi, mm, start, len, &uf, unlock);
3601 	if (ret || !unlock)
3602 		mmap_write_unlock(mm);
3603 
3604 	userfaultfd_unmap_complete(mm, &uf);
3605 	return ret;
3606 }
3607 
3608 /*
3609  * Insert vm structure into process list sorted by address
3610  * and into the inode's i_mmap tree if file-backed.
3611  */
3612 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3613 {
3614 	unsigned long charged = vma_pages(vma);
3615 	int err;
3616 
3617 	if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3618 		return -ENOMEM;
3619 
3620 	err = mmap_validate_vma_flags(&vma->flags);
3621 	if (err)
3622 		return err;
3623 
3624 	if (vma_test(vma, VMA_ACCOUNT_BIT) &&
3625 	     security_vm_enough_memory_mm(mm, charged))
3626 		return -ENOMEM;
3627 
3628 	/*
3629 	 * The vm_pgoff of a purely anonymous vma should be irrelevant
3630 	 * until its first write fault, when page's anon rmap and index
3631 	 * are set.  But now set the vm_pgoff it will almost certainly
3632 	 * end up with (unless mremap moves it elsewhere before that
3633 	 * first wfault), so /proc/pid/maps tells a consistent story.
3634 	 *
3635 	 * By setting it to reflect the virtual start address of the
3636 	 * vma, merges and splits can happen in a seamless way, just
3637 	 * using the existing file pgoff checks and manipulations.
3638 	 * Similarly in do_mmap and in do_brk_flags.
3639 	 */
3640 	if (vma_is_anonymous(vma)) {
3641 		WARN_ON_ONCE(vma_has_anon_rmap(vma));
3642 		vma_set_pgoff(vma, vma->vm_start >> PAGE_SHIFT);
3643 	}
3644 	vma_set_anon_pgoff(vma, vma->vm_start >> PAGE_SHIFT);
3645 
3646 	if (vma_link(mm, vma)) {
3647 		if (vma_test(vma, VMA_ACCOUNT_BIT))
3648 			vm_unacct_memory(charged);
3649 		return -ENOMEM;
3650 	}
3651 
3652 	return 0;
3653 }
3654 
3655 /**
3656  * vma_mmu_pagesize - Default MMU page size granularity for this VMA.
3657  * @vma: The user mapping.
3658  *
3659  * In the common case, the default page size used by the MMU matches the
3660  * default page size used by the kernel (see vma_kernel_pagesize()). On
3661  * architectures where it differs, an architecture-specific 'strong' version
3662  * of this symbol is required.
3663  *
3664  * The default MMU page size is not affected by Transparent Huge Pages
3665  * being in effect, or any usage of larger MMU page sizes (either through
3666  * architectural huge-page mappings or other explicit/implicit coalescing of
3667  * virtual ranges performed by the MMU).
3668  *
3669  * Return: The default MMU page size granularity for this VMA.
3670  */
3671 __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
3672 {
3673 	return vma_kernel_pagesize(vma);
3674 }
3675 
3676 struct vm_area_struct *__install_special_mapping(
3677 	struct mm_struct *mm,
3678 	unsigned long addr, unsigned long len,
3679 	vm_flags_t vm_flags, void *priv,
3680 	const struct vm_operations_struct *ops)
3681 {
3682 	vma_flags_t vma_flags = legacy_to_vma_flags(vm_flags);
3683 	struct vm_area_struct *vma;
3684 	int ret;
3685 
3686 	vma = vm_area_alloc(mm);
3687 	if (unlikely(!vma))
3688 		return ERR_PTR(-ENOMEM);
3689 
3690 	vma_flags_set_mask(&vma_flags, mm->def_vma_flags);
3691 	vma_flags_set(&vma_flags, VMA_DONTEXPAND_BIT);
3692 	if (pgtable_supports_soft_dirty())
3693 		vma_flags_set(&vma_flags, VMA_SOFTDIRTY_BIT);
3694 	vma_flags_clear_mask(&vma_flags, VMA_LOCKED_MASK);
3695 	vma->flags = vma_flags;
3696 	vma->vm_page_prot = vma_get_page_prot(vma);
3697 
3698 	vma->vm_ops = ops;
3699 	vma->vm_private_data = priv;
3700 	vma_set_range(vma, addr, addr + len, 0, addr >> PAGE_SHIFT);
3701 
3702 	ret = insert_vm_struct(mm, vma);
3703 	if (ret)
3704 		goto out;
3705 
3706 	vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3707 
3708 	perf_event_mmap(vma);
3709 
3710 	return vma;
3711 
3712 out:
3713 	vm_area_free(vma);
3714 	return ERR_PTR(ret);
3715 }
3716