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