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