• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 /*
4  * VMA-specific functions.
5  */
6 
7 #include <linux/pgsize_migration.h>
8 
9 #include "vma_internal.h"
10 #include "vma.h"
11 
is_mergeable_vma(struct vma_merge_struct * vmg,bool merge_next)12 static inline bool is_mergeable_vma(struct vma_merge_struct *vmg, bool merge_next)
13 {
14 	struct vm_area_struct *vma = merge_next ? vmg->next : vmg->prev;
15 
16 	if (!mpol_equal(vmg->policy, vma_policy(vma)))
17 		return false;
18 	/*
19 	 * VM_SOFTDIRTY should not prevent from VMA merging, if we
20 	 * match the flags but dirty bit -- the caller should mark
21 	 * merged VMA as dirty. If dirty bit won't be excluded from
22 	 * comparison, we increase pressure on the memory system forcing
23 	 * the kernel to generate new VMAs when old one could be
24 	 * extended instead.
25 	 */
26 	if ((vma->vm_flags ^ vmg->flags) & ~VM_SOFTDIRTY)
27 		return false;
28 	if (vma->vm_file != vmg->file)
29 		return false;
30 	if (!is_mergeable_vm_userfaultfd_ctx(vma, vmg->uffd_ctx))
31 		return false;
32 	if (!anon_vma_name_eq(anon_vma_name(vma), vmg->anon_name))
33 		return false;
34 	if (!is_mergable_pad_vma(vma, vmg->flags))
35 		return false;
36 	return true;
37 }
38 
is_mergeable_anon_vma(struct anon_vma * anon_vma1,struct anon_vma * anon_vma2,struct vm_area_struct * vma)39 static inline bool is_mergeable_anon_vma(struct anon_vma *anon_vma1,
40 		 struct anon_vma *anon_vma2, struct vm_area_struct *vma)
41 {
42 	/*
43 	 * The list_is_singular() test is to avoid merging VMA cloned from
44 	 * parents. This can improve scalability caused by anon_vma lock.
45 	 */
46 	if ((!anon_vma1 || !anon_vma2) && (!vma ||
47 		list_is_singular(&vma->anon_vma_chain)))
48 		return true;
49 	return anon_vma1 == anon_vma2;
50 }
51 
52 /* Are the anon_vma's belonging to each VMA compatible with one another? */
are_anon_vmas_compatible(struct vm_area_struct * vma1,struct vm_area_struct * vma2)53 static inline bool are_anon_vmas_compatible(struct vm_area_struct *vma1,
54 					    struct vm_area_struct *vma2)
55 {
56 	return is_mergeable_anon_vma(vma1->anon_vma, vma2->anon_vma, NULL);
57 }
58 
59 /*
60  * init_multi_vma_prep() - Initializer for struct vma_prepare
61  * @vp: The vma_prepare struct
62  * @vma: The vma that will be altered once locked
63  * @next: The next vma if it is to be adjusted
64  * @remove: The first vma to be removed
65  * @remove2: The second vma to be removed
66  */
init_multi_vma_prep(struct vma_prepare * vp,struct vm_area_struct * vma,struct vm_area_struct * next,struct vm_area_struct * remove,struct vm_area_struct * remove2)67 static void init_multi_vma_prep(struct vma_prepare *vp,
68 				struct vm_area_struct *vma,
69 				struct vm_area_struct *next,
70 				struct vm_area_struct *remove,
71 				struct vm_area_struct *remove2)
72 {
73 	memset(vp, 0, sizeof(struct vma_prepare));
74 	vp->vma = vma;
75 	vp->anon_vma = vma->anon_vma;
76 	vp->remove = remove;
77 	vp->remove2 = remove2;
78 	vp->adj_next = next;
79 	if (!vp->anon_vma && next)
80 		vp->anon_vma = next->anon_vma;
81 
82 	vp->file = vma->vm_file;
83 	if (vp->file)
84 		vp->mapping = vma->vm_file->f_mapping;
85 
86 }
87 
88 /*
89  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
90  * in front of (at a lower virtual address and file offset than) the vma.
91  *
92  * We cannot merge two vmas if they have differently assigned (non-NULL)
93  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
94  *
95  * We don't check here for the merged mmap wrapping around the end of pagecache
96  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
97  * wrap, nor mmaps which cover the final page at index -1UL.
98  *
99  * We assume the vma may be removed as part of the merge.
100  */
can_vma_merge_before(struct vma_merge_struct * vmg)101 static bool can_vma_merge_before(struct vma_merge_struct *vmg)
102 {
103 	pgoff_t pglen = PHYS_PFN(vmg->end - vmg->start);
104 
105 	if (is_mergeable_vma(vmg, /* merge_next = */ true) &&
106 	    is_mergeable_anon_vma(vmg->anon_vma, vmg->next->anon_vma, vmg->next)) {
107 		if (vmg->next->vm_pgoff == vmg->pgoff + pglen)
108 			return true;
109 	}
110 
111 	return false;
112 }
113 
114 /*
115  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
116  * beyond (at a higher virtual address and file offset than) the vma.
117  *
118  * We cannot merge two vmas if they have differently assigned (non-NULL)
119  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
120  *
121  * We assume that vma is not removed as part of the merge.
122  */
can_vma_merge_after(struct vma_merge_struct * vmg)123 static bool can_vma_merge_after(struct vma_merge_struct *vmg)
124 {
125 	if (is_mergeable_vma(vmg, /* merge_next = */ false) &&
126 	    is_mergeable_anon_vma(vmg->anon_vma, vmg->prev->anon_vma, vmg->prev)) {
127 		if (vmg->prev->vm_pgoff + vma_pages(vmg->prev) == vmg->pgoff)
128 			return true;
129 	}
130 	return false;
131 }
132 
__vma_link_file(struct vm_area_struct * vma,struct address_space * mapping)133 static void __vma_link_file(struct vm_area_struct *vma,
134 			    struct address_space *mapping)
135 {
136 	if (vma_is_shared_maywrite(vma))
137 		mapping_allow_writable(mapping);
138 
139 	flush_dcache_mmap_lock(mapping);
140 	vma_interval_tree_insert(vma, &mapping->i_mmap);
141 	flush_dcache_mmap_unlock(mapping);
142 }
143 
144 /*
145  * Requires inode->i_mapping->i_mmap_rwsem
146  */
__remove_shared_vm_struct(struct vm_area_struct * vma,struct address_space * mapping)147 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
148 				      struct address_space *mapping)
149 {
150 	if (vma_is_shared_maywrite(vma))
151 		mapping_unmap_writable(mapping);
152 
153 	flush_dcache_mmap_lock(mapping);
154 	vma_interval_tree_remove(vma, &mapping->i_mmap);
155 	flush_dcache_mmap_unlock(mapping);
156 }
157 
158 /*
159  * vma_prepare() - Helper function for handling locking VMAs prior to altering
160  * @vp: The initialized vma_prepare struct
161  */
vma_prepare(struct vma_prepare * vp)162 static void vma_prepare(struct vma_prepare *vp)
163 {
164 	if (vp->file) {
165 		uprobe_munmap(vp->vma, vp->vma->vm_start, vp->vma->vm_end);
166 
167 		if (vp->adj_next)
168 			uprobe_munmap(vp->adj_next, vp->adj_next->vm_start,
169 				      vp->adj_next->vm_end);
170 
171 		i_mmap_lock_write(vp->mapping);
172 		if (vp->insert && vp->insert->vm_file) {
173 			/*
174 			 * Put into interval tree now, so instantiated pages
175 			 * are visible to arm/parisc __flush_dcache_page
176 			 * throughout; but we cannot insert into address
177 			 * space until vma start or end is updated.
178 			 */
179 			__vma_link_file(vp->insert,
180 					vp->insert->vm_file->f_mapping);
181 		}
182 	}
183 
184 	if (vp->anon_vma) {
185 		anon_vma_lock_write(vp->anon_vma);
186 		anon_vma_interval_tree_pre_update_vma(vp->vma);
187 		if (vp->adj_next)
188 			anon_vma_interval_tree_pre_update_vma(vp->adj_next);
189 	}
190 
191 	if (vp->file) {
192 		flush_dcache_mmap_lock(vp->mapping);
193 		vma_interval_tree_remove(vp->vma, &vp->mapping->i_mmap);
194 		if (vp->adj_next)
195 			vma_interval_tree_remove(vp->adj_next,
196 						 &vp->mapping->i_mmap);
197 	}
198 
199 }
200 
201 /*
202  * vma_complete- Helper function for handling the unlocking after altering VMAs,
203  * or for inserting a VMA.
204  *
205  * @vp: The vma_prepare struct
206  * @vmi: The vma iterator
207  * @mm: The mm_struct
208  */
vma_complete(struct vma_prepare * vp,struct vma_iterator * vmi,struct mm_struct * mm)209 static void vma_complete(struct vma_prepare *vp, struct vma_iterator *vmi,
210 			 struct mm_struct *mm)
211 {
212 	if (vp->file) {
213 		if (vp->adj_next)
214 			vma_interval_tree_insert(vp->adj_next,
215 						 &vp->mapping->i_mmap);
216 		vma_interval_tree_insert(vp->vma, &vp->mapping->i_mmap);
217 		flush_dcache_mmap_unlock(vp->mapping);
218 	}
219 
220 	if (vp->remove && vp->file) {
221 		__remove_shared_vm_struct(vp->remove, vp->mapping);
222 		if (vp->remove2)
223 			__remove_shared_vm_struct(vp->remove2, vp->mapping);
224 	} else if (vp->insert) {
225 		/*
226 		 * split_vma has split insert from vma, and needs
227 		 * us to insert it before dropping the locks
228 		 * (it may either follow vma or precede it).
229 		 */
230 		vma_iter_store_new(vmi, vp->insert);
231 		mm->map_count++;
232 	}
233 
234 	if (vp->anon_vma) {
235 		anon_vma_interval_tree_post_update_vma(vp->vma);
236 		if (vp->adj_next)
237 			anon_vma_interval_tree_post_update_vma(vp->adj_next);
238 		anon_vma_unlock_write(vp->anon_vma);
239 	}
240 
241 	if (vp->file) {
242 		i_mmap_unlock_write(vp->mapping);
243 		uprobe_mmap(vp->vma);
244 
245 		if (vp->adj_next)
246 			uprobe_mmap(vp->adj_next);
247 	}
248 
249 	if (vp->remove) {
250 again:
251 		vma_mark_detached(vp->remove);
252 		if (vp->file) {
253 			uprobe_munmap(vp->remove, vp->remove->vm_start,
254 				      vp->remove->vm_end);
255 			fput(vp->file);
256 		}
257 		if (vp->remove->anon_vma)
258 			anon_vma_merge(vp->vma, vp->remove);
259 		mm->map_count--;
260 		mpol_put(vma_policy(vp->remove));
261 		if (!vp->remove2)
262 			WARN_ON_ONCE(vp->vma->vm_end < vp->remove->vm_end);
263 		vm_area_free(vp->remove);
264 
265 		/*
266 		 * In mprotect's case 6 (see comments on vma_merge),
267 		 * we are removing both mid and next vmas
268 		 */
269 		if (vp->remove2) {
270 			vp->remove = vp->remove2;
271 			vp->remove2 = NULL;
272 			goto again;
273 		}
274 	}
275 	if (vp->insert && vp->file)
276 		uprobe_mmap(vp->insert);
277 }
278 
279 /*
280  * init_vma_prep() - Initializer wrapper for vma_prepare struct
281  * @vp: The vma_prepare struct
282  * @vma: The vma that will be altered once locked
283  */
init_vma_prep(struct vma_prepare * vp,struct vm_area_struct * vma)284 static void init_vma_prep(struct vma_prepare *vp, struct vm_area_struct *vma)
285 {
286 	init_multi_vma_prep(vp, vma, NULL, NULL, NULL);
287 }
288 
289 /*
290  * Can the proposed VMA be merged with the left (previous) VMA taking into
291  * account the start position of the proposed range.
292  */
can_vma_merge_left(struct vma_merge_struct * vmg)293 static bool can_vma_merge_left(struct vma_merge_struct *vmg)
294 
295 {
296 	return vmg->prev && vmg->prev->vm_end == vmg->start &&
297 		can_vma_merge_after(vmg);
298 }
299 
300 /*
301  * Can the proposed VMA be merged with the right (next) VMA taking into
302  * account the end position of the proposed range.
303  *
304  * In addition, if we can merge with the left VMA, ensure that left and right
305  * anon_vma's are also compatible.
306  */
can_vma_merge_right(struct vma_merge_struct * vmg,bool can_merge_left)307 static bool can_vma_merge_right(struct vma_merge_struct *vmg,
308 				bool can_merge_left)
309 {
310 	if (!vmg->next || vmg->end != vmg->next->vm_start ||
311 	    !can_vma_merge_before(vmg))
312 		return false;
313 
314 	if (!can_merge_left)
315 		return true;
316 
317 	/*
318 	 * If we can merge with prev (left) and next (right), indicating that
319 	 * each VMA's anon_vma is compatible with the proposed anon_vma, this
320 	 * does not mean prev and next are compatible with EACH OTHER.
321 	 *
322 	 * We therefore check this in addition to mergeability to either side.
323 	 */
324 	return are_anon_vmas_compatible(vmg->prev, vmg->next);
325 }
326 
327 /*
328  * Close a vm structure and free it.
329  */
remove_vma(struct vm_area_struct * vma)330 void remove_vma(struct vm_area_struct *vma)
331 {
332 	might_sleep();
333 	vma_close(vma);
334 	if (vma->vm_file)
335 		fput(vma->vm_file);
336 	mpol_put(vma_policy(vma));
337 	vm_area_free(vma);
338 }
339 
340 /*
341  * Get rid of page table information in the indicated region.
342  *
343  * Called with the mm semaphore held.
344  */
unmap_region(struct ma_state * mas,struct vm_area_struct * vma,struct vm_area_struct * prev,struct vm_area_struct * next)345 void unmap_region(struct ma_state *mas, struct vm_area_struct *vma,
346 		struct vm_area_struct *prev, struct vm_area_struct *next)
347 {
348 	struct mm_struct *mm = vma->vm_mm;
349 	struct mmu_gather tlb;
350 
351 	lru_add_drain();
352 	tlb_gather_mmu(&tlb, mm);
353 	update_hiwater_rss(mm);
354 	unmap_vmas(&tlb, mas, vma, vma->vm_start, vma->vm_end, vma->vm_end,
355 		   /* mm_wr_locked = */ true);
356 	mas_set(mas, vma->vm_end);
357 	free_pgtables(&tlb, mas, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
358 		      next ? next->vm_start : USER_PGTABLES_CEILING,
359 		      /* mm_wr_locked = */ true);
360 	tlb_finish_mmu(&tlb);
361 }
362 
363 /*
364  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
365  * has already been checked or doesn't make sense to fail.
366  * VMA Iterator will point to the original VMA.
367  */
__split_vma(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long addr,int new_below)368 static int __split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
369 		       unsigned long addr, int new_below)
370 {
371 	struct vma_prepare vp;
372 	struct vm_area_struct *new;
373 	int err;
374 
375 	WARN_ON(vma->vm_start >= addr);
376 	WARN_ON(vma->vm_end <= addr);
377 
378 	if (vma->vm_ops && vma->vm_ops->may_split) {
379 		err = vma->vm_ops->may_split(vma, addr);
380 		if (err)
381 			return err;
382 	}
383 
384 	new = vm_area_dup(vma);
385 	if (!new)
386 		return -ENOMEM;
387 
388 	if (new_below) {
389 		new->vm_end = addr;
390 	} else {
391 		new->vm_start = addr;
392 		new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
393 	}
394 
395 	err = -ENOMEM;
396 	vma_iter_config(vmi, new->vm_start, new->vm_end);
397 	if (vma_iter_prealloc(vmi, new))
398 		goto out_free_vma;
399 
400 	err = vma_dup_policy(vma, new);
401 	if (err)
402 		goto out_free_vmi;
403 
404 	err = anon_vma_clone(new, vma);
405 	if (err)
406 		goto out_free_mpol;
407 
408 	if (new->vm_file)
409 		get_file(new->vm_file);
410 
411 	if (new->vm_ops && new->vm_ops->open)
412 		new->vm_ops->open(new);
413 
414 	vma_start_write(vma);
415 	vma_start_write(new);
416 
417 	init_vma_prep(&vp, vma);
418 	vp.insert = new;
419 	vma_prepare(&vp);
420 
421 	/*
422 	 * Get rid of huge pages and shared page tables straddling the split
423 	 * boundary.
424 	 */
425 	vma_adjust_trans_huge(vma, vma->vm_start, addr, 0);
426 	if (is_vm_hugetlb_page(vma))
427 		hugetlb_split(vma, addr);
428 
429 	if (new_below) {
430 		vma->vm_start = addr;
431 		vma->vm_pgoff += (addr - new->vm_start) >> PAGE_SHIFT;
432 	} else {
433 		vma->vm_end = addr;
434 	}
435 
436 	/* vma_complete stores the new vma */
437 	vma_complete(&vp, vmi, vma->vm_mm);
438 	validate_mm(vma->vm_mm);
439 
440 	/* Success. */
441 	if (new_below)
442 		vma_next(vmi);
443 	else
444 		vma_prev(vmi);
445 
446 	split_pad_vma(vma, new, addr, new_below);
447 	return 0;
448 
449 out_free_mpol:
450 	mpol_put(vma_policy(new));
451 out_free_vmi:
452 	vma_iter_free(vmi);
453 out_free_vma:
454 	vm_area_free(new);
455 	return err;
456 }
457 
458 /*
459  * Split a vma into two pieces at address 'addr', a new vma is allocated
460  * either for the first part or the tail.
461  */
split_vma(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long addr,int new_below)462 static int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
463 		     unsigned long addr, int new_below)
464 {
465 	if (vma->vm_mm->map_count >= sysctl_max_map_count)
466 		return -ENOMEM;
467 
468 	return __split_vma(vmi, vma, addr, new_below);
469 }
470 
471 /*
472  * vma has some anon_vma assigned, and is already inserted on that
473  * anon_vma's interval trees.
474  *
475  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
476  * vma must be removed from the anon_vma's interval trees using
477  * anon_vma_interval_tree_pre_update_vma().
478  *
479  * After the update, the vma will be reinserted using
480  * anon_vma_interval_tree_post_update_vma().
481  *
482  * The entire update must be protected by exclusive mmap_lock and by
483  * the root anon_vma's mutex.
484  */
485 void
anon_vma_interval_tree_pre_update_vma(struct vm_area_struct * vma)486 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
487 {
488 	struct anon_vma_chain *avc;
489 
490 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
491 		anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
492 }
493 
494 void
anon_vma_interval_tree_post_update_vma(struct vm_area_struct * vma)495 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
496 {
497 	struct anon_vma_chain *avc;
498 
499 	list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
500 		anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
501 }
502 
503 /*
504  * dup_anon_vma() - Helper function to duplicate anon_vma
505  * @dst: The destination VMA
506  * @src: The source VMA
507  * @dup: Pointer to the destination VMA when successful.
508  *
509  * Returns: 0 on success.
510  */
dup_anon_vma(struct vm_area_struct * dst,struct vm_area_struct * src,struct vm_area_struct ** dup)511 static int dup_anon_vma(struct vm_area_struct *dst,
512 			struct vm_area_struct *src, struct vm_area_struct **dup)
513 {
514 	/*
515 	 * Easily overlooked: when mprotect shifts the boundary, make sure the
516 	 * expanding vma has anon_vma set if the shrinking vma had, to cover any
517 	 * anon pages imported.
518 	 */
519 	if (src->anon_vma && !dst->anon_vma) {
520 		int ret;
521 
522 		vma_assert_write_locked(dst);
523 		dst->anon_vma = src->anon_vma;
524 		ret = anon_vma_clone(dst, src);
525 		if (ret)
526 			return ret;
527 
528 		*dup = dst;
529 	}
530 
531 	return 0;
532 }
533 
534 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
validate_mm(struct mm_struct * mm)535 void validate_mm(struct mm_struct *mm)
536 {
537 	int bug = 0;
538 	int i = 0;
539 	struct vm_area_struct *vma;
540 	VMA_ITERATOR(vmi, mm, 0);
541 
542 	mt_validate(&mm->mm_mt);
543 	for_each_vma(vmi, vma) {
544 #ifdef CONFIG_DEBUG_VM_RB
545 		struct anon_vma *anon_vma = vma->anon_vma;
546 		struct anon_vma_chain *avc;
547 #endif
548 		unsigned long vmi_start, vmi_end;
549 		bool warn = 0;
550 
551 		vmi_start = vma_iter_addr(&vmi);
552 		vmi_end = vma_iter_end(&vmi);
553 		if (VM_WARN_ON_ONCE_MM(vma->vm_end != vmi_end, mm))
554 			warn = 1;
555 
556 		if (VM_WARN_ON_ONCE_MM(vma->vm_start != vmi_start, mm))
557 			warn = 1;
558 
559 		if (warn) {
560 			pr_emerg("issue in %s\n", current->comm);
561 			dump_stack();
562 			dump_vma(vma);
563 			pr_emerg("tree range: %px start %lx end %lx\n", vma,
564 				 vmi_start, vmi_end - 1);
565 			vma_iter_dump_tree(&vmi);
566 		}
567 
568 #ifdef CONFIG_DEBUG_VM_RB
569 		if (anon_vma) {
570 			anon_vma_lock_read(anon_vma);
571 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
572 				anon_vma_interval_tree_verify(avc);
573 			anon_vma_unlock_read(anon_vma);
574 		}
575 #endif
576 		i++;
577 	}
578 	if (i != mm->map_count) {
579 		pr_emerg("map_count %d vma iterator %d\n", mm->map_count, i);
580 		bug = 1;
581 	}
582 	VM_BUG_ON_MM(bug, mm);
583 }
584 #endif /* CONFIG_DEBUG_VM_MAPLE_TREE */
585 
586 /* Actually perform the VMA merge operation. */
commit_merge(struct vma_merge_struct * vmg,struct vm_area_struct * adjust,struct vm_area_struct * remove,struct vm_area_struct * remove2,long adj_start,bool expanded)587 static int commit_merge(struct vma_merge_struct *vmg,
588 			struct vm_area_struct *adjust,
589 			struct vm_area_struct *remove,
590 			struct vm_area_struct *remove2,
591 			long adj_start,
592 			bool expanded)
593 {
594 	struct vma_prepare vp;
595 
596 	init_multi_vma_prep(&vp, vmg->vma, adjust, remove, remove2);
597 
598 	VM_WARN_ON(vp.anon_vma && adjust && adjust->anon_vma &&
599 		   vp.anon_vma != adjust->anon_vma);
600 
601 	if (expanded) {
602 		/* Note: vma iterator must be pointing to 'start'. */
603 		vma_iter_config(vmg->vmi, vmg->start, vmg->end);
604 	} else {
605 		vma_iter_config(vmg->vmi, adjust->vm_start + adj_start,
606 				adjust->vm_end);
607 	}
608 
609 	if (vma_iter_prealloc(vmg->vmi, vmg->vma))
610 		return -ENOMEM;
611 
612 	vma_prepare(&vp);
613 	vma_adjust_trans_huge(vmg->vma, vmg->start, vmg->end, adj_start);
614 	vma_set_range(vmg->vma, vmg->start, vmg->end, vmg->pgoff);
615 
616 	if (expanded)
617 		vma_iter_store_overwrite(vmg->vmi, vmg->vma);
618 
619 	if (adj_start) {
620 		adjust->vm_start += adj_start;
621 		adjust->vm_pgoff += PHYS_PFN(adj_start);
622 		if (adj_start < 0) {
623 			WARN_ON(expanded);
624 			vma_iter_store_overwrite(vmg->vmi, adjust);
625 		}
626 	}
627 
628 	vma_complete(&vp, vmg->vmi, vmg->vma->vm_mm);
629 
630 	return 0;
631 }
632 
633 /* We can only remove VMAs when merging if they do not have a close hook. */
can_merge_remove_vma(struct vm_area_struct * vma)634 static bool can_merge_remove_vma(struct vm_area_struct *vma)
635 {
636 	return !vma->vm_ops || !vma->vm_ops->close;
637 }
638 
639 /*
640  * vma_merge_existing_range - Attempt to merge VMAs based on a VMA having its
641  * attributes modified.
642  *
643  * @vmg: Describes the modifications being made to a VMA and associated
644  *       metadata.
645  *
646  * When the attributes of a range within a VMA change, then it might be possible
647  * for immediately adjacent VMAs to be merged into that VMA due to having
648  * identical properties.
649  *
650  * This function checks for the existence of any such mergeable VMAs and updates
651  * the maple tree describing the @vmg->vma->vm_mm address space to account for
652  * this, as well as any VMAs shrunk/expanded/deleted as a result of this merge.
653  *
654  * As part of this operation, if a merge occurs, the @vmg object will have its
655  * vma, start, end, and pgoff fields modified to execute the merge. Subsequent
656  * calls to this function should reset these fields.
657  *
658  * Returns: The merged VMA if merge succeeds, or NULL otherwise.
659  *
660  * ASSUMPTIONS:
661  * - The caller must assign the VMA to be modifed to @vmg->vma.
662  * - The caller must have set @vmg->prev to the previous VMA, if there is one.
663  * - The caller must not set @vmg->next, as we determine this.
664  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
665  * - vmi must be positioned within [@vmg->vma->vm_start, @vmg->vma->vm_end).
666  */
vma_merge_existing_range(struct vma_merge_struct * vmg)667 static struct vm_area_struct *vma_merge_existing_range(struct vma_merge_struct *vmg)
668 {
669 	struct vm_area_struct *vma = vmg->vma;
670 	struct vm_area_struct *prev = vmg->prev;
671 	struct vm_area_struct *next, *res;
672 	struct vm_area_struct *anon_dup = NULL;
673 	struct vm_area_struct *adjust = NULL;
674 	unsigned long start = vmg->start;
675 	unsigned long end = vmg->end;
676 	bool left_side = vma && start == vma->vm_start;
677 	bool right_side = vma && end == vma->vm_end;
678 	int err = 0;
679 	long adj_start = 0;
680 	bool merge_will_delete_vma, merge_will_delete_next;
681 	bool merge_left, merge_right, merge_both;
682 	bool expanded;
683 
684 	mmap_assert_write_locked(vmg->mm);
685 	VM_WARN_ON(!vma); /* We are modifying a VMA, so caller must specify. */
686 	VM_WARN_ON(vmg->next); /* We set this. */
687 	VM_WARN_ON(prev && start <= prev->vm_start);
688 	VM_WARN_ON(start >= end);
689 	/*
690 	 * If vma == prev, then we are offset into a VMA. Otherwise, if we are
691 	 * not, we must span a portion of the VMA.
692 	 */
693 	VM_WARN_ON(vma && ((vma != prev && vmg->start != vma->vm_start) ||
694 			   vmg->end > vma->vm_end));
695 	/* The vmi must be positioned within vmg->vma. */
696 	VM_WARN_ON(vma && !(vma_iter_addr(vmg->vmi) >= vma->vm_start &&
697 			    vma_iter_addr(vmg->vmi) < vma->vm_end));
698 
699 	vmg->state = VMA_MERGE_NOMERGE;
700 
701 	/*
702 	 * If a special mapping or if the range being modified is neither at the
703 	 * furthermost left or right side of the VMA, then we have no chance of
704 	 * merging and should abort.
705 	 */
706 	if (vmg->flags & VM_SPECIAL || (!left_side && !right_side))
707 		return NULL;
708 
709 	if (left_side)
710 		merge_left = can_vma_merge_left(vmg);
711 	else
712 		merge_left = false;
713 
714 	if (right_side) {
715 		next = vmg->next = vma_iter_next_range(vmg->vmi);
716 		vma_iter_prev_range(vmg->vmi);
717 
718 		merge_right = can_vma_merge_right(vmg, merge_left);
719 	} else {
720 		merge_right = false;
721 		next = NULL;
722 	}
723 
724 	if (merge_left)		/* If merging prev, position iterator there. */
725 		vma_prev(vmg->vmi);
726 	else if (!merge_right)	/* If we have nothing to merge, abort. */
727 		return NULL;
728 
729 	merge_both = merge_left && merge_right;
730 	/* If we span the entire VMA, a merge implies it will be deleted. */
731 	merge_will_delete_vma = left_side && right_side;
732 
733 	/*
734 	 * If we need to remove vma in its entirety but are unable to do so,
735 	 * we have no sensible recourse but to abort the merge.
736 	 */
737 	if (merge_will_delete_vma && !can_merge_remove_vma(vma))
738 		return NULL;
739 
740 	/*
741 	 * If we merge both VMAs, then next is also deleted. This implies
742 	 * merge_will_delete_vma also.
743 	 */
744 	merge_will_delete_next = merge_both;
745 
746 	/*
747 	 * If we cannot delete next, then we can reduce the operation to merging
748 	 * prev and vma (thereby deleting vma).
749 	 */
750 	if (merge_will_delete_next && !can_merge_remove_vma(next)) {
751 		merge_will_delete_next = false;
752 		merge_right = false;
753 		merge_both = false;
754 	}
755 
756 	/* No matter what happens, we will be adjusting vma. */
757 	vma_start_write(vma);
758 
759 	if (merge_left)
760 		vma_start_write(prev);
761 
762 	if (merge_right)
763 		vma_start_write(next);
764 
765 	if (merge_both) {
766 		/*
767 		 *         |<----->|
768 		 * |-------*********-------|
769 		 *   prev     vma     next
770 		 *  extend   delete  delete
771 		 */
772 
773 		vmg->vma = prev;
774 		vmg->start = prev->vm_start;
775 		vmg->end = next->vm_end;
776 		vmg->pgoff = prev->vm_pgoff;
777 
778 		/*
779 		 * We already ensured anon_vma compatibility above, so now it's
780 		 * simply a case of, if prev has no anon_vma object, which of
781 		 * next or vma contains the anon_vma we must duplicate.
782 		 */
783 		err = dup_anon_vma(prev, next->anon_vma ? next : vma, &anon_dup);
784 	} else if (merge_left) {
785 		/*
786 		 *         |<----->| OR
787 		 *         |<--------->|
788 		 * |-------*************
789 		 *   prev       vma
790 		 *  extend shrink/delete
791 		 */
792 
793 		vmg->vma = prev;
794 		vmg->start = prev->vm_start;
795 		vmg->pgoff = prev->vm_pgoff;
796 
797 		if (!merge_will_delete_vma) {
798 			adjust = vma;
799 			adj_start = vmg->end - vma->vm_start;
800 		}
801 
802 		err = dup_anon_vma(prev, vma, &anon_dup);
803 	} else { /* merge_right */
804 		/*
805 		 *     |<----->| OR
806 		 * |<--------->|
807 		 * *************-------|
808 		 *      vma       next
809 		 * shrink/delete extend
810 		 */
811 
812 		pgoff_t pglen = PHYS_PFN(vmg->end - vmg->start);
813 
814 		VM_WARN_ON(!merge_right);
815 		/* If we are offset into a VMA, then prev must be vma. */
816 		VM_WARN_ON(vmg->start > vma->vm_start && prev && vma != prev);
817 
818 		if (merge_will_delete_vma) {
819 			vmg->vma = next;
820 			vmg->end = next->vm_end;
821 			vmg->pgoff = next->vm_pgoff - pglen;
822 		} else {
823 			/*
824 			 * We shrink vma and expand next.
825 			 *
826 			 * IMPORTANT: This is the ONLY case where the final
827 			 * merged VMA is NOT vmg->vma, but rather vmg->next.
828 			 */
829 
830 			vmg->start = vma->vm_start;
831 			vmg->end = start;
832 			vmg->pgoff = vma->vm_pgoff;
833 
834 			adjust = next;
835 			adj_start = -(vma->vm_end - start);
836 		}
837 
838 		err = dup_anon_vma(next, vma, &anon_dup);
839 	}
840 
841 	/*
842 	 * In nearly all cases, we expand vmg->vma. There is one exception -
843 	 * merge_right where we partially span the VMA. In this case we shrink
844 	 * the end of vmg->vma and adjust the start of vmg->next accordingly.
845 	 */
846 	expanded = !merge_right || merge_will_delete_vma;
847 
848 	if (err || commit_merge(vmg, adjust,
849 			merge_will_delete_vma ? vma : NULL,
850 			merge_will_delete_next ? next : NULL,
851 			adj_start, expanded))
852 		goto abort;
853 
854 	res = merge_left ? prev : next;
855 	khugepaged_enter_vma(res, vmg->flags);
856 
857 	vmg->state = VMA_MERGE_SUCCESS;
858 	return res;
859 
860 abort:
861 	vma_iter_set(vmg->vmi, start);
862 	vma_iter_load(vmg->vmi);
863 
864 	if (anon_dup)
865 		unlink_anon_vmas(anon_dup);
866 
867 	/*
868 	 * This means we have failed to clone anon_vma's correctly, but no
869 	 * actual changes to VMAs have occurred, so no harm no foul - if the
870 	 * user doesn't want this reported and instead just wants to give up on
871 	 * the merge, allow it.
872 	 */
873 	if (!vmg->give_up_on_oom)
874 		vmg->state = VMA_MERGE_ERROR_NOMEM;
875 	return NULL;
876 }
877 
878 /*
879  * vma_merge_new_range - Attempt to merge a new VMA into address space
880  *
881  * @vmg: Describes the VMA we are adding, in the range @vmg->start to @vmg->end
882  *       (exclusive), which we try to merge with any adjacent VMAs if possible.
883  *
884  * We are about to add a VMA to the address space starting at @vmg->start and
885  * ending at @vmg->end. There are three different possible scenarios:
886  *
887  * 1. There is a VMA with identical properties immediately adjacent to the
888  *    proposed new VMA [@vmg->start, @vmg->end) either before or after it -
889  *    EXPAND that VMA:
890  *
891  * Proposed:       |-----|  or  |-----|
892  * Existing:  |----|                  |----|
893  *
894  * 2. There are VMAs with identical properties immediately adjacent to the
895  *    proposed new VMA [@vmg->start, @vmg->end) both before AND after it -
896  *    EXPAND the former and REMOVE the latter:
897  *
898  * Proposed:       |-----|
899  * Existing:  |----|     |----|
900  *
901  * 3. There are no VMAs immediately adjacent to the proposed new VMA or those
902  *    VMAs do not have identical attributes - NO MERGE POSSIBLE.
903  *
904  * In instances where we can merge, this function returns the expanded VMA which
905  * will have its range adjusted accordingly and the underlying maple tree also
906  * adjusted.
907  *
908  * Returns: In instances where no merge was possible, NULL. Otherwise, a pointer
909  *          to the VMA we expanded.
910  *
911  * This function adjusts @vmg to provide @vmg->next if not already specified,
912  * and adjusts [@vmg->start, @vmg->end) to span the expanded range.
913  *
914  * ASSUMPTIONS:
915  * - The caller must hold a WRITE lock on the mm_struct->mmap_lock.
916  * - The caller must have determined that [@vmg->start, @vmg->end) is empty,
917      other than VMAs that will be unmapped should the operation succeed.
918  * - The caller must have specified the previous vma in @vmg->prev.
919  * - The caller must have specified the next vma in @vmg->next.
920  * - The caller must have positioned the vmi at or before the gap.
921  */
vma_merge_new_range(struct vma_merge_struct * vmg)922 struct vm_area_struct *vma_merge_new_range(struct vma_merge_struct *vmg)
923 {
924 	struct vm_area_struct *prev = vmg->prev;
925 	struct vm_area_struct *next = vmg->next;
926 	unsigned long start = vmg->start;
927 	unsigned long end = vmg->end;
928 	pgoff_t pgoff = vmg->pgoff;
929 	pgoff_t pglen = PHYS_PFN(end - start);
930 	bool can_merge_left, can_merge_right;
931 	bool just_expand = vmg->merge_flags & VMG_FLAG_JUST_EXPAND;
932 
933 	mmap_assert_write_locked(vmg->mm);
934 	VM_WARN_ON(vmg->vma);
935 	/* vmi must point at or before the gap. */
936 	VM_WARN_ON(vma_iter_addr(vmg->vmi) > end);
937 
938 	vmg->state = VMA_MERGE_NOMERGE;
939 
940 	/* Special VMAs are unmergeable, also if no prev/next. */
941 	if ((vmg->flags & VM_SPECIAL) || (!prev && !next))
942 		return NULL;
943 
944 	can_merge_left = can_vma_merge_left(vmg);
945 	can_merge_right = !just_expand && can_vma_merge_right(vmg, can_merge_left);
946 
947 	/* If we can merge with the next VMA, adjust vmg accordingly. */
948 	if (can_merge_right) {
949 		vmg->end = next->vm_end;
950 		vmg->vma = next;
951 		vmg->pgoff = next->vm_pgoff - pglen;
952 	}
953 
954 	/* If we can merge with the previous VMA, adjust vmg accordingly. */
955 	if (can_merge_left) {
956 		vmg->start = prev->vm_start;
957 		vmg->vma = prev;
958 		vmg->pgoff = prev->vm_pgoff;
959 
960 		/*
961 		 * If this merge would result in removal of the next VMA but we
962 		 * are not permitted to do so, reduce the operation to merging
963 		 * prev and vma.
964 		 */
965 		if (can_merge_right && !can_merge_remove_vma(next))
966 			vmg->end = end;
967 
968 		/* In expand-only case we are already positioned at prev. */
969 		if (!just_expand) {
970 			/* Equivalent to going to the previous range. */
971 			vma_prev(vmg->vmi);
972 		}
973 	}
974 
975 	/*
976 	 * Now try to expand adjacent VMA(s). This takes care of removing the
977 	 * following VMA if we have VMAs on both sides.
978 	 */
979 	if (vmg->vma && !vma_expand(vmg)) {
980 		khugepaged_enter_vma(vmg->vma, vmg->flags);
981 		vmg->state = VMA_MERGE_SUCCESS;
982 		return vmg->vma;
983 	}
984 
985 	/* If expansion failed, reset state. Allows us to retry merge later. */
986 	if (!just_expand) {
987 		vmg->vma = NULL;
988 		vmg->start = start;
989 		vmg->end = end;
990 		vmg->pgoff = pgoff;
991 		if (vmg->vma == prev)
992 			vma_iter_set(vmg->vmi, start);
993 	}
994 
995 	return NULL;
996 }
997 
998 /*
999  * vma_expand - Expand an existing VMA
1000  *
1001  * @vmg: Describes a VMA expansion operation.
1002  *
1003  * Expand @vma to vmg->start and vmg->end.  Can expand off the start and end.
1004  * Will expand over vmg->next if it's different from vmg->vma and vmg->end ==
1005  * vmg->next->vm_end.  Checking if the vmg->vma can expand and merge with
1006  * vmg->next needs to be handled by the caller.
1007  *
1008  * Returns: 0 on success.
1009  *
1010  * ASSUMPTIONS:
1011  * - The caller must hold a WRITE lock on vmg->vma->mm->mmap_lock.
1012  * - The caller must have set @vmg->vma and @vmg->next.
1013  */
vma_expand(struct vma_merge_struct * vmg)1014 int vma_expand(struct vma_merge_struct *vmg)
1015 {
1016 	struct vm_area_struct *anon_dup = NULL;
1017 	bool remove_next = false;
1018 	struct vm_area_struct *vma = vmg->vma;
1019 	struct vm_area_struct *next = vmg->next;
1020 
1021 	mmap_assert_write_locked(vmg->mm);
1022 
1023 	vma_start_write(vma);
1024 	if (next && (vma != next) && (vmg->end == next->vm_end)) {
1025 		int ret;
1026 
1027 		remove_next = true;
1028 		/* This should already have been checked by this point. */
1029 		VM_WARN_ON(!can_merge_remove_vma(next));
1030 		vma_start_write(next);
1031 		ret = dup_anon_vma(vma, next, &anon_dup);
1032 		if (ret)
1033 			return ret;
1034 	}
1035 
1036 	/* Not merging but overwriting any part of next is not handled. */
1037 	VM_WARN_ON(next && !remove_next &&
1038 		  next != vma && vmg->end > next->vm_start);
1039 	/* Only handles expanding */
1040 	VM_WARN_ON(vma->vm_start < vmg->start || vma->vm_end > vmg->end);
1041 
1042 	if (commit_merge(vmg, NULL, remove_next ? next : NULL, NULL, 0, true))
1043 		goto nomem;
1044 
1045 	return 0;
1046 
1047 nomem:
1048 	if (anon_dup)
1049 		unlink_anon_vmas(anon_dup);
1050 	/*
1051 	 * If the user requests that we just give upon OOM, we are safe to do so
1052 	 * here, as commit merge provides this contract to us. Nothing has been
1053 	 * changed - no harm no foul, just don't report it.
1054 	 */
1055 	if (!vmg->give_up_on_oom)
1056 		vmg->state = VMA_MERGE_ERROR_NOMEM;
1057 	return -ENOMEM;
1058 }
1059 
1060 /*
1061  * vma_shrink() - Reduce an existing VMAs memory area
1062  * @vmi: The vma iterator
1063  * @vma: The VMA to modify
1064  * @start: The new start
1065  * @end: The new end
1066  *
1067  * Returns: 0 on success, -ENOMEM otherwise
1068  */
vma_shrink(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long start,unsigned long end,pgoff_t pgoff)1069 int vma_shrink(struct vma_iterator *vmi, struct vm_area_struct *vma,
1070 	       unsigned long start, unsigned long end, pgoff_t pgoff)
1071 {
1072 	struct vma_prepare vp;
1073 
1074 	WARN_ON((vma->vm_start != start) && (vma->vm_end != end));
1075 
1076 	if (vma->vm_start < start)
1077 		vma_iter_config(vmi, vma->vm_start, start);
1078 	else
1079 		vma_iter_config(vmi, end, vma->vm_end);
1080 
1081 	if (vma_iter_prealloc(vmi, NULL))
1082 		return -ENOMEM;
1083 
1084 	vma_start_write(vma);
1085 
1086 	init_vma_prep(&vp, vma);
1087 	vma_prepare(&vp);
1088 	vma_adjust_trans_huge(vma, start, end, 0);
1089 
1090 	vma_iter_clear(vmi);
1091 	vma_set_range(vma, start, end, pgoff);
1092 	vma_complete(&vp, vmi, vma->vm_mm);
1093 	validate_mm(vma->vm_mm);
1094 	return 0;
1095 }
1096 
vms_clear_ptes(struct vma_munmap_struct * vms,struct ma_state * mas_detach,bool mm_wr_locked)1097 static inline void vms_clear_ptes(struct vma_munmap_struct *vms,
1098 		    struct ma_state *mas_detach, bool mm_wr_locked)
1099 {
1100 	struct mmu_gather tlb;
1101 
1102 	if (!vms->clear_ptes) /* Nothing to do */
1103 		return;
1104 
1105 	/*
1106 	 * We can free page tables without write-locking mmap_lock because VMAs
1107 	 * were isolated before we downgraded mmap_lock.
1108 	 */
1109 	mas_set(mas_detach, 1);
1110 	lru_add_drain();
1111 	tlb_gather_mmu(&tlb, vms->vma->vm_mm);
1112 	update_hiwater_rss(vms->vma->vm_mm);
1113 	unmap_vmas(&tlb, mas_detach, vms->vma, vms->start, vms->end,
1114 		   vms->vma_count, mm_wr_locked);
1115 
1116 	mas_set(mas_detach, 1);
1117 	/* start and end may be different if there is no prev or next vma. */
1118 	free_pgtables(&tlb, mas_detach, vms->vma, vms->unmap_start,
1119 		      vms->unmap_end, mm_wr_locked);
1120 	tlb_finish_mmu(&tlb);
1121 	vms->clear_ptes = false;
1122 }
1123 
vms_clean_up_area(struct vma_munmap_struct * vms,struct ma_state * mas_detach)1124 void vms_clean_up_area(struct vma_munmap_struct *vms,
1125 		struct ma_state *mas_detach)
1126 {
1127 	struct vm_area_struct *vma;
1128 
1129 	if (!vms->nr_pages)
1130 		return;
1131 
1132 	vms_clear_ptes(vms, mas_detach, true);
1133 	mas_set(mas_detach, 0);
1134 	mas_for_each(mas_detach, vma, ULONG_MAX)
1135 		vma_close(vma);
1136 }
1137 
1138 /*
1139  * vms_complete_munmap_vmas() - Finish the munmap() operation
1140  * @vms: The vma munmap struct
1141  * @mas_detach: The maple state of the detached vmas
1142  *
1143  * This updates the mm_struct, unmaps the region, frees the resources
1144  * used for the munmap() and may downgrade the lock - if requested.  Everything
1145  * needed to be done once the vma maple tree is updated.
1146  */
vms_complete_munmap_vmas(struct vma_munmap_struct * vms,struct ma_state * mas_detach)1147 void vms_complete_munmap_vmas(struct vma_munmap_struct *vms,
1148 		struct ma_state *mas_detach)
1149 {
1150 	struct vm_area_struct *vma;
1151 	struct mm_struct *mm;
1152 
1153 	mm = current->mm;
1154 	mm->map_count -= vms->vma_count;
1155 	mm->locked_vm -= vms->locked_vm;
1156 	if (vms->unlock)
1157 		mmap_write_downgrade(mm);
1158 
1159 	if (!vms->nr_pages)
1160 		return;
1161 
1162 	vms_clear_ptes(vms, mas_detach, !vms->unlock);
1163 	/* Update high watermark before we lower total_vm */
1164 	update_hiwater_vm(mm);
1165 	/* Stat accounting */
1166 	WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm) - vms->nr_pages);
1167 	/* Paranoid bookkeeping */
1168 	VM_WARN_ON(vms->exec_vm > mm->exec_vm);
1169 	VM_WARN_ON(vms->stack_vm > mm->stack_vm);
1170 	VM_WARN_ON(vms->data_vm > mm->data_vm);
1171 	mm->exec_vm -= vms->exec_vm;
1172 	mm->stack_vm -= vms->stack_vm;
1173 	mm->data_vm -= vms->data_vm;
1174 
1175 	/* Remove and clean up vmas */
1176 	mas_set(mas_detach, 0);
1177 	mas_for_each(mas_detach, vma, ULONG_MAX)
1178 		remove_vma(vma);
1179 
1180 	vm_unacct_memory(vms->nr_accounted);
1181 	validate_mm(mm);
1182 	if (vms->unlock)
1183 		mmap_read_unlock(mm);
1184 
1185 	__mt_destroy(mas_detach->tree);
1186 }
1187 
1188 /*
1189  * vms_gather_munmap_vmas() - Put all VMAs within a range into a maple tree
1190  * for removal at a later date.  Handles splitting first and last if necessary
1191  * and marking the vmas as isolated.
1192  *
1193  * @vms: The vma munmap struct
1194  * @mas_detach: The maple state tracking the detached tree
1195  *
1196  * Return: 0 on success, error otherwise
1197  */
vms_gather_munmap_vmas(struct vma_munmap_struct * vms,struct ma_state * mas_detach)1198 int vms_gather_munmap_vmas(struct vma_munmap_struct *vms,
1199 		struct ma_state *mas_detach)
1200 {
1201 	struct vm_area_struct *next = NULL;
1202 	int error;
1203 
1204 	/*
1205 	 * If we need to split any vma, do it now to save pain later.
1206 	 * Does it split the first one?
1207 	 */
1208 	if (vms->start > vms->vma->vm_start) {
1209 
1210 		/*
1211 		 * Make sure that map_count on return from munmap() will
1212 		 * not exceed its limit; but let map_count go just above
1213 		 * its limit temporarily, to help free resources as expected.
1214 		 */
1215 		if (vms->end < vms->vma->vm_end &&
1216 		    vms->vma->vm_mm->map_count >= sysctl_max_map_count) {
1217 			error = -ENOMEM;
1218 			goto map_count_exceeded;
1219 		}
1220 
1221 		/* Don't bother splitting the VMA if we can't unmap it anyway */
1222 		if (!can_modify_vma(vms->vma)) {
1223 			error = -EPERM;
1224 			goto start_split_failed;
1225 		}
1226 
1227 		error = __split_vma(vms->vmi, vms->vma, vms->start, 1);
1228 		if (error)
1229 			goto start_split_failed;
1230 	}
1231 	vms->prev = vma_prev(vms->vmi);
1232 	if (vms->prev)
1233 		vms->unmap_start = vms->prev->vm_end;
1234 
1235 	/*
1236 	 * Detach a range of VMAs from the mm. Using next as a temp variable as
1237 	 * it is always overwritten.
1238 	 */
1239 	for_each_vma_range(*(vms->vmi), next, vms->end) {
1240 		long nrpages;
1241 
1242 		if (!can_modify_vma(next)) {
1243 			error = -EPERM;
1244 			goto modify_vma_failed;
1245 		}
1246 		/* Does it split the end? */
1247 		if (next->vm_end > vms->end) {
1248 			error = __split_vma(vms->vmi, next, vms->end, 0);
1249 			if (error)
1250 				goto end_split_failed;
1251 		}
1252 		vma_start_write(next);
1253 		mas_set(mas_detach, vms->vma_count++);
1254 		error = mas_store_gfp(mas_detach, next, GFP_KERNEL);
1255 		if (error)
1256 			goto munmap_gather_failed;
1257 
1258 		vma_mark_detached(next);
1259 		nrpages = vma_pages(next);
1260 
1261 		vms->nr_pages += nrpages;
1262 		if (next->vm_flags & VM_LOCKED)
1263 			vms->locked_vm += nrpages;
1264 
1265 		if (next->vm_flags & VM_ACCOUNT)
1266 			vms->nr_accounted += nrpages;
1267 
1268 		if (is_exec_mapping(next->vm_flags))
1269 			vms->exec_vm += nrpages;
1270 		else if (is_stack_mapping(next->vm_flags))
1271 			vms->stack_vm += nrpages;
1272 		else if (is_data_mapping(next->vm_flags))
1273 			vms->data_vm += nrpages;
1274 
1275 		if (unlikely(vms->uf)) {
1276 			/*
1277 			 * If userfaultfd_unmap_prep returns an error the vmas
1278 			 * will remain split, but userland will get a
1279 			 * highly unexpected error anyway. This is no
1280 			 * different than the case where the first of the two
1281 			 * __split_vma fails, but we don't undo the first
1282 			 * split, despite we could. This is unlikely enough
1283 			 * failure that it's not worth optimizing it for.
1284 			 */
1285 			error = userfaultfd_unmap_prep(next, vms->start,
1286 						       vms->end, vms->uf);
1287 			if (error)
1288 				goto userfaultfd_error;
1289 		}
1290 #ifdef CONFIG_DEBUG_VM_MAPLE_TREE
1291 		BUG_ON(next->vm_start < vms->start);
1292 		BUG_ON(next->vm_start > vms->end);
1293 #endif
1294 	}
1295 
1296 	vms->next = vma_next(vms->vmi);
1297 	if (vms->next)
1298 		vms->unmap_end = vms->next->vm_start;
1299 
1300 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
1301 	/* Make sure no VMAs are about to be lost. */
1302 	{
1303 		MA_STATE(test, mas_detach->tree, 0, 0);
1304 		struct vm_area_struct *vma_mas, *vma_test;
1305 		int test_count = 0;
1306 
1307 		vma_iter_set(vms->vmi, vms->start);
1308 		rcu_read_lock();
1309 		vma_test = mas_find(&test, vms->vma_count - 1);
1310 		for_each_vma_range(*(vms->vmi), vma_mas, vms->end) {
1311 			BUG_ON(vma_mas != vma_test);
1312 			test_count++;
1313 			vma_test = mas_next(&test, vms->vma_count - 1);
1314 		}
1315 		rcu_read_unlock();
1316 		BUG_ON(vms->vma_count != test_count);
1317 	}
1318 #endif
1319 
1320 	while (vma_iter_addr(vms->vmi) > vms->start)
1321 		vma_iter_prev_range(vms->vmi);
1322 
1323 	vms->clear_ptes = true;
1324 	return 0;
1325 
1326 userfaultfd_error:
1327 munmap_gather_failed:
1328 end_split_failed:
1329 modify_vma_failed:
1330 	reattach_vmas(mas_detach);
1331 start_split_failed:
1332 map_count_exceeded:
1333 	return error;
1334 }
1335 
1336 /*
1337  * do_vmi_align_munmap() - munmap the aligned region from @start to @end.
1338  * @vmi: The vma iterator
1339  * @vma: The starting vm_area_struct
1340  * @mm: The mm_struct
1341  * @start: The aligned start address to munmap.
1342  * @end: The aligned end address to munmap.
1343  * @uf: The userfaultfd list_head
1344  * @unlock: Set to true to drop the mmap_lock.  unlocking only happens on
1345  * success.
1346  *
1347  * Return: 0 on success and drops the lock if so directed, error and leaves the
1348  * lock held otherwise.
1349  */
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)1350 int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
1351 		struct mm_struct *mm, unsigned long start, unsigned long end,
1352 		struct list_head *uf, bool unlock)
1353 {
1354 	struct maple_tree mt_detach;
1355 	MA_STATE(mas_detach, &mt_detach, 0, 0);
1356 	mt_init_flags(&mt_detach, vmi->mas.tree->ma_flags & MT_FLAGS_LOCK_MASK);
1357 	mt_on_stack(mt_detach);
1358 	struct vma_munmap_struct vms;
1359 	int error;
1360 
1361 	init_vma_munmap(&vms, vmi, vma, start, end, uf, unlock);
1362 	error = vms_gather_munmap_vmas(&vms, &mas_detach);
1363 	if (error)
1364 		goto gather_failed;
1365 
1366 	error = vma_iter_clear_gfp(vmi, start, end, GFP_KERNEL);
1367 	if (error)
1368 		goto clear_tree_failed;
1369 
1370 	/* Point of no return */
1371 	vms_complete_munmap_vmas(&vms, &mas_detach);
1372 	return 0;
1373 
1374 clear_tree_failed:
1375 	reattach_vmas(&mas_detach);
1376 gather_failed:
1377 	validate_mm(mm);
1378 	return error;
1379 }
1380 
1381 /*
1382  * do_vmi_munmap() - munmap a given range.
1383  * @vmi: The vma iterator
1384  * @mm: The mm_struct
1385  * @start: The start address to munmap
1386  * @len: The length of the range to munmap
1387  * @uf: The userfaultfd list_head
1388  * @unlock: set to true if the user wants to drop the mmap_lock on success
1389  *
1390  * This function takes a @mas that is either pointing to the previous VMA or set
1391  * to MA_START and sets it up to remove the mapping(s).  The @len will be
1392  * aligned.
1393  *
1394  * Return: 0 on success and drops the lock if so directed, error and leaves the
1395  * lock held otherwise.
1396  */
do_vmi_munmap(struct vma_iterator * vmi,struct mm_struct * mm,unsigned long start,size_t len,struct list_head * uf,bool unlock)1397 int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
1398 		  unsigned long start, size_t len, struct list_head *uf,
1399 		  bool unlock)
1400 {
1401 	unsigned long end;
1402 	struct vm_area_struct *vma;
1403 
1404 	if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
1405 		return -EINVAL;
1406 
1407 	end = start + PAGE_ALIGN(len);
1408 	if (end == start)
1409 		return -EINVAL;
1410 
1411 	/* Find the first overlapping VMA */
1412 	vma = vma_find(vmi, end);
1413 	if (!vma) {
1414 		if (unlock)
1415 			mmap_write_unlock(mm);
1416 		return 0;
1417 	}
1418 
1419 	return do_vmi_align_munmap(vmi, vma, mm, start, end, uf, unlock);
1420 }
1421 
1422 /*
1423  * We are about to modify one or multiple of a VMA's flags, policy, userfaultfd
1424  * context and anonymous VMA name within the range [start, end).
1425  *
1426  * As a result, we might be able to merge the newly modified VMA range with an
1427  * adjacent VMA with identical properties.
1428  *
1429  * If no merge is possible and the range does not span the entirety of the VMA,
1430  * we then need to split the VMA to accommodate the change.
1431  *
1432  * The function returns either the merged VMA, the original VMA if a split was
1433  * required instead, or an error if the split failed.
1434  */
vma_modify(struct vma_merge_struct * vmg)1435 static struct vm_area_struct *vma_modify(struct vma_merge_struct *vmg)
1436 {
1437 	struct vm_area_struct *vma = vmg->vma;
1438 	unsigned long start = vmg->start;
1439 	unsigned long end = vmg->end;
1440 	struct vm_area_struct *merged;
1441 
1442 	/* First, try to merge. */
1443 	merged = vma_merge_existing_range(vmg);
1444 	if (merged)
1445 		return merged;
1446 	if (vmg_nomem(vmg))
1447 		return ERR_PTR(-ENOMEM);
1448 
1449 	/*
1450 	 * Split can fail for reasons other than OOM, so if the user requests
1451 	 * this it's probably a mistake.
1452 	 */
1453 	VM_WARN_ON(vmg->give_up_on_oom &&
1454 		   (vma->vm_start != start || vma->vm_end != end));
1455 
1456 	/* Split any preceding portion of the VMA. */
1457 	if (vma->vm_start < start) {
1458 		int err = split_vma(vmg->vmi, vma, start, 1);
1459 
1460 		if (err)
1461 			return ERR_PTR(err);
1462 	}
1463 
1464 	/* Split any trailing portion of the VMA. */
1465 	if (vma->vm_end > end) {
1466 		int err = split_vma(vmg->vmi, vma, end, 0);
1467 
1468 		if (err)
1469 			return ERR_PTR(err);
1470 	}
1471 
1472 	return vma;
1473 }
1474 
vma_modify_flags(struct vma_iterator * vmi,struct vm_area_struct * prev,struct vm_area_struct * vma,unsigned long start,unsigned long end,unsigned long new_flags)1475 struct vm_area_struct *vma_modify_flags(
1476 	struct vma_iterator *vmi, struct vm_area_struct *prev,
1477 	struct vm_area_struct *vma, unsigned long start, unsigned long end,
1478 	unsigned long new_flags)
1479 {
1480 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1481 
1482 	vmg.flags = new_flags;
1483 
1484 	return vma_modify(&vmg);
1485 }
1486 
1487 struct vm_area_struct
vma_modify_flags_name(struct vma_iterator * vmi,struct vm_area_struct * prev,struct vm_area_struct * vma,unsigned long start,unsigned long end,unsigned long new_flags,struct anon_vma_name * new_name)1488 *vma_modify_flags_name(struct vma_iterator *vmi,
1489 		       struct vm_area_struct *prev,
1490 		       struct vm_area_struct *vma,
1491 		       unsigned long start,
1492 		       unsigned long end,
1493 		       unsigned long new_flags,
1494 		       struct anon_vma_name *new_name)
1495 {
1496 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1497 
1498 	vmg.flags = new_flags;
1499 	vmg.anon_name = new_name;
1500 
1501 	return vma_modify(&vmg);
1502 }
1503 
1504 struct vm_area_struct
vma_modify_policy(struct vma_iterator * vmi,struct vm_area_struct * prev,struct vm_area_struct * vma,unsigned long start,unsigned long end,struct mempolicy * new_pol)1505 *vma_modify_policy(struct vma_iterator *vmi,
1506 		   struct vm_area_struct *prev,
1507 		   struct vm_area_struct *vma,
1508 		   unsigned long start, unsigned long end,
1509 		   struct mempolicy *new_pol)
1510 {
1511 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1512 
1513 	vmg.policy = new_pol;
1514 
1515 	return vma_modify(&vmg);
1516 }
1517 
1518 struct vm_area_struct
vma_modify_flags_uffd(struct vma_iterator * vmi,struct vm_area_struct * prev,struct vm_area_struct * vma,unsigned long start,unsigned long end,unsigned long new_flags,struct vm_userfaultfd_ctx new_ctx,bool give_up_on_oom)1519 *vma_modify_flags_uffd(struct vma_iterator *vmi,
1520 		       struct vm_area_struct *prev,
1521 		       struct vm_area_struct *vma,
1522 		       unsigned long start, unsigned long end,
1523 		       unsigned long new_flags,
1524 		       struct vm_userfaultfd_ctx new_ctx,
1525 		       bool give_up_on_oom)
1526 {
1527 	VMG_VMA_STATE(vmg, vmi, prev, vma, start, end);
1528 
1529 	vmg.flags = new_flags;
1530 	vmg.uffd_ctx = new_ctx;
1531 	if (give_up_on_oom)
1532 		vmg.give_up_on_oom = true;
1533 
1534 	return vma_modify(&vmg);
1535 }
1536 
1537 /*
1538  * Expand vma by delta bytes, potentially merging with an immediately adjacent
1539  * VMA with identical properties.
1540  */
vma_merge_extend(struct vma_iterator * vmi,struct vm_area_struct * vma,unsigned long delta)1541 struct vm_area_struct *vma_merge_extend(struct vma_iterator *vmi,
1542 					struct vm_area_struct *vma,
1543 					unsigned long delta)
1544 {
1545 	VMG_VMA_STATE(vmg, vmi, vma, vma, vma->vm_end, vma->vm_end + delta);
1546 
1547 	vmg.next = vma_iter_next_rewind(vmi, NULL);
1548 	vmg.vma = NULL; /* We use the VMA to populate VMG fields only. */
1549 
1550 	return vma_merge_new_range(&vmg);
1551 }
1552 
unlink_file_vma_batch_init(struct unlink_vma_file_batch * vb)1553 void unlink_file_vma_batch_init(struct unlink_vma_file_batch *vb)
1554 {
1555 	vb->count = 0;
1556 }
1557 
unlink_file_vma_batch_process(struct unlink_vma_file_batch * vb)1558 static void unlink_file_vma_batch_process(struct unlink_vma_file_batch *vb)
1559 {
1560 	struct address_space *mapping;
1561 	int i;
1562 
1563 	mapping = vb->vmas[0]->vm_file->f_mapping;
1564 	i_mmap_lock_write(mapping);
1565 	for (i = 0; i < vb->count; i++) {
1566 		VM_WARN_ON_ONCE(vb->vmas[i]->vm_file->f_mapping != mapping);
1567 		__remove_shared_vm_struct(vb->vmas[i], mapping);
1568 	}
1569 	i_mmap_unlock_write(mapping);
1570 
1571 	unlink_file_vma_batch_init(vb);
1572 }
1573 
unlink_file_vma_batch_add(struct unlink_vma_file_batch * vb,struct vm_area_struct * vma)1574 void unlink_file_vma_batch_add(struct unlink_vma_file_batch *vb,
1575 			       struct vm_area_struct *vma)
1576 {
1577 	if (vma->vm_file == NULL)
1578 		return;
1579 
1580 	if ((vb->count > 0 && vb->vmas[0]->vm_file != vma->vm_file) ||
1581 	    vb->count == ARRAY_SIZE(vb->vmas))
1582 		unlink_file_vma_batch_process(vb);
1583 
1584 	vb->vmas[vb->count] = vma;
1585 	vb->count++;
1586 }
1587 
unlink_file_vma_batch_final(struct unlink_vma_file_batch * vb)1588 void unlink_file_vma_batch_final(struct unlink_vma_file_batch *vb)
1589 {
1590 	if (vb->count > 0)
1591 		unlink_file_vma_batch_process(vb);
1592 }
1593 
1594 /*
1595  * Unlink a file-based vm structure from its interval tree, to hide
1596  * vma from rmap and vmtruncate before freeing its page tables.
1597  */
unlink_file_vma(struct vm_area_struct * vma)1598 void unlink_file_vma(struct vm_area_struct *vma)
1599 {
1600 	struct file *file = vma->vm_file;
1601 
1602 	if (file) {
1603 		struct address_space *mapping = file->f_mapping;
1604 
1605 		i_mmap_lock_write(mapping);
1606 		__remove_shared_vm_struct(vma, mapping);
1607 		i_mmap_unlock_write(mapping);
1608 	}
1609 }
1610 
vma_link_file(struct vm_area_struct * vma)1611 void vma_link_file(struct vm_area_struct *vma)
1612 {
1613 	struct file *file = vma->vm_file;
1614 	struct address_space *mapping;
1615 
1616 	if (file) {
1617 		mapping = file->f_mapping;
1618 		i_mmap_lock_write(mapping);
1619 		__vma_link_file(vma, mapping);
1620 		i_mmap_unlock_write(mapping);
1621 	}
1622 }
1623 
vma_link(struct mm_struct * mm,struct vm_area_struct * vma)1624 int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
1625 {
1626 	VMA_ITERATOR(vmi, mm, 0);
1627 
1628 	vma_iter_config(&vmi, vma->vm_start, vma->vm_end);
1629 	if (vma_iter_prealloc(&vmi, vma))
1630 		return -ENOMEM;
1631 
1632 	vma_start_write(vma);
1633 	vma_iter_store_new(&vmi, vma);
1634 	vma_link_file(vma);
1635 	mm->map_count++;
1636 	validate_mm(mm);
1637 	return 0;
1638 }
1639 
1640 /*
1641  * Copy the vma structure to a new location in the same mm,
1642  * prior to moving page table entries, to effect an mremap move.
1643  */
copy_vma(struct vm_area_struct ** vmap,unsigned long addr,unsigned long len,pgoff_t pgoff,bool * need_rmap_locks)1644 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
1645 	unsigned long addr, unsigned long len, pgoff_t pgoff,
1646 	bool *need_rmap_locks)
1647 {
1648 	struct vm_area_struct *vma = *vmap;
1649 	unsigned long vma_start = vma->vm_start;
1650 	struct mm_struct *mm = vma->vm_mm;
1651 	struct vm_area_struct *new_vma;
1652 	bool faulted_in_anon_vma = true;
1653 	VMA_ITERATOR(vmi, mm, addr);
1654 	VMG_VMA_STATE(vmg, &vmi, NULL, vma, addr, addr + len);
1655 
1656 	/*
1657 	 * If anonymous vma has not yet been faulted, update new pgoff
1658 	 * to match new location, to increase its chance of merging.
1659 	 */
1660 	if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
1661 		pgoff = addr >> PAGE_SHIFT;
1662 		faulted_in_anon_vma = false;
1663 	}
1664 
1665 	new_vma = find_vma_prev(mm, addr, &vmg.prev);
1666 	if (new_vma && new_vma->vm_start < addr + len)
1667 		return NULL;	/* should never get here */
1668 
1669 	vmg.vma = NULL; /* New VMA range. */
1670 	vmg.pgoff = pgoff;
1671 	vmg.next = vma_iter_next_rewind(&vmi, NULL);
1672 	new_vma = vma_merge_new_range(&vmg);
1673 
1674 	if (new_vma) {
1675 		/*
1676 		 * Source vma may have been merged into new_vma
1677 		 */
1678 		if (unlikely(vma_start >= new_vma->vm_start &&
1679 			     vma_start < new_vma->vm_end)) {
1680 			/*
1681 			 * The only way we can get a vma_merge with
1682 			 * self during an mremap is if the vma hasn't
1683 			 * been faulted in yet and we were allowed to
1684 			 * reset the dst vma->vm_pgoff to the
1685 			 * destination address of the mremap to allow
1686 			 * the merge to happen. mremap must change the
1687 			 * vm_pgoff linearity between src and dst vmas
1688 			 * (in turn preventing a vma_merge) to be
1689 			 * safe. It is only safe to keep the vm_pgoff
1690 			 * linear if there are no pages mapped yet.
1691 			 */
1692 			VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
1693 			*vmap = vma = new_vma;
1694 		}
1695 		*need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
1696 	} else {
1697 		new_vma = vm_area_dup(vma);
1698 		if (!new_vma)
1699 			goto out;
1700 		vma_set_range(new_vma, addr, addr + len, pgoff);
1701 		if (vma_dup_policy(vma, new_vma))
1702 			goto out_free_vma;
1703 		if (anon_vma_clone(new_vma, vma))
1704 			goto out_free_mempol;
1705 		if (new_vma->vm_file)
1706 			get_file(new_vma->vm_file);
1707 		if (new_vma->vm_ops && new_vma->vm_ops->open)
1708 			new_vma->vm_ops->open(new_vma);
1709 		if (vma_link(mm, new_vma))
1710 			goto out_vma_link;
1711 		*need_rmap_locks = false;
1712 	}
1713 	return new_vma;
1714 
1715 out_vma_link:
1716 	vma_close(new_vma);
1717 
1718 	if (new_vma->vm_file)
1719 		fput(new_vma->vm_file);
1720 
1721 	unlink_anon_vmas(new_vma);
1722 out_free_mempol:
1723 	mpol_put(vma_policy(new_vma));
1724 out_free_vma:
1725 	vm_area_free(new_vma);
1726 out:
1727 	return NULL;
1728 }
1729 
1730 /*
1731  * Rough compatibility check to quickly see if it's even worth looking
1732  * at sharing an anon_vma.
1733  *
1734  * They need to have the same vm_file, and the flags can only differ
1735  * in things that mprotect may change.
1736  *
1737  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1738  * we can merge the two vma's. For example, we refuse to merge a vma if
1739  * there is a vm_ops->close() function, because that indicates that the
1740  * driver is doing some kind of reference counting. But that doesn't
1741  * really matter for the anon_vma sharing case.
1742  */
anon_vma_compatible(struct vm_area_struct * a,struct vm_area_struct * b)1743 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1744 {
1745 	return a->vm_end == b->vm_start &&
1746 		mpol_equal(vma_policy(a), vma_policy(b)) &&
1747 		a->vm_file == b->vm_file &&
1748 		!((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1749 		b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1750 }
1751 
1752 /*
1753  * Do some basic sanity checking to see if we can re-use the anon_vma
1754  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1755  * the same as 'old', the other will be the new one that is trying
1756  * to share the anon_vma.
1757  *
1758  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1759  * the anon_vma of 'old' is concurrently in the process of being set up
1760  * by another page fault trying to merge _that_. But that's ok: if it
1761  * is being set up, that automatically means that it will be a singleton
1762  * acceptable for merging, so we can do all of this optimistically. But
1763  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1764  *
1765  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1766  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1767  * is to return an anon_vma that is "complex" due to having gone through
1768  * a fork).
1769  *
1770  * We also make sure that the two vma's are compatible (adjacent,
1771  * and with the same memory policies). That's all stable, even with just
1772  * a read lock on the mmap_lock.
1773  */
reusable_anon_vma(struct vm_area_struct * old,struct vm_area_struct * a,struct vm_area_struct * b)1774 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old,
1775 					  struct vm_area_struct *a,
1776 					  struct vm_area_struct *b)
1777 {
1778 	if (anon_vma_compatible(a, b)) {
1779 		struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1780 
1781 		if (anon_vma && list_is_singular(&old->anon_vma_chain))
1782 			return anon_vma;
1783 	}
1784 	return NULL;
1785 }
1786 
1787 /*
1788  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1789  * neighbouring vmas for a suitable anon_vma, before it goes off
1790  * to allocate a new anon_vma.  It checks because a repetitive
1791  * sequence of mprotects and faults may otherwise lead to distinct
1792  * anon_vmas being allocated, preventing vma merge in subsequent
1793  * mprotect.
1794  */
find_mergeable_anon_vma(struct vm_area_struct * vma)1795 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1796 {
1797 	struct anon_vma *anon_vma = NULL;
1798 	struct vm_area_struct *prev, *next;
1799 	VMA_ITERATOR(vmi, vma->vm_mm, vma->vm_end);
1800 
1801 	/* Try next first. */
1802 	next = vma_iter_load(&vmi);
1803 	if (next) {
1804 		anon_vma = reusable_anon_vma(next, vma, next);
1805 		if (anon_vma)
1806 			return anon_vma;
1807 	}
1808 
1809 	prev = vma_prev(&vmi);
1810 	VM_BUG_ON_VMA(prev != vma, vma);
1811 	prev = vma_prev(&vmi);
1812 	/* Try prev next. */
1813 	if (prev)
1814 		anon_vma = reusable_anon_vma(prev, prev, vma);
1815 
1816 	/*
1817 	 * We might reach here with anon_vma == NULL if we can't find
1818 	 * any reusable anon_vma.
1819 	 * There's no absolute need to look only at touching neighbours:
1820 	 * we could search further afield for "compatible" anon_vmas.
1821 	 * But it would probably just be a waste of time searching,
1822 	 * or lead to too many vmas hanging off the same anon_vma.
1823 	 * We're trying to allow mprotect remerging later on,
1824 	 * not trying to minimize memory used for anon_vmas.
1825 	 */
1826 	return anon_vma;
1827 }
1828 
vm_ops_needs_writenotify(const struct vm_operations_struct * vm_ops)1829 static bool vm_ops_needs_writenotify(const struct vm_operations_struct *vm_ops)
1830 {
1831 	return vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite);
1832 }
1833 
vma_is_shared_writable(struct vm_area_struct * vma)1834 static bool vma_is_shared_writable(struct vm_area_struct *vma)
1835 {
1836 	return (vma->vm_flags & (VM_WRITE | VM_SHARED)) ==
1837 		(VM_WRITE | VM_SHARED);
1838 }
1839 
vma_fs_can_writeback(struct vm_area_struct * vma)1840 static bool vma_fs_can_writeback(struct vm_area_struct *vma)
1841 {
1842 	/* No managed pages to writeback. */
1843 	if (vma->vm_flags & VM_PFNMAP)
1844 		return false;
1845 
1846 	return vma->vm_file && vma->vm_file->f_mapping &&
1847 		mapping_can_writeback(vma->vm_file->f_mapping);
1848 }
1849 
1850 /*
1851  * Does this VMA require the underlying folios to have their dirty state
1852  * tracked?
1853  */
vma_needs_dirty_tracking(struct vm_area_struct * vma)1854 bool vma_needs_dirty_tracking(struct vm_area_struct *vma)
1855 {
1856 	/* Only shared, writable VMAs require dirty tracking. */
1857 	if (!vma_is_shared_writable(vma))
1858 		return false;
1859 
1860 	/* Does the filesystem need to be notified? */
1861 	if (vm_ops_needs_writenotify(vma->vm_ops))
1862 		return true;
1863 
1864 	/*
1865 	 * Even if the filesystem doesn't indicate a need for writenotify, if it
1866 	 * can writeback, dirty tracking is still required.
1867 	 */
1868 	return vma_fs_can_writeback(vma);
1869 }
1870 
1871 /*
1872  * Some shared mappings will want the pages marked read-only
1873  * to track write events. If so, we'll downgrade vm_page_prot
1874  * to the private version (using protection_map[] without the
1875  * VM_SHARED bit).
1876  */
vma_wants_writenotify(struct vm_area_struct * vma,pgprot_t vm_page_prot)1877 bool vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1878 {
1879 	/* If it was private or non-writable, the write bit is already clear */
1880 	if (!vma_is_shared_writable(vma))
1881 		return false;
1882 
1883 	/* The backer wishes to know when pages are first written to? */
1884 	if (vm_ops_needs_writenotify(vma->vm_ops))
1885 		return true;
1886 
1887 	/* The open routine did something to the protections that pgprot_modify
1888 	 * won't preserve? */
1889 	if (pgprot_val(vm_page_prot) !=
1890 	    pgprot_val(vm_pgprot_modify(vm_page_prot, vma->vm_flags)))
1891 		return false;
1892 
1893 	/*
1894 	 * Do we need to track softdirty? hugetlb does not support softdirty
1895 	 * tracking yet.
1896 	 */
1897 	if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1898 		return true;
1899 
1900 	/* Do we need write faults for uffd-wp tracking? */
1901 	if (userfaultfd_wp(vma))
1902 		return true;
1903 
1904 	/* Can the mapping track the dirty pages? */
1905 	return vma_fs_can_writeback(vma);
1906 }
1907 
1908 static DEFINE_MUTEX(mm_all_locks_mutex);
1909 
vm_lock_anon_vma(struct mm_struct * mm,struct anon_vma * anon_vma)1910 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
1911 {
1912 	if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
1913 		/*
1914 		 * The LSB of head.next can't change from under us
1915 		 * because we hold the mm_all_locks_mutex.
1916 		 */
1917 		down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
1918 		/*
1919 		 * We can safely modify head.next after taking the
1920 		 * anon_vma->root->rwsem. If some other vma in this mm shares
1921 		 * the same anon_vma we won't take it again.
1922 		 *
1923 		 * No need of atomic instructions here, head.next
1924 		 * can't change from under us thanks to the
1925 		 * anon_vma->root->rwsem.
1926 		 */
1927 		if (__test_and_set_bit(0, (unsigned long *)
1928 				       &anon_vma->root->rb_root.rb_root.rb_node))
1929 			BUG();
1930 	}
1931 }
1932 
vm_lock_mapping(struct mm_struct * mm,struct address_space * mapping)1933 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
1934 {
1935 	if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
1936 		/*
1937 		 * AS_MM_ALL_LOCKS can't change from under us because
1938 		 * we hold the mm_all_locks_mutex.
1939 		 *
1940 		 * Operations on ->flags have to be atomic because
1941 		 * even if AS_MM_ALL_LOCKS is stable thanks to the
1942 		 * mm_all_locks_mutex, there may be other cpus
1943 		 * changing other bitflags in parallel to us.
1944 		 */
1945 		if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
1946 			BUG();
1947 		down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
1948 	}
1949 }
1950 
1951 /*
1952  * This operation locks against the VM for all pte/vma/mm related
1953  * operations that could ever happen on a certain mm. This includes
1954  * vmtruncate, try_to_unmap, and all page faults.
1955  *
1956  * The caller must take the mmap_lock in write mode before calling
1957  * mm_take_all_locks(). The caller isn't allowed to release the
1958  * mmap_lock until mm_drop_all_locks() returns.
1959  *
1960  * mmap_lock in write mode is required in order to block all operations
1961  * that could modify pagetables and free pages without need of
1962  * altering the vma layout. It's also needed in write mode to avoid new
1963  * anon_vmas to be associated with existing vmas.
1964  *
1965  * A single task can't take more than one mm_take_all_locks() in a row
1966  * or it would deadlock.
1967  *
1968  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
1969  * mapping->flags avoid to take the same lock twice, if more than one
1970  * vma in this mm is backed by the same anon_vma or address_space.
1971  *
1972  * We take locks in following order, accordingly to comment at beginning
1973  * of mm/rmap.c:
1974  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
1975  *     hugetlb mapping);
1976  *   - all vmas marked locked
1977  *   - all i_mmap_rwsem locks;
1978  *   - all anon_vma->rwseml
1979  *
1980  * We can take all locks within these types randomly because the VM code
1981  * doesn't nest them and we protected from parallel mm_take_all_locks() by
1982  * mm_all_locks_mutex.
1983  *
1984  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
1985  * that may have to take thousand of locks.
1986  *
1987  * mm_take_all_locks() can fail if it's interrupted by signals.
1988  */
mm_take_all_locks(struct mm_struct * mm)1989 int mm_take_all_locks(struct mm_struct *mm)
1990 {
1991 	struct vm_area_struct *vma;
1992 	struct anon_vma_chain *avc;
1993 	VMA_ITERATOR(vmi, mm, 0);
1994 
1995 	mmap_assert_write_locked(mm);
1996 
1997 	mutex_lock(&mm_all_locks_mutex);
1998 
1999 	/*
2000 	 * vma_start_write() does not have a complement in mm_drop_all_locks()
2001 	 * because vma_start_write() is always asymmetrical; it marks a VMA as
2002 	 * being written to until mmap_write_unlock() or mmap_write_downgrade()
2003 	 * is reached.
2004 	 */
2005 	for_each_vma(vmi, vma) {
2006 		if (signal_pending(current))
2007 			goto out_unlock;
2008 		vma_start_write(vma);
2009 	}
2010 
2011 	vma_iter_init(&vmi, mm, 0);
2012 	for_each_vma(vmi, vma) {
2013 		if (signal_pending(current))
2014 			goto out_unlock;
2015 		if (vma->vm_file && vma->vm_file->f_mapping &&
2016 				is_vm_hugetlb_page(vma))
2017 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
2018 	}
2019 
2020 	vma_iter_init(&vmi, mm, 0);
2021 	for_each_vma(vmi, vma) {
2022 		if (signal_pending(current))
2023 			goto out_unlock;
2024 		if (vma->vm_file && vma->vm_file->f_mapping &&
2025 				!is_vm_hugetlb_page(vma))
2026 			vm_lock_mapping(mm, vma->vm_file->f_mapping);
2027 	}
2028 
2029 	vma_iter_init(&vmi, mm, 0);
2030 	for_each_vma(vmi, vma) {
2031 		if (signal_pending(current))
2032 			goto out_unlock;
2033 		if (vma->anon_vma)
2034 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2035 				vm_lock_anon_vma(mm, avc->anon_vma);
2036 	}
2037 
2038 	return 0;
2039 
2040 out_unlock:
2041 	mm_drop_all_locks(mm);
2042 	return -EINTR;
2043 }
2044 
vm_unlock_anon_vma(struct anon_vma * anon_vma)2045 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
2046 {
2047 	if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
2048 		/*
2049 		 * The LSB of head.next can't change to 0 from under
2050 		 * us because we hold the mm_all_locks_mutex.
2051 		 *
2052 		 * We must however clear the bitflag before unlocking
2053 		 * the vma so the users using the anon_vma->rb_root will
2054 		 * never see our bitflag.
2055 		 *
2056 		 * No need of atomic instructions here, head.next
2057 		 * can't change from under us until we release the
2058 		 * anon_vma->root->rwsem.
2059 		 */
2060 		if (!__test_and_clear_bit(0, (unsigned long *)
2061 					  &anon_vma->root->rb_root.rb_root.rb_node))
2062 			BUG();
2063 		anon_vma_unlock_write(anon_vma);
2064 	}
2065 }
2066 
vm_unlock_mapping(struct address_space * mapping)2067 static void vm_unlock_mapping(struct address_space *mapping)
2068 {
2069 	if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
2070 		/*
2071 		 * AS_MM_ALL_LOCKS can't change to 0 from under us
2072 		 * because we hold the mm_all_locks_mutex.
2073 		 */
2074 		i_mmap_unlock_write(mapping);
2075 		if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
2076 					&mapping->flags))
2077 			BUG();
2078 	}
2079 }
2080 
2081 /*
2082  * The mmap_lock cannot be released by the caller until
2083  * mm_drop_all_locks() returns.
2084  */
mm_drop_all_locks(struct mm_struct * mm)2085 void mm_drop_all_locks(struct mm_struct *mm)
2086 {
2087 	struct vm_area_struct *vma;
2088 	struct anon_vma_chain *avc;
2089 	VMA_ITERATOR(vmi, mm, 0);
2090 
2091 	mmap_assert_write_locked(mm);
2092 	BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
2093 
2094 	for_each_vma(vmi, vma) {
2095 		if (vma->anon_vma)
2096 			list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
2097 				vm_unlock_anon_vma(avc->anon_vma);
2098 		if (vma->vm_file && vma->vm_file->f_mapping)
2099 			vm_unlock_mapping(vma->vm_file->f_mapping);
2100 	}
2101 
2102 	mutex_unlock(&mm_all_locks_mutex);
2103 }
2104