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