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