948264cd39cdcfda4beb717fded1ac5944a13e37
[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 static unsigned long unmapped_area(struct vm_unmapped_area_info *info)
2017 {
2018         /*
2019          * We implement the search by looking for an rbtree node that
2020          * immediately follows a suitable gap. That is,
2021          * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
2022          * - gap_end   = vma->vm_start        >= info->low_limit  + length;
2023          * - gap_end - gap_start >= length
2024          */
2025
2026         struct mm_struct *mm = current->mm;
2027         struct vm_area_struct *vma;
2028         unsigned long length, low_limit, high_limit, gap_start, gap_end;
2029         unsigned long gap;
2030         MA_STATE(mas, &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         mas_empty_area(&mas, info->low_limit, info->high_limit - 1,
2038                            length);
2039         gap = mas.index;
2040         gap += (info->align_offset - gap) & info->align_mask;
2041
2042         /* Adjust search limits by the desired length */
2043         if (info->high_limit < length)
2044                 return -ENOMEM;
2045         high_limit = info->high_limit - length;
2046
2047         if (info->low_limit > high_limit)
2048                 return -ENOMEM;
2049         low_limit = info->low_limit + length;
2050
2051         /* Check if rbtree root looks promising */
2052         if (RB_EMPTY_ROOT(&mm->mm_rb))
2053                 goto check_highest;
2054         vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
2055         if (vma->rb_subtree_gap < length)
2056                 goto check_highest;
2057
2058         while (true) {
2059                 /* Visit left subtree if it looks promising */
2060                 gap_end = vm_start_gap(vma);
2061                 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
2062                         struct vm_area_struct *left =
2063                                 rb_entry(vma->vm_rb.rb_left,
2064                                          struct vm_area_struct, vm_rb);
2065                         if (left->rb_subtree_gap >= length) {
2066                                 vma = left;
2067                                 continue;
2068                         }
2069                 }
2070
2071                 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
2072 check_current:
2073                 /* Check if current node has a suitable gap */
2074                 if (gap_start > high_limit)
2075                         return -ENOMEM;
2076                 if (gap_end >= low_limit &&
2077                     gap_end > gap_start && gap_end - gap_start >= length)
2078                         goto found;
2079
2080                 /* Visit right subtree if it looks promising */
2081                 if (vma->vm_rb.rb_right) {
2082                         struct vm_area_struct *right =
2083                                 rb_entry(vma->vm_rb.rb_right,
2084                                          struct vm_area_struct, vm_rb);
2085                         if (right->rb_subtree_gap >= length) {
2086                                 vma = right;
2087                                 continue;
2088                         }
2089                 }
2090
2091                 /* Go back up the rbtree to find next candidate node */
2092                 while (true) {
2093                         struct rb_node *prev = &vma->vm_rb;
2094                         if (!rb_parent(prev))
2095                                 goto check_highest;
2096                         vma = rb_entry(rb_parent(prev),
2097                                        struct vm_area_struct, vm_rb);
2098                         if (prev == vma->vm_rb.rb_left) {
2099                                 gap_start = vm_end_gap(vma->vm_prev);
2100                                 gap_end = vm_start_gap(vma);
2101                                 goto check_current;
2102                         }
2103                 }
2104         }
2105
2106 check_highest:
2107         /* Check highest gap, which does not precede any rbtree node */
2108         gap_start = mm->highest_vm_end;
2109         gap_end = ULONG_MAX;  /* Only for VM_BUG_ON below */
2110         if (gap_start > high_limit)
2111                 return -ENOMEM;
2112
2113 found:
2114         /* We found a suitable gap. Clip it with the original low_limit. */
2115         if (gap_start < info->low_limit)
2116                 gap_start = info->low_limit;
2117
2118         /* Adjust gap address to the desired alignment */
2119         gap_start += (info->align_offset - gap_start) & info->align_mask;
2120
2121         VM_BUG_ON(gap_start + info->length > info->high_limit);
2122         VM_BUG_ON(gap_start + info->length > gap_end);
2123
2124         VM_BUG_ON(gap != gap_start);
2125         return gap_start;
2126 }
2127
2128 static unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
2129 {
2130         struct mm_struct *mm = current->mm;
2131         struct vm_area_struct *vma = NULL;
2132         unsigned long length, low_limit, high_limit, gap_start, gap_end;
2133         unsigned long gap;
2134
2135         MA_STATE(mas, &mm->mm_mt, 0, 0);
2136         validate_mm_mt(mm);
2137
2138         /* Adjust search length to account for worst case alignment overhead */
2139         length = info->length + info->align_mask;
2140         if (length < info->length)
2141                 return -ENOMEM;
2142
2143         mas_empty_area_rev(&mas, info->low_limit, info->high_limit - 1,
2144                    length);
2145         gap = mas.last + 1 - info->length;
2146         gap -= (gap - info->align_offset) & info->align_mask;
2147
2148         /*
2149          * Adjust search limits by the desired length.
2150          * See implementation comment at top of unmapped_area().
2151          */
2152         gap_end = info->high_limit;
2153         if (gap_end < length)
2154                 return -ENOMEM;
2155         high_limit = gap_end - length;
2156
2157         if (info->low_limit > high_limit)
2158                 return -ENOMEM;
2159         low_limit = info->low_limit + length;
2160
2161         /* Check highest gap, which does not precede any rbtree node */
2162         gap_start = mm->highest_vm_end;
2163         if (gap_start <= high_limit)
2164                 goto found_highest;
2165
2166         /* Check if rbtree root looks promising */
2167         if (RB_EMPTY_ROOT(&mm->mm_rb))
2168                 return -ENOMEM;
2169         vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
2170         if (vma->rb_subtree_gap < length)
2171                 return -ENOMEM;
2172
2173         while (true) {
2174                 /* Visit right subtree if it looks promising */
2175                 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
2176                 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
2177                         struct vm_area_struct *right =
2178                                 rb_entry(vma->vm_rb.rb_right,
2179                                          struct vm_area_struct, vm_rb);
2180                         if (right->rb_subtree_gap >= length) {
2181                                 vma = right;
2182                                 continue;
2183                         }
2184                 }
2185
2186 check_current:
2187                 /* Check if current node has a suitable gap */
2188                 gap_end = vm_start_gap(vma);
2189                 if (gap_end < low_limit)
2190                         return -ENOMEM;
2191                 if (gap_start <= high_limit &&
2192                     gap_end > gap_start && gap_end - gap_start >= length)
2193                         goto found;
2194
2195                 /* Visit left subtree if it looks promising */
2196                 if (vma->vm_rb.rb_left) {
2197                         struct vm_area_struct *left =
2198                                 rb_entry(vma->vm_rb.rb_left,
2199                                          struct vm_area_struct, vm_rb);
2200                         if (left->rb_subtree_gap >= length) {
2201                                 vma = left;
2202                                 continue;
2203                         }
2204                 }
2205
2206                 /* Go back up the rbtree to find next candidate node */
2207                 while (true) {
2208                         struct rb_node *prev = &vma->vm_rb;
2209                         if (!rb_parent(prev))
2210                                 return -ENOMEM;
2211                         vma = rb_entry(rb_parent(prev),
2212                                        struct vm_area_struct, vm_rb);
2213                         if (prev == vma->vm_rb.rb_right) {
2214                                 gap_start = vma->vm_prev ?
2215                                         vm_end_gap(vma->vm_prev) : 0;
2216                                 goto check_current;
2217                         }
2218                 }
2219         }
2220
2221 found:
2222         /* We found a suitable gap. Clip it with the original high_limit. */
2223         if (gap_end > info->high_limit)
2224                 gap_end = info->high_limit;
2225
2226 found_highest:
2227         /* Compute highest gap address at the desired alignment */
2228         gap_end -= info->length;
2229         gap_end -= (gap_end - info->align_offset) & info->align_mask;
2230
2231         VM_BUG_ON(gap_end < info->low_limit);
2232         VM_BUG_ON(gap_end < gap_start);
2233
2234         if (gap != gap_end) {
2235                 pr_err("%s: %p Gap was found: mt %lu gap_end %lu\n", __func__,
2236                        mm, gap, gap_end);
2237                 pr_err("window was %lu - %lu size %lu\n", info->high_limit,
2238                        info->low_limit, length);
2239                 pr_err("mas.min %lu max %lu mas.last %lu\n", mas.min, mas.max,
2240                        mas.last);
2241                 pr_err("mas.index %lu align mask %lu offset %lu\n", mas.index,
2242                        info->align_mask, info->align_offset);
2243                 pr_err("rb_find_vma find on %lu => %p (%p)\n", mas.index,
2244                        find_vma(mm, mas.index), vma);
2245 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2246                 mt_dump(&mm->mm_mt);
2247 #endif
2248                 {
2249                         struct vm_area_struct *dv = mm->mmap;
2250
2251                         while (dv) {
2252                                 pr_err("vma %p %lu-%lu\n", dv, dv->vm_start, dv->vm_end);
2253                                 dv = dv->vm_next;
2254                         }
2255                 }
2256                 VM_BUG_ON(gap != gap_end);
2257         }
2258
2259         return gap_end;
2260 }
2261
2262 /*
2263  * Search for an unmapped address range.
2264  *
2265  * We are looking for a range that:
2266  * - does not intersect with any VMA;
2267  * - is contained within the [low_limit, high_limit) interval;
2268  * - is at least the desired size.
2269  * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
2270  */
2271 unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
2272 {
2273         unsigned long addr;
2274
2275         if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
2276                 addr = unmapped_area_topdown(info);
2277         else
2278                 addr = unmapped_area(info);
2279
2280         trace_vm_unmapped_area(addr, info);
2281         return addr;
2282 }
2283
2284 /* Get an address range which is currently unmapped.
2285  * For shmat() with addr=0.
2286  *
2287  * Ugly calling convention alert:
2288  * Return value with the low bits set means error value,
2289  * ie
2290  *      if (ret & ~PAGE_MASK)
2291  *              error = ret;
2292  *
2293  * This function "knows" that -ENOMEM has the bits set.
2294  */
2295 unsigned long
2296 generic_get_unmapped_area(struct file *filp, unsigned long addr,
2297                           unsigned long len, unsigned long pgoff,
2298                           unsigned long flags)
2299 {
2300         struct mm_struct *mm = current->mm;
2301         struct vm_area_struct *vma, *prev;
2302         struct vm_unmapped_area_info info;
2303         const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
2304
2305         if (len > mmap_end - mmap_min_addr)
2306                 return -ENOMEM;
2307
2308         if (flags & MAP_FIXED)
2309                 return addr;
2310
2311         if (addr) {
2312                 addr = PAGE_ALIGN(addr);
2313                 vma = find_vma_prev(mm, addr, &prev);
2314                 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2315                     (!vma || addr + len <= vm_start_gap(vma)) &&
2316                     (!prev || addr >= vm_end_gap(prev)))
2317                         return addr;
2318         }
2319
2320         info.flags = 0;
2321         info.length = len;
2322         info.low_limit = mm->mmap_base;
2323         info.high_limit = mmap_end;
2324         info.align_mask = 0;
2325         info.align_offset = 0;
2326         return vm_unmapped_area(&info);
2327 }
2328
2329 #ifndef HAVE_ARCH_UNMAPPED_AREA
2330 unsigned long
2331 arch_get_unmapped_area(struct file *filp, unsigned long addr,
2332                        unsigned long len, unsigned long pgoff,
2333                        unsigned long flags)
2334 {
2335         return generic_get_unmapped_area(filp, addr, len, pgoff, flags);
2336 }
2337 #endif
2338
2339 /*
2340  * This mmap-allocator allocates new areas top-down from below the
2341  * stack's low limit (the base):
2342  */
2343 unsigned long
2344 generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2345                                   unsigned long len, unsigned long pgoff,
2346                                   unsigned long flags)
2347 {
2348         struct vm_area_struct *vma, *prev;
2349         struct mm_struct *mm = current->mm;
2350         struct vm_unmapped_area_info info;
2351         const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
2352
2353         /* requested length too big for entire address space */
2354         if (len > mmap_end - mmap_min_addr)
2355                 return -ENOMEM;
2356
2357         if (flags & MAP_FIXED)
2358                 return addr;
2359
2360         /* requesting a specific address */
2361         if (addr) {
2362                 addr = PAGE_ALIGN(addr);
2363                 vma = find_vma_prev(mm, addr, &prev);
2364                 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2365                                 (!vma || addr + len <= vm_start_gap(vma)) &&
2366                                 (!prev || addr >= vm_end_gap(prev)))
2367                         return addr;
2368         }
2369
2370         info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2371         info.length = len;
2372         info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2373         info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
2374         info.align_mask = 0;
2375         info.align_offset = 0;
2376         addr = vm_unmapped_area(&info);
2377
2378         /*
2379          * A failed mmap() very likely causes application failure,
2380          * so fall back to the bottom-up function here. This scenario
2381          * can happen with large stack limits and large mmap()
2382          * allocations.
2383          */
2384         if (offset_in_page(addr)) {
2385                 VM_BUG_ON(addr != -ENOMEM);
2386                 info.flags = 0;
2387                 info.low_limit = TASK_UNMAPPED_BASE;
2388                 info.high_limit = mmap_end;
2389                 addr = vm_unmapped_area(&info);
2390         }
2391
2392         return addr;
2393 }
2394
2395 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
2396 unsigned long
2397 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2398                                unsigned long len, unsigned long pgoff,
2399                                unsigned long flags)
2400 {
2401         return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags);
2402 }
2403 #endif
2404
2405 unsigned long
2406 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
2407                 unsigned long pgoff, unsigned long flags)
2408 {
2409         unsigned long (*get_area)(struct file *, unsigned long,
2410                                   unsigned long, unsigned long, unsigned long);
2411
2412         unsigned long error = arch_mmap_check(addr, len, flags);
2413         if (error)
2414                 return error;
2415
2416         /* Careful about overflows.. */
2417         if (len > TASK_SIZE)
2418                 return -ENOMEM;
2419
2420         get_area = current->mm->get_unmapped_area;
2421         if (file) {
2422                 if (file->f_op->get_unmapped_area)
2423                         get_area = file->f_op->get_unmapped_area;
2424         } else if (flags & MAP_SHARED) {
2425                 /*
2426                  * mmap_region() will call shmem_zero_setup() to create a file,
2427                  * so use shmem's get_unmapped_area in case it can be huge.
2428                  * do_mmap() will clear pgoff, so match alignment.
2429                  */
2430                 pgoff = 0;
2431                 get_area = shmem_get_unmapped_area;
2432         } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
2433                 /* Ensures that larger anonymous mappings are THP aligned. */
2434                 get_area = thp_get_unmapped_area;
2435         }
2436
2437         addr = get_area(file, addr, len, pgoff, flags);
2438         if (IS_ERR_VALUE(addr))
2439                 return addr;
2440
2441         if (addr > TASK_SIZE - len)
2442                 return -ENOMEM;
2443         if (offset_in_page(addr))
2444                 return -EINVAL;
2445
2446         error = security_mmap_addr(addr);
2447         return error ? error : addr;
2448 }
2449
2450 EXPORT_SYMBOL(get_unmapped_area);
2451
2452 /**
2453  * find_vma() - Find the VMA for a given address, or the next VMA.
2454  * @mm: The mm_struct to check
2455  * @addr: The address
2456  *
2457  * Returns: The VMA associated with addr, or the next VMA.
2458  * May return %NULL in the case of no VMA at addr or above.
2459  */
2460 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2461 {
2462         struct vm_area_struct *vma;
2463         unsigned long index = addr;
2464
2465         mmap_assert_locked(mm);
2466         /* Check the cache first. */
2467         vma = vmacache_find(mm, addr);
2468         if (likely(vma))
2469                 return vma;
2470
2471         vma = mt_find(&mm->mm_mt, &index, ULONG_MAX);
2472         if (vma)
2473                 vmacache_update(addr, vma);
2474         return vma;
2475 }
2476 EXPORT_SYMBOL(find_vma);
2477
2478 /**
2479  * find_vma_prev() - Find the VMA for a given address, or the next vma and
2480  * set %pprev to the previous VMA, if any.
2481  * @mm: The mm_struct to check
2482  * @addr: The address
2483  * @pprev: The pointer to set to the previous VMA
2484  *
2485  * Note that RCU lock is missing here since the external mmap_lock() is used
2486  * instead.
2487  *
2488  * Returns: The VMA associated with @addr, or the next vma.
2489  * May return %NULL in the case of no vma at addr or above.
2490  */
2491 struct vm_area_struct *
2492 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2493                         struct vm_area_struct **pprev)
2494 {
2495         struct vm_area_struct *vma;
2496         MA_STATE(mas, &mm->mm_mt, addr, addr);
2497
2498         vma = mas_walk(&mas);
2499         *pprev = mas_prev(&mas, 0);
2500         if (!vma)
2501                 vma = mas_next(&mas, ULONG_MAX);
2502         return vma;
2503 }
2504
2505 /*
2506  * Verify that the stack growth is acceptable and
2507  * update accounting. This is shared with both the
2508  * grow-up and grow-down cases.
2509  */
2510 static int acct_stack_growth(struct vm_area_struct *vma,
2511                              unsigned long size, unsigned long grow)
2512 {
2513         struct mm_struct *mm = vma->vm_mm;
2514         unsigned long new_start;
2515
2516         /* address space limit tests */
2517         if (!may_expand_vm(mm, vma->vm_flags, grow))
2518                 return -ENOMEM;
2519
2520         /* Stack limit test */
2521         if (size > rlimit(RLIMIT_STACK))
2522                 return -ENOMEM;
2523
2524         /* mlock limit tests */
2525         if (mlock_future_check(mm, vma->vm_flags, grow << PAGE_SHIFT))
2526                 return -ENOMEM;
2527
2528         /* Check to ensure the stack will not grow into a hugetlb-only region */
2529         new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2530                         vma->vm_end - size;
2531         if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2532                 return -EFAULT;
2533
2534         /*
2535          * Overcommit..  This must be the final test, as it will
2536          * update security statistics.
2537          */
2538         if (security_vm_enough_memory_mm(mm, grow))
2539                 return -ENOMEM;
2540
2541         return 0;
2542 }
2543
2544 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2545 /*
2546  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2547  * vma is the last one with address > vma->vm_end.  Have to extend vma.
2548  */
2549 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2550 {
2551         struct mm_struct *mm = vma->vm_mm;
2552         struct vm_area_struct *next;
2553         unsigned long gap_addr;
2554         int error = 0;
2555         MA_STATE(mas, &mm->mm_mt, 0, 0);
2556
2557         validate_mm_mt(mm);
2558         if (!(vma->vm_flags & VM_GROWSUP))
2559                 return -EFAULT;
2560
2561         /* Guard against exceeding limits of the address space. */
2562         address &= PAGE_MASK;
2563         if (address >= (TASK_SIZE & PAGE_MASK))
2564                 return -ENOMEM;
2565         address += PAGE_SIZE;
2566
2567         /* Enforce stack_guard_gap */
2568         gap_addr = address + stack_guard_gap;
2569
2570         /* Guard against overflow */
2571         if (gap_addr < address || gap_addr > TASK_SIZE)
2572                 gap_addr = TASK_SIZE;
2573
2574         next = vma->vm_next;
2575         if (next && next->vm_start < gap_addr && vma_is_accessible(next)) {
2576                 if (!(next->vm_flags & VM_GROWSUP))
2577                         return -ENOMEM;
2578                 /* Check that both stack segments have the same anon_vma? */
2579         }
2580
2581         if (mas_preallocate(&mas, vma, GFP_KERNEL))
2582                 return -ENOMEM;
2583
2584         /* We must make sure the anon_vma is allocated. */
2585         if (unlikely(anon_vma_prepare(vma))) {
2586                 mas_destroy(&mas);
2587                 return -ENOMEM;
2588         }
2589
2590         /*
2591          * vma->vm_start/vm_end cannot change under us because the caller
2592          * is required to hold the mmap_lock in read mode.  We need the
2593          * anon_vma lock to serialize against concurrent expand_stacks.
2594          */
2595         anon_vma_lock_write(vma->anon_vma);
2596
2597         /* Somebody else might have raced and expanded it already */
2598         if (address > vma->vm_end) {
2599                 unsigned long size, grow;
2600
2601                 size = address - vma->vm_start;
2602                 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2603
2604                 error = -ENOMEM;
2605                 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2606                         error = acct_stack_growth(vma, size, grow);
2607                         if (!error) {
2608                                 /*
2609                                  * vma_gap_update() doesn't support concurrent
2610                                  * updates, but we only hold a shared mmap_lock
2611                                  * lock here, so we need to protect against
2612                                  * concurrent vma expansions.
2613                                  * anon_vma_lock_write() doesn't help here, as
2614                                  * we don't guarantee that all growable vmas
2615                                  * in a mm share the same root anon vma.
2616                                  * So, we reuse mm->page_table_lock to guard
2617                                  * against concurrent vma expansions.
2618                                  */
2619                                 spin_lock(&mm->page_table_lock);
2620                                 if (vma->vm_flags & VM_LOCKED)
2621                                         mm->locked_vm += grow;
2622                                 vm_stat_account(mm, vma->vm_flags, grow);
2623                                 anon_vma_interval_tree_pre_update_vma(vma);
2624                                 vma->vm_end = address;
2625                                 /* Overwrite old entry in mtree. */
2626                                 vma_mas_store(vma, &mas);
2627                                 anon_vma_interval_tree_post_update_vma(vma);
2628                                 if (vma->vm_next)
2629                                         vma_gap_update(vma->vm_next);
2630                                 else
2631                                         mm->highest_vm_end = vm_end_gap(vma);
2632                                 spin_unlock(&mm->page_table_lock);
2633
2634                                 perf_event_mmap(vma);
2635                         }
2636                 }
2637         }
2638         anon_vma_unlock_write(vma->anon_vma);
2639         khugepaged_enter_vma(vma, vma->vm_flags);
2640         validate_mm(mm);
2641         validate_mm_mt(mm);
2642         mas_destroy(&mas);
2643         return error;
2644 }
2645 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2646
2647 /*
2648  * vma is the first one with address < vma->vm_start.  Have to extend vma.
2649  */
2650 int expand_downwards(struct vm_area_struct *vma,
2651                                    unsigned long address)
2652 {
2653         struct mm_struct *mm = vma->vm_mm;
2654         struct vm_area_struct *prev;
2655         int error = 0;
2656         MA_STATE(mas, &mm->mm_mt, 0, 0);
2657
2658         validate_mm(mm);
2659         address &= PAGE_MASK;
2660         if (address < mmap_min_addr)
2661                 return -EPERM;
2662
2663         /* Enforce stack_guard_gap */
2664         prev = vma->vm_prev;
2665         /* Check that both stack segments have the same anon_vma? */
2666         if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
2667                         vma_is_accessible(prev)) {
2668                 if (address - prev->vm_end < stack_guard_gap)
2669                         return -ENOMEM;
2670         }
2671
2672         if (mas_preallocate(&mas, vma, GFP_KERNEL))
2673                 return -ENOMEM;
2674
2675         /* We must make sure the anon_vma is allocated. */
2676         if (unlikely(anon_vma_prepare(vma))) {
2677                 mas_destroy(&mas);
2678                 return -ENOMEM;
2679         }
2680
2681         /*
2682          * vma->vm_start/vm_end cannot change under us because the caller
2683          * is required to hold the mmap_lock in read mode.  We need the
2684          * anon_vma lock to serialize against concurrent expand_stacks.
2685          */
2686         anon_vma_lock_write(vma->anon_vma);
2687
2688         /* Somebody else might have raced and expanded it already */
2689         if (address < vma->vm_start) {
2690                 unsigned long size, grow;
2691
2692                 size = vma->vm_end - address;
2693                 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2694
2695                 error = -ENOMEM;
2696                 if (grow <= vma->vm_pgoff) {
2697                         error = acct_stack_growth(vma, size, grow);
2698                         if (!error) {
2699                                 /*
2700                                  * vma_gap_update() doesn't support concurrent
2701                                  * updates, but we only hold a shared mmap_lock
2702                                  * lock here, so we need to protect against
2703                                  * concurrent vma expansions.
2704                                  * anon_vma_lock_write() doesn't help here, as
2705                                  * we don't guarantee that all growable vmas
2706                                  * in a mm share the same root anon vma.
2707                                  * So, we reuse mm->page_table_lock to guard
2708                                  * against concurrent vma expansions.
2709                                  */
2710                                 spin_lock(&mm->page_table_lock);
2711                                 if (vma->vm_flags & VM_LOCKED)
2712                                         mm->locked_vm += grow;
2713                                 vm_stat_account(mm, vma->vm_flags, grow);
2714                                 anon_vma_interval_tree_pre_update_vma(vma);
2715                                 vma->vm_start = address;
2716                                 vma->vm_pgoff -= grow;
2717                                 /* Overwrite old entry in mtree. */
2718                                 vma_mas_store(vma, &mas);
2719                                 anon_vma_interval_tree_post_update_vma(vma);
2720                                 vma_gap_update(vma);
2721                                 spin_unlock(&mm->page_table_lock);
2722
2723                                 perf_event_mmap(vma);
2724                         }
2725                 }
2726         }
2727         anon_vma_unlock_write(vma->anon_vma);
2728         khugepaged_enter_vma(vma, vma->vm_flags);
2729         validate_mm(mm);
2730         mas_destroy(&mas);
2731         return error;
2732 }
2733
2734 /* enforced gap between the expanding stack and other mappings. */
2735 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2736
2737 static int __init cmdline_parse_stack_guard_gap(char *p)
2738 {
2739         unsigned long val;
2740         char *endptr;
2741
2742         val = simple_strtoul(p, &endptr, 10);
2743         if (!*endptr)
2744                 stack_guard_gap = val << PAGE_SHIFT;
2745
2746         return 1;
2747 }
2748 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2749
2750 #ifdef CONFIG_STACK_GROWSUP
2751 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2752 {
2753         return expand_upwards(vma, address);
2754 }
2755
2756 struct vm_area_struct *
2757 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2758 {
2759         struct vm_area_struct *vma, *prev;
2760
2761         addr &= PAGE_MASK;
2762         vma = find_vma_prev(mm, addr, &prev);
2763         if (vma && (vma->vm_start <= addr))
2764                 return vma;
2765         if (!prev || expand_stack(prev, addr))
2766                 return NULL;
2767         if (prev->vm_flags & VM_LOCKED)
2768                 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2769         return prev;
2770 }
2771 #else
2772 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2773 {
2774         return expand_downwards(vma, address);
2775 }
2776
2777 struct vm_area_struct *
2778 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2779 {
2780         struct vm_area_struct *vma;
2781         unsigned long start;
2782
2783         addr &= PAGE_MASK;
2784         vma = find_vma(mm, addr);
2785         if (!vma)
2786                 return NULL;
2787         if (vma->vm_start <= addr)
2788                 return vma;
2789         if (!(vma->vm_flags & VM_GROWSDOWN))
2790                 return NULL;
2791         start = vma->vm_start;
2792         if (expand_stack(vma, addr))
2793                 return NULL;
2794         if (vma->vm_flags & VM_LOCKED)
2795                 populate_vma_page_range(vma, addr, start, NULL);
2796         return vma;
2797 }
2798 #endif
2799
2800 EXPORT_SYMBOL_GPL(find_extend_vma);
2801
2802 /*
2803  * Ok - we have the memory areas we should free on the vma list,
2804  * so release them, and do the vma updates.
2805  *
2806  * Called with the mm semaphore held.
2807  */
2808 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2809 {
2810         unsigned long nr_accounted = 0;
2811
2812         /* Update high watermark before we lower total_vm */
2813         update_hiwater_vm(mm);
2814         do {
2815                 long nrpages = vma_pages(vma);
2816
2817                 if (vma->vm_flags & VM_ACCOUNT)
2818                         nr_accounted += nrpages;
2819                 vm_stat_account(mm, vma->vm_flags, -nrpages);
2820                 vma = remove_vma(vma);
2821         } while (vma);
2822         vm_unacct_memory(nr_accounted);
2823         validate_mm(mm);
2824 }
2825
2826 /*
2827  * Get rid of page table information in the indicated region.
2828  *
2829  * Called with the mm semaphore held.
2830  */
2831 static void unmap_region(struct mm_struct *mm,
2832                 struct vm_area_struct *vma, struct vm_area_struct *prev,
2833                 unsigned long start, unsigned long end)
2834 {
2835         struct vm_area_struct *next = __vma_next(mm, prev);
2836         struct mmu_gather tlb;
2837
2838         lru_add_drain();
2839         tlb_gather_mmu(&tlb, mm);
2840         update_hiwater_rss(mm);
2841         unmap_vmas(&tlb, vma, start, end);
2842         free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2843                                  next ? next->vm_start : USER_PGTABLES_CEILING);
2844         tlb_finish_mmu(&tlb);
2845 }
2846
2847 /*
2848  * Create a list of vma's touched by the unmap, removing them from the mm's
2849  * vma list as we go..
2850  */
2851 static bool
2852 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct ma_state *mas,
2853         struct vm_area_struct *vma, struct vm_area_struct *prev,
2854         unsigned long end)
2855 {
2856         struct vm_area_struct **insertion_point;
2857         struct vm_area_struct *tail_vma = NULL;
2858
2859         insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2860         vma->vm_prev = NULL;
2861         mas_set_range(mas, vma->vm_start, end - 1);
2862         mas_store_prealloc(mas, NULL);
2863         do {
2864                 vma_rb_erase(vma, &mm->mm_rb);
2865                 if (vma->vm_flags & VM_LOCKED)
2866                         mm->locked_vm -= vma_pages(vma);
2867                 mm->map_count--;
2868                 tail_vma = vma;
2869                 vma = vma->vm_next;
2870         } while (vma && vma->vm_start < end);
2871         *insertion_point = vma;
2872         if (vma) {
2873                 vma->vm_prev = prev;
2874                 vma_gap_update(vma);
2875         } else
2876                 mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
2877         tail_vma->vm_next = NULL;
2878
2879         /* Kill the cache */
2880         vmacache_invalidate(mm);
2881
2882         /*
2883          * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2884          * VM_GROWSUP VMA. Such VMAs can change their size under
2885          * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2886          */
2887         if (vma && (vma->vm_flags & VM_GROWSDOWN))
2888                 return false;
2889         if (prev && (prev->vm_flags & VM_GROWSUP))
2890                 return false;
2891         return true;
2892 }
2893
2894 /*
2895  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2896  * has already been checked or doesn't make sense to fail.
2897  */
2898 int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2899                 unsigned long addr, int new_below)
2900 {
2901         struct vm_area_struct *new;
2902         int err;
2903         validate_mm_mt(mm);
2904
2905         if (vma->vm_ops && vma->vm_ops->may_split) {
2906                 err = vma->vm_ops->may_split(vma, addr);
2907                 if (err)
2908                         return err;
2909         }
2910
2911         new = vm_area_dup(vma);
2912         if (!new)
2913                 return -ENOMEM;
2914
2915         if (new_below)
2916                 new->vm_end = addr;
2917         else {
2918                 new->vm_start = addr;
2919                 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2920         }
2921
2922         err = vma_dup_policy(vma, new);
2923         if (err)
2924                 goto out_free_vma;
2925
2926         err = anon_vma_clone(new, vma);
2927         if (err)
2928                 goto out_free_mpol;
2929
2930         if (new->vm_file)
2931                 get_file(new->vm_file);
2932
2933         if (new->vm_ops && new->vm_ops->open)
2934                 new->vm_ops->open(new);
2935
2936         if (new_below)
2937                 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2938                         ((addr - new->vm_start) >> PAGE_SHIFT), new);
2939         else
2940                 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2941
2942         /* Success. */
2943         if (!err)
2944                 return 0;
2945
2946         /* Avoid vm accounting in close() operation */
2947         new->vm_start = new->vm_end;
2948         new->vm_pgoff = 0;
2949         /* Clean everything up if vma_adjust failed. */
2950         if (new->vm_ops && new->vm_ops->close)
2951                 new->vm_ops->close(new);
2952         if (new->vm_file)
2953                 fput(new->vm_file);
2954         unlink_anon_vmas(new);
2955  out_free_mpol:
2956         mpol_put(vma_policy(new));
2957  out_free_vma:
2958         vm_area_free(new);
2959         validate_mm_mt(mm);
2960         return err;
2961 }
2962
2963 /*
2964  * Split a vma into two pieces at address 'addr', a new vma is allocated
2965  * either for the first part or the tail.
2966  */
2967 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2968               unsigned long addr, int new_below)
2969 {
2970         if (mm->map_count >= sysctl_max_map_count)
2971                 return -ENOMEM;
2972
2973         return __split_vma(mm, vma, addr, new_below);
2974 }
2975
2976 /* Munmap is split into 2 main parts -- this part which finds
2977  * what needs doing, and the areas themselves, which do the
2978  * work.  This now handles partial unmappings.
2979  * Jeremy Fitzhardinge <jeremy@goop.org>
2980  */
2981 int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2982                 struct list_head *uf, bool downgrade)
2983 {
2984         unsigned long end;
2985         struct vm_area_struct *vma, *prev, *last;
2986         int error = -ENOMEM;
2987         MA_STATE(mas, &mm->mm_mt, 0, 0);
2988
2989         if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2990                 return -EINVAL;
2991
2992         len = PAGE_ALIGN(len);
2993         end = start + len;
2994         if (len == 0)
2995                 return -EINVAL;
2996
2997         /*
2998          * arch_unmap() might do unmaps itself.  It must be called
2999          * and finish any rbtree manipulation before this code
3000          * runs and also starts to manipulate the rbtree.
3001          */
3002         arch_unmap(mm, start, end);
3003
3004         /* Find the first overlapping VMA where start < vma->vm_end */
3005         vma = find_vma_intersection(mm, start, end);
3006         if (!vma)
3007                 return 0;
3008
3009         if (mas_preallocate(&mas, vma, GFP_KERNEL))
3010                 return -ENOMEM;
3011         prev = vma->vm_prev;
3012
3013         /*
3014          * If we need to split any vma, do it now to save pain later.
3015          *
3016          * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
3017          * unmapped vm_area_struct will remain in use: so lower split_vma
3018          * places tmp vma above, and higher split_vma places tmp vma below.
3019          */
3020         if (start > vma->vm_start) {
3021
3022                 /*
3023                  * Make sure that map_count on return from munmap() will
3024                  * not exceed its limit; but let map_count go just above
3025                  * its limit temporarily, to help free resources as expected.
3026                  */
3027                 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
3028                         goto map_count_exceeded;
3029
3030                 error = __split_vma(mm, vma, start, 0);
3031                 if (error)
3032                         goto split_failed;
3033                 prev = vma;
3034         }
3035
3036         /* Does it split the last one? */
3037         last = find_vma(mm, end);
3038         if (last && end > last->vm_start) {
3039                 error = __split_vma(mm, last, end, 1);
3040                 if (error)
3041                         goto split_failed;
3042         }
3043         vma = __vma_next(mm, prev);
3044
3045         if (unlikely(uf)) {
3046                 /*
3047                  * If userfaultfd_unmap_prep returns an error the vmas
3048                  * will remain split, but userland will get a
3049                  * highly unexpected error anyway. This is no
3050                  * different than the case where the first of the two
3051                  * __split_vma fails, but we don't undo the first
3052                  * split, despite we could. This is unlikely enough
3053                  * failure that it's not worth optimizing it for.
3054                  */
3055                 error = userfaultfd_unmap_prep(vma, start, end, uf);
3056                 if (error)
3057                         goto userfaultfd_error;
3058         }
3059
3060         /* Detach vmas from rbtree */
3061         if (!detach_vmas_to_be_unmapped(mm, &mas, vma, prev, end))
3062                 downgrade = false;
3063
3064         if (downgrade)
3065                 mmap_write_downgrade(mm);
3066
3067         unmap_region(mm, vma, prev, start, end);
3068
3069         /* Fix up all other VM information */
3070         remove_vma_list(mm, vma);
3071
3072         return downgrade ? 1 : 0;
3073
3074 map_count_exceeded:
3075 split_failed:
3076 userfaultfd_error:
3077         mas_destroy(&mas);
3078         return error;
3079 }
3080
3081 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
3082               struct list_head *uf)
3083 {
3084         return __do_munmap(mm, start, len, uf, false);
3085 }
3086
3087 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
3088 {
3089         int ret;
3090         struct mm_struct *mm = current->mm;
3091         LIST_HEAD(uf);
3092
3093         if (mmap_write_lock_killable(mm))
3094                 return -EINTR;
3095
3096         ret = __do_munmap(mm, start, len, &uf, downgrade);
3097         /*
3098          * Returning 1 indicates mmap_lock is downgraded.
3099          * But 1 is not legal return value of vm_munmap() and munmap(), reset
3100          * it to 0 before return.
3101          */
3102         if (ret == 1) {
3103                 mmap_read_unlock(mm);
3104                 ret = 0;
3105         } else
3106                 mmap_write_unlock(mm);
3107
3108         userfaultfd_unmap_complete(mm, &uf);
3109         return ret;
3110 }
3111
3112 int vm_munmap(unsigned long start, size_t len)
3113 {
3114         return __vm_munmap(start, len, false);
3115 }
3116 EXPORT_SYMBOL(vm_munmap);
3117
3118 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
3119 {
3120         addr = untagged_addr(addr);
3121         return __vm_munmap(addr, len, true);
3122 }
3123
3124
3125 /*
3126  * Emulation of deprecated remap_file_pages() syscall.
3127  */
3128 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
3129                 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
3130 {
3131
3132         struct mm_struct *mm = current->mm;
3133         struct vm_area_struct *vma;
3134         unsigned long populate = 0;
3135         unsigned long ret = -EINVAL;
3136         struct file *file;
3137
3138         pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
3139                      current->comm, current->pid);
3140
3141         if (prot)
3142                 return ret;
3143         start = start & PAGE_MASK;
3144         size = size & PAGE_MASK;
3145
3146         if (start + size <= start)
3147                 return ret;
3148
3149         /* Does pgoff wrap? */
3150         if (pgoff + (size >> PAGE_SHIFT) < pgoff)
3151                 return ret;
3152
3153         if (mmap_write_lock_killable(mm))
3154                 return -EINTR;
3155
3156         vma = vma_lookup(mm, start);
3157
3158         if (!vma || !(vma->vm_flags & VM_SHARED))
3159                 goto out;
3160
3161         if (start + size > vma->vm_end) {
3162                 struct vm_area_struct *next;
3163
3164                 for (next = vma->vm_next; next; next = next->vm_next) {
3165                         /* hole between vmas ? */
3166                         if (next->vm_start != next->vm_prev->vm_end)
3167                                 goto out;
3168
3169                         if (next->vm_file != vma->vm_file)
3170                                 goto out;
3171
3172                         if (next->vm_flags != vma->vm_flags)
3173                                 goto out;
3174
3175                         if (start + size <= next->vm_end)
3176                                 break;
3177                 }
3178
3179                 if (!next)
3180                         goto out;
3181         }
3182
3183         prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
3184         prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
3185         prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
3186
3187         flags &= MAP_NONBLOCK;
3188         flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
3189         if (vma->vm_flags & VM_LOCKED)
3190                 flags |= MAP_LOCKED;
3191
3192         file = get_file(vma->vm_file);
3193         ret = do_mmap(vma->vm_file, start, size,
3194                         prot, flags, pgoff, &populate, NULL);
3195         fput(file);
3196 out:
3197         mmap_write_unlock(mm);
3198         if (populate)
3199                 mm_populate(ret, populate);
3200         if (!IS_ERR_VALUE(ret))
3201                 ret = 0;
3202         return ret;
3203 }
3204
3205 /*
3206  *  this is really a simplified "do_mmap".  it only handles
3207  *  anonymous maps.  eventually we may be able to do some
3208  *  brk-specific accounting here.
3209  */
3210 static int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)
3211 {
3212         struct mm_struct *mm = current->mm;
3213         struct vm_area_struct *vma, *prev;
3214         struct rb_node **rb_link, *rb_parent;
3215         pgoff_t pgoff = addr >> PAGE_SHIFT;
3216         int error;
3217         unsigned long mapped_addr;
3218         validate_mm_mt(mm);
3219
3220         /* Until we need other flags, refuse anything except VM_EXEC. */
3221         if ((flags & (~VM_EXEC)) != 0)
3222                 return -EINVAL;
3223         flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
3224
3225         mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
3226         if (IS_ERR_VALUE(mapped_addr))
3227                 return mapped_addr;
3228
3229         error = mlock_future_check(mm, mm->def_flags, len);
3230         if (error)
3231                 return error;
3232
3233         /* Clear old maps, set up prev, rb_link, rb_parent, and uf */
3234         if (munmap_vma_range(mm, addr, len, &prev, &rb_link, &rb_parent, uf))
3235                 return -ENOMEM;
3236
3237         /* Check against address space limits *after* clearing old maps... */
3238         if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
3239                 return -ENOMEM;
3240
3241         if (mm->map_count > sysctl_max_map_count)
3242                 return -ENOMEM;
3243
3244         if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3245                 return -ENOMEM;
3246
3247         /* Can we just expand an old private anonymous mapping? */
3248         vma = vma_merge(mm, prev, addr, addr + len, flags,
3249                         NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
3250         if (vma)
3251                 goto out;
3252
3253         /*
3254          * create a vma struct for an anonymous mapping
3255          */
3256         vma = vm_area_alloc(mm);
3257         if (!vma) {
3258                 vm_unacct_memory(len >> PAGE_SHIFT);
3259                 return -ENOMEM;
3260         }
3261
3262         vma_set_anonymous(vma);
3263         vma->vm_start = addr;
3264         vma->vm_end = addr + len;
3265         vma->vm_pgoff = pgoff;
3266         vma->vm_flags = flags;
3267         vma->vm_page_prot = vm_get_page_prot(flags);
3268         if (vma_link(mm, vma, prev, rb_link, rb_parent))
3269                 goto no_vma_link;
3270
3271 out:
3272         perf_event_mmap(vma);
3273         mm->total_vm += len >> PAGE_SHIFT;
3274         mm->data_vm += len >> PAGE_SHIFT;
3275         if (flags & VM_LOCKED)
3276                 mm->locked_vm += (len >> PAGE_SHIFT);
3277         vma->vm_flags |= VM_SOFTDIRTY;
3278         validate_mm_mt(mm);
3279         return 0;
3280
3281 no_vma_link:
3282         vm_area_free(vma);
3283         return -ENOMEM;
3284 }
3285
3286 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3287 {
3288         struct mm_struct *mm = current->mm;
3289         unsigned long len;
3290         int ret;
3291         bool populate;
3292         LIST_HEAD(uf);
3293
3294         len = PAGE_ALIGN(request);
3295         if (len < request)
3296                 return -ENOMEM;
3297         if (!len)
3298                 return 0;
3299
3300         if (mmap_write_lock_killable(mm))
3301                 return -EINTR;
3302
3303         ret = do_brk_flags(addr, len, flags, &uf);
3304         populate = ((mm->def_flags & VM_LOCKED) != 0);
3305         mmap_write_unlock(mm);
3306         userfaultfd_unmap_complete(mm, &uf);
3307         if (populate && !ret)
3308                 mm_populate(addr, len);
3309         return ret;
3310 }
3311 EXPORT_SYMBOL(vm_brk_flags);
3312
3313 int vm_brk(unsigned long addr, unsigned long len)
3314 {
3315         return vm_brk_flags(addr, len, 0);
3316 }
3317 EXPORT_SYMBOL(vm_brk);
3318
3319 /* Release all mmaps. */
3320 void exit_mmap(struct mm_struct *mm)
3321 {
3322         struct mmu_gather tlb;
3323         struct vm_area_struct *vma;
3324         unsigned long nr_accounted = 0;
3325
3326         /* mm's last user has gone, and its about to be pulled down */
3327         mmu_notifier_release(mm);
3328
3329         if (unlikely(mm_is_oom_victim(mm))) {
3330                 /*
3331                  * Manually reap the mm to free as much memory as possible.
3332                  * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3333                  * this mm from further consideration.  Taking mm->mmap_lock for
3334                  * write after setting MMF_OOM_SKIP will guarantee that the oom
3335                  * reaper will not run on this mm again after mmap_lock is
3336                  * dropped.
3337                  *
3338                  * Nothing can be holding mm->mmap_lock here and the above call
3339                  * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
3340                  * __oom_reap_task_mm() will not block.
3341                  */
3342                 (void)__oom_reap_task_mm(mm);
3343                 set_bit(MMF_OOM_SKIP, &mm->flags);
3344         }
3345
3346         mmap_write_lock(mm);
3347         arch_exit_mmap(mm);
3348
3349         vma = mm->mmap;
3350         if (!vma) {
3351                 /* Can happen if dup_mmap() received an OOM */
3352                 mmap_write_unlock(mm);
3353                 return;
3354         }
3355
3356         lru_add_drain();
3357         flush_cache_mm(mm);
3358         tlb_gather_mmu_fullmm(&tlb, mm);
3359         /* update_hiwater_rss(mm) here? but nobody should be looking */
3360         /* Use -1 here to ensure all VMAs in the mm are unmapped */
3361         unmap_vmas(&tlb, vma, 0, -1);
3362         free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3363         tlb_finish_mmu(&tlb);
3364
3365         /* Walk the list again, actually closing and freeing it. */
3366         while (vma) {
3367                 if (vma->vm_flags & VM_ACCOUNT)
3368                         nr_accounted += vma_pages(vma);
3369                 vma = remove_vma(vma);
3370                 cond_resched();
3371         }
3372
3373         trace_exit_mmap(mm);
3374         __mt_destroy(&mm->mm_mt);
3375         mm->mmap = NULL;
3376         mmap_write_unlock(mm);
3377         vm_unacct_memory(nr_accounted);
3378 }
3379
3380 /* Insert vm structure into process list sorted by address
3381  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3382  * then i_mmap_rwsem is taken here.
3383  */
3384 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3385 {
3386         struct vm_area_struct *prev;
3387         struct rb_node **rb_link, *rb_parent;
3388         unsigned long start = vma->vm_start;
3389         struct vm_area_struct *overlap = NULL;
3390         unsigned long charged = vma_pages(vma);
3391
3392         if (find_vma_links(mm, vma->vm_start, vma->vm_end,
3393                            &prev, &rb_link, &rb_parent))
3394
3395         if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
3396                 return -ENOMEM;
3397
3398         overlap = mt_find(&mm->mm_mt, &start, vma->vm_end - 1);
3399         if (overlap) {
3400
3401                 pr_err("Found vma ending at %lu\n", start - 1);
3402                 pr_err("vma : %lu => %lu-%lu\n", (unsigned long)overlap,
3403                                 overlap->vm_start, overlap->vm_end - 1);
3404 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
3405                 mt_dump(&mm->mm_mt);
3406 #endif
3407                 BUG();
3408         }
3409
3410         if ((vma->vm_flags & VM_ACCOUNT) &&
3411              security_vm_enough_memory_mm(mm, charged))
3412                 return -ENOMEM;
3413
3414         /*
3415          * The vm_pgoff of a purely anonymous vma should be irrelevant
3416          * until its first write fault, when page's anon_vma and index
3417          * are set.  But now set the vm_pgoff it will almost certainly
3418          * end up with (unless mremap moves it elsewhere before that
3419          * first wfault), so /proc/pid/maps tells a consistent story.
3420          *
3421          * By setting it to reflect the virtual start address of the
3422          * vma, merges and splits can happen in a seamless way, just
3423          * using the existing file pgoff checks and manipulations.
3424          * Similarly in do_mmap and in do_brk_flags.
3425          */
3426         if (vma_is_anonymous(vma)) {
3427                 BUG_ON(vma->anon_vma);
3428                 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3429         }
3430
3431         if (vma_link(mm, vma, prev, rb_link, rb_parent)) {
3432                 vm_unacct_memory(charged);
3433                 return -ENOMEM;
3434         }
3435
3436         return 0;
3437 }
3438
3439 /*
3440  * Copy the vma structure to a new location in the same mm,
3441  * prior to moving page table entries, to effect an mremap move.
3442  */
3443 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3444         unsigned long addr, unsigned long len, pgoff_t pgoff,
3445         bool *need_rmap_locks)
3446 {
3447         struct vm_area_struct *vma = *vmap;
3448         unsigned long vma_start = vma->vm_start;
3449         struct mm_struct *mm = vma->vm_mm;
3450         struct vm_area_struct *new_vma, *prev;
3451         struct rb_node **rb_link, *rb_parent;
3452         bool faulted_in_anon_vma = true;
3453         unsigned long index = addr;
3454
3455         validate_mm_mt(mm);
3456         /*
3457          * If anonymous vma has not yet been faulted, update new pgoff
3458          * to match new location, to increase its chance of merging.
3459          */
3460         if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3461                 pgoff = addr >> PAGE_SHIFT;
3462                 faulted_in_anon_vma = false;
3463         }
3464
3465         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
3466                 return NULL;    /* should never get here */
3467         if (mt_find(&mm->mm_mt, &index, addr+len - 1))
3468                 BUG();
3469         new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
3470                             vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3471                             vma->vm_userfaultfd_ctx, anon_vma_name(vma));
3472         if (new_vma) {
3473                 /*
3474                  * Source vma may have been merged into new_vma
3475                  */
3476                 if (unlikely(vma_start >= new_vma->vm_start &&
3477                              vma_start < new_vma->vm_end)) {
3478                         /*
3479                          * The only way we can get a vma_merge with
3480                          * self during an mremap is if the vma hasn't
3481                          * been faulted in yet and we were allowed to
3482                          * reset the dst vma->vm_pgoff to the
3483                          * destination address of the mremap to allow
3484                          * the merge to happen. mremap must change the
3485                          * vm_pgoff linearity between src and dst vmas
3486                          * (in turn preventing a vma_merge) to be
3487                          * safe. It is only safe to keep the vm_pgoff
3488                          * linear if there are no pages mapped yet.
3489                          */
3490                         VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3491                         *vmap = vma = new_vma;
3492                 }
3493                 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3494         } else {
3495                 new_vma = vm_area_dup(vma);
3496                 if (!new_vma)
3497                         goto out;
3498                 new_vma->vm_start = addr;
3499                 new_vma->vm_end = addr + len;
3500                 new_vma->vm_pgoff = pgoff;
3501                 if (vma_dup_policy(vma, new_vma))
3502                         goto out_free_vma;
3503                 if (anon_vma_clone(new_vma, vma))
3504                         goto out_free_mempol;
3505                 if (new_vma->vm_file)
3506                         get_file(new_vma->vm_file);
3507                 if (new_vma->vm_ops && new_vma->vm_ops->open)
3508                         new_vma->vm_ops->open(new_vma);
3509                 vma_link(mm, new_vma, prev, rb_link, rb_parent);
3510                 *need_rmap_locks = false;
3511         }
3512         validate_mm_mt(mm);
3513         return new_vma;
3514
3515 out_free_mempol:
3516         mpol_put(vma_policy(new_vma));
3517 out_free_vma:
3518         vm_area_free(new_vma);
3519 out:
3520         validate_mm_mt(mm);
3521         return NULL;
3522 }
3523
3524 /*
3525  * Return true if the calling process may expand its vm space by the passed
3526  * number of pages
3527  */
3528 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3529 {
3530         if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3531                 return false;
3532
3533         if (is_data_mapping(flags) &&
3534             mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3535                 /* Workaround for Valgrind */
3536                 if (rlimit(RLIMIT_DATA) == 0 &&
3537                     mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3538                         return true;
3539
3540                 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3541                              current->comm, current->pid,
3542                              (mm->data_vm + npages) << PAGE_SHIFT,
3543                              rlimit(RLIMIT_DATA),
3544                              ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3545
3546                 if (!ignore_rlimit_data)
3547                         return false;
3548         }
3549
3550         return true;
3551 }
3552
3553 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3554 {
3555         WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
3556
3557         if (is_exec_mapping(flags))
3558                 mm->exec_vm += npages;
3559         else if (is_stack_mapping(flags))
3560                 mm->stack_vm += npages;
3561         else if (is_data_mapping(flags))
3562                 mm->data_vm += npages;
3563 }
3564
3565 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3566
3567 /*
3568  * Having a close hook prevents vma merging regardless of flags.
3569  */
3570 static void special_mapping_close(struct vm_area_struct *vma)
3571 {
3572 }
3573
3574 static const char *special_mapping_name(struct vm_area_struct *vma)
3575 {
3576         return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3577 }
3578
3579 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3580 {
3581         struct vm_special_mapping *sm = new_vma->vm_private_data;
3582
3583         if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3584                 return -EFAULT;
3585
3586         if (sm->mremap)
3587                 return sm->mremap(sm, new_vma);
3588
3589         return 0;
3590 }
3591
3592 static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3593 {
3594         /*
3595          * Forbid splitting special mappings - kernel has expectations over
3596          * the number of pages in mapping. Together with VM_DONTEXPAND
3597          * the size of vma should stay the same over the special mapping's
3598          * lifetime.
3599          */
3600         return -EINVAL;
3601 }
3602
3603 static const struct vm_operations_struct special_mapping_vmops = {
3604         .close = special_mapping_close,
3605         .fault = special_mapping_fault,
3606         .mremap = special_mapping_mremap,
3607         .name = special_mapping_name,
3608         /* vDSO code relies that VVAR can't be accessed remotely */
3609         .access = NULL,
3610         .may_split = special_mapping_split,
3611 };
3612
3613 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3614         .close = special_mapping_close,
3615         .fault = special_mapping_fault,
3616 };
3617
3618 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3619 {
3620         struct vm_area_struct *vma = vmf->vma;
3621         pgoff_t pgoff;
3622         struct page **pages;
3623
3624         if (vma->vm_ops == &legacy_special_mapping_vmops) {
3625                 pages = vma->vm_private_data;
3626         } else {
3627                 struct vm_special_mapping *sm = vma->vm_private_data;
3628
3629                 if (sm->fault)
3630                         return sm->fault(sm, vmf->vma, vmf);
3631
3632                 pages = sm->pages;
3633         }
3634
3635         for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3636                 pgoff--;
3637
3638         if (*pages) {
3639                 struct page *page = *pages;
3640                 get_page(page);
3641                 vmf->page = page;
3642                 return 0;
3643         }
3644
3645         return VM_FAULT_SIGBUS;
3646 }
3647
3648 static struct vm_area_struct *__install_special_mapping(
3649         struct mm_struct *mm,
3650         unsigned long addr, unsigned long len,
3651         unsigned long vm_flags, void *priv,
3652         const struct vm_operations_struct *ops)
3653 {
3654         int ret;
3655         struct vm_area_struct *vma;
3656
3657         validate_mm_mt(mm);
3658         vma = vm_area_alloc(mm);
3659         if (unlikely(vma == NULL))
3660                 return ERR_PTR(-ENOMEM);
3661
3662         vma->vm_start = addr;
3663         vma->vm_end = addr + len;
3664
3665         vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3666         vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
3667         vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3668
3669         vma->vm_ops = ops;
3670         vma->vm_private_data = priv;
3671
3672         ret = insert_vm_struct(mm, vma);
3673         if (ret)
3674                 goto out;
3675
3676         vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3677
3678         perf_event_mmap(vma);
3679
3680         validate_mm_mt(mm);
3681         return vma;
3682
3683 out:
3684         vm_area_free(vma);
3685         validate_mm_mt(mm);
3686         return ERR_PTR(ret);
3687 }
3688
3689 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3690         const struct vm_special_mapping *sm)
3691 {
3692         return vma->vm_private_data == sm &&
3693                 (vma->vm_ops == &special_mapping_vmops ||
3694                  vma->vm_ops == &legacy_special_mapping_vmops);
3695 }
3696
3697 /*
3698  * Called with mm->mmap_lock held for writing.
3699  * Insert a new vma covering the given region, with the given flags.
3700  * Its pages are supplied by the given array of struct page *.
3701  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3702  * The region past the last page supplied will always produce SIGBUS.
3703  * The array pointer and the pages it points to are assumed to stay alive
3704  * for as long as this mapping might exist.
3705  */
3706 struct vm_area_struct *_install_special_mapping(
3707         struct mm_struct *mm,
3708         unsigned long addr, unsigned long len,
3709         unsigned long vm_flags, const struct vm_special_mapping *spec)
3710 {
3711         return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3712                                         &special_mapping_vmops);
3713 }
3714
3715 int install_special_mapping(struct mm_struct *mm,
3716                             unsigned long addr, unsigned long len,
3717                             unsigned long vm_flags, struct page **pages)
3718 {
3719         struct vm_area_struct *vma = __install_special_mapping(
3720                 mm, addr, len, vm_flags, (void *)pages,
3721                 &legacy_special_mapping_vmops);
3722
3723         return PTR_ERR_OR_ZERO(vma);
3724 }
3725
3726 static DEFINE_MUTEX(mm_all_locks_mutex);
3727
3728 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3729 {
3730         if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3731                 /*
3732                  * The LSB of head.next can't change from under us
3733                  * because we hold the mm_all_locks_mutex.
3734                  */
3735                 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
3736                 /*
3737                  * We can safely modify head.next after taking the
3738                  * anon_vma->root->rwsem. If some other vma in this mm shares
3739                  * the same anon_vma we won't take it again.
3740                  *
3741                  * No need of atomic instructions here, head.next
3742                  * can't change from under us thanks to the
3743                  * anon_vma->root->rwsem.
3744                  */
3745                 if (__test_and_set_bit(0, (unsigned long *)
3746                                        &anon_vma->root->rb_root.rb_root.rb_node))
3747                         BUG();
3748         }
3749 }
3750
3751 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3752 {
3753         if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3754                 /*
3755                  * AS_MM_ALL_LOCKS can't change from under us because
3756                  * we hold the mm_all_locks_mutex.
3757                  *
3758                  * Operations on ->flags have to be atomic because
3759                  * even if AS_MM_ALL_LOCKS is stable thanks to the
3760                  * mm_all_locks_mutex, there may be other cpus
3761                  * changing other bitflags in parallel to us.
3762                  */
3763                 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3764                         BUG();
3765                 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
3766         }
3767 }
3768
3769 /*
3770  * This operation locks against the VM for all pte/vma/mm related
3771  * operations that could ever happen on a certain mm. This includes
3772  * vmtruncate, try_to_unmap, and all page faults.
3773  *
3774  * The caller must take the mmap_lock in write mode before calling
3775  * mm_take_all_locks(). The caller isn't allowed to release the
3776  * mmap_lock until mm_drop_all_locks() returns.
3777  *
3778  * mmap_lock in write mode is required in order to block all operations
3779  * that could modify pagetables and free pages without need of
3780  * altering the vma layout. It's also needed in write mode to avoid new
3781  * anon_vmas to be associated with existing vmas.
3782  *
3783  * A single task can't take more than one mm_take_all_locks() in a row
3784  * or it would deadlock.
3785  *
3786  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3787  * mapping->flags avoid to take the same lock twice, if more than one
3788  * vma in this mm is backed by the same anon_vma or address_space.
3789  *
3790  * We take locks in following order, accordingly to comment at beginning
3791  * of mm/rmap.c:
3792  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3793  *     hugetlb mapping);
3794  *   - all i_mmap_rwsem locks;
3795  *   - all anon_vma->rwseml
3796  *
3797  * We can take all locks within these types randomly because the VM code
3798  * doesn't nest them and we protected from parallel mm_take_all_locks() by
3799  * mm_all_locks_mutex.
3800  *
3801  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3802  * that may have to take thousand of locks.
3803  *
3804  * mm_take_all_locks() can fail if it's interrupted by signals.
3805  */
3806 int mm_take_all_locks(struct mm_struct *mm)
3807 {
3808         struct vm_area_struct *vma;
3809         struct anon_vma_chain *avc;
3810
3811         mmap_assert_write_locked(mm);
3812
3813         mutex_lock(&mm_all_locks_mutex);
3814
3815         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3816                 if (signal_pending(current))
3817                         goto out_unlock;
3818                 if (vma->vm_file && vma->vm_file->f_mapping &&
3819                                 is_vm_hugetlb_page(vma))
3820                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
3821         }
3822
3823         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3824                 if (signal_pending(current))
3825                         goto out_unlock;
3826                 if (vma->vm_file && vma->vm_file->f_mapping &&
3827                                 !is_vm_hugetlb_page(vma))
3828                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
3829         }
3830
3831         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3832                 if (signal_pending(current))
3833                         goto out_unlock;
3834                 if (vma->anon_vma)
3835                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3836                                 vm_lock_anon_vma(mm, avc->anon_vma);
3837         }
3838
3839         return 0;
3840
3841 out_unlock:
3842         mm_drop_all_locks(mm);
3843         return -EINTR;
3844 }
3845
3846 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3847 {
3848         if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3849                 /*
3850                  * The LSB of head.next can't change to 0 from under
3851                  * us because we hold the mm_all_locks_mutex.
3852                  *
3853                  * We must however clear the bitflag before unlocking
3854                  * the vma so the users using the anon_vma->rb_root will
3855                  * never see our bitflag.
3856                  *
3857                  * No need of atomic instructions here, head.next
3858                  * can't change from under us until we release the
3859                  * anon_vma->root->rwsem.
3860                  */
3861                 if (!__test_and_clear_bit(0, (unsigned long *)
3862                                           &anon_vma->root->rb_root.rb_root.rb_node))
3863                         BUG();
3864                 anon_vma_unlock_write(anon_vma);
3865         }
3866 }
3867
3868 static void vm_unlock_mapping(struct address_space *mapping)
3869 {
3870         if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3871                 /*
3872                  * AS_MM_ALL_LOCKS can't change to 0 from under us
3873                  * because we hold the mm_all_locks_mutex.
3874                  */
3875                 i_mmap_unlock_write(mapping);
3876                 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3877                                         &mapping->flags))
3878                         BUG();
3879         }
3880 }
3881
3882 /*
3883  * The mmap_lock cannot be released by the caller until
3884  * mm_drop_all_locks() returns.
3885  */
3886 void mm_drop_all_locks(struct mm_struct *mm)
3887 {
3888         struct vm_area_struct *vma;
3889         struct anon_vma_chain *avc;
3890
3891         mmap_assert_write_locked(mm);
3892         BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3893
3894         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3895                 if (vma->anon_vma)
3896                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3897                                 vm_unlock_anon_vma(avc->anon_vma);
3898                 if (vma->vm_file && vma->vm_file->f_mapping)
3899                         vm_unlock_mapping(vma->vm_file->f_mapping);
3900         }
3901
3902         mutex_unlock(&mm_all_locks_mutex);
3903 }
3904
3905 /*
3906  * initialise the percpu counter for VM
3907  */
3908 void __init mmap_init(void)
3909 {
3910         int ret;
3911
3912         ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3913         VM_BUG_ON(ret);
3914 }
3915
3916 /*
3917  * Initialise sysctl_user_reserve_kbytes.
3918  *
3919  * This is intended to prevent a user from starting a single memory hogging
3920  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3921  * mode.
3922  *
3923  * The default value is min(3% of free memory, 128MB)
3924  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3925  */
3926 static int init_user_reserve(void)
3927 {
3928         unsigned long free_kbytes;
3929
3930         free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3931
3932         sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3933         return 0;
3934 }
3935 subsys_initcall(init_user_reserve);
3936
3937 /*
3938  * Initialise sysctl_admin_reserve_kbytes.
3939  *
3940  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3941  * to log in and kill a memory hogging process.
3942  *
3943  * Systems with more than 256MB will reserve 8MB, enough to recover
3944  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3945  * only reserve 3% of free pages by default.
3946  */
3947 static int init_admin_reserve(void)
3948 {
3949         unsigned long free_kbytes;
3950
3951         free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3952
3953         sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3954         return 0;
3955 }
3956 subsys_initcall(init_admin_reserve);
3957
3958 /*
3959  * Reinititalise user and admin reserves if memory is added or removed.
3960  *
3961  * The default user reserve max is 128MB, and the default max for the
3962  * admin reserve is 8MB. These are usually, but not always, enough to
3963  * enable recovery from a memory hogging process using login/sshd, a shell,
3964  * and tools like top. It may make sense to increase or even disable the
3965  * reserve depending on the existence of swap or variations in the recovery
3966  * tools. So, the admin may have changed them.
3967  *
3968  * If memory is added and the reserves have been eliminated or increased above
3969  * the default max, then we'll trust the admin.
3970  *
3971  * If memory is removed and there isn't enough free memory, then we
3972  * need to reset the reserves.
3973  *
3974  * Otherwise keep the reserve set by the admin.
3975  */
3976 static int reserve_mem_notifier(struct notifier_block *nb,
3977                              unsigned long action, void *data)
3978 {
3979         unsigned long tmp, free_kbytes;
3980
3981         switch (action) {
3982         case MEM_ONLINE:
3983                 /* Default max is 128MB. Leave alone if modified by operator. */
3984                 tmp = sysctl_user_reserve_kbytes;
3985                 if (0 < tmp && tmp < (1UL << 17))
3986                         init_user_reserve();
3987
3988                 /* Default max is 8MB.  Leave alone if modified by operator. */
3989                 tmp = sysctl_admin_reserve_kbytes;
3990                 if (0 < tmp && tmp < (1UL << 13))
3991                         init_admin_reserve();
3992
3993                 break;
3994         case MEM_OFFLINE:
3995                 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3996
3997                 if (sysctl_user_reserve_kbytes > free_kbytes) {
3998                         init_user_reserve();
3999                         pr_info("vm.user_reserve_kbytes reset to %lu\n",
4000                                 sysctl_user_reserve_kbytes);
4001                 }
4002
4003                 if (sysctl_admin_reserve_kbytes > free_kbytes) {
4004                         init_admin_reserve();
4005                         pr_info("vm.admin_reserve_kbytes reset to %lu\n",
4006                                 sysctl_admin_reserve_kbytes);
4007                 }
4008                 break;
4009         default:
4010                 break;
4011         }
4012         return NOTIFY_OK;
4013 }
4014
4015 static struct notifier_block reserve_mem_nb = {
4016         .notifier_call = reserve_mem_notifier,
4017 };
4018
4019 static int __meminit init_reserve_notifier(void)
4020 {
4021         if (register_hotmemory_notifier(&reserve_mem_nb))
4022                 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
4023
4024         return 0;
4025 }
4026 subsys_initcall(init_reserve_notifier);