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