mm/mmap: use maple tree for unmapped_area{_topdown}
[platform/kernel/linux-starfive.git] / mm / mmap.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * mm/mmap.c
4  *
5  * Written by obz.
6  *
7  * Address space accounting code        <alan@lxorguk.ukuu.org.uk>
8  */
9
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11
12 #include <linux/kernel.h>
13 #include <linux/slab.h>
14 #include <linux/backing-dev.h>
15 #include <linux/mm.h>
16 #include <linux/mm_inline.h>
17 #include <linux/vmacache.h>
18 #include <linux/shm.h>
19 #include <linux/mman.h>
20 #include <linux/pagemap.h>
21 #include <linux/swap.h>
22 #include <linux/syscalls.h>
23 #include <linux/capability.h>
24 #include <linux/init.h>
25 #include <linux/file.h>
26 #include <linux/fs.h>
27 #include <linux/personality.h>
28 #include <linux/security.h>
29 #include <linux/hugetlb.h>
30 #include <linux/shmem_fs.h>
31 #include <linux/profile.h>
32 #include <linux/export.h>
33 #include <linux/mount.h>
34 #include <linux/mempolicy.h>
35 #include <linux/rmap.h>
36 #include <linux/mmu_notifier.h>
37 #include <linux/mmdebug.h>
38 #include <linux/perf_event.h>
39 #include <linux/audit.h>
40 #include <linux/khugepaged.h>
41 #include <linux/uprobes.h>
42 #include <linux/rbtree_augmented.h>
43 #include <linux/notifier.h>
44 #include <linux/memory.h>
45 #include <linux/printk.h>
46 #include <linux/userfaultfd_k.h>
47 #include <linux/moduleparam.h>
48 #include <linux/pkeys.h>
49 #include <linux/oom.h>
50 #include <linux/sched/mm.h>
51
52 #include <linux/uaccess.h>
53 #include <asm/cacheflush.h>
54 #include <asm/tlb.h>
55 #include <asm/mmu_context.h>
56
57 #define CREATE_TRACE_POINTS
58 #include <trace/events/mmap.h>
59
60 #include "internal.h"
61
62 #ifndef arch_mmap_check
63 #define arch_mmap_check(addr, len, flags)       (0)
64 #endif
65
66 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
67 const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
68 const int mmap_rnd_bits_max = CONFIG_ARCH_MMAP_RND_BITS_MAX;
69 int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
70 #endif
71 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
72 const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
73 const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
74 int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
75 #endif
76
77 static bool ignore_rlimit_data;
78 core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
79
80 static void unmap_region(struct mm_struct *mm,
81                 struct vm_area_struct *vma, struct vm_area_struct *prev,
82                 unsigned long start, unsigned long end);
83
84 static pgprot_t vm_pgprot_modify(pgprot_t oldprot, unsigned long vm_flags)
85 {
86         return pgprot_modify(oldprot, vm_get_page_prot(vm_flags));
87 }
88
89 /* Update vma->vm_page_prot to reflect vma->vm_flags. */
90 void vma_set_page_prot(struct vm_area_struct *vma)
91 {
92         unsigned long vm_flags = vma->vm_flags;
93         pgprot_t vm_page_prot;
94
95         vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
96         if (vma_wants_writenotify(vma, vm_page_prot)) {
97                 vm_flags &= ~VM_SHARED;
98                 vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
99         }
100         /* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
101         WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
102 }
103
104 /*
105  * Requires inode->i_mapping->i_mmap_rwsem
106  */
107 static void __remove_shared_vm_struct(struct vm_area_struct *vma,
108                 struct file *file, struct address_space *mapping)
109 {
110         if (vma->vm_flags & VM_SHARED)
111                 mapping_unmap_writable(mapping);
112
113         flush_dcache_mmap_lock(mapping);
114         vma_interval_tree_remove(vma, &mapping->i_mmap);
115         flush_dcache_mmap_unlock(mapping);
116 }
117
118 /*
119  * Unlink a file-based vm structure from its interval tree, to hide
120  * vma from rmap and vmtruncate before freeing its page tables.
121  */
122 void unlink_file_vma(struct vm_area_struct *vma)
123 {
124         struct file *file = vma->vm_file;
125
126         if (file) {
127                 struct address_space *mapping = file->f_mapping;
128                 i_mmap_lock_write(mapping);
129                 __remove_shared_vm_struct(vma, file, mapping);
130                 i_mmap_unlock_write(mapping);
131         }
132 }
133
134 /*
135  * Close a vm structure and free it, returning the next.
136  */
137 static struct vm_area_struct *remove_vma(struct vm_area_struct *vma)
138 {
139         struct vm_area_struct *next = vma->vm_next;
140
141         might_sleep();
142         if (vma->vm_ops && vma->vm_ops->close)
143                 vma->vm_ops->close(vma);
144         if (vma->vm_file)
145                 fput(vma->vm_file);
146         mpol_put(vma_policy(vma));
147         vm_area_free(vma);
148         return next;
149 }
150
151 static int do_brk_flags(unsigned long addr, unsigned long request, unsigned long flags,
152                 struct list_head *uf);
153 SYSCALL_DEFINE1(brk, unsigned long, brk)
154 {
155         unsigned long newbrk, oldbrk, origbrk;
156         struct mm_struct *mm = current->mm;
157         struct vm_area_struct *next;
158         unsigned long min_brk;
159         bool populate;
160         bool downgraded = false;
161         LIST_HEAD(uf);
162
163         if (mmap_write_lock_killable(mm))
164                 return -EINTR;
165
166         origbrk = mm->brk;
167
168 #ifdef CONFIG_COMPAT_BRK
169         /*
170          * CONFIG_COMPAT_BRK can still be overridden by setting
171          * randomize_va_space to 2, which will still cause mm->start_brk
172          * to be arbitrarily shifted
173          */
174         if (current->brk_randomized)
175                 min_brk = mm->start_brk;
176         else
177                 min_brk = mm->end_data;
178 #else
179         min_brk = mm->start_brk;
180 #endif
181         if (brk < min_brk)
182                 goto out;
183
184         /*
185          * Check against rlimit here. If this check is done later after the test
186          * of oldbrk with newbrk then it can escape the test and let the data
187          * segment grow beyond its set limit the in case where the limit is
188          * not page aligned -Ram Gupta
189          */
190         if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
191                               mm->end_data, mm->start_data))
192                 goto out;
193
194         newbrk = PAGE_ALIGN(brk);
195         oldbrk = PAGE_ALIGN(mm->brk);
196         if (oldbrk == newbrk) {
197                 mm->brk = brk;
198                 goto success;
199         }
200
201         /*
202          * Always allow shrinking brk.
203          * __do_munmap() may downgrade mmap_lock to read.
204          */
205         if (brk <= mm->brk) {
206                 int ret;
207
208                 /*
209                  * mm->brk must to be protected by write mmap_lock so update it
210                  * before downgrading mmap_lock. When __do_munmap() fails,
211                  * mm->brk will be restored from origbrk.
212                  */
213                 mm->brk = brk;
214                 ret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);
215                 if (ret < 0) {
216                         mm->brk = origbrk;
217                         goto out;
218                 } else if (ret == 1) {
219                         downgraded = true;
220                 }
221                 goto success;
222         }
223
224         /* Check against existing mmap mappings. */
225         next = find_vma(mm, oldbrk);
226         if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
227                 goto out;
228
229         /* Ok, looks good - let it rip. */
230         if (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)
231                 goto out;
232         mm->brk = brk;
233
234 success:
235         populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
236         if (downgraded)
237                 mmap_read_unlock(mm);
238         else
239                 mmap_write_unlock(mm);
240         userfaultfd_unmap_complete(mm, &uf);
241         if (populate)
242                 mm_populate(oldbrk, newbrk - oldbrk);
243         return brk;
244
245 out:
246         mmap_write_unlock(mm);
247         return origbrk;
248 }
249
250 static inline unsigned long vma_compute_gap(struct vm_area_struct *vma)
251 {
252         unsigned long gap, prev_end;
253
254         /*
255          * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
256          * allow two stack_guard_gaps between them here, and when choosing
257          * an unmapped area; whereas when expanding we only require one.
258          * That's a little inconsistent, but keeps the code here simpler.
259          */
260         gap = vm_start_gap(vma);
261         if (vma->vm_prev) {
262                 prev_end = vm_end_gap(vma->vm_prev);
263                 if (gap > prev_end)
264                         gap -= prev_end;
265                 else
266                         gap = 0;
267         }
268         return gap;
269 }
270
271 #ifdef CONFIG_DEBUG_VM_RB
272 static unsigned long vma_compute_subtree_gap(struct vm_area_struct *vma)
273 {
274         unsigned long max = vma_compute_gap(vma), subtree_gap;
275         if (vma->vm_rb.rb_left) {
276                 subtree_gap = rb_entry(vma->vm_rb.rb_left,
277                                 struct vm_area_struct, vm_rb)->rb_subtree_gap;
278                 if (subtree_gap > max)
279                         max = subtree_gap;
280         }
281         if (vma->vm_rb.rb_right) {
282                 subtree_gap = rb_entry(vma->vm_rb.rb_right,
283                                 struct vm_area_struct, vm_rb)->rb_subtree_gap;
284                 if (subtree_gap > max)
285                         max = subtree_gap;
286         }
287         return max;
288 }
289
290 static int browse_rb(struct mm_struct *mm)
291 {
292         struct rb_root *root = &mm->mm_rb;
293         int i = 0, j, bug = 0;
294         struct rb_node *nd, *pn = NULL;
295         unsigned long prev = 0, pend = 0;
296
297         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
298                 struct vm_area_struct *vma;
299                 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
300                 if (vma->vm_start < prev) {
301                         pr_emerg("vm_start %lx < prev %lx\n",
302                                   vma->vm_start, prev);
303                         bug = 1;
304                 }
305                 if (vma->vm_start < pend) {
306                         pr_emerg("vm_start %lx < pend %lx\n",
307                                   vma->vm_start, pend);
308                         bug = 1;
309                 }
310                 if (vma->vm_start > vma->vm_end) {
311                         pr_emerg("vm_start %lx > vm_end %lx\n",
312                                   vma->vm_start, vma->vm_end);
313                         bug = 1;
314                 }
315                 spin_lock(&mm->page_table_lock);
316                 if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
317                         pr_emerg("free gap %lx, correct %lx\n",
318                                vma->rb_subtree_gap,
319                                vma_compute_subtree_gap(vma));
320                         bug = 1;
321                 }
322                 spin_unlock(&mm->page_table_lock);
323                 i++;
324                 pn = nd;
325                 prev = vma->vm_start;
326                 pend = vma->vm_end;
327         }
328         j = 0;
329         for (nd = pn; nd; nd = rb_prev(nd))
330                 j++;
331         if (i != j) {
332                 pr_emerg("backwards %d, forwards %d\n", j, i);
333                 bug = 1;
334         }
335         return bug ? -1 : i;
336 }
337 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
338 extern void mt_validate(struct maple_tree *mt);
339 extern void mt_dump(const struct maple_tree *mt);
340
341 /* Validate the maple tree */
342 static void validate_mm_mt(struct mm_struct *mm)
343 {
344         struct maple_tree *mt = &mm->mm_mt;
345         struct vm_area_struct *vma_mt, *vma = mm->mmap;
346
347         MA_STATE(mas, mt, 0, 0);
348
349         mt_validate(&mm->mm_mt);
350         mas_for_each(&mas, vma_mt, ULONG_MAX) {
351                 if (xa_is_zero(vma_mt))
352                         continue;
353
354                 if (!vma)
355                         break;
356
357                 if ((vma != vma_mt) ||
358                     (vma->vm_start != vma_mt->vm_start) ||
359                     (vma->vm_end != vma_mt->vm_end) ||
360                     (vma->vm_start != mas.index) ||
361                     (vma->vm_end - 1 != mas.last)) {
362                         pr_emerg("issue in %s\n", current->comm);
363                         dump_stack();
364 #ifdef CONFIG_DEBUG_VM
365                         dump_vma(vma_mt);
366                         pr_emerg("and next in rb\n");
367                         dump_vma(vma->vm_next);
368 #endif
369                         pr_emerg("mt piv: %p %lu - %lu\n", vma_mt,
370                                  mas.index, mas.last);
371                         pr_emerg("mt vma: %p %lu - %lu\n", vma_mt,
372                                  vma_mt->vm_start, vma_mt->vm_end);
373                         pr_emerg("rb vma: %p %lu - %lu\n", vma,
374                                  vma->vm_start, vma->vm_end);
375                         pr_emerg("rb->next = %p %lu - %lu\n", vma->vm_next,
376                                         vma->vm_next->vm_start, vma->vm_next->vm_end);
377
378                         mt_dump(mas.tree);
379                         if (vma_mt->vm_end != mas.last + 1) {
380                                 pr_err("vma: %p vma_mt %lu-%lu\tmt %lu-%lu\n",
381                                                 mm, vma_mt->vm_start, vma_mt->vm_end,
382                                                 mas.index, mas.last);
383                                 mt_dump(mas.tree);
384                         }
385                         VM_BUG_ON_MM(vma_mt->vm_end != mas.last + 1, mm);
386                         if (vma_mt->vm_start != mas.index) {
387                                 pr_err("vma: %p vma_mt %p %lu - %lu doesn't match\n",
388                                                 mm, vma_mt, vma_mt->vm_start, vma_mt->vm_end);
389                                 mt_dump(mas.tree);
390                         }
391                         VM_BUG_ON_MM(vma_mt->vm_start != mas.index, mm);
392                 }
393                 VM_BUG_ON(vma != vma_mt);
394                 vma = vma->vm_next;
395
396         }
397         VM_BUG_ON(vma);
398 }
399 #else
400 #define validate_mm_mt(root) do { } while (0)
401 #endif
402 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
403 {
404         struct rb_node *nd;
405
406         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
407                 struct vm_area_struct *vma;
408                 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
409                 VM_BUG_ON_VMA(vma != ignore &&
410                         vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
411                         vma);
412         }
413 }
414
415 static void validate_mm(struct mm_struct *mm)
416 {
417         int bug = 0;
418         int i = 0;
419         unsigned long highest_address = 0;
420         struct vm_area_struct *vma = mm->mmap;
421
422         while (vma) {
423                 struct anon_vma *anon_vma = vma->anon_vma;
424                 struct anon_vma_chain *avc;
425
426                 if (anon_vma) {
427                         anon_vma_lock_read(anon_vma);
428                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
429                                 anon_vma_interval_tree_verify(avc);
430                         anon_vma_unlock_read(anon_vma);
431                 }
432
433                 highest_address = vm_end_gap(vma);
434                 vma = vma->vm_next;
435                 i++;
436         }
437         if (i != mm->map_count) {
438                 pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
439                 bug = 1;
440         }
441         if (highest_address != mm->highest_vm_end) {
442                 pr_emerg("mm->highest_vm_end %lx, found %lx\n",
443                           mm->highest_vm_end, highest_address);
444                 bug = 1;
445         }
446         i = browse_rb(mm);
447         if (i != mm->map_count) {
448                 if (i != -1)
449                         pr_emerg("map_count %d rb %d\n", mm->map_count, i);
450                 bug = 1;
451         }
452         VM_BUG_ON_MM(bug, mm);
453 }
454 #else
455 #define validate_mm_rb(root, ignore) do { } while (0)
456 #define validate_mm_mt(root) do { } while (0)
457 #define validate_mm(mm) do { } while (0)
458 #endif
459
460 RB_DECLARE_CALLBACKS_MAX(static, vma_gap_callbacks,
461                          struct vm_area_struct, vm_rb,
462                          unsigned long, rb_subtree_gap, vma_compute_gap)
463
464 /*
465  * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
466  * vma->vm_prev->vm_end values changed, without modifying the vma's position
467  * in the rbtree.
468  */
469 static void vma_gap_update(struct vm_area_struct *vma)
470 {
471         /*
472          * As it turns out, RB_DECLARE_CALLBACKS_MAX() already created
473          * a callback function that does exactly what we want.
474          */
475         vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
476 }
477
478 static inline void vma_rb_insert(struct vm_area_struct *vma,
479                                  struct rb_root *root)
480 {
481         /* All rb_subtree_gap values must be consistent prior to insertion */
482         validate_mm_rb(root, NULL);
483
484         rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
485 }
486
487 static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
488 {
489         /*
490          * Note rb_erase_augmented is a fairly large inline function,
491          * so make sure we instantiate it only once with our desired
492          * augmented rbtree callbacks.
493          */
494         rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
495 }
496
497 static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,
498                                                 struct rb_root *root,
499                                                 struct vm_area_struct *ignore)
500 {
501         /*
502          * All rb_subtree_gap values must be consistent prior to erase,
503          * with the possible exception of
504          *
505          * a. the "next" vma being erased if next->vm_start was reduced in
506          *    __vma_adjust() -> __vma_unlink()
507          * b. the vma being erased in detach_vmas_to_be_unmapped() ->
508          *    vma_rb_erase()
509          */
510         validate_mm_rb(root, ignore);
511
512         __vma_rb_erase(vma, root);
513 }
514
515 static __always_inline void vma_rb_erase(struct vm_area_struct *vma,
516                                          struct rb_root *root)
517 {
518         vma_rb_erase_ignore(vma, root, vma);
519 }
520
521 /*
522  * vma has some anon_vma assigned, and is already inserted on that
523  * anon_vma's interval trees.
524  *
525  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
526  * vma must be removed from the anon_vma's interval trees using
527  * anon_vma_interval_tree_pre_update_vma().
528  *
529  * After the update, the vma will be reinserted using
530  * anon_vma_interval_tree_post_update_vma().
531  *
532  * The entire update must be protected by exclusive mmap_lock and by
533  * the root anon_vma's mutex.
534  */
535 static inline void
536 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
537 {
538         struct anon_vma_chain *avc;
539
540         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
541                 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
542 }
543
544 static inline void
545 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
546 {
547         struct anon_vma_chain *avc;
548
549         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
550                 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
551 }
552
553 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
554                 unsigned long end, struct vm_area_struct **pprev,
555                 struct rb_node ***rb_link, struct rb_node **rb_parent)
556 {
557         struct rb_node **__rb_link, *__rb_parent, *rb_prev;
558
559         mmap_assert_locked(mm);
560         __rb_link = &mm->mm_rb.rb_node;
561         rb_prev = __rb_parent = NULL;
562
563         while (*__rb_link) {
564                 struct vm_area_struct *vma_tmp;
565
566                 __rb_parent = *__rb_link;
567                 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
568
569                 if (vma_tmp->vm_end > addr) {
570                         /* Fail if an existing vma overlaps the area */
571                         if (vma_tmp->vm_start < end)
572                                 return -ENOMEM;
573                         __rb_link = &__rb_parent->rb_left;
574                 } else {
575                         rb_prev = __rb_parent;
576                         __rb_link = &__rb_parent->rb_right;
577                 }
578         }
579
580         *pprev = NULL;
581         if (rb_prev)
582                 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
583         *rb_link = __rb_link;
584         *rb_parent = __rb_parent;
585         return 0;
586 }
587
588 /*
589  * __vma_next() - Get the next VMA.
590  * @mm: The mm_struct.
591  * @vma: The current vma.
592  *
593  * If @vma is NULL, return the first vma in the mm.
594  *
595  * Returns: The next VMA after @vma.
596  */
597 static inline struct vm_area_struct *__vma_next(struct mm_struct *mm,
598                                          struct vm_area_struct *vma)
599 {
600         if (!vma)
601                 return mm->mmap;
602
603         return vma->vm_next;
604 }
605
606 /*
607  * munmap_vma_range() - munmap VMAs that overlap a range.
608  * @mm: The mm struct
609  * @start: The start of the range.
610  * @len: The length of the range.
611  * @pprev: pointer to the pointer that will be set to previous vm_area_struct
612  * @rb_link: the rb_node
613  * @rb_parent: the parent rb_node
614  *
615  * Find all the vm_area_struct that overlap from @start to
616  * @end and munmap them.  Set @pprev to the previous vm_area_struct.
617  *
618  * Returns: -ENOMEM on munmap failure or 0 on success.
619  */
620 static inline int
621 munmap_vma_range(struct mm_struct *mm, unsigned long start, unsigned long len,
622                  struct vm_area_struct **pprev, struct rb_node ***link,
623                  struct rb_node **parent, struct list_head *uf)
624 {
625
626         while (find_vma_links(mm, start, start + len, pprev, link, parent))
627                 if (do_munmap(mm, start, len, uf))
628                         return -ENOMEM;
629
630         return 0;
631 }
632
633 static unsigned long count_vma_pages_range(struct mm_struct *mm,
634                 unsigned long addr, unsigned long end)
635 {
636         VMA_ITERATOR(vmi, mm, addr);
637         struct vm_area_struct *vma;
638         unsigned long nr_pages = 0;
639
640         for_each_vma_range(vmi, vma, end) {
641                 unsigned long vm_start = max(addr, vma->vm_start);
642                 unsigned long vm_end = min(end, vma->vm_end);
643
644                 nr_pages += PHYS_PFN(vm_end - vm_start);
645         }
646
647         return nr_pages;
648 }
649
650 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
651                 struct rb_node **rb_link, struct rb_node *rb_parent)
652 {
653         /* Update tracking information for the gap following the new vma. */
654         if (vma->vm_next)
655                 vma_gap_update(vma->vm_next);
656         else
657                 mm->highest_vm_end = vm_end_gap(vma);
658
659         /*
660          * vma->vm_prev wasn't known when we followed the rbtree to find the
661          * correct insertion point for that vma. As a result, we could not
662          * update the vma vm_rb parents rb_subtree_gap values on the way down.
663          * So, we first insert the vma with a zero rb_subtree_gap value
664          * (to be consistent with what we did on the way down), and then
665          * immediately update the gap to the correct value. Finally we
666          * rebalance the rbtree after all augmented values have been set.
667          */
668         rb_link_node(&vma->vm_rb, rb_parent, rb_link);
669         vma->rb_subtree_gap = 0;
670         vma_gap_update(vma);
671         vma_rb_insert(vma, &mm->mm_rb);
672 }
673
674 static void __vma_link_file(struct vm_area_struct *vma)
675 {
676         struct file *file;
677
678         file = vma->vm_file;
679         if (file) {
680                 struct address_space *mapping = file->f_mapping;
681
682                 if (vma->vm_flags & VM_SHARED)
683                         mapping_allow_writable(mapping);
684
685                 flush_dcache_mmap_lock(mapping);
686                 vma_interval_tree_insert(vma, &mapping->i_mmap);
687                 flush_dcache_mmap_unlock(mapping);
688         }
689 }
690
691 /*
692  * vma_mas_store() - Store a VMA in the maple tree.
693  * @vma: The vm_area_struct
694  * @mas: The maple state
695  *
696  * Efficient way to store a VMA in the maple tree when the @mas has already
697  * walked to the correct location.
698  *
699  * Note: the end address is inclusive in the maple tree.
700  */
701 void vma_mas_store(struct vm_area_struct *vma, struct ma_state *mas)
702 {
703         trace_vma_store(mas->tree, vma);
704         mas_set_range(mas, vma->vm_start, vma->vm_end - 1);
705         mas_store_prealloc(mas, vma);
706 }
707
708 /*
709  * vma_mas_remove() - Remove a VMA from the maple tree.
710  * @vma: The vm_area_struct
711  * @mas: The maple state
712  *
713  * Efficient way to remove a VMA from the maple tree when the @mas has already
714  * been established and points to the correct location.
715  * Note: the end address is inclusive in the maple tree.
716  */
717 void vma_mas_remove(struct vm_area_struct *vma, struct ma_state *mas)
718 {
719         trace_vma_mas_szero(mas->tree, vma->vm_start, vma->vm_end - 1);
720         mas->index = vma->vm_start;
721         mas->last = vma->vm_end - 1;
722         mas_store_prealloc(mas, NULL);
723 }
724
725 /*
726  * vma_mas_szero() - Set a given range to zero.  Used when modifying a
727  * vm_area_struct start or end.
728  *
729  * @mm: The struct_mm
730  * @start: The start address to zero
731  * @end: The end address to zero.
732  */
733 static inline void vma_mas_szero(struct ma_state *mas, unsigned long start,
734                                 unsigned long end)
735 {
736         trace_vma_mas_szero(mas->tree, start, end - 1);
737         mas_set_range(mas, start, end - 1);
738         mas_store_prealloc(mas, NULL);
739 }
740
741 static void
742 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
743         struct vm_area_struct *prev, struct rb_node **rb_link,
744         struct rb_node *rb_parent)
745 {
746         __vma_link_list(mm, vma, prev);
747         __vma_link_rb(mm, vma, rb_link, rb_parent);
748 }
749
750 static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
751                         struct vm_area_struct *prev, struct rb_node **rb_link,
752                         struct rb_node *rb_parent)
753 {
754         MA_STATE(mas, &mm->mm_mt, 0, 0);
755         struct address_space *mapping = NULL;
756
757         if (mas_preallocate(&mas, vma, GFP_KERNEL))
758                 return -ENOMEM;
759
760         if (vma->vm_file) {
761                 mapping = vma->vm_file->f_mapping;
762                 i_mmap_lock_write(mapping);
763         }
764
765         vma_mas_store(vma, &mas);
766         __vma_link(mm, vma, prev, rb_link, rb_parent);
767         __vma_link_file(vma);
768
769         if (mapping)
770                 i_mmap_unlock_write(mapping);
771
772         mm->map_count++;
773         validate_mm(mm);
774         return 0;
775 }
776
777 /*
778  * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
779  * mm's list and rbtree.  It has already been inserted into the interval tree.
780  */
781 static void __insert_vm_struct(struct mm_struct *mm, struct ma_state *mas,
782                                struct vm_area_struct *vma)
783 {
784         struct vm_area_struct *prev;
785         struct rb_node **rb_link, *rb_parent;
786
787         if (find_vma_links(mm, vma->vm_start, vma->vm_end,
788                            &prev, &rb_link, &rb_parent))
789                 BUG();
790
791         vma_mas_store(vma, mas);
792         __vma_link_list(mm, vma, prev);
793         __vma_link_rb(mm, vma, rb_link, rb_parent);
794         mm->map_count++;
795 }
796
797 static __always_inline void __vma_unlink(struct mm_struct *mm,
798                                                 struct vm_area_struct *vma,
799                                                 struct vm_area_struct *ignore)
800 {
801         vma_rb_erase_ignore(vma, &mm->mm_rb, ignore);
802         __vma_unlink_list(mm, vma);
803         /* Kill the cache */
804         vmacache_invalidate(mm);
805 }
806
807 /*
808  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
809  * is already present in an i_mmap tree without adjusting the tree.
810  * The following helper function should be used when such adjustments
811  * are necessary.  The "insert" vma (if any) is to be inserted
812  * before we drop the necessary locks.
813  */
814 int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
815         unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
816         struct vm_area_struct *expand)
817 {
818         struct mm_struct *mm = vma->vm_mm;
819         struct vm_area_struct *next = vma->vm_next, *orig_vma = vma;
820         struct vm_area_struct *next_next;
821         struct address_space *mapping = NULL;
822         struct rb_root_cached *root = NULL;
823         struct anon_vma *anon_vma = NULL;
824         struct file *file = vma->vm_file;
825         bool start_changed = false, end_changed = false;
826         long adjust_next = 0;
827         int remove_next = 0;
828         MA_STATE(mas, &mm->mm_mt, 0, 0);
829         struct vm_area_struct *exporter = NULL, *importer = NULL;
830
831         validate_mm(mm);
832         validate_mm_mt(mm);
833
834         if (next && !insert) {
835                 if (end >= next->vm_end) {
836                         /*
837                          * vma expands, overlapping all the next, and
838                          * perhaps the one after too (mprotect case 6).
839                          * The only other cases that gets here are
840                          * case 1, case 7 and case 8.
841                          */
842                         if (next == expand) {
843                                 /*
844                                  * The only case where we don't expand "vma"
845                                  * and we expand "next" instead is case 8.
846                                  */
847                                 VM_WARN_ON(end != next->vm_end);
848                                 /*
849                                  * remove_next == 3 means we're
850                                  * removing "vma" and that to do so we
851                                  * swapped "vma" and "next".
852                                  */
853                                 remove_next = 3;
854                                 VM_WARN_ON(file != next->vm_file);
855                                 swap(vma, next);
856                         } else {
857                                 VM_WARN_ON(expand != vma);
858                                 /*
859                                  * case 1, 6, 7, remove_next == 2 is case 6,
860                                  * remove_next == 1 is case 1 or 7.
861                                  */
862                                 remove_next = 1 + (end > next->vm_end);
863                                 if (remove_next == 2)
864                                         next_next = find_vma(mm, next->vm_end);
865
866                                 VM_WARN_ON(remove_next == 2 &&
867                                            end != next->vm_next->vm_end);
868                         }
869
870                         exporter = next;
871                         importer = vma;
872
873                         /*
874                          * If next doesn't have anon_vma, import from vma after
875                          * next, if the vma overlaps with it.
876                          */
877                         if (remove_next == 2 && !next->anon_vma)
878                                 exporter = next->vm_next;
879
880                 } else if (end > next->vm_start) {
881                         /*
882                          * vma expands, overlapping part of the next:
883                          * mprotect case 5 shifting the boundary up.
884                          */
885                         adjust_next = (end - next->vm_start);
886                         exporter = next;
887                         importer = vma;
888                         VM_WARN_ON(expand != importer);
889                 } else if (end < vma->vm_end) {
890                         /*
891                          * vma shrinks, and !insert tells it's not
892                          * split_vma inserting another: so it must be
893                          * mprotect case 4 shifting the boundary down.
894                          */
895                         adjust_next = -(vma->vm_end - end);
896                         exporter = vma;
897                         importer = next;
898                         VM_WARN_ON(expand != importer);
899                 }
900
901                 /*
902                  * Easily overlooked: when mprotect shifts the boundary,
903                  * make sure the expanding vma has anon_vma set if the
904                  * shrinking vma had, to cover any anon pages imported.
905                  */
906                 if (exporter && exporter->anon_vma && !importer->anon_vma) {
907                         int error;
908
909                         importer->anon_vma = exporter->anon_vma;
910                         error = anon_vma_clone(importer, exporter);
911                         if (error)
912                                 return error;
913                 }
914         }
915
916         if (mas_preallocate(&mas, vma, GFP_KERNEL))
917                 return -ENOMEM;
918
919         vma_adjust_trans_huge(orig_vma, start, end, adjust_next);
920         if (file) {
921                 mapping = file->f_mapping;
922                 root = &mapping->i_mmap;
923                 uprobe_munmap(vma, vma->vm_start, vma->vm_end);
924
925                 if (adjust_next)
926                         uprobe_munmap(next, next->vm_start, next->vm_end);
927
928                 i_mmap_lock_write(mapping);
929                 if (insert) {
930                         /*
931                          * Put into interval tree now, so instantiated pages
932                          * are visible to arm/parisc __flush_dcache_page
933                          * throughout; but we cannot insert into address
934                          * space until vma start or end is updated.
935                          */
936                         __vma_link_file(insert);
937                 }
938         }
939
940         anon_vma = vma->anon_vma;
941         if (!anon_vma && adjust_next)
942                 anon_vma = next->anon_vma;
943         if (anon_vma) {
944                 VM_WARN_ON(adjust_next && next->anon_vma &&
945                            anon_vma != next->anon_vma);
946                 anon_vma_lock_write(anon_vma);
947                 anon_vma_interval_tree_pre_update_vma(vma);
948                 if (adjust_next)
949                         anon_vma_interval_tree_pre_update_vma(next);
950         }
951
952         if (file) {
953                 flush_dcache_mmap_lock(mapping);
954                 vma_interval_tree_remove(vma, root);
955                 if (adjust_next)
956                         vma_interval_tree_remove(next, root);
957         }
958
959         if (start != vma->vm_start) {
960                 unsigned long old_start = vma->vm_start;
961                 vma->vm_start = start;
962                 if (old_start < start)
963                         vma_mas_szero(&mas, old_start, start);
964                 start_changed = true;
965         }
966         if (end != vma->vm_end) {
967                 unsigned long old_end = vma->vm_end;
968                 vma->vm_end = end;
969                 if (old_end > end)
970                         vma_mas_szero(&mas, end, old_end);
971                 end_changed = true;
972         }
973
974         if (end_changed || start_changed)
975                 vma_mas_store(vma, &mas);
976
977         vma->vm_pgoff = pgoff;
978         if (adjust_next) {
979                 next->vm_start += adjust_next;
980                 next->vm_pgoff += adjust_next >> PAGE_SHIFT;
981                 vma_mas_store(next, &mas);
982         }
983
984         if (file) {
985                 if (adjust_next)
986                         vma_interval_tree_insert(next, root);
987                 vma_interval_tree_insert(vma, root);
988                 flush_dcache_mmap_unlock(mapping);
989         }
990
991         if (remove_next) {
992                 /*
993                  * vma_merge has merged next into vma, and needs
994                  * us to remove next before dropping the locks.
995                  * Since we have expanded over this vma, the maple tree will
996                  * have overwritten by storing the value
997                  */
998                 if (remove_next != 3) {
999                         __vma_unlink(mm, next, next);
1000                         if (remove_next == 2)
1001                                 __vma_unlink(mm, next_next, next_next);
1002                 } else {
1003                         /*
1004                          * vma is not before next if they've been
1005                          * swapped.
1006                          *
1007                          * pre-swap() next->vm_start was reduced so
1008                          * tell validate_mm_rb to ignore pre-swap()
1009                          * "next" (which is stored in post-swap()
1010                          * "vma").
1011                          */
1012                         __vma_unlink(mm, next, vma);
1013                 }
1014                 if (file) {
1015                         __remove_shared_vm_struct(next, file, mapping);
1016                         if (remove_next == 2)
1017                                 __remove_shared_vm_struct(next_next, file, mapping);
1018                 }
1019         } else if (insert) {
1020                 /*
1021                  * split_vma has split insert from vma, and needs
1022                  * us to insert it before dropping the locks
1023                  * (it may either follow vma or precede it).
1024                  */
1025                 __insert_vm_struct(mm, &mas, insert);
1026         } else {
1027                 if (start_changed)
1028                         vma_gap_update(vma);
1029                 if (end_changed) {
1030                         if (!next)
1031                                 mm->highest_vm_end = vm_end_gap(vma);
1032                         else if (!adjust_next)
1033                                 vma_gap_update(next);
1034                 }
1035         }
1036
1037         if (anon_vma) {
1038                 anon_vma_interval_tree_post_update_vma(vma);
1039                 if (adjust_next)
1040                         anon_vma_interval_tree_post_update_vma(next);
1041                 anon_vma_unlock_write(anon_vma);
1042         }
1043
1044         if (file) {
1045                 i_mmap_unlock_write(mapping);
1046                 uprobe_mmap(vma);
1047
1048                 if (adjust_next)
1049                         uprobe_mmap(next);
1050         }
1051
1052         if (remove_next) {
1053 again:
1054                 if (file) {
1055                         uprobe_munmap(next, next->vm_start, next->vm_end);
1056                         fput(file);
1057                 }
1058                 if (next->anon_vma)
1059                         anon_vma_merge(vma, next);
1060                 mm->map_count--;
1061                 mpol_put(vma_policy(next));
1062                 vm_area_free(next);
1063                 /*
1064                  * In mprotect's case 6 (see comments on vma_merge),
1065                  * we must remove another next too. It would clutter
1066                  * up the code too much to do both in one go.
1067                  */
1068                 if (remove_next != 3) {
1069                         /*
1070                          * If "next" was removed and vma->vm_end was
1071                          * expanded (up) over it, in turn
1072                          * "next->vm_prev->vm_end" changed and the
1073                          * "vma->vm_next" gap must be updated.
1074                          */
1075                         next = next_next;
1076                 } else {
1077                         /*
1078                          * For the scope of the comment "next" and
1079                          * "vma" considered pre-swap(): if "vma" was
1080                          * removed, next->vm_start was expanded (down)
1081                          * over it and the "next" gap must be updated.
1082                          * Because of the swap() the post-swap() "vma"
1083                          * actually points to pre-swap() "next"
1084                          * (post-swap() "next" as opposed is now a
1085                          * dangling pointer).
1086                          */
1087                         next = vma;
1088                 }
1089                 if (remove_next == 2) {
1090                         remove_next = 1;
1091                         goto again;
1092                 }
1093                 else if (next)
1094                         vma_gap_update(next);
1095                 else {
1096                         /*
1097                          * If remove_next == 2 we obviously can't
1098                          * reach this path.
1099                          *
1100                          * If remove_next == 3 we can't reach this
1101                          * path because pre-swap() next is always not
1102                          * NULL. pre-swap() "next" is not being
1103                          * removed and its next->vm_end is not altered
1104                          * (and furthermore "end" already matches
1105                          * next->vm_end in remove_next == 3).
1106                          *
1107                          * We reach this only in the remove_next == 1
1108                          * case if the "next" vma that was removed was
1109                          * the highest vma of the mm. However in such
1110                          * case next->vm_end == "end" and the extended
1111                          * "vma" has vma->vm_end == next->vm_end so
1112                          * mm->highest_vm_end doesn't need any update
1113                          * in remove_next == 1 case.
1114                          */
1115                         VM_WARN_ON(mm->highest_vm_end != vm_end_gap(vma));
1116                 }
1117         }
1118         if (insert && file)
1119                 uprobe_mmap(insert);
1120
1121         validate_mm(mm);
1122         validate_mm_mt(mm);
1123
1124         return 0;
1125 }
1126
1127 /*
1128  * If the vma has a ->close operation then the driver probably needs to release
1129  * per-vma resources, so we don't attempt to merge those.
1130  */
1131 static inline int is_mergeable_vma(struct vm_area_struct *vma,
1132                                 struct file *file, unsigned long vm_flags,
1133                                 struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1134                                 struct anon_vma_name *anon_name)
1135 {
1136         /*
1137          * VM_SOFTDIRTY should not prevent from VMA merging, if we
1138          * match the flags but dirty bit -- the caller should mark
1139          * merged VMA as dirty. If dirty bit won't be excluded from
1140          * comparison, we increase pressure on the memory system forcing
1141          * the kernel to generate new VMAs when old one could be
1142          * extended instead.
1143          */
1144         if ((vma->vm_flags ^ vm_flags) & ~VM_SOFTDIRTY)
1145                 return 0;
1146         if (vma->vm_file != file)
1147                 return 0;
1148         if (vma->vm_ops && vma->vm_ops->close)
1149                 return 0;
1150         if (!is_mergeable_vm_userfaultfd_ctx(vma, vm_userfaultfd_ctx))
1151                 return 0;
1152         if (!anon_vma_name_eq(anon_vma_name(vma), anon_name))
1153                 return 0;
1154         return 1;
1155 }
1156
1157 static inline int is_mergeable_anon_vma(struct anon_vma *anon_vma1,
1158                                         struct anon_vma *anon_vma2,
1159                                         struct vm_area_struct *vma)
1160 {
1161         /*
1162          * The list_is_singular() test is to avoid merging VMA cloned from
1163          * parents. This can improve scalability caused by anon_vma lock.
1164          */
1165         if ((!anon_vma1 || !anon_vma2) && (!vma ||
1166                 list_is_singular(&vma->anon_vma_chain)))
1167                 return 1;
1168         return anon_vma1 == anon_vma2;
1169 }
1170
1171 /*
1172  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1173  * in front of (at a lower virtual address and file offset than) the vma.
1174  *
1175  * We cannot merge two vmas if they have differently assigned (non-NULL)
1176  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1177  *
1178  * We don't check here for the merged mmap wrapping around the end of pagecache
1179  * indices (16TB on ia32) because do_mmap() does not permit mmap's which
1180  * wrap, nor mmaps which cover the final page at index -1UL.
1181  */
1182 static int
1183 can_vma_merge_before(struct vm_area_struct *vma, unsigned long vm_flags,
1184                      struct anon_vma *anon_vma, struct file *file,
1185                      pgoff_t vm_pgoff,
1186                      struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1187                      struct anon_vma_name *anon_name)
1188 {
1189         if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1190             is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1191                 if (vma->vm_pgoff == vm_pgoff)
1192                         return 1;
1193         }
1194         return 0;
1195 }
1196
1197 /*
1198  * Return true if we can merge this (vm_flags,anon_vma,file,vm_pgoff)
1199  * beyond (at a higher virtual address and file offset than) the vma.
1200  *
1201  * We cannot merge two vmas if they have differently assigned (non-NULL)
1202  * anon_vmas, nor if same anon_vma is assigned but offsets incompatible.
1203  */
1204 static int
1205 can_vma_merge_after(struct vm_area_struct *vma, unsigned long vm_flags,
1206                     struct anon_vma *anon_vma, struct file *file,
1207                     pgoff_t vm_pgoff,
1208                     struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1209                     struct anon_vma_name *anon_name)
1210 {
1211         if (is_mergeable_vma(vma, file, vm_flags, vm_userfaultfd_ctx, anon_name) &&
1212             is_mergeable_anon_vma(anon_vma, vma->anon_vma, vma)) {
1213                 pgoff_t vm_pglen;
1214                 vm_pglen = vma_pages(vma);
1215                 if (vma->vm_pgoff + vm_pglen == vm_pgoff)
1216                         return 1;
1217         }
1218         return 0;
1219 }
1220
1221 /*
1222  * Given a mapping request (addr,end,vm_flags,file,pgoff,anon_name),
1223  * figure out whether that can be merged with its predecessor or its
1224  * successor.  Or both (it neatly fills a hole).
1225  *
1226  * In most cases - when called for mmap, brk or mremap - [addr,end) is
1227  * certain not to be mapped by the time vma_merge is called; but when
1228  * called for mprotect, it is certain to be already mapped (either at
1229  * an offset within prev, or at the start of next), and the flags of
1230  * this area are about to be changed to vm_flags - and the no-change
1231  * case has already been eliminated.
1232  *
1233  * The following mprotect cases have to be considered, where AAAA is
1234  * the area passed down from mprotect_fixup, never extending beyond one
1235  * vma, PPPPPP is the prev vma specified, and NNNNNN the next vma after:
1236  *
1237  *     AAAA             AAAA                   AAAA
1238  *    PPPPPPNNNNNN    PPPPPPNNNNNN       PPPPPPNNNNNN
1239  *    cannot merge    might become       might become
1240  *                    PPNNNNNNNNNN       PPPPPPPPPPNN
1241  *    mmap, brk or    case 4 below       case 5 below
1242  *    mremap move:
1243  *                        AAAA               AAAA
1244  *                    PPPP    NNNN       PPPPNNNNXXXX
1245  *                    might become       might become
1246  *                    PPPPPPPPPPPP 1 or  PPPPPPPPPPPP 6 or
1247  *                    PPPPPPPPNNNN 2 or  PPPPPPPPXXXX 7 or
1248  *                    PPPPNNNNNNNN 3     PPPPXXXXXXXX 8
1249  *
1250  * It is important for case 8 that the vma NNNN overlapping the
1251  * region AAAA is never going to extended over XXXX. Instead XXXX must
1252  * be extended in region AAAA and NNNN must be removed. This way in
1253  * all cases where vma_merge succeeds, the moment vma_adjust drops the
1254  * rmap_locks, the properties of the merged vma will be already
1255  * correct for the whole merged range. Some of those properties like
1256  * vm_page_prot/vm_flags may be accessed by rmap_walks and they must
1257  * be correct for the whole merged range immediately after the
1258  * rmap_locks are released. Otherwise if XXXX would be removed and
1259  * NNNN would be extended over the XXXX range, remove_migration_ptes
1260  * or other rmap walkers (if working on addresses beyond the "end"
1261  * parameter) may establish ptes with the wrong permissions of NNNN
1262  * instead of the right permissions of XXXX.
1263  */
1264 struct vm_area_struct *vma_merge(struct mm_struct *mm,
1265                         struct vm_area_struct *prev, unsigned long addr,
1266                         unsigned long end, unsigned long vm_flags,
1267                         struct anon_vma *anon_vma, struct file *file,
1268                         pgoff_t pgoff, struct mempolicy *policy,
1269                         struct vm_userfaultfd_ctx vm_userfaultfd_ctx,
1270                         struct anon_vma_name *anon_name)
1271 {
1272         pgoff_t pglen = (end - addr) >> PAGE_SHIFT;
1273         struct vm_area_struct *area, *next;
1274         int err;
1275
1276         validate_mm_mt(mm);
1277         /*
1278          * We later require that vma->vm_flags == vm_flags,
1279          * so this tests vma->vm_flags & VM_SPECIAL, too.
1280          */
1281         if (vm_flags & VM_SPECIAL)
1282                 return NULL;
1283
1284         next = __vma_next(mm, prev);
1285         area = next;
1286         if (area && area->vm_end == end)                /* cases 6, 7, 8 */
1287                 next = next->vm_next;
1288
1289         /* verify some invariant that must be enforced by the caller */
1290         VM_WARN_ON(prev && addr <= prev->vm_start);
1291         VM_WARN_ON(area && end > area->vm_end);
1292         VM_WARN_ON(addr >= end);
1293
1294         /*
1295          * Can it merge with the predecessor?
1296          */
1297         if (prev && prev->vm_end == addr &&
1298                         mpol_equal(vma_policy(prev), policy) &&
1299                         can_vma_merge_after(prev, vm_flags,
1300                                             anon_vma, file, pgoff,
1301                                             vm_userfaultfd_ctx, anon_name)) {
1302                 /*
1303                  * OK, it can.  Can we now merge in the successor as well?
1304                  */
1305                 if (next && end == next->vm_start &&
1306                                 mpol_equal(policy, vma_policy(next)) &&
1307                                 can_vma_merge_before(next, vm_flags,
1308                                                      anon_vma, file,
1309                                                      pgoff+pglen,
1310                                                      vm_userfaultfd_ctx, anon_name) &&
1311                                 is_mergeable_anon_vma(prev->anon_vma,
1312                                                       next->anon_vma, NULL)) {
1313                                                         /* cases 1, 6 */
1314                         err = __vma_adjust(prev, prev->vm_start,
1315                                          next->vm_end, prev->vm_pgoff, NULL,
1316                                          prev);
1317                 } else                                  /* cases 2, 5, 7 */
1318                         err = __vma_adjust(prev, prev->vm_start,
1319                                          end, prev->vm_pgoff, NULL, prev);
1320                 if (err)
1321                         return NULL;
1322                 khugepaged_enter_vma(prev, vm_flags);
1323                 return prev;
1324         }
1325
1326         /*
1327          * Can this new request be merged in front of next?
1328          */
1329         if (next && end == next->vm_start &&
1330                         mpol_equal(policy, vma_policy(next)) &&
1331                         can_vma_merge_before(next, vm_flags,
1332                                              anon_vma, file, pgoff+pglen,
1333                                              vm_userfaultfd_ctx, anon_name)) {
1334                 if (prev && addr < prev->vm_end)        /* case 4 */
1335                         err = __vma_adjust(prev, prev->vm_start,
1336                                          addr, prev->vm_pgoff, NULL, next);
1337                 else {                                  /* cases 3, 8 */
1338                         err = __vma_adjust(area, addr, next->vm_end,
1339                                          next->vm_pgoff - pglen, NULL, next);
1340                         /*
1341                          * In case 3 area is already equal to next and
1342                          * this is a noop, but in case 8 "area" has
1343                          * been removed and next was expanded over it.
1344                          */
1345                         area = next;
1346                 }
1347                 if (err)
1348                         return NULL;
1349                 khugepaged_enter_vma(area, vm_flags);
1350                 return area;
1351         }
1352         validate_mm_mt(mm);
1353
1354         return NULL;
1355 }
1356
1357 /*
1358  * Rough compatibility check to quickly see if it's even worth looking
1359  * at sharing an anon_vma.
1360  *
1361  * They need to have the same vm_file, and the flags can only differ
1362  * in things that mprotect may change.
1363  *
1364  * NOTE! The fact that we share an anon_vma doesn't _have_ to mean that
1365  * we can merge the two vma's. For example, we refuse to merge a vma if
1366  * there is a vm_ops->close() function, because that indicates that the
1367  * driver is doing some kind of reference counting. But that doesn't
1368  * really matter for the anon_vma sharing case.
1369  */
1370 static int anon_vma_compatible(struct vm_area_struct *a, struct vm_area_struct *b)
1371 {
1372         return a->vm_end == b->vm_start &&
1373                 mpol_equal(vma_policy(a), vma_policy(b)) &&
1374                 a->vm_file == b->vm_file &&
1375                 !((a->vm_flags ^ b->vm_flags) & ~(VM_ACCESS_FLAGS | VM_SOFTDIRTY)) &&
1376                 b->vm_pgoff == a->vm_pgoff + ((b->vm_start - a->vm_start) >> PAGE_SHIFT);
1377 }
1378
1379 /*
1380  * Do some basic sanity checking to see if we can re-use the anon_vma
1381  * from 'old'. The 'a'/'b' vma's are in VM order - one of them will be
1382  * the same as 'old', the other will be the new one that is trying
1383  * to share the anon_vma.
1384  *
1385  * NOTE! This runs with mmap_lock held for reading, so it is possible that
1386  * the anon_vma of 'old' is concurrently in the process of being set up
1387  * by another page fault trying to merge _that_. But that's ok: if it
1388  * is being set up, that automatically means that it will be a singleton
1389  * acceptable for merging, so we can do all of this optimistically. But
1390  * we do that READ_ONCE() to make sure that we never re-load the pointer.
1391  *
1392  * IOW: that the "list_is_singular()" test on the anon_vma_chain only
1393  * matters for the 'stable anon_vma' case (ie the thing we want to avoid
1394  * is to return an anon_vma that is "complex" due to having gone through
1395  * a fork).
1396  *
1397  * We also make sure that the two vma's are compatible (adjacent,
1398  * and with the same memory policies). That's all stable, even with just
1399  * a read lock on the mmap_lock.
1400  */
1401 static struct anon_vma *reusable_anon_vma(struct vm_area_struct *old, struct vm_area_struct *a, struct vm_area_struct *b)
1402 {
1403         if (anon_vma_compatible(a, b)) {
1404                 struct anon_vma *anon_vma = READ_ONCE(old->anon_vma);
1405
1406                 if (anon_vma && list_is_singular(&old->anon_vma_chain))
1407                         return anon_vma;
1408         }
1409         return NULL;
1410 }
1411
1412 /*
1413  * find_mergeable_anon_vma is used by anon_vma_prepare, to check
1414  * neighbouring vmas for a suitable anon_vma, before it goes off
1415  * to allocate a new anon_vma.  It checks because a repetitive
1416  * sequence of mprotects and faults may otherwise lead to distinct
1417  * anon_vmas being allocated, preventing vma merge in subsequent
1418  * mprotect.
1419  */
1420 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma)
1421 {
1422         struct anon_vma *anon_vma = NULL;
1423
1424         /* Try next first. */
1425         if (vma->vm_next) {
1426                 anon_vma = reusable_anon_vma(vma->vm_next, vma, vma->vm_next);
1427                 if (anon_vma)
1428                         return anon_vma;
1429         }
1430
1431         /* Try prev next. */
1432         if (vma->vm_prev)
1433                 anon_vma = reusable_anon_vma(vma->vm_prev, vma->vm_prev, vma);
1434
1435         /*
1436          * We might reach here with anon_vma == NULL if we can't find
1437          * any reusable anon_vma.
1438          * There's no absolute need to look only at touching neighbours:
1439          * we could search further afield for "compatible" anon_vmas.
1440          * But it would probably just be a waste of time searching,
1441          * or lead to too many vmas hanging off the same anon_vma.
1442          * We're trying to allow mprotect remerging later on,
1443          * not trying to minimize memory used for anon_vmas.
1444          */
1445         return anon_vma;
1446 }
1447
1448 /*
1449  * If a hint addr is less than mmap_min_addr change hint to be as
1450  * low as possible but still greater than mmap_min_addr
1451  */
1452 static inline unsigned long round_hint_to_min(unsigned long hint)
1453 {
1454         hint &= PAGE_MASK;
1455         if (((void *)hint != NULL) &&
1456             (hint < mmap_min_addr))
1457                 return PAGE_ALIGN(mmap_min_addr);
1458         return hint;
1459 }
1460
1461 int mlock_future_check(struct mm_struct *mm, unsigned long flags,
1462                        unsigned long len)
1463 {
1464         unsigned long locked, lock_limit;
1465
1466         /*  mlock MCL_FUTURE? */
1467         if (flags & VM_LOCKED) {
1468                 locked = len >> PAGE_SHIFT;
1469                 locked += mm->locked_vm;
1470                 lock_limit = rlimit(RLIMIT_MEMLOCK);
1471                 lock_limit >>= PAGE_SHIFT;
1472                 if (locked > lock_limit && !capable(CAP_IPC_LOCK))
1473                         return -EAGAIN;
1474         }
1475         return 0;
1476 }
1477
1478 static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
1479 {
1480         if (S_ISREG(inode->i_mode))
1481                 return MAX_LFS_FILESIZE;
1482
1483         if (S_ISBLK(inode->i_mode))
1484                 return MAX_LFS_FILESIZE;
1485
1486         if (S_ISSOCK(inode->i_mode))
1487                 return MAX_LFS_FILESIZE;
1488
1489         /* Special "we do even unsigned file positions" case */
1490         if (file->f_mode & FMODE_UNSIGNED_OFFSET)
1491                 return 0;
1492
1493         /* Yes, random drivers might want more. But I'm tired of buggy drivers */
1494         return ULONG_MAX;
1495 }
1496
1497 static inline bool file_mmap_ok(struct file *file, struct inode *inode,
1498                                 unsigned long pgoff, unsigned long len)
1499 {
1500         u64 maxsize = file_mmap_size_max(file, inode);
1501
1502         if (maxsize && len > maxsize)
1503                 return false;
1504         maxsize -= len;
1505         if (pgoff > maxsize >> PAGE_SHIFT)
1506                 return false;
1507         return true;
1508 }
1509
1510 /*
1511  * The caller must write-lock current->mm->mmap_lock.
1512  */
1513 unsigned long do_mmap(struct file *file, unsigned long addr,
1514                         unsigned long len, unsigned long prot,
1515                         unsigned long flags, unsigned long pgoff,
1516                         unsigned long *populate, struct list_head *uf)
1517 {
1518         struct mm_struct *mm = current->mm;
1519         vm_flags_t vm_flags;
1520         int pkey = 0;
1521
1522         *populate = 0;
1523
1524         if (!len)
1525                 return -EINVAL;
1526
1527         /*
1528          * Does the application expect PROT_READ to imply PROT_EXEC?
1529          *
1530          * (the exception is when the underlying filesystem is noexec
1531          *  mounted, in which case we dont add PROT_EXEC.)
1532          */
1533         if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
1534                 if (!(file && path_noexec(&file->f_path)))
1535                         prot |= PROT_EXEC;
1536
1537         /* force arch specific MAP_FIXED handling in get_unmapped_area */
1538         if (flags & MAP_FIXED_NOREPLACE)
1539                 flags |= MAP_FIXED;
1540
1541         if (!(flags & MAP_FIXED))
1542                 addr = round_hint_to_min(addr);
1543
1544         /* Careful about overflows.. */
1545         len = PAGE_ALIGN(len);
1546         if (!len)
1547                 return -ENOMEM;
1548
1549         /* offset overflow? */
1550         if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
1551                 return -EOVERFLOW;
1552
1553         /* Too many mappings? */
1554         if (mm->map_count > sysctl_max_map_count)
1555                 return -ENOMEM;
1556
1557         /* Obtain the address to map to. we verify (or select) it and ensure
1558          * that it represents a valid section of the address space.
1559          */
1560         addr = get_unmapped_area(file, addr, len, pgoff, flags);
1561         if (IS_ERR_VALUE(addr))
1562                 return addr;
1563
1564         if (flags & MAP_FIXED_NOREPLACE) {
1565                 if (find_vma_intersection(mm, addr, addr + len))
1566                         return -EEXIST;
1567         }
1568
1569         if (prot == PROT_EXEC) {
1570                 pkey = execute_only_pkey(mm);
1571                 if (pkey < 0)
1572                         pkey = 0;
1573         }
1574
1575         /* Do simple checking here so the lower-level routines won't have
1576          * to. we assume access permissions have been handled by the open
1577          * of the memory object, so we don't do any here.
1578          */
1579         vm_flags = calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(flags) |
1580                         mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
1581
1582         if (flags & MAP_LOCKED)
1583                 if (!can_do_mlock())
1584                         return -EPERM;
1585
1586         if (mlock_future_check(mm, vm_flags, len))
1587                 return -EAGAIN;
1588
1589         if (file) {
1590                 struct inode *inode = file_inode(file);
1591                 unsigned long flags_mask;
1592
1593                 if (!file_mmap_ok(file, inode, pgoff, len))
1594                         return -EOVERFLOW;
1595
1596                 flags_mask = LEGACY_MAP_MASK | file->f_op->mmap_supported_flags;
1597
1598                 switch (flags & MAP_TYPE) {
1599                 case MAP_SHARED:
1600                         /*
1601                          * Force use of MAP_SHARED_VALIDATE with non-legacy
1602                          * flags. E.g. MAP_SYNC is dangerous to use with
1603                          * MAP_SHARED as you don't know which consistency model
1604                          * you will get. We silently ignore unsupported flags
1605                          * with MAP_SHARED to preserve backward compatibility.
1606                          */
1607                         flags &= LEGACY_MAP_MASK;
1608                         fallthrough;
1609                 case MAP_SHARED_VALIDATE:
1610                         if (flags & ~flags_mask)
1611                                 return -EOPNOTSUPP;
1612                         if (prot & PROT_WRITE) {
1613                                 if (!(file->f_mode & FMODE_WRITE))
1614                                         return -EACCES;
1615                                 if (IS_SWAPFILE(file->f_mapping->host))
1616                                         return -ETXTBSY;
1617                         }
1618
1619                         /*
1620                          * Make sure we don't allow writing to an append-only
1621                          * file..
1622                          */
1623                         if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
1624                                 return -EACCES;
1625
1626                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1627                         if (!(file->f_mode & FMODE_WRITE))
1628                                 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
1629                         fallthrough;
1630                 case MAP_PRIVATE:
1631                         if (!(file->f_mode & FMODE_READ))
1632                                 return -EACCES;
1633                         if (path_noexec(&file->f_path)) {
1634                                 if (vm_flags & VM_EXEC)
1635                                         return -EPERM;
1636                                 vm_flags &= ~VM_MAYEXEC;
1637                         }
1638
1639                         if (!file->f_op->mmap)
1640                                 return -ENODEV;
1641                         if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1642                                 return -EINVAL;
1643                         break;
1644
1645                 default:
1646                         return -EINVAL;
1647                 }
1648         } else {
1649                 switch (flags & MAP_TYPE) {
1650                 case MAP_SHARED:
1651                         if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
1652                                 return -EINVAL;
1653                         /*
1654                          * Ignore pgoff.
1655                          */
1656                         pgoff = 0;
1657                         vm_flags |= VM_SHARED | VM_MAYSHARE;
1658                         break;
1659                 case MAP_PRIVATE:
1660                         /*
1661                          * Set pgoff according to addr for anon_vma.
1662                          */
1663                         pgoff = addr >> PAGE_SHIFT;
1664                         break;
1665                 default:
1666                         return -EINVAL;
1667                 }
1668         }
1669
1670         /*
1671          * Set 'VM_NORESERVE' if we should not account for the
1672          * memory use of this mapping.
1673          */
1674         if (flags & MAP_NORESERVE) {
1675                 /* We honor MAP_NORESERVE if allowed to overcommit */
1676                 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
1677                         vm_flags |= VM_NORESERVE;
1678
1679                 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
1680                 if (file && is_file_hugepages(file))
1681                         vm_flags |= VM_NORESERVE;
1682         }
1683
1684         addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
1685         if (!IS_ERR_VALUE(addr) &&
1686             ((vm_flags & VM_LOCKED) ||
1687              (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
1688                 *populate = len;
1689         return addr;
1690 }
1691
1692 unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
1693                               unsigned long prot, unsigned long flags,
1694                               unsigned long fd, unsigned long pgoff)
1695 {
1696         struct file *file = NULL;
1697         unsigned long retval;
1698
1699         if (!(flags & MAP_ANONYMOUS)) {
1700                 audit_mmap_fd(fd, flags);
1701                 file = fget(fd);
1702                 if (!file)
1703                         return -EBADF;
1704                 if (is_file_hugepages(file)) {
1705                         len = ALIGN(len, huge_page_size(hstate_file(file)));
1706                 } else if (unlikely(flags & MAP_HUGETLB)) {
1707                         retval = -EINVAL;
1708                         goto out_fput;
1709                 }
1710         } else if (flags & MAP_HUGETLB) {
1711                 struct hstate *hs;
1712
1713                 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1714                 if (!hs)
1715                         return -EINVAL;
1716
1717                 len = ALIGN(len, huge_page_size(hs));
1718                 /*
1719                  * VM_NORESERVE is used because the reservations will be
1720                  * taken when vm_ops->mmap() is called
1721                  */
1722                 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1723                                 VM_NORESERVE,
1724                                 HUGETLB_ANONHUGE_INODE,
1725                                 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1726                 if (IS_ERR(file))
1727                         return PTR_ERR(file);
1728         }
1729
1730         retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1731 out_fput:
1732         if (file)
1733                 fput(file);
1734         return retval;
1735 }
1736
1737 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1738                 unsigned long, prot, unsigned long, flags,
1739                 unsigned long, fd, unsigned long, pgoff)
1740 {
1741         return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1742 }
1743
1744 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1745 struct mmap_arg_struct {
1746         unsigned long addr;
1747         unsigned long len;
1748         unsigned long prot;
1749         unsigned long flags;
1750         unsigned long fd;
1751         unsigned long offset;
1752 };
1753
1754 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1755 {
1756         struct mmap_arg_struct a;
1757
1758         if (copy_from_user(&a, arg, sizeof(a)))
1759                 return -EFAULT;
1760         if (offset_in_page(a.offset))
1761                 return -EINVAL;
1762
1763         return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1764                                a.offset >> PAGE_SHIFT);
1765 }
1766 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1767
1768 /*
1769  * Some shared mappings will want the pages marked read-only
1770  * to track write events. If so, we'll downgrade vm_page_prot
1771  * to the private version (using protection_map[] without the
1772  * VM_SHARED bit).
1773  */
1774 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1775 {
1776         vm_flags_t vm_flags = vma->vm_flags;
1777         const struct vm_operations_struct *vm_ops = vma->vm_ops;
1778
1779         /* If it was private or non-writable, the write bit is already clear */
1780         if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1781                 return 0;
1782
1783         /* The backer wishes to know when pages are first written to? */
1784         if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1785                 return 1;
1786
1787         /* The open routine did something to the protections that pgprot_modify
1788          * won't preserve? */
1789         if (pgprot_val(vm_page_prot) !=
1790             pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1791                 return 0;
1792
1793         /*
1794          * Do we need to track softdirty? hugetlb does not support softdirty
1795          * tracking yet.
1796          */
1797         if (vma_soft_dirty_enabled(vma) && !is_vm_hugetlb_page(vma))
1798                 return 1;
1799
1800         /* Specialty mapping? */
1801         if (vm_flags & VM_PFNMAP)
1802                 return 0;
1803
1804         /* Can the mapping track the dirty pages? */
1805         return vma->vm_file && vma->vm_file->f_mapping &&
1806                 mapping_can_writeback(vma->vm_file->f_mapping);
1807 }
1808
1809 /*
1810  * We account for memory if it's a private writeable mapping,
1811  * not hugepages and VM_NORESERVE wasn't set.
1812  */
1813 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1814 {
1815         /*
1816          * hugetlb has its own accounting separate from the core VM
1817          * VM_HUGETLB may not be set yet so we cannot check for that flag.
1818          */
1819         if (file && is_file_hugepages(file))
1820                 return 0;
1821
1822         return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1823 }
1824
1825 unsigned long mmap_region(struct file *file, unsigned long addr,
1826                 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
1827                 struct list_head *uf)
1828 {
1829         struct mm_struct *mm = current->mm;
1830         struct vm_area_struct *vma, *prev, *merge;
1831         int error;
1832         struct rb_node **rb_link, *rb_parent;
1833         unsigned long charged = 0;
1834
1835         validate_mm_mt(mm);
1836         /* Check against address space limit. */
1837         if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
1838                 unsigned long nr_pages;
1839
1840                 /*
1841                  * MAP_FIXED may remove pages of mappings that intersects with
1842                  * requested mapping. Account for the pages it would unmap.
1843                  */
1844                 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1845
1846                 if (!may_expand_vm(mm, vm_flags,
1847                                         (len >> PAGE_SHIFT) - nr_pages))
1848                         return -ENOMEM;
1849         }
1850
1851         /* Clear old maps, set up prev, rb_link, rb_parent, and uf */
1852         if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
1853                 return -ENOMEM;
1854         /*
1855          * Private writable mapping: check memory availability
1856          */
1857         if (accountable_mapping(file, vm_flags)) {
1858                 charged = len >> PAGE_SHIFT;
1859                 if (security_vm_enough_memory_mm(mm, charged))
1860                         return -ENOMEM;
1861                 vm_flags |= VM_ACCOUNT;
1862         }
1863
1864         /*
1865          * Can we just expand an old mapping?
1866          */
1867         vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
1868                         NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1869         if (vma)
1870                 goto out;
1871
1872         /*
1873          * Determine the object being mapped and call the appropriate
1874          * specific mapper. the address has already been validated, but
1875          * not unmapped, but the maps are removed from the list.
1876          */
1877         vma = vm_area_alloc(mm);
1878         if (!vma) {
1879                 error = -ENOMEM;
1880                 goto unacct_error;
1881         }
1882
1883         vma->vm_start = addr;
1884         vma->vm_end = addr + len;
1885         vma->vm_flags = vm_flags;
1886         vma->vm_page_prot = vm_get_page_prot(vm_flags);
1887         vma->vm_pgoff = pgoff;
1888
1889         if (file) {
1890                 if (vm_flags & VM_SHARED) {
1891                         error = mapping_map_writable(file->f_mapping);
1892                         if (error)
1893                                 goto free_vma;
1894                 }
1895
1896                 vma->vm_file = get_file(file);
1897                 error = call_mmap(file, vma);
1898                 if (error)
1899                         goto unmap_and_free_vma;
1900
1901                 /* Can addr have changed??
1902                  *
1903                  * Answer: Yes, several device drivers can do it in their
1904                  *         f_op->mmap method. -DaveM
1905                  * Bug: If addr is changed, prev, rb_link, rb_parent should
1906                  *      be updated for vma_link()
1907                  */
1908                 WARN_ON_ONCE(addr != vma->vm_start);
1909
1910                 addr = vma->vm_start;
1911
1912                 /* If vm_flags changed after call_mmap(), we should try merge vma again
1913                  * as we may succeed this time.
1914                  */
1915                 if (unlikely(vm_flags != vma->vm_flags && prev)) {
1916                         merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
1917                                 NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
1918                         if (merge) {
1919                                 /* ->mmap() can change vma->vm_file and fput the original file. So
1920                                  * fput the vma->vm_file here or we would add an extra fput for file
1921                                  * and cause general protection fault ultimately.
1922                                  */
1923                                 fput(vma->vm_file);
1924                                 vm_area_free(vma);
1925                                 vma = merge;
1926                                 /* Update vm_flags to pick up the change. */
1927                                 vm_flags = vma->vm_flags;
1928                                 goto unmap_writable;
1929                         }
1930                 }
1931
1932                 vm_flags = vma->vm_flags;
1933         } else if (vm_flags & VM_SHARED) {
1934                 error = shmem_zero_setup(vma);
1935                 if (error)
1936                         goto free_vma;
1937         } else {
1938                 vma_set_anonymous(vma);
1939         }
1940
1941         /* Allow architectures to sanity-check the vm_flags */
1942         if (!arch_validate_flags(vma->vm_flags)) {
1943                 error = -EINVAL;
1944                 if (file)
1945                         goto unmap_and_free_vma;
1946                 else
1947                         goto free_vma;
1948         }
1949
1950         if (vma_link(mm, vma, prev, rb_link, rb_parent)) {
1951                 error = -ENOMEM;
1952                 if (file)
1953                         goto unmap_and_free_vma;
1954                 else
1955                         goto free_vma;
1956         }
1957
1958         /*
1959          * vma_merge() calls khugepaged_enter_vma() either, the below
1960          * call covers the non-merge case.
1961          */
1962         khugepaged_enter_vma(vma, vma->vm_flags);
1963
1964         /* Once vma denies write, undo our temporary denial count */
1965 unmap_writable:
1966         if (file && vm_flags & VM_SHARED)
1967                 mapping_unmap_writable(file->f_mapping);
1968         file = vma->vm_file;
1969 out:
1970         perf_event_mmap(vma);
1971
1972         vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
1973         if (vm_flags & VM_LOCKED) {
1974                 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
1975                                         is_vm_hugetlb_page(vma) ||
1976                                         vma == get_gate_vma(current->mm))
1977                         vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1978                 else
1979                         mm->locked_vm += (len >> PAGE_SHIFT);
1980         }
1981
1982         if (file)
1983                 uprobe_mmap(vma);
1984
1985         /*
1986          * New (or expanded) vma always get soft dirty status.
1987          * Otherwise user-space soft-dirty page tracker won't
1988          * be able to distinguish situation when vma area unmapped,
1989          * then new mapped in-place (which must be aimed as
1990          * a completely new data area).
1991          */
1992         vma->vm_flags |= VM_SOFTDIRTY;
1993
1994         vma_set_page_prot(vma);
1995
1996         validate_mm_mt(mm);
1997         return addr;
1998
1999 unmap_and_free_vma:
2000         fput(vma->vm_file);
2001         vma->vm_file = NULL;
2002
2003         /* Undo any partial mapping done by a device driver. */
2004         unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
2005         if (vm_flags & VM_SHARED)
2006                 mapping_unmap_writable(file->f_mapping);
2007 free_vma:
2008         vm_area_free(vma);
2009 unacct_error:
2010         if (charged)
2011                 vm_unacct_memory(charged);
2012         validate_mm_mt(mm);
2013         return error;
2014 }
2015
2016 /**
2017  * unmapped_area() - Find an area between the low_limit and the high_limit with
2018  * the correct alignment and offset, all from @info. Note: current->mm is used
2019  * for the search.
2020  *
2021  * @info: The unmapped area information including the range (low_limit -
2022  * hight_limit), the alignment offset and mask.
2023  *
2024  * Return: A memory address or -ENOMEM.
2025  */
2026 static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
2027 {
2028         unsigned long length, gap;
2029
2030         MA_STATE(mas, &current->mm->mm_mt, 0, 0);
2031
2032         /* Adjust search length to account for worst case alignment overhead */
2033         length = info->length + info->align_mask;
2034         if (length < info->length)
2035                 return -ENOMEM;
2036
2037         if (mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
2038                                   length))
2039                 return -ENOMEM;
2040
2041         gap = mas.index;
2042         gap += (info->align_offset - gap) & info->align_mask;
2043         return gap;
2044 }
2045
2046 /**
2047  * unmapped_area_topdown() - Find an area between the low_limit and the
2048  * high_limit with * the correct alignment and offset at the highest available
2049  * address, all from @info. Note: current->mm is used for the search.
2050  *
2051  * @info: The unmapped area information including the range (low_limit -
2052  * hight_limit), the alignment offset and mask.
2053  *
2054  * Return: A memory address or -ENOMEM.
2055  */
2056 static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
2057 {
2058         unsigned long length, gap;
2059
2060         MA_STATE(mas, &current->mm->mm_mt, 0, 0);
2061         /* Adjust search length to account for worst case alignment overhead */
2062         length = info->length + info->align_mask;
2063         if (length < info->length)
2064                 return -ENOMEM;
2065
2066         if (mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
2067                                 length))
2068                 return -ENOMEM;
2069
2070         gap = mas.last + 1 - info->length;
2071         gap -= (gap - info->align_offset) & info->align_mask;
2072         return gap;
2073 }
2074
2075 /*
2076  * Search for an unmapped address range.
2077  *
2078  * We are looking for a range that:
2079  * - does not intersect with any VMA;
2080  * - is contained within the [low_limit, high_limit) interval;
2081  * - is at least the desired size.
2082  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
2083  */
2084 unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
2085 {
2086         unsigned long addr;
2087
2088         if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
2089                 addr = unmapped_area_topdown(info);
2090         else
2091                 addr = unmapped_area(info);
2092
2093         trace_vm_unmapped_area(addr, info);
2094         return addr;
2095 }
2096
2097 /* Get an address range which is currently unmapped.
2098  * For shmat() with addr=0.
2099  *
2100  * Ugly calling convention alert:
2101  * Return value with the low bits set means error value,
2102  * ie
2103  *      if (ret & ~PAGE_MASK)
2104  *              error = ret;
2105  *
2106  * This function "knows" that -ENOMEM has the bits set.
2107  */
2108 unsigned long
2109 generic_get_unmapped_area(struct file *filp, unsigned long addr,
2110                           unsigned long len, unsigned long pgoff,
2111                           unsigned long flags)
2112 {
2113         struct mm_struct *mm = current->mm;
2114         struct vm_area_struct *vma, *prev;
2115         struct vm_unmapped_area_info info;
2116         const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
2117
2118         if (len > mmap_end - mmap_min_addr)
2119                 return -ENOMEM;
2120
2121         if (flags & MAP_FIXED)
2122                 return addr;
2123
2124         if (addr) {
2125                 addr = PAGE_ALIGN(addr);
2126                 vma = find_vma_prev(mm, addr, &prev);
2127                 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2128                     (!vma || addr + len <= vm_start_gap(vma)) &&
2129                     (!prev || addr >= vm_end_gap(prev)))
2130                         return addr;
2131         }
2132
2133         info.flags = 0;
2134         info.length = len;
2135         info.low_limit = mm->mmap_base;
2136         info.high_limit = mmap_end;
2137         info.align_mask = 0;
2138         info.align_offset = 0;
2139         return vm_unmapped_area(&info);
2140 }
2141
2142 #ifndef HAVE_ARCH_UNMAPPED_AREA
2143 unsigned long
2144 arch_get_unmapped_area(struct file *filp, unsigned long addr,
2145                        unsigned long len, unsigned long pgoff,
2146                        unsigned long flags)
2147 {
2148         return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
2149 }
2150 #endif
2151
2152 /*
2153  * This mmap-allocator allocates new areas top-down from below the
2154  * stack's low limit (the base):
2155  */
2156 unsigned long
2157 generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2158                                   unsigned long len, unsigned long pgoff,
2159                                   unsigned long flags)
2160 {
2161         struct vm_area_struct *vma, *prev;
2162         struct mm_struct *mm = current->mm;
2163         struct vm_unmapped_area_info info;
2164         const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
2165
2166         /* requested length too big for entire address space */
2167         if (len > mmap_end - mmap_min_addr)
2168                 return -ENOMEM;
2169
2170         if (flags & MAP_FIXED)
2171                 return addr;
2172
2173         /* requesting a specific address */
2174         if (addr) {
2175                 addr = PAGE_ALIGN(addr);
2176                 vma = find_vma_prev(mm, addr, &prev);
2177                 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2178                                 (!vma || addr + len <= vm_start_gap(vma)) &&
2179                                 (!prev || addr >= vm_end_gap(prev)))
2180                         return addr;
2181         }
2182
2183         info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2184         info.length = len;
2185         info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2186         info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
2187         info.align_mask = 0;
2188         info.align_offset = 0;
2189         addr = vm_unmapped_area(&info);
2190
2191         /*
2192          * A failed mmap() very likely causes application failure,
2193          * so fall back to the bottom-up function here. This scenario
2194          * can happen with large stack limits and large mmap()
2195          * allocations.
2196          */
2197         if (offset_in_page(addr)) {
2198                 VM_BUG_ON(addr != -ENOMEM);
2199                 info.flags = 0;
2200                 info.low_limit = TASK_UNMAPPED_BASE;
2201                 info.high_limit = mmap_end;
2202                 addr = vm_unmapped_area(&info);
2203         }
2204
2205         return addr;
2206 }
2207
2208 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
2209 unsigned long
2210 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2211                                unsigned long len, unsigned long pgoff,
2212                                unsigned long flags)
2213 {
2214         return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
2215 }
2216 #endif
2217
2218 unsigned long
2219 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
2220                 unsigned long pgoff, unsigned long flags)
2221 {
2222         unsigned long (*get_area)(struct file *, unsigned long,
2223                                   unsigned long, unsigned long, unsigned long);
2224
2225         unsigned long error = arch_mmap_check(addr, len, flags);
2226         if (error)
2227                 return error;
2228
2229         /* Careful about overflows.. */
2230         if (len > TASK_SIZE)
2231                 return -ENOMEM;
2232
2233         get_area = current->mm->get_unmapped_area;
2234         if (file) {
2235                 if (file->f_op->get_unmapped_area)
2236                         get_area = file->f_op->get_unmapped_area;
2237         } else if (flags & MAP_SHARED) {
2238                 /*
2239                  * mmap_region() will call shmem_zero_setup() to create a file,
2240                  * so use shmem's get_unmapped_area in case it can be huge.
2241                  * do_mmap() will clear pgoff, so match alignment.
2242                  */
2243                 pgoff = 0;
2244                 get_area = shmem_get_unmapped_area;
2245         } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
2246                 /* Ensures that larger anonymous mappings are THP aligned. */
2247                 get_area = thp_get_unmapped_area;
2248         }
2249
2250         addr = get_area(file, addr, len, pgoff, flags);
2251         if (IS_ERR_VALUE(addr))
2252                 return addr;
2253
2254         if (addr > TASK_SIZE - len)
2255                 return -ENOMEM;
2256         if (offset_in_page(addr))
2257                 return -EINVAL;
2258
2259         error = security_mmap_addr(addr);
2260         return error ? error : addr;
2261 }
2262
2263 EXPORT_SYMBOL(get_unmapped_area);
2264
2265 /**
2266  * find_vma() - Find the VMA for a given address, or the next VMA.
2267  * @mm: The mm_struct to check
2268  * @addr: The address
2269  *
2270  * Returns: The VMA associated with addr, or the next VMA.
2271  * May return %NULL in the case of no VMA at addr or above.
2272  */
2273 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2274 {
2275         struct vm_area_struct *vma;
2276         unsigned long index = addr;
2277
2278         mmap_assert_locked(mm);
2279         /* Check the cache first. */
2280         vma = vmacache_find(mm, addr);
2281         if (likely(vma))
2282                 return vma;
2283
2284         vma = mt_find(&mm->mm_mt, &index, ULONG_MAX);
2285         if (vma)
2286                 vmacache_update(addr, vma);
2287         return vma;
2288 }
2289 EXPORT_SYMBOL(find_vma);
2290
2291 /**
2292  * find_vma_prev() - Find the VMA for a given address, or the next vma and
2293  * set %pprev to the previous VMA, if any.
2294  * @mm: The mm_struct to check
2295  * @addr: The address
2296  * @pprev: The pointer to set to the previous VMA
2297  *
2298  * Note that RCU lock is missing here since the external mmap_lock() is used
2299  * instead.
2300  *
2301  * Returns: The VMA associated with @addr, or the next vma.
2302  * May return %NULL in the case of no vma at addr or above.
2303  */
2304 struct vm_area_struct *
2305 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2306                         struct vm_area_struct **pprev)
2307 {
2308         struct vm_area_struct *vma;
2309         MA_STATE(mas, &mm->mm_mt, addr, addr);
2310
2311         vma = mas_walk(&mas);
2312         *pprev = mas_prev(&mas, 0);
2313         if (!vma)
2314                 vma = mas_next(&mas, ULONG_MAX);
2315         return vma;
2316 }
2317
2318 /*
2319  * Verify that the stack growth is acceptable and
2320  * update accounting. This is shared with both the
2321  * grow-up and grow-down cases.
2322  */
2323 static int acct_stack_growth(struct vm_area_struct *vma,
2324                              unsigned long size, unsigned long grow)
2325 {
2326         struct mm_struct *mm = vma->vm_mm;
2327         unsigned long new_start;
2328
2329         /* address space limit tests */
2330         if (!may_expand_vm(mm, vma->vm_flags, grow))
2331                 return -ENOMEM;
2332
2333         /* Stack limit test */
2334         if (size > rlimit(RLIMIT_STACK))
2335                 return -ENOMEM;
2336
2337         /* mlock limit tests */
2338         if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
2339                 return -ENOMEM;
2340
2341         /* Check to ensure the stack will not grow into a hugetlb-only region */
2342         new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2343                         vma->vm_end - size;
2344         if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2345                 return -EFAULT;
2346
2347         /*
2348          * Overcommit..  This must be the final test, as it will
2349          * update security statistics.
2350          */
2351         if (security_vm_enough_memory_mm(mm, grow))
2352                 return -ENOMEM;
2353
2354         return 0;
2355 }
2356
2357 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2358 /*
2359  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2360  * vma is the last one with address > vma->vm_end.  Have to extend vma.
2361  */
2362 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2363 {
2364         struct mm_struct *mm = vma->vm_mm;
2365         struct vm_area_struct *next;
2366         unsigned long gap_addr;
2367         int error = 0;
2368         MA_STATE(mas, &mm->mm_mt, 0, 0);
2369
2370         validate_mm_mt(mm);
2371         if (!(vma->vm_flags & VM_GROWSUP))
2372                 return -EFAULT;
2373
2374         /* Guard against exceeding limits of the address space. */
2375         address &= PAGE_MASK;
2376         if (address >= (TASK_SIZE & PAGE_MASK))
2377                 return -ENOMEM;
2378         address += PAGE_SIZE;
2379
2380         /* Enforce stack_guard_gap */
2381         gap_addr = address + stack_guard_gap;
2382
2383         /* Guard against overflow */
2384         if (gap_addr < address || gap_addr > TASK_SIZE)
2385                 gap_addr = TASK_SIZE;
2386
2387         next = vma->vm_next;
2388         if (next && next->vm_start < gap_addr && vma_is_accessible(next)) {
2389                 if (!(next->vm_flags & VM_GROWSUP))
2390                         return -ENOMEM;
2391                 /* Check that both stack segments have the same anon_vma? */
2392         }
2393
2394         if (mas_preallocate(&mas, vma, GFP_KERNEL))
2395                 return -ENOMEM;
2396
2397         /* We must make sure the anon_vma is allocated. */
2398         if (unlikely(anon_vma_prepare(vma))) {
2399                 mas_destroy(&mas);
2400                 return -ENOMEM;
2401         }
2402
2403         /*
2404          * vma->vm_start/vm_end cannot change under us because the caller
2405          * is required to hold the mmap_lock in read mode.  We need the
2406          * anon_vma lock to serialize against concurrent expand_stacks.
2407          */
2408         anon_vma_lock_write(vma->anon_vma);
2409
2410         /* Somebody else might have raced and expanded it already */
2411         if (address > vma->vm_end) {
2412                 unsigned long size, grow;
2413
2414                 size = address - vma->vm_start;
2415                 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2416
2417                 error = -ENOMEM;
2418                 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2419                         error = acct_stack_growth(vma, size, grow);
2420                         if (!error) {
2421                                 /*
2422                                  * vma_gap_update() doesn't support concurrent
2423                                  * updates, but we only hold a shared mmap_lock
2424                                  * lock here, so we need to protect against
2425                                  * concurrent vma expansions.
2426                                  * anon_vma_lock_write() doesn't help here, as
2427                                  * we don't guarantee that all growable vmas
2428                                  * in a mm share the same root anon vma.
2429                                  * So, we reuse mm->page_table_lock to guard
2430                                  * against concurrent vma expansions.
2431                                  */
2432                                 spin_lock(&mm->page_table_lock);
2433                                 if (vma->vm_flags & VM_LOCKED)
2434                                         mm->locked_vm += grow;
2435                                 vm_stat_account(mm, vma->vm_flags, grow);
2436                                 anon_vma_interval_tree_pre_update_vma(vma);
2437                                 vma->vm_end = address;
2438                                 /* Overwrite old entry in mtree. */
2439                                 vma_mas_store(vma, &mas);
2440                                 anon_vma_interval_tree_post_update_vma(vma);
2441                                 if (vma->vm_next)
2442                                         vma_gap_update(vma->vm_next);
2443                                 else
2444                                         mm->highest_vm_end = vm_end_gap(vma);
2445                                 spin_unlock(&mm->page_table_lock);
2446
2447                                 perf_event_mmap(vma);
2448                         }
2449                 }
2450         }
2451         anon_vma_unlock_write(vma->anon_vma);
2452         khugepaged_enter_vma(vma, vma->vm_flags);
2453         validate_mm(mm);
2454         validate_mm_mt(mm);
2455         mas_destroy(&mas);
2456         return error;
2457 }
2458 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2459
2460 /*
2461  * vma is the first one with address < vma->vm_start.  Have to extend vma.
2462  */
2463 int expand_downwards(struct vm_area_struct *vma,
2464                                    unsigned long address)
2465 {
2466         struct mm_struct *mm = vma->vm_mm;
2467         struct vm_area_struct *prev;
2468         int error = 0;
2469         MA_STATE(mas, &mm->mm_mt, 0, 0);
2470
2471         validate_mm(mm);
2472         address &= PAGE_MASK;
2473         if (address < mmap_min_addr)
2474                 return -EPERM;
2475
2476         /* Enforce stack_guard_gap */
2477         prev = vma->vm_prev;
2478         /* Check that both stack segments have the same anon_vma? */
2479         if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
2480                         vma_is_accessible(prev)) {
2481                 if (address - prev->vm_end < stack_guard_gap)
2482                         return -ENOMEM;
2483         }
2484
2485         if (mas_preallocate(&mas, vma, GFP_KERNEL))
2486                 return -ENOMEM;
2487
2488         /* We must make sure the anon_vma is allocated. */
2489         if (unlikely(anon_vma_prepare(vma))) {
2490                 mas_destroy(&mas);
2491                 return -ENOMEM;
2492         }
2493
2494         /*
2495          * vma->vm_start/vm_end cannot change under us because the caller
2496          * is required to hold the mmap_lock in read mode.  We need the
2497          * anon_vma lock to serialize against concurrent expand_stacks.
2498          */
2499         anon_vma_lock_write(vma->anon_vma);
2500
2501         /* Somebody else might have raced and expanded it already */
2502         if (address < vma->vm_start) {
2503                 unsigned long size, grow;
2504
2505                 size = vma->vm_end - address;
2506                 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2507
2508                 error = -ENOMEM;
2509                 if (grow <= vma->vm_pgoff) {
2510                         error = acct_stack_growth(vma, size, grow);
2511                         if (!error) {
2512                                 /*
2513                                  * vma_gap_update() doesn't support concurrent
2514                                  * updates, but we only hold a shared mmap_lock
2515                                  * lock here, so we need to protect against
2516                                  * concurrent vma expansions.
2517                                  * anon_vma_lock_write() doesn't help here, as
2518                                  * we don't guarantee that all growable vmas
2519                                  * in a mm share the same root anon vma.
2520                                  * So, we reuse mm->page_table_lock to guard
2521                                  * against concurrent vma expansions.
2522                                  */
2523                                 spin_lock(&mm->page_table_lock);
2524                                 if (vma->vm_flags & VM_LOCKED)
2525                                         mm->locked_vm += grow;
2526                                 vm_stat_account(mm, vma->vm_flags, grow);
2527                                 anon_vma_interval_tree_pre_update_vma(vma);
2528                                 vma->vm_start = address;
2529                                 vma->vm_pgoff -= grow;
2530                                 /* Overwrite old entry in mtree. */
2531                                 vma_mas_store(vma, &mas);
2532                                 anon_vma_interval_tree_post_update_vma(vma);
2533                                 vma_gap_update(vma);
2534                                 spin_unlock(&mm->page_table_lock);
2535
2536                                 perf_event_mmap(vma);
2537                         }
2538                 }
2539         }
2540         anon_vma_unlock_write(vma->anon_vma);
2541         khugepaged_enter_vma(vma, vma->vm_flags);
2542         validate_mm(mm);
2543         mas_destroy(&mas);
2544         return error;
2545 }
2546
2547 /* enforced gap between the expanding stack and other mappings. */
2548 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2549
2550 static int __init cmdline_parse_stack_guard_gap(char *p)
2551 {
2552         unsigned long val;
2553         char *endptr;
2554
2555         val = simple_strtoul(p, &endptr, 10);
2556         if (!*endptr)
2557                 stack_guard_gap = val << PAGE_SHIFT;
2558
2559         return 1;
2560 }
2561 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2562
2563 #ifdef CONFIG_STACK_GROWSUP
2564 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2565 {
2566         return expand_upwards(vma, address);
2567 }
2568
2569 struct vm_area_struct *
2570 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2571 {
2572         struct vm_area_struct *vma, *prev;
2573
2574         addr &= PAGE_MASK;
2575         vma = find_vma_prev(mm, addr, &prev);
2576         if (vma && (vma->vm_start <= addr))
2577                 return vma;
2578         if (!prev || expand_stack(prev, addr))
2579                 return NULL;
2580         if (prev->vm_flags & VM_LOCKED)
2581                 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2582         return prev;
2583 }
2584 #else
2585 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2586 {
2587         return expand_downwards(vma, address);
2588 }
2589
2590 struct vm_area_struct *
2591 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2592 {
2593         struct vm_area_struct *vma;
2594         unsigned long start;
2595
2596         addr &= PAGE_MASK;
2597         vma = find_vma(mm, addr);
2598         if (!vma)
2599                 return NULL;
2600         if (vma->vm_start <= addr)
2601                 return vma;
2602         if (!(vma->vm_flags & VM_GROWSDOWN))
2603                 return NULL;
2604         start = vma->vm_start;
2605         if (expand_stack(vma, addr))
2606                 return NULL;
2607         if (vma->vm_flags & VM_LOCKED)
2608                 populate_vma_page_range(vma, addr, start, NULL);
2609         return vma;
2610 }
2611 #endif
2612
2613 EXPORT_SYMBOL_GPL(find_extend_vma);
2614
2615 /*
2616  * Ok - we have the memory areas we should free on the vma list,
2617  * so release them, and do the vma updates.
2618  *
2619  * Called with the mm semaphore held.
2620  */
2621 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2622 {
2623         unsigned long nr_accounted = 0;
2624
2625         /* Update high watermark before we lower total_vm */
2626         update_hiwater_vm(mm);
2627         do {
2628                 long nrpages = vma_pages(vma);
2629
2630                 if (vma->vm_flags & VM_ACCOUNT)
2631                         nr_accounted += nrpages;
2632                 vm_stat_account(mm, vma->vm_flags, -nrpages);
2633                 vma = remove_vma(vma);
2634         } while (vma);
2635         vm_unacct_memory(nr_accounted);
2636         validate_mm(mm);
2637 }
2638
2639 /*
2640  * Get rid of page table information in the indicated region.
2641  *
2642  * Called with the mm semaphore held.
2643  */
2644 static void unmap_region(struct mm_struct *mm,
2645                 struct vm_area_struct *vma, struct vm_area_struct *prev,
2646                 unsigned long start, unsigned long end)
2647 {
2648         struct vm_area_struct *next = __vma_next(mm, prev);
2649         struct mmu_gather tlb;
2650
2651         lru_add_drain();
2652         tlb_gather_mmu(&tlb, mm);
2653         update_hiwater_rss(mm);
2654         unmap_vmas(&tlb, vma, start, end);
2655         free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2656                                  next ? next->vm_start : USER_PGTABLES_CEILING);
2657         tlb_finish_mmu(&tlb);
2658 }
2659
2660 /*
2661  * Create a list of vma's touched by the unmap, removing them from the mm's
2662  * vma list as we go..
2663  */
2664 static bool
2665 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct ma_state *mas,
2666         struct vm_area_struct *vma, struct vm_area_struct *prev,
2667         unsigned long end)
2668 {
2669         struct vm_area_struct **insertion_point;
2670         struct vm_area_struct *tail_vma = NULL;
2671
2672         insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2673         vma->vm_prev = NULL;
2674         mas_set_range(mas, vma->vm_start, end - 1);
2675         mas_store_prealloc(mas, NULL);
2676         do {
2677                 vma_rb_erase(vma, &mm->mm_rb);
2678                 if (vma->vm_flags & VM_LOCKED)
2679                         mm->locked_vm -= vma_pages(vma);
2680                 mm->map_count--;
2681                 tail_vma = vma;
2682                 vma = vma->vm_next;
2683         } while (vma && vma->vm_start < end);
2684         *insertion_point = vma;
2685         if (vma) {
2686                 vma->vm_prev = prev;
2687                 vma_gap_update(vma);
2688         } else
2689                 mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
2690         tail_vma->vm_next = NULL;
2691
2692         /* Kill the cache */
2693         vmacache_invalidate(mm);
2694
2695         /*
2696          * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2697          * VM_GROWSUP VMA. Such VMAs can change their size under
2698          * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2699          */
2700         if (vma && (vma->vm_flags & VM_GROWSDOWN))
2701                 return false;
2702         if (prev && (prev->vm_flags & VM_GROWSUP))
2703                 return false;
2704         return true;
2705 }
2706
2707 /*
2708  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2709  * has already been checked or doesn't make sense to fail.
2710  */
2711 int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2712                 unsigned long addr, int new_below)
2713 {
2714         struct vm_area_struct *new;
2715         int err;
2716         validate_mm_mt(mm);
2717
2718         if (vma->vm_ops && vma->vm_ops->may_split) {
2719                 err = vma->vm_ops->may_split(vma, addr);
2720                 if (err)
2721                         return err;
2722         }
2723
2724         new = vm_area_dup(vma);
2725         if (!new)
2726                 return -ENOMEM;
2727
2728         if (new_below)
2729                 new->vm_end = addr;
2730         else {
2731                 new->vm_start = addr;
2732                 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2733         }
2734
2735         err = vma_dup_policy(vma, new);
2736         if (err)
2737                 goto out_free_vma;
2738
2739         err = anon_vma_clone(new, vma);
2740         if (err)
2741                 goto out_free_mpol;
2742
2743         if (new->vm_file)
2744                 get_file(new->vm_file);
2745
2746         if (new->vm_ops && new->vm_ops->open)
2747                 new->vm_ops->open(new);
2748
2749         if (new_below)
2750                 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2751                         ((addr - new->vm_start) >> PAGE_SHIFT), new);
2752         else
2753                 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2754
2755         /* Success. */
2756         if (!err)
2757                 return 0;
2758
2759         /* Avoid vm accounting in close() operation */
2760         new->vm_start = new->vm_end;
2761         new->vm_pgoff = 0;
2762         /* Clean everything up if vma_adjust failed. */
2763         if (new->vm_ops && new->vm_ops->close)
2764                 new->vm_ops->close(new);
2765         if (new->vm_file)
2766                 fput(new->vm_file);
2767         unlink_anon_vmas(new);
2768  out_free_mpol:
2769         mpol_put(vma_policy(new));
2770  out_free_vma:
2771         vm_area_free(new);
2772         validate_mm_mt(mm);
2773         return err;
2774 }
2775
2776 /*
2777  * Split a vma into two pieces at address 'addr', a new vma is allocated
2778  * either for the first part or the tail.
2779  */
2780 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2781               unsigned long addr, int new_below)
2782 {
2783         if (mm->map_count >= sysctl_max_map_count)
2784                 return -ENOMEM;
2785
2786         return __split_vma(mm, vma, addr, new_below);
2787 }
2788
2789 /* Munmap is split into 2 main parts -- this part which finds
2790  * what needs doing, and the areas themselves, which do the
2791  * work.  This now handles partial unmappings.
2792  * Jeremy Fitzhardinge <jeremy@goop.org>
2793  */
2794 int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2795                 struct list_head *uf, bool downgrade)
2796 {
2797         unsigned long end;
2798         struct vm_area_struct *vma, *prev, *last;
2799         int error = -ENOMEM;
2800         MA_STATE(mas, &mm->mm_mt, 0, 0);
2801
2802         if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2803                 return -EINVAL;
2804
2805         len = PAGE_ALIGN(len);
2806         end = start + len;
2807         if (len == 0)
2808                 return -EINVAL;
2809
2810         /*
2811          * arch_unmap() might do unmaps itself.  It must be called
2812          * and finish any rbtree manipulation before this code
2813          * runs and also starts to manipulate the rbtree.
2814          */
2815         arch_unmap(mm, start, end);
2816
2817         /* Find the first overlapping VMA where start < vma->vm_end */
2818         vma = find_vma_intersection(mm, start, end);
2819         if (!vma)
2820                 return 0;
2821
2822         if (mas_preallocate(&mas, vma, GFP_KERNEL))
2823                 return -ENOMEM;
2824         prev = vma->vm_prev;
2825
2826         /*
2827          * If we need to split any vma, do it now to save pain later.
2828          *
2829          * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2830          * unmapped vm_area_struct will remain in use: so lower split_vma
2831          * places tmp vma above, and higher split_vma places tmp vma below.
2832          */
2833         if (start > vma->vm_start) {
2834
2835                 /*
2836                  * Make sure that map_count on return from munmap() will
2837                  * not exceed its limit; but let map_count go just above
2838                  * its limit temporarily, to help free resources as expected.
2839                  */
2840                 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2841                         goto map_count_exceeded;
2842
2843                 error = __split_vma(mm, vma, start, 0);
2844                 if (error)
2845                         goto split_failed;
2846                 prev = vma;
2847         }
2848
2849         /* Does it split the last one? */
2850         last = find_vma(mm, end);
2851         if (last && end > last->vm_start) {
2852                 error = __split_vma(mm, last, end, 1);
2853                 if (error)
2854                         goto split_failed;
2855         }
2856         vma = __vma_next(mm, prev);
2857
2858         if (unlikely(uf)) {
2859                 /*
2860                  * If userfaultfd_unmap_prep returns an error the vmas
2861                  * will remain split, but userland will get a
2862                  * highly unexpected error anyway. This is no
2863                  * different than the case where the first of the two
2864                  * __split_vma fails, but we don't undo the first
2865                  * split, despite we could. This is unlikely enough
2866                  * failure that it's not worth optimizing it for.
2867                  */
2868                 error = userfaultfd_unmap_prep(vma, start, end, uf);
2869                 if (error)
2870                         goto userfaultfd_error;
2871         }
2872
2873         /* Detach vmas from rbtree */
2874         if (!detach_vmas_to_be_unmapped(mm, &mas, vma, prev, end))
2875                 downgrade = false;
2876
2877         if (downgrade)
2878                 mmap_write_downgrade(mm);
2879
2880         unmap_region(mm, vma, prev, start, end);
2881
2882         /* Fix up all other VM information */
2883         remove_vma_list(mm, vma);
2884
2885         return downgrade ? 1 : 0;
2886
2887 map_count_exceeded:
2888 split_failed:
2889 userfaultfd_error:
2890         mas_destroy(&mas);
2891         return error;
2892 }
2893
2894 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2895               struct list_head *uf)
2896 {
2897         return __do_munmap(mm, start, len, uf, false);
2898 }
2899
2900 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2901 {
2902         int ret;
2903         struct mm_struct *mm = current->mm;
2904         LIST_HEAD(uf);
2905
2906         if (mmap_write_lock_killable(mm))
2907                 return -EINTR;
2908
2909         ret = __do_munmap(mm, start, len, &uf, downgrade);
2910         /*
2911          * Returning 1 indicates mmap_lock is downgraded.
2912          * But 1 is not legal return value of vm_munmap() and munmap(), reset
2913          * it to 0 before return.
2914          */
2915         if (ret == 1) {
2916                 mmap_read_unlock(mm);
2917                 ret = 0;
2918         } else
2919                 mmap_write_unlock(mm);
2920
2921         userfaultfd_unmap_complete(mm, &uf);
2922         return ret;
2923 }
2924
2925 int vm_munmap(unsigned long start, size_t len)
2926 {
2927         return __vm_munmap(start, len, false);
2928 }
2929 EXPORT_SYMBOL(vm_munmap);
2930
2931 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2932 {
2933         addr = untagged_addr(addr);
2934         return __vm_munmap(addr, len, true);
2935 }
2936
2937
2938 /*
2939  * Emulation of deprecated remap_file_pages() syscall.
2940  */
2941 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2942                 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2943 {
2944
2945         struct mm_struct *mm = current->mm;
2946         struct vm_area_struct *vma;
2947         unsigned long populate = 0;
2948         unsigned long ret = -EINVAL;
2949         struct file *file;
2950
2951         pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
2952                      current->comm, current->pid);
2953
2954         if (prot)
2955                 return ret;
2956         start = start & PAGE_MASK;
2957         size = size & PAGE_MASK;
2958
2959         if (start + size <= start)
2960                 return ret;
2961
2962         /* Does pgoff wrap? */
2963         if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2964                 return ret;
2965
2966         if (mmap_write_lock_killable(mm))
2967                 return -EINTR;
2968
2969         vma = vma_lookup(mm, start);
2970
2971         if (!vma || !(vma->vm_flags & VM_SHARED))
2972                 goto out;
2973
2974         if (start + size > vma->vm_end) {
2975                 struct vm_area_struct *next;
2976
2977                 for (next = vma->vm_next; next; next = next->vm_next) {
2978                         /* hole between vmas ? */
2979                         if (next->vm_start != next->vm_prev->vm_end)
2980                                 goto out;
2981
2982                         if (next->vm_file != vma->vm_file)
2983                                 goto out;
2984
2985                         if (next->vm_flags != vma->vm_flags)
2986                                 goto out;
2987
2988                         if (start + size <= next->vm_end)
2989                                 break;
2990                 }
2991
2992                 if (!next)
2993                         goto out;
2994         }
2995
2996         prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2997         prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2998         prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2999
3000         flags &= MAP_NONBLOCK;
3001         flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
3002         if (vma->vm_flags & VM_LOCKED)
3003                 flags |= MAP_LOCKED;
3004
3005         file = get_file(vma->vm_file);
3006         ret = do_mmap(vma->vm_file, start, size,
3007                         prot, flags, pgoff, &populate, NULL);
3008         fput(file);
3009 out:
3010         mmap_write_unlock(mm);
3011         if (populate)
3012                 mm_populate(ret, populate);
3013         if (!IS_ERR_VALUE(ret))
3014                 ret = 0;
3015         return ret;
3016 }
3017
3018 /*
3019  *  this is really a simplified "do_mmap".  it only handles
3020  *  anonymous maps.  eventually we may be able to do some
3021  *  brk-specific accounting here.
3022  */
3023 static int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)
3024 {
3025         struct mm_struct *mm = current->mm;
3026         struct vm_area_struct *vma, *prev;
3027         struct rb_node **rb_link, *rb_parent;
3028         pgoff_t pgoff = addr >> PAGE_SHIFT;
3029         int error;
3030         unsigned long mapped_addr;
3031         validate_mm_mt(mm);
3032
3033         /* Until we need other flags, refuse anything except VM_EXEC. */
3034         if ((flags & (~VM_EXEC)) != 0)
3035                 return -EINVAL;
3036         flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
3037
3038         mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
3039         if (IS_ERR_VALUE(mapped_addr))
3040                 return mapped_addr;
3041
3042         error = mlock_future_check(mm, mm->def_flags, len);
3043         if (error)
3044                 return error;
3045
3046         /* Clear old maps, set up prev, rb_link, rb_parent, and uf */
3047         if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
3048                 return -ENOMEM;
3049
3050         /* Check against address space limits *after* clearing old maps... */
3051         if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
3052                 return -ENOMEM;
3053
3054         if (mm->map_count > sysctl_max_map_count)
3055                 return -ENOMEM;
3056
3057         if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3058                 return -ENOMEM;
3059
3060         /* Can we just expand an old private anonymous mapping? */
3061         vma = vma_merge(mm, prev, addr, addr + len, flags,
3062                         NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
3063         if (vma)
3064                 goto out;
3065
3066         /*
3067          * create a vma struct for an anonymous mapping
3068          */
3069         vma = vm_area_alloc(mm);
3070         if (!vma) {
3071                 vm_unacct_memory(len >> PAGE_SHIFT);
3072                 return -ENOMEM;
3073         }
3074
3075         vma_set_anonymous(vma);
3076         vma->vm_start = addr;
3077         vma->vm_end = addr + len;
3078         vma->vm_pgoff = pgoff;
3079         vma->vm_flags = flags;
3080         vma->vm_page_prot = vm_get_page_prot(flags);
3081         if (vma_link(mm, vma, prev, rb_link, rb_parent))
3082                 goto no_vma_link;
3083
3084 out:
3085         perf_event_mmap(vma);
3086         mm->total_vm += len >> PAGE_SHIFT;
3087         mm->data_vm += len >> PAGE_SHIFT;
3088         if (flags & VM_LOCKED)
3089                 mm->locked_vm += (len >> PAGE_SHIFT);
3090         vma->vm_flags |= VM_SOFTDIRTY;
3091         validate_mm_mt(mm);
3092         return 0;
3093
3094 no_vma_link:
3095         vm_area_free(vma);
3096         return -ENOMEM;
3097 }
3098
3099 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3100 {
3101         struct mm_struct *mm = current->mm;
3102         unsigned long len;
3103         int ret;
3104         bool populate;
3105         LIST_HEAD(uf);
3106
3107         len = PAGE_ALIGN(request);
3108         if (len < request)
3109                 return -ENOMEM;
3110         if (!len)
3111                 return 0;
3112
3113         if (mmap_write_lock_killable(mm))
3114                 return -EINTR;
3115
3116         ret = do_brk_flags(addr, len, flags, &uf);
3117         populate = ((mm->def_flags & VM_LOCKED) != 0);
3118         mmap_write_unlock(mm);
3119         userfaultfd_unmap_complete(mm, &uf);
3120         if (populate && !ret)
3121                 mm_populate(addr, len);
3122         return ret;
3123 }
3124 EXPORT_SYMBOL(vm_brk_flags);
3125
3126 int vm_brk(unsigned long addr, unsigned long len)
3127 {
3128         return vm_brk_flags(addr, len, 0);
3129 }
3130 EXPORT_SYMBOL(vm_brk);
3131
3132 /* Release all mmaps. */
3133 void exit_mmap(struct mm_struct *mm)
3134 {
3135         struct mmu_gather tlb;
3136         struct vm_area_struct *vma;
3137         unsigned long nr_accounted = 0;
3138
3139         /* mm's last user has gone, and its about to be pulled down */
3140         mmu_notifier_release(mm);
3141
3142         if (unlikely(mm_is_oom_victim(mm))) {
3143                 /*
3144                  * Manually reap the mm to free as much memory as possible.
3145                  * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3146                  * this mm from further consideration.  Taking mm->mmap_lock for
3147                  * write after setting MMF_OOM_SKIP will guarantee that the oom
3148                  * reaper will not run on this mm again after mmap_lock is
3149                  * dropped.
3150                  *
3151                  * Nothing can be holding mm->mmap_lock here and the above call
3152                  * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
3153                  * __oom_reap_task_mm() will not block.
3154                  */
3155                 (void)__oom_reap_task_mm(mm);
3156                 set_bit(MMF_OOM_SKIP, &mm->flags);
3157         }
3158
3159         mmap_write_lock(mm);
3160         arch_exit_mmap(mm);
3161
3162         vma = mm->mmap;
3163         if (!vma) {
3164                 /* Can happen if dup_mmap() received an OOM */
3165                 mmap_write_unlock(mm);
3166                 return;
3167         }
3168
3169         lru_add_drain();
3170         flush_cache_mm(mm);
3171         tlb_gather_mmu_fullmm(&tlb, mm);
3172         /* update_hiwater_rss(mm) here? but nobody should be looking */
3173         /* Use -1 here to ensure all VMAs in the mm are unmapped */
3174         unmap_vmas(&tlb, vma, 0, -1);
3175         free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3176         tlb_finish_mmu(&tlb);
3177
3178         /* Walk the list again, actually closing and freeing it. */
3179         while (vma) {
3180                 if (vma->vm_flags & VM_ACCOUNT)
3181                         nr_accounted += vma_pages(vma);
3182                 vma = remove_vma(vma);
3183                 cond_resched();
3184         }
3185
3186         trace_exit_mmap(mm);
3187         __mt_destroy(&mm->mm_mt);
3188         mm->mmap = NULL;
3189         mmap_write_unlock(mm);
3190         vm_unacct_memory(nr_accounted);
3191 }
3192
3193 /* Insert vm structure into process list sorted by address
3194  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3195  * then i_mmap_rwsem is taken here.
3196  */
3197 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3198 {
3199         struct vm_area_struct *prev;
3200         struct rb_node **rb_link, *rb_parent;
3201         unsigned long start = vma->vm_start;
3202         struct vm_area_struct *overlap = NULL;
3203         unsigned long charged = vma_pages(vma);
3204
3205         if (find_vma_links(mm, vma->vm_start, vma->vm_end,
3206                            &prev, &rb_link, &rb_parent))
3207
3208         if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3209                 return -ENOMEM;
3210
3211         overlap = mt_find(&mm->mm_mt, &start, vma->vm_end - 1);
3212         if (overlap) {
3213
3214                 pr_err("Found vma ending at %lu\n", start - 1);
3215                 pr_err("vma : %lu => %lu-%lu\n", (unsigned long)overlap,
3216                                 overlap->vm_start, overlap->vm_end - 1);
3217 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
3218                 mt_dump(&mm->mm_mt);
3219 #endif
3220                 BUG();
3221         }
3222
3223         if ((vma->vm_flags & VM_ACCOUNT) &&
3224              security_vm_enough_memory_mm(mm, charged))
3225                 return -ENOMEM;
3226
3227         /*
3228          * The vm_pgoff of a purely anonymous vma should be irrelevant
3229          * until its first write fault, when page's anon_vma and index
3230          * are set.  But now set the vm_pgoff it will almost certainly
3231          * end up with (unless mremap moves it elsewhere before that
3232          * first wfault), so /proc/pid/maps tells a consistent story.
3233          *
3234          * By setting it to reflect the virtual start address of the
3235          * vma, merges and splits can happen in a seamless way, just
3236          * using the existing file pgoff checks and manipulations.
3237          * Similarly in do_mmap and in do_brk_flags.
3238          */
3239         if (vma_is_anonymous(vma)) {
3240                 BUG_ON(vma->anon_vma);
3241                 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3242         }
3243
3244         if (vma_link(mm, vma, prev, rb_link, rb_parent)) {
3245                 vm_unacct_memory(charged);
3246                 return -ENOMEM;
3247         }
3248
3249         return 0;
3250 }
3251
3252 /*
3253  * Copy the vma structure to a new location in the same mm,
3254  * prior to moving page table entries, to effect an mremap move.
3255  */
3256 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3257         unsigned long addr, unsigned long len, pgoff_t pgoff,
3258         bool *need_rmap_locks)
3259 {
3260         struct vm_area_struct *vma = *vmap;
3261         unsigned long vma_start = vma->vm_start;
3262         struct mm_struct *mm = vma->vm_mm;
3263         struct vm_area_struct *new_vma, *prev;
3264         struct rb_node **rb_link, *rb_parent;
3265         bool faulted_in_anon_vma = true;
3266         unsigned long index = addr;
3267
3268         validate_mm_mt(mm);
3269         /*
3270          * If anonymous vma has not yet been faulted, update new pgoff
3271          * to match new location, to increase its chance of merging.
3272          */
3273         if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3274                 pgoff = addr >> PAGE_SHIFT;
3275                 faulted_in_anon_vma = false;
3276         }
3277
3278         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
3279                 return NULL;    /* should never get here */
3280         if (mt_find(&mm->mm_mt, &index, addr+len - 1))
3281                 BUG();
3282         new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
3283                             vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3284                             vma->vm_userfaultfd_ctx, anon_vma_name(vma));
3285         if (new_vma) {
3286                 /*
3287                  * Source vma may have been merged into new_vma
3288                  */
3289                 if (unlikely(vma_start >= new_vma->vm_start &&
3290                              vma_start < new_vma->vm_end)) {
3291                         /*
3292                          * The only way we can get a vma_merge with
3293                          * self during an mremap is if the vma hasn't
3294                          * been faulted in yet and we were allowed to
3295                          * reset the dst vma->vm_pgoff to the
3296                          * destination address of the mremap to allow
3297                          * the merge to happen. mremap must change the
3298                          * vm_pgoff linearity between src and dst vmas
3299                          * (in turn preventing a vma_merge) to be
3300                          * safe. It is only safe to keep the vm_pgoff
3301                          * linear if there are no pages mapped yet.
3302                          */
3303                         VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3304                         *vmap = vma = new_vma;
3305                 }
3306                 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3307         } else {
3308                 new_vma = vm_area_dup(vma);
3309                 if (!new_vma)
3310                         goto out;
3311                 new_vma->vm_start = addr;
3312                 new_vma->vm_end = addr + len;
3313                 new_vma->vm_pgoff = pgoff;
3314                 if (vma_dup_policy(vma, new_vma))
3315                         goto out_free_vma;
3316                 if (anon_vma_clone(new_vma, vma))
3317                         goto out_free_mempol;
3318                 if (new_vma->vm_file)
3319                         get_file(new_vma->vm_file);
3320                 if (new_vma->vm_ops && new_vma->vm_ops->open)
3321                         new_vma->vm_ops->open(new_vma);
3322                 vma_link(mm, new_vma, prev, rb_link, rb_parent);
3323                 *need_rmap_locks = false;
3324         }
3325         validate_mm_mt(mm);
3326         return new_vma;
3327
3328 out_free_mempol:
3329         mpol_put(vma_policy(new_vma));
3330 out_free_vma:
3331         vm_area_free(new_vma);
3332 out:
3333         validate_mm_mt(mm);
3334         return NULL;
3335 }
3336
3337 /*
3338  * Return true if the calling process may expand its vm space by the passed
3339  * number of pages
3340  */
3341 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3342 {
3343         if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3344                 return false;
3345
3346         if (is_data_mapping(flags) &&
3347             mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3348                 /* Workaround for Valgrind */
3349                 if (rlimit(RLIMIT_DATA) == 0 &&
3350                     mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3351                         return true;
3352
3353                 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3354                              current->comm, current->pid,
3355                              (mm->data_vm + npages) << PAGE_SHIFT,
3356                              rlimit(RLIMIT_DATA),
3357                              ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3358
3359                 if (!ignore_rlimit_data)
3360                         return false;
3361         }
3362
3363         return true;
3364 }
3365
3366 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3367 {
3368         WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3369
3370         if (is_exec_mapping(flags))
3371                 mm->exec_vm += npages;
3372         else if (is_stack_mapping(flags))
3373                 mm->stack_vm += npages;
3374         else if (is_data_mapping(flags))
3375                 mm->data_vm += npages;
3376 }
3377
3378 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3379
3380 /*
3381  * Having a close hook prevents vma merging regardless of flags.
3382  */
3383 static void special_mapping_close(struct vm_area_struct *vma)
3384 {
3385 }
3386
3387 static const char *special_mapping_name(struct vm_area_struct *vma)
3388 {
3389         return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3390 }
3391
3392 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3393 {
3394         struct vm_special_mapping *sm = new_vma->vm_private_data;
3395
3396         if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3397                 return -EFAULT;
3398
3399         if (sm->mremap)
3400                 return sm->mremap(sm, new_vma);
3401
3402         return 0;
3403 }
3404
3405 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3406 {
3407         /*
3408          * Forbid splitting special mappings - kernel has expectations over
3409          * the number of pages in mapping. Together with VM_DONTEXPAND
3410          * the size of vma should stay the same over the special mapping's
3411          * lifetime.
3412          */
3413         return -EINVAL;
3414 }
3415
3416 static const struct vm_operations_struct special_mapping_vmops = {
3417         .close = special_mapping_close,
3418         .fault = special_mapping_fault,
3419         .mremap = special_mapping_mremap,
3420         .name = special_mapping_name,
3421         /* vDSO code relies that VVAR can't be accessed remotely */
3422         .access = NULL,
3423         .may_split = special_mapping_split,
3424 };
3425
3426 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3427         .close = special_mapping_close,
3428         .fault = special_mapping_fault,
3429 };
3430
3431 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3432 {
3433         struct vm_area_struct *vma = vmf->vma;
3434         pgoff_t pgoff;
3435         struct page **pages;
3436
3437         if (vma->vm_ops == &legacy_special_mapping_vmops) {
3438                 pages = vma->vm_private_data;
3439         } else {
3440                 struct vm_special_mapping *sm = vma->vm_private_data;
3441
3442                 if (sm->fault)
3443                         return sm->fault(sm, vmf->vma, vmf);
3444
3445                 pages = sm->pages;
3446         }
3447
3448         for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3449                 pgoff--;
3450
3451         if (*pages) {
3452                 struct page *page = *pages;
3453                 get_page(page);
3454                 vmf->page = page;
3455                 return 0;
3456         }
3457
3458         return VM_FAULT_SIGBUS;
3459 }
3460
3461 static struct vm_area_struct *__install_special_mapping(
3462         struct mm_struct *mm,
3463         unsigned long addr, unsigned long len,
3464         unsigned long vm_flags, void *priv,
3465         const struct vm_operations_struct *ops)
3466 {
3467         int ret;
3468         struct vm_area_struct *vma;
3469
3470         validate_mm_mt(mm);
3471         vma = vm_area_alloc(mm);
3472         if (unlikely(vma == NULL))
3473                 return ERR_PTR(-ENOMEM);
3474
3475         vma->vm_start = addr;
3476         vma->vm_end = addr + len;
3477
3478         vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3479         vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
3480         vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3481
3482         vma->vm_ops = ops;
3483         vma->vm_private_data = priv;
3484
3485         ret = insert_vm_struct(mm, vma);
3486         if (ret)
3487                 goto out;
3488
3489         vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3490
3491         perf_event_mmap(vma);
3492
3493         validate_mm_mt(mm);
3494         return vma;
3495
3496 out:
3497         vm_area_free(vma);
3498         validate_mm_mt(mm);
3499         return ERR_PTR(ret);
3500 }
3501
3502 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3503         const struct vm_special_mapping *sm)
3504 {
3505         return vma->vm_private_data == sm &&
3506                 (vma->vm_ops == &special_mapping_vmops ||
3507                  vma->vm_ops == &legacy_special_mapping_vmops);
3508 }
3509
3510 /*
3511  * Called with mm->mmap_lock held for writing.
3512  * Insert a new vma covering the given region, with the given flags.
3513  * Its pages are supplied by the given array of struct page *.
3514  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3515  * The region past the last page supplied will always produce SIGBUS.
3516  * The array pointer and the pages it points to are assumed to stay alive
3517  * for as long as this mapping might exist.
3518  */
3519 struct vm_area_struct *_install_special_mapping(
3520         struct mm_struct *mm,
3521         unsigned long addr, unsigned long len,
3522         unsigned long vm_flags, const struct vm_special_mapping *spec)
3523 {
3524         return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3525                                         &special_mapping_vmops);
3526 }
3527
3528 int install_special_mapping(struct mm_struct *mm,
3529                             unsigned long addr, unsigned long len,
3530                             unsigned long vm_flags, struct page **pages)
3531 {
3532         struct vm_area_struct *vma = __install_special_mapping(
3533                 mm, addr, len, vm_flags, (void *)pages,
3534                 &legacy_special_mapping_vmops);
3535
3536         return PTR_ERR_OR_ZERO(vma);
3537 }
3538
3539 static DEFINE_MUTEX(mm_all_locks_mutex);
3540
3541 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3542 {
3543         if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3544                 /*
3545                  * The LSB of head.next can't change from under us
3546                  * because we hold the mm_all_locks_mutex.
3547                  */
3548                 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3549                 /*
3550                  * We can safely modify head.next after taking the
3551                  * anon_vma->root->rwsem. If some other vma in this mm shares
3552                  * the same anon_vma we won't take it again.
3553                  *
3554                  * No need of atomic instructions here, head.next
3555                  * can't change from under us thanks to the
3556                  * anon_vma->root->rwsem.
3557                  */
3558                 if (__test_and_set_bit(0, (unsigned long *)
3559                                        &anon_vma->root->rb_root.rb_root.rb_node))
3560                         BUG();
3561         }
3562 }
3563
3564 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3565 {
3566         if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3567                 /*
3568                  * AS_MM_ALL_LOCKS can't change from under us because
3569                  * we hold the mm_all_locks_mutex.
3570                  *
3571                  * Operations on ->flags have to be atomic because
3572                  * even if AS_MM_ALL_LOCKS is stable thanks to the
3573                  * mm_all_locks_mutex, there may be other cpus
3574                  * changing other bitflags in parallel to us.
3575                  */
3576                 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3577                         BUG();
3578                 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3579         }
3580 }
3581
3582 /*
3583  * This operation locks against the VM for all pte/vma/mm related
3584  * operations that could ever happen on a certain mm. This includes
3585  * vmtruncate, try_to_unmap, and all page faults.
3586  *
3587  * The caller must take the mmap_lock in write mode before calling
3588  * mm_take_all_locks(). The caller isn't allowed to release the
3589  * mmap_lock until mm_drop_all_locks() returns.
3590  *
3591  * mmap_lock in write mode is required in order to block all operations
3592  * that could modify pagetables and free pages without need of
3593  * altering the vma layout. It's also needed in write mode to avoid new
3594  * anon_vmas to be associated with existing vmas.
3595  *
3596  * A single task can't take more than one mm_take_all_locks() in a row
3597  * or it would deadlock.
3598  *
3599  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3600  * mapping->flags avoid to take the same lock twice, if more than one
3601  * vma in this mm is backed by the same anon_vma or address_space.
3602  *
3603  * We take locks in following order, accordingly to comment at beginning
3604  * of mm/rmap.c:
3605  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3606  *     hugetlb mapping);
3607  *   - all i_mmap_rwsem locks;
3608  *   - all anon_vma->rwseml
3609  *
3610  * We can take all locks within these types randomly because the VM code
3611  * doesn't nest them and we protected from parallel mm_take_all_locks() by
3612  * mm_all_locks_mutex.
3613  *
3614  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3615  * that may have to take thousand of locks.
3616  *
3617  * mm_take_all_locks() can fail if it's interrupted by signals.
3618  */
3619 int mm_take_all_locks(struct mm_struct *mm)
3620 {
3621         struct vm_area_struct *vma;
3622         struct anon_vma_chain *avc;
3623
3624         mmap_assert_write_locked(mm);
3625
3626         mutex_lock(&mm_all_locks_mutex);
3627
3628         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3629                 if (signal_pending(current))
3630                         goto out_unlock;
3631                 if (vma->vm_file && vma->vm_file->f_mapping &&
3632                                 is_vm_hugetlb_page(vma))
3633                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
3634         }
3635
3636         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3637                 if (signal_pending(current))
3638                         goto out_unlock;
3639                 if (vma->vm_file && vma->vm_file->f_mapping &&
3640                                 !is_vm_hugetlb_page(vma))
3641                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
3642         }
3643
3644         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3645                 if (signal_pending(current))
3646                         goto out_unlock;
3647                 if (vma->anon_vma)
3648                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3649                                 vm_lock_anon_vma(mm, avc->anon_vma);
3650         }
3651
3652         return 0;
3653
3654 out_unlock:
3655         mm_drop_all_locks(mm);
3656         return -EINTR;
3657 }
3658
3659 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3660 {
3661         if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3662                 /*
3663                  * The LSB of head.next can't change to 0 from under
3664                  * us because we hold the mm_all_locks_mutex.
3665                  *
3666                  * We must however clear the bitflag before unlocking
3667                  * the vma so the users using the anon_vma->rb_root will
3668                  * never see our bitflag.
3669                  *
3670                  * No need of atomic instructions here, head.next
3671                  * can't change from under us until we release the
3672                  * anon_vma->root->rwsem.
3673                  */
3674                 if (!__test_and_clear_bit(0, (unsigned long *)
3675                                           &anon_vma->root->rb_root.rb_root.rb_node))
3676                         BUG();
3677                 anon_vma_unlock_write(anon_vma);
3678         }
3679 }
3680
3681 static void vm_unlock_mapping(struct address_space *mapping)
3682 {
3683         if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3684                 /*
3685                  * AS_MM_ALL_LOCKS can't change to 0 from under us
3686                  * because we hold the mm_all_locks_mutex.
3687                  */
3688                 i_mmap_unlock_write(mapping);
3689                 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3690                                         &mapping->flags))
3691                         BUG();
3692         }
3693 }
3694
3695 /*
3696  * The mmap_lock cannot be released by the caller until
3697  * mm_drop_all_locks() returns.
3698  */
3699 void mm_drop_all_locks(struct mm_struct *mm)
3700 {
3701         struct vm_area_struct *vma;
3702         struct anon_vma_chain *avc;
3703
3704         mmap_assert_write_locked(mm);
3705         BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3706
3707         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3708                 if (vma->anon_vma)
3709                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3710                                 vm_unlock_anon_vma(avc->anon_vma);
3711                 if (vma->vm_file && vma->vm_file->f_mapping)
3712                         vm_unlock_mapping(vma->vm_file->f_mapping);
3713         }
3714
3715         mutex_unlock(&mm_all_locks_mutex);
3716 }
3717
3718 /*
3719  * initialise the percpu counter for VM
3720  */
3721 void __init mmap_init(void)
3722 {
3723         int ret;
3724
3725         ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3726         VM_BUG_ON(ret);
3727 }
3728
3729 /*
3730  * Initialise sysctl_user_reserve_kbytes.
3731  *
3732  * This is intended to prevent a user from starting a single memory hogging
3733  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3734  * mode.
3735  *
3736  * The default value is min(3% of free memory, 128MB)
3737  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3738  */
3739 static int init_user_reserve(void)
3740 {
3741         unsigned long free_kbytes;
3742
3743         free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3744
3745         sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3746         return 0;
3747 }
3748 subsys_initcall(init_user_reserve);
3749
3750 /*
3751  * Initialise sysctl_admin_reserve_kbytes.
3752  *
3753  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3754  * to log in and kill a memory hogging process.
3755  *
3756  * Systems with more than 256MB will reserve 8MB, enough to recover
3757  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3758  * only reserve 3% of free pages by default.
3759  */
3760 static int init_admin_reserve(void)
3761 {
3762         unsigned long free_kbytes;
3763
3764         free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3765
3766         sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3767         return 0;
3768 }
3769 subsys_initcall(init_admin_reserve);
3770
3771 /*
3772  * Reinititalise user and admin reserves if memory is added or removed.
3773  *
3774  * The default user reserve max is 128MB, and the default max for the
3775  * admin reserve is 8MB. These are usually, but not always, enough to
3776  * enable recovery from a memory hogging process using login/sshd, a shell,
3777  * and tools like top. It may make sense to increase or even disable the
3778  * reserve depending on the existence of swap or variations in the recovery
3779  * tools. So, the admin may have changed them.
3780  *
3781  * If memory is added and the reserves have been eliminated or increased above
3782  * the default max, then we'll trust the admin.
3783  *
3784  * If memory is removed and there isn't enough free memory, then we
3785  * need to reset the reserves.
3786  *
3787  * Otherwise keep the reserve set by the admin.
3788  */
3789 static int reserve_mem_notifier(struct notifier_block *nb,
3790                              unsigned long action, void *data)
3791 {
3792         unsigned long tmp, free_kbytes;
3793
3794         switch (action) {
3795         case MEM_ONLINE:
3796                 /* Default max is 128MB. Leave alone if modified by operator. */
3797                 tmp = sysctl_user_reserve_kbytes;
3798                 if (0 < tmp && tmp < (1UL << 17))
3799                         init_user_reserve();
3800
3801                 /* Default max is 8MB.  Leave alone if modified by operator. */
3802                 tmp = sysctl_admin_reserve_kbytes;
3803                 if (0 < tmp && tmp < (1UL << 13))
3804                         init_admin_reserve();
3805
3806                 break;
3807         case MEM_OFFLINE:
3808                 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3809
3810                 if (sysctl_user_reserve_kbytes > free_kbytes) {
3811                         init_user_reserve();
3812                         pr_info("vm.user_reserve_kbytes reset to %lu\n",
3813                                 sysctl_user_reserve_kbytes);
3814                 }
3815
3816                 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3817                         init_admin_reserve();
3818                         pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3819                                 sysctl_admin_reserve_kbytes);
3820                 }
3821                 break;
3822         default:
3823                 break;
3824         }
3825         return NOTIFY_OK;
3826 }
3827
3828 static struct notifier_block reserve_mem_nb = {
3829         .notifier_call = reserve_mem_notifier,
3830 };
3831
3832 static int __meminit init_reserve_notifier(void)
3833 {
3834         if (register_hotmemory_notifier(&reserve_mem_nb))
3835                 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3836
3837         return 0;
3838 }
3839 subsys_initcall(init_reserve_notifier);