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