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